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/test/special/Javac.java b/test/special/Javac.java index 1564f672..fa0d7241 100644 --- a/test/special/Javac.java +++ b/test/special/Javac.java @@ -1,17 +1,17 @@ package test.special; import javax.tools.*; public class Javac { - public static void main(String[] args) { - if (args.length < 1) { - System.out.println("Syntax: java Javac [classes]"); - return; + public static void main(String[] args) { + if (args.length < 1) { + System.out.println("Syntax: java Javac [classes]"); + return; + } + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + int result = compiler.run(null, null, null, args); + if (result != 0) { + System.out.println("Compiler failed."); + } } - JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - int result = compiler.run(null, null, null, args); - if (result != 0) { - System.out.println("Compiler failed."); - } - } }
false
true
public static void main(String[] args) { if (args.length < 1) { System.out.println("Syntax: java Javac [classes]"); return; } JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, args); if (result != 0) { System.out.println("Compiler failed."); } }
public static void main(String[] args) { if (args.length < 1) { System.out.println("Syntax: java Javac [classes]"); return; } JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, args); if (result != 0) { System.out.println("Compiler failed."); } }
diff --git a/src/hdfs/org/apache/hadoop/hdfs/server/namenode/GetImageServlet.java b/src/hdfs/org/apache/hadoop/hdfs/server/namenode/GetImageServlet.java index 3c569d9f9..42a91a4e7 100644 --- a/src/hdfs/org/apache/hadoop/hdfs/server/namenode/GetImageServlet.java +++ b/src/hdfs/org/apache/hadoop/hdfs/server/namenode/GetImageServlet.java @@ -1,167 +1,167 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY; import java.io.IOException; import java.security.PrivilegedExceptionAction; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.hadoop.security.SecurityUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.io.MD5Hash; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.StringUtils; /** * This class is used in Namesystem's jetty to retrieve a file. * Typically used by the Secondary NameNode to retrieve image and * edit file for periodic checkpointing. */ public class GetImageServlet extends HttpServlet { private static final long serialVersionUID = -7669068179452648952L; private static final Log LOG = LogFactory.getLog(GetImageServlet.class); /** * A lock object to prevent multiple 2NNs from simultaneously uploading * fsimage snapshots. */ private Object fsImageTransferLock = new Object(); @SuppressWarnings("unchecked") public void doGet(final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException { Map<String,String[]> pmap = request.getParameterMap(); try { ServletContext context = getServletContext(); final FSImage nnImage = (FSImage)context.getAttribute("name.system.image"); final TransferFsImage ff = new TransferFsImage(pmap, request, response); final Configuration conf = (Configuration)getServletContext().getAttribute(JspHelper.CURRENT_CONF); if(UserGroupInformation.isSecurityEnabled() && !isValidRequestor(request.getRemoteUser(), conf)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Namenode and Secondary Namenode may access this servlet"); LOG.warn("Received non-NN/SNN request for image or edits from " + request.getRemoteHost()); return; } UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { if (ff.getImage()) { // send fsImage TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsImageName()); } else if (ff.getEdit()) { // send edits TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsEditName()); } else if (ff.putImage()) { synchronized (fsImageTransferLock) { final MD5Hash expectedChecksum = ff.getNewChecksum(); // issue a HTTP get request to download the new fsimage nnImage.validateCheckpointUpload(ff.getToken()); reloginIfNecessary().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { MD5Hash actualChecksum = TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1", nnImage.getFsImageNameCheckpoint(), true); LOG.info("Downloaded new fsimage with checksum: " + actualChecksum); if (!actualChecksum.equals(expectedChecksum)) { throw new IOException("Actual checksum of transferred fsimage: " + actualChecksum + " does not match expected checksum: " + expectedChecksum); } return null; } }); nnImage.checkpointUploadDone(); } } return null; } // We may have lost our ticket since the last time we tried to open // an http connection, so log in just in case. private UserGroupInformation reloginIfNecessary() throws IOException { // This method is only called on the NN, therefore it is safe to // use these key values. return UserGroupInformation .loginUserFromKeytabAndReturnUGI( SecurityUtil.getServerPrincipal(conf .get(DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY), NameNode .getAddress(conf).getHostName()), conf.get(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY)); } }); - } catch (Exception ie) { - String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie); + } catch (Throwable t) { + String errMsg = "GetImage failed. " + StringUtils.stringifyException(t); response.sendError(HttpServletResponse.SC_GONE, errMsg); throw new IOException(errMsg); } finally { response.getOutputStream().close(); } } private boolean isValidRequestor(String remoteUser, Configuration conf) throws IOException { if(remoteUser == null) { // This really shouldn't happen... LOG.warn("Received null remoteUser while authorizing access to getImage servlet"); return false; } String[] validRequestors = { SecurityUtil.getServerPrincipal(conf .get(DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY), NameNode.getAddress( conf).getHostName()), SecurityUtil.getServerPrincipal(conf.get(DFS_NAMENODE_USER_NAME_KEY), NameNode.getAddress(conf).getHostName()), SecurityUtil.getServerPrincipal(conf .get(DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY), SecondaryNameNode.getHttpAddress(conf).getHostName()), SecurityUtil.getServerPrincipal(conf .get(DFS_SECONDARY_NAMENODE_USER_NAME_KEY), SecondaryNameNode .getHttpAddress(conf).getHostName()) }; for(String v : validRequestors) { if(v != null && v.equals(remoteUser)) { if(LOG.isDebugEnabled()) LOG.debug("isValidRequestor is allowing: " + remoteUser); return true; } } if(LOG.isDebugEnabled()) LOG.debug("isValidRequestor is rejecting: " + remoteUser); return false; } }
true
true
public void doGet(final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException { Map<String,String[]> pmap = request.getParameterMap(); try { ServletContext context = getServletContext(); final FSImage nnImage = (FSImage)context.getAttribute("name.system.image"); final TransferFsImage ff = new TransferFsImage(pmap, request, response); final Configuration conf = (Configuration)getServletContext().getAttribute(JspHelper.CURRENT_CONF); if(UserGroupInformation.isSecurityEnabled() && !isValidRequestor(request.getRemoteUser(), conf)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Namenode and Secondary Namenode may access this servlet"); LOG.warn("Received non-NN/SNN request for image or edits from " + request.getRemoteHost()); return; } UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { if (ff.getImage()) { // send fsImage TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsImageName()); } else if (ff.getEdit()) { // send edits TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsEditName()); } else if (ff.putImage()) { synchronized (fsImageTransferLock) { final MD5Hash expectedChecksum = ff.getNewChecksum(); // issue a HTTP get request to download the new fsimage nnImage.validateCheckpointUpload(ff.getToken()); reloginIfNecessary().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { MD5Hash actualChecksum = TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1", nnImage.getFsImageNameCheckpoint(), true); LOG.info("Downloaded new fsimage with checksum: " + actualChecksum); if (!actualChecksum.equals(expectedChecksum)) { throw new IOException("Actual checksum of transferred fsimage: " + actualChecksum + " does not match expected checksum: " + expectedChecksum); } return null; } }); nnImage.checkpointUploadDone(); } } return null; } // We may have lost our ticket since the last time we tried to open // an http connection, so log in just in case. private UserGroupInformation reloginIfNecessary() throws IOException { // This method is only called on the NN, therefore it is safe to // use these key values. return UserGroupInformation .loginUserFromKeytabAndReturnUGI( SecurityUtil.getServerPrincipal(conf .get(DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY), NameNode .getAddress(conf).getHostName()), conf.get(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY)); } }); } catch (Exception ie) { String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie); response.sendError(HttpServletResponse.SC_GONE, errMsg); throw new IOException(errMsg); } finally { response.getOutputStream().close(); } }
public void doGet(final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException { Map<String,String[]> pmap = request.getParameterMap(); try { ServletContext context = getServletContext(); final FSImage nnImage = (FSImage)context.getAttribute("name.system.image"); final TransferFsImage ff = new TransferFsImage(pmap, request, response); final Configuration conf = (Configuration)getServletContext().getAttribute(JspHelper.CURRENT_CONF); if(UserGroupInformation.isSecurityEnabled() && !isValidRequestor(request.getRemoteUser(), conf)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Namenode and Secondary Namenode may access this servlet"); LOG.warn("Received non-NN/SNN request for image or edits from " + request.getRemoteHost()); return; } UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { if (ff.getImage()) { // send fsImage TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsImageName()); } else if (ff.getEdit()) { // send edits TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsEditName()); } else if (ff.putImage()) { synchronized (fsImageTransferLock) { final MD5Hash expectedChecksum = ff.getNewChecksum(); // issue a HTTP get request to download the new fsimage nnImage.validateCheckpointUpload(ff.getToken()); reloginIfNecessary().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { MD5Hash actualChecksum = TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1", nnImage.getFsImageNameCheckpoint(), true); LOG.info("Downloaded new fsimage with checksum: " + actualChecksum); if (!actualChecksum.equals(expectedChecksum)) { throw new IOException("Actual checksum of transferred fsimage: " + actualChecksum + " does not match expected checksum: " + expectedChecksum); } return null; } }); nnImage.checkpointUploadDone(); } } return null; } // We may have lost our ticket since the last time we tried to open // an http connection, so log in just in case. private UserGroupInformation reloginIfNecessary() throws IOException { // This method is only called on the NN, therefore it is safe to // use these key values. return UserGroupInformation .loginUserFromKeytabAndReturnUGI( SecurityUtil.getServerPrincipal(conf .get(DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY), NameNode .getAddress(conf).getHostName()), conf.get(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY)); } }); } catch (Throwable t) { String errMsg = "GetImage failed. " + StringUtils.stringifyException(t); response.sendError(HttpServletResponse.SC_GONE, errMsg); throw new IOException(errMsg); } finally { response.getOutputStream().close(); } }
diff --git a/src/java/org/apache/bcel/generic/MethodGen.java b/src/java/org/apache/bcel/generic/MethodGen.java index df5eefab..5b4b074f 100644 --- a/src/java/org/apache/bcel/generic/MethodGen.java +++ b/src/java/org/apache/bcel/generic/MethodGen.java @@ -1,1123 +1,1125 @@ /* * Copyright 2000-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.bcel.generic; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.ExceptionTable; import org.apache.bcel.classfile.LineNumber; import org.apache.bcel.classfile.LineNumberTable; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.Utility; import org.apache.bcel.util.BCELComparator; /** * Template class for building up a method. This is done by defining exception * handlers, adding thrown exceptions, local variables and attributes, whereas * the `LocalVariableTable' and `LineNumberTable' attributes will be set * automatically for the code. Use stripAttributes() if you don't like this. * * While generating code it may be necessary to insert NOP operations. You can * use the `removeNOPs' method to get rid off them. * The resulting method object can be obtained via the `getMethod()' method. * * @version $Id$ * @author <A HREF="mailto:[email protected]">M. Dahm</A> * @author <A HREF="http://www.vmeng.com/beard">Patrick C. Beard</A> [setMaxStack()] * @see InstructionList * @see Method */ public class MethodGen extends FieldGenOrMethodGen { private String class_name; private Type[] arg_types; private String[] arg_names; private int max_locals; private int max_stack; private InstructionList il; private boolean strip_attributes; private List variable_vec = new ArrayList(); private List line_number_vec = new ArrayList(); private List exception_vec = new ArrayList(); private List throws_vec = new ArrayList(); private List code_attrs_vec = new ArrayList(); private static BCELComparator _cmp = new BCELComparator() { public boolean equals(Object o1, Object o2) { MethodGen THIS = (MethodGen)o1; MethodGen THAT = (MethodGen)o2; return THIS.getName().equals(THAT.getName()) && THIS.getSignature().equals(THAT.getSignature()); } public int hashCode(Object o) { MethodGen THIS = (MethodGen)o; return THIS.getSignature().hashCode() ^ THIS.getName().hashCode(); } }; /** * Declare method. If the method is non-static the constructor * automatically declares a local variable `$this' in slot 0. The * actual code is contained in the `il' parameter, which may further * manipulated by the user. But he must take care not to remove any * instruction (handles) that are still referenced from this object. * * For example one may not add a local variable and later remove the * instructions it refers to without causing havoc. It is safe * however if you remove that local variable, too. * * @param access_flags access qualifiers * @param return_type method type * @param arg_types argument types * @param arg_names argument names (if this is null, default names will be provided * for them) * @param method_name name of method * @param class_name class name containing this method (may be null, if you don't care) * @param il instruction list associated with this method, may be null only for * abstract or native methods * @param cp constant pool */ public MethodGen( int access_flags, Type return_type, Type[] arg_types, String[] arg_names, String method_name, String class_name, InstructionList il, ConstantPoolGen cp) { setAccessFlags(access_flags); setType(return_type); setArgumentTypes(arg_types); setArgumentNames(arg_names); setName(method_name); setClassName(class_name); setInstructionList(il); setConstantPool(cp); boolean abstract_ = isAbstract() || isNative(); InstructionHandle start = null; InstructionHandle end = null; if (!abstract_) { start = il.getStart(); end = il.getEnd(); /* Add local variables, namely the implicit `this' and the arguments */ if (!isStatic() && (class_name != null)) { // Instance method -> `this' is local var 0 addLocalVariable("this", new ObjectType(class_name), start, end); } } if (arg_types != null) { int size = arg_types.length; for (int i = 0; i < size; i++) { if (Type.VOID == arg_types[i]) { throw new ClassGenException("'void' is an illegal argument type for a method"); } } if (arg_names != null) { // Names for variables provided? if (size != arg_names.length) throw new ClassGenException( "Mismatch in argument array lengths: " + size + " vs. " + arg_names.length); } else { // Give them dummy names arg_names = new String[size]; for (int i = 0; i < size; i++) arg_names[i] = "arg" + i; setArgumentNames(arg_names); } if (!abstract_) { for (int i = 0; i < size; i++) { addLocalVariable(arg_names[i], arg_types[i], start, end); } } } } /** * Instantiate from existing method. * * @param m method * @param class_name class name containing this method * @param cp constant pool */ public MethodGen(Method m, String class_name, ConstantPoolGen cp) { this( m.getAccessFlags(), Type.getReturnType(m.getSignature()), Type.getArgumentTypes(m.getSignature()), null /* may be overridden anyway */ , m.getName(), class_name, ((m.getAccessFlags() & (Constants.ACC_ABSTRACT | Constants.ACC_NATIVE)) == 0) ? new InstructionList(m.getCode().getCode()) : null, cp); Attribute[] attributes = m.getAttributes(); for (int i = 0; i < attributes.length; i++) { Attribute a = attributes[i]; if (a instanceof Code) { Code c = (Code)a; setMaxStack(c.getMaxStack()); setMaxLocals(c.getMaxLocals()); CodeException[] ces = c.getExceptionTable(); if (ces != null) { for (int j = 0; j < ces.length; j++) { CodeException ce = ces[j]; int type = ce.getCatchType(); ObjectType c_type = null; if (type > 0) { String cen = m.getConstantPool().getConstantString( type, Constants.CONSTANT_Class); c_type = new ObjectType(cen); } int end_pc = ce.getEndPC(); int length = m.getCode().getCode().length; InstructionHandle end; if (length == end_pc) { // May happen, because end_pc is exclusive end = il.getEnd(); } else { end = il.findHandle(end_pc); end = end.getPrev(); // Make it inclusive } addExceptionHandler( il.findHandle(ce.getStartPC()), end, il.findHandle(ce.getHandlerPC()), c_type); } } Attribute[] c_attributes = c.getAttributes(); for (int j = 0; j < c_attributes.length; j++) { a = c_attributes[j]; if (a instanceof LineNumberTable) { LineNumber[] ln = ((LineNumberTable)a).getLineNumberTable(); for (int k = 0; k < ln.length; k++) { LineNumber l = ln[k]; - addLineNumber(il.findHandle(l.getStartPC()), l.getLineNumber()); + InstructionHandle ih = il.findHandle(l.getStartPC()); + if (ih != null) + addLineNumber(ih, l.getLineNumber()); } } else if (a instanceof LocalVariableTable) { LocalVariable[] lv = ((LocalVariableTable)a).getLocalVariableTable(); removeLocalVariables(); for (int k = 0; k < lv.length; k++) { LocalVariable l = lv[k]; InstructionHandle start = il.findHandle(l.getStartPC()); InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength()); // Repair malformed handles if (null == start) { start = il.getStart(); } if (null == end) { end = il.getEnd(); } addLocalVariable( l.getName(), Type.getType(l.getSignature()), l.getIndex(), start, end); } } else addCodeAttribute(a); } } else if (a instanceof ExceptionTable) { String[] names = ((ExceptionTable)a).getExceptionNames(); for (int j = 0; j < names.length; j++) addException(names[j]); } else addAttribute(a); } } /** * Adds a local variable to this method. * * @param name variable name * @param type variable type * @param slot the index of the local variable, if type is long or double, the next available * index is slot+2 * @param start from where the variable is valid * @param end until where the variable is valid * @return new local variable object * @see LocalVariable */ public LocalVariableGen addLocalVariable( String name, Type type, int slot, InstructionHandle start, InstructionHandle end) { byte t = type.getType(); if (t != Constants.T_ADDRESS) { int add = type.getSize(); if (slot + add > max_locals) max_locals = slot + add; LocalVariableGen l = new LocalVariableGen(slot, name, type, start, end); int i; if ((i = variable_vec.indexOf(l)) >= 0) // Overwrite if necessary variable_vec.set(i, l); else variable_vec.add(l); return l; } else { throw new IllegalArgumentException( "Can not use " + type + " as type for local variable"); } } /** * Adds a local variable to this method and assigns an index automatically. * * @param name variable name * @param type variable type * @param start from where the variable is valid, if this is null, * it is valid from the start * @param end until where the variable is valid, if this is null, * it is valid to the end * @return new local variable object * @see LocalVariable */ public LocalVariableGen addLocalVariable( String name, Type type, InstructionHandle start, InstructionHandle end) { return addLocalVariable(name, type, max_locals, start, end); } /** * Remove a local variable, its slot will not be reused, if you do not use addLocalVariable * with an explicit index argument. */ public void removeLocalVariable(LocalVariableGen l) { variable_vec.remove(l); } /** * Remove all local variables. */ public void removeLocalVariables() { variable_vec.clear(); } /** * Sort local variables by index */ private static final void sort(LocalVariableGen[] vars, int l, int r) { int i = l, j = r; int m = vars[(l + r) / 2].getIndex(); LocalVariableGen h; do { while (vars[i].getIndex() < m) i++; while (m < vars[j].getIndex()) j--; if (i <= j) { h = vars[i]; vars[i] = vars[j]; vars[j] = h; // Swap elements i++; j--; } } while (i <= j); if (l < j) sort(vars, l, j); if (i < r) sort(vars, i, r); } /* * If the range of the variable has not been set yet, it will be set to be valid from * the start to the end of the instruction list. * * @return array of declared local variables sorted by index */ public LocalVariableGen[] getLocalVariables() { int size = variable_vec.size(); LocalVariableGen[] lg = new LocalVariableGen[size]; variable_vec.toArray(lg); for (int i = 0; i < size; i++) { if (lg[i].getStart() == null) lg[i].setStart(il.getStart()); if (lg[i].getEnd() == null) lg[i].setEnd(il.getEnd()); } if (size > 1) sort(lg, 0, size - 1); return lg; } /** * @return `LocalVariableTable' attribute of all the local variables of this method. */ public LocalVariableTable getLocalVariableTable(ConstantPoolGen cp) { LocalVariableGen[] lg = getLocalVariables(); int size = lg.length; LocalVariable[] lv = new LocalVariable[size]; for (int i = 0; i < size; i++) lv[i] = lg[i].getLocalVariable(cp); return new LocalVariableTable( cp.addUtf8("LocalVariableTable"), 2 + lv.length * 10, lv, cp.getConstantPool()); } /** * Give an instruction a line number corresponding to the source code line. * * @param ih instruction to tag * @return new line number object * @see LineNumber */ public LineNumberGen addLineNumber(InstructionHandle ih, int src_line) { LineNumberGen l = new LineNumberGen(ih, src_line); line_number_vec.add(l); return l; } /** * Remove a line number. */ public void removeLineNumber(LineNumberGen l) { line_number_vec.remove(l); } /** * Remove all line numbers. */ public void removeLineNumbers() { line_number_vec.clear(); } /* * @return array of line numbers */ public LineNumberGen[] getLineNumbers() { LineNumberGen[] lg = new LineNumberGen[line_number_vec.size()]; line_number_vec.toArray(lg); return lg; } /** * @return `LineNumberTable' attribute of all the local variables of this method. */ public LineNumberTable getLineNumberTable(ConstantPoolGen cp) { int size = line_number_vec.size(); LineNumber[] ln = new LineNumber[size]; try { for (int i = 0; i < size; i++) ln[i] = ((LineNumberGen)line_number_vec.get(i)).getLineNumber(); } catch (ArrayIndexOutOfBoundsException e) { } // Never occurs return new LineNumberTable( cp.addUtf8("LineNumberTable"), 2 + ln.length * 4, ln, cp.getConstantPool()); } /** * Add an exception handler, i.e., specify region where a handler is active and an * instruction where the actual handling is done. * * @param start_pc Start of region (inclusive) * @param end_pc End of region (inclusive) * @param handler_pc Where handling is done * @param catch_type class type of handled exception or null if any * exception is handled * @return new exception handler object */ public CodeExceptionGen addExceptionHandler( InstructionHandle start_pc, InstructionHandle end_pc, InstructionHandle handler_pc, ObjectType catch_type) { if ((start_pc == null) || (end_pc == null) || (handler_pc == null)) throw new ClassGenException("Exception handler target is null instruction"); CodeExceptionGen c = new CodeExceptionGen(start_pc, end_pc, handler_pc, catch_type); exception_vec.add(c); return c; } /** * Remove an exception handler. */ public void removeExceptionHandler(CodeExceptionGen c) { exception_vec.remove(c); } /** * Remove all line numbers. */ public void removeExceptionHandlers() { exception_vec.clear(); } /* * @return array of declared exception handlers */ public CodeExceptionGen[] getExceptionHandlers() { CodeExceptionGen[] cg = new CodeExceptionGen[exception_vec.size()]; exception_vec.toArray(cg); return cg; } /** * @return code exceptions for `Code' attribute */ private CodeException[] getCodeExceptions() { int size = exception_vec.size(); CodeException[] c_exc = new CodeException[size]; try { for (int i = 0; i < size; i++) { CodeExceptionGen c = (CodeExceptionGen)exception_vec.get(i); c_exc[i] = c.getCodeException(cp); } } catch (ArrayIndexOutOfBoundsException e) { } return c_exc; } /** * Add an exception possibly thrown by this method. * * @param class_name (fully qualified) name of exception */ public void addException(String class_name) { throws_vec.add(class_name); } /** * Remove an exception. */ public void removeException(String c) { throws_vec.remove(c); } /** * Remove all exceptions. */ public void removeExceptions() { throws_vec.clear(); } /* * @return array of thrown exceptions */ public String[] getExceptions() { String[] e = new String[throws_vec.size()]; throws_vec.toArray(e); return e; } /** * @return `Exceptions' attribute of all the exceptions thrown by this method. */ private ExceptionTable getExceptionTable(ConstantPoolGen cp) { int size = throws_vec.size(); int[] ex = new int[size]; try { for (int i = 0; i < size; i++) ex[i] = cp.addClass((String)throws_vec.get(i)); } catch (ArrayIndexOutOfBoundsException e) { } return new ExceptionTable( cp.addUtf8("Exceptions"), 2 + 2 * size, ex, cp.getConstantPool()); } /** * Add an attribute to the code. Currently, the JVM knows about the * LineNumberTable, LocalVariableTable and StackMap attributes, * where the former two will be generated automatically and the * latter is used for the MIDP only. Other attributes will be * ignored by the JVM but do no harm. * * @param a attribute to be added */ public void addCodeAttribute(Attribute a) { code_attrs_vec.add(a); } /** * Remove a code attribute. */ public void removeCodeAttribute(Attribute a) { code_attrs_vec.remove(a); } /** * Remove all code attributes. */ public void removeCodeAttributes() { code_attrs_vec.clear(); } /** * @return all attributes of this method. */ public Attribute[] getCodeAttributes() { Attribute[] attributes = new Attribute[code_attrs_vec.size()]; code_attrs_vec.toArray(attributes); return attributes; } /** * Get method object. Never forget to call setMaxStack() or setMaxStack(max), respectively, * before calling this method (the same applies for max locals). * * @return method object */ public Method getMethod() { String signature = getSignature(); int name_index = cp.addUtf8(name); int signature_index = cp.addUtf8(signature); /* Also updates positions of instructions, i.e., their indices */ byte[] byte_code = null; if (il != null) byte_code = il.getByteCode(); LineNumberTable lnt = null; LocalVariableTable lvt = null; /* Create LocalVariableTable and LineNumberTable attributes (for debuggers, e.g.) */ if ((variable_vec.size() > 0) && !strip_attributes) addCodeAttribute(lvt = getLocalVariableTable(cp)); if ((line_number_vec.size() > 0) && !strip_attributes) addCodeAttribute(lnt = getLineNumberTable(cp)); Attribute[] code_attrs = getCodeAttributes(); /* Each attribute causes 6 additional header bytes */ int attrs_len = 0; for (int i = 0; i < code_attrs.length; i++) attrs_len += (code_attrs[i].getLength() + 6); CodeException[] c_exc = getCodeExceptions(); int exc_len = c_exc.length * 8; // Every entry takes 8 bytes Code code = null; if ((il != null) && !isAbstract() && !isNative()) { // Remove any stale code attribute Attribute[] attributes = getAttributes(); for (int i = 0; i < attributes.length; i++) { Attribute a = attributes[i]; if (a instanceof Code) removeAttribute(a); } code = new Code( cp.addUtf8("Code"), 8 + byte_code.length + // prologue byte code 2 + exc_len + // exceptions 2 + attrs_len, // attributes max_stack, max_locals, byte_code, c_exc, code_attrs, cp.getConstantPool()); addAttribute(code); } ExceptionTable et = null; if (throws_vec.size() > 0) addAttribute(et = getExceptionTable(cp)); // Add `Exceptions' if there are "throws" clauses Method m = new Method( access_flags, name_index, signature_index, getAttributes(), cp.getConstantPool()); // Undo effects of adding attributes if (lvt != null) removeCodeAttribute(lvt); if (lnt != null) removeCodeAttribute(lnt); if (code != null) removeAttribute(code); if (et != null) removeAttribute(et); return m; } /** * Remove all NOPs from the instruction list (if possible) and update every * object refering to them, i.e., branch instructions, local variables and * exception handlers. */ public void removeNOPs() { if (il != null) { InstructionHandle next; /* Check branch instructions. */ for (InstructionHandle ih = il.getStart(); ih != null; ih = next) { next = ih.next; if ((next != null) && (ih.getInstruction() instanceof NOP)) { try { il.delete(ih); } catch (TargetLostException e) { InstructionHandle[] targets = e.getTargets(); for (int i = 0; i < targets.length; i++) { InstructionTargeter[] targeters = targets[i].getTargeters(); for (int j = 0; j < targeters.length; j++) targeters[j].updateTarget(targets[i], next); } } } } } } /** * Set maximum number of local variables. */ public void setMaxLocals(int m) { max_locals = m; } public int getMaxLocals() { return max_locals; } /** * Set maximum stack size for this method. */ public void setMaxStack(int m) { max_stack = m; } public int getMaxStack() { return max_stack; } /** @return class that contains this method */ public String getClassName() { return class_name; } public void setClassName(String class_name) { this.class_name = class_name; } public void setReturnType(Type return_type) { setType(return_type); } public Type getReturnType() { return getType(); } public void setArgumentTypes(Type[] arg_types) { this.arg_types = arg_types; } public Type[] getArgumentTypes() { return (Type[])arg_types.clone(); } public void setArgumentType(int i, Type type) { arg_types[i] = type; } public Type getArgumentType(int i) { return arg_types[i]; } public void setArgumentNames(String[] arg_names) { this.arg_names = arg_names; } public String[] getArgumentNames() { return (String[])arg_names.clone(); } public void setArgumentName(int i, String name) { arg_names[i] = name; } public String getArgumentName(int i) { return arg_names[i]; } public InstructionList getInstructionList() { return il; } public void setInstructionList(InstructionList il) { this.il = il; } public String getSignature() { return Type.getMethodSignature(type, arg_types); } /** * Computes max. stack size by performing control flow analysis. */ public void setMaxStack() { if (il != null) max_stack = getMaxStack(cp, il, getExceptionHandlers()); else max_stack = 0; } /** * Compute maximum number of local variables. */ public void setMaxLocals() { if (il != null) { int max = isStatic() ? 0 : 1; if (arg_types != null) for (int i = 0; i < arg_types.length; i++) max += arg_types[i].getSize(); for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { Instruction ins = ih.getInstruction(); if ((ins instanceof LocalVariableInstruction) || (ins instanceof RET) || (ins instanceof IINC)) { int index = ((IndexedInstruction)ins).getIndex() + ((TypedInstruction)ins).getType(cp).getSize(); if (index > max) max = index; } } max_locals = max; } else max_locals = 0; } /** Do not/Do produce attributes code attributesLineNumberTable and * LocalVariableTable, like javac -O */ public void stripAttributes(boolean flag) { strip_attributes = flag; } static final class BranchTarget { InstructionHandle target; int stackDepth; BranchTarget(InstructionHandle target, int stackDepth) { this.target = target; this.stackDepth = stackDepth; } } static final class BranchStack { Stack branchTargets = new Stack(); Hashtable visitedTargets = new Hashtable(); public void push(InstructionHandle target, int stackDepth) { if (visited(target)) return; branchTargets.push(visit(target, stackDepth)); } public BranchTarget pop() { if (!branchTargets.empty()) { BranchTarget bt = (BranchTarget)branchTargets.pop(); return bt; } return null; } private final BranchTarget visit( InstructionHandle target, int stackDepth) { BranchTarget bt = new BranchTarget(target, stackDepth); visitedTargets.put(target, bt); return bt; } private final boolean visited(InstructionHandle target) { return (visitedTargets.get(target) != null); } } /** * Computes stack usage of an instruction list by performing control flow analysis. * * @return maximum stack depth used by method */ public static int getMaxStack( ConstantPoolGen cp, InstructionList il, CodeExceptionGen[] et) { BranchStack branchTargets = new BranchStack(); /* Initially, populate the branch stack with the exception * handlers, because these aren't (necessarily) branched to * explicitly. in each case, the stack will have depth 1, * containing the exception object. */ for (int i = 0; i < et.length; i++) { InstructionHandle handler_pc = et[i].getHandlerPC(); if (handler_pc != null) branchTargets.push(handler_pc, 1); } int stackDepth = 0, maxStackDepth = 0; InstructionHandle ih = il.getStart(); while (ih != null) { Instruction instruction = ih.getInstruction(); short opcode = instruction.getOpcode(); int delta = instruction.produceStack(cp) - instruction.consumeStack(cp); stackDepth += delta; if (stackDepth > maxStackDepth) maxStackDepth = stackDepth; // choose the next instruction based on whether current is a branch. if (instruction instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction)instruction; if (instruction instanceof Select) { // explore all of the select's targets. the default target is handled below. Select select = (Select)branch; InstructionHandle[] targets = select.getTargets(); for (int i = 0; i < targets.length; i++) branchTargets.push(targets[i], stackDepth); // nothing to fall through to. ih = null; } else if (!(branch instanceof IfInstruction)) { // if an instruction that comes back to following PC, // push next instruction, with stack depth reduced by 1. if (opcode == Constants.JSR || opcode == Constants.JSR_W) branchTargets.push(ih.getNext(), stackDepth - 1); ih = null; } // for all branches, the target of the branch is pushed on the branch stack. // conditional branches have a fall through case, selects don't, and // jsr/jsr_w return to the next instruction. branchTargets.push(branch.getTarget(), stackDepth); } else { // check for instructions that terminate the method. if (opcode == Constants.ATHROW || opcode == Constants.RET || (opcode >= Constants.IRETURN && opcode <= Constants.RETURN)) ih = null; } // normal case, go to the next instruction. if (ih != null) ih = ih.getNext(); // if we have no more instructions, see if there are any deferred branches to explore. if (ih == null) { BranchTarget bt = branchTargets.pop(); if (bt != null) { ih = bt.target; stackDepth = bt.stackDepth; } } } return maxStackDepth; } private List observers; /** Add observer for this object. */ public void addObserver(MethodObserver o) { if (observers == null) observers = new ArrayList(); observers.add(o); } /** Remove observer for this object. */ public void removeObserver(MethodObserver o) { if (observers != null) observers.remove(o); } /** Call notify() method on all observers. This method is not called * automatically whenever the state has changed, but has to be * called by the user after he has finished editing the object. */ public void update() { if (observers != null) for (Iterator e = observers.iterator(); e.hasNext();) ((MethodObserver)e.next()).notify(this); } /** * Return string representation close to declaration format, * `public static void main(String[]) throws IOException', e.g. * * @return String representation of the method. */ public final String toString() { String access = Utility.accessToString(access_flags); String signature = Type.getMethodSignature(type, arg_types); signature = Utility.methodSignatureToString( signature, name, access, true, getLocalVariableTable(cp)); StringBuffer buf = new StringBuffer(signature); if (throws_vec.size() > 0) { for (Iterator e = throws_vec.iterator(); e.hasNext();) buf.append("\n\t\tthrows " + e.next()); } return buf.toString(); } /** @return deep copy of this method */ public MethodGen copy(String class_name, ConstantPoolGen cp) { Method m = ((MethodGen)clone()).getMethod(); MethodGen mg = new MethodGen(m, class_name, this.cp); if (this.cp != cp) { mg.setConstantPool(cp); mg.getInstructionList().replaceConstantPool(this.cp, cp); } return mg; } /** * @return Comparison strategy object */ public static BCELComparator getComparator() { return _cmp; } /** * @param comparator Comparison strategy object */ public static void setComparator(BCELComparator comparator) { _cmp = comparator; } /** * Return value as defined by given BCELComparator strategy. * By default two MethodGen objects are said to be equal when * their names and signatures are equal. * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return _cmp.equals(this, obj); } /** * Return value as defined by given BCELComparator strategy. * By default return the hashcode of the method's name XOR signature. * * @see java.lang.Object#hashCode() */ public int hashCode() { return _cmp.hashCode(this); } }
true
true
public MethodGen(Method m, String class_name, ConstantPoolGen cp) { this( m.getAccessFlags(), Type.getReturnType(m.getSignature()), Type.getArgumentTypes(m.getSignature()), null /* may be overridden anyway */ , m.getName(), class_name, ((m.getAccessFlags() & (Constants.ACC_ABSTRACT | Constants.ACC_NATIVE)) == 0) ? new InstructionList(m.getCode().getCode()) : null, cp); Attribute[] attributes = m.getAttributes(); for (int i = 0; i < attributes.length; i++) { Attribute a = attributes[i]; if (a instanceof Code) { Code c = (Code)a; setMaxStack(c.getMaxStack()); setMaxLocals(c.getMaxLocals()); CodeException[] ces = c.getExceptionTable(); if (ces != null) { for (int j = 0; j < ces.length; j++) { CodeException ce = ces[j]; int type = ce.getCatchType(); ObjectType c_type = null; if (type > 0) { String cen = m.getConstantPool().getConstantString( type, Constants.CONSTANT_Class); c_type = new ObjectType(cen); } int end_pc = ce.getEndPC(); int length = m.getCode().getCode().length; InstructionHandle end; if (length == end_pc) { // May happen, because end_pc is exclusive end = il.getEnd(); } else { end = il.findHandle(end_pc); end = end.getPrev(); // Make it inclusive } addExceptionHandler( il.findHandle(ce.getStartPC()), end, il.findHandle(ce.getHandlerPC()), c_type); } } Attribute[] c_attributes = c.getAttributes(); for (int j = 0; j < c_attributes.length; j++) { a = c_attributes[j]; if (a instanceof LineNumberTable) { LineNumber[] ln = ((LineNumberTable)a).getLineNumberTable(); for (int k = 0; k < ln.length; k++) { LineNumber l = ln[k]; addLineNumber(il.findHandle(l.getStartPC()), l.getLineNumber()); } } else if (a instanceof LocalVariableTable) { LocalVariable[] lv = ((LocalVariableTable)a).getLocalVariableTable(); removeLocalVariables(); for (int k = 0; k < lv.length; k++) { LocalVariable l = lv[k]; InstructionHandle start = il.findHandle(l.getStartPC()); InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength()); // Repair malformed handles if (null == start) { start = il.getStart(); } if (null == end) { end = il.getEnd(); } addLocalVariable( l.getName(), Type.getType(l.getSignature()), l.getIndex(), start, end); } } else addCodeAttribute(a); } } else if (a instanceof ExceptionTable) { String[] names = ((ExceptionTable)a).getExceptionNames(); for (int j = 0; j < names.length; j++) addException(names[j]); } else addAttribute(a); } }
public MethodGen(Method m, String class_name, ConstantPoolGen cp) { this( m.getAccessFlags(), Type.getReturnType(m.getSignature()), Type.getArgumentTypes(m.getSignature()), null /* may be overridden anyway */ , m.getName(), class_name, ((m.getAccessFlags() & (Constants.ACC_ABSTRACT | Constants.ACC_NATIVE)) == 0) ? new InstructionList(m.getCode().getCode()) : null, cp); Attribute[] attributes = m.getAttributes(); for (int i = 0; i < attributes.length; i++) { Attribute a = attributes[i]; if (a instanceof Code) { Code c = (Code)a; setMaxStack(c.getMaxStack()); setMaxLocals(c.getMaxLocals()); CodeException[] ces = c.getExceptionTable(); if (ces != null) { for (int j = 0; j < ces.length; j++) { CodeException ce = ces[j]; int type = ce.getCatchType(); ObjectType c_type = null; if (type > 0) { String cen = m.getConstantPool().getConstantString( type, Constants.CONSTANT_Class); c_type = new ObjectType(cen); } int end_pc = ce.getEndPC(); int length = m.getCode().getCode().length; InstructionHandle end; if (length == end_pc) { // May happen, because end_pc is exclusive end = il.getEnd(); } else { end = il.findHandle(end_pc); end = end.getPrev(); // Make it inclusive } addExceptionHandler( il.findHandle(ce.getStartPC()), end, il.findHandle(ce.getHandlerPC()), c_type); } } Attribute[] c_attributes = c.getAttributes(); for (int j = 0; j < c_attributes.length; j++) { a = c_attributes[j]; if (a instanceof LineNumberTable) { LineNumber[] ln = ((LineNumberTable)a).getLineNumberTable(); for (int k = 0; k < ln.length; k++) { LineNumber l = ln[k]; InstructionHandle ih = il.findHandle(l.getStartPC()); if (ih != null) addLineNumber(ih, l.getLineNumber()); } } else if (a instanceof LocalVariableTable) { LocalVariable[] lv = ((LocalVariableTable)a).getLocalVariableTable(); removeLocalVariables(); for (int k = 0; k < lv.length; k++) { LocalVariable l = lv[k]; InstructionHandle start = il.findHandle(l.getStartPC()); InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength()); // Repair malformed handles if (null == start) { start = il.getStart(); } if (null == end) { end = il.getEnd(); } addLocalVariable( l.getName(), Type.getType(l.getSignature()), l.getIndex(), start, end); } } else addCodeAttribute(a); } } else if (a instanceof ExceptionTable) { String[] names = ((ExceptionTable)a).getExceptionNames(); for (int j = 0; j < names.length; j++) addException(names[j]); } else addAttribute(a); } }
diff --git a/src/main/java/com/ids/controllers/DeleteController.java b/src/main/java/com/ids/controllers/DeleteController.java index 56d0d6d..81b3a8a 100644 --- a/src/main/java/com/ids/controllers/DeleteController.java +++ b/src/main/java/com/ids/controllers/DeleteController.java @@ -1,412 +1,412 @@ package com.ids.controllers; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.logging.Level; import java.util.logging.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; import org.apache.commons.lang3.text.WordUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.google.appengine.api.rdbms.AppEngineDriver; import com.google.cloud.sql.jdbc.PreparedStatement; import com.ids.businessLogic.DownloadExcel; import com.ids.businessLogic.DropdownInterface; import com.ids.businessLogic.FirstTimeQuery; import com.ids.businessLogic.StoreRequestParameters; import com.ids.context.GetBeansFromContext; import com.ids.json.ColumnModel; import com.ids.json.ColumnNameArray; import com.ids.json.ColumnSummaryNameArray; import com.ids.json.JsonGroupSummaryWithinLoop; import com.ids.json.JsonPackaging; import com.ids.json.JsonSummaryWithinLoop; import com.ids.json.JsonWithInLoop; import com.ids.sql.SQL1; import com.ids.sql.SQL1GrpSummary; import com.ids.sql.SQL1Summary; import com.ids.sql.SQL2; import com.ids.sql.SQL3; import com.ids.sql.SQL4; import com.ids.sql.SQL5; import com.ids.sql.SQL6; import com.ids.user.User; @Controller @RequestMapping(value="/deleterow") public class DeleteController implements DropdownInterface { private Connection con; private final static Logger logger = Logger.getLogger(DeleteController.class.getName()); // HashMap<Integer,Integer> totalLine = null; HashMap<String,Integer> totalLine2 = null; // HashMap<Integer,Integer> otherLine = null; @RequestMapping( method = RequestMethod.GET) public String getMethodOne( HttpServletResponse response, HttpServletRequest request, ModelMap model) { try{ logger.warning("Entering application via GEt"); logger.warning("excelDownload: "+request.getParameter("excelDownload")); GetBeansFromContext gcfc = new GetBeansFromContext(); con = gcfc.myConnection(); Enumeration keys = request.getParameterNames(); while (keys.hasMoreElements() ) { String key = (String)keys.nextElement(); logger.warning(key); //To retrieve a single value String value = request.getParameter(key); logger.warning(value); // If the same key has multiple values (check boxes) String[] valueArray = request.getParameterValues(key); for(int i = 0; i > valueArray.length; i++){ logger.warning("VALUE ARRAY" + valueArray[i]); } } Statement statement = con.createStatement(); ResultSet resultSet = null; HttpSession session = request.getSession(true); User user = (User) session.getAttribute("myUser"); if (user==null ) { model.addAttribute("errortext","You must logon before you can access IDS"); return "login"; } if (request.getParameter("exit")!= null ){ if (session.getAttribute("myUser") != null) { session.setAttribute("myUser",null); } return "login"; } String query = " select 'found' as found from ids_users where userId = '"+user.getUserName() +"' and passwordId = '"+user.getPassword()+"'"; resultSet = statement.executeQuery(query); boolean found = false; while (resultSet.next()) { if (resultSet.getString("found").equals("found")) { found = true; break; } break; } if (!found) { model.addAttribute("errortext","Invalid user credentials"); return "login"; } model.addAttribute("openOrClose","close"); String year = ""; String productId = ""; String countryId = ""; String companyId = ""; String PorS =""; String SQL = ""; String value = request.getParameter("dimension1Name"); logger.warning("dimension1Name: "+value); value = WordUtils.capitalize(value); if (value.equals("Year")) { year = request.getParameter("dimension1Val"); } else { boolean comp = false; if (value.equals("Company")) { try { Integer.parseInt(request.getParameter("dimension1Val")); comp =true; } catch(Exception e) { } } if (comp) { companyId=request.getParameter("dimension1Val"); } else{ SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension1Val") +"' "; logger.warning("SQL1: "+SQL); resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.equals("Country")) { countryId= resultSet.getString("id"); break; } if (value.equals("Company")) { companyId= resultSet.getString("id"); break; } if (value.equals("Product")) { productId= resultSet.getString("id"); break; } } } //not company } value = request.getParameter("dimension2Name"); value =WordUtils.capitalize(value) ; if (value.equals("Year")) { year = request.getParameter("dimension2Val"); } else { if (request.getParameter("dimension2Name").trim().equals("Country")){ SQL = " select id from "+value+ " where country = '" +request.getParameter("dimension2Val").trim() +"' "; } else { SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension2Val").trim() +"' "; } logger.warning("SQL2: "+SQL); logger.warning("value2: "+value); if (resultSet != null) { resultSet.close(); } resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.trim().equals("Country")) { logger.warning("come one we must have got in here"); countryId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Company")) { companyId=Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Product")) { productId= Integer.toString(resultSet.getInt("id")); break; } } } value = request.getParameter("dimension3Name"); value =WordUtils.capitalize(value) ; if (value.equals("Year")) { year = request.getParameter("dimension3Val"); } else { if (value.equals("Country")) { SQL = " select id from "+value+ " where country = '" +request.getParameter("dimension3Val").trim() +"' "; }else{ SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension3Val").trim() +"' "; } logger.warning("SQL3: "+SQL); logger.warning("value3: "+value); resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.equals("Country")) { countryId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Company")) { companyId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Product")) { productId= Integer.toString(resultSet.getInt("id")); break; } } } if (request.getParameter("dimension4Val").equals("Sales") ) { PorS= "1"; } else { PorS = "2"; } logger.warning("year: "+year); logger.warning("productId: "+productId); logger.warning("countryId: "+countryId); logger.warning("companyId: "+companyId); logger.warning("PorS: "+PorS); String newSQL=""; if (productId==null || productId.equals("")){ newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where year = "+year+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where year = "+year+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (year==null || year.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (companyId == null || companyId.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); - newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + + newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (countryId==null || countryId.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and companyId = "+companyId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); - newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + + newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and companyId = "+companyId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } newSQL = "update editing set flag = '1' "; PreparedStatement statement3 = (PreparedStatement) con.prepareStatement(newSQL); statement3.executeUpdate(); con.commit(); }catch(Exception e) { logger.log(Level.SEVERE,"Error",e); } return "redirect:editor?openOrClose=open"; } @Transactional @RequestMapping( method = RequestMethod.POST) public String postMethodOne( HttpServletResponse response, HttpServletRequest request, ModelMap model) { logger.warning("Entering application via POST"); return getMethodOne( response, request, model); } }
false
true
public String getMethodOne( HttpServletResponse response, HttpServletRequest request, ModelMap model) { try{ logger.warning("Entering application via GEt"); logger.warning("excelDownload: "+request.getParameter("excelDownload")); GetBeansFromContext gcfc = new GetBeansFromContext(); con = gcfc.myConnection(); Enumeration keys = request.getParameterNames(); while (keys.hasMoreElements() ) { String key = (String)keys.nextElement(); logger.warning(key); //To retrieve a single value String value = request.getParameter(key); logger.warning(value); // If the same key has multiple values (check boxes) String[] valueArray = request.getParameterValues(key); for(int i = 0; i > valueArray.length; i++){ logger.warning("VALUE ARRAY" + valueArray[i]); } } Statement statement = con.createStatement(); ResultSet resultSet = null; HttpSession session = request.getSession(true); User user = (User) session.getAttribute("myUser"); if (user==null ) { model.addAttribute("errortext","You must logon before you can access IDS"); return "login"; } if (request.getParameter("exit")!= null ){ if (session.getAttribute("myUser") != null) { session.setAttribute("myUser",null); } return "login"; } String query = " select 'found' as found from ids_users where userId = '"+user.getUserName() +"' and passwordId = '"+user.getPassword()+"'"; resultSet = statement.executeQuery(query); boolean found = false; while (resultSet.next()) { if (resultSet.getString("found").equals("found")) { found = true; break; } break; } if (!found) { model.addAttribute("errortext","Invalid user credentials"); return "login"; } model.addAttribute("openOrClose","close"); String year = ""; String productId = ""; String countryId = ""; String companyId = ""; String PorS =""; String SQL = ""; String value = request.getParameter("dimension1Name"); logger.warning("dimension1Name: "+value); value = WordUtils.capitalize(value); if (value.equals("Year")) { year = request.getParameter("dimension1Val"); } else { boolean comp = false; if (value.equals("Company")) { try { Integer.parseInt(request.getParameter("dimension1Val")); comp =true; } catch(Exception e) { } } if (comp) { companyId=request.getParameter("dimension1Val"); } else{ SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension1Val") +"' "; logger.warning("SQL1: "+SQL); resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.equals("Country")) { countryId= resultSet.getString("id"); break; } if (value.equals("Company")) { companyId= resultSet.getString("id"); break; } if (value.equals("Product")) { productId= resultSet.getString("id"); break; } } } //not company } value = request.getParameter("dimension2Name"); value =WordUtils.capitalize(value) ; if (value.equals("Year")) { year = request.getParameter("dimension2Val"); } else { if (request.getParameter("dimension2Name").trim().equals("Country")){ SQL = " select id from "+value+ " where country = '" +request.getParameter("dimension2Val").trim() +"' "; } else { SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension2Val").trim() +"' "; } logger.warning("SQL2: "+SQL); logger.warning("value2: "+value); if (resultSet != null) { resultSet.close(); } resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.trim().equals("Country")) { logger.warning("come one we must have got in here"); countryId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Company")) { companyId=Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Product")) { productId= Integer.toString(resultSet.getInt("id")); break; } } } value = request.getParameter("dimension3Name"); value =WordUtils.capitalize(value) ; if (value.equals("Year")) { year = request.getParameter("dimension3Val"); } else { if (value.equals("Country")) { SQL = " select id from "+value+ " where country = '" +request.getParameter("dimension3Val").trim() +"' "; }else{ SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension3Val").trim() +"' "; } logger.warning("SQL3: "+SQL); logger.warning("value3: "+value); resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.equals("Country")) { countryId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Company")) { companyId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Product")) { productId= Integer.toString(resultSet.getInt("id")); break; } } } if (request.getParameter("dimension4Val").equals("Sales") ) { PorS= "1"; } else { PorS = "2"; } logger.warning("year: "+year); logger.warning("productId: "+productId); logger.warning("countryId: "+countryId); logger.warning("companyId: "+companyId); logger.warning("PorS: "+PorS); String newSQL=""; if (productId==null || productId.equals("")){ newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where year = "+year+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where year = "+year+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (year==null || year.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (companyId == null || companyId.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (countryId==null || countryId.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and companyId = "+companyId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and companyId = "+companyId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } newSQL = "update editing set flag = '1' "; PreparedStatement statement3 = (PreparedStatement) con.prepareStatement(newSQL); statement3.executeUpdate(); con.commit(); }catch(Exception e) { logger.log(Level.SEVERE,"Error",e); } return "redirect:editor?openOrClose=open"; }
public String getMethodOne( HttpServletResponse response, HttpServletRequest request, ModelMap model) { try{ logger.warning("Entering application via GEt"); logger.warning("excelDownload: "+request.getParameter("excelDownload")); GetBeansFromContext gcfc = new GetBeansFromContext(); con = gcfc.myConnection(); Enumeration keys = request.getParameterNames(); while (keys.hasMoreElements() ) { String key = (String)keys.nextElement(); logger.warning(key); //To retrieve a single value String value = request.getParameter(key); logger.warning(value); // If the same key has multiple values (check boxes) String[] valueArray = request.getParameterValues(key); for(int i = 0; i > valueArray.length; i++){ logger.warning("VALUE ARRAY" + valueArray[i]); } } Statement statement = con.createStatement(); ResultSet resultSet = null; HttpSession session = request.getSession(true); User user = (User) session.getAttribute("myUser"); if (user==null ) { model.addAttribute("errortext","You must logon before you can access IDS"); return "login"; } if (request.getParameter("exit")!= null ){ if (session.getAttribute("myUser") != null) { session.setAttribute("myUser",null); } return "login"; } String query = " select 'found' as found from ids_users where userId = '"+user.getUserName() +"' and passwordId = '"+user.getPassword()+"'"; resultSet = statement.executeQuery(query); boolean found = false; while (resultSet.next()) { if (resultSet.getString("found").equals("found")) { found = true; break; } break; } if (!found) { model.addAttribute("errortext","Invalid user credentials"); return "login"; } model.addAttribute("openOrClose","close"); String year = ""; String productId = ""; String countryId = ""; String companyId = ""; String PorS =""; String SQL = ""; String value = request.getParameter("dimension1Name"); logger.warning("dimension1Name: "+value); value = WordUtils.capitalize(value); if (value.equals("Year")) { year = request.getParameter("dimension1Val"); } else { boolean comp = false; if (value.equals("Company")) { try { Integer.parseInt(request.getParameter("dimension1Val")); comp =true; } catch(Exception e) { } } if (comp) { companyId=request.getParameter("dimension1Val"); } else{ SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension1Val") +"' "; logger.warning("SQL1: "+SQL); resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.equals("Country")) { countryId= resultSet.getString("id"); break; } if (value.equals("Company")) { companyId= resultSet.getString("id"); break; } if (value.equals("Product")) { productId= resultSet.getString("id"); break; } } } //not company } value = request.getParameter("dimension2Name"); value =WordUtils.capitalize(value) ; if (value.equals("Year")) { year = request.getParameter("dimension2Val"); } else { if (request.getParameter("dimension2Name").trim().equals("Country")){ SQL = " select id from "+value+ " where country = '" +request.getParameter("dimension2Val").trim() +"' "; } else { SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension2Val").trim() +"' "; } logger.warning("SQL2: "+SQL); logger.warning("value2: "+value); if (resultSet != null) { resultSet.close(); } resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.trim().equals("Country")) { logger.warning("come one we must have got in here"); countryId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Company")) { companyId=Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Product")) { productId= Integer.toString(resultSet.getInt("id")); break; } } } value = request.getParameter("dimension3Name"); value =WordUtils.capitalize(value) ; if (value.equals("Year")) { year = request.getParameter("dimension3Val"); } else { if (value.equals("Country")) { SQL = " select id from "+value+ " where country = '" +request.getParameter("dimension3Val").trim() +"' "; }else{ SQL = " select id from "+value+ " where name = '" +request.getParameter("dimension3Val").trim() +"' "; } logger.warning("SQL3: "+SQL); logger.warning("value3: "+value); resultSet = statement.executeQuery(SQL); while (resultSet.next()) { if (value.equals("Country")) { countryId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Company")) { companyId= Integer.toString(resultSet.getInt("id")); break; } if (value.equals("Product")) { productId= Integer.toString(resultSet.getInt("id")); break; } } } if (request.getParameter("dimension4Val").equals("Sales") ) { PorS= "1"; } else { PorS = "2"; } logger.warning("year: "+year); logger.warning("productId: "+productId); logger.warning("countryId: "+countryId); logger.warning("companyId: "+companyId); logger.warning("PorS: "+PorS); String newSQL=""; if (productId==null || productId.equals("")){ newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where year = "+year+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where year = "+year+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (year==null || year.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and companyId = "+companyId+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (companyId == null || companyId.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and countryId = "+countryId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } if (countryId==null || countryId.equals("")) { newSQL = "delete from FactsEdit_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and companyId = "+companyId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); PreparedStatement statement2 = (PreparedStatement) con.prepareStatement(newSQL); int retval = statement2.executeUpdate(); newSQL = "delete from Facts_"+request.getParameter("accessCurr")+" " + " where productId = "+productId+ " and year = "+year+ " and companyId = "+companyId+ " and sales_production ="+PorS+ " and access = '"+request.getParameter("accessCurr")+"'"; logger.warning("deleteSQL: "+newSQL); statement2 = (PreparedStatement) con.prepareStatement(newSQL); retval = statement2.executeUpdate(); } newSQL = "update editing set flag = '1' "; PreparedStatement statement3 = (PreparedStatement) con.prepareStatement(newSQL); statement3.executeUpdate(); con.commit(); }catch(Exception e) { logger.log(Level.SEVERE,"Error",e); } return "redirect:editor?openOrClose=open"; }
diff --git a/arquillian/classpath/src/main/java/org/jboss/forge/arquillian/ForgeDeployableContainer.java b/arquillian/classpath/src/main/java/org/jboss/forge/arquillian/ForgeDeployableContainer.java index 70f045716..bc8b24317 100644 --- a/arquillian/classpath/src/main/java/org/jboss/forge/arquillian/ForgeDeployableContainer.java +++ b/arquillian/classpath/src/main/java/org/jboss/forge/arquillian/ForgeDeployableContainer.java @@ -1,339 +1,339 @@ /* * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.arquillian; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Future; import org.jboss.arquillian.container.spi.client.container.DeployableContainer; import org.jboss.arquillian.container.spi.client.container.DeploymentException; import org.jboss.arquillian.container.spi.client.container.LifecycleException; import org.jboss.arquillian.container.spi.client.deployment.Deployment; import org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription; import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData; import org.jboss.arquillian.core.api.Instance; import org.jboss.arquillian.core.api.annotation.Inject; import org.jboss.forge.addon.manager.AddonManager; import org.jboss.forge.addon.manager.impl.AddonManagerImpl; import org.jboss.forge.addon.maven.dependencies.MavenDependencyResolver; import org.jboss.forge.arquillian.archive.ForgeArchive; import org.jboss.forge.arquillian.archive.ForgeRemoteAddon; import org.jboss.forge.arquillian.protocol.ForgeProtocolDescription; import org.jboss.forge.arquillian.util.ShrinkWrapUtil; import org.jboss.forge.furnace.Furnace; import org.jboss.forge.furnace.FurnaceImpl; import org.jboss.forge.furnace.addons.Addon; import org.jboss.forge.furnace.addons.AddonId; import org.jboss.forge.furnace.addons.AddonRegistry; import org.jboss.forge.furnace.exception.ContainerException; import org.jboss.forge.furnace.lock.LockMode; import org.jboss.forge.furnace.repositories.AddonRepositoryMode; import org.jboss.forge.furnace.repositories.MutableAddonRepository; import org.jboss.forge.furnace.spi.ContainerLifecycleListener; import org.jboss.forge.furnace.spi.ListenerRegistration; import org.jboss.forge.furnace.util.Addons; import org.jboss.forge.furnace.util.ClassLoaders; import org.jboss.forge.furnace.util.Files; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.descriptor.api.Descriptor; /** * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a> */ public class ForgeDeployableContainer implements DeployableContainer<ForgeContainerConfiguration> { @Inject private Instance<Deployment> deploymentInstance; private ForgeRunnable runnable; private File addonDir; private MutableAddonRepository repository; private Map<Deployment, AddonId> deployedAddons = new HashMap<Deployment, AddonId>(); private Thread thread; private boolean undeploying = false; @Override public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException { if (undeploying) { undeploying = false; cleanup(); } Deployment deployment = deploymentInstance.get(); final AddonId addonToDeploy = getAddonEntry(deployment); File destDir = repository.getAddonBaseDir(addonToDeploy); destDir.mkdirs(); System.out.println("Deploying [" + addonToDeploy + "] to repository [" + repository + "]"); if (archive instanceof ForgeArchive) { ShrinkWrapUtil.toFile(new File(destDir.getAbsolutePath() + "/" + archive.getName()), archive); ShrinkWrapUtil.unzip(destDir, archive); ConfigurationScanListener listener = new ConfigurationScanListener(); ListenerRegistration<ContainerLifecycleListener> registration = runnable.furnace .addContainerLifecycleListener(listener); repository.deploy(addonToDeploy, ((ForgeArchive) archive).getAddonDependencies(), new ArrayList<File>()); repository.enable(addonToDeploy); while (runnable.furnace.getStatus().isStarting() || !listener.isConfigurationScanned()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } registration.removeListener(); AddonRegistry registry = runnable.getForge().getAddonRegistry(); Addon addon = registry.getAddon(addonToDeploy); try { Future<Void> future = addon.getFuture(); future.get(); if (addon.getStatus().isFailed()) { DeploymentException e = new DeploymentException("AddonDependency " + addonToDeploy + " failed to deploy."); deployment.deployedWithError(e); - throw e; + throw new DeploymentException("AddonDependency " + addonToDeploy + " failed to deploy.", e); } } catch (Exception e) { deployment.deployedWithError(e); throw new DeploymentException("AddonDependency " + addonToDeploy + " failed to deploy.", e); } } else if (archive instanceof ForgeRemoteAddon) { ForgeRemoteAddon remoteAddon = (ForgeRemoteAddon) archive; AddonManager addonManager = new AddonManagerImpl(runnable.furnace, new MavenDependencyResolver(), false); addonManager.install(remoteAddon.getAddonId()).perform(); AddonRegistry registry = runnable.getForge().getAddonRegistry(); Addon addon = registry.getAddon(addonToDeploy); try { Future<Void> future = addon.getFuture(); future.get(); if (addon.getStatus().isFailed()) { ContainerException e = new ContainerException("AddonDependency " + addonToDeploy + " failed to deploy."); deployment.deployedWithError(e); throw e; } } catch (Exception e) { throw new DeploymentException("Failed to deploy " + addonToDeploy, e); } } else { throw new IllegalArgumentException( "Invalid Archive type. Ensure that your @Deployment method returns type 'ForgeArchive'."); } return new ProtocolMetaData().addContext(runnable.getForge()); } private void cleanup() { runnable.getForge().getLockManager().performLocked(LockMode.WRITE, new Callable<Void>() { @Override public Void call() throws Exception { for (AddonId enabled : repository.listEnabled()) { try { repository.disable(enabled); repository.undeploy(enabled); } catch (Exception e) { e.printStackTrace(); } } return null; } }); } @Override public void deploy(Descriptor descriptor) throws DeploymentException { throw new UnsupportedOperationException("Descriptors not supported by Furnace"); } private AddonId getAddonEntry(Deployment deployment) { if (!deployedAddons.containsKey(deployment)) { String[] coordinates = deployment.getDescription().getName().split(","); AddonId entry; if (coordinates.length == 3) entry = AddonId.from(coordinates[0], coordinates[1], coordinates[2]); else if (coordinates.length == 2) entry = AddonId.from(coordinates[0], coordinates[1]); else if (coordinates.length == 1) entry = AddonId.from(coordinates[0], UUID.randomUUID().toString()); else entry = AddonId.from(UUID.randomUUID().toString(), UUID.randomUUID().toString()); deployedAddons.put(deployment, entry); } return deployedAddons.get(deployment); } @Override public Class<ForgeContainerConfiguration> getConfigurationClass() { return ForgeContainerConfiguration.class; } @Override public ProtocolDescription getDefaultProtocol() { return new ForgeProtocolDescription(); } @Override public void setup(ForgeContainerConfiguration configuration) { } @Override public void start() throws LifecycleException { try { this.addonDir = File.createTempFile("furnace", "test-addon-dir"); runnable = new ForgeRunnable(addonDir, ClassLoader.getSystemClassLoader()); thread = new Thread(runnable, "Arquillian Furnace Runtime"); System.out.println("Executing test case with addon dir [" + addonDir + "]"); thread.start(); } catch (IOException e) { throw new LifecycleException("Failed to create temporary addon directory", e); } catch (Exception e) { throw new LifecycleException("Could not start Furnace runnable.", e); } } @Override public void stop() throws LifecycleException { this.runnable.stop(); Files.delete(addonDir, true); } @Override public void undeploy(Archive<?> archive) throws DeploymentException { undeploying = true; AddonId addonToUndeploy = getAddonEntry(deploymentInstance.get()); AddonRegistry registry = runnable.getForge().getAddonRegistry(); System.out.println("Undeploying [" + addonToUndeploy + "] ... "); try { repository.disable(addonToUndeploy); Addon addonToStop = registry.getAddon(addonToUndeploy); Addons.waitUntilStopped(addonToStop); } catch (Exception e) { throw new DeploymentException("Failed to undeploy " + addonToUndeploy, e); } finally { repository.undeploy(addonToUndeploy); } } @Override public void undeploy(Descriptor descriptor) throws DeploymentException { throw new UnsupportedOperationException("Descriptors not supported by Furnace"); } private class ForgeRunnable implements Runnable { private Furnace furnace; private ClassLoader loader; private File addonDir; public ForgeRunnable(File addonDir, ClassLoader loader) { this.furnace = new FurnaceImpl(); this.addonDir = addonDir; this.loader = loader; } public Furnace getForge() { return furnace; } @Override public void run() { try { ClassLoaders.executeIn(loader, new Callable<Object>() { @Override public Object call() throws Exception { repository = (MutableAddonRepository) runnable.furnace .addRepository(AddonRepositoryMode.MUTABLE, addonDir); furnace.setServerMode(true); furnace.start(loader); return furnace; } }); } catch (Exception e) { throw new RuntimeException("Failed to start Furnace container.", e); } } public void stop() { furnace.stop(); Thread.currentThread().interrupt(); } } }
true
true
public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException { if (undeploying) { undeploying = false; cleanup(); } Deployment deployment = deploymentInstance.get(); final AddonId addonToDeploy = getAddonEntry(deployment); File destDir = repository.getAddonBaseDir(addonToDeploy); destDir.mkdirs(); System.out.println("Deploying [" + addonToDeploy + "] to repository [" + repository + "]"); if (archive instanceof ForgeArchive) { ShrinkWrapUtil.toFile(new File(destDir.getAbsolutePath() + "/" + archive.getName()), archive); ShrinkWrapUtil.unzip(destDir, archive); ConfigurationScanListener listener = new ConfigurationScanListener(); ListenerRegistration<ContainerLifecycleListener> registration = runnable.furnace .addContainerLifecycleListener(listener); repository.deploy(addonToDeploy, ((ForgeArchive) archive).getAddonDependencies(), new ArrayList<File>()); repository.enable(addonToDeploy); while (runnable.furnace.getStatus().isStarting() || !listener.isConfigurationScanned()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } registration.removeListener(); AddonRegistry registry = runnable.getForge().getAddonRegistry(); Addon addon = registry.getAddon(addonToDeploy); try { Future<Void> future = addon.getFuture(); future.get(); if (addon.getStatus().isFailed()) { DeploymentException e = new DeploymentException("AddonDependency " + addonToDeploy + " failed to deploy."); deployment.deployedWithError(e); throw e; } } catch (Exception e) { deployment.deployedWithError(e); throw new DeploymentException("AddonDependency " + addonToDeploy + " failed to deploy.", e); } } else if (archive instanceof ForgeRemoteAddon) { ForgeRemoteAddon remoteAddon = (ForgeRemoteAddon) archive; AddonManager addonManager = new AddonManagerImpl(runnable.furnace, new MavenDependencyResolver(), false); addonManager.install(remoteAddon.getAddonId()).perform(); AddonRegistry registry = runnable.getForge().getAddonRegistry(); Addon addon = registry.getAddon(addonToDeploy); try { Future<Void> future = addon.getFuture(); future.get(); if (addon.getStatus().isFailed()) { ContainerException e = new ContainerException("AddonDependency " + addonToDeploy + " failed to deploy."); deployment.deployedWithError(e); throw e; } } catch (Exception e) { throw new DeploymentException("Failed to deploy " + addonToDeploy, e); } } else { throw new IllegalArgumentException( "Invalid Archive type. Ensure that your @Deployment method returns type 'ForgeArchive'."); } return new ProtocolMetaData().addContext(runnable.getForge()); }
public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException { if (undeploying) { undeploying = false; cleanup(); } Deployment deployment = deploymentInstance.get(); final AddonId addonToDeploy = getAddonEntry(deployment); File destDir = repository.getAddonBaseDir(addonToDeploy); destDir.mkdirs(); System.out.println("Deploying [" + addonToDeploy + "] to repository [" + repository + "]"); if (archive instanceof ForgeArchive) { ShrinkWrapUtil.toFile(new File(destDir.getAbsolutePath() + "/" + archive.getName()), archive); ShrinkWrapUtil.unzip(destDir, archive); ConfigurationScanListener listener = new ConfigurationScanListener(); ListenerRegistration<ContainerLifecycleListener> registration = runnable.furnace .addContainerLifecycleListener(listener); repository.deploy(addonToDeploy, ((ForgeArchive) archive).getAddonDependencies(), new ArrayList<File>()); repository.enable(addonToDeploy); while (runnable.furnace.getStatus().isStarting() || !listener.isConfigurationScanned()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } registration.removeListener(); AddonRegistry registry = runnable.getForge().getAddonRegistry(); Addon addon = registry.getAddon(addonToDeploy); try { Future<Void> future = addon.getFuture(); future.get(); if (addon.getStatus().isFailed()) { DeploymentException e = new DeploymentException("AddonDependency " + addonToDeploy + " failed to deploy."); deployment.deployedWithError(e); throw new DeploymentException("AddonDependency " + addonToDeploy + " failed to deploy.", e); } } catch (Exception e) { deployment.deployedWithError(e); throw new DeploymentException("AddonDependency " + addonToDeploy + " failed to deploy.", e); } } else if (archive instanceof ForgeRemoteAddon) { ForgeRemoteAddon remoteAddon = (ForgeRemoteAddon) archive; AddonManager addonManager = new AddonManagerImpl(runnable.furnace, new MavenDependencyResolver(), false); addonManager.install(remoteAddon.getAddonId()).perform(); AddonRegistry registry = runnable.getForge().getAddonRegistry(); Addon addon = registry.getAddon(addonToDeploy); try { Future<Void> future = addon.getFuture(); future.get(); if (addon.getStatus().isFailed()) { ContainerException e = new ContainerException("AddonDependency " + addonToDeploy + " failed to deploy."); deployment.deployedWithError(e); throw e; } } catch (Exception e) { throw new DeploymentException("Failed to deploy " + addonToDeploy, e); } } else { throw new IllegalArgumentException( "Invalid Archive type. Ensure that your @Deployment method returns type 'ForgeArchive'."); } return new ProtocolMetaData().addContext(runnable.getForge()); }
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCat.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCat.java index ea67b4695..6698f9b74 100644 --- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCat.java +++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCat.java @@ -1,112 +1,112 @@ package org.tmatesoft.svn.core.internal.wc2.ng; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Map; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.admin.SVNTranslator; import org.tmatesoft.svn.core.internal.wc.admin.SVNTranslatorInputStream; import org.tmatesoft.svn.core.internal.wc17.SVNStatusEditor17; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.PristineContentsInfo; import org.tmatesoft.svn.core.internal.wc17.db.Structure; import org.tmatesoft.svn.core.internal.wc17.db.StructureFields.NodeInfo; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc2.SvnCat; import org.tmatesoft.svn.core.wc2.SvnStatus; import org.tmatesoft.svn.util.SVNLogType; public class SvnNgCat extends SvnNgOperationRunner<Long, SvnCat> { @Override protected Long run(SVNWCContext context) throws SVNException { SVNNodeKind kind = context.readKind(getFirstTarget(), false); if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget().getAbsolutePath()); SVNErrorManager.error(err, SVNLogType.WC); } if (kind != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_IS_DIRECTORY, "''{0}'' refers to a directory", getFirstTarget().getAbsolutePath()); SVNErrorManager.error(err, SVNLogType.WC); } SVNRevision revision = getOperation().getRevision(); SVNProperties properties; InputStream source = null; boolean localModifications = false; try { if (revision != SVNRevision.WORKING) { PristineContentsInfo info = context.getPristineContents(getFirstTarget(), true, false); source = info.stream; properties = context.getPristineProps(getFirstTarget()); } else { source = SVNFileUtil.openFileForReading(getFirstTarget()); properties = context.getDb().readProperties(getFirstTarget()); SvnStatus status = SVNStatusEditor17.internalStatus(context, getFirstTarget()); localModifications = status.getTextStatus() != SVNStatusType.STATUS_NORMAL; } String eolStyle = properties.getStringValue(SVNProperty.EOL_STYLE); String keywords = properties.getStringValue(SVNProperty.KEYWORDS); boolean special = properties.getStringValue(SVNProperty.SPECIAL) != null; long lastModified = 0; if (localModifications && !special) { lastModified = getFirstTarget().lastModified(); } else { Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.recordedTime); - lastModified = info.lng(NodeInfo.recordedSize) / 1000; + lastModified = info.lng(NodeInfo.recordedTime) / 1000; info.release(); } Map<?, ?> keywordsMap = null; if (keywords != null && getOperation().isExpandKeywords()) { Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.changedRev, NodeInfo.changedAuthor); SVNURL url = context.getNodeUrl(getFirstTarget()); String rev = Long.toString(info.lng(NodeInfo.changedRev)); String author = info.get(NodeInfo.changedAuthor); info.release(); if (localModifications) { rev = rev + "M"; author = "(local)"; } String date = SVNDate.formatDate(new Date(lastModified)); keywordsMap = SVNTranslator.computeKeywords(keywords, url.toString(), author, date, rev, getOperation().getOptions()); } if (keywordsMap != null || eolStyle != null) { source = new SVNTranslatorInputStream(source, SVNTranslator.getEOL(eolStyle, getOperation().getOptions()), false, keywordsMap, true); } try { SVNTranslator.copy(source, getOperation().getOutput()); } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e); SVNErrorManager.error(err, SVNLogType.WC); } } finally { SVNFileUtil.closeFile(source); } return null; } }
true
true
protected Long run(SVNWCContext context) throws SVNException { SVNNodeKind kind = context.readKind(getFirstTarget(), false); if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget().getAbsolutePath()); SVNErrorManager.error(err, SVNLogType.WC); } if (kind != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_IS_DIRECTORY, "''{0}'' refers to a directory", getFirstTarget().getAbsolutePath()); SVNErrorManager.error(err, SVNLogType.WC); } SVNRevision revision = getOperation().getRevision(); SVNProperties properties; InputStream source = null; boolean localModifications = false; try { if (revision != SVNRevision.WORKING) { PristineContentsInfo info = context.getPristineContents(getFirstTarget(), true, false); source = info.stream; properties = context.getPristineProps(getFirstTarget()); } else { source = SVNFileUtil.openFileForReading(getFirstTarget()); properties = context.getDb().readProperties(getFirstTarget()); SvnStatus status = SVNStatusEditor17.internalStatus(context, getFirstTarget()); localModifications = status.getTextStatus() != SVNStatusType.STATUS_NORMAL; } String eolStyle = properties.getStringValue(SVNProperty.EOL_STYLE); String keywords = properties.getStringValue(SVNProperty.KEYWORDS); boolean special = properties.getStringValue(SVNProperty.SPECIAL) != null; long lastModified = 0; if (localModifications && !special) { lastModified = getFirstTarget().lastModified(); } else { Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.recordedTime); lastModified = info.lng(NodeInfo.recordedSize) / 1000; info.release(); } Map<?, ?> keywordsMap = null; if (keywords != null && getOperation().isExpandKeywords()) { Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.changedRev, NodeInfo.changedAuthor); SVNURL url = context.getNodeUrl(getFirstTarget()); String rev = Long.toString(info.lng(NodeInfo.changedRev)); String author = info.get(NodeInfo.changedAuthor); info.release(); if (localModifications) { rev = rev + "M"; author = "(local)"; } String date = SVNDate.formatDate(new Date(lastModified)); keywordsMap = SVNTranslator.computeKeywords(keywords, url.toString(), author, date, rev, getOperation().getOptions()); } if (keywordsMap != null || eolStyle != null) { source = new SVNTranslatorInputStream(source, SVNTranslator.getEOL(eolStyle, getOperation().getOptions()), false, keywordsMap, true); } try { SVNTranslator.copy(source, getOperation().getOutput()); } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e); SVNErrorManager.error(err, SVNLogType.WC); } } finally { SVNFileUtil.closeFile(source); } return null; }
protected Long run(SVNWCContext context) throws SVNException { SVNNodeKind kind = context.readKind(getFirstTarget(), false); if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget().getAbsolutePath()); SVNErrorManager.error(err, SVNLogType.WC); } if (kind != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_IS_DIRECTORY, "''{0}'' refers to a directory", getFirstTarget().getAbsolutePath()); SVNErrorManager.error(err, SVNLogType.WC); } SVNRevision revision = getOperation().getRevision(); SVNProperties properties; InputStream source = null; boolean localModifications = false; try { if (revision != SVNRevision.WORKING) { PristineContentsInfo info = context.getPristineContents(getFirstTarget(), true, false); source = info.stream; properties = context.getPristineProps(getFirstTarget()); } else { source = SVNFileUtil.openFileForReading(getFirstTarget()); properties = context.getDb().readProperties(getFirstTarget()); SvnStatus status = SVNStatusEditor17.internalStatus(context, getFirstTarget()); localModifications = status.getTextStatus() != SVNStatusType.STATUS_NORMAL; } String eolStyle = properties.getStringValue(SVNProperty.EOL_STYLE); String keywords = properties.getStringValue(SVNProperty.KEYWORDS); boolean special = properties.getStringValue(SVNProperty.SPECIAL) != null; long lastModified = 0; if (localModifications && !special) { lastModified = getFirstTarget().lastModified(); } else { Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.recordedTime); lastModified = info.lng(NodeInfo.recordedTime) / 1000; info.release(); } Map<?, ?> keywordsMap = null; if (keywords != null && getOperation().isExpandKeywords()) { Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.changedRev, NodeInfo.changedAuthor); SVNURL url = context.getNodeUrl(getFirstTarget()); String rev = Long.toString(info.lng(NodeInfo.changedRev)); String author = info.get(NodeInfo.changedAuthor); info.release(); if (localModifications) { rev = rev + "M"; author = "(local)"; } String date = SVNDate.formatDate(new Date(lastModified)); keywordsMap = SVNTranslator.computeKeywords(keywords, url.toString(), author, date, rev, getOperation().getOptions()); } if (keywordsMap != null || eolStyle != null) { source = new SVNTranslatorInputStream(source, SVNTranslator.getEOL(eolStyle, getOperation().getOptions()), false, keywordsMap, true); } try { SVNTranslator.copy(source, getOperation().getOutput()); } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e); SVNErrorManager.error(err, SVNLogType.WC); } } finally { SVNFileUtil.closeFile(source); } return null; }
diff --git a/Meteorolog-a-AguasCalientes/src/java/org/meteorologaaguascalientes/view/History.java b/Meteorolog-a-AguasCalientes/src/java/org/meteorologaaguascalientes/view/History.java index 73c7506..d6a7a6d 100644 --- a/Meteorolog-a-AguasCalientes/src/java/org/meteorologaaguascalientes/view/History.java +++ b/Meteorolog-a-AguasCalientes/src/java/org/meteorologaaguascalientes/view/History.java @@ -1,132 +1,132 @@ package org.meteorologaaguascalientes.view; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Map.Entry; import java.util.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.meteorologaaguascalientes.dao.AbstractVariableDao; import org.meteorologaaguascalientes.dao.DaoList; @WebServlet(name = "History", urlPatterns = {"/history"}) public class History extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Properties prop = new Properties(); prop.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties")); response.setContentType("text/csv;charset=UTF-8"); PrintWriter out = response.getWriter(); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String variableName = request.getParameter("variable"); if (variableName != null) { for (Entry<String,AbstractVariableDao> entry : DaoList.getInstance().getVariablesDaoMap().entrySet()) { if (entry.getKey().equals(variableName)) { List<SortedMap<Date, Double>> dataList; SortedMap<Date, Double> data; /* * HistoryControl invocation HistoryControl - * historyControl = new HistoryControl(); + * HistoryControl historyControl = new HistoryControl(); * dataList = historyControl.getData(entry.getValue()); */ dataList = new ArrayList<SortedMap<Date, Double>>(); data = new TreeMap<Date, Double>(); Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_YEAR, 1); int i = 1; do { data.put(c.getTime(), Math.random()); c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 1); } while (i++ <= 365); dataList.add(data); data = new TreeMap<Date, Double>(); data.put(dataList.get(0).lastKey(), dataList.get(0).get(dataList.get(0).lastKey())); i = 1; do { data.put(c.getTime(), Math.random()); c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 1); } while (i++ <= 10); dataList.add(data); out.println(prop.getProperty("date") + "," + prop.getProperty("dao." + variableName) + "," + prop.getProperty("forecast")); data = dataList.get(0); for (Map.Entry<Date, Double> e : data.entrySet()) { out.println(formatter.format(e.getKey()) + "," + e.getValue() + ","); } data = dataList.get(1); for (Map.Entry<Date, Double> e : data.entrySet()) { out.println(formatter.format(e.getKey()) + ",," + e.getValue()); } return; } } } } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
true
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Properties prop = new Properties(); prop.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties")); response.setContentType("text/csv;charset=UTF-8"); PrintWriter out = response.getWriter(); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String variableName = request.getParameter("variable"); if (variableName != null) { for (Entry<String,AbstractVariableDao> entry : DaoList.getInstance().getVariablesDaoMap().entrySet()) { if (entry.getKey().equals(variableName)) { List<SortedMap<Date, Double>> dataList; SortedMap<Date, Double> data; /* * HistoryControl invocation HistoryControl * historyControl = new HistoryControl(); * dataList = historyControl.getData(entry.getValue()); */ dataList = new ArrayList<SortedMap<Date, Double>>(); data = new TreeMap<Date, Double>(); Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_YEAR, 1); int i = 1; do { data.put(c.getTime(), Math.random()); c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 1); } while (i++ <= 365); dataList.add(data); data = new TreeMap<Date, Double>(); data.put(dataList.get(0).lastKey(), dataList.get(0).get(dataList.get(0).lastKey())); i = 1; do { data.put(c.getTime(), Math.random()); c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 1); } while (i++ <= 10); dataList.add(data); out.println(prop.getProperty("date") + "," + prop.getProperty("dao." + variableName) + "," + prop.getProperty("forecast")); data = dataList.get(0); for (Map.Entry<Date, Double> e : data.entrySet()) { out.println(formatter.format(e.getKey()) + "," + e.getValue() + ","); } data = dataList.get(1); for (Map.Entry<Date, Double> e : data.entrySet()) { out.println(formatter.format(e.getKey()) + ",," + e.getValue()); } return; } } } } finally { out.close(); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Properties prop = new Properties(); prop.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties")); response.setContentType("text/csv;charset=UTF-8"); PrintWriter out = response.getWriter(); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String variableName = request.getParameter("variable"); if (variableName != null) { for (Entry<String,AbstractVariableDao> entry : DaoList.getInstance().getVariablesDaoMap().entrySet()) { if (entry.getKey().equals(variableName)) { List<SortedMap<Date, Double>> dataList; SortedMap<Date, Double> data; /* * HistoryControl invocation HistoryControl * HistoryControl historyControl = new HistoryControl(); * dataList = historyControl.getData(entry.getValue()); */ dataList = new ArrayList<SortedMap<Date, Double>>(); data = new TreeMap<Date, Double>(); Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_YEAR, 1); int i = 1; do { data.put(c.getTime(), Math.random()); c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 1); } while (i++ <= 365); dataList.add(data); data = new TreeMap<Date, Double>(); data.put(dataList.get(0).lastKey(), dataList.get(0).get(dataList.get(0).lastKey())); i = 1; do { data.put(c.getTime(), Math.random()); c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 1); } while (i++ <= 10); dataList.add(data); out.println(prop.getProperty("date") + "," + prop.getProperty("dao." + variableName) + "," + prop.getProperty("forecast")); data = dataList.get(0); for (Map.Entry<Date, Double> e : data.entrySet()) { out.println(formatter.format(e.getKey()) + "," + e.getValue() + ","); } data = dataList.get(1); for (Map.Entry<Date, Double> e : data.entrySet()) { out.println(formatter.format(e.getKey()) + ",," + e.getValue()); } return; } } } } finally { out.close(); } }
diff --git a/ted/ui/addshowdialog/AddShowDialog.java b/ted/ui/addshowdialog/AddShowDialog.java index 8bb0c4f..0244569 100644 --- a/ted/ui/addshowdialog/AddShowDialog.java +++ b/ted/ui/addshowdialog/AddShowDialog.java @@ -1,548 +1,548 @@ package ted.ui.addshowdialog; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.GregorianCalendar; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.w3c.dom.Element; import ted.BrowserLauncher; import ted.Lang; import ted.TedDailySerie; import ted.TedIO; import ted.TedLog; import ted.TedMainDialog; import ted.TedSerie; import ted.TedXMLParser; import ted.datastructures.DailyDate; import ted.datastructures.SeasonEpisode; import ted.datastructures.SimpleTedSerie; import ted.interfaces.EpisodeChooserListener; import ted.ui.TableRenderer; import ted.ui.editshowdialog.EditShowDialog; import ted.ui.editshowdialog.FeedPopupItem; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class AddShowDialog extends JDialog implements ActionListener, MouseListener, EpisodeChooserListener, KeyListener { /** * */ private static final long serialVersionUID = 1006862655927988046L; private JTable showsTable; private JButton cancelButton; private JButton okButton; private JScrollPane showsScrollPane; private ShowsTableModel showsTableModel; private TedSerie selectedSerie; private TedMainDialog tedMain; private JTextPane showInfoPane; private JTextField jSearchField; private JLabel showNameLabel; private JLabel selectShowLabel; private JLabel selectEpisodeLabel; private JButton jHelpButton; private JScrollPane showInfoScrollPane; private JLabel buyDVDLabel; private JButton buttonAddEmptyShow; private Vector<SimpleTedSerie> allShows; private EpisodeChooserPanel episodeChooserPanel = new EpisodeChooserPanel(this); public AddShowDialog() { this.initGUI(); } public AddShowDialog(TedMainDialog main) { this.setModal(true); this.tedMain = main; this.initGUI(); } private void initGUI() { try { this.episodeChooserPanel.setActivityStatus(false); FormLayout thisLayout = new FormLayout( - "max(p;5dlu), 68dlu:grow, max(p;68dlu), max(p;15dlu), 9dlu, 5dlu:grow, max(p;15dlu), 5dlu, 85dlu, max(p;5dlu)", + "max(p;5dlu), 68dlu:grow, max(p;68dlu), max(p;15dlu), 5dlu:grow, max(p;15dlu), 5dlu, 85dlu, max(p;5dlu)", "max(p;5dlu), fill:max(p;15dlu), 5dlu, 10dlu:grow, max(p;5dlu), max(p;15dlu), 5dlu, 28dlu, 10dlu:grow, 5dlu, max(p;15dlu), 5dlu, max(p;15dlu), max(p;5dlu)"); getContentPane().setLayout(thisLayout); showsTableModel = new ShowsTableModel(); showsTable = new JTable(); //getContentPane().add(showsTable, new CellConstraints("4, 3, 1, 1, default, default")); getShowsScrollPane().setViewportView(showsTable); getContentPane().add(getShowsScrollPane(), new CellConstraints("2, 4, 2, 6, fill, fill")); - getContentPane().add(episodeChooserPanel, new CellConstraints("6, 9, 4, 2, fill, fill")); - getContentPane().add(getOkButton(), new CellConstraints("9, 13, 1, 1, default, default")); - getContentPane().add(getCancelButton(), new CellConstraints("7, 13, 1, 1, default, default")); - getContentPane().add(getShowInfoScrollPane(), new CellConstraints("6, 4, 4, 1, fill, fill")); + getContentPane().add(episodeChooserPanel, new CellConstraints("5, 8, 4, 2, fill, fill")); + getContentPane().add(getOkButton(), new CellConstraints("8, 13, 1, 1, default, default")); + getContentPane().add(getCancelButton(), new CellConstraints("6, 13, 1, 1, default, default")); + getContentPane().add(getShowInfoScrollPane(), new CellConstraints("5, 4, 4, 1, fill, fill")); getContentPane().add(getJHelpButton(), new CellConstraints("2, 13, 1, 1, left, default")); getContentPane().add(getSelectShowLabel(), new CellConstraints("2, 2, 2, 1, left, fill")); - getContentPane().add(getSelectEpisodeLabel(), new CellConstraints("6, 6, 4, 1, left, bottom")); - getContentPane().add(getShowNameLabel(), new CellConstraints("6, 2, 4, 1, left, bottom")); + getContentPane().add(getSelectEpisodeLabel(), new CellConstraints("5, 6, 4, 1, left, bottom")); + getContentPane().add(getShowNameLabel(), new CellConstraints("5, 2, 4, 1, left, bottom")); getContentPane().add(getButtonAddEmptyShow(), new CellConstraints("2, 11, 2, 1, default, default")); - getContentPane().add(getBuyDVDLabel(), new CellConstraints("6, 11, 4, 1, left, default")); + getContentPane().add(getBuyDVDLabel(), new CellConstraints("5, 11, 4, 1, left, default")); getContentPane().add(getJSearchField(), new CellConstraints("3, 2, 1, 1, default, fill")); showsTable.setModel(showsTableModel); showsTableModel.setSeries(this.readShowNames()); showsTable.setAutoCreateColumnsFromModel(true); showsTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); showsTable.setEditingRow(0); showsTable.setFont(new java.awt.Font("Dialog",0,15)); showsTable.setRowHeight(showsTable.getRowHeight()+10); TableRenderer tr = new TableRenderer(); showsTable.setDefaultRenderer(Object.class, tr); // disable horizontal lines in table showsTable.setShowHorizontalLines(false); showsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); showsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { showsTableSelectionChanged(); }}); jSearchField.addKeyListener(this); // Get the screen size Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); this.setSize((int)(screenSize.width*0.75), (int)(screenSize.height*0.75)); //Calculate the frame location int x = (screenSize.width - this.getWidth()) / 2; int y = (screenSize.height - this.getHeight()) / 2; //Set the new frame location this.setLocation(x, y); this.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Read the shownames from the xml file * @return Vector with names */ private Vector readShowNames() { Vector<SimpleTedSerie> names = new Vector<SimpleTedSerie>(); TedXMLParser parser = new TedXMLParser(); Element shows = parser.readXMLFromFile(TedIO.XML_SHOWS_FILE); //$NON-NLS-1$ if(shows!=null) { names = parser.getNames(shows); allShows = names; } else TedLog.error(Lang.getString("TedEpisodeDialog.LogXmlNotFound")); //$NON-NLS-1$ return names; } private JScrollPane getShowsScrollPane() { if (showsScrollPane == null) { showsScrollPane = new JScrollPane(); } return showsScrollPane; } /** * Called whenever the selection of a show is changed in the dialog */ private void showsTableSelectionChanged() { // disable ok button this.okButton.setEnabled(false); // get the selected show int selectedRow = showsTable.getSelectedRow(); if (selectedRow >= 0) { // get the simple info of the show SimpleTedSerie selectedShow = this.showsTableModel.getSerieAt(selectedRow); this.showNameLabel.setText(selectedShow.getName()); // get the details of the show TedXMLParser parser = new TedXMLParser(); Element series = parser.readXMLFromFile(TedIO.XML_SHOWS_FILE); //$NON-NLS-1$ TedSerie selectedSerie = parser.getSerie(series, selectedShow.getName()); buyDVDLabel.setText("<html><u>"+ Lang.getString("TedAddShowDialog.LabelSupportTed1")+ " " + selectedSerie.getName() +" " + Lang.getString("TedAddShowDialog.LabelSupportTed2") +"</u></html>"); // create a new infoPane to (correctly) show the information showInfoPane = null; showInfoScrollPane.setViewportView(this.getShowInfoPane()); // add auto-generated search based feeds to the show Vector<FeedPopupItem> items = new Vector<FeedPopupItem>(); items = parser.getAutoFeedLocations(series); selectedSerie.generateFeedLocations(items); // retrieve the show info and the episodes from the web ShowInfoThread sit = new ShowInfoThread(this.getShowInfoPane(), selectedSerie); sit.setPriority( Thread.NORM_PRIORITY + 1 ); EpisodeParserThread ept = new EpisodeParserThread(this.episodeChooserPanel, selectedSerie); ept.setPriority( Thread.NORM_PRIORITY - 1 ); sit.start(); ept.start(); // set the selected show this.setSelectedSerie(selectedSerie); } } private JButton getOkButton() { if (okButton == null) { okButton = new JButton(); okButton.setText(Lang.getString("TedGeneral.ButtonAdd")); okButton.setActionCommand("OK"); okButton.addActionListener(this); this.getRootPane().setDefaultButton(okButton); this.okButton.setEnabled(false); } return okButton; } private JButton getCancelButton() { if (cancelButton == null) { cancelButton = new JButton(); cancelButton.setText(Lang.getString("TedGeneral.ButtonCancel")); cancelButton.setActionCommand("Cancel"); cancelButton.addActionListener(this); } return cancelButton; } public void actionPerformed(ActionEvent arg0) { String command = arg0.getActionCommand(); if (command.equals("OK")) { this.addShow(); } else if (command.equals("Cancel")) { this.close(); } else if (command.equals("Help")) { try { // open the help page of ted BrowserLauncher.openURL("http://www.ted.nu/wiki/index.php/Add_show"); //$NON-NLS-1$ } catch (Exception err) { } } else if (command.equals("addempty")) { // create an edit show dialog with an empty show and hide add show dialog TedSerie temp = new TedSerie(); this.close(); new EditShowDialog(tedMain, temp, true); } else if (command.equals("search")) { this.searchShows(jSearchField.getText()); } } /** * Add the selected show with the selected season/episode to teds show list */ private void addShow() { // add show if (selectedSerie != null) { // set season and episode settings if (selectedSerie.isDaily()) { DailyDate dd = (DailyDate)this.episodeChooserPanel.getSelectedStructure(); GregorianCalendar d = new GregorianCalendar(dd.getYear(), dd.getMonth(), dd.getDay()); ((TedDailySerie)selectedSerie).setLatestDownloadDate(d.getTimeInMillis()); } else { SeasonEpisode se = (SeasonEpisode)this.episodeChooserPanel.getSelectedStructure(); selectedSerie.setCurrentEpisode(se.getEpisode()); selectedSerie.setCurrentSeason(se.getSeason()); } // add the serie tedMain.addSerie(selectedSerie); this.close(); } } private void close() { this.showsTableModel.removeSeries(); // close the dialog this.setVisible(false); this.dispose(); // call garbage collector to cleanup dirt Runtime.getRuntime().gc(); } public void setSelectedSerie(TedSerie selectedSerie2) { this.selectedSerie = selectedSerie2; } private JScrollPane getShowInfoScrollPane() { if (showInfoScrollPane == null) { showInfoScrollPane = new JScrollPane(); showInfoScrollPane.setViewportView(getShowInfoPane()); } return showInfoScrollPane; } private JTextPane getShowInfoPane() { if (showInfoPane == null) { showInfoPane = new JTextPane(); showInfoPane.setContentType( "text/html" ); showInfoPane.setEditable( false ); //showInfoPane.setPreferredSize(new java.awt.Dimension(325, 128)); //showInfoPane.setText("jTextPane1"); // Set up the JEditorPane to handle clicks on hyperlinks showInfoPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { // Handle clicks; ignore mouseovers and other link-related events if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { // Get the HREF of the link and display it. try { BrowserLauncher.openURL(e.getDescription()); } catch (IOException e1) { // TODO Auto-generated catch block } } } }); } return showInfoPane; } private JButton getJHelpButton() { if (jHelpButton == null) { jHelpButton = new JButton(); jHelpButton.setActionCommand("Help"); jHelpButton.setIcon(new ImageIcon(getClass().getClassLoader() .getResource("icons/help.png"))); jHelpButton.setBounds(11, 380, 28, 28); jHelpButton.addActionListener(this); jHelpButton.setToolTipText(Lang.getString("TedGeneral.ButtonHelpToolTip")); } return jHelpButton; } private JLabel getSelectShowLabel() { if (selectShowLabel == null) { selectShowLabel = new JLabel(); selectShowLabel.setText(Lang.getString("TedAddShowDialog.LabelSelectShow")); } return selectShowLabel; } private JLabel getSelectEpisodeLabel() { if (selectEpisodeLabel == null) { selectEpisodeLabel = new JLabel(); selectEpisodeLabel .setText(Lang.getString("TedAddShowDialog.LabelSelectEpisode")); } return selectEpisodeLabel; } private JLabel getShowNameLabel() { if (showNameLabel == null) { showNameLabel = new JLabel(); showNameLabel.setFont(new java.awt.Font("Tahoma",1,14)); } return showNameLabel; } private JButton getButtonAddEmptyShow() { if (buttonAddEmptyShow == null) { buttonAddEmptyShow = new JButton(); buttonAddEmptyShow.setText(Lang.getString("TedAddShowDialog.ButtonAddCustomShow")); buttonAddEmptyShow.addActionListener(this); buttonAddEmptyShow.setActionCommand("addempty"); } return buttonAddEmptyShow; } private JLabel getBuyDVDLabel() { if (buyDVDLabel == null) { buyDVDLabel = new JLabel(); buyDVDLabel.setText(""); buyDVDLabel.setForeground(Color.BLUE); buyDVDLabel.setFont(new java.awt.Font("Dialog",1,12)); buyDVDLabel.addMouseListener(this); buyDVDLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } return buyDVDLabel; } public void mouseClicked(MouseEvent arg0) { // clicked on label to buy dvd this.tedMain.openBuyLink(this.selectedSerie.getName()); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } public void episodeSelectionChanged() { // called when episode selection is changed. // check if episode and show selected if (selectedSerie != null && this.episodeChooserPanel.getSelectedStructure() != null) { // enable add button this.okButton.setEnabled(true); } else { this.okButton.setEnabled(false); } } /* (non-Javadoc) * @see ted.interfaces.EpisodeChooserListener#doubleClickOnEpisodeList() */ public void doubleClickOnEpisodeList() { // add show this.addShow(); } private JTextField getJSearchField() { if(jSearchField == null) { jSearchField = new SearchTextField(); } return jSearchField; } private void searchShows(String searchString) { // Only search if we've entered a search term if (!searchString.equals("<SEARCH>")) { Vector<SimpleTedSerie> tempShows = new Vector<SimpleTedSerie>(); // If we've entered a search term filter the list, otherwise // display all shows if (!searchString.equals("")) { // Do the filtering for (int show = 0; show < allShows.size(); ++show) { SimpleTedSerie serie = allShows.get(show); if (serie.getName().toLowerCase().contains(searchString.toLowerCase())) { tempShows.add(serie); } } // Update the table showsTableModel.setSeries(tempShows); } else { showsTableModel.setSeries(allShows); } // Let the table know that there's new information showsTableModel.fireTableDataChanged(); } } public void keyPressed (KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { searchShows(jSearchField.getText()); } public void keyTyped (KeyEvent arg0) { } }
false
true
private void initGUI() { try { this.episodeChooserPanel.setActivityStatus(false); FormLayout thisLayout = new FormLayout( "max(p;5dlu), 68dlu:grow, max(p;68dlu), max(p;15dlu), 9dlu, 5dlu:grow, max(p;15dlu), 5dlu, 85dlu, max(p;5dlu)", "max(p;5dlu), fill:max(p;15dlu), 5dlu, 10dlu:grow, max(p;5dlu), max(p;15dlu), 5dlu, 28dlu, 10dlu:grow, 5dlu, max(p;15dlu), 5dlu, max(p;15dlu), max(p;5dlu)"); getContentPane().setLayout(thisLayout); showsTableModel = new ShowsTableModel(); showsTable = new JTable(); //getContentPane().add(showsTable, new CellConstraints("4, 3, 1, 1, default, default")); getShowsScrollPane().setViewportView(showsTable); getContentPane().add(getShowsScrollPane(), new CellConstraints("2, 4, 2, 6, fill, fill")); getContentPane().add(episodeChooserPanel, new CellConstraints("6, 9, 4, 2, fill, fill")); getContentPane().add(getOkButton(), new CellConstraints("9, 13, 1, 1, default, default")); getContentPane().add(getCancelButton(), new CellConstraints("7, 13, 1, 1, default, default")); getContentPane().add(getShowInfoScrollPane(), new CellConstraints("6, 4, 4, 1, fill, fill")); getContentPane().add(getJHelpButton(), new CellConstraints("2, 13, 1, 1, left, default")); getContentPane().add(getSelectShowLabel(), new CellConstraints("2, 2, 2, 1, left, fill")); getContentPane().add(getSelectEpisodeLabel(), new CellConstraints("6, 6, 4, 1, left, bottom")); getContentPane().add(getShowNameLabel(), new CellConstraints("6, 2, 4, 1, left, bottom")); getContentPane().add(getButtonAddEmptyShow(), new CellConstraints("2, 11, 2, 1, default, default")); getContentPane().add(getBuyDVDLabel(), new CellConstraints("6, 11, 4, 1, left, default")); getContentPane().add(getJSearchField(), new CellConstraints("3, 2, 1, 1, default, fill")); showsTable.setModel(showsTableModel); showsTableModel.setSeries(this.readShowNames()); showsTable.setAutoCreateColumnsFromModel(true); showsTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); showsTable.setEditingRow(0); showsTable.setFont(new java.awt.Font("Dialog",0,15)); showsTable.setRowHeight(showsTable.getRowHeight()+10); TableRenderer tr = new TableRenderer(); showsTable.setDefaultRenderer(Object.class, tr); // disable horizontal lines in table showsTable.setShowHorizontalLines(false); showsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); showsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { showsTableSelectionChanged(); }}); jSearchField.addKeyListener(this); // Get the screen size Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); this.setSize((int)(screenSize.width*0.75), (int)(screenSize.height*0.75)); //Calculate the frame location int x = (screenSize.width - this.getWidth()) / 2; int y = (screenSize.height - this.getHeight()) / 2; //Set the new frame location this.setLocation(x, y); this.setVisible(true); } catch (Exception e) { e.printStackTrace(); } }
private void initGUI() { try { this.episodeChooserPanel.setActivityStatus(false); FormLayout thisLayout = new FormLayout( "max(p;5dlu), 68dlu:grow, max(p;68dlu), max(p;15dlu), 5dlu:grow, max(p;15dlu), 5dlu, 85dlu, max(p;5dlu)", "max(p;5dlu), fill:max(p;15dlu), 5dlu, 10dlu:grow, max(p;5dlu), max(p;15dlu), 5dlu, 28dlu, 10dlu:grow, 5dlu, max(p;15dlu), 5dlu, max(p;15dlu), max(p;5dlu)"); getContentPane().setLayout(thisLayout); showsTableModel = new ShowsTableModel(); showsTable = new JTable(); //getContentPane().add(showsTable, new CellConstraints("4, 3, 1, 1, default, default")); getShowsScrollPane().setViewportView(showsTable); getContentPane().add(getShowsScrollPane(), new CellConstraints("2, 4, 2, 6, fill, fill")); getContentPane().add(episodeChooserPanel, new CellConstraints("5, 8, 4, 2, fill, fill")); getContentPane().add(getOkButton(), new CellConstraints("8, 13, 1, 1, default, default")); getContentPane().add(getCancelButton(), new CellConstraints("6, 13, 1, 1, default, default")); getContentPane().add(getShowInfoScrollPane(), new CellConstraints("5, 4, 4, 1, fill, fill")); getContentPane().add(getJHelpButton(), new CellConstraints("2, 13, 1, 1, left, default")); getContentPane().add(getSelectShowLabel(), new CellConstraints("2, 2, 2, 1, left, fill")); getContentPane().add(getSelectEpisodeLabel(), new CellConstraints("5, 6, 4, 1, left, bottom")); getContentPane().add(getShowNameLabel(), new CellConstraints("5, 2, 4, 1, left, bottom")); getContentPane().add(getButtonAddEmptyShow(), new CellConstraints("2, 11, 2, 1, default, default")); getContentPane().add(getBuyDVDLabel(), new CellConstraints("5, 11, 4, 1, left, default")); getContentPane().add(getJSearchField(), new CellConstraints("3, 2, 1, 1, default, fill")); showsTable.setModel(showsTableModel); showsTableModel.setSeries(this.readShowNames()); showsTable.setAutoCreateColumnsFromModel(true); showsTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); showsTable.setEditingRow(0); showsTable.setFont(new java.awt.Font("Dialog",0,15)); showsTable.setRowHeight(showsTable.getRowHeight()+10); TableRenderer tr = new TableRenderer(); showsTable.setDefaultRenderer(Object.class, tr); // disable horizontal lines in table showsTable.setShowHorizontalLines(false); showsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); showsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { showsTableSelectionChanged(); }}); jSearchField.addKeyListener(this); // Get the screen size Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); this.setSize((int)(screenSize.width*0.75), (int)(screenSize.height*0.75)); //Calculate the frame location int x = (screenSize.width - this.getWidth()) / 2; int y = (screenSize.height - this.getHeight()) / 2; //Set the new frame location this.setLocation(x, y); this.setVisible(true); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/connectors/sharepoint/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/sharepoint/SPSProxyHelper.java b/connectors/sharepoint/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/sharepoint/SPSProxyHelper.java index 7d0507c0c..500eddccb 100644 --- a/connectors/sharepoint/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/sharepoint/SPSProxyHelper.java +++ b/connectors/sharepoint/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/sharepoint/SPSProxyHelper.java @@ -1,604 +1,609 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.authorities.authorities.sharepoint; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.regex.*; import java.io.InputStream; import javax.xml.soap.*; import org.apache.manifoldcf.core.common.XMLDoc; import org.apache.manifoldcf.core.interfaces.ManifoldCFException; import org.apache.manifoldcf.agents.interfaces.ServiceInterruption; import org.apache.manifoldcf.authorities.system.Logging; import com.microsoft.schemas.sharepoint.dsp.*; import com.microsoft.schemas.sharepoint.soap.*; import org.apache.http.client.HttpClient; import org.apache.axis.EngineConfiguration; import javax.xml.namespace.QName; import org.apache.axis.message.MessageElement; import org.apache.axis.AxisEngine; import org.apache.axis.ConfigurationException; import org.apache.axis.Handler; import org.apache.axis.WSDDEngineConfiguration; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.deployment.wsdd.WSDDDeployment; import org.apache.axis.deployment.wsdd.WSDDDocument; import org.apache.axis.deployment.wsdd.WSDDGlobalConfiguration; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.utils.Admin; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Document; /** * * @author Michael Cummings * */ public class SPSProxyHelper { public static final String HTTPCLIENT_PROPERTY = org.apache.manifoldcf.sharepoint.CommonsHTTPSender.HTTPCLIENT_PROPERTY; private String serverUrl; private String serverLocation; private String decodedServerLocation; private String baseUrl; private String userName; private String password; private EngineConfiguration configuration; private HttpClient httpClient; /** * * @param serverUrl * @param userName * @param password */ public SPSProxyHelper( String serverUrl, String serverLocation, String decodedServerLocation, String userName, String password, Class resourceClass, String configFileName, HttpClient httpClient ) { this.serverUrl = serverUrl; this.serverLocation = serverLocation; this.decodedServerLocation = decodedServerLocation; if (serverLocation.equals("/")) baseUrl = serverUrl; else baseUrl = serverUrl + serverLocation; this.userName = userName; this.password = password; this.configuration = new ResourceProvider(resourceClass,configFileName); this.httpClient = httpClient; } /** * Get the access tokens for a user principal. */ public List<String> getAccessTokens( String site, String userLoginName ) throws ManifoldCFException { try { if ( site.compareTo("/") == 0 ) site = ""; // root case UserGroupWS userService = new UserGroupWS( baseUrl + site, userName, password, configuration, httpClient ); com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap userCall = userService.getUserGroupSoapHandler( ); com.microsoft.schemas.sharepoint.soap.directory.GetUserInfoResponseGetUserInfoResult userResp = userCall.getUserInfo( userLoginName ); org.apache.axis.message.MessageElement[] usersList = userResp.get_any(); /* Response looks like this: <GetUserInfo xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/"> <User ID="4" Sid="S-1-5-21-2127521184-1604012920-1887927527-34577" Name="User1_Display_Name" LoginName="DOMAIN\User1_Alias" Email="User1_E-mail" Notes="Notes" IsSiteAdmin="False" IsDomainGroup="False" /> </GetUserInfo> */ if (usersList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetUserInfo' node, saw "+Integer.toString(usersList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getUserInfo xml response: '" + usersList[0].toString() + "'"); } MessageElement users = usersList[0]; if (!users.getElementName().getLocalName().equals("GetUserInfo")) throw new ManifoldCFException("Bad response - outer node should have been 'GetUserInfo' node"); String userID = null; Iterator userIter = users.getChildElements(); while (userIter.hasNext()) { MessageElement child = (MessageElement)userIter.next(); if (child.getElementName().getLocalName().equals("User")) { userID = child.getAttribute("ID"); } } // If userID is null, no such user if (userID == null) return null; List<String> accessTokens = new ArrayList<String>(); accessTokens.add("U"+userID); com.microsoft.schemas.sharepoint.soap.directory.GetGroupCollectionFromUserResponseGetGroupCollectionFromUserResult userGroupResp = userCall.getGroupCollectionFromUser( userLoginName ); org.apache.axis.message.MessageElement[] groupsList = userGroupResp.get_any(); /* Response looks like this: <GetGroupCollectionFromUser xmlns= "http://schemas.microsoft.com/sharepoint/soap/directory/"> <Groups> <Group ID="3" Name="Group1" Description="Description" OwnerID="1" OwnerIsUser="False" /> <Group ID="15" Name="Group2" Description="Description" OwnerID="12" OwnerIsUser="True" /> <Group ID="16" Name="Group3" Description="Description" OwnerID="7" OwnerIsUser="False" /> </Groups> </GetGroupCollectionFromUser> */ if (groupsList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetGroupCollectionFromUser' node, saw "+Integer.toString(groupsList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getGroupCollectionFromUser xml response: '" + groupsList[0].toString() + "'"); } MessageElement groups = groupsList[0]; - if (!users.getElementName().getLocalName().equals("GetGroupCollectionFromUser")) + if (!groups.getElementName().getLocalName().equals("GetGroupCollectionFromUser")) throw new ManifoldCFException("Bad response - outer node should have been 'GetGroupCollectionFromUser' node"); Iterator groupsIter = groups.getChildElements(); while (groupsIter.hasNext()) { MessageElement child = (MessageElement)groupsIter.next(); if (child.getElementName().getLocalName().equals("Groups")) { Iterator groupIter = child.getChildElements(); while (groupIter.hasNext()) { MessageElement group = (MessageElement)groupIter.next(); if (group.getElementName().getLocalName().equals("Group")) { String groupID = group.getAttribute("ID"); String groupName = group.getAttribute("Name"); // Add to the access token list accessTokens.add("G"+groupID); } } } } com.microsoft.schemas.sharepoint.soap.directory.GetRoleCollectionFromUserResponseGetRoleCollectionFromUserResult userRoleResp = userCall.getRoleCollectionFromUser( userLoginName ); org.apache.axis.message.MessageElement[] rolesList = userRoleResp.get_any(); if (rolesList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetRoleCollectionFromUser' node, saw "+Integer.toString(rolesList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getRoleCollectionFromUser xml response: '" + rolesList[0].toString() + "'"); } // Not specified in doc and must be determined experimentally // MHL return accessTokens; } catch (java.net.MalformedURLException e) { throw new ManifoldCFException("Bad SharePoint url: "+e.getMessage(),e); } catch (javax.xml.rpc.ServiceException e) { if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got a service exception getting the acls for site "+site,e); throw new ManifoldCFException("Service exception: "+e.getMessage(), e); } catch (org.apache.axis.AxisFault e) { if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/","HTTP"))) { org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName("http://xml.apache.org/axis/","HttpErrorCode")); if (elem != null) { elem.normalize(); String httpErrorCode = elem.getFirstChild().getNodeValue().trim(); if (httpErrorCode.equals("404")) { // Page did not exist if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: The page at "+baseUrl+site+" did not exist"); throw new ManifoldCFException("The page at "+baseUrl+site+" did not exist"); } else if (httpErrorCode.equals("401")) { // User did not have permissions for this library to get the acls if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: The user did not have access to the usergroups service for "+baseUrl+site); throw new ManifoldCFException("The user did not have access to the usergroups service at "+baseUrl+site); } else if (httpErrorCode.equals("403")) throw new ManifoldCFException("Http error "+httpErrorCode+" while reading from "+baseUrl+site+" - check IIS and SharePoint security settings! "+e.getMessage(),e); else throw new ManifoldCFException("Unexpected http error code "+httpErrorCode+" accessing SharePoint at "+baseUrl+site+": "+e.getMessage(),e); } throw new ManifoldCFException("Unknown http error occurred: "+e.getMessage(),e); } else if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/","Server"))) { org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/","errorcode")); if (elem != null) { elem.normalize(); String sharepointErrorCode = elem.getFirstChild().getNodeValue().trim(); + if (sharepointErrorCode.equals("0x80131600")) + { + // No such user + return null; + } if (Logging.authorityConnectors.isDebugEnabled()) { org.w3c.dom.Element elem2 = e.lookupFaultDetail(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/","errorstring")); String errorString = ""; if (elem != null) errorString = elem2.getFirstChild().getNodeValue().trim(); Logging.authorityConnectors.debug("SharePoint: Getting usergroups in site "+site+" failed with unexpected SharePoint error code "+sharepointErrorCode+": "+errorString,e); } throw new ManifoldCFException("SharePoint server error code: "+sharepointErrorCode); } if (Logging.authorityConnectors.isDebugEnabled()) - Logging.authorityConnectors.debug("SharePoint: Unknown SharePoint server error getting the acls for site "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); + Logging.authorityConnectors.debug("SharePoint: Unknown SharePoint server error getting usergroups for site "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); throw new ManifoldCFException("Unknown SharePoint server error: "+e.getMessage()); } if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/","Server.userException"))) { String exceptionName = e.getFaultString(); if (exceptionName.equals("java.lang.InterruptedException")) throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED); } if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got an unknown remote exception getting usergroups for "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); throw new ManifoldCFException("Remote procedure exception: "+e.getMessage(), e); } catch (java.rmi.RemoteException e) { // We expect the axis exception to be thrown, not this generic one! // So, fail hard if we see it. if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got an unexpected remote exception usergroups for site "+site,e); throw new ManifoldCFException("Unexpected remote procedure exception: "+e.getMessage(), e); } } /** * * @return true if connection OK * @throws java.net.MalformedURLException * @throws javax.xml.rpc.ServiceException * @throws java.rmi.RemoteException */ public boolean checkConnection( String site ) throws ManifoldCFException { try { if (site.equals("/")) site = ""; UserGroupWS userService = new UserGroupWS( baseUrl + site, userName, password, configuration, httpClient ); com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap userCall = userService.getUserGroupSoapHandler( ); // Get the info for the admin user com.microsoft.schemas.sharepoint.soap.directory.GetUserInfoResponseGetUserInfoResult userResp = userCall.getUserInfo( userName ); org.apache.axis.message.MessageElement[] userList = userResp.get_any(); // MHL return true; } catch (java.net.MalformedURLException e) { throw new ManifoldCFException("Bad SharePoint url: "+e.getMessage(),e); } catch (javax.xml.rpc.ServiceException e) { if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got a service exception checking connection",e); throw new ManifoldCFException("Service exception: "+e.getMessage(), e); } catch (org.apache.axis.AxisFault e) { if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/","HTTP"))) { org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName("http://xml.apache.org/axis/","HttpErrorCode")); if (elem != null) { elem.normalize(); String httpErrorCode = elem.getFirstChild().getNodeValue().trim(); if (httpErrorCode.equals("404")) { // Page did not exist throw new ManifoldCFException("The site at "+baseUrl+site+" did not exist"); } else if (httpErrorCode.equals("401")) throw new ManifoldCFException("User did not authenticate properly, or has insufficient permissions to access "+baseUrl+site+": "+e.getMessage(),e); else if (httpErrorCode.equals("403")) throw new ManifoldCFException("Http error "+httpErrorCode+" while reading from "+baseUrl+site+" - check IIS and SharePoint security settings! "+e.getMessage(),e); else throw new ManifoldCFException("Unexpected http error code "+httpErrorCode+" accessing SharePoint at "+baseUrl+site+": "+e.getMessage(),e); } throw new ManifoldCFException("Unknown http error occurred: "+e.getMessage(),e); } else if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/","Server"))) { org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/","errorcode")); if (elem != null) { elem.normalize(); String sharepointErrorCode = elem.getFirstChild().getNodeValue().trim(); org.w3c.dom.Element elem2 = e.lookupFaultDetail(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/","errorstring")); String errorString = ""; if (elem != null) errorString = elem2.getFirstChild().getNodeValue().trim(); throw new ManifoldCFException("Accessing site "+site+" failed with unexpected SharePoint error code "+sharepointErrorCode+": "+errorString,e); } throw new ManifoldCFException("Unknown SharePoint server error accessing site "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); } if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/","Server.userException"))) { String exceptionName = e.getFaultString(); if (exceptionName.equals("java.lang.InterruptedException")) throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED); } throw new ManifoldCFException("Got an unknown remote exception accessing site "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); } catch (java.rmi.RemoteException e) { // We expect the axis exception to be thrown, not this generic one! // So, fail hard if we see it. throw new ManifoldCFException("Got an unexpected remote exception accessing site "+site+": "+e.getMessage(),e); } } /** * SharePoint UserGroup Service Wrapper Class */ protected static class UserGroupWS extends com.microsoft.schemas.sharepoint.soap.directory.UserGroupLocator { /** * */ private static final long serialVersionUID = -2052484076803624502L; private java.net.URL endPoint; private String userName; private String password; private HttpClient httpClient; public UserGroupWS ( String siteUrl, String userName, String password, EngineConfiguration configuration, HttpClient httpClient ) throws java.net.MalformedURLException { super(configuration); endPoint = new java.net.URL(siteUrl + "/_vti_bin/usergroup.asmx"); this.userName = userName; this.password = password; this.httpClient = httpClient; } public com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap getUserGroupSoapHandler( ) throws javax.xml.rpc.ServiceException, org.apache.axis.AxisFault { com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoapStub _stub = new com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoapStub(endPoint, this); _stub.setPortName(getUserGroupSoapWSDDServiceName()); _stub.setUsername( userName ); _stub.setPassword( password ); _stub._setProperty( HTTPCLIENT_PROPERTY, httpClient ); return _stub; } } /** Implementation of EngineConfiguration that we'll use to get the wsdd file from a * local resource. */ protected static class ResourceProvider implements WSDDEngineConfiguration { private WSDDDeployment deployment = null; private Class resourceClass; private String resourceName; /** * Constructor setting the resource name. */ public ResourceProvider(Class resourceClass, String resourceName) { this.resourceClass = resourceClass; this.resourceName = resourceName; } public WSDDDeployment getDeployment() { return deployment; } public void configureEngine(AxisEngine engine) throws ConfigurationException { try { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); if (resourceStream == null) throw new ConfigurationException("Resource not found: '"+resourceName+"'"); try { WSDDDocument doc = new WSDDDocument(XMLUtils.newDocument(resourceStream)); deployment = doc.getDeployment(); deployment.configureEngine(engine); engine.refreshGlobalOptions(); } finally { resourceStream.close(); } } catch (ConfigurationException e) { throw e; } catch (Exception e) { throw new ConfigurationException(e); } } public void writeEngineConfig(AxisEngine engine) throws ConfigurationException { // Do nothing } /** * retrieve an instance of the named handler * @param qname XXX * @return XXX * @throws ConfigurationException XXX */ public Handler getHandler(QName qname) throws ConfigurationException { return deployment.getHandler(qname); } /** * retrieve an instance of the named service * @param qname XXX * @return XXX * @throws ConfigurationException XXX */ public SOAPService getService(QName qname) throws ConfigurationException { SOAPService service = deployment.getService(qname); if (service == null) { throw new ConfigurationException(Messages.getMessage("noService10", qname.toString())); } return service; } /** * Get a service which has been mapped to a particular namespace * * @param namespace a namespace URI * @return an instance of the appropriate Service, or null */ public SOAPService getServiceByNamespaceURI(String namespace) throws ConfigurationException { return deployment.getServiceByNamespaceURI(namespace); } /** * retrieve an instance of the named transport * @param qname XXX * @return XXX * @throws ConfigurationException XXX */ public Handler getTransport(QName qname) throws ConfigurationException { return deployment.getTransport(qname); } public TypeMappingRegistry getTypeMappingRegistry() throws ConfigurationException { return deployment.getTypeMappingRegistry(); } /** * Returns a global request handler. */ public Handler getGlobalRequest() throws ConfigurationException { return deployment.getGlobalRequest(); } /** * Returns a global response handler. */ public Handler getGlobalResponse() throws ConfigurationException { return deployment.getGlobalResponse(); } /** * Returns the global configuration options. */ public Hashtable getGlobalOptions() throws ConfigurationException { WSDDGlobalConfiguration globalConfig = deployment.getGlobalConfiguration(); if (globalConfig != null) return globalConfig.getParametersTable(); return null; } /** * Get an enumeration of the services deployed to this engine */ public Iterator getDeployedServices() throws ConfigurationException { return deployment.getDeployedServices(); } /** * Get a list of roles that this engine plays globally. Services * within the engine configuration may also add additional roles. * * @return a <code>List</code> of the roles for this engine */ public List getRoles() { return deployment.getRoles(); } } }
false
true
public List<String> getAccessTokens( String site, String userLoginName ) throws ManifoldCFException { try { if ( site.compareTo("/") == 0 ) site = ""; // root case UserGroupWS userService = new UserGroupWS( baseUrl + site, userName, password, configuration, httpClient ); com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap userCall = userService.getUserGroupSoapHandler( ); com.microsoft.schemas.sharepoint.soap.directory.GetUserInfoResponseGetUserInfoResult userResp = userCall.getUserInfo( userLoginName ); org.apache.axis.message.MessageElement[] usersList = userResp.get_any(); /* Response looks like this: <GetUserInfo xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/"> <User ID="4" Sid="S-1-5-21-2127521184-1604012920-1887927527-34577" Name="User1_Display_Name" LoginName="DOMAIN\User1_Alias" Email="User1_E-mail" Notes="Notes" IsSiteAdmin="False" IsDomainGroup="False" /> </GetUserInfo> */ if (usersList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetUserInfo' node, saw "+Integer.toString(usersList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getUserInfo xml response: '" + usersList[0].toString() + "'"); } MessageElement users = usersList[0]; if (!users.getElementName().getLocalName().equals("GetUserInfo")) throw new ManifoldCFException("Bad response - outer node should have been 'GetUserInfo' node"); String userID = null; Iterator userIter = users.getChildElements(); while (userIter.hasNext()) { MessageElement child = (MessageElement)userIter.next(); if (child.getElementName().getLocalName().equals("User")) { userID = child.getAttribute("ID"); } } // If userID is null, no such user if (userID == null) return null; List<String> accessTokens = new ArrayList<String>(); accessTokens.add("U"+userID); com.microsoft.schemas.sharepoint.soap.directory.GetGroupCollectionFromUserResponseGetGroupCollectionFromUserResult userGroupResp = userCall.getGroupCollectionFromUser( userLoginName ); org.apache.axis.message.MessageElement[] groupsList = userGroupResp.get_any(); /* Response looks like this: <GetGroupCollectionFromUser xmlns= "http://schemas.microsoft.com/sharepoint/soap/directory/"> <Groups> <Group ID="3" Name="Group1" Description="Description" OwnerID="1" OwnerIsUser="False" /> <Group ID="15" Name="Group2" Description="Description" OwnerID="12" OwnerIsUser="True" /> <Group ID="16" Name="Group3" Description="Description" OwnerID="7" OwnerIsUser="False" /> </Groups> </GetGroupCollectionFromUser> */ if (groupsList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetGroupCollectionFromUser' node, saw "+Integer.toString(groupsList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getGroupCollectionFromUser xml response: '" + groupsList[0].toString() + "'"); } MessageElement groups = groupsList[0]; if (!users.getElementName().getLocalName().equals("GetGroupCollectionFromUser")) throw new ManifoldCFException("Bad response - outer node should have been 'GetGroupCollectionFromUser' node"); Iterator groupsIter = groups.getChildElements(); while (groupsIter.hasNext()) { MessageElement child = (MessageElement)groupsIter.next(); if (child.getElementName().getLocalName().equals("Groups")) { Iterator groupIter = child.getChildElements(); while (groupIter.hasNext()) { MessageElement group = (MessageElement)groupIter.next(); if (group.getElementName().getLocalName().equals("Group")) { String groupID = group.getAttribute("ID"); String groupName = group.getAttribute("Name"); // Add to the access token list accessTokens.add("G"+groupID); } } } } com.microsoft.schemas.sharepoint.soap.directory.GetRoleCollectionFromUserResponseGetRoleCollectionFromUserResult userRoleResp = userCall.getRoleCollectionFromUser( userLoginName ); org.apache.axis.message.MessageElement[] rolesList = userRoleResp.get_any(); if (rolesList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetRoleCollectionFromUser' node, saw "+Integer.toString(rolesList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getRoleCollectionFromUser xml response: '" + rolesList[0].toString() + "'"); } // Not specified in doc and must be determined experimentally // MHL return accessTokens; } catch (java.net.MalformedURLException e) { throw new ManifoldCFException("Bad SharePoint url: "+e.getMessage(),e); } catch (javax.xml.rpc.ServiceException e) { if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got a service exception getting the acls for site "+site,e); throw new ManifoldCFException("Service exception: "+e.getMessage(), e); } catch (org.apache.axis.AxisFault e) { if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/","HTTP"))) { org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName("http://xml.apache.org/axis/","HttpErrorCode")); if (elem != null) { elem.normalize(); String httpErrorCode = elem.getFirstChild().getNodeValue().trim(); if (httpErrorCode.equals("404")) { // Page did not exist if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: The page at "+baseUrl+site+" did not exist"); throw new ManifoldCFException("The page at "+baseUrl+site+" did not exist"); } else if (httpErrorCode.equals("401")) { // User did not have permissions for this library to get the acls if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: The user did not have access to the usergroups service for "+baseUrl+site); throw new ManifoldCFException("The user did not have access to the usergroups service at "+baseUrl+site); } else if (httpErrorCode.equals("403")) throw new ManifoldCFException("Http error "+httpErrorCode+" while reading from "+baseUrl+site+" - check IIS and SharePoint security settings! "+e.getMessage(),e); else throw new ManifoldCFException("Unexpected http error code "+httpErrorCode+" accessing SharePoint at "+baseUrl+site+": "+e.getMessage(),e); } throw new ManifoldCFException("Unknown http error occurred: "+e.getMessage(),e); } else if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/","Server"))) { org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/","errorcode")); if (elem != null) { elem.normalize(); String sharepointErrorCode = elem.getFirstChild().getNodeValue().trim(); if (Logging.authorityConnectors.isDebugEnabled()) { org.w3c.dom.Element elem2 = e.lookupFaultDetail(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/","errorstring")); String errorString = ""; if (elem != null) errorString = elem2.getFirstChild().getNodeValue().trim(); Logging.authorityConnectors.debug("SharePoint: Getting usergroups in site "+site+" failed with unexpected SharePoint error code "+sharepointErrorCode+": "+errorString,e); } throw new ManifoldCFException("SharePoint server error code: "+sharepointErrorCode); } if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Unknown SharePoint server error getting the acls for site "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); throw new ManifoldCFException("Unknown SharePoint server error: "+e.getMessage()); } if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/","Server.userException"))) { String exceptionName = e.getFaultString(); if (exceptionName.equals("java.lang.InterruptedException")) throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED); } if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got an unknown remote exception getting usergroups for "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); throw new ManifoldCFException("Remote procedure exception: "+e.getMessage(), e); } catch (java.rmi.RemoteException e) { // We expect the axis exception to be thrown, not this generic one! // So, fail hard if we see it. if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got an unexpected remote exception usergroups for site "+site,e); throw new ManifoldCFException("Unexpected remote procedure exception: "+e.getMessage(), e); } }
public List<String> getAccessTokens( String site, String userLoginName ) throws ManifoldCFException { try { if ( site.compareTo("/") == 0 ) site = ""; // root case UserGroupWS userService = new UserGroupWS( baseUrl + site, userName, password, configuration, httpClient ); com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap userCall = userService.getUserGroupSoapHandler( ); com.microsoft.schemas.sharepoint.soap.directory.GetUserInfoResponseGetUserInfoResult userResp = userCall.getUserInfo( userLoginName ); org.apache.axis.message.MessageElement[] usersList = userResp.get_any(); /* Response looks like this: <GetUserInfo xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/"> <User ID="4" Sid="S-1-5-21-2127521184-1604012920-1887927527-34577" Name="User1_Display_Name" LoginName="DOMAIN\User1_Alias" Email="User1_E-mail" Notes="Notes" IsSiteAdmin="False" IsDomainGroup="False" /> </GetUserInfo> */ if (usersList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetUserInfo' node, saw "+Integer.toString(usersList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getUserInfo xml response: '" + usersList[0].toString() + "'"); } MessageElement users = usersList[0]; if (!users.getElementName().getLocalName().equals("GetUserInfo")) throw new ManifoldCFException("Bad response - outer node should have been 'GetUserInfo' node"); String userID = null; Iterator userIter = users.getChildElements(); while (userIter.hasNext()) { MessageElement child = (MessageElement)userIter.next(); if (child.getElementName().getLocalName().equals("User")) { userID = child.getAttribute("ID"); } } // If userID is null, no such user if (userID == null) return null; List<String> accessTokens = new ArrayList<String>(); accessTokens.add("U"+userID); com.microsoft.schemas.sharepoint.soap.directory.GetGroupCollectionFromUserResponseGetGroupCollectionFromUserResult userGroupResp = userCall.getGroupCollectionFromUser( userLoginName ); org.apache.axis.message.MessageElement[] groupsList = userGroupResp.get_any(); /* Response looks like this: <GetGroupCollectionFromUser xmlns= "http://schemas.microsoft.com/sharepoint/soap/directory/"> <Groups> <Group ID="3" Name="Group1" Description="Description" OwnerID="1" OwnerIsUser="False" /> <Group ID="15" Name="Group2" Description="Description" OwnerID="12" OwnerIsUser="True" /> <Group ID="16" Name="Group3" Description="Description" OwnerID="7" OwnerIsUser="False" /> </Groups> </GetGroupCollectionFromUser> */ if (groupsList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetGroupCollectionFromUser' node, saw "+Integer.toString(groupsList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getGroupCollectionFromUser xml response: '" + groupsList[0].toString() + "'"); } MessageElement groups = groupsList[0]; if (!groups.getElementName().getLocalName().equals("GetGroupCollectionFromUser")) throw new ManifoldCFException("Bad response - outer node should have been 'GetGroupCollectionFromUser' node"); Iterator groupsIter = groups.getChildElements(); while (groupsIter.hasNext()) { MessageElement child = (MessageElement)groupsIter.next(); if (child.getElementName().getLocalName().equals("Groups")) { Iterator groupIter = child.getChildElements(); while (groupIter.hasNext()) { MessageElement group = (MessageElement)groupIter.next(); if (group.getElementName().getLocalName().equals("Group")) { String groupID = group.getAttribute("ID"); String groupName = group.getAttribute("Name"); // Add to the access token list accessTokens.add("G"+groupID); } } } } com.microsoft.schemas.sharepoint.soap.directory.GetRoleCollectionFromUserResponseGetRoleCollectionFromUserResult userRoleResp = userCall.getRoleCollectionFromUser( userLoginName ); org.apache.axis.message.MessageElement[] rolesList = userRoleResp.get_any(); if (rolesList.length != 1) throw new ManifoldCFException("Bad response - expecting one outer 'GetRoleCollectionFromUser' node, saw "+Integer.toString(rolesList.length)); if (Logging.authorityConnectors.isDebugEnabled()){ Logging.authorityConnectors.debug("SharePoint authority: getRoleCollectionFromUser xml response: '" + rolesList[0].toString() + "'"); } // Not specified in doc and must be determined experimentally // MHL return accessTokens; } catch (java.net.MalformedURLException e) { throw new ManifoldCFException("Bad SharePoint url: "+e.getMessage(),e); } catch (javax.xml.rpc.ServiceException e) { if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got a service exception getting the acls for site "+site,e); throw new ManifoldCFException("Service exception: "+e.getMessage(), e); } catch (org.apache.axis.AxisFault e) { if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/","HTTP"))) { org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName("http://xml.apache.org/axis/","HttpErrorCode")); if (elem != null) { elem.normalize(); String httpErrorCode = elem.getFirstChild().getNodeValue().trim(); if (httpErrorCode.equals("404")) { // Page did not exist if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: The page at "+baseUrl+site+" did not exist"); throw new ManifoldCFException("The page at "+baseUrl+site+" did not exist"); } else if (httpErrorCode.equals("401")) { // User did not have permissions for this library to get the acls if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: The user did not have access to the usergroups service for "+baseUrl+site); throw new ManifoldCFException("The user did not have access to the usergroups service at "+baseUrl+site); } else if (httpErrorCode.equals("403")) throw new ManifoldCFException("Http error "+httpErrorCode+" while reading from "+baseUrl+site+" - check IIS and SharePoint security settings! "+e.getMessage(),e); else throw new ManifoldCFException("Unexpected http error code "+httpErrorCode+" accessing SharePoint at "+baseUrl+site+": "+e.getMessage(),e); } throw new ManifoldCFException("Unknown http error occurred: "+e.getMessage(),e); } else if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/","Server"))) { org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/","errorcode")); if (elem != null) { elem.normalize(); String sharepointErrorCode = elem.getFirstChild().getNodeValue().trim(); if (sharepointErrorCode.equals("0x80131600")) { // No such user return null; } if (Logging.authorityConnectors.isDebugEnabled()) { org.w3c.dom.Element elem2 = e.lookupFaultDetail(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/","errorstring")); String errorString = ""; if (elem != null) errorString = elem2.getFirstChild().getNodeValue().trim(); Logging.authorityConnectors.debug("SharePoint: Getting usergroups in site "+site+" failed with unexpected SharePoint error code "+sharepointErrorCode+": "+errorString,e); } throw new ManifoldCFException("SharePoint server error code: "+sharepointErrorCode); } if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Unknown SharePoint server error getting usergroups for site "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); throw new ManifoldCFException("Unknown SharePoint server error: "+e.getMessage()); } if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/","Server.userException"))) { String exceptionName = e.getFaultString(); if (exceptionName.equals("java.lang.InterruptedException")) throw new ManifoldCFException("Interrupted",ManifoldCFException.INTERRUPTED); } if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got an unknown remote exception getting usergroups for "+site+" - axis fault = "+e.getFaultCode().getLocalPart()+", detail = "+e.getFaultString(),e); throw new ManifoldCFException("Remote procedure exception: "+e.getMessage(), e); } catch (java.rmi.RemoteException e) { // We expect the axis exception to be thrown, not this generic one! // So, fail hard if we see it. if (Logging.authorityConnectors.isDebugEnabled()) Logging.authorityConnectors.debug("SharePoint: Got an unexpected remote exception usergroups for site "+site,e); throw new ManifoldCFException("Unexpected remote procedure exception: "+e.getMessage(), e); } }
diff --git a/src/com/arantius/tivocommander/Content.java b/src/com/arantius/tivocommander/Content.java index a1ebaa6..fd403a0 100644 --- a/src/com/arantius/tivocommander/Content.java +++ b/src/com/arantius/tivocommander/Content.java @@ -1,203 +1,211 @@ package com.arantius.tivocommander; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import org.codehaus.jackson.JsonNode; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.arantius.tivocommander.rpc.MindRpc; import com.arantius.tivocommander.rpc.request.ContentSearch; import com.arantius.tivocommander.rpc.request.RecordingUpdate; import com.arantius.tivocommander.rpc.request.UiNavigate; import com.arantius.tivocommander.rpc.response.MindRpcResponse; import com.arantius.tivocommander.rpc.response.MindRpcResponseListener; public class Content extends Activity { private final class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... urls) { URL url = null; try { url = new URL(urls[0]); } catch (MalformedURLException e) { Utils.logError("Parse URL; " + urls[0], e); return null; } try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); return BitmapFactory.decodeStream(is); } catch (IOException e) { Utils.logError("Download URL; " + urls[0], e); return null; } } @Override protected void onPostExecute(Bitmap result) { if (result != null) { ImageView v = ((ImageView) findViewById(R.id.content_image)); v.setImageDrawable(new BitmapDrawable(result)); } mImageProgress.setVisibility(View.GONE); } } private final MindRpcResponseListener contentListener = new MindRpcResponseListener() { public void onResponse(MindRpcResponse response) { + if ("error".equals(response.getBody().path("type").getValueAsText())) { + if ("staleData".equals(response.getBody().path("code"))) { + Toast.makeText(getBaseContext(), "Stale data error, panicing.", + Toast.LENGTH_SHORT).show(); + finish(); + return; + } + } setContentView(R.layout.content); mContent = response.getBody().path("content").path(0); mImageProgress = findViewById(R.id.content_image_progress); mRecordingId = mContent.path("recordingForContentId").path(0) .path("recordingId").getTextValue(); // Display titles. String title = mContent.path("title").getTextValue(); String subtitle = mContent.path("subtitle").getTextValue(); ((TextView) findViewById(R.id.content_title)).setText(title); TextView subtitleView = ((TextView) findViewById(R.id.content_subtitle)); if (subtitle == null) { setTitle(title); subtitleView.setVisibility(View.GONE); } else { setTitle(title + " - " + subtitle); subtitleView.setText(subtitle); } // Construct and display details. ArrayList<String> detailParts = new ArrayList<String>(); int season = mContent.path("seasonNumber").getIntValue(); int epNum = mContent.path("episodeNum").path(0).getIntValue(); if (season != 0 && epNum != 0) { detailParts.add(String.format("Sea %d Ep %d", season, epNum)); } if (mContent.has("mpaaRating")) { detailParts.add(mContent.path("mpaaRating").getTextValue() .toUpperCase()); } else if (mContent.has("tvRating")) { detailParts.add("TV-" + mContent.path("tvRating").getTextValue().toUpperCase()); } detailParts.add(mContent.path("category").path(0).path("label") .getTextValue()); int year = mContent.path("originalAirYear").getIntValue(); if (year != 0) { detailParts.add(Integer.toString(year)); } String detail1 = "(" + Utils.joinList(", ", detailParts) + ")"; String detail2 = mContent.path("description").getTextValue(); TextView detailView = ((TextView) findViewById(R.id.content_details)); if (detail2 == null) { detailView.setText(detail1); } else { Spannable details = new SpannableString(detail1 + " " + detail2); details.setSpan(new ForegroundColorSpan(Color.WHITE), detail1.length(), details.length(), 0); detailView.setText(details); } // Add credits. ArrayList<String> credits = new ArrayList<String>(); for (JsonNode credit : mContent.path("credit")) { credits.add(credit.path("first").getTextValue() + " " + credit.path("last").getTextValue()); } TextView creditsView = (TextView) findViewById(R.id.content_credits); creditsView.setText(Utils.joinList(", ", credits)); // Find and set the banner image if possible. String imageUrl = findImageUrl(); if (imageUrl != null) { new DownloadImageTask().execute(imageUrl); } else { mImageProgress.setVisibility(View.GONE); } } }; private final String findImageUrl() { String url = null; int biggestSize = 0; int size = 0; for (JsonNode image : mContent.path("image")) { size = image.path("width").getIntValue() * image.path("height").getIntValue(); if (size > biggestSize) { biggestSize = size; url = image.path("imageUrl").getTextValue(); } } return url; } private JsonNode mContent; private String mContentId; private View mImageProgress; private String mRecordingId; public void doDelete(View v) { // Delete the recording ... MindRpc.addRequest(new RecordingUpdate(mRecordingId, "deleted"), null); // .. and tell the show list to refresh itself. Intent resultIntent = new Intent(); resultIntent.putExtra("refresh", true); setResult(Activity.RESULT_OK, resultIntent); finish(); } public void doExplore(View v) { Toast.makeText(getBaseContext(), "Explore not implemented yet.", Toast.LENGTH_SHORT).show(); } public void doWatch(View v) { MindRpc.addRequest(new UiNavigate(mRecordingId), null); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MindRpc.init(this); Bundle bundle = getIntent().getExtras(); if (bundle != null) { mContentId = bundle.getString("contentId"); } else { Toast.makeText(getBaseContext(), R.string.error_reading_content_id, Toast.LENGTH_SHORT).show(); finish(); return; } setContentView(R.layout.progress); MindRpc.addRequest(new ContentSearch(mContentId), contentListener); } }
true
true
public void onResponse(MindRpcResponse response) { setContentView(R.layout.content); mContent = response.getBody().path("content").path(0); mImageProgress = findViewById(R.id.content_image_progress); mRecordingId = mContent.path("recordingForContentId").path(0) .path("recordingId").getTextValue(); // Display titles. String title = mContent.path("title").getTextValue(); String subtitle = mContent.path("subtitle").getTextValue(); ((TextView) findViewById(R.id.content_title)).setText(title); TextView subtitleView = ((TextView) findViewById(R.id.content_subtitle)); if (subtitle == null) { setTitle(title); subtitleView.setVisibility(View.GONE); } else { setTitle(title + " - " + subtitle); subtitleView.setText(subtitle); } // Construct and display details. ArrayList<String> detailParts = new ArrayList<String>(); int season = mContent.path("seasonNumber").getIntValue(); int epNum = mContent.path("episodeNum").path(0).getIntValue(); if (season != 0 && epNum != 0) { detailParts.add(String.format("Sea %d Ep %d", season, epNum)); } if (mContent.has("mpaaRating")) { detailParts.add(mContent.path("mpaaRating").getTextValue() .toUpperCase()); } else if (mContent.has("tvRating")) { detailParts.add("TV-" + mContent.path("tvRating").getTextValue().toUpperCase()); } detailParts.add(mContent.path("category").path(0).path("label") .getTextValue()); int year = mContent.path("originalAirYear").getIntValue(); if (year != 0) { detailParts.add(Integer.toString(year)); } String detail1 = "(" + Utils.joinList(", ", detailParts) + ")"; String detail2 = mContent.path("description").getTextValue(); TextView detailView = ((TextView) findViewById(R.id.content_details)); if (detail2 == null) { detailView.setText(detail1); } else { Spannable details = new SpannableString(detail1 + " " + detail2); details.setSpan(new ForegroundColorSpan(Color.WHITE), detail1.length(), details.length(), 0); detailView.setText(details); } // Add credits. ArrayList<String> credits = new ArrayList<String>(); for (JsonNode credit : mContent.path("credit")) { credits.add(credit.path("first").getTextValue() + " " + credit.path("last").getTextValue()); } TextView creditsView = (TextView) findViewById(R.id.content_credits); creditsView.setText(Utils.joinList(", ", credits)); // Find and set the banner image if possible. String imageUrl = findImageUrl(); if (imageUrl != null) { new DownloadImageTask().execute(imageUrl); } else { mImageProgress.setVisibility(View.GONE); } }
public void onResponse(MindRpcResponse response) { if ("error".equals(response.getBody().path("type").getValueAsText())) { if ("staleData".equals(response.getBody().path("code"))) { Toast.makeText(getBaseContext(), "Stale data error, panicing.", Toast.LENGTH_SHORT).show(); finish(); return; } } setContentView(R.layout.content); mContent = response.getBody().path("content").path(0); mImageProgress = findViewById(R.id.content_image_progress); mRecordingId = mContent.path("recordingForContentId").path(0) .path("recordingId").getTextValue(); // Display titles. String title = mContent.path("title").getTextValue(); String subtitle = mContent.path("subtitle").getTextValue(); ((TextView) findViewById(R.id.content_title)).setText(title); TextView subtitleView = ((TextView) findViewById(R.id.content_subtitle)); if (subtitle == null) { setTitle(title); subtitleView.setVisibility(View.GONE); } else { setTitle(title + " - " + subtitle); subtitleView.setText(subtitle); } // Construct and display details. ArrayList<String> detailParts = new ArrayList<String>(); int season = mContent.path("seasonNumber").getIntValue(); int epNum = mContent.path("episodeNum").path(0).getIntValue(); if (season != 0 && epNum != 0) { detailParts.add(String.format("Sea %d Ep %d", season, epNum)); } if (mContent.has("mpaaRating")) { detailParts.add(mContent.path("mpaaRating").getTextValue() .toUpperCase()); } else if (mContent.has("tvRating")) { detailParts.add("TV-" + mContent.path("tvRating").getTextValue().toUpperCase()); } detailParts.add(mContent.path("category").path(0).path("label") .getTextValue()); int year = mContent.path("originalAirYear").getIntValue(); if (year != 0) { detailParts.add(Integer.toString(year)); } String detail1 = "(" + Utils.joinList(", ", detailParts) + ")"; String detail2 = mContent.path("description").getTextValue(); TextView detailView = ((TextView) findViewById(R.id.content_details)); if (detail2 == null) { detailView.setText(detail1); } else { Spannable details = new SpannableString(detail1 + " " + detail2); details.setSpan(new ForegroundColorSpan(Color.WHITE), detail1.length(), details.length(), 0); detailView.setText(details); } // Add credits. ArrayList<String> credits = new ArrayList<String>(); for (JsonNode credit : mContent.path("credit")) { credits.add(credit.path("first").getTextValue() + " " + credit.path("last").getTextValue()); } TextView creditsView = (TextView) findViewById(R.id.content_credits); creditsView.setText(Utils.joinList(", ", credits)); // Find and set the banner image if possible. String imageUrl = findImageUrl(); if (imageUrl != null) { new DownloadImageTask().execute(imageUrl); } else { mImageProgress.setVisibility(View.GONE); } }
diff --git a/src/main/java/edu/jhu/hlt/concrete/agiga/AgigaConverter.java b/src/main/java/edu/jhu/hlt/concrete/agiga/AgigaConverter.java index 3f9863b..37deef1 100644 --- a/src/main/java/edu/jhu/hlt/concrete/agiga/AgigaConverter.java +++ b/src/main/java/edu/jhu/hlt/concrete/agiga/AgigaConverter.java @@ -1,361 +1,361 @@ package edu.jhu.hlt.concrete.agiga; import edu.jhu.hlt.concrete.Concrete.*; import edu.jhu.hlt.concrete.Concrete.TokenTagging.TaggedToken; import edu.jhu.hlt.concrete.util.*; import edu.jhu.hlt.concrete.io.ProtocolBufferWriter; import edu.jhu.agiga.*; import edu.stanford.nlp.trees.*; import java.util.*; import java.util.zip.GZIPOutputStream; import java.io.*; class AgigaConverter { public static final String toolName = "Annotated Gigaword Pipeline"; public static final String corpusName = "Annotated Gigaword"; public static final double annotationTime = Calendar.getInstance().getTimeInMillis() / 1000d; public static AnnotationMetadata metadata() { return metadata(null); } public static AnnotationMetadata metadata(String addToToolName) { String fullToolName = toolName; if(addToToolName != null) fullToolName += addToToolName; return AnnotationMetadata.newBuilder() .setTool(fullToolName) .setTimestamp(annotationTime) .setConfidence(1f) .build(); } public static String flattenText(AgigaDocument doc) { StringBuilder sb = new StringBuilder(); for(AgigaSentence sent : doc.getSents()) sb.append(flattenText(sent)); return sb.toString(); } public static String flattenText(AgigaSentence sent) { StringBuilder sb = new StringBuilder(); for(AgigaToken tok : sent.getTokens()) sb.append(tok.getWord() + " "); return sb.toString().trim(); } public static Parse stanford2concrete(Tree root, Tokenization tokenization) { int[] nodeCounter = new int[]{0}; int left = 0; int right = root.getLeaves().size(); return Parse.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata(" http://www.aclweb.org/anthology-new/D/D10/D10-1002.pdf")) .setRoot(s2cHelper(root, nodeCounter, left, right, tokenization)) .build(); } /** * i'm using int[] as a java hack for int* (pass by reference rather than value). */ private static final HeadFinder HEAD_FINDER = new SemanticHeadFinder(); private static Parse.Constituent.Builder s2cHelper(Tree root, int[] nodeCounter, int left, int right, Tokenization tokenization) { assert(nodeCounter.length == 1); Parse.Constituent.Builder cb = Parse.Constituent.newBuilder() .setId(nodeCounter[0]++) .setTag(root.value()) .setTokenSequence(extractTokenRefSequence(left, right, tokenization)); Tree headTree = HEAD_FINDER.determineHead(root); int i = 0, headTreeIdx = -1; int leftPtr = left; for(Tree child : root.getChildrenAsList()) { int width = child.getLeaves().size(); cb.addChild(s2cHelper(child, nodeCounter, leftPtr, leftPtr + width, tokenization)); leftPtr += width; if(child == headTree) { assert(headTreeIdx < 0); headTreeIdx = i; } i++; } assert(leftPtr == right); if(headTreeIdx >= 0) cb.setHeadChildIndex(headTreeIdx); return cb; } public static TokenRefSequence extractTokenRefSequence(AgigaMention m, Tokenization tok) { return extractTokenRefSequence(m.getStartTokenIdx(), m.getEndTokenIdx(), tok); } public static TokenRefSequence extractTokenRefSequence(int left, int right, Tokenization tokenization) { assert(left < right && left >= 0 && right <= tokenization.getTokenList().size()); assert(tokenization.getKind() == Tokenization.Kind.TOKEN_LIST); TokenRefSequence.Builder tb = TokenRefSequence.newBuilder() .setTokenization(tokenization.getUuid()); for(int i=left; i<right; i++) tb.addTokenId(tokenization.getToken(i).getTokenId()); return tb.build(); } public static TokenRef extractTokenRef(int index, Tokenization tokenization) { assert(index >= 0); assert(tokenization.getKind() == Tokenization.Kind.TOKEN_LIST); int tokId = tokenization.getToken(index).getTokenId(); return TokenRef.newBuilder() .setTokenId(tokId) .setTokenization(tokenization.getUuid()) .build(); } /** * name is the type of dependencies, e.g. "col-deps" or "col-ccproc-deps" */ public static DependencyParse convertDependencyParse(List<AgigaTypedDependency> deps, String name, Tokenization tokenization) { DependencyParse.Builder db = DependencyParse.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata(" " + name + " http://nlp.stanford.edu/software/dependencies_manual.pdf")); for(AgigaTypedDependency ad : deps) { DependencyParse.Dependency.Builder depB = DependencyParse.Dependency.newBuilder() .setDep(extractTokenRef(ad.getDepIdx(), tokenization)) .setEdgeType(ad.getType()); if(ad.getGovIdx() >= 0) // else ROOT depB.setGov(extractTokenRef(ad.getGovIdx(), tokenization)); db.addDependency(depB.build()); } return db.build(); } public static Tokenization convertTokenization(AgigaSentence sent) { TokenTagging.Builder lemmaBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); TokenTagging.Builder posBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); TokenTagging.Builder nerBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); //TokenTagging.Builder normNerBuilder = TokenTagging.newBuilder() // .setUuid(IdUtil.generateUUID()) // .setMetadata(metadata()); Tokenization.Builder tb = Tokenization.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata(" http://nlp.stanford.edu/software/tokensregex.shtml")) .setKind(Tokenization.Kind.TOKEN_LIST); int charOffset = 0; int tokId = 0; for(AgigaToken tok : sent.getTokens()) { int curTokId = tokId++; // token tb.addToken(Token.newBuilder() .setTokenId(curTokId) .setText(tok.getWord()) .setTextSpan(TextSpan.newBuilder() .setStart(charOffset) .setEnd(charOffset + tok.getWord().length()) .build()) .build()); // token annotations lemmaBuilder.addTaggedToken(makeTaggedToken(tok.getLemma(), curTokId)); posBuilder.addTaggedToken(makeTaggedToken(tok.getPosTag(), curTokId)); nerBuilder.addTaggedToken(makeTaggedToken(tok.getNerTag(), curTokId)); //normNerBuilder.addTaggedToken(makeTaggedToken(tok.getNormNerTag(), curTokId)); charOffset += tok.getWord().length() + 1; } return tb - .addLemmas(posBuilder.build()) + .addLemmas(lemmaBuilder.build()) .addPosTags(posBuilder.build()) - .addNerTags(posBuilder.build()) + .addNerTags(nerBuilder.build()) .build(); } public static TaggedToken makeTaggedToken(String tag, int tokId) { return TaggedToken.newBuilder() .setTokenId(tokId) .setTag(tag) .setConfidence(1f) .build(); } public static Sentence convertSentence(AgigaSentence sent, List<Tokenization> addTo) { Tokenization tokenization = convertTokenization(sent); addTo.add(tokenization); // one tokenization per sentence return Sentence.newBuilder() .setUuid(IdUtil.generateUUID()) .setTextSpan(TextSpan.newBuilder() .setStart(0) .setEnd(flattenText(sent).length()) .build()) // tokenization .addTokenization(tokenization) // parses .addParse(stanford2concrete(sent.getStanfordContituencyTree(), tokenization)) .addDependencyParse(convertDependencyParse(sent.getBasicDeps(), "basic-deps", tokenization)) .addDependencyParse(convertDependencyParse(sent.getColDeps(), "col-deps", tokenization)) .addDependencyParse(convertDependencyParse(sent.getColCcprocDeps(), "col-ccproc-deps", tokenization)) .build(); } public static SentenceSegmentation sentenceSegment(AgigaDocument doc, List<Tokenization> addTo) { SentenceSegmentation.Builder sb = SentenceSegmentation.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata(" Splitta http://www.aclweb.org/anthology-new/N/N09/N09-2061.pdf")); for(AgigaSentence sentence : doc.getSents()) sb = sb.addSentence(convertSentence(sentence, addTo)); return sb.build(); } public static SectionSegmentation sectionSegment(AgigaDocument doc, String rawText, List<Tokenization> addTo) { return SectionSegmentation.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()) .addSection(Section.newBuilder() .setUuid(IdUtil.generateUUID()) .setTextSpan(TextSpan.newBuilder() .setStart(0) .setEnd(rawText.length()) .build()) .addSentenceSegmentation(sentenceSegment(doc, addTo)) .build()) .build(); } public static String extractMentionString(AgigaMention m, AgigaDocument doc) { List<AgigaToken> sentence = doc.getSents().get(m.getSentenceIdx()).getTokens(); StringBuilder sb = new StringBuilder(); for(int i=m.getStartTokenIdx(); i<m.getEndTokenIdx(); i++) { sb.append(sentence.get(i).getWord()); if(i > m.getStartTokenIdx()) sb.append(" "); } return sb.toString(); } public static TextSpan mention2TextSpan(AgigaMention m, AgigaDocument doc) { // count the number of chars from the start of the sentence int start = 0; int end = 0; List<AgigaToken> sentence = doc.getSents().get(m.getSentenceIdx()).getTokens(); StringBuilder sb = new StringBuilder(); for(int i=0; i<m.getEndTokenIdx(); i++) { int len = sentence.get(i).getWord().length(); if(i < m.getStartTokenIdx()) start += len; end += len; // spaces between words if(i > m.getStartTokenIdx()) { start++; end++; } } return TextSpan.newBuilder() .setStart(start) .setEnd(end) .build(); } public static EntityMention convertMention(AgigaMention m, AgigaDocument doc, edu.jhu.hlt.concrete.Concrete.UUID corefSet, Tokenization tokenization) { String mstring = extractMentionString(m, doc); return EntityMention.newBuilder() .setUuid(IdUtil.generateUUID()) .setTokenSequence(extractTokenRefSequence(m, tokenization)) .setEntityType(Entity.Type.UNKNOWN) .setPhraseType(EntityMention.PhraseType.NAME) // TODO warn users that this may not be accurate .setConfidence(1f) .setText(mstring) // TODO merge this an method below .setTextSpan(mention2TextSpan(m, doc)) .setCorefId(corefSet) .setSentenceIndex(m.getSentenceIdx()) .setHeadIndex(m.getHeadTokenIdx()) .build(); } public static EntityMentionSet convertCoref(AgigaCoref coref, AgigaDocument doc, List<Tokenization> toks) { EntityMentionSet.Builder eb = EntityMentionSet.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata(" http://nlp.stanford.edu/pubs/conllst2011-coref.pdf")); for(AgigaMention m : coref.getMentions()) eb.addMention(convertMention(m, doc, IdUtil.generateUUID(), toks.get(m.getSentenceIdx()))); return eb.build(); } public static Communication convertDoc(AgigaDocument doc, KnowledgeGraph kg) { CommunicationGUID guid = CommunicationGUID.newBuilder() .setCorpusName(corpusName) .setCommunicationId(doc.getDocId()) .build(); String flatText = flattenText(doc); List<Tokenization> toks = new ArrayList<Tokenization>(); Communication.Builder cb = Communication.newBuilder() .setUuid(IdUtil.generateUUID()) .setGuid(guid) .setText(flatText) .addSectionSegmentation(sectionSegment(doc, flatText, toks)) .setKind(Communication.Kind.NEWS) .setKnowledgeGraph(kg); // this must occur last so that the tokenizations have been added to toks for(AgigaCoref coref : doc.getCorefs()) cb.addEntityMentionSet(convertCoref(coref, doc, toks)); return cb.build(); } // need some code that reads agiga docs, converts, and then dumps them into a file public static void main(String[] args) throws Exception { assert(false); if(args.length != 2) { System.out.println("please provide:"); System.out.println("1) an input Agiga XML file"); System.out.println("2) an output Concrete Protobuf file"); return; } long start = System.currentTimeMillis(); File agigaXML = new File(args[0]); assert(agigaXML.exists() && agigaXML.isFile()); File output = new File(args[1]); StreamingDocumentReader docReader = new StreamingDocumentReader(agigaXML.getPath(), new AgigaPrefs()); BufferedOutputStream writer = new BufferedOutputStream( output.getName().toLowerCase().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output)); //ProtocolBufferWriter writer = new ProtocolBufferWriter(new FileOutputStream(output)); // TODO we need a knowledge graph KnowledgeGraph kg = new ProtoFactory(9001).generateKnowledgeGraph(); kg.writeDelimitedTo(writer); //writer.write(kg); int c = 0; int step = 250; for(AgigaDocument doc : docReader) { Communication comm = convertDoc(doc, kg); comm.writeDelimitedTo(writer); //writer.write(comm); c++; if(c % step == 0) { System.out.printf("wrote %d documents in %.1f sec\n", c, (System.currentTimeMillis() - start)/1000d); } } writer.close(); System.out.printf("done, wrote %d communications to %s in %.1f seconds\n", c, output.getPath(), (System.currentTimeMillis() - start)/1000d); } }
false
true
public static Tokenization convertTokenization(AgigaSentence sent) { TokenTagging.Builder lemmaBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); TokenTagging.Builder posBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); TokenTagging.Builder nerBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); //TokenTagging.Builder normNerBuilder = TokenTagging.newBuilder() // .setUuid(IdUtil.generateUUID()) // .setMetadata(metadata()); Tokenization.Builder tb = Tokenization.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata(" http://nlp.stanford.edu/software/tokensregex.shtml")) .setKind(Tokenization.Kind.TOKEN_LIST); int charOffset = 0; int tokId = 0; for(AgigaToken tok : sent.getTokens()) { int curTokId = tokId++; // token tb.addToken(Token.newBuilder() .setTokenId(curTokId) .setText(tok.getWord()) .setTextSpan(TextSpan.newBuilder() .setStart(charOffset) .setEnd(charOffset + tok.getWord().length()) .build()) .build()); // token annotations lemmaBuilder.addTaggedToken(makeTaggedToken(tok.getLemma(), curTokId)); posBuilder.addTaggedToken(makeTaggedToken(tok.getPosTag(), curTokId)); nerBuilder.addTaggedToken(makeTaggedToken(tok.getNerTag(), curTokId)); //normNerBuilder.addTaggedToken(makeTaggedToken(tok.getNormNerTag(), curTokId)); charOffset += tok.getWord().length() + 1; } return tb .addLemmas(posBuilder.build()) .addPosTags(posBuilder.build()) .addNerTags(posBuilder.build()) .build(); }
public static Tokenization convertTokenization(AgigaSentence sent) { TokenTagging.Builder lemmaBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); TokenTagging.Builder posBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); TokenTagging.Builder nerBuilder = TokenTagging.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata()); //TokenTagging.Builder normNerBuilder = TokenTagging.newBuilder() // .setUuid(IdUtil.generateUUID()) // .setMetadata(metadata()); Tokenization.Builder tb = Tokenization.newBuilder() .setUuid(IdUtil.generateUUID()) .setMetadata(metadata(" http://nlp.stanford.edu/software/tokensregex.shtml")) .setKind(Tokenization.Kind.TOKEN_LIST); int charOffset = 0; int tokId = 0; for(AgigaToken tok : sent.getTokens()) { int curTokId = tokId++; // token tb.addToken(Token.newBuilder() .setTokenId(curTokId) .setText(tok.getWord()) .setTextSpan(TextSpan.newBuilder() .setStart(charOffset) .setEnd(charOffset + tok.getWord().length()) .build()) .build()); // token annotations lemmaBuilder.addTaggedToken(makeTaggedToken(tok.getLemma(), curTokId)); posBuilder.addTaggedToken(makeTaggedToken(tok.getPosTag(), curTokId)); nerBuilder.addTaggedToken(makeTaggedToken(tok.getNerTag(), curTokId)); //normNerBuilder.addTaggedToken(makeTaggedToken(tok.getNormNerTag(), curTokId)); charOffset += tok.getWord().length() + 1; } return tb .addLemmas(lemmaBuilder.build()) .addPosTags(posBuilder.build()) .addNerTags(nerBuilder.build()) .build(); }
diff --git a/SoftwareProjectDay/src/edu/se/se441/threads/Manager.java b/SoftwareProjectDay/src/edu/se/se441/threads/Manager.java index 8be2d7c..7539e2c 100644 --- a/SoftwareProjectDay/src/edu/se/se441/threads/Manager.java +++ b/SoftwareProjectDay/src/edu/se/se441/threads/Manager.java @@ -1,230 +1,230 @@ package edu.se.se441.threads; import java.util.concurrent.*; import edu.se.se441.Office; public class Manager extends Thread { final int NUMQUESTIONS = 10; private Office office; private CountDownLatch startSignal; private BlockingQueue<Employee> hasQuestion = new ArrayBlockingQueue<Employee>(NUMQUESTIONS); private volatile boolean attendedMeeting1 = false; private volatile boolean attendedMeeting2 = false; private volatile boolean ateLunch = false; private volatile boolean attendedFinalMeeting = false; private Object questionLock = new Object(); private long timeSpentAnsweringQuestions = 0; private long timeSpentInMeetings = 0; private long timeSpentWorking = 0; private long timeSpentAtLunch = 0; public Manager(Office office){ this.office = office; office.setManager(this); } public void run(){ office.addTimeEvent(1000); // 10AM Meeting office.addTimeEvent(1200); // Lunch Time office.addTimeEvent(1200); // 2PM Meeting office.addTimeEvent(1600); // 4PM Meeting office.addTimeEvent(1700); // 5PM end of day try { // Starting all threads at the same time (clock == 0 / "8:00AM"). startSignal.await(); Thread.yield(); if(office.getTime() == 800){ System.out.println(office.getStringTime() + " Manager arrives at office"); } else { System.out.println("8:00 Manager arrives at office"); } long startCheck = System.currentTimeMillis(); // Waiting for team leads for the meeting. office.waitForStandupMeeting(); long endCheck = System.currentTimeMillis(); System.out.println("Worked: " + (int)((endCheck - startCheck)/10)); timeSpentWorking =+ (endCheck - startCheck)/10; startCheck = System.currentTimeMillis(); Thread.sleep(150); endCheck = System.currentTimeMillis(); timeSpentInMeetings += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } while(office.getTime() < 1700){ long startCheck = System.currentTimeMillis(); office.startWorking(); long endCheck = System.currentTimeMillis(); timeSpentWorking += (endCheck - startCheck)/10; while(!hasQuestion.isEmpty()){ checkConditions(); startCheck = System.currentTimeMillis(); answerQuestion(); endCheck = System.currentTimeMillis(); timeSpentAnsweringQuestions += (endCheck - startCheck)/10; } checkConditions(); } System.out.println(office.getStringTime() + " Manager leaves"); System.out.println("Manager report: a) " + timeSpentWorking + " b) " + timeSpentAtLunch + " c) " + timeSpentInMeetings + " c) " + timeSpentAnsweringQuestions); } public void setStartSignal(CountDownLatch startSignal) { this.startSignal = startSignal; } public void checkConditions(){ if(office.getTime() >= 1000 && !attendedMeeting1){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to meeting"); sleep(600); long endCheck = System.currentTimeMillis(); timeSpentInMeetings += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedMeeting1 = true; } if(office.getTime() >= 1200 && !ateLunch){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to lunch"); sleep(600); long endCheck = System.currentTimeMillis(); timeSpentAtLunch += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } ateLunch = true; } if(office.getTime() >= 1400 && !attendedMeeting2){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to meeting"); sleep(600); long endCheck = System.currentTimeMillis(); - timeSpentAtLunch += (endCheck - startCheck)/10; + timeSpentInMeetings += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedMeeting2 = true; } // Is it time for the 4 oclock meeting? if(office.getTime() >= 1600 && !attendedFinalMeeting){ office.waitForEndOfDayMeeting(); try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager heads to end of day meeting"); sleep(150); long endCheck = System.currentTimeMillis(); - timeSpentAtLunch += (endCheck - startCheck)/10; + timeSpentInMeetings += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedFinalMeeting = true; } } public void askQuestion(Employee employee){ // Add question to queue synchronized(hasQuestion){ hasQuestion.add(employee); } // Waiting until question can be answered synchronized(questionLock){ while(hasQuestion.contains(employee)){ // Is it time for the 4 o'clock meeting? try { if(office.getTime() >= 1600 && !employee.isAttendedEndOfDayMeeting()){ System.out.println("Starting end of day meeting."); office.waitForEndOfDayMeeting(); System.out.println("Everyone is ready for end of day meeting."); sleep(150); employee.setAttendedEndOfDayMeeting(true); } // Tell the Manager there is a question. office.notifyWorking(); questionLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // Question is being answered while(employee.isWaitingQuestion()){ try { questionLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } public boolean isLeadAsking(Employee lead){ return hasQuestion.contains(lead); } public Object getQuestionLock(){ return questionLock; } private void answerQuestion(){ Employee employee = hasQuestion.poll(); if(office.getTime() < 1700){ synchronized(questionLock){ questionLock.notifyAll(); } try { System.out.println(office.getStringTime() + " Manager starts answering question. Queue depth: " + hasQuestion.size()); sleep(100); System.out.println(office.getStringTime() + " Manager ends answering question. Queue depth: " + hasQuestion.size()); } catch (InterruptedException e) { e.printStackTrace(); } employee.questionAnswered(); synchronized(questionLock){ questionLock.notifyAll(); } } else{ while(!hasQuestion.isEmpty()){ hasQuestion.poll(); } synchronized(questionLock){ questionLock.notifyAll(); } } } }
false
true
public void checkConditions(){ if(office.getTime() >= 1000 && !attendedMeeting1){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to meeting"); sleep(600); long endCheck = System.currentTimeMillis(); timeSpentInMeetings += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedMeeting1 = true; } if(office.getTime() >= 1200 && !ateLunch){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to lunch"); sleep(600); long endCheck = System.currentTimeMillis(); timeSpentAtLunch += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } ateLunch = true; } if(office.getTime() >= 1400 && !attendedMeeting2){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to meeting"); sleep(600); long endCheck = System.currentTimeMillis(); timeSpentAtLunch += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedMeeting2 = true; } // Is it time for the 4 oclock meeting? if(office.getTime() >= 1600 && !attendedFinalMeeting){ office.waitForEndOfDayMeeting(); try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager heads to end of day meeting"); sleep(150); long endCheck = System.currentTimeMillis(); timeSpentAtLunch += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedFinalMeeting = true; } }
public void checkConditions(){ if(office.getTime() >= 1000 && !attendedMeeting1){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to meeting"); sleep(600); long endCheck = System.currentTimeMillis(); timeSpentInMeetings += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedMeeting1 = true; } if(office.getTime() >= 1200 && !ateLunch){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to lunch"); sleep(600); long endCheck = System.currentTimeMillis(); timeSpentAtLunch += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } ateLunch = true; } if(office.getTime() >= 1400 && !attendedMeeting2){ try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager goes to meeting"); sleep(600); long endCheck = System.currentTimeMillis(); timeSpentInMeetings += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedMeeting2 = true; } // Is it time for the 4 oclock meeting? if(office.getTime() >= 1600 && !attendedFinalMeeting){ office.waitForEndOfDayMeeting(); try { long startCheck = System.currentTimeMillis(); System.out.println(office.getStringTime() + " Manager heads to end of day meeting"); sleep(150); long endCheck = System.currentTimeMillis(); timeSpentInMeetings += (endCheck - startCheck)/10; } catch (InterruptedException e) { e.printStackTrace(); } attendedFinalMeeting = true; } }
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/cleaner/CleanerChore.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/cleaner/CleanerChore.java index 6d3212296..8711c8252 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/cleaner/CleanerChore.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/cleaner/CleanerChore.java @@ -1,238 +1,238 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.master.cleaner; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Chore; import org.apache.hadoop.hbase.RemoteExceptionHandler; import org.apache.hadoop.hbase.Stoppable; import org.apache.hadoop.hbase.util.FSUtils; /** * Abstract Cleaner that uses a chain of delegates to clean a directory of files * @param <T> Cleaner delegate class that is dynamically loaded from configuration */ public abstract class CleanerChore<T extends FileCleanerDelegate> extends Chore { private static final Log LOG = LogFactory.getLog(CleanerChore.class.getName()); private final FileSystem fs; private final Path oldFileDir; private final Configuration conf; private List<T> cleanersChain; /** * @param name name of the chore being run * @param sleepPeriod the period of time to sleep between each run * @param s the stopper * @param conf configuration to use * @param fs handle to the FS * @param oldFileDir the path to the archived files * @param confKey configuration key for the classes to instantiate */ public CleanerChore(String name, final int sleepPeriod, final Stoppable s, Configuration conf, FileSystem fs, Path oldFileDir, String confKey) { super(name, sleepPeriod, s); this.fs = fs; this.oldFileDir = oldFileDir; this.conf = conf; initCleanerChain(confKey); } /** * Validate the file to see if it even belongs in the directory. If it is valid, then the file * will go through the cleaner delegates, but otherwise the file is just deleted. * @param file full {@link Path} of the file to be checked * @return <tt>true</tt> if the file is valid, <tt>false</tt> otherwise */ protected abstract boolean validate(Path file); /** * Instanitate and initialize all the file cleaners set in the configuration * @param confKey key to get the file cleaner classes from the configuration */ private void initCleanerChain(String confKey) { this.cleanersChain = new LinkedList<T>(); String[] logCleaners = conf.getStrings(confKey); if (logCleaners != null) { for (String className : logCleaners) { T logCleaner = newFileCleaner(className, conf); if (logCleaner != null) this.cleanersChain.add(logCleaner); } } } /** * A utility method to create new instances of LogCleanerDelegate based on the class name of the * LogCleanerDelegate. * @param className fully qualified class name of the LogCleanerDelegate * @param conf * @return the new instance */ public T newFileCleaner(String className, Configuration conf) { try { Class<? extends FileCleanerDelegate> c = Class.forName(className).asSubclass( FileCleanerDelegate.class); @SuppressWarnings("unchecked") T cleaner = (T) c.newInstance(); cleaner.setConf(conf); return cleaner; } catch (Exception e) { LOG.warn("Can NOT create CleanerDelegate: " + className, e); // skipping if can't instantiate return null; } } @Override protected void chore() { try { FileStatus[] files = FSUtils.listStatus(this.fs, this.oldFileDir, null); // if the path (file or directory) doesn't exist, then we can just return if (files == null) return; // loop over the found files and see if they should be deleted for (FileStatus file : files) { try { if (file.isDir()) checkDirectory(file.getPath()); else checkAndDelete(file.getPath()); } catch (IOException e) { e = RemoteExceptionHandler.checkIOException(e); LOG.warn("Error while cleaning the logs", e); } } } catch (IOException e) { LOG.warn("Failed to get status of:" + oldFileDir); } } /** * Check to see if we can delete a directory (and all the children files of that directory). * <p> * A directory will not be deleted if it has children that are subsequently deleted since that * will require another set of lookups in the filesystem, which is semantically same as waiting * until the next time the chore is run, so we might as well wait. * @param fs {@link FileSystem} where he directory resides * @param toCheck directory to check * @throws IOException */ private void checkDirectory(Path toCheck) throws IOException { LOG.debug("Checking directory: " + toCheck); FileStatus[] files = checkAndDeleteDirectory(toCheck); // if the directory doesn't exist, then we are done if (files == null) return; // otherwise we need to check each of the child files for (FileStatus file : files) { Path filePath = file.getPath(); // if its a directory, then check to see if it should be deleted if (file.isDir()) { // check the subfiles to see if they can be deleted checkDirectory(filePath); continue; } // otherwise we can just check the file checkAndDelete(filePath); } // recheck the directory to see if we can delete it this time checkAndDeleteDirectory(toCheck); } /** * Check and delete the passed directory if the directory is empty * @param toCheck full path to the directory to check (and possibly delete) * @return <tt>null</tt> if the directory was empty (and possibly deleted) and otherwise an array * of <code>FileStatus</code> for the files in the directory * @throws IOException */ private FileStatus[] checkAndDeleteDirectory(Path toCheck) throws IOException { LOG.debug("Attempting to delete directory:" + toCheck); // if it doesn't exist, we are done if (!fs.exists(toCheck)) return null; // get the files below the directory FileStatus[] files = FSUtils.listStatus(fs, toCheck, null); // if there are no subfiles, then we can delete the directory if (files == null) { checkAndDelete(toCheck); return null; } // return the status of the files in the directory return files; } /** * Run the given file through each of the cleaners to see if it should be deleted, deleting it if * necessary. * @param filePath path of the file to check (and possibly delete) * @throws IOException if cann't delete a file because of a filesystem issue * @throws IllegalArgumentException if the file is a directory and has children */ private void checkAndDelete(Path filePath) throws IOException, IllegalArgumentException { if (!validate(filePath)) { LOG.warn("Found a wrongly formatted file: " + filePath.getName() + "deleting it."); if (!this.fs.delete(filePath, true)) { LOG.warn("Attempted to delete:" + filePath + ", but couldn't. Run cleaner chain and attempt to delete on next pass."); } return; } for (T cleaner : cleanersChain) { if (cleaner.isStopped()) { LOG.warn("A file cleaner" + this.getName() + " is stopped, won't delete any file in:" + this.oldFileDir); return; } if (!cleaner.isFileDeleteable(filePath)) { // this file is not deletable, then we are done LOG.debug(filePath + " is not deletable according to:" + cleaner); return; } } // delete this file if it passes all the cleaners LOG.debug("Removing:" + filePath + " from archive"); - if (this.fs.delete(filePath, false)) { + if (!this.fs.delete(filePath, false)) { LOG.warn("Attempted to delete:" + filePath + ", but couldn't. Run cleaner chain and attempt to delete on next pass."); } } @Override public void cleanup() { for (T lc : this.cleanersChain) { try { lc.stop("Exiting"); } catch (Throwable t) { LOG.warn("Stopping", t); } } } }
true
true
private void checkAndDelete(Path filePath) throws IOException, IllegalArgumentException { if (!validate(filePath)) { LOG.warn("Found a wrongly formatted file: " + filePath.getName() + "deleting it."); if (!this.fs.delete(filePath, true)) { LOG.warn("Attempted to delete:" + filePath + ", but couldn't. Run cleaner chain and attempt to delete on next pass."); } return; } for (T cleaner : cleanersChain) { if (cleaner.isStopped()) { LOG.warn("A file cleaner" + this.getName() + " is stopped, won't delete any file in:" + this.oldFileDir); return; } if (!cleaner.isFileDeleteable(filePath)) { // this file is not deletable, then we are done LOG.debug(filePath + " is not deletable according to:" + cleaner); return; } } // delete this file if it passes all the cleaners LOG.debug("Removing:" + filePath + " from archive"); if (this.fs.delete(filePath, false)) { LOG.warn("Attempted to delete:" + filePath + ", but couldn't. Run cleaner chain and attempt to delete on next pass."); } }
private void checkAndDelete(Path filePath) throws IOException, IllegalArgumentException { if (!validate(filePath)) { LOG.warn("Found a wrongly formatted file: " + filePath.getName() + "deleting it."); if (!this.fs.delete(filePath, true)) { LOG.warn("Attempted to delete:" + filePath + ", but couldn't. Run cleaner chain and attempt to delete on next pass."); } return; } for (T cleaner : cleanersChain) { if (cleaner.isStopped()) { LOG.warn("A file cleaner" + this.getName() + " is stopped, won't delete any file in:" + this.oldFileDir); return; } if (!cleaner.isFileDeleteable(filePath)) { // this file is not deletable, then we are done LOG.debug(filePath + " is not deletable according to:" + cleaner); return; } } // delete this file if it passes all the cleaners LOG.debug("Removing:" + filePath + " from archive"); if (!this.fs.delete(filePath, false)) { LOG.warn("Attempted to delete:" + filePath + ", but couldn't. Run cleaner chain and attempt to delete on next pass."); } }
diff --git a/src/main/java/edu/sc/seis/sod/TotalLoserEventCleaner.java b/src/main/java/edu/sc/seis/sod/TotalLoserEventCleaner.java index cf12e7295..1db11a9a3 100644 --- a/src/main/java/edu/sc/seis/sod/TotalLoserEventCleaner.java +++ b/src/main/java/edu/sc/seis/sod/TotalLoserEventCleaner.java @@ -1,64 +1,64 @@ package edu.sc.seis.sod; import java.util.Iterator; import java.util.TimerTask; import org.hibernate.Query; import edu.iris.Fissures.model.MicroSecondDate; import edu.iris.Fissures.model.TimeInterval; import edu.sc.seis.fissuresUtil.chooser.ClockUtil; import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler; import edu.sc.seis.sod.hibernate.StatefulEvent; import edu.sc.seis.sod.hibernate.StatefulEventDB; /** * This task runs immediately on instantiation and then once a week after that. * It removes all events that were failed in the eventArm by a subsetter from * the database on each run. * * @author groves * * Created on Dec 28, 2006 */ public class TotalLoserEventCleaner extends TimerTask { public TotalLoserEventCleaner(TimeInterval lag) { this.lagInterval = lag; eventdb = StatefulEventDB.getSingleton(); // Timer t = new Timer(true); // t.schedule(this, 0, ONE_WEEK); } public void run() { try { logger.debug("Working"); MicroSecondDate ageAgo = ClockUtil.now().subtract(lagInterval); - Query q = eventdb.getSession().createQuery(" from "+StatefulEvent.class.getName()+" e where e.statusAsShort = 258 and e.preferred.originTime.time < :ageAgo"); + Query q = eventdb.getSession().createQuery(" from "+StatefulEvent.class.getName()+" e where e.status.standingint = 2 and e.preferred.originTime.time < :ageAgo"); q.setTimestamp("ageAgo", ageAgo.getTimestamp()); Iterator<StatefulEvent> it = q.iterate(); int counter=0; while(it.hasNext()) { StatefulEvent se = it.next(); eventdb.getSession().delete(se); counter++; } eventdb.commit(); logger.debug("Done, deleted "+counter+" events."); } catch(Throwable e) { try { eventdb.rollback(); } catch(Throwable e1) { GlobalExceptionHandler.handle(e1); } GlobalExceptionHandler.handle(e); } } TimeInterval lagInterval ; StatefulEventDB eventdb; private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(TotalLoserEventCleaner.class); private static final long ONE_WEEK = 7 * 24 * 60 * 60 * 1000; }
true
true
public void run() { try { logger.debug("Working"); MicroSecondDate ageAgo = ClockUtil.now().subtract(lagInterval); Query q = eventdb.getSession().createQuery(" from "+StatefulEvent.class.getName()+" e where e.statusAsShort = 258 and e.preferred.originTime.time < :ageAgo"); q.setTimestamp("ageAgo", ageAgo.getTimestamp()); Iterator<StatefulEvent> it = q.iterate(); int counter=0; while(it.hasNext()) { StatefulEvent se = it.next(); eventdb.getSession().delete(se); counter++; } eventdb.commit(); logger.debug("Done, deleted "+counter+" events."); } catch(Throwable e) { try { eventdb.rollback(); } catch(Throwable e1) { GlobalExceptionHandler.handle(e1); } GlobalExceptionHandler.handle(e); } }
public void run() { try { logger.debug("Working"); MicroSecondDate ageAgo = ClockUtil.now().subtract(lagInterval); Query q = eventdb.getSession().createQuery(" from "+StatefulEvent.class.getName()+" e where e.status.standingint = 2 and e.preferred.originTime.time < :ageAgo"); q.setTimestamp("ageAgo", ageAgo.getTimestamp()); Iterator<StatefulEvent> it = q.iterate(); int counter=0; while(it.hasNext()) { StatefulEvent se = it.next(); eventdb.getSession().delete(se); counter++; } eventdb.commit(); logger.debug("Done, deleted "+counter+" events."); } catch(Throwable e) { try { eventdb.rollback(); } catch(Throwable e1) { GlobalExceptionHandler.handle(e1); } GlobalExceptionHandler.handle(e); } }
diff --git a/src/main/java/com/dacklabs/spookyaction/client/command/KeyToCommandConverter.java b/src/main/java/com/dacklabs/spookyaction/client/command/KeyToCommandConverter.java index 6fe7826..fd0d98f 100755 --- a/src/main/java/com/dacklabs/spookyaction/client/command/KeyToCommandConverter.java +++ b/src/main/java/com/dacklabs/spookyaction/client/command/KeyToCommandConverter.java @@ -1,111 +1,111 @@ package com.dacklabs.spookyaction.client.command; import com.dacklabs.spookyaction.client.editor.EditorEventHandler; import com.dacklabs.spookyaction.shared.Command; import com.dacklabs.spookyaction.shared.Command.CommandType; import com.dacklabs.spookyaction.shared.EditingSurface; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyEvent; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; /** * Converts User keystrokes into {@link Command} objects for syncing with the server. * * @author "David Ackerman ([email protected])" */ public class KeyToCommandConverter implements EditorEventHandler { private final EventBus eventBus; private EditingSurface editingSurface; @Inject public KeyToCommandConverter(EventBus eventBus) { this.eventBus = eventBus; } public void setEditor(EditingSurface editor) { editingSurface = editor; editingSurface.setEditorEventHandler(this); } @Override public void onClick(int lineNumber, int cursorPosition, ClickEvent event) { } @Override public void onKeyPress(int lineNumber, int cursorPosition, KeyPressEvent event) { char charCode = event.getCharCode(); if (!typeableCharacter(charCode)) { return; } Command.Builder builder = Command.builder(); builder.ofType(CommandType.KEY); builder.repeatedTimes(1); builder.withOffset(cursorPosition); builder.onLine(lineNumber); builder.withData(String.valueOf(charCode)); fireCommandEvent(event, builder); } private boolean typeableCharacter(char charCode) { // upper & lower case, numbers, special characters, and space. if (charCode >= ' ' && charCode <= '~') { return true; } else { return false; } } @Override public void onKeyUp(int lineNumber, int cursorPosition, KeyUpEvent event) { Command.Builder builder = Command.builder(); switch (event.getNativeKeyCode()) { case KeyCodes.KEY_BACKSPACE: if (cursorPosition <= 0) { return; } event.stopPropagation(); - builder.withOffset(cursorPosition); + builder.withOffset(cursorPosition + 1); // after key up, the cursor has already moved. builder.onLine(lineNumber); builder.ofType(CommandType.BACKSPACE); event.preventDefault(); event.stopPropagation(); fireCommandEvent(event, builder); return; } } @Override public void onKeyDown(int lineNumber, int cursorPosition, KeyDownEvent event) { Command.Builder builder = Command.builder(); switch (event.getNativeKeyCode()) { case KeyCodes.KEY_ENTER: builder.withOffset(cursorPosition); builder.onLine(lineNumber); builder.ofType(CommandType.NEWLINE); fireCommandEvent(event, builder); return; } } /** * Fires a command event and prevents any other events from propagating. */ private void fireCommandEvent(KeyEvent<?> event, Command.Builder builder) { event.stopPropagation(); event.preventDefault(); eventBus.fireEvent(new CommandEvent(builder.build())); } }
true
true
public void onKeyUp(int lineNumber, int cursorPosition, KeyUpEvent event) { Command.Builder builder = Command.builder(); switch (event.getNativeKeyCode()) { case KeyCodes.KEY_BACKSPACE: if (cursorPosition <= 0) { return; } event.stopPropagation(); builder.withOffset(cursorPosition); builder.onLine(lineNumber); builder.ofType(CommandType.BACKSPACE); event.preventDefault(); event.stopPropagation(); fireCommandEvent(event, builder); return; } }
public void onKeyUp(int lineNumber, int cursorPosition, KeyUpEvent event) { Command.Builder builder = Command.builder(); switch (event.getNativeKeyCode()) { case KeyCodes.KEY_BACKSPACE: if (cursorPosition <= 0) { return; } event.stopPropagation(); builder.withOffset(cursorPosition + 1); // after key up, the cursor has already moved. builder.onLine(lineNumber); builder.ofType(CommandType.BACKSPACE); event.preventDefault(); event.stopPropagation(); fireCommandEvent(event, builder); return; } }
diff --git a/core/src/org/riotfamily/core/dao/InMemoryRiotDao.java b/core/src/org/riotfamily/core/dao/InMemoryRiotDao.java index d5a5788c6..3ee29a7d5 100644 --- a/core/src/org/riotfamily/core/dao/InMemoryRiotDao.java +++ b/core/src/org/riotfamily/core/dao/InMemoryRiotDao.java @@ -1,125 +1,125 @@ /* 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.riotfamily.core.dao; import java.util.ArrayList; import java.util.Collection; import org.riotfamily.common.beans.property.PropertyUtils; import org.riotfamily.common.util.Generics; import org.springframework.beans.PropertyAccessor; import org.springframework.beans.support.PropertyComparator; import org.springframework.dao.DataAccessException; import org.springframework.dao.RecoverableDataAccessException; import org.springframework.util.StringUtils; public abstract class InMemoryRiotDao extends RiotDaoAdapter implements Sortable, Searchable { private String[] searchableProperties; public void setSearch(String search) { searchableProperties = StringUtils.tokenizeToStringArray(search, " ,\t\r\n"); } public String[] getSearchableProperties() { return searchableProperties; } public boolean canSortBy(String property) { return true; } @Override public int getListSize(Object parent, ListParams params) throws DataAccessException { try { return listInternal(parent).size(); } catch (Exception e) { throw new RecoverableDataAccessException(e.getMessage(), e); } } @Override public Collection<?> list(Object parent, ListParams params) throws DataAccessException { try { Collection<?> items = listInternal(parent); ArrayList<Object> list = Generics.newArrayList(items.size()); for (Object item : items) { if (filterMatches(item, params) && searchMatches(item, params)) { list.add(item); } } if (params.getOrder() != null && params.getOrder().size() > 0) { Order order = params.getOrder().get(0); PropertyComparator.sort(list, order); } if (params.getPageSize() > 0) { int end = params.getOffset() + params.getPageSize(); - if (end >= list.size()) { - end = list.size() - 1; + if (end > list.size()) { + end = list.size(); } return list.subList(params.getOffset(), end); } return list; } catch (Exception e) { throw new RecoverableDataAccessException(e.getMessage(), e); } } protected boolean filterMatches(Object item, ListParams params) { if (params.getFilteredProperties() != null) { PropertyAccessor itemAccessor = PropertyUtils.createAccessor(item); PropertyAccessor filterAccessor = PropertyUtils.createAccessor(params.getFilter()); for (String prop : params.getFilteredProperties()) { Object filterValue = filterAccessor.getPropertyValue(prop); if (filterValue != null) { Object itemValue = itemAccessor.getPropertyValue(prop); if (itemValue instanceof Collection<?>) { Collection<?> c = (Collection<?>) itemValue; if (!c.contains(filterValue)) { return false; } } else if (!filterValue.equals(itemValue)) { return false; } } } } return true; } protected boolean searchMatches(Object item, ListParams params) { if (params.getSearch() == null) { return true; } PropertyAccessor itemAccessor = PropertyUtils.createAccessor(item); for (String prop : getSearchableProperties()) { Object itemValue = itemAccessor.getPropertyValue(prop); if (itemValue != null && itemValue.toString().indexOf(params.getSearch()) >= 0) { return true; } } return false; } protected abstract Collection<?> listInternal(Object parent) throws Exception; }
true
true
public Collection<?> list(Object parent, ListParams params) throws DataAccessException { try { Collection<?> items = listInternal(parent); ArrayList<Object> list = Generics.newArrayList(items.size()); for (Object item : items) { if (filterMatches(item, params) && searchMatches(item, params)) { list.add(item); } } if (params.getOrder() != null && params.getOrder().size() > 0) { Order order = params.getOrder().get(0); PropertyComparator.sort(list, order); } if (params.getPageSize() > 0) { int end = params.getOffset() + params.getPageSize(); if (end >= list.size()) { end = list.size() - 1; } return list.subList(params.getOffset(), end); } return list; } catch (Exception e) { throw new RecoverableDataAccessException(e.getMessage(), e); } }
public Collection<?> list(Object parent, ListParams params) throws DataAccessException { try { Collection<?> items = listInternal(parent); ArrayList<Object> list = Generics.newArrayList(items.size()); for (Object item : items) { if (filterMatches(item, params) && searchMatches(item, params)) { list.add(item); } } if (params.getOrder() != null && params.getOrder().size() > 0) { Order order = params.getOrder().get(0); PropertyComparator.sort(list, order); } if (params.getPageSize() > 0) { int end = params.getOffset() + params.getPageSize(); if (end > list.size()) { end = list.size(); } return list.subList(params.getOffset(), end); } return list; } catch (Exception e) { throw new RecoverableDataAccessException(e.getMessage(), e); } }
diff --git a/src/main/java/org/weymouth/demo/Main.java b/src/main/java/org/weymouth/demo/Main.java index 14a71e7..cabf671 100755 --- a/src/main/java/org/weymouth/demo/Main.java +++ b/src/main/java/org/weymouth/demo/Main.java @@ -1,29 +1,28 @@ package org.weymouth.demo; import org.weymouth.demo.model.Data; import org.weymouth.demo.model.Results; import org.weymouth.demo.work.Input; import org.weymouth.demo.work.Output; import org.weymouth.demo.work.Process; public class Main { /** * @param args */ public static void main(String[] args) { Input in = new Input(); Process worker = new Process(); Output out = new Output(); Data data; while ((data = in.next()) != null){ Results r = worker.process(data); out.report(r); - junk; } } }
true
true
public static void main(String[] args) { Input in = new Input(); Process worker = new Process(); Output out = new Output(); Data data; while ((data = in.next()) != null){ Results r = worker.process(data); out.report(r); junk; } }
public static void main(String[] args) { Input in = new Input(); Process worker = new Process(); Output out = new Output(); Data data; while ((data = in.next()) != null){ Results r = worker.process(data); out.report(r); } }
diff --git a/java/src/com/google/template/soy/data/SoyData.java b/java/src/com/google/template/soy/data/SoyData.java index 35198e5..f902194 100644 --- a/java/src/com/google/template/soy/data/SoyData.java +++ b/java/src/com/google/template/soy/data/SoyData.java @@ -1,171 +1,174 @@ /* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.data; import com.google.template.soy.data.restricted.BooleanData; import com.google.template.soy.data.restricted.FloatData; import com.google.template.soy.data.restricted.IntegerData; import com.google.template.soy.data.restricted.NullData; import com.google.template.soy.data.restricted.StringData; import java.util.List; import java.util.Map; /** * Abstract base class for all nodes in a Soy data tree. * * @author Kai Huang */ public abstract class SoyData { /** * Creation function for creating a SoyData object out of any existing primitive, data object, or * data structure. * * <p> Important: Avoid using this function if you know the type of the object at compile time. * For example, if the object is a primitive, it can be passed directly to methods such as * {@code SoyMapData.put()} or {@code SoyListData.add()}. If the object is a Map or an Iterable, * you can directly create the equivalent SoyData object using the constructor of * {@code SoyMapData} or {@code SoyListData}. * * <p> If the given object is already a SoyData object, then it is simply returned. * Otherwise a new SoyData object will be created that is equivalent to the given primitive, data * object, or data structure (even if the given object is null!). * * <p> Note that in order for the conversion process to succeed, the given data structure must * correspond to a valid SoyData tree. Some requirements include: * (a) all Maps within your data structure must have string keys that are identifiers, * (b) all non-leaf nodes must be Maps or Lists, * (c) all leaf nodes must be null, boolean, int, double, or String (corresponding to Soy * primitive data types null, boolean, integer, float, string). * * @param obj The existing object or data structure to convert. * @return A SoyData object or tree that corresponds to the given object. * @throws SoyDataException If the given object cannot be converted to SoyData. */ public static SoyData createFromExistingData(Object obj) { if (obj == null) { return NullData.INSTANCE; } else if (obj instanceof SoyData) { return (SoyData) obj; } else if (obj instanceof String) { return new StringData((String) obj); } else if (obj instanceof Boolean) { return new BooleanData((Boolean) obj); } else if (obj instanceof Integer) { return new IntegerData((Integer) obj); - } else if (obj instanceof Double) { - return new FloatData((Double) obj); } else if (obj instanceof Map) { @SuppressWarnings("unchecked") Map<String, ?> objCast = (Map<String, ?>) obj; return new SoyMapData(objCast); } else if (obj instanceof List) { return new SoyListData((List<?>) obj); + } else if (obj instanceof Double) { + return new FloatData((Double) obj); + } else if (obj instanceof Float) { + // Automatically convert float to double. + return new FloatData((Float) obj); } else { throw new SoyDataException( "Attempting to convert unrecognized object to Soy data (object type " + obj.getClass().getSimpleName() + ")."); } } /** * Converts this data object into a string (e.g. when used in a string context). * @return The value of this data object if coerced into a string. */ @Override public abstract String toString(); /** * Converts this data object into a boolean (e.g. when used in a boolean context). In other words, * this method tells whether this object is truthy. * @return The value of this data object if coerced into a boolean. I.e. true if this object is * truthy, false if this object is falsy. */ public abstract boolean toBoolean(); /** * Compares this data object against another for equality in the sense of the operator '==' for * Soy expressions. * * @param other The other data object to compare against. * @return True if the two objects are equal. */ @Override public abstract boolean equals(Object other); /** * Precondition: Only call this method if you know that this SoyData object is a boolean. * This method gets the boolean value of this boolean object. * @return The boolean value of this boolean object. * @throws SoyDataException If this object is not actually a boolean. */ public boolean booleanValue() { throw new SoyDataException("Non-boolean found when expecting boolean value."); } /** * Precondition: Only call this method if you know that this SoyData object is an integer. * This method gets the integer value of this integer object. * @return The integer value of this integer object. * @throws SoyDataException If this object is not actually an integer. */ public int integerValue() { throw new SoyDataException("Non-integer found when expecting integer value."); } /** * Precondition: Only call this method if you know that this SoyData object is a float. * This method gets the float value of this float object. * @return The float value of this float object. * @throws SoyDataException If this object is not actually a float. */ public double floatValue() { throw new SoyDataException("Non-float found when expecting float value."); } /** * Precondition: Only call this method if you know that this SoyData object is a number. * This method gets the float value of this number object (converting integer to float if * necessary). * @return The float value of this number object. * @throws SoyDataException If this object is not actually a number. */ public double numberValue() { throw new SoyDataException("Non-number found when expecting number value."); } /** * Precondition: Only call this method if you know that this SoyData object is a string. * This method gets the string value of this string object. * @return The string value of this string object. * @throws SoyDataException If this object is not actually a string. */ public String stringValue() { throw new SoyDataException("Non-string found when expecting string value."); } }
false
true
public static SoyData createFromExistingData(Object obj) { if (obj == null) { return NullData.INSTANCE; } else if (obj instanceof SoyData) { return (SoyData) obj; } else if (obj instanceof String) { return new StringData((String) obj); } else if (obj instanceof Boolean) { return new BooleanData((Boolean) obj); } else if (obj instanceof Integer) { return new IntegerData((Integer) obj); } else if (obj instanceof Double) { return new FloatData((Double) obj); } else if (obj instanceof Map) { @SuppressWarnings("unchecked") Map<String, ?> objCast = (Map<String, ?>) obj; return new SoyMapData(objCast); } else if (obj instanceof List) { return new SoyListData((List<?>) obj); } else { throw new SoyDataException( "Attempting to convert unrecognized object to Soy data (object type " + obj.getClass().getSimpleName() + ")."); } }
public static SoyData createFromExistingData(Object obj) { if (obj == null) { return NullData.INSTANCE; } else if (obj instanceof SoyData) { return (SoyData) obj; } else if (obj instanceof String) { return new StringData((String) obj); } else if (obj instanceof Boolean) { return new BooleanData((Boolean) obj); } else if (obj instanceof Integer) { return new IntegerData((Integer) obj); } else if (obj instanceof Map) { @SuppressWarnings("unchecked") Map<String, ?> objCast = (Map<String, ?>) obj; return new SoyMapData(objCast); } else if (obj instanceof List) { return new SoyListData((List<?>) obj); } else if (obj instanceof Double) { return new FloatData((Double) obj); } else if (obj instanceof Float) { // Automatically convert float to double. return new FloatData((Float) obj); } else { throw new SoyDataException( "Attempting to convert unrecognized object to Soy data (object type " + obj.getClass().getSimpleName() + ")."); } }
diff --git a/src/main/java/me/desht/scrollingmenusign/spout/SpoutViewPopup.java b/src/main/java/me/desht/scrollingmenusign/spout/SpoutViewPopup.java index e9f9358..f1a7688 100644 --- a/src/main/java/me/desht/scrollingmenusign/spout/SpoutViewPopup.java +++ b/src/main/java/me/desht/scrollingmenusign/spout/SpoutViewPopup.java @@ -1,96 +1,96 @@ package me.desht.scrollingmenusign.spout; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import me.desht.scrollingmenusign.ScrollingMenuSign; import me.desht.scrollingmenusign.util.MiscUtil; import me.desht.scrollingmenusign.views.SMSSpoutView; import org.getspout.spoutapi.gui.GenericLabel; import org.getspout.spoutapi.gui.GenericPopup; import org.getspout.spoutapi.gui.GenericTexture; import org.getspout.spoutapi.gui.Label; import org.getspout.spoutapi.gui.RenderPriority; import org.getspout.spoutapi.gui.Screen; import org.getspout.spoutapi.gui.Texture; import org.getspout.spoutapi.player.SpoutPlayer; public class SpoutViewPopup extends GenericPopup { private static final int LIST_WIDTH = 200; private static final int TITLE_HEIGHT = 15; private static final int TITLE_WIDTH = 100; private SpoutPlayer sp; private SMSSpoutView view; private boolean poppedUp; private Label title; private Texture texture; private SMSListWidget listWidget; public SpoutViewPopup(SpoutPlayer sp, SMSSpoutView view) { this.sp = sp; this.view = view; this.poppedUp = false; Screen mainScreen = sp.getMainScreen(); title = new GenericLabel(view.getMenu().getTitle()); title.setX((mainScreen.getWidth() - TITLE_WIDTH) / 2).setY(5).setWidth(TITLE_WIDTH).setHeight(TITLE_HEIGHT); title.setAuto(false ); int listX = (mainScreen.getWidth() - LIST_WIDTH) / 2; int listY = 5 + 2 + TITLE_HEIGHT; String textureName = view.getAttributeAsString(SMSSpoutView.TEXTURE); if (textureName != null && !textureName.isEmpty()) { try { URL textureURL = ScrollingMenuSign.makeImageURL(textureName); - texture = new GenericTexture(view.getAttributeAsString(textureURL.toString())); + texture = new GenericTexture(textureURL.toString()); texture.setDrawAlphaChannel(true); texture.setX(listX).setY(listY).setWidth(LIST_WIDTH).setHeight(LIST_WIDTH); texture.setPriority(RenderPriority.Highest); // put it behind the list widget } catch (MalformedURLException e) { MiscUtil.log(Level.WARNING, "malformed texture URL for spout view " + view.getName() + ": " + e.getMessage()); } } listWidget = new SMSListWidget(sp, view); listWidget.setX(listX).setY(listY).setWidth(LIST_WIDTH).setHeight(LIST_WIDTH); this.attachWidget(ScrollingMenuSign.getInstance(), title); this.attachWidget(ScrollingMenuSign.getInstance(), texture); this.attachWidget(ScrollingMenuSign.getInstance(), listWidget); } public SMSSpoutView getView() { return view; } public boolean isPoppedUp() { return poppedUp; } public void repaint() { title.setText(view.getMenu().getTitle()); texture.setUrl(view.getAttributeAsString(SMSSpoutView.TEXTURE)); listWidget.repaint(); } public void scrollTo(int scrollPos) { listWidget.ignoreNextSelection(true); listWidget.setSelection(scrollPos - 1); // System.out.println("scroll to " + scrollPos + " = " + listWidget.getSelectedItem().getTitle()); } public void popup() { poppedUp = true; sp.getMainScreen().attachPopupScreen(this); } public void popdown() { poppedUp = false; sp.getMainScreen().closePopup(); } }
true
true
public SpoutViewPopup(SpoutPlayer sp, SMSSpoutView view) { this.sp = sp; this.view = view; this.poppedUp = false; Screen mainScreen = sp.getMainScreen(); title = new GenericLabel(view.getMenu().getTitle()); title.setX((mainScreen.getWidth() - TITLE_WIDTH) / 2).setY(5).setWidth(TITLE_WIDTH).setHeight(TITLE_HEIGHT); title.setAuto(false ); int listX = (mainScreen.getWidth() - LIST_WIDTH) / 2; int listY = 5 + 2 + TITLE_HEIGHT; String textureName = view.getAttributeAsString(SMSSpoutView.TEXTURE); if (textureName != null && !textureName.isEmpty()) { try { URL textureURL = ScrollingMenuSign.makeImageURL(textureName); texture = new GenericTexture(view.getAttributeAsString(textureURL.toString())); texture.setDrawAlphaChannel(true); texture.setX(listX).setY(listY).setWidth(LIST_WIDTH).setHeight(LIST_WIDTH); texture.setPriority(RenderPriority.Highest); // put it behind the list widget } catch (MalformedURLException e) { MiscUtil.log(Level.WARNING, "malformed texture URL for spout view " + view.getName() + ": " + e.getMessage()); } } listWidget = new SMSListWidget(sp, view); listWidget.setX(listX).setY(listY).setWidth(LIST_WIDTH).setHeight(LIST_WIDTH); this.attachWidget(ScrollingMenuSign.getInstance(), title); this.attachWidget(ScrollingMenuSign.getInstance(), texture); this.attachWidget(ScrollingMenuSign.getInstance(), listWidget); }
public SpoutViewPopup(SpoutPlayer sp, SMSSpoutView view) { this.sp = sp; this.view = view; this.poppedUp = false; Screen mainScreen = sp.getMainScreen(); title = new GenericLabel(view.getMenu().getTitle()); title.setX((mainScreen.getWidth() - TITLE_WIDTH) / 2).setY(5).setWidth(TITLE_WIDTH).setHeight(TITLE_HEIGHT); title.setAuto(false ); int listX = (mainScreen.getWidth() - LIST_WIDTH) / 2; int listY = 5 + 2 + TITLE_HEIGHT; String textureName = view.getAttributeAsString(SMSSpoutView.TEXTURE); if (textureName != null && !textureName.isEmpty()) { try { URL textureURL = ScrollingMenuSign.makeImageURL(textureName); texture = new GenericTexture(textureURL.toString()); texture.setDrawAlphaChannel(true); texture.setX(listX).setY(listY).setWidth(LIST_WIDTH).setHeight(LIST_WIDTH); texture.setPriority(RenderPriority.Highest); // put it behind the list widget } catch (MalformedURLException e) { MiscUtil.log(Level.WARNING, "malformed texture URL for spout view " + view.getName() + ": " + e.getMessage()); } } listWidget = new SMSListWidget(sp, view); listWidget.setX(listX).setY(listY).setWidth(LIST_WIDTH).setHeight(LIST_WIDTH); this.attachWidget(ScrollingMenuSign.getInstance(), title); this.attachWidget(ScrollingMenuSign.getInstance(), texture); this.attachWidget(ScrollingMenuSign.getInstance(), listWidget); }
diff --git a/src/main/java/com/concursive/connect/web/modules/admin/actions/AdminSync.java b/src/main/java/com/concursive/connect/web/modules/admin/actions/AdminSync.java index cbadaae..e270269 100644 --- a/src/main/java/com/concursive/connect/web/modules/admin/actions/AdminSync.java +++ b/src/main/java/com/concursive/connect/web/modules/admin/actions/AdminSync.java @@ -1,145 +1,150 @@ /* * ConcourseConnect * Copyright 2009 Concursive Corporation * http://www.concursive.com * * This file is part of ConcourseConnect, an open source social business * software and community platform. * * Concursive ConcourseConnect 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, version 3 of the License. * * Under the terms of the GNU Affero General Public License you must release the * complete source code for any application that uses any part of ConcourseConnect * (system header files and libraries used by the operating system are excluded). * These terms must be included in any work that has ConcourseConnect components. * If you are developing and distributing open source applications under the * GNU Affero General Public License, then you are free to use ConcourseConnect * under the GNU Affero General Public License. * * If you are deploying a web site in which users interact with any portion of * ConcourseConnect over a network, the complete source code changes must be made * available. For example, include a link to the source archive directly from * your web site. * * For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their * products, and do not license and distribute their source code under the GNU * Affero General Public License, Concursive provides a flexible commercial * license. * * To anyone in doubt, we recommend the commercial license. Our commercial license * is competitively priced and will eliminate any confusion about how * ConcourseConnect can be used and distributed. * * ConcourseConnect 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 ConcourseConnect. If not, see <http://www.gnu.org/licenses/>. * * Attribution Notice: ConcourseConnect is an Original Work of software created * by Concursive Corporation */ package com.concursive.connect.web.modules.admin.actions; import com.concursive.commons.web.mvc.actions.ActionContext; import com.concursive.connect.Constants; import com.concursive.connect.config.ApplicationPrefs; import com.concursive.connect.web.controller.actions.GenericAction; import org.aspcfs.utils.StringUtils; import org.quartz.Scheduler; import java.util.Vector; /** * Actions for the administration module * * @author Kailash Bhoopalam * @created June 18, 2009 */ public final class AdminSync extends GenericAction { /** * Action to prepare a list of Admin options * * @param context Description of the Parameter * @return Description of the Return Value */ public String executeCommandDefault(ActionContext context) { if (!getUser(context).getAccessAdmin()) { return "PermissionError"; } try { Scheduler scheduler = (Scheduler) context.getServletContext().getAttribute(Constants.SCHEDULER); context.getRequest().setAttribute("syncStatus", scheduler.getContext().get("CRMSyncStatus")); } catch (Exception e) { context.getRequest().setAttribute("Error", e); return ("SystemError"); } finally { } return "DefaultOK"; } public String executeCommandStartSync(ActionContext context) { if (!getUser(context).getAccessAdmin()) { return "PermissionError"; } try { Scheduler scheduler = (Scheduler) context.getServletContext().getAttribute(Constants.SCHEDULER); Vector syncStatus = (Vector) scheduler.getContext().get("CRMSyncStatus"); String startSync = context.getRequest().getParameter("startSync"); if ("true".equals(startSync)){ if (syncStatus != null && syncStatus.size() == 0) { // Trigger the sync job triggerJob(context, "syncSystem"); } else { // Do nothing as a sync is already in progress. } } String saveConnectionDetails = context.getRequest().getParameter("saveConnectionDetails"); if ("true".equals(saveConnectionDetails)){ ApplicationPrefs prefs = this.getApplicationPrefs(context); String serverURL = context.getRequest().getParameter("serverURL"); String apiClientId = context.getRequest().getParameter("apiClientId"); String apiCode = context.getRequest().getParameter("apiCode"); - String domainAndPort = serverURL.substring(7).split("/")[0]; + String domainAndPort = ""; + if (serverURL.indexOf("http://") != -1){ + domainAndPort = serverURL.substring(7).split("/")[0]; + } else if (serverURL.indexOf("https://") != -1){ + domainAndPort = serverURL.substring(8).split("/")[0]; + } String domain = domainAndPort; if (domainAndPort.indexOf(":") != -1){ domain = domainAndPort.split(":")[0]; } if (StringUtils.hasText(serverURL) && StringUtils.hasText(domain) && StringUtils.hasText(apiClientId) && StringUtils.hasText(apiCode)){ prefs.add("CONCURSIVE_CRM.SERVER", serverURL); prefs.add("CONCURSIVE_CRM.ID", domain); prefs.add("CONCURSIVE_CRM.CODE", apiCode); prefs.add("CONCURSIVE_CRM.CLIENT", apiClientId); prefs.save(); triggerJob(context, "syncSystem"); } else { context.getRequest().setAttribute("serverURL", serverURL); context.getRequest().setAttribute("apiClientId", apiClientId); context.getRequest().setAttribute("apiCode", apiCode); } } } catch (Exception e) { context.getRequest().setAttribute("Error", e); return ("SystemError"); } finally { } return "StartSyncOK"; } }
true
true
public String executeCommandStartSync(ActionContext context) { if (!getUser(context).getAccessAdmin()) { return "PermissionError"; } try { Scheduler scheduler = (Scheduler) context.getServletContext().getAttribute(Constants.SCHEDULER); Vector syncStatus = (Vector) scheduler.getContext().get("CRMSyncStatus"); String startSync = context.getRequest().getParameter("startSync"); if ("true".equals(startSync)){ if (syncStatus != null && syncStatus.size() == 0) { // Trigger the sync job triggerJob(context, "syncSystem"); } else { // Do nothing as a sync is already in progress. } } String saveConnectionDetails = context.getRequest().getParameter("saveConnectionDetails"); if ("true".equals(saveConnectionDetails)){ ApplicationPrefs prefs = this.getApplicationPrefs(context); String serverURL = context.getRequest().getParameter("serverURL"); String apiClientId = context.getRequest().getParameter("apiClientId"); String apiCode = context.getRequest().getParameter("apiCode"); String domainAndPort = serverURL.substring(7).split("/")[0]; String domain = domainAndPort; if (domainAndPort.indexOf(":") != -1){ domain = domainAndPort.split(":")[0]; } if (StringUtils.hasText(serverURL) && StringUtils.hasText(domain) && StringUtils.hasText(apiClientId) && StringUtils.hasText(apiCode)){ prefs.add("CONCURSIVE_CRM.SERVER", serverURL); prefs.add("CONCURSIVE_CRM.ID", domain); prefs.add("CONCURSIVE_CRM.CODE", apiCode); prefs.add("CONCURSIVE_CRM.CLIENT", apiClientId); prefs.save(); triggerJob(context, "syncSystem"); } else { context.getRequest().setAttribute("serverURL", serverURL); context.getRequest().setAttribute("apiClientId", apiClientId); context.getRequest().setAttribute("apiCode", apiCode); } } } catch (Exception e) { context.getRequest().setAttribute("Error", e); return ("SystemError"); } finally { } return "StartSyncOK"; }
public String executeCommandStartSync(ActionContext context) { if (!getUser(context).getAccessAdmin()) { return "PermissionError"; } try { Scheduler scheduler = (Scheduler) context.getServletContext().getAttribute(Constants.SCHEDULER); Vector syncStatus = (Vector) scheduler.getContext().get("CRMSyncStatus"); String startSync = context.getRequest().getParameter("startSync"); if ("true".equals(startSync)){ if (syncStatus != null && syncStatus.size() == 0) { // Trigger the sync job triggerJob(context, "syncSystem"); } else { // Do nothing as a sync is already in progress. } } String saveConnectionDetails = context.getRequest().getParameter("saveConnectionDetails"); if ("true".equals(saveConnectionDetails)){ ApplicationPrefs prefs = this.getApplicationPrefs(context); String serverURL = context.getRequest().getParameter("serverURL"); String apiClientId = context.getRequest().getParameter("apiClientId"); String apiCode = context.getRequest().getParameter("apiCode"); String domainAndPort = ""; if (serverURL.indexOf("http://") != -1){ domainAndPort = serverURL.substring(7).split("/")[0]; } else if (serverURL.indexOf("https://") != -1){ domainAndPort = serverURL.substring(8).split("/")[0]; } String domain = domainAndPort; if (domainAndPort.indexOf(":") != -1){ domain = domainAndPort.split(":")[0]; } if (StringUtils.hasText(serverURL) && StringUtils.hasText(domain) && StringUtils.hasText(apiClientId) && StringUtils.hasText(apiCode)){ prefs.add("CONCURSIVE_CRM.SERVER", serverURL); prefs.add("CONCURSIVE_CRM.ID", domain); prefs.add("CONCURSIVE_CRM.CODE", apiCode); prefs.add("CONCURSIVE_CRM.CLIENT", apiClientId); prefs.save(); triggerJob(context, "syncSystem"); } else { context.getRequest().setAttribute("serverURL", serverURL); context.getRequest().setAttribute("apiClientId", apiClientId); context.getRequest().setAttribute("apiCode", apiCode); } } } catch (Exception e) { context.getRequest().setAttribute("Error", e); return ("SystemError"); } finally { } return "StartSyncOK"; }
diff --git a/src/worker/GeneSetMerger.java b/src/worker/GeneSetMerger.java index 0ea44bb..621fcdd 100644 --- a/src/worker/GeneSetMerger.java +++ b/src/worker/GeneSetMerger.java @@ -1,266 +1,267 @@ package worker; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import obj.GeneSet; import obj.ValIdx; public class GeneSetMerger extends DistributedWorker{ ArrayList<GeneSet> allGeneSets; public static int mergeCount = 0; public static int minSize = 0; public GeneSetMerger(int id, int totalComputers, long jobID){ super(id, totalComputers, jobID); allGeneSets = new ArrayList<GeneSet>(); } public void mergeWeightedGeneSets(String path, int numFiles, float precision, boolean finalOutput) throws IOException{ if(!path.endsWith("/")) path = path + "/"; int start = id * numFiles/totalComputers; int end = (id+1) * numFiles/totalComputers; BufferedReader br; ArrayList<float[]> wVecs = new ArrayList<float[]>(); ArrayList<ArrayList<Integer>> basins = new ArrayList<ArrayList<Integer>>(); ArrayList<String> chrs = new ArrayList<String>(); System.out.println("Processing file " + start + " to file " + end ); for(int i = start; i < end; i++){ System.out.println(i); br = new BufferedReader(new FileReader(path + "caf."+ String.format("%05d", i)+".txt")); String line = br.readLine(); // Greedily merge gene set while(line != null){ String[] tokens = line.split("\t"); String tag = tokens[0]; int nt = tokens.length; int m = nt-2; float[] wvec = new float[m]; ArrayList<Integer> basin = new ArrayList<Integer>(); String[] t2 = tokens[1].split(","); int nt2 = t2.length; if(finalOutput && nt2 < 2){ + line = br.readLine(); continue; } for(int j = 0; j < nt2; j++){ basin.add(Integer.parseInt(t2[j])); } for(int j = 0; j < m; j++){ wvec[j] = Float.parseFloat(tokens[j+2]); } boolean newOne = true; int foundIdx = -1; for(int j = 0; j < wVecs.size(); j++){ if(tag.equals(chrs.get(j))){ float[] fs = wVecs.get(j); float err = Converger.calcMSE(fs, wvec, m); if(err < precision/m){ foundIdx = j; newOne = false; break; } } } if(newOne){ wVecs.add(wvec); basins.add(basin); chrs.add(tag); }else{ basins.get(foundIdx).addAll(basin); } line = br.readLine(); } br.close(); } if(finalOutput){ new File("output").mkdir(); new File("output/" + jobID).mkdir(); PrintWriter pw = new PrintWriter(new FileWriter("output/" + jobID + "/attractors.gwt")); PrintWriter pw2 = new PrintWriter(new FileWriter("output/" + jobID + "/attractees.gwt")); for(int i = 0; i < wVecs.size(); i++){ ArrayList<Integer> basin = basins.get(i); if(basin.size() < 2){ continue; } String name = "Attractor" + String.format("%05d", i); pw2.print(name + "\t" + chrs.get(i)); pw.print(name+ "\t" + chrs.get(i)); for(int j : basin){ pw2.print("\t" + j); }pw2.println(); float[] fs = wVecs.get(i); for(float f : fs){ pw.print("\t" + f); }pw.println(); } pw2.close(); pw.close(); }else{ prepare("merge" + mergeCount); PrintWriter pw = new PrintWriter(new FileWriter("tmp/" + jobID + "/merge" + mergeCount+ "/caf."+ String.format("%05d", id)+".txt")); for(int i = 0; i < wVecs.size(); i++){ pw.print(chrs.get(i)); ArrayList<Integer> basin = basins.get(i); int k = basin.size(); for(int j = 0; j < k; j++){ if(j == 0){ pw.print("\t" + basin.get(j)); }else{ pw.print("," + basin.get(j)); } } float[] fs = wVecs.get(i); for(float f : fs){ pw.print("\t" + f); } pw.println(); } pw.close(); mergeCount++; } } public void mergeGeneSets(String path, int numFiles, boolean finalOutput) throws IOException{ if(!path.endsWith("/")) path = path + "/"; int start = id * numFiles/totalComputers; int end = (id+1) * numFiles/totalComputers; BufferedReader br; System.out.println("Processing file " + start + " to file " + end ); for(int i = start; i < end; i++){ System.out.println(i); br = new BufferedReader(new FileReader(path + "caf."+ String.format("%05d", i)+".txt")); String line = br.readLine(); // Greedily merge gene set while(line != null){ String[] tokens = line.split("\t"); if(!tokens[2].equals("NA")){ //first token: attractees separated by "," HashSet<Integer> attr = new HashSet<Integer>(); String[] t2 = tokens[0].split(","); for(String s: t2){ attr.add(Integer.parseInt(s)); } int nt = tokens.length; ValIdx[] geneIdx = new ValIdx[nt-2]; float[] Zs = new float[nt-2]; //int[] gIdx = new int[nt-2]; //float[] wts = new float[nt-2]; // mi with metagene int numChild = Integer.parseInt(tokens[1]); for(int j = 2; j < nt; j++){ t2 = tokens[j].split(","); geneIdx[j-2] = new ValIdx(Integer.parseInt(t2[0]), Float.parseFloat(t2[1])); Zs[j-2] = t2.length > 2 ? Float.parseFloat(t2[2]) : Float.NaN; //gIdx[j-2] = Integer.parseInt(t2[0]); //wts[j-2] = Float.parseFloat(t2[1]); } //GeneSet rookie = new GeneSet(attr,gIdx, wts, numChild); GeneSet rookie = new GeneSet(attr, geneIdx, Zs, numChild); int origSize = allGeneSets.size(); if(origSize == 0){ allGeneSets.add(rookie); }else{ boolean mergeable = false; for(int j = 0; j < origSize; j++){ GeneSet gs = allGeneSets.get(j); if(gs.equals(rookie)){ mergeable = true; gs.merge(rookie); break; } /*if(gs.merge(rookie)){ mergeable = true; break; // gene set merged }*/ } if(!mergeable){ allGeneSets.add(rookie); } } } line = br.readLine(); } br.close(); } if(finalOutput){ new File("output").mkdir(); new File("output/" + jobID).mkdir(); //new File("output/" + jobID + "/lists").mkdir(); PrintWriter pw = new PrintWriter(new FileWriter("output/" + jobID + "/attractors.gwt")); PrintWriter pw2 = new PrintWriter(new FileWriter("output/" + jobID + "/attractees.gwt")); //PrintWriter pw3 = new PrintWriter(new FileWriter("output/" + jobID + "/weights.txt")); int cnt = 0; for(GeneSet gs : allGeneSets){ //if(gs.size() >= minSize){ String name = "Attractor" + String.format("%03d", cnt); gs.sort(); //gs.calcWeight(); /*pw3.print(name + "\t" + gs.size() + ":" + gs.getAttracteeSize() + "\t"); pw3.println(gs.getWeight());*/ pw2.print(name + "\t" + gs.size() + ":" + gs.getAttracteeSize() + "\t"); pw2.println(gs.getAttractees()); pw.print(name + "\t" + gs.size() + ":" + gs.getAttracteeSize() + "\t"); if(GeneSet.hasAnnot()){ pw.println(gs.toGenes()); }else{ pw.println(gs.toProbes()); } /*PrintWriter pw4 = new PrintWriter(new FileWriter("output/" + jobID + "/lists/" + name + ".txt")); if(GeneSet.hasAnnot()){ pw4.println("Probe\tGene\tWeight"); //int[] indices = gs.getGeneIdx(); for(int i = 0; i < gs.size(); i++){ pw4.println(gs.getOnePair(i)); } }else{ pw4.println("Gene\tWeight"); for(int i = 0; i < gs.size(); i++){ pw4.println(gs.getOnePair(i)); } } pw4.close();*/ cnt++; //} } //pw3.close(); pw2.close(); pw.close(); }else{ prepare("merge" + mergeCount); PrintWriter pw = new PrintWriter(new FileWriter("tmp/" + jobID + "/merge" + mergeCount + "/caf."+ String.format("%05d", id)+".txt")); for(GeneSet gs : allGeneSets){ pw.println(gs.toString()); } pw.close(); mergeCount++; } } public void setMinSize(int minSize){ GeneSetMerger.minSize = minSize; } public static void addMergeCount(){ mergeCount++; } }
true
true
public void mergeWeightedGeneSets(String path, int numFiles, float precision, boolean finalOutput) throws IOException{ if(!path.endsWith("/")) path = path + "/"; int start = id * numFiles/totalComputers; int end = (id+1) * numFiles/totalComputers; BufferedReader br; ArrayList<float[]> wVecs = new ArrayList<float[]>(); ArrayList<ArrayList<Integer>> basins = new ArrayList<ArrayList<Integer>>(); ArrayList<String> chrs = new ArrayList<String>(); System.out.println("Processing file " + start + " to file " + end ); for(int i = start; i < end; i++){ System.out.println(i); br = new BufferedReader(new FileReader(path + "caf."+ String.format("%05d", i)+".txt")); String line = br.readLine(); // Greedily merge gene set while(line != null){ String[] tokens = line.split("\t"); String tag = tokens[0]; int nt = tokens.length; int m = nt-2; float[] wvec = new float[m]; ArrayList<Integer> basin = new ArrayList<Integer>(); String[] t2 = tokens[1].split(","); int nt2 = t2.length; if(finalOutput && nt2 < 2){ continue; } for(int j = 0; j < nt2; j++){ basin.add(Integer.parseInt(t2[j])); } for(int j = 0; j < m; j++){ wvec[j] = Float.parseFloat(tokens[j+2]); } boolean newOne = true; int foundIdx = -1; for(int j = 0; j < wVecs.size(); j++){ if(tag.equals(chrs.get(j))){ float[] fs = wVecs.get(j); float err = Converger.calcMSE(fs, wvec, m); if(err < precision/m){ foundIdx = j; newOne = false; break; } } } if(newOne){ wVecs.add(wvec); basins.add(basin); chrs.add(tag); }else{ basins.get(foundIdx).addAll(basin); } line = br.readLine(); } br.close(); } if(finalOutput){ new File("output").mkdir(); new File("output/" + jobID).mkdir(); PrintWriter pw = new PrintWriter(new FileWriter("output/" + jobID + "/attractors.gwt")); PrintWriter pw2 = new PrintWriter(new FileWriter("output/" + jobID + "/attractees.gwt")); for(int i = 0; i < wVecs.size(); i++){ ArrayList<Integer> basin = basins.get(i); if(basin.size() < 2){ continue; } String name = "Attractor" + String.format("%05d", i); pw2.print(name + "\t" + chrs.get(i)); pw.print(name+ "\t" + chrs.get(i)); for(int j : basin){ pw2.print("\t" + j); }pw2.println(); float[] fs = wVecs.get(i); for(float f : fs){ pw.print("\t" + f); }pw.println(); } pw2.close(); pw.close(); }else{ prepare("merge" + mergeCount); PrintWriter pw = new PrintWriter(new FileWriter("tmp/" + jobID + "/merge" + mergeCount+ "/caf."+ String.format("%05d", id)+".txt")); for(int i = 0; i < wVecs.size(); i++){ pw.print(chrs.get(i)); ArrayList<Integer> basin = basins.get(i); int k = basin.size(); for(int j = 0; j < k; j++){ if(j == 0){ pw.print("\t" + basin.get(j)); }else{ pw.print("," + basin.get(j)); } } float[] fs = wVecs.get(i); for(float f : fs){ pw.print("\t" + f); } pw.println(); } pw.close(); mergeCount++; } }
public void mergeWeightedGeneSets(String path, int numFiles, float precision, boolean finalOutput) throws IOException{ if(!path.endsWith("/")) path = path + "/"; int start = id * numFiles/totalComputers; int end = (id+1) * numFiles/totalComputers; BufferedReader br; ArrayList<float[]> wVecs = new ArrayList<float[]>(); ArrayList<ArrayList<Integer>> basins = new ArrayList<ArrayList<Integer>>(); ArrayList<String> chrs = new ArrayList<String>(); System.out.println("Processing file " + start + " to file " + end ); for(int i = start; i < end; i++){ System.out.println(i); br = new BufferedReader(new FileReader(path + "caf."+ String.format("%05d", i)+".txt")); String line = br.readLine(); // Greedily merge gene set while(line != null){ String[] tokens = line.split("\t"); String tag = tokens[0]; int nt = tokens.length; int m = nt-2; float[] wvec = new float[m]; ArrayList<Integer> basin = new ArrayList<Integer>(); String[] t2 = tokens[1].split(","); int nt2 = t2.length; if(finalOutput && nt2 < 2){ line = br.readLine(); continue; } for(int j = 0; j < nt2; j++){ basin.add(Integer.parseInt(t2[j])); } for(int j = 0; j < m; j++){ wvec[j] = Float.parseFloat(tokens[j+2]); } boolean newOne = true; int foundIdx = -1; for(int j = 0; j < wVecs.size(); j++){ if(tag.equals(chrs.get(j))){ float[] fs = wVecs.get(j); float err = Converger.calcMSE(fs, wvec, m); if(err < precision/m){ foundIdx = j; newOne = false; break; } } } if(newOne){ wVecs.add(wvec); basins.add(basin); chrs.add(tag); }else{ basins.get(foundIdx).addAll(basin); } line = br.readLine(); } br.close(); } if(finalOutput){ new File("output").mkdir(); new File("output/" + jobID).mkdir(); PrintWriter pw = new PrintWriter(new FileWriter("output/" + jobID + "/attractors.gwt")); PrintWriter pw2 = new PrintWriter(new FileWriter("output/" + jobID + "/attractees.gwt")); for(int i = 0; i < wVecs.size(); i++){ ArrayList<Integer> basin = basins.get(i); if(basin.size() < 2){ continue; } String name = "Attractor" + String.format("%05d", i); pw2.print(name + "\t" + chrs.get(i)); pw.print(name+ "\t" + chrs.get(i)); for(int j : basin){ pw2.print("\t" + j); }pw2.println(); float[] fs = wVecs.get(i); for(float f : fs){ pw.print("\t" + f); }pw.println(); } pw2.close(); pw.close(); }else{ prepare("merge" + mergeCount); PrintWriter pw = new PrintWriter(new FileWriter("tmp/" + jobID + "/merge" + mergeCount+ "/caf."+ String.format("%05d", id)+".txt")); for(int i = 0; i < wVecs.size(); i++){ pw.print(chrs.get(i)); ArrayList<Integer> basin = basins.get(i); int k = basin.size(); for(int j = 0; j < k; j++){ if(j == 0){ pw.print("\t" + basin.get(j)); }else{ pw.print("," + basin.get(j)); } } float[] fs = wVecs.get(i); for(float f : fs){ pw.print("\t" + f); } pw.println(); } pw.close(); mergeCount++; } }
diff --git a/stripes/src/net/sourceforge/stripes/controller/multipart/CommonsMultipartWrapper.java b/stripes/src/net/sourceforge/stripes/controller/multipart/CommonsMultipartWrapper.java index 0369191..77a59a0 100644 --- a/stripes/src/net/sourceforge/stripes/controller/multipart/CommonsMultipartWrapper.java +++ b/stripes/src/net/sourceforge/stripes/controller/multipart/CommonsMultipartWrapper.java @@ -1,210 +1,210 @@ /* Copyright 2005-2006 Tim Fennell * * 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.sourceforge.stripes.controller.multipart; import net.sourceforge.stripes.action.FileBean; import net.sourceforge.stripes.controller.FileUploadLimitExceededException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileUploadBase; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Iterator; import java.util.regex.Pattern; /** * An implementation of MultipartWrapper that uses Jakarta Commons FileUpload (from apache) * to parse the request parts. This implementation requires that both commons-fileupload and * commons-io be present in the classpath. While this implementation does introduce additional * dependencies, it's licensing (ASL 2.0) is significantly less restrictive than the licensing * for COS - the other alternative provided by Stripes. * * @author Tim Fennell * @since Stripes 1.4 */ public class CommonsMultipartWrapper implements MultipartWrapper { private static final Pattern WINDOWS_PATH_PREFIX_PATTERN = Pattern.compile("(?i:^[A-Z]:\\\\)"); private Map<String,FileItem> files = new HashMap<String,FileItem>(); private Map<String,String[]> parameters = new HashMap<String, String[]>(); private String charset; /** * Pseudo-constructor that allows the class to perform any initialization necessary. * * @param request an HttpServletRequest that has a content-type of multipart. * @param tempDir a File representing the temporary directory that can be used to store * file parts as they are uploaded if this is desirable * @param maxPostSize the size in bytes beyond which the request should not be read, and a * FileUploadLimitExceeded exception should be thrown * @throws IOException if a problem occurs processing the request of storing temporary * files * @throws FileUploadLimitExceededException if the POST content is longer than the * maxPostSize supplied. */ @SuppressWarnings("unchecked") public void build(HttpServletRequest request, File tempDir, long maxPostSize) throws IOException, FileUploadLimitExceededException { try { this.charset = request.getCharacterEncoding(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); List<FileItem> items = upload.parseRequest(request); Map<String,List<String>> params = new HashMap<String, List<String>>(); for (FileItem item : items) { // If it's a form field, add the string value to the list if (item.isFormField()) { List<String> values = params.get(item.getFieldName()); if (values == null) { values = new ArrayList<String>(); params.put(item.getFieldName(), values); } values.add(charset == null ? item.getString() : item.getString(charset)); } // Else store the file param else { files.put(item.getFieldName(), item); } } // Now convert them down into the usual map of String->String[] for (Map.Entry<String,List<String>> entry : params.entrySet()) { List<String> values = entry.getValue(); this.parameters.put(entry.getKey(), values.toArray(new String[values.size()])); } } catch (FileUploadBase.SizeLimitExceededException slee) { throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize()); } catch (FileUploadException fue) { IOException ioe = new IOException("Could not parse and cache file upload data."); ioe.initCause(fue); throw ioe; } } /** * Fetches the names of all non-file parameters in the request. Directly analogous to the * method of the same name in HttpServletRequest when the request is non-multipart. * * @return an Enumeration of all non-file parameter names in the request */ public Enumeration<String> getParameterNames() { return new IteratorEnumeration(this.parameters.keySet().iterator()); } /** * Fetches all values of a specific parameter in the request. To simulate the HTTP request * style, the array should be null for non-present parameters, and values in the array should * never be null - the empty String should be used when there is value. * * @param name the name of the request parameter * @return an array of non-null parameters or null */ public String[] getParameterValues(String name) { return this.parameters.get(name); } /** * Fetches the names of all file parameters in the request. Note that these are not the file * names, but the names given to the form fields in which the files are specified. * * @return the names of all file parameters in the request. */ public Enumeration<String> getFileParameterNames() { return new IteratorEnumeration(this.files.keySet().iterator()); } /** * Responsible for constructing a FileBean object for the named file parameter. If there is no * file parameter with the specified name this method should return null. * * @param name the name of the file parameter * @return a FileBean object wrapping the uploaded file */ public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); - if (item == null) { + String filename = item.getName(); + if (item == null || ((filename == null || filename.length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included - String basename = item.getName(); int index; - if (WINDOWS_PATH_PREFIX_PATTERN.matcher(basename).find()) - index = basename.lastIndexOf('\\'); + if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) + index = filename.lastIndexOf('\\'); else - index = basename.lastIndexOf('/'); - if (index >= 0 && index + 1 < basename.length() - 1) - basename = basename.substring(index + 1); + index = filename.lastIndexOf('/'); + if (index >= 0 && index + 1 < filename.length() - 1) + filename = filename.substring(index + 1); // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. - return new FileBean(null, item.getContentType(), basename, this.charset) { + return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } } /** Little helper class to create an enumeration as per the interface. */ private static class IteratorEnumeration implements Enumeration<String> { Iterator<String> iterator; /** Constructs an enumeration that consumes from the underlying iterator. */ IteratorEnumeration(Iterator<String> iterator) { this.iterator = iterator; } /** Returns true if more elements can be consumed, false otherwise. */ public boolean hasMoreElements() { return this.iterator.hasNext(); } /** Gets the next element out of the iterator. */ public String nextElement() { return this.iterator.next(); } } }
false
true
public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); if (item == null) { return null; } else { // Attempt to ensure the file name is just the basename with no path included String basename = item.getName(); int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(basename).find()) index = basename.lastIndexOf('\\'); else index = basename.lastIndexOf('/'); if (index >= 0 && index + 1 < basename.length() - 1) basename = basename.substring(index + 1); // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), basename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } }
public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); String filename = item.getName(); if (item == null || ((filename == null || filename.length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) index = filename.lastIndexOf('\\'); else index = filename.lastIndexOf('/'); if (index >= 0 && index + 1 < filename.length() - 1) filename = filename.substring(index + 1); // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } }
diff --git a/src/main/java/org/spout/engine/SpoutServer.java b/src/main/java/org/spout/engine/SpoutServer.java index 28b968ddd..6a62aede3 100644 --- a/src/main/java/org/spout/engine/SpoutServer.java +++ b/src/main/java/org/spout/engine/SpoutServer.java @@ -1,280 +1,285 @@ /* * This file is part of Spout. * * Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/> * Spout is licensed under the SpoutDev License Version 1. * * Spout is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * Spout is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spout.engine; import java.net.SocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.spout.api.Server; import org.spout.api.Spout; import org.spout.api.event.Listener; import org.spout.api.plugin.Platform; import org.spout.api.protocol.CommonPipelineFactory; import org.spout.api.protocol.Session; import org.spout.api.protocol.bootstrap.BootstrapProtocol; import org.spout.engine.filesystem.ServerFileSystem; import org.spout.engine.listener.SpoutListener; import org.spout.engine.protocol.SpoutSession; import org.spout.engine.util.bans.BanManager; import org.spout.engine.util.bans.FlatFileBanManager; import com.beust.jcommander.JCommander; public class SpoutServer extends SpoutEngine implements Server { private final String name = "Spout Server"; private volatile int maxPlayers = 20; /** * If the server has a whitelist or not. */ private volatile boolean whitelist = false; /** * If the server allows flight. */ private volatile boolean allowFlight = false; /** * A list of all players who can log onto this server, if using a whitelist. */ private List<String> whitelistedPlayers = new ArrayList<String>(); /** * The server's ban manager */ private BanManager banManager; /** * The {@link ServerBootstrap} used to initialize Netty. */ private final ServerBootstrap bootstrap = new ServerBootstrap(); public SpoutServer() { this.filesystem = new ServerFileSystem(); } public static void main(String[] args) { SpoutServer server = new SpoutServer(); Spout.setEngine(server); Spout.getFilesystem().init(); new JCommander(server, args); server.init(args); server.start(); } public void start() { start(true); } public void start(boolean checkWorlds) { start(checkWorlds, new SpoutListener(this)); } public void start(boolean checkWorlds, Listener listener) { super.start(checkWorlds); banManager = new FlatFileBanManager(this); getEventManager().registerEvents(listener, this); Spout.getFilesystem().postStartup(); getLogger().info("Done Loading, ready for players."); } @Override public void init(String[] args) { super.init(args); ChannelFactory factory = new NioServerSocketChannelFactory(executor, executor); bootstrap.setFactory(factory); ChannelPipelineFactory pipelineFactory = new CommonPipelineFactory(this); bootstrap.setPipelineFactory(pipelineFactory); } @Override public void stop() { super.stop(); bootstrap.getFactory().releaseExternalResources(); } /** * Binds this server to the specified address. * @param address The addresss. */ @Override public boolean bind(SocketAddress address, BootstrapProtocol protocol) { if (protocol == null) { throw new IllegalArgumentException("Protocol cannot be null"); } if (bootstrapProtocols.containsKey(address)) { return false; } bootstrapProtocols.put(address, protocol); - group.add(bootstrap.bind(address)); + try { + group.add(bootstrap.bind(address)); + } catch (org.jboss.netty.channel.ChannelException e) { + Logger.log(Level.SEVERE, "Failed to bind to address " + address + ". Is there already another server running on this address?", ex); + return false; + } logger.log(Level.INFO, "Binding to address: {0}...", address); return true; } @Override public int getMaxPlayers() { return maxPlayers; } @Override public void save(boolean worlds, boolean players) { // TODO Auto-generated method stub } @Override public boolean allowFlight() { return allowFlight; } @Override public boolean isWhitelist() { return whitelist; } @Override public void setWhitelist(boolean whitelist) { this.whitelist = whitelist; } @Override public void updateWhitelist() { List<String> whitelist = SpoutConfiguration.WHITELIST.getStringList(); if (whitelist != null) { whitelistedPlayers = whitelist; } else { whitelistedPlayers = new ArrayList<String>(); } } @Override public String[] getWhitelistedPlayers() { String[] whitelist = new String[whitelistedPlayers.size()]; for (int i = 0; i < whitelist.length; i++) { whitelist[i] = whitelistedPlayers.get(i); } return whitelist; } @Override public void whitelist(String player) { whitelistedPlayers.add(player); List<String> whitelist = SpoutConfiguration.WHITELIST.getStringList(); if (whitelist == null) { whitelist = whitelistedPlayers; } else { whitelist.add(player); } SpoutConfiguration.WHITELIST.setValue(whitelist); } @Override public void unWhitelist(String player) { whitelistedPlayers.remove(player); } @Override public Collection<String> getIPBans() { return banManager.getIpBans(); } @Override public void banIp(String address) { banManager.setIpBanned(address, true); } @Override public void unbanIp(String address) { banManager.setIpBanned(address, false); } @Override public void banPlayer(String player) { banManager.setBanned(player, true); } @Override public void unbanPlayer(String player) { banManager.setBanned(player, false); } @Override public boolean isBanned(String player, String address) { return banManager.isBanned(player, address); } @Override public boolean isIpBanned(String address) { return banManager.isIpBanned(address); } @Override public boolean isPlayerBanned(String player) { return banManager.isBanned(player); } @Override public String getBanMessage(String player) { return banManager.getBanMessage(player); } @Override public String getIpBanMessage(String address) { return banManager.getIpBanMessage(address); } @Override public Collection<String> getBannedPlayers() { return banManager.getBans(); } @Override public Session newSession(Channel channel) { BootstrapProtocol protocol = getBootstrapProtocol(channel.getLocalAddress()); return new SpoutSession(this, channel, protocol); } @Override public Platform getPlatform() { return Platform.SERVER; } @Override public String getName() { return name; } }
true
true
public boolean bind(SocketAddress address, BootstrapProtocol protocol) { if (protocol == null) { throw new IllegalArgumentException("Protocol cannot be null"); } if (bootstrapProtocols.containsKey(address)) { return false; } bootstrapProtocols.put(address, protocol); group.add(bootstrap.bind(address)); logger.log(Level.INFO, "Binding to address: {0}...", address); return true; }
public boolean bind(SocketAddress address, BootstrapProtocol protocol) { if (protocol == null) { throw new IllegalArgumentException("Protocol cannot be null"); } if (bootstrapProtocols.containsKey(address)) { return false; } bootstrapProtocols.put(address, protocol); try { group.add(bootstrap.bind(address)); } catch (org.jboss.netty.channel.ChannelException e) { Logger.log(Level.SEVERE, "Failed to bind to address " + address + ". Is there already another server running on this address?", ex); return false; } logger.log(Level.INFO, "Binding to address: {0}...", address); return true; }
diff --git a/src/com/buzzingandroid/ui/ViewAspectRatioMeasurer.java b/src/com/buzzingandroid/ui/ViewAspectRatioMeasurer.java index e25b4c2..f34c860 100644 --- a/src/com/buzzingandroid/ui/ViewAspectRatioMeasurer.java +++ b/src/com/buzzingandroid/ui/ViewAspectRatioMeasurer.java @@ -1,131 +1,131 @@ package com.buzzingandroid.ui; import android.view.View.MeasureSpec; /** * This class is a helper to measure views that require a specific aspect ratio.<br /> * <br /> * The measurement calculation is differing depending on whether the height and width * are fixed (match_parent or a dimension) or not (wrap_content) * * <pre> * | Width fixed | Width dynamic | * ---------------+-------------+---------------| * Height fixed | 1 | 2 | * ---------------+-------------+---------------| * Height dynamic | 3 | 4 | * </pre> * Everything is measured according to a specific aspect ratio.<br /> * <br /> * <ul> * <li>1: Both width and height fixed: Fixed (Aspect ratio isn't respected)</li> * <li>2: Width dynamic, height fixed: Set width depending on height</li> * <li>3: Width fixed, height dynamic: Set height depending on width</li> * <li>4: Both width and height dynamic: Largest size possible</li> * </ul> * * @author Jesper Borgstrup */ public class ViewAspectRatioMeasurer { private double aspectRatio; /** * Create a ViewAspectRatioMeasurer instance.<br/> * <br/> * Note: Don't construct a new instance everytime your <tt>View.onMeasure()</tt> method * is called.<br /> * Instead, create one instance when your <tt>View</tt> is constructed, and * use this instance's <tt>measure()</tt> methods in the <tt>onMeasure()</tt> method. * @param aspectRatio */ public ViewAspectRatioMeasurer(double aspectRatio) { this.aspectRatio = aspectRatio; } /** * Measure with the aspect ratio given at construction.<br /> * <br /> * After measuring, get the width and height with the {@link #getMeasuredWidth()} * and {@link #getMeasuredHeight()} methods, respectively. * @param widthMeasureSpec The width <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method * @param heightMeasureSpec The height <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method */ public void measure(int widthMeasureSpec, int heightMeasureSpec) { measure(widthMeasureSpec, heightMeasureSpec, this.aspectRatio); } /** * Measure with a specific aspect ratio<br /> * <br /> * After measuring, get the width and height with the {@link #getMeasuredWidth()} * and {@link #getMeasuredHeight()} methods, respectively. * @param widthMeasureSpec The width <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method * @param heightMeasureSpec The height <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method * @param aspectRatio The aspect ratio to calculate measurements in respect to */ public void measure(int widthMeasureSpec, int heightMeasureSpec, double aspectRatio) { int widthMode = MeasureSpec.getMode( widthMeasureSpec ); int widthSize = widthMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( widthMeasureSpec ); int heightMode = MeasureSpec.getMode( heightMeasureSpec ); int heightSize = heightMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( heightMeasureSpec ); if ( heightMode == MeasureSpec.EXACTLY && widthMode == MeasureSpec.EXACTLY ) { /* * Possibility 1: Both width and height fixed */ - measuredWidth = widthMode; - measuredHeight = heightMode; + measuredWidth = widthSize; + measuredHeight = heightSize; } else if ( heightMode == MeasureSpec.EXACTLY ) { /* * Possibility 2: Width dynamic, height fixed */ measuredWidth = (int) Math.min( widthSize, heightSize * aspectRatio ); measuredHeight = (int) (measuredWidth / aspectRatio); } else if ( widthMode == MeasureSpec.EXACTLY ) { /* * Possibility 3: Width fixed, height dynamic */ measuredHeight = (int) Math.min( heightSize, widthSize / aspectRatio ); measuredWidth = (int) (measuredHeight * aspectRatio); } else { /* * Possibility 4: Both width and height dynamic */ if ( widthSize > heightSize * aspectRatio ) { measuredHeight = heightSize; measuredWidth = (int)( measuredHeight * aspectRatio ); } else { measuredWidth = widthSize; measuredHeight = (int) (measuredWidth / aspectRatio); } } } private Integer measuredWidth = null; /** * Get the width measured in the latest call to <tt>measure()</tt>. */ public int getMeasuredWidth() { if ( measuredWidth == null ) { throw new IllegalStateException( "You need to run measure() before trying to get measured dimensions" ); } return measuredWidth; } private Integer measuredHeight = null; /** * Get the height measured in the latest call to <tt>measure()</tt>. */ public int getMeasuredHeight() { if ( measuredHeight == null ) { throw new IllegalStateException( "You need to run measure() before trying to get measured dimensions" ); } return measuredHeight; } }
true
true
public void measure(int widthMeasureSpec, int heightMeasureSpec, double aspectRatio) { int widthMode = MeasureSpec.getMode( widthMeasureSpec ); int widthSize = widthMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( widthMeasureSpec ); int heightMode = MeasureSpec.getMode( heightMeasureSpec ); int heightSize = heightMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( heightMeasureSpec ); if ( heightMode == MeasureSpec.EXACTLY && widthMode == MeasureSpec.EXACTLY ) { /* * Possibility 1: Both width and height fixed */ measuredWidth = widthMode; measuredHeight = heightMode; } else if ( heightMode == MeasureSpec.EXACTLY ) { /* * Possibility 2: Width dynamic, height fixed */ measuredWidth = (int) Math.min( widthSize, heightSize * aspectRatio ); measuredHeight = (int) (measuredWidth / aspectRatio); } else if ( widthMode == MeasureSpec.EXACTLY ) { /* * Possibility 3: Width fixed, height dynamic */ measuredHeight = (int) Math.min( heightSize, widthSize / aspectRatio ); measuredWidth = (int) (measuredHeight * aspectRatio); } else { /* * Possibility 4: Both width and height dynamic */ if ( widthSize > heightSize * aspectRatio ) { measuredHeight = heightSize; measuredWidth = (int)( measuredHeight * aspectRatio ); } else { measuredWidth = widthSize; measuredHeight = (int) (measuredWidth / aspectRatio); } } }
public void measure(int widthMeasureSpec, int heightMeasureSpec, double aspectRatio) { int widthMode = MeasureSpec.getMode( widthMeasureSpec ); int widthSize = widthMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( widthMeasureSpec ); int heightMode = MeasureSpec.getMode( heightMeasureSpec ); int heightSize = heightMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( heightMeasureSpec ); if ( heightMode == MeasureSpec.EXACTLY && widthMode == MeasureSpec.EXACTLY ) { /* * Possibility 1: Both width and height fixed */ measuredWidth = widthSize; measuredHeight = heightSize; } else if ( heightMode == MeasureSpec.EXACTLY ) { /* * Possibility 2: Width dynamic, height fixed */ measuredWidth = (int) Math.min( widthSize, heightSize * aspectRatio ); measuredHeight = (int) (measuredWidth / aspectRatio); } else if ( widthMode == MeasureSpec.EXACTLY ) { /* * Possibility 3: Width fixed, height dynamic */ measuredHeight = (int) Math.min( heightSize, widthSize / aspectRatio ); measuredWidth = (int) (measuredHeight * aspectRatio); } else { /* * Possibility 4: Both width and height dynamic */ if ( widthSize > heightSize * aspectRatio ) { measuredHeight = heightSize; measuredWidth = (int)( measuredHeight * aspectRatio ); } else { measuredWidth = widthSize; measuredHeight = (int) (measuredWidth / aspectRatio); } } }
diff --git a/src/de/robv/android/xposed/installer/PackageChangeReceiver.java b/src/de/robv/android/xposed/installer/PackageChangeReceiver.java index b05d758..5e18985 100644 --- a/src/de/robv/android/xposed/installer/PackageChangeReceiver.java +++ b/src/de/robv/android/xposed/installer/PackageChangeReceiver.java @@ -1,301 +1,309 @@ package de.robv.android.xposed.installer; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; public class PackageChangeReceiver extends BroadcastReceiver { public static String MIN_MODULE_VERSION = "2.0b2"; @Override public void onReceive(final Context context, final Intent intent) { if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED) && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) return; String packageName = getPackageName(intent); if (packageName == null) return; String appName; try { PackageManager pm = context.getPackageManager(); ApplicationInfo app = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); if (app.metaData == null || !app.metaData.containsKey("xposedmodule")) return; appName = pm.getApplicationLabel(app).toString(); } catch (NameNotFoundException e) { return; } Set<String> enabledModules = getEnabledModules(context); if (enabledModules.contains(packageName)) { updateModulesList(context, enabledModules); updateNativeLibs(context, enabledModules); } else { showNotActivatedNotification(context, packageName, appName); } } private static String getPackageName(Intent intent) { Uri uri = intent.getData(); return (uri != null) ? uri.getSchemeSpecificPart() : null; } static Set<String> getEnabledModules(Context context) { Set<String> modules = new HashSet<String>(); try { BufferedReader moduleLines = new BufferedReader(new FileReader("/data/xposed/modules.whitelist")); String module; while ((module = moduleLines.readLine()) != null) { modules.add(module); } moduleLines.close(); } catch (IOException e) { Toast.makeText(context, "cannot read /data/xposed/modules.whitelist", 1000).show(); Log.e(XposedInstallerActivity.TAG, "cannot read /data/xposed/modules.whitelist", e); return modules; } return modules; } static void setEnabledModules(Context context, Set<String> modules) { try { PrintWriter pw = new PrintWriter("/data/xposed/modules.whitelist"); for (String module : modules) { pw.println(module); } pw.close(); } catch (IOException e) { Toast.makeText(context, "cannot write /data/xposed/modules.whitelist", 1000).show(); Log.e(XposedInstallerActivity.TAG, "cannot write /data/xposed/modules.whitelist", e); } } static synchronized void updateModulesList(final Context context, final Set<String> enabledModules) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { try { Log.i(XposedInstallerActivity.TAG, "updating modules.list"); String installedXposedVersion = InstallerFragment.getJarInstalledVersion(null); if (installedXposedVersion == null) return "The xposed framework is not installed"; PackageManager pm = context.getPackageManager(); PrintWriter modulesList = new PrintWriter("/data/xposed/modules.list"); for (String packageName : enabledModules) { ApplicationInfo app; try { app = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); } catch (NameNotFoundException e) { continue; } if (app.metaData == null || !app.metaData.containsKey("xposedmodule") || !app.metaData.containsKey("xposedminversion")) continue; String minVersion = app.metaData.getString("xposedminversion"); if (PackageChangeReceiver.compareVersions(minVersion, installedXposedVersion) > 0 || PackageChangeReceiver.compareVersions(minVersion, MIN_MODULE_VERSION) < 0) continue; modulesList.println(app.sourceDir); } modulesList.close(); return context.getString(R.string.xposed_module_list_updated); } catch (IOException e) { Log.e(XposedInstallerActivity.TAG, "cannot write /data/xposed/modules.list", e); return "cannot write /data/xposed/modules.list"; } } @Override protected void onPostExecute(String result) { Toast.makeText(context, result, 1000).show(); } }.execute(); } static synchronized void updateNativeLibs(final Context context, final Set<String> enabledModules) { new Thread() { @Override public void run() { Log.i(XposedInstallerActivity.TAG, "updating native libraries"); try { new ProcessBuilder("sh", "-c", "rm -r /data/xposed/lib/*").start().waitFor(); } catch (Exception e) { Log.e("XposedInstaller", "", e); } new File("/data/xposed/lib/always/").delete(); new File("/data/xposed/lib/testonly/").delete(); PackageManager pm = context.getPackageManager(); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); Map<String, ?> prefs = pref.getAll(); for (Map.Entry<String, ?> entry : prefs.entrySet()) { String key = entry.getKey(); if (!key.startsWith("nativelib_")) continue; String value[] = String.valueOf(entry.getValue()).split("!"); if (value.length != 2) continue; String packageName = value[0]; if (!enabledModules.contains(packageName)) continue; String assetPath = "assets/" + value[1]; String libName = key.substring(10); boolean testOnly = Boolean.TRUE.equals(prefs.get("nativelibtest_" + libName)); try { ApplicationInfo app = pm.getApplicationInfo(packageName, 0); JarFile jf = new JarFile(app.sourceDir); JarEntry jfentry = jf.getJarEntry(assetPath); if (jfentry == null) { jf.close(); Log.e("XposedInstaller", "Could not find " + assetPath + " in " + app.sourceDir); continue; } InputStream is = jf.getInputStream(jfentry); - String targetPath = "/data/xposed/lib/" + (testOnly ? "testonly" : "always") + "/" + libName; - File targetFile = new File(targetPath); - targetFile.getParentFile().mkdirs(); + File targetDir = new File("/data/xposed/lib/" + (testOnly ? "testonly" : "always")); + File targetFile = new File(targetDir, libName); + // Must fetch the Dir again in case the libName contains a subdir + targetDir = targetFile.getParentFile(); + targetDir.mkdirs(); + for (File dir = targetDir; + !dir.getAbsolutePath().equals("/data/xposed/lib"); + dir = dir.getParentFile()) { + dir.setReadable(true, false); + dir.setExecutable(true, false); + } FileOutputStream os = new FileOutputStream(targetFile); byte[] temp = new byte[1024]; int read; while ((read = is.read(temp)) > 0) { os.write(temp, 0, read); } is.close(); os.close(); targetFile.setReadable(true, false); } catch (NameNotFoundException e) { Log.e("XposedInstaller", "", e); continue; } catch (IOException e) { Log.e("XposedInstaller", "", e); continue; } } } }.start(); } private static void showNotActivatedNotification(Context context, String packageName, String appName) { Intent startXposedInstaller = new Intent(context, XposedInstallerActivity.class); startXposedInstaller.putExtra(XposedInstallerActivity.EXTRA_OPEN_TAB, XposedInstallerActivity.TAB_MODULES); startXposedInstaller.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Notification notification = new Notification.Builder(context) .setContentTitle(context.getString(R.string.module_is_not_activated_yet)) .setContentText(appName) .setTicker(context.getString(R.string.module_is_not_activated_yet)) .setContentIntent(PendingIntent.getActivity(context, 0, startXposedInstaller, PendingIntent.FLAG_UPDATE_CURRENT)) .setAutoCancel(true) .setSmallIcon(android.R.drawable.ic_dialog_info) .getNotification(); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(packageName, XposedInstallerActivity.NOTIFICATION_MODULE_NOT_ACTIVATED_YET, notification); } private static Pattern SEARCH_PATTERN = Pattern.compile("(\\d+)(\\D+)?"); // removes: spaces at front and back, any dots and following zeros/stars at the end, any stars at the end private static Pattern TRIM_VERSION = Pattern.compile("^\\s*(.*?)(?:\\.+[0*]*)*\\**\\s*$"); public static int compareVersions(String s1, String s2) { // easy: both are equal if (s1.equalsIgnoreCase(s2)) return 0; s1 = trimVersion(s1); s2 = trimVersion(s2); // check again if (s1.equalsIgnoreCase(s2)) return 0; Matcher m1 = SEARCH_PATTERN.matcher(s1); Matcher m2 = SEARCH_PATTERN.matcher(s2); boolean bothMatch = false; while (m1.find() && m2.find()) { bothMatch = true; // if the whole match is equal, continue with the next match if (m1.group().equalsIgnoreCase(m2.group())) continue; // compare numeric part int i1 = Integer.parseInt(m1.group(1)); int i2 = Integer.parseInt(m2.group(1)); if (i1 != i2) return i1 - i2; // numeric part is equal from here on, now compare the suffix (anything non-numeric after the number) String suf1 = m1.group(2); String suf2 = m2.group(2); // both have no suffix, means nothing left in the string => equal if (suf1 == null && suf2 == null) return 0; // only one has a suffix => if it is a dot, a number will follow => newer, otherwise older if (suf1 == null) return suf2.equals(".") ? -1 : 1; if (suf2 == null) return suf1.equals(".") ? 1 : -1; // both have a prefix if (suf1 != null && suf2 != null && !suf1.equalsIgnoreCase(suf2)) return suf1.compareToIgnoreCase(suf2); } // if one of the strings does not start with a number, do a simple string comparison if (!bothMatch) return s1.compareToIgnoreCase(s2); // either whoever has remaining digits is bigger return m1.hitEnd() ? -1 : 1; } public static String trimVersion(String version) { return TRIM_VERSION.matcher(version).replaceFirst("$1"); } }
true
true
static synchronized void updateNativeLibs(final Context context, final Set<String> enabledModules) { new Thread() { @Override public void run() { Log.i(XposedInstallerActivity.TAG, "updating native libraries"); try { new ProcessBuilder("sh", "-c", "rm -r /data/xposed/lib/*").start().waitFor(); } catch (Exception e) { Log.e("XposedInstaller", "", e); } new File("/data/xposed/lib/always/").delete(); new File("/data/xposed/lib/testonly/").delete(); PackageManager pm = context.getPackageManager(); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); Map<String, ?> prefs = pref.getAll(); for (Map.Entry<String, ?> entry : prefs.entrySet()) { String key = entry.getKey(); if (!key.startsWith("nativelib_")) continue; String value[] = String.valueOf(entry.getValue()).split("!"); if (value.length != 2) continue; String packageName = value[0]; if (!enabledModules.contains(packageName)) continue; String assetPath = "assets/" + value[1]; String libName = key.substring(10); boolean testOnly = Boolean.TRUE.equals(prefs.get("nativelibtest_" + libName)); try { ApplicationInfo app = pm.getApplicationInfo(packageName, 0); JarFile jf = new JarFile(app.sourceDir); JarEntry jfentry = jf.getJarEntry(assetPath); if (jfentry == null) { jf.close(); Log.e("XposedInstaller", "Could not find " + assetPath + " in " + app.sourceDir); continue; } InputStream is = jf.getInputStream(jfentry); String targetPath = "/data/xposed/lib/" + (testOnly ? "testonly" : "always") + "/" + libName; File targetFile = new File(targetPath); targetFile.getParentFile().mkdirs(); FileOutputStream os = new FileOutputStream(targetFile); byte[] temp = new byte[1024]; int read; while ((read = is.read(temp)) > 0) { os.write(temp, 0, read); } is.close(); os.close(); targetFile.setReadable(true, false); } catch (NameNotFoundException e) { Log.e("XposedInstaller", "", e); continue; } catch (IOException e) { Log.e("XposedInstaller", "", e); continue; } } } }.start(); }
static synchronized void updateNativeLibs(final Context context, final Set<String> enabledModules) { new Thread() { @Override public void run() { Log.i(XposedInstallerActivity.TAG, "updating native libraries"); try { new ProcessBuilder("sh", "-c", "rm -r /data/xposed/lib/*").start().waitFor(); } catch (Exception e) { Log.e("XposedInstaller", "", e); } new File("/data/xposed/lib/always/").delete(); new File("/data/xposed/lib/testonly/").delete(); PackageManager pm = context.getPackageManager(); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); Map<String, ?> prefs = pref.getAll(); for (Map.Entry<String, ?> entry : prefs.entrySet()) { String key = entry.getKey(); if (!key.startsWith("nativelib_")) continue; String value[] = String.valueOf(entry.getValue()).split("!"); if (value.length != 2) continue; String packageName = value[0]; if (!enabledModules.contains(packageName)) continue; String assetPath = "assets/" + value[1]; String libName = key.substring(10); boolean testOnly = Boolean.TRUE.equals(prefs.get("nativelibtest_" + libName)); try { ApplicationInfo app = pm.getApplicationInfo(packageName, 0); JarFile jf = new JarFile(app.sourceDir); JarEntry jfentry = jf.getJarEntry(assetPath); if (jfentry == null) { jf.close(); Log.e("XposedInstaller", "Could not find " + assetPath + " in " + app.sourceDir); continue; } InputStream is = jf.getInputStream(jfentry); File targetDir = new File("/data/xposed/lib/" + (testOnly ? "testonly" : "always")); File targetFile = new File(targetDir, libName); // Must fetch the Dir again in case the libName contains a subdir targetDir = targetFile.getParentFile(); targetDir.mkdirs(); for (File dir = targetDir; !dir.getAbsolutePath().equals("/data/xposed/lib"); dir = dir.getParentFile()) { dir.setReadable(true, false); dir.setExecutable(true, false); } FileOutputStream os = new FileOutputStream(targetFile); byte[] temp = new byte[1024]; int read; while ((read = is.read(temp)) > 0) { os.write(temp, 0, read); } is.close(); os.close(); targetFile.setReadable(true, false); } catch (NameNotFoundException e) { Log.e("XposedInstaller", "", e); continue; } catch (IOException e) { Log.e("XposedInstaller", "", e); continue; } } } }.start(); }
diff --git a/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java b/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java index 0bcfd0bda..b179b85cc 100644 --- a/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java +++ b/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java @@ -1,669 +1,669 @@ /* * 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 android.support.v7.media; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.DeadObjectException; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.os.IBinder.DeathRecipient; import android.os.Message; import android.os.Messenger; import android.support.v7.media.MediaRouter.ControlRequestCallback; import android.util.Log; import android.util.SparseArray; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; /** * Maintains a connection to a particular media route provider service. */ final class RegisteredMediaRouteProvider extends MediaRouteProvider implements ServiceConnection { private static final String TAG = "MediaRouteProviderProxy"; // max. 23 chars private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); private final ComponentName mComponentName; private final PrivateHandler mPrivateHandler; private final ArrayList<Controller> mControllers = new ArrayList<Controller>(); private boolean mStarted; private boolean mBound; private Connection mActiveConnection; private boolean mConnectionReady; public RegisteredMediaRouteProvider(Context context, ComponentName componentName) { super(context, new ProviderMetadata(componentName.getPackageName())); mComponentName = componentName; mPrivateHandler = new PrivateHandler(); } @Override public RouteController onCreateRouteController(String routeId) { MediaRouteProviderDescriptor descriptor = getDescriptor(); if (descriptor != null) { List<MediaRouteDescriptor> routes = descriptor.getRoutes(); final int count = routes.size(); for (int i = 0; i < count; i++) { final MediaRouteDescriptor route = routes.get(i); if (route.getId().equals(routeId)) { Controller controller = new Controller(routeId); mControllers.add(controller); if (mConnectionReady) { controller.attachConnection(mActiveConnection); } updateBinding(); return controller; } } } return null; } @Override public void onDiscoveryRequestChanged(MediaRouteDiscoveryRequest request) { if (mConnectionReady) { mActiveConnection.setDiscoveryRequest(request); } updateBinding(); } public boolean hasComponentName(String packageName, String className) { return mComponentName.getPackageName().equals(packageName) && mComponentName.getClassName().equals(className); } public void start() { if (!mStarted) { if (DEBUG) { Log.d(TAG, this + ": Starting"); } mStarted = true; updateBinding(); } } public void stop() { if (mStarted) { if (DEBUG) { Log.d(TAG, this + ": Stopping"); } mStarted = false; updateBinding(); } } public void rebindIfDisconnected() { if (mActiveConnection == null && shouldBind()) { unbind(); bind(); } } private void updateBinding() { if (shouldBind()) { bind(); } else { unbind(); } } private boolean shouldBind() { if (mStarted) { // Bind whenever there is a discovery request. if (getDiscoveryRequest() != null) { return true; } // Bind whenever the application has an active route controller. // This means that one of this provider's routes is selected. if (!mControllers.isEmpty()) { return true; } } return false; } private void bind() { if (!mBound) { if (DEBUG) { Log.d(TAG, this + ": Binding"); } Intent service = new Intent(MediaRouteProviderService.SERVICE_INTERFACE); service.setComponent(mComponentName); try { mBound = getContext().bindService(service, this, Context.BIND_AUTO_CREATE); if (!mBound && DEBUG) { Log.d(TAG, this + ": Bind failed"); } } catch (SecurityException ex) { if (DEBUG) { Log.d(TAG, this + ": Bind failed", ex); } } } } private void unbind() { if (mBound) { if (DEBUG) { Log.d(TAG, this + ": Unbinding"); } mBound = false; disconnect(); getContext().unbindService(this); } } @Override public void onServiceConnected(ComponentName name, IBinder service) { if (DEBUG) { Log.d(TAG, this + ": Connected"); } if (mBound) { disconnect(); Messenger messenger = (service != null ? new Messenger(service) : null); if (MediaRouteProviderService.isValidRemoteMessenger(messenger)) { Connection connection = new Connection(messenger); if (connection.register()) { mActiveConnection = connection; } else { if (DEBUG) { Log.d(TAG, this + ": Registration failed"); } } } else { Log.e(TAG, this + ": Service returned invalid messenger binder"); } } } @Override public void onServiceDisconnected(ComponentName name) { if (DEBUG) { Log.d(TAG, this + ": Service disconnected"); } disconnect(); } private void onConnectionReady(Connection connection) { if (mActiveConnection == connection) { mConnectionReady = true; attachControllersToConnection(); MediaRouteDiscoveryRequest request = getDiscoveryRequest(); if (request != null) { mActiveConnection.setDiscoveryRequest(request); } } } private void onConnectionDied(Connection connection) { if (mActiveConnection == connection) { if (DEBUG) { Log.d(TAG, this + ": Service connection died"); } disconnect(); } } private void onConnectionError(Connection connection, String error) { if (mActiveConnection == connection) { if (DEBUG) { Log.d(TAG, this + ": Service connection error - " + error); } unbind(); } } private void onConnectionDescriptorChanged(Connection connection, MediaRouteProviderDescriptor descriptor) { if (mActiveConnection == connection) { if (DEBUG) { Log.d(TAG, this + ": Descriptor changed, descriptor=" + descriptor); } setDescriptor(descriptor); } } private void disconnect() { if (mActiveConnection != null) { setDescriptor(null); mConnectionReady = false; detachControllersFromConnection(); mActiveConnection.dispose(); mActiveConnection = null; } } private void onControllerReleased(Controller controller) { mControllers.remove(controller); controller.detachConnection(); updateBinding(); } private void attachControllersToConnection() { int count = mControllers.size(); for (int i = 0; i < count; i++) { mControllers.get(i).attachConnection(mActiveConnection); } } private void detachControllersFromConnection() { int count = mControllers.size(); for (int i = 0; i < count; i++) { mControllers.get(i).detachConnection(); } } @Override public String toString() { return "Service connection " + mComponentName.flattenToShortString(); } private final class Controller extends RouteController { private final String mRouteId; private boolean mSelected; private int mPendingSetVolume = -1; private int mPendingUpdateVolumeDelta; private Connection mConnection; private int mControllerId; public Controller(String routeId) { mRouteId = routeId; } public void attachConnection(Connection connection) { mConnection = connection; mControllerId = connection.createRouteController(mRouteId); if (mSelected) { connection.selectRoute(mControllerId); if (mPendingSetVolume >= 0) { connection.setVolume(mControllerId, mPendingSetVolume); mPendingSetVolume = -1; } if (mPendingUpdateVolumeDelta != 0) { connection.updateVolume(mControllerId, mPendingUpdateVolumeDelta); mPendingUpdateVolumeDelta = 0; } } } public void detachConnection() { if (mConnection != null) { mConnection.releaseRouteController(mControllerId); mConnection = null; mControllerId = 0; } } @Override public void onRelease() { onControllerReleased(this); } @Override public void onSelect() { mSelected = true; if (mConnection != null) { mConnection.selectRoute(mControllerId); } } @Override public void onUnselect() { mSelected = false; if (mConnection != null) { mConnection.unselectRoute(mControllerId); } } @Override public void onSetVolume(int volume) { if (mConnection != null) { mConnection.setVolume(mControllerId, volume); } else { mPendingSetVolume = volume; mPendingUpdateVolumeDelta = 0; } } @Override public void onUpdateVolume(int delta) { if (mConnection != null) { mConnection.updateVolume(mControllerId, delta); } else { mPendingUpdateVolumeDelta += delta; } } @Override public boolean onControlRequest(Intent intent, ControlRequestCallback callback) { if (mConnection != null) { return mConnection.sendControlRequest(mControllerId, intent, callback); } return false; } } private final class Connection implements DeathRecipient { private final Messenger mServiceMessenger; private final ReceiveHandler mReceiveHandler; private final Messenger mReceiveMessenger; private int mNextRequestId = 1; private int mNextControllerId = 1; private int mServiceVersion; // non-zero when registration complete private int mPendingRegisterRequestId; private final SparseArray<ControlRequestCallback> mPendingCallbacks = new SparseArray<ControlRequestCallback>(); public Connection(Messenger serviceMessenger) { mServiceMessenger = serviceMessenger; mReceiveHandler = new ReceiveHandler(this); mReceiveMessenger = new Messenger(mReceiveHandler); } public boolean register() { mPendingRegisterRequestId = mNextRequestId++; if (!sendRequest(MediaRouteProviderService.CLIENT_MSG_REGISTER, mPendingRegisterRequestId, MediaRouteProviderService.CLIENT_VERSION_CURRENT, null, null)) { return false; } try { mServiceMessenger.getBinder().linkToDeath(this, 0); return true; } catch (RemoteException ex) { binderDied(); } return false; } public void dispose() { sendRequest(MediaRouteProviderService.CLIENT_MSG_UNREGISTER, 0, 0, null, null); mReceiveHandler.dispose(); mServiceMessenger.getBinder().unlinkToDeath(this, 0); mPrivateHandler.post(new Runnable() { @Override public void run() { failPendingCallbacks(); } }); } private void failPendingCallbacks() { int count = 0; for (int i = 0; i < mPendingCallbacks.size(); i++) { mPendingCallbacks.valueAt(i).onError(null, null); } mPendingCallbacks.clear(); } public boolean onGenericFailure(int requestId) { if (requestId == mPendingRegisterRequestId) { mPendingRegisterRequestId = 0; onConnectionError(this, "Registation failed"); } ControlRequestCallback callback = mPendingCallbacks.get(requestId); if (callback != null) { mPendingCallbacks.remove(requestId); callback.onError(null, null); } return true; } public boolean onGenericSuccess(int requestId) { return true; } public boolean onRegistered(int requestId, int serviceVersion, Bundle descriptorBundle) { if (mServiceVersion == 0 && requestId == mPendingRegisterRequestId && serviceVersion >= MediaRouteProviderService.SERVICE_VERSION_1) { mPendingRegisterRequestId = 0; mServiceVersion = serviceVersion; onConnectionDescriptorChanged(this, MediaRouteProviderDescriptor.fromBundle(descriptorBundle)); onConnectionReady(this); return true; } return false; } public boolean onDescriptorChanged(Bundle descriptorBundle) { if (mServiceVersion != 0) { onConnectionDescriptorChanged(this, MediaRouteProviderDescriptor.fromBundle(descriptorBundle)); return true; } return false; } public boolean onControlRequestSucceeded(int requestId, Bundle data) { ControlRequestCallback callback = mPendingCallbacks.get(requestId); if (callback != null) { mPendingCallbacks.remove(requestId); callback.onResult(data); return true; } return false; } public boolean onControlRequestFailed(int requestId, String error, Bundle data) { ControlRequestCallback callback = mPendingCallbacks.get(requestId); if (callback != null) { mPendingCallbacks.remove(requestId); callback.onError(error, data); return true; } return false; } @Override public void binderDied() { mPrivateHandler.post(new Runnable() { @Override public void run() { onConnectionDied(Connection.this); } }); } public int createRouteController(String routeId) { int controllerId = mNextControllerId++; Bundle data = new Bundle(); data.putString(MediaRouteProviderService.CLIENT_DATA_ROUTE_ID, routeId); sendRequest(MediaRouteProviderService.CLIENT_MSG_CREATE_ROUTE_CONTROLLER, mNextRequestId++, controllerId, null, data); return controllerId; } public void releaseRouteController(int controllerId) { sendRequest(MediaRouteProviderService.CLIENT_MSG_RELEASE_ROUTE_CONTROLLER, mNextRequestId++, controllerId, null, null); } public void selectRoute(int controllerId) { sendRequest(MediaRouteProviderService.CLIENT_MSG_SELECT_ROUTE, mNextRequestId++, controllerId, null, null); } public void unselectRoute(int controllerId) { sendRequest(MediaRouteProviderService.CLIENT_MSG_UNSELECT_ROUTE, mNextRequestId++, controllerId, null, null); } public void setVolume(int controllerId, int volume) { Bundle data = new Bundle(); data.putInt(MediaRouteProviderService.CLIENT_DATA_VOLUME, volume); sendRequest(MediaRouteProviderService.CLIENT_MSG_SET_ROUTE_VOLUME, mNextRequestId++, controllerId, null, data); } public void updateVolume(int controllerId, int delta) { Bundle data = new Bundle(); data.putInt(MediaRouteProviderService.CLIENT_DATA_VOLUME, delta); sendRequest(MediaRouteProviderService.CLIENT_MSG_UPDATE_ROUTE_VOLUME, mNextRequestId++, controllerId, null, data); } public boolean sendControlRequest(int controllerId, Intent intent, ControlRequestCallback callback) { int requestId = mNextRequestId++; if (sendRequest(MediaRouteProviderService.CLIENT_MSG_ROUTE_CONTROL_REQUEST, requestId, controllerId, intent, null)) { if (callback != null) { mPendingCallbacks.put(requestId, callback); } return true; } return false; } public void setDiscoveryRequest(MediaRouteDiscoveryRequest request) { sendRequest(MediaRouteProviderService.CLIENT_MSG_SET_DISCOVERY_REQUEST, mNextRequestId++, 0, request != null ? request.asBundle() : null, null); } private boolean sendRequest(int what, int requestId, int arg, Object obj, Bundle data) { Message msg = Message.obtain(); msg.what = what; msg.arg1 = requestId; msg.arg2 = arg; msg.obj = obj; msg.setData(data); msg.replyTo = mReceiveMessenger; try { mServiceMessenger.send(msg); return true; } catch (DeadObjectException ex) { // The service died. } catch (RemoteException ex) { if (what != MediaRouteProviderService.CLIENT_MSG_UNREGISTER) { Log.e(TAG, "Could not send message to service.", ex); } } return false; } } private final class PrivateHandler extends Handler { } /** * Handler that receives messages from the server. * <p> * This inner class is static and only retains a weak reference to the connection * to prevent the client from being leaked in case the service is holding an * active reference to the client's messenger. * </p><p> * This handler should not be used to handle any messages other than those * that come from the service. * </p> */ private static final class ReceiveHandler extends Handler { private final WeakReference<Connection> mConnectionRef; public ReceiveHandler(Connection connection) { mConnectionRef = new WeakReference<Connection>(connection); } public void dispose() { mConnectionRef.clear(); } @Override public void handleMessage(Message msg) { Connection connection = mConnectionRef.get(); if (connection != null) { final int what = msg.what; final int requestId = msg.arg1; final int arg = msg.arg2; final Object obj = msg.obj; final Bundle data = msg.peekData(); if (!processMessage(connection, what, requestId, arg, obj, data)) { if (DEBUG) { Log.d(TAG, "Unhandled message from server: " + msg); } } } } private boolean processMessage(Connection connection, int what, int requestId, int arg, Object obj, Bundle data) { switch (what) { case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE: connection.onGenericFailure(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS: connection.onGenericSuccess(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_REGISTERED: if (obj == null || obj instanceof Bundle) { return connection.onRegistered(requestId, arg, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED: if (obj == null || obj instanceof Bundle) { return connection.onDescriptorChanged((Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED: if (obj == null || obj instanceof Bundle) { return connection.onControlRequestSucceeded( requestId, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED: if (obj == null || obj instanceof Bundle) { - String error = - data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR); + String error = (data == null ? null : + data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR)); return connection.onControlRequestFailed( requestId, error, (Bundle)obj); } break; } return false; } } }
true
true
private boolean processMessage(Connection connection, int what, int requestId, int arg, Object obj, Bundle data) { switch (what) { case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE: connection.onGenericFailure(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS: connection.onGenericSuccess(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_REGISTERED: if (obj == null || obj instanceof Bundle) { return connection.onRegistered(requestId, arg, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED: if (obj == null || obj instanceof Bundle) { return connection.onDescriptorChanged((Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED: if (obj == null || obj instanceof Bundle) { return connection.onControlRequestSucceeded( requestId, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED: if (obj == null || obj instanceof Bundle) { String error = data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR); return connection.onControlRequestFailed( requestId, error, (Bundle)obj); } break; } return false; }
private boolean processMessage(Connection connection, int what, int requestId, int arg, Object obj, Bundle data) { switch (what) { case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE: connection.onGenericFailure(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS: connection.onGenericSuccess(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_REGISTERED: if (obj == null || obj instanceof Bundle) { return connection.onRegistered(requestId, arg, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED: if (obj == null || obj instanceof Bundle) { return connection.onDescriptorChanged((Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED: if (obj == null || obj instanceof Bundle) { return connection.onControlRequestSucceeded( requestId, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED: if (obj == null || obj instanceof Bundle) { String error = (data == null ? null : data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR)); return connection.onControlRequestFailed( requestId, error, (Bundle)obj); } break; } return false; }
diff --git a/rwiki-util/radeox/src/java/org/radeox/macro/MacroListMacro.java b/rwiki-util/radeox/src/java/org/radeox/macro/MacroListMacro.java index ffa60e79..71ec5676 100755 --- a/rwiki-util/radeox/src/java/org/radeox/macro/MacroListMacro.java +++ b/rwiki-util/radeox/src/java/org/radeox/macro/MacroListMacro.java @@ -1,106 +1,106 @@ /* * This file is part of "SnipSnap Radeox Rendering Engine". * * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel * All Rights Reserved. * * Please visit http://radeox.org/ for updates and contact. * * --LICENSE NOTICE-- * 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. * --LICENSE NOTICE-- */ package org.radeox.macro; import java.io.IOException; import java.io.Writer; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.radeox.Messages; import org.radeox.api.macro.Macro; import org.radeox.api.macro.MacroParameter; /* * MacroListMacro displays a list of all known macros of the EngineManager with * their name, parameters and a description. @author Matthias L. Jugel * * @version $Id: MacroListMacro.java 7707 2006-04-12 17:30:19Z * [email protected] $ */ public class MacroListMacro extends BaseLocaleMacro { public String getLocaleKey() { return Messages.getString("MacroListMacro.0"); //$NON-NLS-1$ } public void execute(Writer writer, MacroParameter params) throws IllegalArgumentException, IOException { if (params.getLength() == 0) { appendTo(writer); } else { throw new IllegalArgumentException( "MacroListMacro: number of arguments does not match"); //$NON-NLS-1$ } } public Writer appendTo(Writer writer) throws IOException { List macroList = MacroRepository.getInstance().getPlugins(); Collections.sort(macroList); Iterator iterator = macroList.iterator(); writer.write(Messages.getString("MacroListMacro.2")); //$NON-NLS-1$ writer.write("Macro|Description|Parameters\n"); //$NON-NLS-1$ while (iterator.hasNext()) { Macro macro = (Macro) iterator.next(); writer.write(macro.getName()); - writer.write(Messages.getString("|")); //$NON-NLS-1$ + writer.write("|"); //$NON-NLS-1$ writer.write(macro.getDescription()); - writer.write(Messages.getString("|")); //$NON-NLS-1$ + writer.write("|"); //$NON-NLS-1$ String[] params = macro.getParamDescription(); if (params.length == 0) { writer.write("none"); //$NON-NLS-1$ } else { for (int i = 0; i < params.length; i++) { String description = params[i]; if (description.startsWith("?")) //$NON-NLS-1$ { writer.write(description.substring(1)); writer.write(" (optional)"); //$NON-NLS-1$ } else { writer.write(params[i]); } writer.write("\\\\"); //$NON-NLS-1$ } } writer.write("\n"); //$NON-NLS-1$ } writer.write(Messages.getString("MacroListMacro.11")); //$NON-NLS-1$ return writer; } }
false
true
public Writer appendTo(Writer writer) throws IOException { List macroList = MacroRepository.getInstance().getPlugins(); Collections.sort(macroList); Iterator iterator = macroList.iterator(); writer.write(Messages.getString("MacroListMacro.2")); //$NON-NLS-1$ writer.write("Macro|Description|Parameters\n"); //$NON-NLS-1$ while (iterator.hasNext()) { Macro macro = (Macro) iterator.next(); writer.write(macro.getName()); writer.write(Messages.getString("|")); //$NON-NLS-1$ writer.write(macro.getDescription()); writer.write(Messages.getString("|")); //$NON-NLS-1$ String[] params = macro.getParamDescription(); if (params.length == 0) { writer.write("none"); //$NON-NLS-1$ } else { for (int i = 0; i < params.length; i++) { String description = params[i]; if (description.startsWith("?")) //$NON-NLS-1$ { writer.write(description.substring(1)); writer.write(" (optional)"); //$NON-NLS-1$ } else { writer.write(params[i]); } writer.write("\\\\"); //$NON-NLS-1$ } } writer.write("\n"); //$NON-NLS-1$ } writer.write(Messages.getString("MacroListMacro.11")); //$NON-NLS-1$ return writer; }
public Writer appendTo(Writer writer) throws IOException { List macroList = MacroRepository.getInstance().getPlugins(); Collections.sort(macroList); Iterator iterator = macroList.iterator(); writer.write(Messages.getString("MacroListMacro.2")); //$NON-NLS-1$ writer.write("Macro|Description|Parameters\n"); //$NON-NLS-1$ while (iterator.hasNext()) { Macro macro = (Macro) iterator.next(); writer.write(macro.getName()); writer.write("|"); //$NON-NLS-1$ writer.write(macro.getDescription()); writer.write("|"); //$NON-NLS-1$ String[] params = macro.getParamDescription(); if (params.length == 0) { writer.write("none"); //$NON-NLS-1$ } else { for (int i = 0; i < params.length; i++) { String description = params[i]; if (description.startsWith("?")) //$NON-NLS-1$ { writer.write(description.substring(1)); writer.write(" (optional)"); //$NON-NLS-1$ } else { writer.write(params[i]); } writer.write("\\\\"); //$NON-NLS-1$ } } writer.write("\n"); //$NON-NLS-1$ } writer.write(Messages.getString("MacroListMacro.11")); //$NON-NLS-1$ return writer; }
diff --git a/src/main/java/org/eknet/swing/uploadfield/IconsList.java b/src/main/java/org/eknet/swing/uploadfield/IconsList.java index 25457a8..1c8dc14 100644 --- a/src/main/java/org/eknet/swing/uploadfield/IconsList.java +++ b/src/main/java/org/eknet/swing/uploadfield/IconsList.java @@ -1,135 +1,140 @@ /* * Copyright 2011 Eike Kettner * * 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.eknet.swing.uploadfield; import java.awt.Component; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JList; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.border.Border; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jetbrains.annotations.Nullable; /** * Displays a list of images, which can be * <ul> * <li>{@link Icon}s,</li> * <li>{@link URL}s to images or</li> * <li>{@link DefaultUploadValue}s</li> * </ul> * * @author <a href="mailto:[email protected]">Eike Kettner</a> * @since 01.10.11 20:44 */ public class IconsList extends JList { private static final Logger log = LoggerFactory.getLogger(IconsList.class); private Dimension previewSize; public IconsList() { setPreviewSize(new Dimension(25, 25)); setModel(new DefaultListModel()); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setLayoutOrientation(JList.HORIZONTAL_WRAP); setVisibleRowCount(-1); setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setHorizontalAlignment(SwingConstants.CENTER); setVerticalAlignment(SwingConstants.CENTER); setPreferredSize(getPreviewSize()); super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); setText(null); if (value instanceof URL) { setToolTipText(Utils.lastUrlPart((URL) value)); try { BufferedImage img = ImageIO.read((URL) value); - setIcon(new ImageIcon(Scales.scaleIfNecessary(img, previewSize.width, previewSize.height))); + if (img == null) { + log.error("URL '" + value + "' cannot be read!"); + setIcon(new ImageIcon(Utils.getMissingImage(previewSize.width, previewSize.height))); + } else { + setIcon(new ImageIcon(Scales.scaleIfNecessary(img, previewSize.width, previewSize.height))); + } } catch (IOException e) { log.error("Cannot scale image: " + value, e); } } else if (value instanceof Icon) { setIcon((Icon) value); } else if (value instanceof UploadValue) { UploadValue iv = (UploadValue) value; setIcon(iv.getIcon()); setToolTipText(iv.getName()); } else { setIcon(null); } Border border = getBorder(); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), border)); return this; } }); } public void setIconElements(@Nullable Iterable<?> icons) { DefaultListModel model = new DefaultListModel(); if (icons != null) { for (Object icon : icons) { model.addElement(icon); } } setModel(model); } public Dimension getPreviewSize() { return previewSize; } public void setPreviewSize(Dimension previewSize) { this.previewSize = previewSize; Dimension np = new Dimension(previewSize); np.width += 5; np.height += 5; setFixedCellHeight(np.height); setFixedCellWidth(np.width); } public void addElement(Object urlOrIconOrImageValue) { if (urlOrIconOrImageValue != null) { ((DefaultListModel) getModel()).addElement(urlOrIconOrImageValue); } } public void removeElement(Object urlOrIconOrImageValue) { if (urlOrIconOrImageValue != null) { ((DefaultListModel) getModel()).removeElement(urlOrIconOrImageValue); } } }
true
true
public IconsList() { setPreviewSize(new Dimension(25, 25)); setModel(new DefaultListModel()); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setLayoutOrientation(JList.HORIZONTAL_WRAP); setVisibleRowCount(-1); setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setHorizontalAlignment(SwingConstants.CENTER); setVerticalAlignment(SwingConstants.CENTER); setPreferredSize(getPreviewSize()); super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); setText(null); if (value instanceof URL) { setToolTipText(Utils.lastUrlPart((URL) value)); try { BufferedImage img = ImageIO.read((URL) value); setIcon(new ImageIcon(Scales.scaleIfNecessary(img, previewSize.width, previewSize.height))); } catch (IOException e) { log.error("Cannot scale image: " + value, e); } } else if (value instanceof Icon) { setIcon((Icon) value); } else if (value instanceof UploadValue) { UploadValue iv = (UploadValue) value; setIcon(iv.getIcon()); setToolTipText(iv.getName()); } else { setIcon(null); } Border border = getBorder(); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), border)); return this; } }); }
public IconsList() { setPreviewSize(new Dimension(25, 25)); setModel(new DefaultListModel()); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setLayoutOrientation(JList.HORIZONTAL_WRAP); setVisibleRowCount(-1); setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setHorizontalAlignment(SwingConstants.CENTER); setVerticalAlignment(SwingConstants.CENTER); setPreferredSize(getPreviewSize()); super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); setText(null); if (value instanceof URL) { setToolTipText(Utils.lastUrlPart((URL) value)); try { BufferedImage img = ImageIO.read((URL) value); if (img == null) { log.error("URL '" + value + "' cannot be read!"); setIcon(new ImageIcon(Utils.getMissingImage(previewSize.width, previewSize.height))); } else { setIcon(new ImageIcon(Scales.scaleIfNecessary(img, previewSize.width, previewSize.height))); } } catch (IOException e) { log.error("Cannot scale image: " + value, e); } } else if (value instanceof Icon) { setIcon((Icon) value); } else if (value instanceof UploadValue) { UploadValue iv = (UploadValue) value; setIcon(iv.getIcon()); setToolTipText(iv.getName()); } else { setIcon(null); } Border border = getBorder(); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), border)); return this; } }); }
diff --git a/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java b/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java index 97cef235..103a2bff 100755 --- a/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java +++ b/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java @@ -1,5820 +1,5822 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cismap.commons.gui; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import edu.umd.cs.piccolo.*; import edu.umd.cs.piccolo.event.PBasicInputEventHandler; import edu.umd.cs.piccolo.event.PInputEvent; import edu.umd.cs.piccolo.event.PInputEventListener; import edu.umd.cs.piccolo.nodes.PPath; import edu.umd.cs.piccolo.util.PBounds; import edu.umd.cs.piccolo.util.PPaintContext; import org.apache.log4j.Logger; import org.jdom.Attribute; import org.jdom.DataConversionException; import org.jdom.Element; import org.openide.util.Exceptions; import org.openide.util.NbBundle; import pswing.PSwingCanvas; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import javax.swing.*; import javax.swing.Timer; import de.cismet.cismap.commons.*; import de.cismet.cismap.commons.features.*; import de.cismet.cismap.commons.featureservice.DocumentFeatureService; import de.cismet.cismap.commons.featureservice.WebFeatureService; import de.cismet.cismap.commons.gui.layerwidget.ActiveLayerModel; import de.cismet.cismap.commons.gui.piccolo.*; import de.cismet.cismap.commons.gui.piccolo.eventlistener.*; import de.cismet.cismap.commons.gui.printing.PrintingSettingsWidget; import de.cismet.cismap.commons.gui.printing.PrintingWidget; import de.cismet.cismap.commons.gui.printing.Scale; import de.cismet.cismap.commons.gui.progresswidgets.DocumentProgressWidget; import de.cismet.cismap.commons.gui.simplelayerwidget.LayerControl; import de.cismet.cismap.commons.gui.simplelayerwidget.NewSimpleInternalLayerWidget; import de.cismet.cismap.commons.interaction.CismapBroker; import de.cismet.cismap.commons.interaction.CrsChangeListener; import de.cismet.cismap.commons.interaction.events.CrsChangedEvent; import de.cismet.cismap.commons.interaction.events.MapDnDEvent; import de.cismet.cismap.commons.interaction.events.StatusEvent; import de.cismet.cismap.commons.interaction.memento.Memento; import de.cismet.cismap.commons.interaction.memento.MementoInterface; import de.cismet.cismap.commons.preferences.CismapPreferences; import de.cismet.cismap.commons.preferences.GlobalPreferences; import de.cismet.cismap.commons.preferences.LayersPreferences; import de.cismet.cismap.commons.rasterservice.FeatureAwareRasterService; import de.cismet.cismap.commons.rasterservice.MapService; import de.cismet.cismap.commons.rasterservice.RasterMapService; import de.cismet.cismap.commons.retrieval.AbstractRetrievalService; import de.cismet.cismap.commons.retrieval.RetrievalEvent; import de.cismet.cismap.commons.retrieval.RetrievalListener; import de.cismet.tools.CismetThreadPool; import de.cismet.tools.CurrentStackTrace; import de.cismet.tools.StaticDebuggingTools; import de.cismet.tools.configuration.Configurable; import de.cismet.tools.gui.StaticSwingTools; import de.cismet.tools.gui.WaitDialog; import de.cismet.tools.gui.historybutton.DefaultHistoryModel; import de.cismet.tools.gui.historybutton.HistoryModel; /** * DOCUMENT ME! * * @author [email protected] * @version $Revision$, $Date$ */ public final class MappingComponent extends PSwingCanvas implements MappingModelListener, FeatureCollectionListener, HistoryModel, Configurable, DropTargetListener, CrsChangeListener { //~ Static fields/initializers --------------------------------------------- /** Wenn false, werden alle debug statements vom compiler wegoptimiert. */ private static final boolean DEBUG = Debug.DEBUG; public static final String PROPERTY_MAP_INTERACTION_MODE = "INTERACTION_MODE"; // NOI18N public static final String MOTION = "MOTION"; // NOI18N public static final String SELECT = "SELECT"; // NOI18N public static final String ZOOM = "ZOOM"; // NOI18N public static final String PAN = "PAN"; // NOI18N public static final String ALKIS_PRINT = "ALKIS_PRINT"; // NOI18N public static final String FEATURE_INFO = "FEATURE_INFO"; // NOI18N public static final String CREATE_SEARCH_POLYGON = "SEARCH_POLYGON"; // NOI18N public static final String CREATE_SIMPLE_GEOMETRY = "CREATE_SIMPLE_GEOMETRY"; // NOI18N public static final String MOVE_POLYGON = "MOVE_POLYGON"; // NOI18N public static final String REMOVE_POLYGON = "REMOVE_POLYGON"; // NOI18N public static final String NEW_POLYGON = "NEW_POLYGON"; // NOI18N public static final String SPLIT_POLYGON = "SPLIT_POLYGON"; // NOI18N public static final String JOIN_POLYGONS = "JOIN_POLYGONS"; // NOI18N public static final String RAISE_POLYGON = "RAISE_POLYGON"; // NOI18N public static final String ROTATE_POLYGON = "ROTATE_POLYGON"; // NOI18N public static final String REFLECT_POLYGON = "REFLECT_POLYGON"; // NOI18N public static final String ATTACH_POLYGON_TO_ALPHADATA = "ATTACH_POLYGON_TO_ALPHADATA"; // NOI18N public static final String MOVE_HANDLE = "MOVE_HANDLE"; // NOI18N public static final String REMOVE_HANDLE = "REMOVE_HANDLE"; // NOI18N public static final String ADD_HANDLE = "ADD_HANDLE"; // NOI18N public static final String MEASUREMENT = "MEASUREMENT"; // NOI18N public static final String LINEAR_REFERENCING = "LINEMEASUREMENT"; // NOI18N public static final String PRINTING_AREA_SELECTION = "PRINTING_AREA_SELECTION"; // NOI18N public static final String CUSTOM_FEATUREACTION = "CUSTOM_FEATUREACTION"; // NOI18N public static final String CUSTOM_FEATUREINFO = "CUSTOM_FEATUREINFO"; // NOI18N public static final String OVERVIEW = "OVERVIEW"; // NOI18N private static MappingComponent THIS; /** Name of the internal Simple Layer Widget. */ public static final String LAYERWIDGET = "SimpleInternalLayerWidget"; // NOI18N /** Name of the internal Document Progress Widget. */ public static final String PROGRESSWIDGET = "DocumentProgressWidget"; // NOI18N /** Internat Widget at position north west. */ public static final int POSITION_NORTHWEST = 1; /** Internat Widget at position south west. */ public static final int POSITION_SOUTHWEST = 2; /** Internat Widget at position north east. */ public static final int POSITION_NORTHEAST = 4; /** Internat Widget at position south east. */ public static final int POSITION_SOUTHEAST = 8; /** Delay after a compoent resize event triggers a service reload request. */ private static final int RESIZE_DELAY = 500; /** If a document exceeds the criticalDocumentSize, the document progress widget is displayed. */ private static final long criticalDocumentSize = 10000000; // 10MB private static final transient Logger LOG = Logger.getLogger(MappingComponent.class); //~ Instance fields -------------------------------------------------------- private boolean featureServiceLayerVisible = true; private final List<LayerControl> layerControls = new ArrayList<LayerControl>(); private boolean gridEnabled = true; private MappingModel mappingModel; private ConcurrentHashMap<Feature, PFeature> pFeatureHM = new ConcurrentHashMap<Feature, PFeature>(); private WorldToScreenTransform wtst = null; private double clip_offset_x; private double clip_offset_y; private double printingResolution = 0d; private boolean backgroundEnabled = true; private PLayer featureLayer = new PLayer(); private PLayer tmpFeatureLayer = new PLayer(); private PLayer mapServicelayer = new PLayer(); private PLayer featureServiceLayer = new PLayer(); private PLayer handleLayer = new PLayer(); private PLayer snapHandleLayer = new PLayer(); private PLayer rubberBandLayer = new PLayer(); private PLayer highlightingLayer = new PLayer(); private PLayer crosshairLayer = new PLayer(); private PLayer stickyLayer = new PLayer(); private PLayer printingFrameLayer = new PLayer(); private PLayer dragPerformanceImproverLayer = new PLayer(); private boolean readOnly = true; private boolean snappingEnabled = true; private boolean visualizeSnappingEnabled = true; private boolean visualizeSnappingRectEnabled = false; private int snappingRectSize = 20; private final Map<String, Cursor> cursors = new HashMap<String, Cursor>(); private final Map<String, PBasicInputEventHandler> inputEventListener = new HashMap<String, PBasicInputEventHandler>(); private final Action zoomAction; private int acceptableActions = DnDConstants.ACTION_COPY_OR_MOVE; private FeatureCollection featureCollection; private boolean infoNodesVisible = false; private boolean fixedMapExtent = false; private boolean fixedMapScale = false; private boolean inGlueIdenticalPointsMode = true; /** Holds value of property interactionMode. */ private String interactionMode; /** Holds value of property handleInteractionMode. */ private String handleInteractionMode; // "Phantom PCanvas" der nie selbst dargestellt wird // wird nur dazu benutzt das Graphics Objekt up to date // zu halten und dann als Hintergrund von z.B. einem // Panel zu fungieren // coooooooool, was ? ;-) private final PCanvas selectedObjectPresenter = new PCanvas(); // private BoundingBox currentBoundingBox = null; private Rectangle2D newViewBounds; private int animationDuration = 500; private int taskCounter = 0; private CismapPreferences cismapPrefs; private DefaultHistoryModel historyModel = new DefaultHistoryModel(); // Scales private final List<Scale> scales = new ArrayList<Scale>(); // Printing private PrintingSettingsWidget printingSettingsDialog; private PrintingWidget printingDialog; // Scalebar private double screenResolution = 100.0; private volatile boolean locked = true; private final List<PNode> stickyPNodes = new ArrayList<PNode>(); // Undo- & Redo-Stacks private final MementoInterface memUndo = new Memento(); private final MementoInterface memRedo = new Memento(); private boolean featureDebugging = false; private BoundingBox fixedBoundingBox = null; // Object handleFeatureServiceBlocker = new Object(); private final List<MapListener> mapListeners = new ArrayList<MapListener>(); /** Contains the internal widgets. */ private final Map<String, JInternalFrame> internalWidgets = new HashMap<String, JInternalFrame>(); /** Contains the positions of the internal widgets. */ private final Map<String, Integer> internalWidgetPositions = new HashMap<String, Integer>(); /** The timer that delays the reload requests. */ private Timer delayedResizeEventTimer = null; private DocumentProgressListener documentProgressListener = null; private List<Crs> crsList = new ArrayList<Crs>(); private CrsTransformer transformer; private boolean resetCrs = false; private final Timer showHandleDelay; private final Map<MapService, Future<?>> serviceFuturesMap = new HashMap<MapService, Future<?>>(); /** Utility field used by bound properties. */ private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); private ButtonGroup interactionButtonGroup; private boolean mainMappingComponent = false; /** * Creates new PFeatures for all features in the given array and adds them to the PFeatureHashmap. Then adds the * PFeature to the featurelayer. * * <p>DANGER: there's a bug risk here because the method runs in an own thread! It is possible that a PFeature of a * feature is demanded but not yet added to the hashmap which causes in most cases a NullPointerException!</p> * * @param features array with features to add */ private final HashMap<String, PLayer> featureGrpLayerMap = new HashMap<String, PLayer>(); private BoundingBox initialBoundingBox; //~ Constructors ----------------------------------------------------------- /** * Creates a new instance of MappingComponent. */ public MappingComponent() { this(false); } /** * Creates a new MappingComponent object. * * @param mainMappingComponent DOCUMENT ME! */ public MappingComponent(final boolean mainMappingComponent) { super(); this.mainMappingComponent = mainMappingComponent; locked = true; THIS = this; // wird in der Regel wieder ueberschrieben setSnappingRectSize(20); setSnappingEnabled(false); setVisualizeSnappingEnabled(false); setAnimationDuration(500); setInteractionMode(ZOOM); showHandleDelay = new Timer(500, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { showHandles(false); } }); showHandleDelay.setRepeats(false); featureDebugging = StaticDebuggingTools.checkHomeForFile("cismetTurnOnFeatureDebugging"); // NOI18N setFeatureCollection(new DefaultFeatureCollection()); addMapListener((DefaultFeatureCollection)getFeatureCollection()); final DropTarget dt = new DropTarget(this, acceptableActions, this); setDefaultRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); setAnimatingRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); removeInputEventListener(getPanEventHandler()); removeInputEventListener(getZoomEventHandler()); addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent evt) { if (MappingComponent.this.delayedResizeEventTimer == null) { delayedResizeEventTimer = new Timer(RESIZE_DELAY, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { delayedResizeEventTimer.stop(); delayedResizeEventTimer = null; // perform delayed resize: // rescape map + move widgets + reload services componentResizedDelayed(); } }); delayedResizeEventTimer.start(); } else { // perform intermediate resize: // rescape map + move widgets componentResizedIntermediate(); delayedResizeEventTimer.restart(); } } }); final PRoot root = getRoot(); final PCamera otherCamera = new PCamera(); otherCamera.addLayer(featureLayer); selectedObjectPresenter.setCamera(otherCamera); root.addChild(otherCamera); getLayer().addChild(mapServicelayer); getLayer().addChild(featureServiceLayer); getLayer().addChild(featureLayer); getLayer().addChild(tmpFeatureLayer); getLayer().addChild(rubberBandLayer); getLayer().addChild(highlightingLayer); getLayer().addChild(crosshairLayer); getLayer().addChild(dragPerformanceImproverLayer); getLayer().addChild(printingFrameLayer); getCamera().addLayer(mapServicelayer); getCamera().addLayer(featureLayer); getCamera().addLayer(tmpFeatureLayer); getCamera().addLayer(rubberBandLayer); getCamera().addLayer(highlightingLayer); getCamera().addLayer(crosshairLayer); getCamera().addLayer(dragPerformanceImproverLayer); getCamera().addLayer(printingFrameLayer); getCamera().addChild(snapHandleLayer); getCamera().addChild(handleLayer); getCamera().addChild(stickyLayer); handleLayer.moveToFront(); otherCamera.setTransparency(0.05f); initInputListener(); initCursors(); addInputEventListener(getInputListener(MOTION)); addInputEventListener(getInputListener(CUSTOM_FEATUREACTION)); final KeyboardListener k = new KeyboardListener(this); addInputEventListener(k); getRoot().getDefaultInputManager().setKeyboardFocus(k); setInteractionMode(ZOOM); setHandleInteractionMode(MOVE_HANDLE); dragPerformanceImproverLayer.setVisible(false); historyModel.setMaximumPossibilities(30); zoomAction = new AbstractAction() { { putValue( Action.NAME, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.zoomAction.NAME")); // NOI18N putValue( Action.SMALL_ICON, new ImageIcon(getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/layers.png"))); // NOI18N putValue( Action.SHORT_DESCRIPTION, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.zoomAction.SHORT_DESCRIPTION")); // NOI18N putValue( Action.LONG_DESCRIPTION, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.zoomAction.LONG_DESCRIPTION")); // NOI18N putValue(Action.MNEMONIC_KEY, Integer.valueOf('Z')); // NOI18N putValue(Action.ACTION_COMMAND_KEY, "zoom.action"); // NOI18N } @Override public void actionPerformed(final ActionEvent event) { zoomAction.putValue( Action.SMALL_ICON, new ImageIcon(getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N setInteractionMode(MappingComponent.ZOOM); } }; this.getCamera().addPropertyChangeListener(PCamera.PROPERTY_VIEW_TRANSFORM, new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { checkAndFixErroneousTransformation(); handleLayer.removeAllChildren(); showHandleDelay.restart(); rescaleStickyNodes(); CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.SCALE, interactionMode)); } }); } //~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public ButtonGroup getInteractionButtonGroup() { return interactionButtonGroup; } /** * DOCUMENT ME! * * @param interactionButtonGroup DOCUMENT ME! */ public void setInteractionButtonGroup(final ButtonGroup interactionButtonGroup) { this.interactionButtonGroup = interactionButtonGroup; } /** * DOCUMENT ME! * * @param mapListener DOCUMENT ME! */ public void addMapListener(final MapListener mapListener) { if (mapListener != null) { mapListeners.add(mapListener); } } /** * DOCUMENT ME! * * @param mapListener DOCUMENT ME! */ public void removeMapListener(final MapListener mapListener) { if (mapListener != null) { mapListeners.remove(mapListener); } } /** * DOCUMENT ME! */ public void dispose() { CismapBroker.getInstance().removeCrsChangeListener(this); getFeatureCollection().removeAllFeatures(); } /** * DOCUMENT ME! * * @return true, if debug-messages are logged. */ public boolean isFeatureDebugging() { return featureDebugging; } /** * Creates printingDialog and printingSettingsDialog. */ public void initPrintingDialogs() { printingSettingsDialog = new PrintingSettingsWidget(true, this); printingDialog = new PrintingWidget(true, this); } /** * Returns the momentary image of the PCamera of this MappingComponent. * * @return Image */ public Image getImage() { // this.getCamera().print(); return this.getCamera().toImage(this.getWidth(), this.getHeight(), Color.white); } /** * Creates an image with given width and height from all features in the given featurecollection. The image will be * used for printing. * * @param fc FeatureCollection * @param width desired width of the resulting image * @param height desired height of the resulting image * * @return Image of the featurecollection */ public Image getImageOfFeatures(final Collection<Feature> fc, final int width, final int height) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getImageOffFeatures (" + width + "x" + height + ")"); // NOI18N } } final PrintingFrameListener pfl = ((PrintingFrameListener)getInputListener(PRINTING_AREA_SELECTION)); final PCanvas pc = new PCanvas(); pc.setSize(width, height); final List<PFeature> list = new ArrayList<PFeature>(); final Iterator it = fc.iterator(); while (it.hasNext()) { final Feature f = (Feature)it.next(); final PFeature p = new PFeature(f, wtst, clip_offset_x, clip_offset_y, MappingComponent.this); if (p.getFullBounds().intersects(pfl.getPrintingRectangle().getBounds())) { list.add(p); } } pc.getCamera().animateViewToCenterBounds(pfl.getPrintingRectangle().getBounds(), true, 0); final double scale = 1 / pc.getCamera().getViewScale(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("subPCscale:" + scale); // NOI18N } } // TODO Sorge dafür dass die PSwingKomponente richtig gedruckt wird und dass die Karte nicht mehr "zittert" int printingLineWidth = -1; for (final PNode p : list) { if (p instanceof PFeature) { final PFeature original = ((PFeature)p); original.setInfoNodeExpanded(false); if (printingLineWidth > 0) { ((StyledFeature)original.getFeature()).setLineWidth(printingLineWidth); } else if (StyledFeature.class.isAssignableFrom(original.getFeature().getClass())) { final int orginalLineWidth = ((StyledFeature)original.getFeature()).getLineWidth(); printingLineWidth = (int)Math.round(orginalLineWidth * (getPrintingResolution() * 2)); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getImageOfFeatures: changed printingLineWidth from " + orginalLineWidth + " to " + printingLineWidth + " (resolution=" + getPrintingResolution() + ")"); // NOI18N } } ((StyledFeature)original.getFeature()).setLineWidth(printingLineWidth); } final PFeature copy = new PFeature(original.getFeature(), getWtst(), 0, 0, MappingComponent.this, true); pc.getLayer().addChild(copy); copy.setTransparency(original.getTransparency()); copy.setStrokePaint(original.getStrokePaint()); final boolean expanded = original.isInfoNodeExpanded(); copy.addInfoNode(); copy.setInfoNodeExpanded(false); copy.refreshInfoNode(); original.refreshInfoNode(); removeStickyNode(copy.getStickyChild()); final PNode stickyChild = copy.getStickyChild(); if (stickyChild != null) { stickyChild.setScale(scale * getPrintingResolution()); if (copy.hasSecondStickyChild()) { copy.getSecondStickyChild().setScale(scale * getPrintingResolution()); } } } } final Image ret = pc.getCamera().toImage(width, height, new Color(255, 255, 255, 0)); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug(ret); } } return ret; } catch (final Exception exception) { LOG.error("Error during the creation of an image from features", exception); // NOI18N return null; } } /** * Creates an image with given width and height from all features that intersects the printingframe. * * @param width desired width of the resulting image * @param height desired height of the resulting image * * @return Image of intersecting features */ public Image getFeatureImage(final int width, final int height) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getFeatureImage " + width + "x" + height); // NOI18N } } final PrintingFrameListener pfl = ((PrintingFrameListener)getInputListener(PRINTING_AREA_SELECTION)); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("printing rectangle bounds: " + pfl.getPrintingRectangle().getBounds()); // NOI18N } } final PCanvas pc = new PCanvas(); pc.setSize(width, height); final List<PNode> list = new ArrayList<PNode>(); final Iterator it = featureLayer.getChildrenIterator(); while (it.hasNext()) { final PNode p = (PNode)it.next(); if (p.getFullBounds().intersects(pfl.getPrintingRectangle().getBounds())) { list.add(p); } } /* * Prüfe alle Features der Gruppen Layer (welche auch Kinder des Feature-Layers sind) und füge sie der Liste für * alle zum malen anstehenden Features hinzu, wenn - der Gruppen-Layer sichtbar ist und - das Feature im * Druckbereich liegt */ final Collection<PLayer> groupLayers = this.featureGrpLayerMap.values(); List<PNode> grpMembers; for (final PLayer layer : groupLayers) { if (layer.getVisible()) { grpMembers = layer.getChildrenReference(); for (final PNode p : grpMembers) { if (p.getFullBounds().intersects(pfl.getPrintingRectangle().getBounds())) { list.add(p); } } } } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("intersecting feature count: " + list.size()); // NOI18N } } pc.getCamera().animateViewToCenterBounds(pfl.getPrintingRectangle().getBounds(), true, 0); final double scale = 1 / pc.getCamera().getViewScale(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("subPCscale:" + scale); // NOI18N } } // TODO Sorge dafür dass die PSwingKomponente richtig gedruckt wird und dass die Karte nicht mehr "zittert" for (final PNode p : list) { if (p instanceof PFeature) { final PFeature original = ((PFeature)p); try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { try { original.setInfoNodeExpanded(false); final PFeature copy = new PFeature( original.getFeature(), getWtst(), 0, 0, MappingComponent.this, true); pc.getLayer().addChild(copy); copy.setTransparency(original.getTransparency()); copy.setStrokePaint(original.getStrokePaint()); copy.addInfoNode(); copy.setInfoNodeExpanded(false); // Wenn mal irgendwas wegen Querformat kommt : if (copy.getStickyChild() != null) { copy.getStickyChild().setScale(scale * getPrintingResolution()); } } catch (final Exception t) { LOG.error("Fehler beim erstellen des Featureabbildes", t); // NOI18N } } }); } catch (final Exception t) { LOG.error("Fehler beim erstellen des Featureabbildes", t); // NOI18N return null; } } } return pc.getCamera().toImage(width, height, new Color(255, 255, 255, 0)); } /** * Adds the given PCamera to the PRoot of this MappingComponent. * * @param cam PCamera-object */ public void addToPRoot(final PCamera cam) { getRoot().addChild(cam); } /** * Adds a PNode to the StickyNode-vector. * * @param pn PNode-object */ public void addStickyNode(final PNode pn) { // if(DEBUG)log.debug("addStickyNode:" + pn); stickyPNodes.add(pn); } /** * Removes a specific PNode from the StickyNode-vector. * * @param pn PNode that should be removed */ public void removeStickyNode(final PNode pn) { stickyPNodes.remove(pn); } /** * DOCUMENT ME! * * @return Vector<PNode> with all sticky PNodes */ public List<PNode> getStickyNodes() { return stickyPNodes; } /** * Calls private method rescaleStickyNodeWork(node) to rescale the sticky PNode. Forces the execution to the EDT. * * @param n PNode to rescale */ public void rescaleStickyNode(final PNode n) { if (!EventQueue.isDispatchThread()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { rescaleStickyNodeWork(n); } }); } else { rescaleStickyNodeWork(n); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ private double getPrintingResolution() { return this.printingResolution; } /** * DOCUMENT ME! * * @param printingResolution DOCUMENT ME! */ public void setPrintingResolution(final double printingResolution) { this.printingResolution = printingResolution; } /** * Sets the scale of the given PNode to the value of the camera scale. * * @param n PNode to rescale */ private void rescaleStickyNodeWork(final PNode n) { final double s = MappingComponent.this.getCamera().getViewScale(); n.setScale(1 / s); } /** * Rescales all nodes inside the StickyNode-vector. */ public void rescaleStickyNodes() { final List<PNode> stickyNodeCopy = new ArrayList<PNode>(getStickyNodes()); for (final PNode each : stickyNodeCopy) { if ((each instanceof PSticky) && each.getVisible()) { rescaleStickyNode(each); } else { if ((each instanceof PSticky) && (each.getParent() == null)) { removeStickyNode(each); } } } } /** * Returns the custom created Action zoomAction. * * @return Action-object */ public Action getZoomAction() { return zoomAction; } /** * Pans to the given bounds without creating a historyaction to undo the action. * * @param bounds new bounds of the camera */ public void gotoBoundsWithoutHistory(PBounds bounds) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("gotoBoundsWithoutHistory(PBounds: " + bounds, new CurrentStackTrace()); // NOI18N } } try { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("error during removeAllCHildren", e); // NOI18N } if (bounds.getWidth() < 0) { bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight()); } if (bounds.getHeight() < 0) { bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1)); } if (bounds instanceof PBoundsWithCleverToString) { final PBoundsWithCleverToString boundWCTS = (PBoundsWithCleverToString)bounds; if (!boundWCTS.getCrsCode().equals(mappingModel.getSrs().getCode())) { try { final Rectangle2D pos = new Rectangle2D.Double(); XBoundingBox bbox = boundWCTS.getWorldCoordinates(); final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode()); bbox = trans.transformBoundingBox(bbox); bounds = bbox.getPBounds(getWtst()); } catch (final Exception e) { LOG.error("Cannot transform the bounding box from " + boundWCTS.getCrsCode() + " to " + mappingModel.getSrs().getCode()); } } } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("before animateView"); // NOI18N } } getCamera().animateViewToCenterBounds((bounds), true, animationDuration); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("after animateView"); // NOI18N } } queryServicesWithoutHistory(); showHandles(true); } catch (NullPointerException npe) { LOG.warn("NPE in gotoBoundsWithoutHistory(" + bounds + ")", npe); // NOI18N } } /** * Checks out the y-camerascales for negative value and fixes it by negating both x- and y-scales. */ private void checkAndFixErroneousTransformation() { if (getCamera().getViewTransform().getScaleY() < 0) { final double y = getCamera().getViewTransform().getScaleY(); final double x = getCamera().getViewTransform().getScaleX(); LOG.warn("Erroneous ViewTransform: getViewTransform (scaleY=" + y + " scaleX=" + x + "). Try to fix it."); // NOI18N getCamera().getViewTransformReference() .setToScale(getCamera().getViewTransform().getScaleX() * (-1), y * (-1)); } } /** * Re-adds the default layers in a given order. */ private void adjustLayers() { int counter = 0; getCamera().addLayer(counter++, mapServicelayer); for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) { getCamera().addLayer(counter++, (PLayer)featureServiceLayer.getChild(i)); } getCamera().addLayer(counter++, featureLayer); getCamera().addLayer(counter++, tmpFeatureLayer); getCamera().addLayer(counter++, rubberBandLayer); getCamera().addLayer(counter++, dragPerformanceImproverLayer); getCamera().addLayer(counter++, printingFrameLayer); } /** * Assigns the listeners to the according interactionmodes. */ public void initInputListener() { inputEventListener.put(MOTION, new SimpleMoveListener(this)); inputEventListener.put(CUSTOM_FEATUREACTION, new CustomFeatureActionListener(this)); inputEventListener.put(ZOOM, new RubberBandZoomListener()); inputEventListener.put(PAN, new PanAndMousewheelZoomListener()); inputEventListener.put(SELECT, new SelectionListener()); inputEventListener.put(FEATURE_INFO, new GetFeatureInfoClickDetectionListener()); inputEventListener.put(CREATE_SEARCH_POLYGON, new MetaSearchCreateSearchGeometryListener(this)); inputEventListener.put(CREATE_SIMPLE_GEOMETRY, new CreateSimpleGeometryListener(this)); inputEventListener.put(MOVE_POLYGON, new FeatureMoveListener(this)); inputEventListener.put(NEW_POLYGON, new CreateNewGeometryListener(this)); inputEventListener.put(RAISE_POLYGON, new RaisePolygonListener(this)); inputEventListener.put(REMOVE_POLYGON, new DeleteFeatureListener(this)); inputEventListener.put(ATTACH_POLYGON_TO_ALPHADATA, new AttachFeatureListener()); inputEventListener.put(JOIN_POLYGONS, new JoinPolygonsListener()); inputEventListener.put(SPLIT_POLYGON, new SplitPolygonListener(this)); inputEventListener.put(LINEAR_REFERENCING, new CreateLinearReferencedMarksListener(this)); inputEventListener.put(MEASUREMENT, new MeasurementListener(this)); inputEventListener.put(PRINTING_AREA_SELECTION, new PrintingFrameListener(this)); inputEventListener.put(CUSTOM_FEATUREINFO, new CustomFeatureInfoListener()); inputEventListener.put(OVERVIEW, new OverviewModeListener()); } /** * Assigns a custom interactionmode with an own PBasicInputEventHandler. * * @param key interactionmode as String * @param listener new PBasicInputEventHandler */ public void addCustomInputListener(final String key, final PBasicInputEventHandler listener) { inputEventListener.put(key, listener); } /** * Assigns the cursors to the according interactionmodes. */ public void initCursors() { putCursor(SELECT, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(ZOOM, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(PAN, new Cursor(Cursor.HAND_CURSOR)); putCursor(FEATURE_INFO, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(CREATE_SEARCH_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(MOVE_POLYGON, new Cursor(Cursor.HAND_CURSOR)); putCursor(ROTATE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(NEW_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(RAISE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(REMOVE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(ATTACH_POLYGON_TO_ALPHADATA, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(JOIN_POLYGONS, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(SPLIT_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(MEASUREMENT, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(LINEAR_REFERENCING, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(CREATE_SIMPLE_GEOMETRY, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(MOVE_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(REMOVE_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(ADD_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR)); } /** * Shows the printingsetting-dialog that resets the interactionmode after printing. * * @param oldInteractionMode String-object */ public void showPrintingSettingsDialog(final String oldInteractionMode) { printingSettingsDialog = printingSettingsDialog.cloneWithNewParent(true, this); printingSettingsDialog.setInteractionModeAfterPrinting(oldInteractionMode); StaticSwingTools.showDialog(printingSettingsDialog); } /** * Shows the printing-dialog that resets the interactionmode after printing. * * @param oldInteractionMode String-object */ public void showPrintingDialog(final String oldInteractionMode) { setPointerAnnotationVisibility(false); printingDialog = printingDialog.cloneWithNewParent(true, this); try { printingDialog.setInteractionModeAfterPrinting(oldInteractionMode); printingDialog.startLoading(); StaticSwingTools.showDialog(printingDialog); } catch (final Exception e) { LOG.error("Fehler beim Anzeigen des Printing Dialogs", e); // NOI18N } } /** * Getter for property interactionMode. * * @return Value of property interactionMode. */ public String getInteractionMode() { return this.interactionMode; } /** * Changes the interactionmode. * * @param interactionMode new interactionmode as String */ public void setInteractionMode(final String interactionMode) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:" + this.interactionMode + "", new Exception()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } setPointerAnnotationVisibility(false); if (getPrintingFrameLayer().getChildrenCount() > 1) { getPrintingFrameLayer().removeAllChildren(); } if (this.interactionMode != null) { if (interactionMode.equals(FEATURE_INFO)) { ((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo() .setVisible(true); } else { ((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo() .setVisible(false); } if (isReadOnly()) { ((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class); } final PInputEventListener pivl = this.getInputListener(this.interactionMode); if (pivl != null) { removeInputEventListener(pivl); } else { LOG.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N } if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) { featureCollection.unselectAll(); } if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEAR_REFERENCING) || interactionMode.equals(SPLIT_POLYGON)) && (this.readOnly == false)) { featureSelectionChanged(null); } if (interactionMode.equals(JOIN_POLYGONS)) { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent( this, PROPERTY_MAP_INTERACTION_MODE, this.interactionMode, interactionMode); this.interactionMode = interactionMode; final PInputEventListener pivl = getInputListener(interactionMode); if (pivl != null) { addInputEventListener(pivl); propertyChangeSupport.firePropertyChange(interactionModeChangedEvent); CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode)); } else { LOG.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N } } catch (final Exception e) { LOG.error("Fehler beim Ändern des InteractionModes", e); // NOI18N } } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Deprecated public void formComponentResized(final ComponentEvent evt) { this.componentResizedDelayed(); } /** * Resizes the map and does not reload all services. * * @see #componentResizedDelayed() */ public void componentResizedIntermediate() { if (!this.isLocked()) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { // rescale map if (historyModel.getCurrentElement() != null) { PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds == null) { bounds = initialBoundingBox.getPBounds(wtst); } if (bounds.getWidth() < 0) { bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight()); } if (bounds.getHeight() < 0) { bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1)); } getCamera().animateViewToCenterBounds(bounds, true, animationDuration); } } } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } /** * Resizes the map and reloads all services. * * @see #componentResizedIntermediate() */ public void componentResizedDelayed() { if (!this.isLocked()) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { final PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds != null) { gotoBoundsWithoutHistory(bounds); } else { gotoBoundsWithoutHistory(getInitialBoundingBox().getPBounds(wtst)); } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } } catch (final Exception t) { LOG.error("Fehler in formComponentResized()", t); // NOI18N } } } /** * syncSelectedObjectPresenter(int i). * * @param i DOCUMENT ME! */ public void syncSelectedObjectPresenter(final int i) { selectedObjectPresenter.setVisible(true); if (featureCollection.getSelectedFeatures().size() > 0) { if (featureCollection.getSelectedFeatures().size() == 1) { final PFeature selectedFeature = (PFeature)pFeatureHM.get( featureCollection.getSelectedFeatures().toArray()[0]); if (selectedFeature != null) { selectedObjectPresenter.getCamera() .animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2); } } else { // todo } } else { LOG.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public BoundingBox getInitialBoundingBox() { if (initialBoundingBox == null) { return mappingModel.getInitialBoundingBox(); } else { return initialBoundingBox; } } /** * Returns the current featureCollection. * * @return DOCUMENT ME! */ public FeatureCollection getFeatureCollection() { return featureCollection; } /** * Replaces the old featureCollection with a new one. * * @param featureCollection the new featureCollection */ public void setFeatureCollection(final FeatureCollection featureCollection) { this.featureCollection = featureCollection; featureCollection.addFeatureCollectionListener(this); } /** * DOCUMENT ME! * * @param visibility DOCUMENT ME! */ public void setFeatureCollectionVisibility(final boolean visibility) { featureLayer.setVisible(visibility); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFeatureCollectionVisible() { return featureLayer.getVisible(); } /** * Adds a new mapservice at a specific place of the layercontrols. * * @param mapService the new mapservice * @param position the index where to position the mapservice */ public void addMapService(final MapService mapService, final int position) { try { PNode p = new PNode(); if (mapService instanceof RasterMapService) { LOG.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N if (mapService.getPNode() instanceof XPImage) { p = (XPImage)mapService.getPNode(); } else { p = new XPImage(); mapService.setPNode(p); } mapService.addRetrievalListener(new MappingComponentRasterServiceListener( position, p, (ServiceLayer)mapService)); } else { LOG.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName() + ")"); // NOI18N p = new PLayer(); mapService.setPNode(p); if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): isDocumentFeatureService, checking document size"); // NOI18N } } final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService; if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) { LOG.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '" + documentFeatureService.getName() + "' size of " + (documentFeatureService.getDocumentSize() / 1000000) + "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000) + "MB)"); // NOI18N if (this.documentProgressListener == null) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): lazy instantiation of documentProgressListener"); // NOI18N } } this.documentProgressListener = new DocumentProgressListener(); } if (this.documentProgressListener.getRequestId() != -1) { LOG.error("FeatureMapService(" + mapService + "): The documentProgressListener is already in use by request '" + this.documentProgressListener.getRequestId() + ", document progress cannot be tracked"); // NOI18N } else { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N } } documentFeatureService.addRetrievalListener(this.documentProgressListener); } } } mapService.addRetrievalListener(new MappingComponentFeatureServiceListener( (ServiceLayer)mapService, (PLayer)mapService.getPNode())); } p.setTransparency(mapService.getTranslucency()); p.setVisible(mapService.isVisible()); mapServicelayer.addChild(p); } catch (final Exception e) { LOG.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + e.getMessage(), e); // NOI18N } } /** * DOCUMENT ME! * * @param mm DOCUMENT ME! */ public void preparationSetMappingModel(final MappingModel mm) { mappingModel = mm; } /** * Sets a new mappingmodel in this MappingComponent. * * @param mm the new mappingmodel */ public void setMappingModel(final MappingModel mm) { LOG.info("setMappingModel"); // NOI18N // FIXME: why is the default uncaught exception handler set in such a random place? if (Thread.getDefaultUncaughtExceptionHandler() == null) { LOG.info("setDefaultUncaughtExceptionHandler"); // NOI18N Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { LOG.error("Error", e); } }); } mappingModel = mm; // currentBoundingBox = mm.getInitialBoundingBox(); final Runnable r = new Runnable() { @Override public void run() { mappingModel.addMappingModelListener(MappingComponent.this); final TreeMap rs = mappingModel.getRasterServices(); // Rückwärts wegen der Reihenfolge der Layer im Layer Widget final Iterator it = rs.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { addMapService(((MapService)o), rsi); } } adjustLayers(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Set Mapping Modell done"); // NOI18N } } } }; CismetThreadPool.execute(r); } /** * Returns the current mappingmodel. * * @return current mappingmodel */ public MappingModel getMappingModel() { return mappingModel; } /** * Animates a component to a given x/y-coordinate in a given time. * * @param c the component to animate * @param toX final x-position * @param toY final y-position * @param animationDuration duration of the animation * @param hideAfterAnimation should the component be hidden after animation? */ private void animateComponent(final JComponent c, final int toX, final int toY, final int animationDuration, final boolean hideAfterAnimation) { if (animationDuration > 0) { final int x = (int)c.getBounds().getX() - toX; final int y = (int)c.getBounds().getY() - toY; int sx; int sy; if (x > 0) { sx = -1; } else { sx = 1; } if (y > 0) { sy = -1; } else { sy = 1; } int big; if (Math.abs(x) > Math.abs(y)) { big = Math.abs(x); } else { big = Math.abs(y); } final int sleepy; if ((animationDuration / big) < 1) { sleepy = 1; } else { sleepy = animationDuration / big; } final int directionY = sy; final int directionX = sx; if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY + ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX=" + toX + ", toY=" + toY); // NOI18N } } final Thread timer = new Thread() { @Override public void run() { while (!isInterrupted()) { try { sleep(sleepy); } catch (final Exception iex) { } EventQueue.invokeLater(new Runnable() { @Override public void run() { int currentY = (int)c.getBounds().getY(); int currentX = (int)c.getBounds().getX(); if (currentY != toY) { currentY = currentY + directionY; } if (currentX != toX) { currentX = currentX + directionX; } c.setBounds(currentX, currentY, c.getWidth(), c.getHeight()); } }); if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) { if (hideAfterAnimation) { EventQueue.invokeLater(new Runnable() { @Override public void run() { c.setVisible(false); c.hide(); } }); } break; } } } }; timer.setPriority(Thread.NORM_PRIORITY); timer.start(); } else { c.setBounds(toX, toY, c.getWidth(), c.getHeight()); if (hideAfterAnimation) { c.setVisible(false); } } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ @Deprecated public NewSimpleInternalLayerWidget getInternalLayerWidget() { return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET); } /** * Adds a new internal widget to the map.<br/> * If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget * will be added. If a widget with a different name already exisit at the same {@code position} the new widget will * not be added and the operation returns {@code false}. * * @param name unique name of the widget * @param position position of the widget * @param widget the widget * * @return {@code true} if the widget could be added, {@code false} otherwise * * @see #POSITION_NORTHEAST * @see #POSITION_NORTHWEST * @see #POSITION_SOUTHEAST * @see #POSITION_SOUTHWEST */ public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) { if (LOG.isDebugEnabled()) { LOG.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N } if (this.internalWidgets.containsKey(name)) { LOG.warn("widget '" + name + "' already added, removing old widget"); // NOI18N this.remove(this.getInternalWidget(name)); } else if (this.internalWidgetPositions.containsValue(position)) { LOG.warn("widget position '" + position + "' already taken"); // NOI18N return false; } this.internalWidgets.put(name, widget); this.internalWidgetPositions.put(name, position); widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N this.add(widget); widget.pack(); return true; } /** * Removes an existing internal widget from the map. * * @param name name of the widget to be removed * * @return {@code true} id the widget was found and removed, {@code false} otherwise */ public boolean removeInternalWidget(final String name) { if (LOG.isDebugEnabled()) { LOG.debug("removing internal widget '" + name + "'"); // NOI18N } if (!this.internalWidgets.containsKey(name)) { LOG.warn("widget '" + name + "' not found"); // NOI18N return false; } this.remove(this.getInternalWidget(name)); this.internalWidgets.remove(name); this.internalWidgetPositions.remove(name); return true; } /** * Shows an InternalWidget by sliding it into the mappingcomponent. * * @param name name of the internl component to show * @param visible should the widget be visible after the animation? * @param animationDuration duration of the animation * * @return {@code true} if the operation was successful, {@code false} otherwise */ public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) { final JInternalFrame internalWidget = this.getInternalWidget(name); if (internalWidget == null) { return false; } final int positionX; final int positionY; final int widgetPosition = this.getInternalWidgetPosition(name); final boolean isHigher = (getHeight() < (internalWidget.getHeight() + 2)) && (getHeight() > 0); final boolean isWider = (getWidth() < (internalWidget.getWidth() + 2)) && (getWidth() > 0); switch (widgetPosition) { case POSITION_NORTHWEST: { positionX = 1; positionY = 1; break; } case POSITION_SOUTHWEST: { positionX = 1; positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1); break; } case POSITION_NORTHEAST: { positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1); positionY = 1; break; } case POSITION_SOUTHEAST: { positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1); positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1); break; } default: { LOG.warn("unkown widget position?!"); // NOI18N return false; } } if (visible) { final int toY; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { if (isHigher) { toY = getHeight() - 1; } else { toY = positionY - internalWidget.getHeight() - 1; } } else { if (isHigher) { toY = getHeight() + 1; } else { toY = positionY + internalWidget.getHeight() + 1; } } internalWidget.setBounds( positionX, toY, isWider ? (getWidth() - 2) : internalWidget.getWidth(), isHigher ? (getHeight() - 2) : internalWidget.getHeight()); internalWidget.setVisible(true); internalWidget.show(); animateComponent(internalWidget, positionX, positionY, animationDuration, false); } else { internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight()); int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } animateComponent(internalWidget, positionX, toY, animationDuration, true); } return true; } /** * DOCUMENT ME! * * @param visible DOCUMENT ME! * @param animationDuration DOCUMENT ME! */ @Deprecated public void showInternalLayerWidget(final boolean visible, final int animationDuration) { this.showInternalWidget(LAYERWIDGET, visible, animationDuration); } /** * Returns a boolean, if the InternalLayerWidget is visible. * * @return true, if visible, else false */ @Deprecated public boolean isInternalLayerWidgetVisible() { return this.getInternalLayerWidget().isVisible(); } /** * Returns a boolean, if the InternalWidget is visible. * * @param name name of the widget * * @return true, if visible, else false */ public boolean isInternalWidgetVisible(final String name) { final JInternalFrame widget = this.getInternalWidget(name); if (widget != null) { return widget.isVisible(); } return false; } /** * Moves the camera to the initial bounding box (e.g. if the home-button is pressed). */ public void gotoInitialBoundingBox() { final double x1; final double y1; final double x2; final double y2; final double w; final double h; x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1()); y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1()); x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2()); y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2()); final Rectangle2D home = new Rectangle2D.Double(); home.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(home, true, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { LOG.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } setNewViewBounds(home); queryServices(); } /** * Refreshs all registered services. */ public void queryServices() { if (newViewBounds != null) { addToHistory(new PBoundsWithCleverToString( new PBounds(newViewBounds), wtst, mappingModel.getSrs().getCode())); queryServicesWithoutHistory(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServices()"); // NOI18N } } rescaleStickyNodes(); } } /** * Forces all services to refresh themselves. */ public void refresh() { forceQueryServicesWithoutHistory(); } /** * Forces all services to refresh themselves. */ private void forceQueryServicesWithoutHistory() { queryServicesWithoutHistory(true); } /** * Refreshs all services, but not forced. */ private void queryServicesWithoutHistory() { queryServicesWithoutHistory(false); } /** * Waits until all animations are done, then iterates through all registered services and calls handleMapService() * for each. * * @param forced forces the refresh */ private void queryServicesWithoutHistory(final boolean forced) { if (forced && mainMappingComponent) { CismapBroker.getInstance().fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_RESET, this)); } if (!locked) { final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception doNothing) { } } CismapBroker.getInstance().fireMapBoundsChanged(); if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N } } handleMapService(rsi, (MapService)o, forced); } else { LOG.warn("service is not of type MapService:" + o); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof MapService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N } } handleMapService(fsi, (MapService)o, forced); } else { LOG.warn("service is not of type MapService:" + o); // NOI18N } } } } }; CismetThreadPool.execute(r); } } /** * queryServicesIndependentFromMap. * * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param rl DOCUMENT ME! */ public void queryServicesIndependentFromMap(final int width, final int height, final BoundingBox bb, final RetrievalListener rl) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N } } final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception doNothing) { } } if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer) && ((ServiceLayer)o).isEnabled() && (o instanceof RetrievalServiceLayer) && ((RetrievalServiceLayer)o).getPNode().getVisible()) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = wfsClone; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(rsi); handleMapService(rsi, (MapService)r, width, height, bb, true); } catch (final Exception t) { LOG.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N } } else { LOG.warn("ignoring service '" + o + "' for printing"); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof AbstractRetrievalService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = (AbstractRetrievalService)o; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(fsi); handleMapService(fsi, (MapService)r, 0, 0, bb, true); } } } } }; CismetThreadPool.execute(r); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param service rs * @param forced DOCUMENT ME! */ public void handleMapService(final int position, final MapService service, final boolean forced) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("in handleRasterService: " + service + "(" + Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N } } final PBounds bounds = getCamera().getViewBounds(); final BoundingBox bb = new BoundingBox(); final double x1 = getWtst().getWorldX(bounds.getMinX()); final double y1 = getWtst().getWorldY(bounds.getMaxY()); final double x2 = getWtst().getWorldX(bounds.getMaxX()); final double y2 = getWtst().getWorldY(bounds.getMinY()); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Bounds=" + bounds); // NOI18N } } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N } } if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N bb.setX1(x1 - (x2 - x1)); bb.setY1(y1 - (y2 - y1)); bb.setX2(x2 + (x2 - x1)); bb.setY2(y2 + (y2 - y1)); } else { bb.setX1(x1); bb.setY1(y1); bb.setX2(x2); bb.setY2(y2); } handleMapService(position, service, getWidth(), getHeight(), bb, forced); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param rs DOCUMENT ME! * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param forced DOCUMENT ME! */ private void handleMapService(final int position, final MapService rs, final int width, final int height, final BoundingBox bb, final boolean forced) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("handleMapService: " + rs); // NOI18N } } rs.setSize(height, width); if (((ServiceLayer)rs).isEnabled()) { synchronized (serviceFuturesMap) { final Future<?> sf = serviceFuturesMap.get(rs); if ((sf == null) || sf.isDone()) { final Runnable serviceCall = new Runnable() { @Override public void run() { try { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception e) { } } rs.setBoundingBox(bb); if (rs instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection); } rs.retrieve(forced); } finally { serviceFuturesMap.remove(rs); } } }; synchronized (serviceFuturesMap) { serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall)); } } } } else { rs.setBoundingBox(bb); } } /** * Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it. * * @return new WorldToScreenTransform or null */ public WorldToScreenTransform getWtst() { try { if (wtst == null) { final double y_real = mappingModel.getInitialBoundingBox().getY2() - mappingModel.getInitialBoundingBox().getY1(); final double x_real = mappingModel.getInitialBoundingBox().getX2() - mappingModel.getInitialBoundingBox().getX1(); double clip_height; double clip_width; double x_screen = getWidth(); double y_screen = getHeight(); if (x_screen == 0) { x_screen = 100; } if (y_screen == 0) { y_screen = 100; } if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert clip_height = x_screen * y_real / x_real; clip_width = x_screen; clip_offset_y = 0; // (y_screen-clip_height)/2; clip_offset_x = 0; } else { // Y ist Bestimmer clip_height = y_screen; clip_width = y_screen * x_real / y_real; clip_offset_y = 0; clip_offset_x = 0; // (x_screen-clip_width)/2; } wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(), mappingModel.getInitialBoundingBox().getY2()); } return wtst; } catch (final Exception t) { LOG.error("Fehler in getWtst()", t); // NOI18N return null; } } /** * Resets the current WorldToScreenTransformation. */ public void resetWtst() { wtst = null; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_x() { return 0; // clip_offset_x; } /** * Assigns a new value to the x-clip-offset. * * @param clip_offset_x new clipoffset */ public void setClip_offset_x(final double clip_offset_x) { this.clip_offset_x = clip_offset_x; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_y() { return 0; // clip_offset_y; } /** * Assigns a new value to the y-clip-offset. * * @param clip_offset_y new clipoffset */ public void setClip_offset_y(final double clip_offset_y) { this.clip_offset_y = clip_offset_y; } /** * Returns the rubberband-PLayer. * * @return DOCUMENT ME! */ public PLayer getRubberBandLayer() { return rubberBandLayer; } /** * Assigns a given PLayer to the variable rubberBandLayer. * * @param rubberBandLayer a PLayer */ public void setRubberBandLayer(final PLayer rubberBandLayer) { this.rubberBandLayer = rubberBandLayer; } /** * Sets new viewbounds. * * @param r2d Rectangle2D */ public void setNewViewBounds(final Rectangle2D r2d) { newViewBounds = r2d; } /** * Will be called if the selection of features changes. It selects the PFeatures connected to the selected features * of the featurecollectionevent and moves them to the front. Also repaints handles at the end. * * @param fce featurecollectionevent with selected features */ @Override public void featureSelectionChanged(final FeatureCollectionEvent fce) { final Collection allChildren = featureLayer.getChildrenReference(); final ArrayList<PFeature> all = new ArrayList<PFeature>(); for (final Object o : allChildren) { if (o instanceof PFeature) { all.add((PFeature)o); } else if (o instanceof PLayer) { // Handling von Feature-Gruppen-Layer, welche als Kinder dem Feature Layer hinzugefügt wurden all.addAll(((PLayer)o).getChildrenReference()); } } // final Collection<PFeature> all = featureLayer.getChildrenReference(); for (final PFeature f : all) { f.setSelected(false); } Collection<Feature> c; if (fce != null) { c = fce.getFeatureCollection().getSelectedFeatures(); } else { c = featureCollection.getSelectedFeatures(); } ////handle featuregroup select-delegation//// final Set<Feature> selectionResult = new HashSet<Feature>(); for (final Feature current : c) { if (current instanceof FeatureGroup) { selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current)); } else { selectionResult.add(current); } } c = selectionResult; for (final Feature f : c) { if (f != null) { final PFeature feature = getPFeatureHM().get(f); if (feature != null) { if (feature.getParent() != null) { feature.getParent().moveToFront(); } feature.setSelected(true); feature.moveToFront(); // Fuer den selectedObjectPresenter (Eigener PCanvas) syncSelectedObjectPresenter(1000); } else { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } } showHandles(false); } /** * Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on * each feature of the given featurecollectionevent. Repaints handles at the end. * * @param fce featurecollectionevent with changed features */ @Override public void featuresChanged(final FeatureCollectionEvent fce) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("featuresChanged"); // NOI18N } } final List<Feature> list = new ArrayList<Feature>(); list.addAll(fce.getEventFeatures()); for (final Feature elem : list) { reconsiderFeature(elem); } showHandles(false); } /** * Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls * following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode() * * @param fce featurecollectionevent with features to reconsile */ @Override public void featureReconsiderationRequested(final FeatureCollectionEvent fce) { for (final Feature f : fce.getEventFeatures()) { if (f != null) { final PFeature node = pFeatureHM.get(f); if (node != null) { node.syncGeometry(); node.visualize(); node.resetInfoNodePosition(); node.refreshInfoNode(); repaint(); } } } } /** * Method is deprecated and deactivated. Does nothing!! * * @param fce FeatureCollectionEvent with features to add */ @Override @Deprecated public void featuresAdded(final FeatureCollectionEvent fce) { } /** * Method is deprecated and deactivated. Does nothing!! * * @deprecated DOCUMENT ME! */ @Override @Deprecated public void featureCollectionChanged() { } /** * Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a * checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent. * * @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice */ @Override public void allFeaturesRemoved(final FeatureCollectionEvent fce) { for (final PFeature feature : pFeatureHM.values()) { feature.cleanup(); } stickyPNodes.clear(); pFeatureHM.clear(); featureLayer.removeAllChildren(); // Lösche alle Features in den Gruppen-Layer, aber füge den Gruppen-Layer wieder dem FeatureLayer hinzu for (final PLayer layer : featureGrpLayerMap.values()) { layer.removeAllChildren(); featureLayer.addChild(layer); } checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); } /** * Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining * supporting rasterservices and paints handles at the end. * * @param fce FeatureCollectionEvent with features to remove */ @Override public void featuresRemoved(final FeatureCollectionEvent fce) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("featuresRemoved"); // NOI18N } } removeFeatures(fce.getEventFeatures()); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); showHandles(false); } /** * Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and * which need a refresh. * * @param fce FeatureCollectionEvent with removed features */ private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) { final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>(); for (final Feature f : getFeatureCollection().getAllFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } rasterServices.add(rs); // DANGER } } for (final Feature f : fce.getEventFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } if (rasterServices.contains(rs)) { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r); } } } else { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r); } } } } } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) { getMappingModel().removeLayer(frs); } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) { handleMapService(0, frs, true); } } /** * public void showFeatureCollection(Feature[] features) { com.vividsolutions.jts.geom.Envelope * env=computeFeatureEnvelope(features); showFeatureCollection(features,env); } public void * showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { selectedFeature=null; * handleLayer.removeAllChildren(); //setRasterServiceLayerImagesVisibility(false); Envelope eSquare=null; * HashSet<Feature> featureSet=new HashSet<Feature>(); featureSet.addAll(holdFeatures); * featureSet.addAll(java.util.Arrays.asList(f)); Feature[] features=featureSet.toArray(new Feature[0]); * pFeatureHM.clear(); addFeaturesToMap(features); zoomToFullFeatureCollectionBounds(); }. * * @param groupId DOCUMENT ME! * @param visible DOCUMENT ME! */ public void setGroupLayerVisibility(final String groupId, final boolean visible) { final PLayer layer = this.featureGrpLayerMap.get(groupId); if (layer != null) { layer.setVisible(visible); } } /** * is called when new feature is added to FeatureCollection. * * @param features DOCUMENT ME! */ public void addFeaturesToMap(final Feature[] features) { final double local_clip_offset_y = clip_offset_y; final double local_clip_offset_x = clip_offset_x; /// Hier muss der layer bestimmt werdenn for (int i = 0; i < features.length; ++i) { final Feature feature = features[i]; final PFeature p = new PFeature( feature, getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); try { if (feature instanceof StyledFeature) { p.setTransparency(((StyledFeature)(feature)).getTransparency()); } else { p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); } EventQueue.invokeLater(new Runnable() { @Override public void run() { if (feature instanceof FeatureGroupMember) { final FeatureGroupMember fgm = (FeatureGroupMember)feature; final String groupId = fgm.getGroupId(); PLayer groupLayer = featureGrpLayerMap.get(groupId); if (groupLayer == null) { groupLayer = new PLayer(); featureLayer.addChild(groupLayer); featureGrpLayerMap.put(groupId, groupLayer); if (LOG.isDebugEnabled()) { LOG.debug("created layer for group " + groupId); } } groupLayer.addChild(p); if (fgm.getGeometry() != null) { pFeatureHM.put(fgm.getFeature(), p); pFeatureHM.put(fgm, p); } if (LOG.isDebugEnabled()) { LOG.debug("added feature to group " + groupId); } } } }); } catch (final Exception e) { p.setTransparency(0.8f); LOG.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N } // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) if (!(feature instanceof FeatureGroupMember)) { if (feature.getGeometry() != null) { pFeatureHM.put(p.getFeature(), p); final int ii = i; EventQueue.invokeLater(new Runnable() { @Override public void run() { featureLayer.addChild(p); if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { p.moveToFront(); } } }); } } } EventQueue.invokeLater(new Runnable() { @Override public void run() { rescaleStickyNodes(); repaint(); fireFeaturesAddedToMap(Arrays.asList(features)); // SuchFeatures in den Vordergrund stellen for (final Feature feature : featureCollection.getAllFeatures()) { if (feature instanceof SearchFeature) { final PFeature pFeature = pFeatureHM.get(feature); pFeature.moveToFront(); } } } }); // check whether the feature has a rasterSupportLayer or not for (final Feature f : features) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (!getMappingModel().getRasterServices().containsValue(rs)) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureAwareRasterServiceAdded"); // NOI18N } } rs.setFeatureCollection(getFeatureCollection()); getMappingModel().addLayer(rs); } } } showHandles(false); } /** * DOCUMENT ME! * * @param cf DOCUMENT ME! */ private void fireFeaturesAddedToMap(final Collection<Feature> cf) { for (final MapListener curMapListener : mapListeners) { curMapListener.featuresAddedToMap(cf); } } /** * Creates an envelope around all features from the given array. * * @param features features to create the envelope around * * @return Envelope com.vividsolutions.jts.geom.Envelope */ private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) { final PNode root = new PNode(); for (int i = 0; i < features.length; ++i) { final PNode p = PNodeFactory.createPFeature(features[i], this); if (p != null) { root.addChild(p); } } final PBounds ext = root.getFullBounds(); final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope( ext.x, ext.x + ext.width, ext.y, ext.y + ext.height); return env; } /** * Zooms in / out to match the bounds of the featurecollection. */ public void zoomToFullFeatureCollectionBounds() { zoomToFeatureCollection(); } /** * Adds a new cursor to the cursor-hashmap. * * @param mode interactionmode as string * @param cursor cursor-object */ public void putCursor(final String mode, final Cursor cursor) { cursors.put(mode, cursor); } /** * Returns the cursor assigned to the given mode. * * @param mode mode as String * * @return Cursor-object or null */ public Cursor getCursor(final String mode) { return cursors.get(mode); } /** * Adds a new PBasicInputEventHandler for a specific interactionmode. * * @param mode interactionmode as string * @param listener new PBasicInputEventHandler */ public void addInputListener(final String mode, final PBasicInputEventHandler listener) { inputEventListener.put(mode, listener); } /** * Returns the PBasicInputEventHandler assigned to the committed interactionmode. * * @param mode interactionmode as string * * @return PBasicInputEventHandler-object or null */ public PInputEventListener getInputListener(final String mode) { final Object o = inputEventListener.get(mode); if (o instanceof PInputEventListener) { return (PInputEventListener)o; } else { return null; } } /** * Returns whether the features are editable or not. * * @return DOCUMENT ME! */ public boolean isReadOnly() { return readOnly; } /** * Sets all Features ReadOnly use Feature.setEditable(boolean) instead. * * @param readOnly DOCUMENT ME! */ public void setReadOnly(final boolean readOnly) { for (final Object f : featureCollection.getAllFeatures()) { ((Feature)f).setEditable(!readOnly); } this.readOnly = readOnly; handleLayer.repaint(); try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } snapHandleLayer.removeAllChildren(); } /** * Returns the current HandleInteractionMode. * * @return DOCUMENT ME! */ public String getHandleInteractionMode() { return handleInteractionMode; } /** * Changes the HandleInteractionMode. Repaints handles. * * @param handleInteractionMode the new HandleInteractionMode */ public void setHandleInteractionMode(final String handleInteractionMode) { this.handleInteractionMode = handleInteractionMode; showHandles(false); } /** * Returns whether the background is enabled or not. * * @return DOCUMENT ME! */ public boolean isBackgroundEnabled() { return backgroundEnabled; } /** * TODO. * * @param backgroundEnabled DOCUMENT ME! */ public void setBackgroundEnabled(final boolean backgroundEnabled) { if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) { featureServiceLayerVisible = featureServiceLayer.getVisible(); } this.mapServicelayer.setVisible(backgroundEnabled); this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible); for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) { featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible); } if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) { this.queryServices(); } this.backgroundEnabled = backgroundEnabled; } /** * Returns the featurelayer. * * @return DOCUMENT ME! */ public PLayer getFeatureLayer() { return featureLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Map<String, PLayer> getFeatureGroupLayers() { return this.featureGrpLayerMap; } /** * Adds a PFeature to the PFeatureHashmap. * * @param p PFeature to add */ public void refreshHM(final PFeature p) { pFeatureHM.put(p.getFeature(), p); } /** * Returns the selectedObjectPresenter (PCanvas). * * @return DOCUMENT ME! */ public PCanvas getSelectedObjectPresenter() { return selectedObjectPresenter; } /** * If f != null it calls the reconsiderFeature()-method of the featurecollection. * * @param f feature to reconcile */ public void reconsiderFeature(final Feature f) { if (f != null) { featureCollection.reconsiderFeature(f); } } /** * Removes all features of the collection from the hashmap. * * @param fc collection of features to remove */ public void removeFeatures(final Collection<Feature> fc) { featureLayer.setVisible(false); for (final Feature elem : fc) { removeFromHM(elem); } featureLayer.setVisible(true); } /** * Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key. * * @param f feature of the Pfeature that should be deleted */ public void removeFromHM(final Feature f) { final PFeature pf = pFeatureHM.get(f); if (pf != null) { pf.cleanup(); pFeatureHM.remove(f); stickyPNodes.remove(pf); try { LOG.info("Entferne Feature " + f); // NOI18N featureLayer.removeChild(pf); for (final PLayer grpLayer : this.featureGrpLayerMap.values()) { if (grpLayer.removeChild(pf) != null) { break; } } } catch (Exception ex) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N } } } } else { LOG.warn("Feature war nicht in pFeatureHM"); // NOI18N } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("pFeatureHM" + pFeatureHM); // NOI18N } } } /** * Zooms to the current selected node. * * @deprecated DOCUMENT ME! */ public void zoomToSelectedNode() { zoomToSelection(); } /** * Zooms to the current selected features. */ public void zoomToSelection() { final Collection<Feature> selection = featureCollection.getSelectedFeatures(); zoomToAFeatureCollection(selection, true, false); } /** * Zooms to a specific featurecollection. * * @param collection the featurecolltion * @param withHistory should the zoomaction be undoable * @param fixedScale fixedScale */ public void zoomToAFeatureCollection(final Collection<Feature> collection, final boolean withHistory, final boolean fixedScale) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("zoomToAFeatureCollection"); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } boolean first = true; Geometry g = null; for (final Feature f : collection) { if (first) { if (f.getGeometry() != null) { g = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode()) .getEnvelope(); if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) { g = g.buffer(((Bufferable)f).getBuffer() + 0.001); } first = false; } } else { if (f.getGeometry() != null) { Geometry geometry = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode()) .getEnvelope(); if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) { geometry = geometry.buffer(((Bufferable)f).getBuffer() + 0.001); } g = g.getEnvelope().union(geometry); } } } if (g != null) { // FIXME: we shouldn't only complain but do sth if ((getHeight() == 0) || (getWidth() == 0)) { LOG.warn("DIVISION BY ZERO"); // NOI18N } // dreisatz.de final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10; final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10; double buff = 0; if (hBuff > vBuff) { buff = hBuff; } else { buff = vBuff; } if (buff == 0.0) { if (mappingModel.getSrs().isMetric()) { buff = 1.0; } else { buff = 0.01; } } g = g.buffer(buff); final BoundingBox bb = new BoundingBox(g); final boolean onlyOnePoint = (collection.size() == 1) && (((Feature)(collection.toArray()[0])).getGeometry() instanceof com.vividsolutions.jts.geom.Point); gotoBoundingBox(bb, withHistory, !(fixedScale || (onlyOnePoint && (g.getArea() < 10))), animationDuration); } } /** * Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create * their handles and to add them to the handlelayer. * * @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles */ public void showHandles(final boolean waitTillAllAnimationsAreComplete) { // are there features selected? if (featureCollection.getSelectedFeatures().size() > 0) { // DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf final Runnable handle = new Runnable() { @Override public void run() { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); while (getAnimating() && waitTillAllAnimationsAreComplete) { try { Thread.currentThread().sleep(10); } catch (final Exception e) { LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (featureCollection.areFeaturesEditable() && (getInteractionMode().equals(SELECT) || getInteractionMode().equals(LINEAR_REFERENCING) || getInteractionMode().equals(PAN) || getInteractionMode().equals(ZOOM) || getInteractionMode().equals(ALKIS_PRINT) || getInteractionMode().equals(SPLIT_POLYGON))) { // Handles für alle selektierten Features der Collection hinzufügen if (getHandleInteractionMode().equals(ROTATE_POLYGON)) { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature instanceof Feature) && selectedFeature.isEditable()) { - if (pFeatureHM.get(selectedFeature) != null) { + if ((pFeatureHM.get(selectedFeature) != null) + && pFeatureHM.get(selectedFeature).getVisible()) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { pFeatureHM.get(selectedFeature).addRotationHandles(handleLayer); } }); } else { LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } } } } else { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature != null) && selectedFeature.isEditable()) { - if (pFeatureHM.get(selectedFeature) != null) { + if ((pFeatureHM.get(selectedFeature) != null) + && pFeatureHM.get(selectedFeature).getVisible()) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { try { pFeatureHM.get(selectedFeature).addHandles(handleLayer); } catch (final Exception e) { LOG.error("Error bei addHandles: ", e); // NOI18N } } }); } else { LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } // DANGER mit break werden nur die Handles EINES slektierten Features angezeigt // wird break auskommentiert werden jedoch zu viele Handles angezeigt break; } } } } } }; if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("showHandles", new CurrentStackTrace()); // NOI18N } } CismetThreadPool.execute(handle); } else { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); } } /** * Will return a PureNewFeature if there is only one in the featurecollection else null. * * @return DOCUMENT ME! */ public PFeature getSolePureNewFeature() { int counter = 0; PFeature sole = null; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object o = it.next(); if (o instanceof PFeature) { if (((PFeature)o).getFeature() instanceof PureNewFeature) { ++counter; sole = ((PFeature)o); } } } if (counter == 1) { return sole; } else { return null; } } /** * Returns the temporary featurelayer. * * @return DOCUMENT ME! */ public PLayer getTmpFeatureLayer() { return tmpFeatureLayer; } /** * Assigns a new temporary featurelayer. * * @param tmpFeatureLayer PLayer */ public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) { this.tmpFeatureLayer = tmpFeatureLayer; } /** * Returns whether the grid is enabled or not. * * @return DOCUMENT ME! */ public boolean isGridEnabled() { return gridEnabled; } /** * Enables or disables the grid. * * @param gridEnabled true, to enable the grid */ public void setGridEnabled(final boolean gridEnabled) { this.gridEnabled = gridEnabled; } /** * Returns a String from two double-values. Serves the visualization. * * @param x X-coordinate * @param y Y-coordinate * * @return a String-object like "(X,Y)" */ public static String getCoordinateString(final double x, final double y) { final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N final DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); df.setDecimalFormatSymbols(dfs); return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N } /** * DOCUMENT ME! * * @param event DOCUMENT ME! * * @return DOCUMENT ME! */ public com.vividsolutions.jts.geom.Point getPointGeometryFromPInputEvent(final PInputEvent event) { final double xCoord = getWtst().getSourceX(event.getPosition().getX() - getClip_offset_x()); final double yCoord = getWtst().getSourceY(event.getPosition().getY() - getClip_offset_y()); final GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), CrsTransformer.extractSridFromCrs(getMappingModel().getSrs().getCode())); return gf.createPoint(new Coordinate(xCoord, yCoord)); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHandleLayer() { return handleLayer; } /** * DOCUMENT ME! * * @param handleLayer DOCUMENT ME! */ public void setHandleLayer(final PLayer handleLayer) { this.handleLayer = handleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingEnabled() { return visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingEnabled DOCUMENT ME! */ public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) { this.visualizeSnappingEnabled = visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingRectEnabled() { return visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingRectEnabled DOCUMENT ME! */ public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) { this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getSnappingRectSize() { return snappingRectSize; } /** * DOCUMENT ME! * * @param snappingRectSize DOCUMENT ME! */ public void setSnappingRectSize(final int snappingRectSize) { this.snappingRectSize = snappingRectSize; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getSnapHandleLayer() { return snapHandleLayer; } /** * DOCUMENT ME! * * @param snapHandleLayer DOCUMENT ME! */ public void setSnapHandleLayer(final PLayer snapHandleLayer) { this.snapHandleLayer = snapHandleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isSnappingEnabled() { return snappingEnabled; } /** * DOCUMENT ME! * * @param snappingEnabled DOCUMENT ME! */ public void setSnappingEnabled(final boolean snappingEnabled) { this.snappingEnabled = snappingEnabled; setVisualizeSnappingEnabled(snappingEnabled); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getFeatureServiceLayer() { return featureServiceLayer; } /** * DOCUMENT ME! * * @param featureServiceLayer DOCUMENT ME! */ public void setFeatureServiceLayer(final PLayer featureServiceLayer) { this.featureServiceLayer = featureServiceLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getAnimationDuration() { return animationDuration; } /** * DOCUMENT ME! * * @param animationDuration DOCUMENT ME! */ public void setAnimationDuration(final int animationDuration) { this.animationDuration = animationDuration; } /** * DOCUMENT ME! * * @param prefs DOCUMENT ME! */ @Deprecated public void setPreferences(final CismapPreferences prefs) { LOG.warn("involing deprecated operation setPreferences()"); // NOI18N cismapPrefs = prefs; final ActiveLayerModel mm = new ActiveLayerModel(); final LayersPreferences layersPrefs = prefs.getLayersPrefs(); final GlobalPreferences globalPrefs = prefs.getGlobalPrefs(); setSnappingRectSize(globalPrefs.getSnappingRectSize()); setSnappingEnabled(globalPrefs.isSnappingEnabled()); setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled()); setAnimationDuration(globalPrefs.getAnimationDuration()); setInteractionMode(globalPrefs.getStartMode()); mm.addHome(globalPrefs.getInitialBoundingBox()); final Crs crs = new Crs(); crs.setCode(globalPrefs.getInitialBoundingBox().getSrs()); crs.setName(globalPrefs.getInitialBoundingBox().getSrs()); crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs()); mm.setSrs(crs); final TreeMap raster = layersPrefs.getRasterServices(); if (raster != null) { final Iterator it = raster.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = raster.get(key); if (o instanceof MapService) { mm.addLayer((RetrievalServiceLayer)o); } } } final TreeMap features = layersPrefs.getFeatureServices(); if (features != null) { final Iterator it = features.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = features.get(key); if (o instanceof MapService) { // TODO mm.addLayer((RetrievalServiceLayer)o); } } } setMappingModel(mm); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public CismapPreferences getCismapPrefs() { return cismapPrefs; } /** * DOCUMENT ME! * * @param duration DOCUMENT ME! * @param animationDuration DOCUMENT ME! * @param what DOCUMENT ME! * @param number DOCUMENT ME! */ public void flash(final int duration, final int animationDuration, final int what, final int number) { } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getDragPerformanceImproverLayer() { return dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @param dragPerformanceImproverLayer DOCUMENT ME! */ public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) { this.dragPerformanceImproverLayer = dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public PLayer getRasterServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getMapServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @param rasterServiceLayer DOCUMENT ME! */ public void setRasterServiceLayer(final PLayer rasterServiceLayer) { this.mapServicelayer = rasterServiceLayer; } /** * DOCUMENT ME! * * @param f DOCUMENT ME! */ public void showGeometryInfoPanel(final Feature f) { } /** * Adds a PropertyChangeListener to the listener list. * * @param l The listener to add. */ @Override public void addPropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.addPropertyChangeListener(l); } /** * Removes a PropertyChangeListener from the listener list. * * @param l The listener to remove. */ @Override public void removePropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.removePropertyChangeListener(l); } /** * Setter for property taskCounter. former synchronized method */ public void fireActivityChanged() { propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N } /** * Returns true, if there's still one layercontrol running. Else false; former synchronized method * * @return DOCUMENT ME! */ public boolean isRunning() { for (final LayerControl lc : layerControls) { if (lc.isRunning()) { return true; } } return false; } /** * Sets the visibility of all infonodes. * * @param visible true, if infonodes should be visible */ public void setInfoNodesVisible(final boolean visible) { infoNodesVisible = visible; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object elem = it.next(); if (elem instanceof PFeature) { ((PFeature)elem).setInfoNodeVisible(visible); } } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("setInfoNodesVisible()"); // NOI18N } } rescaleStickyNodes(); } /** * Adds an object to the historymodel. * * @param o Object to add */ @Override public void addToHistory(final Object o) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("addToHistory:" + o.toString()); // NOI18N } } historyModel.addToHistory(o); } /** * Removes a specific HistoryModelListener from the historymodel. * * @param hml HistoryModelListener */ @Override public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.removeHistoryModelListener(hml); } /** * Adds aHistoryModelListener to the historymodel. * * @param hml HistoryModelListener */ @Override public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.addHistoryModelListener(hml); } /** * Sets the maximum value of saved historyactions. * * @param max new integer value */ @Override public void setMaximumPossibilities(final int max) { historyModel.setMaximumPossibilities(max); } /** * Redos the last undone historyaction. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the forward-action */ @Override public Object forward(final boolean external) { final PBounds fwd = (PBounds)historyModel.forward(external); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("HistoryModel.forward():" + fwd); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(fwd); } return fwd; } /** * Undos the last action. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the back-action */ @Override public Object back(final boolean external) { final PBounds back = (PBounds)historyModel.back(external); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("HistoryModel.back():" + back); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(back); } return back; } /** * Returns true, if it's possible to redo an action. * * @return DOCUMENT ME! */ @Override public boolean isForwardPossible() { return historyModel.isForwardPossible(); } /** * Returns true, if it's possible to undo an action. * * @return DOCUMENT ME! */ @Override public boolean isBackPossible() { return historyModel.isBackPossible(); } /** * Returns a vector with all redo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getForwardPossibilities() { return historyModel.getForwardPossibilities(); } /** * Returns the current element of the historymodel. * * @return DOCUMENT ME! */ @Override public Object getCurrentElement() { return historyModel.getCurrentElement(); } /** * Returns a vector with all undo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getBackPossibilities() { return historyModel.getBackPossibilities(); } /** * Returns whether an internallayerwidget is available. * * @return DOCUMENT ME! */ @Deprecated public boolean isInternalLayerWidgetAvailable() { return this.getInternalWidget(LAYERWIDGET) != null; } /** * Sets the variable, if an internallayerwidget is available or not. * * @param internalLayerWidgetAvailable true, if available */ @Deprecated public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) { if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) { this.removeInternalWidget(LAYERWIDGET); } else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) { final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); } } /** * DOCUMENT ME! * * @param mme DOCUMENT ME! */ @Override public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) { } /** * Removes the mapservice from the rasterservicelayer. * * @param rasterService the removing mapservice */ @Override public void mapServiceRemoved(final MapService rasterService) { try { mapServicelayer.removeChild(rasterService.getPNode()); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_REMOVED, rasterService)); } System.gc(); } catch (final Exception e) { LOG.warn("Fehler bei mapServiceRemoved", e); // NOI18N } } /** * Adds the commited mapservice on the last position to the rasterservicelayer. * * @param mapService the new mapservice */ @Override public void mapServiceAdded(final MapService mapService) { addMapService(mapService, mapServicelayer.getChildrenCount()); if (mapService instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection()); } if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) { handleMapService(0, mapService, false); } } /** * Returns the current OGC scale. * * @return DOCUMENT ME! */ public double getCurrentOGCScale() { // funktioniert nur bei metrischen SRS's final double h = getCamera().getViewBounds().getHeight() / getHeight(); final double w = getCamera().getViewBounds().getWidth() / getWidth(); return Math.sqrt((h * h) + (w * w)); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public BoundingBox getCurrentBoundingBox() { return getCurrentBoundingBoxFromCamera(); } /** * <p>Returns the current BoundingBox.</p> * * @return DOCUMENT ME! */ public BoundingBox getCurrentBoundingBoxFromCamera() { if (fixedBoundingBox != null) { return fixedBoundingBox; } else { try { final PBounds bounds = getCamera().getViewBounds(); final double x1 = wtst.getWorldX(bounds.getX()); final double y1 = wtst.getWorldY(bounds.getY()); final double x2 = x1 + bounds.width; final double y2 = y1 - bounds.height; final Crs currentCrs = CismapBroker.getInstance().getSrs(); final boolean metric; // FIXME: this is a hack to overcome the "metric" issue for 4326 default srs if (CrsTransformer.getCurrentSrid() == 4326) { metric = false; } else { metric = currentCrs.isMetric(); } return new XBoundingBox(x1, y1, x2, y2, currentCrs.getCode(), metric); } catch (final Exception e) { LOG.error("cannot create bounding box from current view, return null", e); // NOI18N return null; } } } /** * Returns a BoundingBox with a fixed size. * * @return DOCUMENT ME! */ public BoundingBox getFixedBoundingBox() { return fixedBoundingBox; } /** * Assigns fixedBoundingBox a new value. * * @param fixedBoundingBox new boundingbox */ public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) { this.fixedBoundingBox = fixedBoundingBox; } /** * Paints the outline of the forwarded BoundingBox. * * @param bb BoundingBox */ public void outlineArea(final BoundingBox bb) { outlineArea(bb, null); } /** * Paints the outline of the forwarded PBounds. * * @param b PBounds */ public void outlineArea(final PBounds b) { outlineArea(b, null); } /** * Paints a filled rectangle of the area of the forwarded BoundingBox. * * @param bb BoundingBox * @param fillingPaint Color to fill the rectangle */ public void outlineArea(final BoundingBox bb, final Paint fillingPaint) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } outlineArea(pb, fillingPaint); } /** * Paints a filled rectangle of the area of the forwarded PBounds. * * @param b PBounds to paint * @param fillingColor Color to fill the rectangle */ public void outlineArea(final PBounds b, final Paint fillingColor) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { highlightingLayer.removeAllChildren(); } } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(fillingColor); rectangle.setStroke(new FixedWidthStroke()); rectangle.setStrokePaint(new Color(100, 100, 100, 255)); rectangle.setPathTo(b); highlightingLayer.addChild(rectangle); } } /** * Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally. * * @param bb BoundingBox to highlight */ public void highlightArea(final BoundingBox bb) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } highlightArea(pb); } /** * Highlights the delivered PBounds by painting over with a transparent white. * * @param b PBounds to hightlight */ private void highlightArea(final PBounds b) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { } highlightingLayer.animateToTransparency(0, animationDuration); highlightingLayer.removeAllChildren(); } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(new Color(255, 255, 255, 100)); rectangle.setStroke(null); rectangle.setPathTo(this.getCamera().getViewBounds()); highlightingLayer.addChild(rectangle); rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration); } } /** * Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls * crossHairPoint(Point p) internally. * * @param c coordinate of the crosshair's venue */ public void crossHairPoint(final Coordinate c) { Point p = null; if (c != null) { p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y)); } crossHairPoint(p); } /** * Paints a crosshair at the delivered point. * * @param p point of the crosshair's venue */ public void crossHairPoint(final Point p) { if (p == null) { if (crosshairLayer.getChildrenCount() > 0) { crosshairLayer.removeAllChildren(); } } else { crosshairLayer.removeAllChildren(); crosshairLayer.setTransparency(1); final PPath lineX = new PPath(); final PPath lineY = new PPath(); lineX.setStroke(new FixedWidthStroke()); lineX.setStrokePaint(new Color(100, 100, 100, 255)); lineY.setStroke(new FixedWidthStroke()); lineY.setStrokePaint(new Color(100, 100, 100, 255)); final PBounds current = getCamera().getViewBounds(); final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1); final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2); lineX.setPathTo(x); crosshairLayer.addChild(lineX); lineY.setPathTo(y); crosshairLayer.addChild(lineY); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public Element getConfiguration() { if (LOG.isDebugEnabled()) { LOG.debug("writing configuration <cismapMappingPreferences>"); // NOI18N } final Element ret = new Element("cismapMappingPreferences"); // NOI18N ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N ret.setAttribute( "creationMode", ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON); if (inputListener instanceof CreateSearchGeometryListener) { final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener; ret.setAttribute("createSearchMode", listener.getMode()); } // Position final Element currentPosition = new Element("Position"); // NOI18N currentPosition.addContent(getCurrentBoundingBoxFromCamera().getJDOMElement()); currentPosition.setAttribute("CRS", mappingModel.getSrs().getCode()); ret.addContent(currentPosition); // Crs final Element crsListElement = new Element("crsList"); for (final Crs tmp : crsList) { crsListElement.addContent(tmp.getJDOMElement()); } ret.addContent(crsListElement); if (printingSettingsDialog != null) { ret.addContent(printingSettingsDialog.getConfiguration()); } // save internal widgets status final Element widgets = new Element("InternalWidgets"); // NOI18N for (final String name : this.internalWidgets.keySet()) { final Element widget = new Element("Widget"); // NOI18N widget.setAttribute("name", name); // NOI18N widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N widgets.addContent(widget); } ret.addContent(widgets); return ret; } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void masterConfigure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N // CRS List try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N boolean defaultCrsFound = false; crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); crsList.add(s); if (s.isSelected() && s.isMetric()) { try { if (defaultCrsFound) { LOG.warn("More than one default CRS is set. " + "Please check your master configuration file."); // NOI18N } CismapBroker.getInstance().setDefaultCrs(s.getCode()); defaultCrsFound = true; transformer = new CrsTransformer(s.getCode()); } catch (final Exception ex) { LOG.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (final Exception skip) { LOG.error("Error while reading the crs list", skip); // NOI18N } if (CismapBroker.getInstance().getDefaultCrs() == null) { LOG.fatal("The default CRS is not set. This can lead to almost irreparable data errors. " + "Keep in mind: The default CRS must be metric"); // NOI18N } if (transformer == null) { LOG.error("No metric default crs found. Use EPSG:31466 as default crs"); // NOI18N try { transformer = new CrsTransformer("EPSG:31466"); // NOI18N CismapBroker.getInstance().setDefaultCrs("EPSG:31466"); // NOI18N } catch (final Exception ex) { LOG.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); // NOI18N } } // HOME try { if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N } } while (it.hasNext()) { final Element elem = it.next(); final String srs = elem.getAttribute("srs").getValue(); // NOI18N boolean metric = false; try { metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { LOG.warn("Metric hat falschen Syntax", dce); // NOI18N } boolean defaultVal = false; try { defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { LOG.warn("default hat falschen Syntax", dce); // NOI18N } final XBoundingBox xbox = new XBoundingBox(elem, srs, metric); alm.addHome(xbox); if (defaultVal) { Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(srs)) { crsObject = tmp; break; } } if (crsObject == null) { LOG.error("CRS " + srs + " from the default home is not found in the crs list"); crsObject = new Crs(srs, srs, srs, true, false); crsList.add(crsObject); } alm.setSrs(crsObject); alm.setDefaultHomeSrs(crsObject); CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } } } } catch (final Exception ex) { LOG.error("Fehler beim MasterConfigure der MappingComponent", ex); // NOI18N } try { final Element defaultCrs = prefs.getChild("defaultCrs"); final int defaultCrsInt = Integer.parseInt(defaultCrs.getAttributeValue("geometrySridAlias")); CismapBroker.getInstance().setDefaultCrsAlias(defaultCrsInt); } catch (final Exception ex) { LOG.error("Error while reading the default crs alias from the master configuration file.", ex); } try { final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N scales.clear(); for (final Object elem : scalesList) { if (elem instanceof Element) { final Scale s = new Scale((Element)elem); scales.add(s); } } } catch (final Exception skip) { LOG.error("Fehler beim Lesen von Scale", skip); // NOI18N } // Und jetzt noch die PriningEinstellungen initPrintingDialogs(); printingSettingsDialog.masterConfigure(prefs); } /** * Configurates this MappingComponent. * * @param e JDOM-Element with configuration */ @Override public void configure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); // the crs is equals to an other crs, if the code is equal. If a crs has in the // local configuration file an other name than in the master configuration file, // the old crs will be removed and the local one should be added to use the // local name and short name of the crs. if (crsList.contains(s)) { crsList.remove(s); } crsList.add(s); } } } catch (final Exception skip) { LOG.warn("Error while reading the crs list", skip); // NOI18N } // InteractionMode try { final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N setInteractionMode(interactMode); if (interactMode.equals(MappingComponent.NEW_POLYGON)) { try { final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode); } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des CreationInteractionMode", ex); // NOI18N } } } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des InteractionMode", ex); // NOI18N } try { final String createSearchMode = prefs.getAttribute("createSearchMode").getValue(); final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON); if ((inputListener instanceof CreateSearchGeometryListener) && (createSearchMode != null)) { final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener; listener.setMode(createSearchMode); } } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des CreateSearchMode", ex); // NOI18N } try { final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N setHandleInteractionMode(handleInterMode); } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des HandleInteractionMode", ex); // NOI18N } try { final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N LOG.info("snapping=" + snapping); // NOI18N setSnappingEnabled(snapping); setVisualizeSnappingEnabled(snapping); setInGlueIdenticalPointsMode(snapping); } catch (final Exception ex) { LOG.warn("Fehler beim setzen von snapping und Konsorten", ex); // NOI18N } // aktuelle Position try { final Element pos = prefs.getChild("Position"); // NOI18N final BoundingBox b = new BoundingBox(pos); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Position:" + b); // NOI18N } } final PBounds pb = b.getPBounds(getWtst()); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("PositionPb:" + pb); // NOI18N } } if (Double.isNaN(b.getX1()) || Double.isNaN(b.getX2()) || Double.isNaN(b.getY1()) || Double.isNaN(b.getY2())) { LOG.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); addToHistory(new PBoundsWithCleverToString( new PBounds(getMappingModel().getInitialBoundingBox().getPBounds(wtst)), wtst, crsCode)); } else { // set the current crs final Attribute crsAtt = pos.getAttribute("CRS"); if (crsAtt != null) { final String currentCrs = crsAtt.getValue(); Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(currentCrs)) { crsObject = tmp; break; } } if (crsObject == null) { LOG.error("CRS " + currentCrs + " from the position element is not found in the crs list"); } final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); if (alm instanceof ActiveLayerModel) { alm.setSrs(crsObject); } CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } this.initialBoundingBox = b; this.gotoBoundingBox(b, true, true, 0, false); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.fatal("added to History" + b); // NOI18N } } } } catch (final Exception ex) { LOG.warn("Fehler beim lesen der aktuellen Position", ex); // NOI18N this.gotoBoundingBox(getMappingModel().getInitialBoundingBox(), true, true, 0, false); } if (printingSettingsDialog != null) { printingSettingsDialog.configure(prefs); } try { final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N if (widgets != null) { for (final Object widget : widgets.getChildren()) { final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N this.showInternalWidget(name, visible, 0); } } } catch (final Exception ex) { LOG.warn("could not enable internal widgets: " + ex, ex); // NOI18N } } /** * Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent * will only pan to the featurecollection and not zoom. * * @param fixedScale true, if zoom is not allowed */ public void zoomToFeatureCollection(final boolean fixedScale) { zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale); } /** * Zooms to all features of the mappingcomponents featurecollection. */ public void zoomToFeatureCollection() { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("zoomToFeatureCollection"); // NOI18N } } zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration) { gotoBoundingBox(bb, history, scaleToFit, animationDuration, true); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation * @param queryServices true, if the services should be refreshed after animation */ public void gotoBoundingBox(BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration, final boolean queryServices) { if (bb != null) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } if (bb instanceof XBoundingBox) { if (!((XBoundingBox)bb).getSrs().equals(mappingModel.getSrs().getCode())) { try { final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode()); bb = trans.transformBoundingBox((XBoundingBox)bb); } catch (final Exception e) { LOG.warn("Cannot transform the bounding box", e); } } } final double x1 = getWtst().getScreenX(bb.getX1()); final double y1 = getWtst().getScreenY(bb.getY1()); final double x2 = getWtst().getScreenX(bb.getX2()); final double y2 = getWtst().getScreenY(bb.getY2()); final double w; final double h; final Rectangle2D pos = new Rectangle2D.Double(); pos.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { LOG.warn("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } showHandles(true); final Runnable handle = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(10); } catch (final Exception e) { LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (history) { if ((x1 == x2) || (y1 == y2) || !scaleToFit) { setNewViewBounds(getCamera().getViewBounds()); } else { setNewViewBounds(pos); } if (queryServices) { queryServices(); } } else { if (queryServices) { queryServicesWithoutHistory(); } } } }; CismetThreadPool.execute(handle); } else { LOG.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N } } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) { gotoBoundingBoxWithoutHistory(bb, animationDuration); } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox * @param animationDuration the animation duration */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb, final int animationDuration) { gotoBoundingBox(bb, false, true, animationDuration); } /** * Moves the view to the target Boundingbox and saves the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithHistory(final BoundingBox bb) { gotoBoundingBox(bb, true, true, animationDuration); } /** * Returns a BoundingBox of the current view in another scale. * * @param scaleDenominator specific target scale * * @return DOCUMENT ME! */ public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) { return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBoxFromCamera()); } /** * Returns the BoundingBox of the delivered BoundingBox in another scale. * * @param scaleDenominator specific target scale * @param bb source BoundingBox * * @return DOCUMENT ME! */ public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) { final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator; final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator; if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { // transform the given bounding box to a metric coordinate system bb = transformer.transformBoundingBox(bb, mappingModel.getSrs().getCode()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2); final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2); BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2), midY - (realWorldHeightInMeter / 2), midX + (realWorldWidthInMeter / 2), midY + (realWorldHeightInMeter / 2)); if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { // transform the scaled bounding box to the current coordinate system final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode()); scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } return scaledBox; } /** * Calculate the current scaledenominator. * * @return DOCUMENT ME! */ public double getScaleDenominator() { BoundingBox boundingBox = getCurrentBoundingBoxFromCamera(); final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { boundingBox = transformer.transformBoundingBox( boundingBox, mappingModel.getSrs().getCode()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } final double realWorldWidthInMeter = boundingBox.getWidth(); return realWorldWidthInMeter / screenWidthInMeter; } /** * Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code> * DropTarget</code> registered with this listener. * * <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code> * DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data * object(s) to be transfered.</p> * * <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int * dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P> * * <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be * invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData() * method.</P> * * <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the * drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method.</P> * * <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code> * Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only * if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code> * true</code>. Otherwise, the behavior of the call is implementation-dependent.</P> * * @param dtde the <code>DropTargetDropEvent</code> */ @Override public void drop(final DropTargetDropEvent dtde) { if (isDropEnabled(dtde)) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDropOnMap(mde); } catch (final Exception ex) { LOG.error("Error in drop", ex); // NOI18N } } } /** * DOCUMENT ME! * * @param dtde DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean isDropEnabled(final DropTargetDropEvent dtde) { if (ALKIS_PRINT.equals(getInteractionMode())) { for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) { // necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) { return false; } } } return true; } /** * Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site * for the <code>DropTarget</code> registered with this listener. * * @param dte the <code>DropTargetEvent</code> */ @Override public void dragExit(final DropTargetEvent dte) { } /** * Called if the user has modified the current drop gesture. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dropActionChanged(final DropTargetDragEvent dtde) { } /** * Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p * site for the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragOver(final DropTargetDragEvent dtde) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); // TODO: this seems to be buggy! final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDragOverMap(mde); } catch (final Exception ex) { LOG.error("Error in dragOver", ex); // NOI18N } } /** * Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for * the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragEnter(final DropTargetDragEvent dtde) { } /** * Returns the PfeatureHashmap which assigns a Feature to a PFeature. * * @return DOCUMENT ME! */ public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() { return pFeatureHM; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapExtent() { return fixedMapExtent; } /** * DOCUMENT ME! * * @param fixedMapExtent DOCUMENT ME! */ public void setFixedMapExtent(final boolean fixedMapExtent) { this.fixedMapExtent = fixedMapExtent; if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent( StatusEvent.MAP_EXTEND_FIXED, this.fixedMapExtent)); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapScale() { return fixedMapScale; } /** * DOCUMENT ME! * * @param fixedMapScale DOCUMENT ME! */ public void setFixedMapScale(final boolean fixedMapScale) { this.fixedMapScale = fixedMapScale; if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent( StatusEvent.MAP_SCALE_FIXED, this.fixedMapScale)); } } /** * DOCUMENT ME! * * @param one DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public void selectPFeatureManually(final PFeature one) { if (one != null) { featureCollection.select(one.getFeature()); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public PFeature getSelectedNode() { // gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist // deshalb gebe ich mal nur das erste zur�ck if (featureCollection.getSelectedFeatures().size() > 0) { final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0]; if (selF == null) { return null; } return pFeatureHM.get(selF); } else { return null; } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInfoNodesVisible() { return infoNodesVisible; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getPrintingFrameLayer() { return printingFrameLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PrintingSettingsWidget getPrintingSettingsDialog() { return printingSettingsDialog; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInGlueIdenticalPointsMode() { return inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @param inGlueIdenticalPointsMode DOCUMENT ME! */ public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) { this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHighlightingLayer() { return highlightingLayer; } /** * DOCUMENT ME! * * @param anno DOCUMENT ME! */ public void setPointerAnnotation(final PNode anno) { ((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno); } /** * DOCUMENT ME! * * @param visib DOCUMENT ME! */ public void setPointerAnnotationVisibility(final boolean visib) { if (getInputListener(MOTION) != null) { ((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib); } } /** * Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't * equal MOTION. * * @return DOCUMENT ME! */ public boolean isPointerAnnotationVisible() { if (getInputListener(MOTION) != null) { return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible(); } else { return false; } } /** * Returns a vector with different scales. * * @return DOCUMENT ME! */ public List<Scale> getScales() { return scales; } /** * Returns a list with different crs. * * @return DOCUMENT ME! */ public List<Crs> getCrsList() { return crsList; } /** * DOCUMENT ME! * * @return a transformer with the default crs as destination crs. The default crs is the first crs in the * configuration file that has set the selected attribut on true). This crs must be metric. */ public CrsTransformer getMetricTransformer() { return transformer; } /** * Locks the MappingComponent. */ public void lock() { locked = true; } /** * Unlocks the MappingComponent. */ public void unlock() { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("unlock"); // NOI18N } } locked = false; // if (DEBUG) { // if (LOG.isDebugEnabled()) { // LOG.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N // } // } gotoBoundingBoxWithHistory(getInitialBoundingBox()); } /** * Returns whether the MappingComponent is locked or not. * * @return DOCUMENT ME! */ public boolean isLocked() { return locked; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isMainMappingComponent() { return mainMappingComponent; } /** * Returns the MementoInterface for redo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemRedo() { return memRedo; } /** * Returns the MementoInterface for undo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemUndo() { return memUndo; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Map<String, PBasicInputEventHandler> getInputEventListener() { return inputEventListener; } /** * DOCUMENT ME! * * @param inputEventListener DOCUMENT ME! */ public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) { this.inputEventListener.clear(); this.inputEventListener.putAll(inputEventListener); } /** * DOCUMENT ME! * * @param event DOCUMENT ME! */ @Override public synchronized void crsChanged(final CrsChangedEvent event) { if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) { if (locked) { return; } final WaitDialog dialog = new WaitDialog(StaticSwingTools.getParentFrame(MappingComponent.this), false, NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).wait"), null); EventQueue.invokeLater(new Runnable() { @Override public void run() { try { StaticSwingTools.showDialog(dialog); // the wtst object should not be null, so the getWtst method will be invoked final WorldToScreenTransform oldWtst = getWtst(); final BoundingBox bbox = getCurrentBoundingBoxFromCamera(); // getCurrentBoundingBox(); final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode()); final BoundingBox newBbox = crsTransformer.transformBoundingBox( bbox, event.getFormerCrs().getCode()); if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); } wtst = null; getWtst(); gotoBoundingBoxWithoutHistory(newBbox, 0); final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures()); featureCollection.removeAllFeatures(); featureCollection.addFeatures(list); if (LOG.isDebugEnabled()) { LOG.debug("debug features added: " + list.size()); } // refresh all wfs layer if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.refreshWebFeatureServices(); alm.refreshShapeFileLayer(); } // transform the highlighting layer for (int i = 0; i < highlightingLayer.getChildrenCount(); ++i) { final PNode node = highlightingLayer.getChild(i); CrsTransformer.transformPNodeToGivenCrs( node, event.getFormerCrs().getCode(), event.getCurrentCrs().getCode(), oldWtst, getWtst()); rescaleStickyNode(node); } } catch (final Exception e) { JOptionPane.showMessageDialog( StaticSwingTools.getParentFrame(MappingComponent.this), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"), JOptionPane.ERROR_MESSAGE); LOG.error( "Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e); resetCrs = true; final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); CismapBroker.getInstance().setSrs(event.getFormerCrs()); } finally { if (dialog != null) { dialog.setVisible(false); } } } }); } else { resetCrs = false; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public JInternalFrame getInternalWidget(final String name) { if (this.internalWidgets.containsKey(name)) { return this.internalWidgets.get(name); } else { LOG.warn("unknown internal widget '" + name + "'"); // NOI18N return null; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public int getInternalWidgetPosition(final String name) { if (this.internalWidgetPositions.containsKey(name)) { return this.internalWidgetPositions.get(name); } else { LOG.warn("unknown position for '" + name + "'"); // NOI18N return -1; } } //~ Inner Classes ---------------------------------------------------------- /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class MappingComponentRasterServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); private final transient ServiceLayer rasterService; private final XPImage pi; private int position = -1; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentRasterServiceListener object. * * @param position DOCUMENT ME! * @param pn DOCUMENT ME! * @param rasterService DOCUMENT ME! */ public MappingComponentRasterServiceListener(final int position, final PNode pn, final ServiceLayer rasterService) { this.position = position; this.rasterService = rasterService; if (pn instanceof XPImage) { this.pi = (XPImage)pn; } else { this.pi = null; } } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { fireActivityChanged(); if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { this.log.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() // NOI18N + " Errors: " // NOI18N + e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N fireActivityChanged(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { final Point2D localOrigin = getCamera().getViewBounds().getOrigin(); final double localScale = getCamera().getViewScale(); final PBounds localBounds = getCamera().getViewBounds(); final Object o = e.getRetrievedObject(); if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } final Runnable paintImageOnMap = new Runnable() { @Override public void run() { fireActivityChanged(); if ((o instanceof Image) && (e.isHasErrors() == false)) { // TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden if (isBackgroundEnabled()) { final Image i = (Image)o; if (rasterService.getName().startsWith("prefetching")) { // NOI18N final double x = localOrigin.getX() - localBounds.getWidth(); final double y = localOrigin.getY() - localBounds.getHeight(); pi.setImage(i, 0); pi.setScale(3 / localScale); pi.setOffset(x, y); } else { pi.setImage(i, animationDuration * 2); pi.setScale(1 / localScale); pi.setOffset(localOrigin); MappingComponent.this.repaint(); } } } } }; if (EventQueue.isDispatchThread()) { paintImageOnMap.run(); } else { EventQueue.invokeLater(paintImageOnMap); } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { this.log.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, rasterService)); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getPosition() { return position; } /** * DOCUMENT ME! * * @param position DOCUMENT ME! */ public void setPosition(final int position) { this.position = position; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class DocumentProgressListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); /** Displays the loading progress of Documents, e.g. SHP Files */ private final transient DocumentProgressWidget documentProgressWidget; private transient long requestId = -1; //~ Constructors ------------------------------------------------------- /** * Creates a new DocumentProgressListener object. */ public DocumentProgressListener() { documentProgressWidget = new DocumentProgressWidget(); documentProgressWidget.setVisible(false); if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) { MappingComponent.this.addInternalWidget( MappingComponent.PROGRESSWIDGET, MappingComponent.POSITION_SOUTHWEST, documentProgressWidget); } } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != -1) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = e.getRequestIdentifier(); this.documentProgressWidget.setServiceName(e.getRetrievalService().toString()); this.documentProgressWidget.setProgress(-1); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N } if (DEBUG) { if (log.isDebugEnabled()) { log.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: initialisation progress: " + e.getPercentageDone()); // NOI18N } } this.documentProgressWidget.setProgress(e.getPercentageDone()); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N } e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(100); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; e.getRetrievalService().removeRetrievalListener(this); this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public long getRequestId() { return this.requestId; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class MappingComponentFeatureServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); private final transient ServiceLayer featureService; private final transient PLayer parent; private long requestIdentifier; private Thread completionThread; private final List deletionCandidates; private final List twins; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentFeatureServiceListener. * * @param featureService the featureretrievalservice * @param parent the featurelayer (PNode) connected with the servicelayer */ public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) { this.featureService = featureService; this.parent = parent; this.deletionCandidates = new ArrayList(); this.twins = new ArrayList(); } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { requestIdentifier = e.getRequestIdentifier(); } if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N } } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: " + e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress() + ")"); // NOI18N } } fireActivityChanged(); // TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das // flüssiger ist } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { this.log.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N } } if (e.isInitialisationEvent()) { this.log.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: initialisation complete"); // NOI18N fireActivityChanged(); return; } if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N } ((RetrievalServiceLayer)featureService).setProgress(-1); fireActivityChanged(); return; } final List newFeatures = new ArrayList(); EventQueue.invokeLater(new Runnable() { @Override public void run() { ((RetrievalServiceLayer)featureService).setProgress(-1); parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible()); } }); // clear all old data to delete twins deletionCandidates.clear(); twins.clear(); // if it's a refresh, add all old features which should be deleted in the // newly acquired featurecollection if (!e.isRefreshExisting()) { deletionCandidates.addAll(parent.getChildrenReference()); } if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N } } // only start parsing the features if there are no errors and a correct collection if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) { completionThread = new Thread() { @Override public void run() { // this is the collection with the retrieved features final List features = new ArrayList((Collection)e.getRetrievedObject()); final int size = features.size(); int counter = 0; final Iterator it = features.iterator(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N } } while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted() && it.hasNext()) { counter++; final Object o = it.next(); if (o instanceof Feature) { final PFeature p = new PFeature(((Feature)o), wtst, clip_offset_x, clip_offset_y, MappingComponent.this); PFeature twin = null; for (final Object tester : deletionCandidates) { // if tester and PFeature are FeatureWithId-objects if ((((PFeature)tester).getFeature() instanceof FeatureWithId) && (p.getFeature() instanceof FeatureWithId)) { final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId(); final int id2 = ((FeatureWithId)(p.getFeature())).getId(); if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id if (id1 == id2) { twin = ((PFeature)tester); break; } } else { // else test the geometry for equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } else { // no FeatureWithId, test geometries for // equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } // if a twin is found remove him from the deletion candidates // and add him to the twins if (twin != null) { deletionCandidates.remove(twin); twins.add(twin); } else { // else add the PFeature to the new features newFeatures.add(p); } // calculate the advance of the progressbar // fire event only wheen needed final int currentProgress = (int)((double)counter / (double)size * 100d); if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) { ((RetrievalServiceLayer)featureService).setProgress(currentProgress); fireActivityChanged(); } } } if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) { // after all features are computed do stuff on the EDT EventQueue.invokeLater(new Runnable() { @Override public void run() { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N } } // if it's a refresh, delete all previous features if (e.isRefreshExisting()) { parent.removeAllChildren(); } final List deleteFeatures = new ArrayList(); for (final Object o : newFeatures) { parent.addChild((PNode)o); } // set the prograssbar to full if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: set progress to 100"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(100); fireActivityChanged(); // repaint the featurelayer parent.repaint(); // remove stickyNode from all deletionCandidates and add // each to the new deletefeature-collection for (final Object o : deletionCandidates) { if (o instanceof PFeature) { final PNode p = ((PFeature)o).getPrimaryAnnotationNode(); if (p != null) { removeStickyNode(p); } deleteFeatures.add(o); } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount before:" + parent.getChildrenCount()); // NOI18N } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: deleteFeatures=" + deleteFeatures.size()); // + " :" + // deleteFeatures);//NOI18N } } parent.removeChildren(deleteFeatures); if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount after:" + parent.getChildrenCount()); // NOI18N } } if (LOG.isInfoEnabled()) { LOG.info( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + parent.getChildrenCount() + " features retrieved or updated"); // NOI18N } rescaleStickyNodes(); } catch (final Exception exception) { log.warn( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Fehler beim Aufr\u00E4umen", exception); // NOI18N } } }); } else { if (DEBUG) { if (log.isDebugEnabled()) { log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } }; completionThread.setPriority(Thread.NORM_PRIORITY); if (requestIdentifier == e.getRequestIdentifier()) { completionThread.start(); } else { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: aborted, TaskCounter:" + taskCounter); // NOI18N if (completionThread != null) { completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(-1); } else { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(0); } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, featureService)); } } } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ class ImageSelection implements Transferable { //~ Instance fields -------------------------------------------------------- private Image image; //~ Constructors ----------------------------------------------------------- /** * Creates a new ImageSelection object. * * @param image DOCUMENT ME! */ public ImageSelection(final Image image) { this.image = image; } //~ Methods ---------------------------------------------------------------- /** * Returns supported flavors. * * @return DOCUMENT ME! */ @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; } /** * Returns true if flavor is supported. * * @param flavor DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public boolean isDataFlavorSupported(final DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } /** * Returns image. * * @param flavor DOCUMENT ME! * * @return DOCUMENT ME! * * @throws UnsupportedFlavorException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ @Override public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (!DataFlavor.imageFlavor.equals(flavor)) { throw new UnsupportedFlavorException(flavor); } return image; } }
false
true
public void setInteractionMode(final String interactionMode) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:" + this.interactionMode + "", new Exception()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } setPointerAnnotationVisibility(false); if (getPrintingFrameLayer().getChildrenCount() > 1) { getPrintingFrameLayer().removeAllChildren(); } if (this.interactionMode != null) { if (interactionMode.equals(FEATURE_INFO)) { ((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo() .setVisible(true); } else { ((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo() .setVisible(false); } if (isReadOnly()) { ((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class); } final PInputEventListener pivl = this.getInputListener(this.interactionMode); if (pivl != null) { removeInputEventListener(pivl); } else { LOG.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N } if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) { featureCollection.unselectAll(); } if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEAR_REFERENCING) || interactionMode.equals(SPLIT_POLYGON)) && (this.readOnly == false)) { featureSelectionChanged(null); } if (interactionMode.equals(JOIN_POLYGONS)) { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent( this, PROPERTY_MAP_INTERACTION_MODE, this.interactionMode, interactionMode); this.interactionMode = interactionMode; final PInputEventListener pivl = getInputListener(interactionMode); if (pivl != null) { addInputEventListener(pivl); propertyChangeSupport.firePropertyChange(interactionModeChangedEvent); CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode)); } else { LOG.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N } } catch (final Exception e) { LOG.error("Fehler beim Ändern des InteractionModes", e); // NOI18N } } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Deprecated public void formComponentResized(final ComponentEvent evt) { this.componentResizedDelayed(); } /** * Resizes the map and does not reload all services. * * @see #componentResizedDelayed() */ public void componentResizedIntermediate() { if (!this.isLocked()) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { // rescale map if (historyModel.getCurrentElement() != null) { PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds == null) { bounds = initialBoundingBox.getPBounds(wtst); } if (bounds.getWidth() < 0) { bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight()); } if (bounds.getHeight() < 0) { bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1)); } getCamera().animateViewToCenterBounds(bounds, true, animationDuration); } } } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } /** * Resizes the map and reloads all services. * * @see #componentResizedIntermediate() */ public void componentResizedDelayed() { if (!this.isLocked()) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { final PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds != null) { gotoBoundsWithoutHistory(bounds); } else { gotoBoundsWithoutHistory(getInitialBoundingBox().getPBounds(wtst)); } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } } catch (final Exception t) { LOG.error("Fehler in formComponentResized()", t); // NOI18N } } } /** * syncSelectedObjectPresenter(int i). * * @param i DOCUMENT ME! */ public void syncSelectedObjectPresenter(final int i) { selectedObjectPresenter.setVisible(true); if (featureCollection.getSelectedFeatures().size() > 0) { if (featureCollection.getSelectedFeatures().size() == 1) { final PFeature selectedFeature = (PFeature)pFeatureHM.get( featureCollection.getSelectedFeatures().toArray()[0]); if (selectedFeature != null) { selectedObjectPresenter.getCamera() .animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2); } } else { // todo } } else { LOG.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public BoundingBox getInitialBoundingBox() { if (initialBoundingBox == null) { return mappingModel.getInitialBoundingBox(); } else { return initialBoundingBox; } } /** * Returns the current featureCollection. * * @return DOCUMENT ME! */ public FeatureCollection getFeatureCollection() { return featureCollection; } /** * Replaces the old featureCollection with a new one. * * @param featureCollection the new featureCollection */ public void setFeatureCollection(final FeatureCollection featureCollection) { this.featureCollection = featureCollection; featureCollection.addFeatureCollectionListener(this); } /** * DOCUMENT ME! * * @param visibility DOCUMENT ME! */ public void setFeatureCollectionVisibility(final boolean visibility) { featureLayer.setVisible(visibility); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFeatureCollectionVisible() { return featureLayer.getVisible(); } /** * Adds a new mapservice at a specific place of the layercontrols. * * @param mapService the new mapservice * @param position the index where to position the mapservice */ public void addMapService(final MapService mapService, final int position) { try { PNode p = new PNode(); if (mapService instanceof RasterMapService) { LOG.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N if (mapService.getPNode() instanceof XPImage) { p = (XPImage)mapService.getPNode(); } else { p = new XPImage(); mapService.setPNode(p); } mapService.addRetrievalListener(new MappingComponentRasterServiceListener( position, p, (ServiceLayer)mapService)); } else { LOG.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName() + ")"); // NOI18N p = new PLayer(); mapService.setPNode(p); if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): isDocumentFeatureService, checking document size"); // NOI18N } } final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService; if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) { LOG.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '" + documentFeatureService.getName() + "' size of " + (documentFeatureService.getDocumentSize() / 1000000) + "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000) + "MB)"); // NOI18N if (this.documentProgressListener == null) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): lazy instantiation of documentProgressListener"); // NOI18N } } this.documentProgressListener = new DocumentProgressListener(); } if (this.documentProgressListener.getRequestId() != -1) { LOG.error("FeatureMapService(" + mapService + "): The documentProgressListener is already in use by request '" + this.documentProgressListener.getRequestId() + ", document progress cannot be tracked"); // NOI18N } else { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N } } documentFeatureService.addRetrievalListener(this.documentProgressListener); } } } mapService.addRetrievalListener(new MappingComponentFeatureServiceListener( (ServiceLayer)mapService, (PLayer)mapService.getPNode())); } p.setTransparency(mapService.getTranslucency()); p.setVisible(mapService.isVisible()); mapServicelayer.addChild(p); } catch (final Exception e) { LOG.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + e.getMessage(), e); // NOI18N } } /** * DOCUMENT ME! * * @param mm DOCUMENT ME! */ public void preparationSetMappingModel(final MappingModel mm) { mappingModel = mm; } /** * Sets a new mappingmodel in this MappingComponent. * * @param mm the new mappingmodel */ public void setMappingModel(final MappingModel mm) { LOG.info("setMappingModel"); // NOI18N // FIXME: why is the default uncaught exception handler set in such a random place? if (Thread.getDefaultUncaughtExceptionHandler() == null) { LOG.info("setDefaultUncaughtExceptionHandler"); // NOI18N Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { LOG.error("Error", e); } }); } mappingModel = mm; // currentBoundingBox = mm.getInitialBoundingBox(); final Runnable r = new Runnable() { @Override public void run() { mappingModel.addMappingModelListener(MappingComponent.this); final TreeMap rs = mappingModel.getRasterServices(); // Rückwärts wegen der Reihenfolge der Layer im Layer Widget final Iterator it = rs.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { addMapService(((MapService)o), rsi); } } adjustLayers(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Set Mapping Modell done"); // NOI18N } } } }; CismetThreadPool.execute(r); } /** * Returns the current mappingmodel. * * @return current mappingmodel */ public MappingModel getMappingModel() { return mappingModel; } /** * Animates a component to a given x/y-coordinate in a given time. * * @param c the component to animate * @param toX final x-position * @param toY final y-position * @param animationDuration duration of the animation * @param hideAfterAnimation should the component be hidden after animation? */ private void animateComponent(final JComponent c, final int toX, final int toY, final int animationDuration, final boolean hideAfterAnimation) { if (animationDuration > 0) { final int x = (int)c.getBounds().getX() - toX; final int y = (int)c.getBounds().getY() - toY; int sx; int sy; if (x > 0) { sx = -1; } else { sx = 1; } if (y > 0) { sy = -1; } else { sy = 1; } int big; if (Math.abs(x) > Math.abs(y)) { big = Math.abs(x); } else { big = Math.abs(y); } final int sleepy; if ((animationDuration / big) < 1) { sleepy = 1; } else { sleepy = animationDuration / big; } final int directionY = sy; final int directionX = sx; if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY + ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX=" + toX + ", toY=" + toY); // NOI18N } } final Thread timer = new Thread() { @Override public void run() { while (!isInterrupted()) { try { sleep(sleepy); } catch (final Exception iex) { } EventQueue.invokeLater(new Runnable() { @Override public void run() { int currentY = (int)c.getBounds().getY(); int currentX = (int)c.getBounds().getX(); if (currentY != toY) { currentY = currentY + directionY; } if (currentX != toX) { currentX = currentX + directionX; } c.setBounds(currentX, currentY, c.getWidth(), c.getHeight()); } }); if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) { if (hideAfterAnimation) { EventQueue.invokeLater(new Runnable() { @Override public void run() { c.setVisible(false); c.hide(); } }); } break; } } } }; timer.setPriority(Thread.NORM_PRIORITY); timer.start(); } else { c.setBounds(toX, toY, c.getWidth(), c.getHeight()); if (hideAfterAnimation) { c.setVisible(false); } } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ @Deprecated public NewSimpleInternalLayerWidget getInternalLayerWidget() { return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET); } /** * Adds a new internal widget to the map.<br/> * If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget * will be added. If a widget with a different name already exisit at the same {@code position} the new widget will * not be added and the operation returns {@code false}. * * @param name unique name of the widget * @param position position of the widget * @param widget the widget * * @return {@code true} if the widget could be added, {@code false} otherwise * * @see #POSITION_NORTHEAST * @see #POSITION_NORTHWEST * @see #POSITION_SOUTHEAST * @see #POSITION_SOUTHWEST */ public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) { if (LOG.isDebugEnabled()) { LOG.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N } if (this.internalWidgets.containsKey(name)) { LOG.warn("widget '" + name + "' already added, removing old widget"); // NOI18N this.remove(this.getInternalWidget(name)); } else if (this.internalWidgetPositions.containsValue(position)) { LOG.warn("widget position '" + position + "' already taken"); // NOI18N return false; } this.internalWidgets.put(name, widget); this.internalWidgetPositions.put(name, position); widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N this.add(widget); widget.pack(); return true; } /** * Removes an existing internal widget from the map. * * @param name name of the widget to be removed * * @return {@code true} id the widget was found and removed, {@code false} otherwise */ public boolean removeInternalWidget(final String name) { if (LOG.isDebugEnabled()) { LOG.debug("removing internal widget '" + name + "'"); // NOI18N } if (!this.internalWidgets.containsKey(name)) { LOG.warn("widget '" + name + "' not found"); // NOI18N return false; } this.remove(this.getInternalWidget(name)); this.internalWidgets.remove(name); this.internalWidgetPositions.remove(name); return true; } /** * Shows an InternalWidget by sliding it into the mappingcomponent. * * @param name name of the internl component to show * @param visible should the widget be visible after the animation? * @param animationDuration duration of the animation * * @return {@code true} if the operation was successful, {@code false} otherwise */ public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) { final JInternalFrame internalWidget = this.getInternalWidget(name); if (internalWidget == null) { return false; } final int positionX; final int positionY; final int widgetPosition = this.getInternalWidgetPosition(name); final boolean isHigher = (getHeight() < (internalWidget.getHeight() + 2)) && (getHeight() > 0); final boolean isWider = (getWidth() < (internalWidget.getWidth() + 2)) && (getWidth() > 0); switch (widgetPosition) { case POSITION_NORTHWEST: { positionX = 1; positionY = 1; break; } case POSITION_SOUTHWEST: { positionX = 1; positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1); break; } case POSITION_NORTHEAST: { positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1); positionY = 1; break; } case POSITION_SOUTHEAST: { positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1); positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1); break; } default: { LOG.warn("unkown widget position?!"); // NOI18N return false; } } if (visible) { final int toY; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { if (isHigher) { toY = getHeight() - 1; } else { toY = positionY - internalWidget.getHeight() - 1; } } else { if (isHigher) { toY = getHeight() + 1; } else { toY = positionY + internalWidget.getHeight() + 1; } } internalWidget.setBounds( positionX, toY, isWider ? (getWidth() - 2) : internalWidget.getWidth(), isHigher ? (getHeight() - 2) : internalWidget.getHeight()); internalWidget.setVisible(true); internalWidget.show(); animateComponent(internalWidget, positionX, positionY, animationDuration, false); } else { internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight()); int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } animateComponent(internalWidget, positionX, toY, animationDuration, true); } return true; } /** * DOCUMENT ME! * * @param visible DOCUMENT ME! * @param animationDuration DOCUMENT ME! */ @Deprecated public void showInternalLayerWidget(final boolean visible, final int animationDuration) { this.showInternalWidget(LAYERWIDGET, visible, animationDuration); } /** * Returns a boolean, if the InternalLayerWidget is visible. * * @return true, if visible, else false */ @Deprecated public boolean isInternalLayerWidgetVisible() { return this.getInternalLayerWidget().isVisible(); } /** * Returns a boolean, if the InternalWidget is visible. * * @param name name of the widget * * @return true, if visible, else false */ public boolean isInternalWidgetVisible(final String name) { final JInternalFrame widget = this.getInternalWidget(name); if (widget != null) { return widget.isVisible(); } return false; } /** * Moves the camera to the initial bounding box (e.g. if the home-button is pressed). */ public void gotoInitialBoundingBox() { final double x1; final double y1; final double x2; final double y2; final double w; final double h; x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1()); y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1()); x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2()); y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2()); final Rectangle2D home = new Rectangle2D.Double(); home.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(home, true, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { LOG.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } setNewViewBounds(home); queryServices(); } /** * Refreshs all registered services. */ public void queryServices() { if (newViewBounds != null) { addToHistory(new PBoundsWithCleverToString( new PBounds(newViewBounds), wtst, mappingModel.getSrs().getCode())); queryServicesWithoutHistory(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServices()"); // NOI18N } } rescaleStickyNodes(); } } /** * Forces all services to refresh themselves. */ public void refresh() { forceQueryServicesWithoutHistory(); } /** * Forces all services to refresh themselves. */ private void forceQueryServicesWithoutHistory() { queryServicesWithoutHistory(true); } /** * Refreshs all services, but not forced. */ private void queryServicesWithoutHistory() { queryServicesWithoutHistory(false); } /** * Waits until all animations are done, then iterates through all registered services and calls handleMapService() * for each. * * @param forced forces the refresh */ private void queryServicesWithoutHistory(final boolean forced) { if (forced && mainMappingComponent) { CismapBroker.getInstance().fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_RESET, this)); } if (!locked) { final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception doNothing) { } } CismapBroker.getInstance().fireMapBoundsChanged(); if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N } } handleMapService(rsi, (MapService)o, forced); } else { LOG.warn("service is not of type MapService:" + o); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof MapService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N } } handleMapService(fsi, (MapService)o, forced); } else { LOG.warn("service is not of type MapService:" + o); // NOI18N } } } } }; CismetThreadPool.execute(r); } } /** * queryServicesIndependentFromMap. * * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param rl DOCUMENT ME! */ public void queryServicesIndependentFromMap(final int width, final int height, final BoundingBox bb, final RetrievalListener rl) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N } } final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception doNothing) { } } if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer) && ((ServiceLayer)o).isEnabled() && (o instanceof RetrievalServiceLayer) && ((RetrievalServiceLayer)o).getPNode().getVisible()) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = wfsClone; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(rsi); handleMapService(rsi, (MapService)r, width, height, bb, true); } catch (final Exception t) { LOG.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N } } else { LOG.warn("ignoring service '" + o + "' for printing"); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof AbstractRetrievalService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = (AbstractRetrievalService)o; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(fsi); handleMapService(fsi, (MapService)r, 0, 0, bb, true); } } } } }; CismetThreadPool.execute(r); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param service rs * @param forced DOCUMENT ME! */ public void handleMapService(final int position, final MapService service, final boolean forced) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("in handleRasterService: " + service + "(" + Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N } } final PBounds bounds = getCamera().getViewBounds(); final BoundingBox bb = new BoundingBox(); final double x1 = getWtst().getWorldX(bounds.getMinX()); final double y1 = getWtst().getWorldY(bounds.getMaxY()); final double x2 = getWtst().getWorldX(bounds.getMaxX()); final double y2 = getWtst().getWorldY(bounds.getMinY()); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Bounds=" + bounds); // NOI18N } } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N } } if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N bb.setX1(x1 - (x2 - x1)); bb.setY1(y1 - (y2 - y1)); bb.setX2(x2 + (x2 - x1)); bb.setY2(y2 + (y2 - y1)); } else { bb.setX1(x1); bb.setY1(y1); bb.setX2(x2); bb.setY2(y2); } handleMapService(position, service, getWidth(), getHeight(), bb, forced); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param rs DOCUMENT ME! * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param forced DOCUMENT ME! */ private void handleMapService(final int position, final MapService rs, final int width, final int height, final BoundingBox bb, final boolean forced) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("handleMapService: " + rs); // NOI18N } } rs.setSize(height, width); if (((ServiceLayer)rs).isEnabled()) { synchronized (serviceFuturesMap) { final Future<?> sf = serviceFuturesMap.get(rs); if ((sf == null) || sf.isDone()) { final Runnable serviceCall = new Runnable() { @Override public void run() { try { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception e) { } } rs.setBoundingBox(bb); if (rs instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection); } rs.retrieve(forced); } finally { serviceFuturesMap.remove(rs); } } }; synchronized (serviceFuturesMap) { serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall)); } } } } else { rs.setBoundingBox(bb); } } /** * Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it. * * @return new WorldToScreenTransform or null */ public WorldToScreenTransform getWtst() { try { if (wtst == null) { final double y_real = mappingModel.getInitialBoundingBox().getY2() - mappingModel.getInitialBoundingBox().getY1(); final double x_real = mappingModel.getInitialBoundingBox().getX2() - mappingModel.getInitialBoundingBox().getX1(); double clip_height; double clip_width; double x_screen = getWidth(); double y_screen = getHeight(); if (x_screen == 0) { x_screen = 100; } if (y_screen == 0) { y_screen = 100; } if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert clip_height = x_screen * y_real / x_real; clip_width = x_screen; clip_offset_y = 0; // (y_screen-clip_height)/2; clip_offset_x = 0; } else { // Y ist Bestimmer clip_height = y_screen; clip_width = y_screen * x_real / y_real; clip_offset_y = 0; clip_offset_x = 0; // (x_screen-clip_width)/2; } wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(), mappingModel.getInitialBoundingBox().getY2()); } return wtst; } catch (final Exception t) { LOG.error("Fehler in getWtst()", t); // NOI18N return null; } } /** * Resets the current WorldToScreenTransformation. */ public void resetWtst() { wtst = null; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_x() { return 0; // clip_offset_x; } /** * Assigns a new value to the x-clip-offset. * * @param clip_offset_x new clipoffset */ public void setClip_offset_x(final double clip_offset_x) { this.clip_offset_x = clip_offset_x; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_y() { return 0; // clip_offset_y; } /** * Assigns a new value to the y-clip-offset. * * @param clip_offset_y new clipoffset */ public void setClip_offset_y(final double clip_offset_y) { this.clip_offset_y = clip_offset_y; } /** * Returns the rubberband-PLayer. * * @return DOCUMENT ME! */ public PLayer getRubberBandLayer() { return rubberBandLayer; } /** * Assigns a given PLayer to the variable rubberBandLayer. * * @param rubberBandLayer a PLayer */ public void setRubberBandLayer(final PLayer rubberBandLayer) { this.rubberBandLayer = rubberBandLayer; } /** * Sets new viewbounds. * * @param r2d Rectangle2D */ public void setNewViewBounds(final Rectangle2D r2d) { newViewBounds = r2d; } /** * Will be called if the selection of features changes. It selects the PFeatures connected to the selected features * of the featurecollectionevent and moves them to the front. Also repaints handles at the end. * * @param fce featurecollectionevent with selected features */ @Override public void featureSelectionChanged(final FeatureCollectionEvent fce) { final Collection allChildren = featureLayer.getChildrenReference(); final ArrayList<PFeature> all = new ArrayList<PFeature>(); for (final Object o : allChildren) { if (o instanceof PFeature) { all.add((PFeature)o); } else if (o instanceof PLayer) { // Handling von Feature-Gruppen-Layer, welche als Kinder dem Feature Layer hinzugefügt wurden all.addAll(((PLayer)o).getChildrenReference()); } } // final Collection<PFeature> all = featureLayer.getChildrenReference(); for (final PFeature f : all) { f.setSelected(false); } Collection<Feature> c; if (fce != null) { c = fce.getFeatureCollection().getSelectedFeatures(); } else { c = featureCollection.getSelectedFeatures(); } ////handle featuregroup select-delegation//// final Set<Feature> selectionResult = new HashSet<Feature>(); for (final Feature current : c) { if (current instanceof FeatureGroup) { selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current)); } else { selectionResult.add(current); } } c = selectionResult; for (final Feature f : c) { if (f != null) { final PFeature feature = getPFeatureHM().get(f); if (feature != null) { if (feature.getParent() != null) { feature.getParent().moveToFront(); } feature.setSelected(true); feature.moveToFront(); // Fuer den selectedObjectPresenter (Eigener PCanvas) syncSelectedObjectPresenter(1000); } else { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } } showHandles(false); } /** * Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on * each feature of the given featurecollectionevent. Repaints handles at the end. * * @param fce featurecollectionevent with changed features */ @Override public void featuresChanged(final FeatureCollectionEvent fce) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("featuresChanged"); // NOI18N } } final List<Feature> list = new ArrayList<Feature>(); list.addAll(fce.getEventFeatures()); for (final Feature elem : list) { reconsiderFeature(elem); } showHandles(false); } /** * Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls * following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode() * * @param fce featurecollectionevent with features to reconsile */ @Override public void featureReconsiderationRequested(final FeatureCollectionEvent fce) { for (final Feature f : fce.getEventFeatures()) { if (f != null) { final PFeature node = pFeatureHM.get(f); if (node != null) { node.syncGeometry(); node.visualize(); node.resetInfoNodePosition(); node.refreshInfoNode(); repaint(); } } } } /** * Method is deprecated and deactivated. Does nothing!! * * @param fce FeatureCollectionEvent with features to add */ @Override @Deprecated public void featuresAdded(final FeatureCollectionEvent fce) { } /** * Method is deprecated and deactivated. Does nothing!! * * @deprecated DOCUMENT ME! */ @Override @Deprecated public void featureCollectionChanged() { } /** * Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a * checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent. * * @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice */ @Override public void allFeaturesRemoved(final FeatureCollectionEvent fce) { for (final PFeature feature : pFeatureHM.values()) { feature.cleanup(); } stickyPNodes.clear(); pFeatureHM.clear(); featureLayer.removeAllChildren(); // Lösche alle Features in den Gruppen-Layer, aber füge den Gruppen-Layer wieder dem FeatureLayer hinzu for (final PLayer layer : featureGrpLayerMap.values()) { layer.removeAllChildren(); featureLayer.addChild(layer); } checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); } /** * Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining * supporting rasterservices and paints handles at the end. * * @param fce FeatureCollectionEvent with features to remove */ @Override public void featuresRemoved(final FeatureCollectionEvent fce) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("featuresRemoved"); // NOI18N } } removeFeatures(fce.getEventFeatures()); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); showHandles(false); } /** * Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and * which need a refresh. * * @param fce FeatureCollectionEvent with removed features */ private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) { final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>(); for (final Feature f : getFeatureCollection().getAllFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } rasterServices.add(rs); // DANGER } } for (final Feature f : fce.getEventFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } if (rasterServices.contains(rs)) { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r); } } } else { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r); } } } } } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) { getMappingModel().removeLayer(frs); } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) { handleMapService(0, frs, true); } } /** * public void showFeatureCollection(Feature[] features) { com.vividsolutions.jts.geom.Envelope * env=computeFeatureEnvelope(features); showFeatureCollection(features,env); } public void * showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { selectedFeature=null; * handleLayer.removeAllChildren(); //setRasterServiceLayerImagesVisibility(false); Envelope eSquare=null; * HashSet<Feature> featureSet=new HashSet<Feature>(); featureSet.addAll(holdFeatures); * featureSet.addAll(java.util.Arrays.asList(f)); Feature[] features=featureSet.toArray(new Feature[0]); * pFeatureHM.clear(); addFeaturesToMap(features); zoomToFullFeatureCollectionBounds(); }. * * @param groupId DOCUMENT ME! * @param visible DOCUMENT ME! */ public void setGroupLayerVisibility(final String groupId, final boolean visible) { final PLayer layer = this.featureGrpLayerMap.get(groupId); if (layer != null) { layer.setVisible(visible); } } /** * is called when new feature is added to FeatureCollection. * * @param features DOCUMENT ME! */ public void addFeaturesToMap(final Feature[] features) { final double local_clip_offset_y = clip_offset_y; final double local_clip_offset_x = clip_offset_x; /// Hier muss der layer bestimmt werdenn for (int i = 0; i < features.length; ++i) { final Feature feature = features[i]; final PFeature p = new PFeature( feature, getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); try { if (feature instanceof StyledFeature) { p.setTransparency(((StyledFeature)(feature)).getTransparency()); } else { p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); } EventQueue.invokeLater(new Runnable() { @Override public void run() { if (feature instanceof FeatureGroupMember) { final FeatureGroupMember fgm = (FeatureGroupMember)feature; final String groupId = fgm.getGroupId(); PLayer groupLayer = featureGrpLayerMap.get(groupId); if (groupLayer == null) { groupLayer = new PLayer(); featureLayer.addChild(groupLayer); featureGrpLayerMap.put(groupId, groupLayer); if (LOG.isDebugEnabled()) { LOG.debug("created layer for group " + groupId); } } groupLayer.addChild(p); if (fgm.getGeometry() != null) { pFeatureHM.put(fgm.getFeature(), p); pFeatureHM.put(fgm, p); } if (LOG.isDebugEnabled()) { LOG.debug("added feature to group " + groupId); } } } }); } catch (final Exception e) { p.setTransparency(0.8f); LOG.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N } // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) if (!(feature instanceof FeatureGroupMember)) { if (feature.getGeometry() != null) { pFeatureHM.put(p.getFeature(), p); final int ii = i; EventQueue.invokeLater(new Runnable() { @Override public void run() { featureLayer.addChild(p); if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { p.moveToFront(); } } }); } } } EventQueue.invokeLater(new Runnable() { @Override public void run() { rescaleStickyNodes(); repaint(); fireFeaturesAddedToMap(Arrays.asList(features)); // SuchFeatures in den Vordergrund stellen for (final Feature feature : featureCollection.getAllFeatures()) { if (feature instanceof SearchFeature) { final PFeature pFeature = pFeatureHM.get(feature); pFeature.moveToFront(); } } } }); // check whether the feature has a rasterSupportLayer or not for (final Feature f : features) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (!getMappingModel().getRasterServices().containsValue(rs)) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureAwareRasterServiceAdded"); // NOI18N } } rs.setFeatureCollection(getFeatureCollection()); getMappingModel().addLayer(rs); } } } showHandles(false); } /** * DOCUMENT ME! * * @param cf DOCUMENT ME! */ private void fireFeaturesAddedToMap(final Collection<Feature> cf) { for (final MapListener curMapListener : mapListeners) { curMapListener.featuresAddedToMap(cf); } } /** * Creates an envelope around all features from the given array. * * @param features features to create the envelope around * * @return Envelope com.vividsolutions.jts.geom.Envelope */ private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) { final PNode root = new PNode(); for (int i = 0; i < features.length; ++i) { final PNode p = PNodeFactory.createPFeature(features[i], this); if (p != null) { root.addChild(p); } } final PBounds ext = root.getFullBounds(); final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope( ext.x, ext.x + ext.width, ext.y, ext.y + ext.height); return env; } /** * Zooms in / out to match the bounds of the featurecollection. */ public void zoomToFullFeatureCollectionBounds() { zoomToFeatureCollection(); } /** * Adds a new cursor to the cursor-hashmap. * * @param mode interactionmode as string * @param cursor cursor-object */ public void putCursor(final String mode, final Cursor cursor) { cursors.put(mode, cursor); } /** * Returns the cursor assigned to the given mode. * * @param mode mode as String * * @return Cursor-object or null */ public Cursor getCursor(final String mode) { return cursors.get(mode); } /** * Adds a new PBasicInputEventHandler for a specific interactionmode. * * @param mode interactionmode as string * @param listener new PBasicInputEventHandler */ public void addInputListener(final String mode, final PBasicInputEventHandler listener) { inputEventListener.put(mode, listener); } /** * Returns the PBasicInputEventHandler assigned to the committed interactionmode. * * @param mode interactionmode as string * * @return PBasicInputEventHandler-object or null */ public PInputEventListener getInputListener(final String mode) { final Object o = inputEventListener.get(mode); if (o instanceof PInputEventListener) { return (PInputEventListener)o; } else { return null; } } /** * Returns whether the features are editable or not. * * @return DOCUMENT ME! */ public boolean isReadOnly() { return readOnly; } /** * Sets all Features ReadOnly use Feature.setEditable(boolean) instead. * * @param readOnly DOCUMENT ME! */ public void setReadOnly(final boolean readOnly) { for (final Object f : featureCollection.getAllFeatures()) { ((Feature)f).setEditable(!readOnly); } this.readOnly = readOnly; handleLayer.repaint(); try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } snapHandleLayer.removeAllChildren(); } /** * Returns the current HandleInteractionMode. * * @return DOCUMENT ME! */ public String getHandleInteractionMode() { return handleInteractionMode; } /** * Changes the HandleInteractionMode. Repaints handles. * * @param handleInteractionMode the new HandleInteractionMode */ public void setHandleInteractionMode(final String handleInteractionMode) { this.handleInteractionMode = handleInteractionMode; showHandles(false); } /** * Returns whether the background is enabled or not. * * @return DOCUMENT ME! */ public boolean isBackgroundEnabled() { return backgroundEnabled; } /** * TODO. * * @param backgroundEnabled DOCUMENT ME! */ public void setBackgroundEnabled(final boolean backgroundEnabled) { if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) { featureServiceLayerVisible = featureServiceLayer.getVisible(); } this.mapServicelayer.setVisible(backgroundEnabled); this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible); for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) { featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible); } if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) { this.queryServices(); } this.backgroundEnabled = backgroundEnabled; } /** * Returns the featurelayer. * * @return DOCUMENT ME! */ public PLayer getFeatureLayer() { return featureLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Map<String, PLayer> getFeatureGroupLayers() { return this.featureGrpLayerMap; } /** * Adds a PFeature to the PFeatureHashmap. * * @param p PFeature to add */ public void refreshHM(final PFeature p) { pFeatureHM.put(p.getFeature(), p); } /** * Returns the selectedObjectPresenter (PCanvas). * * @return DOCUMENT ME! */ public PCanvas getSelectedObjectPresenter() { return selectedObjectPresenter; } /** * If f != null it calls the reconsiderFeature()-method of the featurecollection. * * @param f feature to reconcile */ public void reconsiderFeature(final Feature f) { if (f != null) { featureCollection.reconsiderFeature(f); } } /** * Removes all features of the collection from the hashmap. * * @param fc collection of features to remove */ public void removeFeatures(final Collection<Feature> fc) { featureLayer.setVisible(false); for (final Feature elem : fc) { removeFromHM(elem); } featureLayer.setVisible(true); } /** * Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key. * * @param f feature of the Pfeature that should be deleted */ public void removeFromHM(final Feature f) { final PFeature pf = pFeatureHM.get(f); if (pf != null) { pf.cleanup(); pFeatureHM.remove(f); stickyPNodes.remove(pf); try { LOG.info("Entferne Feature " + f); // NOI18N featureLayer.removeChild(pf); for (final PLayer grpLayer : this.featureGrpLayerMap.values()) { if (grpLayer.removeChild(pf) != null) { break; } } } catch (Exception ex) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N } } } } else { LOG.warn("Feature war nicht in pFeatureHM"); // NOI18N } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("pFeatureHM" + pFeatureHM); // NOI18N } } } /** * Zooms to the current selected node. * * @deprecated DOCUMENT ME! */ public void zoomToSelectedNode() { zoomToSelection(); } /** * Zooms to the current selected features. */ public void zoomToSelection() { final Collection<Feature> selection = featureCollection.getSelectedFeatures(); zoomToAFeatureCollection(selection, true, false); } /** * Zooms to a specific featurecollection. * * @param collection the featurecolltion * @param withHistory should the zoomaction be undoable * @param fixedScale fixedScale */ public void zoomToAFeatureCollection(final Collection<Feature> collection, final boolean withHistory, final boolean fixedScale) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("zoomToAFeatureCollection"); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } boolean first = true; Geometry g = null; for (final Feature f : collection) { if (first) { if (f.getGeometry() != null) { g = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode()) .getEnvelope(); if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) { g = g.buffer(((Bufferable)f).getBuffer() + 0.001); } first = false; } } else { if (f.getGeometry() != null) { Geometry geometry = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode()) .getEnvelope(); if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) { geometry = geometry.buffer(((Bufferable)f).getBuffer() + 0.001); } g = g.getEnvelope().union(geometry); } } } if (g != null) { // FIXME: we shouldn't only complain but do sth if ((getHeight() == 0) || (getWidth() == 0)) { LOG.warn("DIVISION BY ZERO"); // NOI18N } // dreisatz.de final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10; final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10; double buff = 0; if (hBuff > vBuff) { buff = hBuff; } else { buff = vBuff; } if (buff == 0.0) { if (mappingModel.getSrs().isMetric()) { buff = 1.0; } else { buff = 0.01; } } g = g.buffer(buff); final BoundingBox bb = new BoundingBox(g); final boolean onlyOnePoint = (collection.size() == 1) && (((Feature)(collection.toArray()[0])).getGeometry() instanceof com.vividsolutions.jts.geom.Point); gotoBoundingBox(bb, withHistory, !(fixedScale || (onlyOnePoint && (g.getArea() < 10))), animationDuration); } } /** * Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create * their handles and to add them to the handlelayer. * * @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles */ public void showHandles(final boolean waitTillAllAnimationsAreComplete) { // are there features selected? if (featureCollection.getSelectedFeatures().size() > 0) { // DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf final Runnable handle = new Runnable() { @Override public void run() { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); while (getAnimating() && waitTillAllAnimationsAreComplete) { try { Thread.currentThread().sleep(10); } catch (final Exception e) { LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (featureCollection.areFeaturesEditable() && (getInteractionMode().equals(SELECT) || getInteractionMode().equals(LINEAR_REFERENCING) || getInteractionMode().equals(PAN) || getInteractionMode().equals(ZOOM) || getInteractionMode().equals(ALKIS_PRINT) || getInteractionMode().equals(SPLIT_POLYGON))) { // Handles für alle selektierten Features der Collection hinzufügen if (getHandleInteractionMode().equals(ROTATE_POLYGON)) { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature instanceof Feature) && selectedFeature.isEditable()) { if (pFeatureHM.get(selectedFeature) != null) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { pFeatureHM.get(selectedFeature).addRotationHandles(handleLayer); } }); } else { LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } } } } else { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature != null) && selectedFeature.isEditable()) { if (pFeatureHM.get(selectedFeature) != null) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { try { pFeatureHM.get(selectedFeature).addHandles(handleLayer); } catch (final Exception e) { LOG.error("Error bei addHandles: ", e); // NOI18N } } }); } else { LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } // DANGER mit break werden nur die Handles EINES slektierten Features angezeigt // wird break auskommentiert werden jedoch zu viele Handles angezeigt break; } } } } } }; if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("showHandles", new CurrentStackTrace()); // NOI18N } } CismetThreadPool.execute(handle); } else { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); } } /** * Will return a PureNewFeature if there is only one in the featurecollection else null. * * @return DOCUMENT ME! */ public PFeature getSolePureNewFeature() { int counter = 0; PFeature sole = null; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object o = it.next(); if (o instanceof PFeature) { if (((PFeature)o).getFeature() instanceof PureNewFeature) { ++counter; sole = ((PFeature)o); } } } if (counter == 1) { return sole; } else { return null; } } /** * Returns the temporary featurelayer. * * @return DOCUMENT ME! */ public PLayer getTmpFeatureLayer() { return tmpFeatureLayer; } /** * Assigns a new temporary featurelayer. * * @param tmpFeatureLayer PLayer */ public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) { this.tmpFeatureLayer = tmpFeatureLayer; } /** * Returns whether the grid is enabled or not. * * @return DOCUMENT ME! */ public boolean isGridEnabled() { return gridEnabled; } /** * Enables or disables the grid. * * @param gridEnabled true, to enable the grid */ public void setGridEnabled(final boolean gridEnabled) { this.gridEnabled = gridEnabled; } /** * Returns a String from two double-values. Serves the visualization. * * @param x X-coordinate * @param y Y-coordinate * * @return a String-object like "(X,Y)" */ public static String getCoordinateString(final double x, final double y) { final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N final DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); df.setDecimalFormatSymbols(dfs); return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N } /** * DOCUMENT ME! * * @param event DOCUMENT ME! * * @return DOCUMENT ME! */ public com.vividsolutions.jts.geom.Point getPointGeometryFromPInputEvent(final PInputEvent event) { final double xCoord = getWtst().getSourceX(event.getPosition().getX() - getClip_offset_x()); final double yCoord = getWtst().getSourceY(event.getPosition().getY() - getClip_offset_y()); final GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), CrsTransformer.extractSridFromCrs(getMappingModel().getSrs().getCode())); return gf.createPoint(new Coordinate(xCoord, yCoord)); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHandleLayer() { return handleLayer; } /** * DOCUMENT ME! * * @param handleLayer DOCUMENT ME! */ public void setHandleLayer(final PLayer handleLayer) { this.handleLayer = handleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingEnabled() { return visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingEnabled DOCUMENT ME! */ public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) { this.visualizeSnappingEnabled = visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingRectEnabled() { return visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingRectEnabled DOCUMENT ME! */ public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) { this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getSnappingRectSize() { return snappingRectSize; } /** * DOCUMENT ME! * * @param snappingRectSize DOCUMENT ME! */ public void setSnappingRectSize(final int snappingRectSize) { this.snappingRectSize = snappingRectSize; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getSnapHandleLayer() { return snapHandleLayer; } /** * DOCUMENT ME! * * @param snapHandleLayer DOCUMENT ME! */ public void setSnapHandleLayer(final PLayer snapHandleLayer) { this.snapHandleLayer = snapHandleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isSnappingEnabled() { return snappingEnabled; } /** * DOCUMENT ME! * * @param snappingEnabled DOCUMENT ME! */ public void setSnappingEnabled(final boolean snappingEnabled) { this.snappingEnabled = snappingEnabled; setVisualizeSnappingEnabled(snappingEnabled); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getFeatureServiceLayer() { return featureServiceLayer; } /** * DOCUMENT ME! * * @param featureServiceLayer DOCUMENT ME! */ public void setFeatureServiceLayer(final PLayer featureServiceLayer) { this.featureServiceLayer = featureServiceLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getAnimationDuration() { return animationDuration; } /** * DOCUMENT ME! * * @param animationDuration DOCUMENT ME! */ public void setAnimationDuration(final int animationDuration) { this.animationDuration = animationDuration; } /** * DOCUMENT ME! * * @param prefs DOCUMENT ME! */ @Deprecated public void setPreferences(final CismapPreferences prefs) { LOG.warn("involing deprecated operation setPreferences()"); // NOI18N cismapPrefs = prefs; final ActiveLayerModel mm = new ActiveLayerModel(); final LayersPreferences layersPrefs = prefs.getLayersPrefs(); final GlobalPreferences globalPrefs = prefs.getGlobalPrefs(); setSnappingRectSize(globalPrefs.getSnappingRectSize()); setSnappingEnabled(globalPrefs.isSnappingEnabled()); setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled()); setAnimationDuration(globalPrefs.getAnimationDuration()); setInteractionMode(globalPrefs.getStartMode()); mm.addHome(globalPrefs.getInitialBoundingBox()); final Crs crs = new Crs(); crs.setCode(globalPrefs.getInitialBoundingBox().getSrs()); crs.setName(globalPrefs.getInitialBoundingBox().getSrs()); crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs()); mm.setSrs(crs); final TreeMap raster = layersPrefs.getRasterServices(); if (raster != null) { final Iterator it = raster.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = raster.get(key); if (o instanceof MapService) { mm.addLayer((RetrievalServiceLayer)o); } } } final TreeMap features = layersPrefs.getFeatureServices(); if (features != null) { final Iterator it = features.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = features.get(key); if (o instanceof MapService) { // TODO mm.addLayer((RetrievalServiceLayer)o); } } } setMappingModel(mm); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public CismapPreferences getCismapPrefs() { return cismapPrefs; } /** * DOCUMENT ME! * * @param duration DOCUMENT ME! * @param animationDuration DOCUMENT ME! * @param what DOCUMENT ME! * @param number DOCUMENT ME! */ public void flash(final int duration, final int animationDuration, final int what, final int number) { } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getDragPerformanceImproverLayer() { return dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @param dragPerformanceImproverLayer DOCUMENT ME! */ public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) { this.dragPerformanceImproverLayer = dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public PLayer getRasterServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getMapServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @param rasterServiceLayer DOCUMENT ME! */ public void setRasterServiceLayer(final PLayer rasterServiceLayer) { this.mapServicelayer = rasterServiceLayer; } /** * DOCUMENT ME! * * @param f DOCUMENT ME! */ public void showGeometryInfoPanel(final Feature f) { } /** * Adds a PropertyChangeListener to the listener list. * * @param l The listener to add. */ @Override public void addPropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.addPropertyChangeListener(l); } /** * Removes a PropertyChangeListener from the listener list. * * @param l The listener to remove. */ @Override public void removePropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.removePropertyChangeListener(l); } /** * Setter for property taskCounter. former synchronized method */ public void fireActivityChanged() { propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N } /** * Returns true, if there's still one layercontrol running. Else false; former synchronized method * * @return DOCUMENT ME! */ public boolean isRunning() { for (final LayerControl lc : layerControls) { if (lc.isRunning()) { return true; } } return false; } /** * Sets the visibility of all infonodes. * * @param visible true, if infonodes should be visible */ public void setInfoNodesVisible(final boolean visible) { infoNodesVisible = visible; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object elem = it.next(); if (elem instanceof PFeature) { ((PFeature)elem).setInfoNodeVisible(visible); } } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("setInfoNodesVisible()"); // NOI18N } } rescaleStickyNodes(); } /** * Adds an object to the historymodel. * * @param o Object to add */ @Override public void addToHistory(final Object o) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("addToHistory:" + o.toString()); // NOI18N } } historyModel.addToHistory(o); } /** * Removes a specific HistoryModelListener from the historymodel. * * @param hml HistoryModelListener */ @Override public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.removeHistoryModelListener(hml); } /** * Adds aHistoryModelListener to the historymodel. * * @param hml HistoryModelListener */ @Override public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.addHistoryModelListener(hml); } /** * Sets the maximum value of saved historyactions. * * @param max new integer value */ @Override public void setMaximumPossibilities(final int max) { historyModel.setMaximumPossibilities(max); } /** * Redos the last undone historyaction. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the forward-action */ @Override public Object forward(final boolean external) { final PBounds fwd = (PBounds)historyModel.forward(external); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("HistoryModel.forward():" + fwd); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(fwd); } return fwd; } /** * Undos the last action. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the back-action */ @Override public Object back(final boolean external) { final PBounds back = (PBounds)historyModel.back(external); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("HistoryModel.back():" + back); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(back); } return back; } /** * Returns true, if it's possible to redo an action. * * @return DOCUMENT ME! */ @Override public boolean isForwardPossible() { return historyModel.isForwardPossible(); } /** * Returns true, if it's possible to undo an action. * * @return DOCUMENT ME! */ @Override public boolean isBackPossible() { return historyModel.isBackPossible(); } /** * Returns a vector with all redo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getForwardPossibilities() { return historyModel.getForwardPossibilities(); } /** * Returns the current element of the historymodel. * * @return DOCUMENT ME! */ @Override public Object getCurrentElement() { return historyModel.getCurrentElement(); } /** * Returns a vector with all undo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getBackPossibilities() { return historyModel.getBackPossibilities(); } /** * Returns whether an internallayerwidget is available. * * @return DOCUMENT ME! */ @Deprecated public boolean isInternalLayerWidgetAvailable() { return this.getInternalWidget(LAYERWIDGET) != null; } /** * Sets the variable, if an internallayerwidget is available or not. * * @param internalLayerWidgetAvailable true, if available */ @Deprecated public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) { if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) { this.removeInternalWidget(LAYERWIDGET); } else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) { final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); } } /** * DOCUMENT ME! * * @param mme DOCUMENT ME! */ @Override public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) { } /** * Removes the mapservice from the rasterservicelayer. * * @param rasterService the removing mapservice */ @Override public void mapServiceRemoved(final MapService rasterService) { try { mapServicelayer.removeChild(rasterService.getPNode()); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_REMOVED, rasterService)); } System.gc(); } catch (final Exception e) { LOG.warn("Fehler bei mapServiceRemoved", e); // NOI18N } } /** * Adds the commited mapservice on the last position to the rasterservicelayer. * * @param mapService the new mapservice */ @Override public void mapServiceAdded(final MapService mapService) { addMapService(mapService, mapServicelayer.getChildrenCount()); if (mapService instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection()); } if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) { handleMapService(0, mapService, false); } } /** * Returns the current OGC scale. * * @return DOCUMENT ME! */ public double getCurrentOGCScale() { // funktioniert nur bei metrischen SRS's final double h = getCamera().getViewBounds().getHeight() / getHeight(); final double w = getCamera().getViewBounds().getWidth() / getWidth(); return Math.sqrt((h * h) + (w * w)); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public BoundingBox getCurrentBoundingBox() { return getCurrentBoundingBoxFromCamera(); } /** * <p>Returns the current BoundingBox.</p> * * @return DOCUMENT ME! */ public BoundingBox getCurrentBoundingBoxFromCamera() { if (fixedBoundingBox != null) { return fixedBoundingBox; } else { try { final PBounds bounds = getCamera().getViewBounds(); final double x1 = wtst.getWorldX(bounds.getX()); final double y1 = wtst.getWorldY(bounds.getY()); final double x2 = x1 + bounds.width; final double y2 = y1 - bounds.height; final Crs currentCrs = CismapBroker.getInstance().getSrs(); final boolean metric; // FIXME: this is a hack to overcome the "metric" issue for 4326 default srs if (CrsTransformer.getCurrentSrid() == 4326) { metric = false; } else { metric = currentCrs.isMetric(); } return new XBoundingBox(x1, y1, x2, y2, currentCrs.getCode(), metric); } catch (final Exception e) { LOG.error("cannot create bounding box from current view, return null", e); // NOI18N return null; } } } /** * Returns a BoundingBox with a fixed size. * * @return DOCUMENT ME! */ public BoundingBox getFixedBoundingBox() { return fixedBoundingBox; } /** * Assigns fixedBoundingBox a new value. * * @param fixedBoundingBox new boundingbox */ public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) { this.fixedBoundingBox = fixedBoundingBox; } /** * Paints the outline of the forwarded BoundingBox. * * @param bb BoundingBox */ public void outlineArea(final BoundingBox bb) { outlineArea(bb, null); } /** * Paints the outline of the forwarded PBounds. * * @param b PBounds */ public void outlineArea(final PBounds b) { outlineArea(b, null); } /** * Paints a filled rectangle of the area of the forwarded BoundingBox. * * @param bb BoundingBox * @param fillingPaint Color to fill the rectangle */ public void outlineArea(final BoundingBox bb, final Paint fillingPaint) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } outlineArea(pb, fillingPaint); } /** * Paints a filled rectangle of the area of the forwarded PBounds. * * @param b PBounds to paint * @param fillingColor Color to fill the rectangle */ public void outlineArea(final PBounds b, final Paint fillingColor) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { highlightingLayer.removeAllChildren(); } } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(fillingColor); rectangle.setStroke(new FixedWidthStroke()); rectangle.setStrokePaint(new Color(100, 100, 100, 255)); rectangle.setPathTo(b); highlightingLayer.addChild(rectangle); } } /** * Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally. * * @param bb BoundingBox to highlight */ public void highlightArea(final BoundingBox bb) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } highlightArea(pb); } /** * Highlights the delivered PBounds by painting over with a transparent white. * * @param b PBounds to hightlight */ private void highlightArea(final PBounds b) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { } highlightingLayer.animateToTransparency(0, animationDuration); highlightingLayer.removeAllChildren(); } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(new Color(255, 255, 255, 100)); rectangle.setStroke(null); rectangle.setPathTo(this.getCamera().getViewBounds()); highlightingLayer.addChild(rectangle); rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration); } } /** * Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls * crossHairPoint(Point p) internally. * * @param c coordinate of the crosshair's venue */ public void crossHairPoint(final Coordinate c) { Point p = null; if (c != null) { p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y)); } crossHairPoint(p); } /** * Paints a crosshair at the delivered point. * * @param p point of the crosshair's venue */ public void crossHairPoint(final Point p) { if (p == null) { if (crosshairLayer.getChildrenCount() > 0) { crosshairLayer.removeAllChildren(); } } else { crosshairLayer.removeAllChildren(); crosshairLayer.setTransparency(1); final PPath lineX = new PPath(); final PPath lineY = new PPath(); lineX.setStroke(new FixedWidthStroke()); lineX.setStrokePaint(new Color(100, 100, 100, 255)); lineY.setStroke(new FixedWidthStroke()); lineY.setStrokePaint(new Color(100, 100, 100, 255)); final PBounds current = getCamera().getViewBounds(); final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1); final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2); lineX.setPathTo(x); crosshairLayer.addChild(lineX); lineY.setPathTo(y); crosshairLayer.addChild(lineY); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public Element getConfiguration() { if (LOG.isDebugEnabled()) { LOG.debug("writing configuration <cismapMappingPreferences>"); // NOI18N } final Element ret = new Element("cismapMappingPreferences"); // NOI18N ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N ret.setAttribute( "creationMode", ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON); if (inputListener instanceof CreateSearchGeometryListener) { final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener; ret.setAttribute("createSearchMode", listener.getMode()); } // Position final Element currentPosition = new Element("Position"); // NOI18N currentPosition.addContent(getCurrentBoundingBoxFromCamera().getJDOMElement()); currentPosition.setAttribute("CRS", mappingModel.getSrs().getCode()); ret.addContent(currentPosition); // Crs final Element crsListElement = new Element("crsList"); for (final Crs tmp : crsList) { crsListElement.addContent(tmp.getJDOMElement()); } ret.addContent(crsListElement); if (printingSettingsDialog != null) { ret.addContent(printingSettingsDialog.getConfiguration()); } // save internal widgets status final Element widgets = new Element("InternalWidgets"); // NOI18N for (final String name : this.internalWidgets.keySet()) { final Element widget = new Element("Widget"); // NOI18N widget.setAttribute("name", name); // NOI18N widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N widgets.addContent(widget); } ret.addContent(widgets); return ret; } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void masterConfigure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N // CRS List try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N boolean defaultCrsFound = false; crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); crsList.add(s); if (s.isSelected() && s.isMetric()) { try { if (defaultCrsFound) { LOG.warn("More than one default CRS is set. " + "Please check your master configuration file."); // NOI18N } CismapBroker.getInstance().setDefaultCrs(s.getCode()); defaultCrsFound = true; transformer = new CrsTransformer(s.getCode()); } catch (final Exception ex) { LOG.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (final Exception skip) { LOG.error("Error while reading the crs list", skip); // NOI18N } if (CismapBroker.getInstance().getDefaultCrs() == null) { LOG.fatal("The default CRS is not set. This can lead to almost irreparable data errors. " + "Keep in mind: The default CRS must be metric"); // NOI18N } if (transformer == null) { LOG.error("No metric default crs found. Use EPSG:31466 as default crs"); // NOI18N try { transformer = new CrsTransformer("EPSG:31466"); // NOI18N CismapBroker.getInstance().setDefaultCrs("EPSG:31466"); // NOI18N } catch (final Exception ex) { LOG.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); // NOI18N } } // HOME try { if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N } } while (it.hasNext()) { final Element elem = it.next(); final String srs = elem.getAttribute("srs").getValue(); // NOI18N boolean metric = false; try { metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { LOG.warn("Metric hat falschen Syntax", dce); // NOI18N } boolean defaultVal = false; try { defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { LOG.warn("default hat falschen Syntax", dce); // NOI18N } final XBoundingBox xbox = new XBoundingBox(elem, srs, metric); alm.addHome(xbox); if (defaultVal) { Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(srs)) { crsObject = tmp; break; } } if (crsObject == null) { LOG.error("CRS " + srs + " from the default home is not found in the crs list"); crsObject = new Crs(srs, srs, srs, true, false); crsList.add(crsObject); } alm.setSrs(crsObject); alm.setDefaultHomeSrs(crsObject); CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } } } } catch (final Exception ex) { LOG.error("Fehler beim MasterConfigure der MappingComponent", ex); // NOI18N } try { final Element defaultCrs = prefs.getChild("defaultCrs"); final int defaultCrsInt = Integer.parseInt(defaultCrs.getAttributeValue("geometrySridAlias")); CismapBroker.getInstance().setDefaultCrsAlias(defaultCrsInt); } catch (final Exception ex) { LOG.error("Error while reading the default crs alias from the master configuration file.", ex); } try { final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N scales.clear(); for (final Object elem : scalesList) { if (elem instanceof Element) { final Scale s = new Scale((Element)elem); scales.add(s); } } } catch (final Exception skip) { LOG.error("Fehler beim Lesen von Scale", skip); // NOI18N } // Und jetzt noch die PriningEinstellungen initPrintingDialogs(); printingSettingsDialog.masterConfigure(prefs); } /** * Configurates this MappingComponent. * * @param e JDOM-Element with configuration */ @Override public void configure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); // the crs is equals to an other crs, if the code is equal. If a crs has in the // local configuration file an other name than in the master configuration file, // the old crs will be removed and the local one should be added to use the // local name and short name of the crs. if (crsList.contains(s)) { crsList.remove(s); } crsList.add(s); } } } catch (final Exception skip) { LOG.warn("Error while reading the crs list", skip); // NOI18N } // InteractionMode try { final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N setInteractionMode(interactMode); if (interactMode.equals(MappingComponent.NEW_POLYGON)) { try { final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode); } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des CreationInteractionMode", ex); // NOI18N } } } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des InteractionMode", ex); // NOI18N } try { final String createSearchMode = prefs.getAttribute("createSearchMode").getValue(); final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON); if ((inputListener instanceof CreateSearchGeometryListener) && (createSearchMode != null)) { final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener; listener.setMode(createSearchMode); } } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des CreateSearchMode", ex); // NOI18N } try { final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N setHandleInteractionMode(handleInterMode); } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des HandleInteractionMode", ex); // NOI18N } try { final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N LOG.info("snapping=" + snapping); // NOI18N setSnappingEnabled(snapping); setVisualizeSnappingEnabled(snapping); setInGlueIdenticalPointsMode(snapping); } catch (final Exception ex) { LOG.warn("Fehler beim setzen von snapping und Konsorten", ex); // NOI18N } // aktuelle Position try { final Element pos = prefs.getChild("Position"); // NOI18N final BoundingBox b = new BoundingBox(pos); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Position:" + b); // NOI18N } } final PBounds pb = b.getPBounds(getWtst()); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("PositionPb:" + pb); // NOI18N } } if (Double.isNaN(b.getX1()) || Double.isNaN(b.getX2()) || Double.isNaN(b.getY1()) || Double.isNaN(b.getY2())) { LOG.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); addToHistory(new PBoundsWithCleverToString( new PBounds(getMappingModel().getInitialBoundingBox().getPBounds(wtst)), wtst, crsCode)); } else { // set the current crs final Attribute crsAtt = pos.getAttribute("CRS"); if (crsAtt != null) { final String currentCrs = crsAtt.getValue(); Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(currentCrs)) { crsObject = tmp; break; } } if (crsObject == null) { LOG.error("CRS " + currentCrs + " from the position element is not found in the crs list"); } final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); if (alm instanceof ActiveLayerModel) { alm.setSrs(crsObject); } CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } this.initialBoundingBox = b; this.gotoBoundingBox(b, true, true, 0, false); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.fatal("added to History" + b); // NOI18N } } } } catch (final Exception ex) { LOG.warn("Fehler beim lesen der aktuellen Position", ex); // NOI18N this.gotoBoundingBox(getMappingModel().getInitialBoundingBox(), true, true, 0, false); } if (printingSettingsDialog != null) { printingSettingsDialog.configure(prefs); } try { final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N if (widgets != null) { for (final Object widget : widgets.getChildren()) { final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N this.showInternalWidget(name, visible, 0); } } } catch (final Exception ex) { LOG.warn("could not enable internal widgets: " + ex, ex); // NOI18N } } /** * Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent * will only pan to the featurecollection and not zoom. * * @param fixedScale true, if zoom is not allowed */ public void zoomToFeatureCollection(final boolean fixedScale) { zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale); } /** * Zooms to all features of the mappingcomponents featurecollection. */ public void zoomToFeatureCollection() { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("zoomToFeatureCollection"); // NOI18N } } zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration) { gotoBoundingBox(bb, history, scaleToFit, animationDuration, true); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation * @param queryServices true, if the services should be refreshed after animation */ public void gotoBoundingBox(BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration, final boolean queryServices) { if (bb != null) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } if (bb instanceof XBoundingBox) { if (!((XBoundingBox)bb).getSrs().equals(mappingModel.getSrs().getCode())) { try { final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode()); bb = trans.transformBoundingBox((XBoundingBox)bb); } catch (final Exception e) { LOG.warn("Cannot transform the bounding box", e); } } } final double x1 = getWtst().getScreenX(bb.getX1()); final double y1 = getWtst().getScreenY(bb.getY1()); final double x2 = getWtst().getScreenX(bb.getX2()); final double y2 = getWtst().getScreenY(bb.getY2()); final double w; final double h; final Rectangle2D pos = new Rectangle2D.Double(); pos.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { LOG.warn("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } showHandles(true); final Runnable handle = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(10); } catch (final Exception e) { LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (history) { if ((x1 == x2) || (y1 == y2) || !scaleToFit) { setNewViewBounds(getCamera().getViewBounds()); } else { setNewViewBounds(pos); } if (queryServices) { queryServices(); } } else { if (queryServices) { queryServicesWithoutHistory(); } } } }; CismetThreadPool.execute(handle); } else { LOG.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N } } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) { gotoBoundingBoxWithoutHistory(bb, animationDuration); } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox * @param animationDuration the animation duration */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb, final int animationDuration) { gotoBoundingBox(bb, false, true, animationDuration); } /** * Moves the view to the target Boundingbox and saves the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithHistory(final BoundingBox bb) { gotoBoundingBox(bb, true, true, animationDuration); } /** * Returns a BoundingBox of the current view in another scale. * * @param scaleDenominator specific target scale * * @return DOCUMENT ME! */ public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) { return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBoxFromCamera()); } /** * Returns the BoundingBox of the delivered BoundingBox in another scale. * * @param scaleDenominator specific target scale * @param bb source BoundingBox * * @return DOCUMENT ME! */ public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) { final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator; final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator; if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { // transform the given bounding box to a metric coordinate system bb = transformer.transformBoundingBox(bb, mappingModel.getSrs().getCode()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2); final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2); BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2), midY - (realWorldHeightInMeter / 2), midX + (realWorldWidthInMeter / 2), midY + (realWorldHeightInMeter / 2)); if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { // transform the scaled bounding box to the current coordinate system final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode()); scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } return scaledBox; } /** * Calculate the current scaledenominator. * * @return DOCUMENT ME! */ public double getScaleDenominator() { BoundingBox boundingBox = getCurrentBoundingBoxFromCamera(); final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { boundingBox = transformer.transformBoundingBox( boundingBox, mappingModel.getSrs().getCode()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } final double realWorldWidthInMeter = boundingBox.getWidth(); return realWorldWidthInMeter / screenWidthInMeter; } /** * Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code> * DropTarget</code> registered with this listener. * * <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code> * DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data * object(s) to be transfered.</p> * * <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int * dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P> * * <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be * invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData() * method.</P> * * <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the * drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method.</P> * * <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code> * Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only * if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code> * true</code>. Otherwise, the behavior of the call is implementation-dependent.</P> * * @param dtde the <code>DropTargetDropEvent</code> */ @Override public void drop(final DropTargetDropEvent dtde) { if (isDropEnabled(dtde)) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDropOnMap(mde); } catch (final Exception ex) { LOG.error("Error in drop", ex); // NOI18N } } } /** * DOCUMENT ME! * * @param dtde DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean isDropEnabled(final DropTargetDropEvent dtde) { if (ALKIS_PRINT.equals(getInteractionMode())) { for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) { // necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) { return false; } } } return true; } /** * Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site * for the <code>DropTarget</code> registered with this listener. * * @param dte the <code>DropTargetEvent</code> */ @Override public void dragExit(final DropTargetEvent dte) { } /** * Called if the user has modified the current drop gesture. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dropActionChanged(final DropTargetDragEvent dtde) { } /** * Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p * site for the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragOver(final DropTargetDragEvent dtde) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); // TODO: this seems to be buggy! final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDragOverMap(mde); } catch (final Exception ex) { LOG.error("Error in dragOver", ex); // NOI18N } } /** * Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for * the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragEnter(final DropTargetDragEvent dtde) { } /** * Returns the PfeatureHashmap which assigns a Feature to a PFeature. * * @return DOCUMENT ME! */ public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() { return pFeatureHM; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapExtent() { return fixedMapExtent; } /** * DOCUMENT ME! * * @param fixedMapExtent DOCUMENT ME! */ public void setFixedMapExtent(final boolean fixedMapExtent) { this.fixedMapExtent = fixedMapExtent; if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent( StatusEvent.MAP_EXTEND_FIXED, this.fixedMapExtent)); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapScale() { return fixedMapScale; } /** * DOCUMENT ME! * * @param fixedMapScale DOCUMENT ME! */ public void setFixedMapScale(final boolean fixedMapScale) { this.fixedMapScale = fixedMapScale; if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent( StatusEvent.MAP_SCALE_FIXED, this.fixedMapScale)); } } /** * DOCUMENT ME! * * @param one DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public void selectPFeatureManually(final PFeature one) { if (one != null) { featureCollection.select(one.getFeature()); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public PFeature getSelectedNode() { // gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist // deshalb gebe ich mal nur das erste zur�ck if (featureCollection.getSelectedFeatures().size() > 0) { final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0]; if (selF == null) { return null; } return pFeatureHM.get(selF); } else { return null; } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInfoNodesVisible() { return infoNodesVisible; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getPrintingFrameLayer() { return printingFrameLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PrintingSettingsWidget getPrintingSettingsDialog() { return printingSettingsDialog; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInGlueIdenticalPointsMode() { return inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @param inGlueIdenticalPointsMode DOCUMENT ME! */ public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) { this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHighlightingLayer() { return highlightingLayer; } /** * DOCUMENT ME! * * @param anno DOCUMENT ME! */ public void setPointerAnnotation(final PNode anno) { ((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno); } /** * DOCUMENT ME! * * @param visib DOCUMENT ME! */ public void setPointerAnnotationVisibility(final boolean visib) { if (getInputListener(MOTION) != null) { ((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib); } } /** * Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't * equal MOTION. * * @return DOCUMENT ME! */ public boolean isPointerAnnotationVisible() { if (getInputListener(MOTION) != null) { return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible(); } else { return false; } } /** * Returns a vector with different scales. * * @return DOCUMENT ME! */ public List<Scale> getScales() { return scales; } /** * Returns a list with different crs. * * @return DOCUMENT ME! */ public List<Crs> getCrsList() { return crsList; } /** * DOCUMENT ME! * * @return a transformer with the default crs as destination crs. The default crs is the first crs in the * configuration file that has set the selected attribut on true). This crs must be metric. */ public CrsTransformer getMetricTransformer() { return transformer; } /** * Locks the MappingComponent. */ public void lock() { locked = true; } /** * Unlocks the MappingComponent. */ public void unlock() { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("unlock"); // NOI18N } } locked = false; // if (DEBUG) { // if (LOG.isDebugEnabled()) { // LOG.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N // } // } gotoBoundingBoxWithHistory(getInitialBoundingBox()); } /** * Returns whether the MappingComponent is locked or not. * * @return DOCUMENT ME! */ public boolean isLocked() { return locked; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isMainMappingComponent() { return mainMappingComponent; } /** * Returns the MementoInterface for redo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemRedo() { return memRedo; } /** * Returns the MementoInterface for undo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemUndo() { return memUndo; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Map<String, PBasicInputEventHandler> getInputEventListener() { return inputEventListener; } /** * DOCUMENT ME! * * @param inputEventListener DOCUMENT ME! */ public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) { this.inputEventListener.clear(); this.inputEventListener.putAll(inputEventListener); } /** * DOCUMENT ME! * * @param event DOCUMENT ME! */ @Override public synchronized void crsChanged(final CrsChangedEvent event) { if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) { if (locked) { return; } final WaitDialog dialog = new WaitDialog(StaticSwingTools.getParentFrame(MappingComponent.this), false, NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).wait"), null); EventQueue.invokeLater(new Runnable() { @Override public void run() { try { StaticSwingTools.showDialog(dialog); // the wtst object should not be null, so the getWtst method will be invoked final WorldToScreenTransform oldWtst = getWtst(); final BoundingBox bbox = getCurrentBoundingBoxFromCamera(); // getCurrentBoundingBox(); final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode()); final BoundingBox newBbox = crsTransformer.transformBoundingBox( bbox, event.getFormerCrs().getCode()); if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); } wtst = null; getWtst(); gotoBoundingBoxWithoutHistory(newBbox, 0); final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures()); featureCollection.removeAllFeatures(); featureCollection.addFeatures(list); if (LOG.isDebugEnabled()) { LOG.debug("debug features added: " + list.size()); } // refresh all wfs layer if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.refreshWebFeatureServices(); alm.refreshShapeFileLayer(); } // transform the highlighting layer for (int i = 0; i < highlightingLayer.getChildrenCount(); ++i) { final PNode node = highlightingLayer.getChild(i); CrsTransformer.transformPNodeToGivenCrs( node, event.getFormerCrs().getCode(), event.getCurrentCrs().getCode(), oldWtst, getWtst()); rescaleStickyNode(node); } } catch (final Exception e) { JOptionPane.showMessageDialog( StaticSwingTools.getParentFrame(MappingComponent.this), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"), JOptionPane.ERROR_MESSAGE); LOG.error( "Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e); resetCrs = true; final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); CismapBroker.getInstance().setSrs(event.getFormerCrs()); } finally { if (dialog != null) { dialog.setVisible(false); } } } }); } else { resetCrs = false; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public JInternalFrame getInternalWidget(final String name) { if (this.internalWidgets.containsKey(name)) { return this.internalWidgets.get(name); } else { LOG.warn("unknown internal widget '" + name + "'"); // NOI18N return null; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public int getInternalWidgetPosition(final String name) { if (this.internalWidgetPositions.containsKey(name)) { return this.internalWidgetPositions.get(name); } else { LOG.warn("unknown position for '" + name + "'"); // NOI18N return -1; } } //~ Inner Classes ---------------------------------------------------------- /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class MappingComponentRasterServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); private final transient ServiceLayer rasterService; private final XPImage pi; private int position = -1; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentRasterServiceListener object. * * @param position DOCUMENT ME! * @param pn DOCUMENT ME! * @param rasterService DOCUMENT ME! */ public MappingComponentRasterServiceListener(final int position, final PNode pn, final ServiceLayer rasterService) { this.position = position; this.rasterService = rasterService; if (pn instanceof XPImage) { this.pi = (XPImage)pn; } else { this.pi = null; } } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { fireActivityChanged(); if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { this.log.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() // NOI18N + " Errors: " // NOI18N + e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N fireActivityChanged(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { final Point2D localOrigin = getCamera().getViewBounds().getOrigin(); final double localScale = getCamera().getViewScale(); final PBounds localBounds = getCamera().getViewBounds(); final Object o = e.getRetrievedObject(); if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } final Runnable paintImageOnMap = new Runnable() { @Override public void run() { fireActivityChanged(); if ((o instanceof Image) && (e.isHasErrors() == false)) { // TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden if (isBackgroundEnabled()) { final Image i = (Image)o; if (rasterService.getName().startsWith("prefetching")) { // NOI18N final double x = localOrigin.getX() - localBounds.getWidth(); final double y = localOrigin.getY() - localBounds.getHeight(); pi.setImage(i, 0); pi.setScale(3 / localScale); pi.setOffset(x, y); } else { pi.setImage(i, animationDuration * 2); pi.setScale(1 / localScale); pi.setOffset(localOrigin); MappingComponent.this.repaint(); } } } } }; if (EventQueue.isDispatchThread()) { paintImageOnMap.run(); } else { EventQueue.invokeLater(paintImageOnMap); } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { this.log.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, rasterService)); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getPosition() { return position; } /** * DOCUMENT ME! * * @param position DOCUMENT ME! */ public void setPosition(final int position) { this.position = position; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class DocumentProgressListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); /** Displays the loading progress of Documents, e.g. SHP Files */ private final transient DocumentProgressWidget documentProgressWidget; private transient long requestId = -1; //~ Constructors ------------------------------------------------------- /** * Creates a new DocumentProgressListener object. */ public DocumentProgressListener() { documentProgressWidget = new DocumentProgressWidget(); documentProgressWidget.setVisible(false); if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) { MappingComponent.this.addInternalWidget( MappingComponent.PROGRESSWIDGET, MappingComponent.POSITION_SOUTHWEST, documentProgressWidget); } } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != -1) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = e.getRequestIdentifier(); this.documentProgressWidget.setServiceName(e.getRetrievalService().toString()); this.documentProgressWidget.setProgress(-1); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N } if (DEBUG) { if (log.isDebugEnabled()) { log.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: initialisation progress: " + e.getPercentageDone()); // NOI18N } } this.documentProgressWidget.setProgress(e.getPercentageDone()); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N } e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(100); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; e.getRetrievalService().removeRetrievalListener(this); this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public long getRequestId() { return this.requestId; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class MappingComponentFeatureServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); private final transient ServiceLayer featureService; private final transient PLayer parent; private long requestIdentifier; private Thread completionThread; private final List deletionCandidates; private final List twins; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentFeatureServiceListener. * * @param featureService the featureretrievalservice * @param parent the featurelayer (PNode) connected with the servicelayer */ public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) { this.featureService = featureService; this.parent = parent; this.deletionCandidates = new ArrayList(); this.twins = new ArrayList(); } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { requestIdentifier = e.getRequestIdentifier(); } if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N } } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: " + e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress() + ")"); // NOI18N } } fireActivityChanged(); // TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das // flüssiger ist } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { this.log.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N } } if (e.isInitialisationEvent()) { this.log.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: initialisation complete"); // NOI18N fireActivityChanged(); return; } if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N } ((RetrievalServiceLayer)featureService).setProgress(-1); fireActivityChanged(); return; } final List newFeatures = new ArrayList(); EventQueue.invokeLater(new Runnable() { @Override public void run() { ((RetrievalServiceLayer)featureService).setProgress(-1); parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible()); } }); // clear all old data to delete twins deletionCandidates.clear(); twins.clear(); // if it's a refresh, add all old features which should be deleted in the // newly acquired featurecollection if (!e.isRefreshExisting()) { deletionCandidates.addAll(parent.getChildrenReference()); } if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N } } // only start parsing the features if there are no errors and a correct collection if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) { completionThread = new Thread() { @Override public void run() { // this is the collection with the retrieved features final List features = new ArrayList((Collection)e.getRetrievedObject()); final int size = features.size(); int counter = 0; final Iterator it = features.iterator(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N } } while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted() && it.hasNext()) { counter++; final Object o = it.next(); if (o instanceof Feature) { final PFeature p = new PFeature(((Feature)o), wtst, clip_offset_x, clip_offset_y, MappingComponent.this); PFeature twin = null; for (final Object tester : deletionCandidates) { // if tester and PFeature are FeatureWithId-objects if ((((PFeature)tester).getFeature() instanceof FeatureWithId) && (p.getFeature() instanceof FeatureWithId)) { final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId(); final int id2 = ((FeatureWithId)(p.getFeature())).getId(); if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id if (id1 == id2) { twin = ((PFeature)tester); break; } } else { // else test the geometry for equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } else { // no FeatureWithId, test geometries for // equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } // if a twin is found remove him from the deletion candidates // and add him to the twins if (twin != null) { deletionCandidates.remove(twin); twins.add(twin); } else { // else add the PFeature to the new features newFeatures.add(p); } // calculate the advance of the progressbar // fire event only wheen needed final int currentProgress = (int)((double)counter / (double)size * 100d); if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) { ((RetrievalServiceLayer)featureService).setProgress(currentProgress); fireActivityChanged(); } } } if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) { // after all features are computed do stuff on the EDT EventQueue.invokeLater(new Runnable() { @Override public void run() { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N } } // if it's a refresh, delete all previous features if (e.isRefreshExisting()) { parent.removeAllChildren(); } final List deleteFeatures = new ArrayList(); for (final Object o : newFeatures) { parent.addChild((PNode)o); } // set the prograssbar to full if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: set progress to 100"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(100); fireActivityChanged(); // repaint the featurelayer parent.repaint(); // remove stickyNode from all deletionCandidates and add // each to the new deletefeature-collection for (final Object o : deletionCandidates) { if (o instanceof PFeature) { final PNode p = ((PFeature)o).getPrimaryAnnotationNode(); if (p != null) { removeStickyNode(p); } deleteFeatures.add(o); } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount before:" + parent.getChildrenCount()); // NOI18N } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: deleteFeatures=" + deleteFeatures.size()); // + " :" + // deleteFeatures);//NOI18N } } parent.removeChildren(deleteFeatures); if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount after:" + parent.getChildrenCount()); // NOI18N } } if (LOG.isInfoEnabled()) { LOG.info( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + parent.getChildrenCount() + " features retrieved or updated"); // NOI18N } rescaleStickyNodes(); } catch (final Exception exception) { log.warn( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Fehler beim Aufr\u00E4umen", exception); // NOI18N } } }); } else { if (DEBUG) { if (log.isDebugEnabled()) { log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } }; completionThread.setPriority(Thread.NORM_PRIORITY); if (requestIdentifier == e.getRequestIdentifier()) { completionThread.start(); } else { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: aborted, TaskCounter:" + taskCounter); // NOI18N if (completionThread != null) { completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(-1); } else { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(0); } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, featureService)); } } } }
public void setInteractionMode(final String interactionMode) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:" + this.interactionMode + "", new Exception()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } setPointerAnnotationVisibility(false); if (getPrintingFrameLayer().getChildrenCount() > 1) { getPrintingFrameLayer().removeAllChildren(); } if (this.interactionMode != null) { if (interactionMode.equals(FEATURE_INFO)) { ((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo() .setVisible(true); } else { ((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo() .setVisible(false); } if (isReadOnly()) { ((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class); } final PInputEventListener pivl = this.getInputListener(this.interactionMode); if (pivl != null) { removeInputEventListener(pivl); } else { LOG.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N } if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) { featureCollection.unselectAll(); } if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEAR_REFERENCING) || interactionMode.equals(SPLIT_POLYGON)) && (this.readOnly == false)) { featureSelectionChanged(null); } if (interactionMode.equals(JOIN_POLYGONS)) { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent( this, PROPERTY_MAP_INTERACTION_MODE, this.interactionMode, interactionMode); this.interactionMode = interactionMode; final PInputEventListener pivl = getInputListener(interactionMode); if (pivl != null) { addInputEventListener(pivl); propertyChangeSupport.firePropertyChange(interactionModeChangedEvent); CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode)); } else { LOG.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N } } catch (final Exception e) { LOG.error("Fehler beim Ändern des InteractionModes", e); // NOI18N } } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Deprecated public void formComponentResized(final ComponentEvent evt) { this.componentResizedDelayed(); } /** * Resizes the map and does not reload all services. * * @see #componentResizedDelayed() */ public void componentResizedIntermediate() { if (!this.isLocked()) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { // rescale map if (historyModel.getCurrentElement() != null) { PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds == null) { bounds = initialBoundingBox.getPBounds(wtst); } if (bounds.getWidth() < 0) { bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight()); } if (bounds.getHeight() < 0) { bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1)); } getCamera().animateViewToCenterBounds(bounds, true, animationDuration); } } } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } /** * Resizes the map and reloads all services. * * @see #componentResizedIntermediate() */ public void componentResizedDelayed() { if (!this.isLocked()) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { final PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds != null) { gotoBoundsWithoutHistory(bounds); } else { gotoBoundsWithoutHistory(getInitialBoundingBox().getPBounds(wtst)); } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } } catch (final Exception t) { LOG.error("Fehler in formComponentResized()", t); // NOI18N } } } /** * syncSelectedObjectPresenter(int i). * * @param i DOCUMENT ME! */ public void syncSelectedObjectPresenter(final int i) { selectedObjectPresenter.setVisible(true); if (featureCollection.getSelectedFeatures().size() > 0) { if (featureCollection.getSelectedFeatures().size() == 1) { final PFeature selectedFeature = (PFeature)pFeatureHM.get( featureCollection.getSelectedFeatures().toArray()[0]); if (selectedFeature != null) { selectedObjectPresenter.getCamera() .animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2); } } else { // todo } } else { LOG.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public BoundingBox getInitialBoundingBox() { if (initialBoundingBox == null) { return mappingModel.getInitialBoundingBox(); } else { return initialBoundingBox; } } /** * Returns the current featureCollection. * * @return DOCUMENT ME! */ public FeatureCollection getFeatureCollection() { return featureCollection; } /** * Replaces the old featureCollection with a new one. * * @param featureCollection the new featureCollection */ public void setFeatureCollection(final FeatureCollection featureCollection) { this.featureCollection = featureCollection; featureCollection.addFeatureCollectionListener(this); } /** * DOCUMENT ME! * * @param visibility DOCUMENT ME! */ public void setFeatureCollectionVisibility(final boolean visibility) { featureLayer.setVisible(visibility); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFeatureCollectionVisible() { return featureLayer.getVisible(); } /** * Adds a new mapservice at a specific place of the layercontrols. * * @param mapService the new mapservice * @param position the index where to position the mapservice */ public void addMapService(final MapService mapService, final int position) { try { PNode p = new PNode(); if (mapService instanceof RasterMapService) { LOG.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N if (mapService.getPNode() instanceof XPImage) { p = (XPImage)mapService.getPNode(); } else { p = new XPImage(); mapService.setPNode(p); } mapService.addRetrievalListener(new MappingComponentRasterServiceListener( position, p, (ServiceLayer)mapService)); } else { LOG.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName() + ")"); // NOI18N p = new PLayer(); mapService.setPNode(p); if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): isDocumentFeatureService, checking document size"); // NOI18N } } final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService; if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) { LOG.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '" + documentFeatureService.getName() + "' size of " + (documentFeatureService.getDocumentSize() / 1000000) + "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000) + "MB)"); // NOI18N if (this.documentProgressListener == null) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): lazy instantiation of documentProgressListener"); // NOI18N } } this.documentProgressListener = new DocumentProgressListener(); } if (this.documentProgressListener.getRequestId() != -1) { LOG.error("FeatureMapService(" + mapService + "): The documentProgressListener is already in use by request '" + this.documentProgressListener.getRequestId() + ", document progress cannot be tracked"); // NOI18N } else { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N } } documentFeatureService.addRetrievalListener(this.documentProgressListener); } } } mapService.addRetrievalListener(new MappingComponentFeatureServiceListener( (ServiceLayer)mapService, (PLayer)mapService.getPNode())); } p.setTransparency(mapService.getTranslucency()); p.setVisible(mapService.isVisible()); mapServicelayer.addChild(p); } catch (final Exception e) { LOG.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + e.getMessage(), e); // NOI18N } } /** * DOCUMENT ME! * * @param mm DOCUMENT ME! */ public void preparationSetMappingModel(final MappingModel mm) { mappingModel = mm; } /** * Sets a new mappingmodel in this MappingComponent. * * @param mm the new mappingmodel */ public void setMappingModel(final MappingModel mm) { LOG.info("setMappingModel"); // NOI18N // FIXME: why is the default uncaught exception handler set in such a random place? if (Thread.getDefaultUncaughtExceptionHandler() == null) { LOG.info("setDefaultUncaughtExceptionHandler"); // NOI18N Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { LOG.error("Error", e); } }); } mappingModel = mm; // currentBoundingBox = mm.getInitialBoundingBox(); final Runnable r = new Runnable() { @Override public void run() { mappingModel.addMappingModelListener(MappingComponent.this); final TreeMap rs = mappingModel.getRasterServices(); // Rückwärts wegen der Reihenfolge der Layer im Layer Widget final Iterator it = rs.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { addMapService(((MapService)o), rsi); } } adjustLayers(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Set Mapping Modell done"); // NOI18N } } } }; CismetThreadPool.execute(r); } /** * Returns the current mappingmodel. * * @return current mappingmodel */ public MappingModel getMappingModel() { return mappingModel; } /** * Animates a component to a given x/y-coordinate in a given time. * * @param c the component to animate * @param toX final x-position * @param toY final y-position * @param animationDuration duration of the animation * @param hideAfterAnimation should the component be hidden after animation? */ private void animateComponent(final JComponent c, final int toX, final int toY, final int animationDuration, final boolean hideAfterAnimation) { if (animationDuration > 0) { final int x = (int)c.getBounds().getX() - toX; final int y = (int)c.getBounds().getY() - toY; int sx; int sy; if (x > 0) { sx = -1; } else { sx = 1; } if (y > 0) { sy = -1; } else { sy = 1; } int big; if (Math.abs(x) > Math.abs(y)) { big = Math.abs(x); } else { big = Math.abs(y); } final int sleepy; if ((animationDuration / big) < 1) { sleepy = 1; } else { sleepy = animationDuration / big; } final int directionY = sy; final int directionX = sx; if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY + ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX=" + toX + ", toY=" + toY); // NOI18N } } final Thread timer = new Thread() { @Override public void run() { while (!isInterrupted()) { try { sleep(sleepy); } catch (final Exception iex) { } EventQueue.invokeLater(new Runnable() { @Override public void run() { int currentY = (int)c.getBounds().getY(); int currentX = (int)c.getBounds().getX(); if (currentY != toY) { currentY = currentY + directionY; } if (currentX != toX) { currentX = currentX + directionX; } c.setBounds(currentX, currentY, c.getWidth(), c.getHeight()); } }); if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) { if (hideAfterAnimation) { EventQueue.invokeLater(new Runnable() { @Override public void run() { c.setVisible(false); c.hide(); } }); } break; } } } }; timer.setPriority(Thread.NORM_PRIORITY); timer.start(); } else { c.setBounds(toX, toY, c.getWidth(), c.getHeight()); if (hideAfterAnimation) { c.setVisible(false); } } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ @Deprecated public NewSimpleInternalLayerWidget getInternalLayerWidget() { return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET); } /** * Adds a new internal widget to the map.<br/> * If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget * will be added. If a widget with a different name already exisit at the same {@code position} the new widget will * not be added and the operation returns {@code false}. * * @param name unique name of the widget * @param position position of the widget * @param widget the widget * * @return {@code true} if the widget could be added, {@code false} otherwise * * @see #POSITION_NORTHEAST * @see #POSITION_NORTHWEST * @see #POSITION_SOUTHEAST * @see #POSITION_SOUTHWEST */ public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) { if (LOG.isDebugEnabled()) { LOG.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N } if (this.internalWidgets.containsKey(name)) { LOG.warn("widget '" + name + "' already added, removing old widget"); // NOI18N this.remove(this.getInternalWidget(name)); } else if (this.internalWidgetPositions.containsValue(position)) { LOG.warn("widget position '" + position + "' already taken"); // NOI18N return false; } this.internalWidgets.put(name, widget); this.internalWidgetPositions.put(name, position); widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N this.add(widget); widget.pack(); return true; } /** * Removes an existing internal widget from the map. * * @param name name of the widget to be removed * * @return {@code true} id the widget was found and removed, {@code false} otherwise */ public boolean removeInternalWidget(final String name) { if (LOG.isDebugEnabled()) { LOG.debug("removing internal widget '" + name + "'"); // NOI18N } if (!this.internalWidgets.containsKey(name)) { LOG.warn("widget '" + name + "' not found"); // NOI18N return false; } this.remove(this.getInternalWidget(name)); this.internalWidgets.remove(name); this.internalWidgetPositions.remove(name); return true; } /** * Shows an InternalWidget by sliding it into the mappingcomponent. * * @param name name of the internl component to show * @param visible should the widget be visible after the animation? * @param animationDuration duration of the animation * * @return {@code true} if the operation was successful, {@code false} otherwise */ public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) { final JInternalFrame internalWidget = this.getInternalWidget(name); if (internalWidget == null) { return false; } final int positionX; final int positionY; final int widgetPosition = this.getInternalWidgetPosition(name); final boolean isHigher = (getHeight() < (internalWidget.getHeight() + 2)) && (getHeight() > 0); final boolean isWider = (getWidth() < (internalWidget.getWidth() + 2)) && (getWidth() > 0); switch (widgetPosition) { case POSITION_NORTHWEST: { positionX = 1; positionY = 1; break; } case POSITION_SOUTHWEST: { positionX = 1; positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1); break; } case POSITION_NORTHEAST: { positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1); positionY = 1; break; } case POSITION_SOUTHEAST: { positionX = isWider ? 1 : (getWidth() - internalWidget.getWidth() - 1); positionY = isHigher ? 1 : (getHeight() - internalWidget.getHeight() - 1); break; } default: { LOG.warn("unkown widget position?!"); // NOI18N return false; } } if (visible) { final int toY; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { if (isHigher) { toY = getHeight() - 1; } else { toY = positionY - internalWidget.getHeight() - 1; } } else { if (isHigher) { toY = getHeight() + 1; } else { toY = positionY + internalWidget.getHeight() + 1; } } internalWidget.setBounds( positionX, toY, isWider ? (getWidth() - 2) : internalWidget.getWidth(), isHigher ? (getHeight() - 2) : internalWidget.getHeight()); internalWidget.setVisible(true); internalWidget.show(); animateComponent(internalWidget, positionX, positionY, animationDuration, false); } else { internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight()); int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } animateComponent(internalWidget, positionX, toY, animationDuration, true); } return true; } /** * DOCUMENT ME! * * @param visible DOCUMENT ME! * @param animationDuration DOCUMENT ME! */ @Deprecated public void showInternalLayerWidget(final boolean visible, final int animationDuration) { this.showInternalWidget(LAYERWIDGET, visible, animationDuration); } /** * Returns a boolean, if the InternalLayerWidget is visible. * * @return true, if visible, else false */ @Deprecated public boolean isInternalLayerWidgetVisible() { return this.getInternalLayerWidget().isVisible(); } /** * Returns a boolean, if the InternalWidget is visible. * * @param name name of the widget * * @return true, if visible, else false */ public boolean isInternalWidgetVisible(final String name) { final JInternalFrame widget = this.getInternalWidget(name); if (widget != null) { return widget.isVisible(); } return false; } /** * Moves the camera to the initial bounding box (e.g. if the home-button is pressed). */ public void gotoInitialBoundingBox() { final double x1; final double y1; final double x2; final double y2; final double w; final double h; x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1()); y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1()); x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2()); y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2()); final Rectangle2D home = new Rectangle2D.Double(); home.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(home, true, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { LOG.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } setNewViewBounds(home); queryServices(); } /** * Refreshs all registered services. */ public void queryServices() { if (newViewBounds != null) { addToHistory(new PBoundsWithCleverToString( new PBounds(newViewBounds), wtst, mappingModel.getSrs().getCode())); queryServicesWithoutHistory(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServices()"); // NOI18N } } rescaleStickyNodes(); } } /** * Forces all services to refresh themselves. */ public void refresh() { forceQueryServicesWithoutHistory(); } /** * Forces all services to refresh themselves. */ private void forceQueryServicesWithoutHistory() { queryServicesWithoutHistory(true); } /** * Refreshs all services, but not forced. */ private void queryServicesWithoutHistory() { queryServicesWithoutHistory(false); } /** * Waits until all animations are done, then iterates through all registered services and calls handleMapService() * for each. * * @param forced forces the refresh */ private void queryServicesWithoutHistory(final boolean forced) { if (forced && mainMappingComponent) { CismapBroker.getInstance().fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_RESET, this)); } if (!locked) { final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception doNothing) { } } CismapBroker.getInstance().fireMapBoundsChanged(); if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N } } handleMapService(rsi, (MapService)o, forced); } else { LOG.warn("service is not of type MapService:" + o); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof MapService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N } } handleMapService(fsi, (MapService)o, forced); } else { LOG.warn("service is not of type MapService:" + o); // NOI18N } } } } }; CismetThreadPool.execute(r); } } /** * queryServicesIndependentFromMap. * * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param rl DOCUMENT ME! */ public void queryServicesIndependentFromMap(final int width, final int height, final BoundingBox bb, final RetrievalListener rl) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N } } final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception doNothing) { } } if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer) && ((ServiceLayer)o).isEnabled() && (o instanceof RetrievalServiceLayer) && ((RetrievalServiceLayer)o).getPNode().getVisible()) { try { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = wfsClone; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(rsi); handleMapService(rsi, (MapService)r, width, height, bb, true); } catch (final Exception t) { LOG.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N } } else { LOG.warn("ignoring service '" + o + "' for printing"); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof AbstractRetrievalService) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = (AbstractRetrievalService)o; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(fsi); handleMapService(fsi, (MapService)r, 0, 0, bb, true); } } } } }; CismetThreadPool.execute(r); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param service rs * @param forced DOCUMENT ME! */ public void handleMapService(final int position, final MapService service, final boolean forced) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("in handleRasterService: " + service + "(" + Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N } } final PBounds bounds = getCamera().getViewBounds(); final BoundingBox bb = new BoundingBox(); final double x1 = getWtst().getWorldX(bounds.getMinX()); final double y1 = getWtst().getWorldY(bounds.getMaxY()); final double x2 = getWtst().getWorldX(bounds.getMaxX()); final double y2 = getWtst().getWorldY(bounds.getMinY()); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Bounds=" + bounds); // NOI18N } } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N } } if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N bb.setX1(x1 - (x2 - x1)); bb.setY1(y1 - (y2 - y1)); bb.setX2(x2 + (x2 - x1)); bb.setY2(y2 + (y2 - y1)); } else { bb.setX1(x1); bb.setY1(y1); bb.setX2(x2); bb.setY2(y2); } handleMapService(position, service, getWidth(), getHeight(), bb, forced); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param rs DOCUMENT ME! * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param forced DOCUMENT ME! */ private void handleMapService(final int position, final MapService rs, final int width, final int height, final BoundingBox bb, final boolean forced) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("handleMapService: " + rs); // NOI18N } } rs.setSize(height, width); if (((ServiceLayer)rs).isEnabled()) { synchronized (serviceFuturesMap) { final Future<?> sf = serviceFuturesMap.get(rs); if ((sf == null) || sf.isDone()) { final Runnable serviceCall = new Runnable() { @Override public void run() { try { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (final Exception e) { } } rs.setBoundingBox(bb); if (rs instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection); } rs.retrieve(forced); } finally { serviceFuturesMap.remove(rs); } } }; synchronized (serviceFuturesMap) { serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall)); } } } } else { rs.setBoundingBox(bb); } } /** * Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it. * * @return new WorldToScreenTransform or null */ public WorldToScreenTransform getWtst() { try { if (wtst == null) { final double y_real = mappingModel.getInitialBoundingBox().getY2() - mappingModel.getInitialBoundingBox().getY1(); final double x_real = mappingModel.getInitialBoundingBox().getX2() - mappingModel.getInitialBoundingBox().getX1(); double clip_height; double clip_width; double x_screen = getWidth(); double y_screen = getHeight(); if (x_screen == 0) { x_screen = 100; } if (y_screen == 0) { y_screen = 100; } if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert clip_height = x_screen * y_real / x_real; clip_width = x_screen; clip_offset_y = 0; // (y_screen-clip_height)/2; clip_offset_x = 0; } else { // Y ist Bestimmer clip_height = y_screen; clip_width = y_screen * x_real / y_real; clip_offset_y = 0; clip_offset_x = 0; // (x_screen-clip_width)/2; } wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(), mappingModel.getInitialBoundingBox().getY2()); } return wtst; } catch (final Exception t) { LOG.error("Fehler in getWtst()", t); // NOI18N return null; } } /** * Resets the current WorldToScreenTransformation. */ public void resetWtst() { wtst = null; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_x() { return 0; // clip_offset_x; } /** * Assigns a new value to the x-clip-offset. * * @param clip_offset_x new clipoffset */ public void setClip_offset_x(final double clip_offset_x) { this.clip_offset_x = clip_offset_x; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_y() { return 0; // clip_offset_y; } /** * Assigns a new value to the y-clip-offset. * * @param clip_offset_y new clipoffset */ public void setClip_offset_y(final double clip_offset_y) { this.clip_offset_y = clip_offset_y; } /** * Returns the rubberband-PLayer. * * @return DOCUMENT ME! */ public PLayer getRubberBandLayer() { return rubberBandLayer; } /** * Assigns a given PLayer to the variable rubberBandLayer. * * @param rubberBandLayer a PLayer */ public void setRubberBandLayer(final PLayer rubberBandLayer) { this.rubberBandLayer = rubberBandLayer; } /** * Sets new viewbounds. * * @param r2d Rectangle2D */ public void setNewViewBounds(final Rectangle2D r2d) { newViewBounds = r2d; } /** * Will be called if the selection of features changes. It selects the PFeatures connected to the selected features * of the featurecollectionevent and moves them to the front. Also repaints handles at the end. * * @param fce featurecollectionevent with selected features */ @Override public void featureSelectionChanged(final FeatureCollectionEvent fce) { final Collection allChildren = featureLayer.getChildrenReference(); final ArrayList<PFeature> all = new ArrayList<PFeature>(); for (final Object o : allChildren) { if (o instanceof PFeature) { all.add((PFeature)o); } else if (o instanceof PLayer) { // Handling von Feature-Gruppen-Layer, welche als Kinder dem Feature Layer hinzugefügt wurden all.addAll(((PLayer)o).getChildrenReference()); } } // final Collection<PFeature> all = featureLayer.getChildrenReference(); for (final PFeature f : all) { f.setSelected(false); } Collection<Feature> c; if (fce != null) { c = fce.getFeatureCollection().getSelectedFeatures(); } else { c = featureCollection.getSelectedFeatures(); } ////handle featuregroup select-delegation//// final Set<Feature> selectionResult = new HashSet<Feature>(); for (final Feature current : c) { if (current instanceof FeatureGroup) { selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current)); } else { selectionResult.add(current); } } c = selectionResult; for (final Feature f : c) { if (f != null) { final PFeature feature = getPFeatureHM().get(f); if (feature != null) { if (feature.getParent() != null) { feature.getParent().moveToFront(); } feature.setSelected(true); feature.moveToFront(); // Fuer den selectedObjectPresenter (Eigener PCanvas) syncSelectedObjectPresenter(1000); } else { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } } showHandles(false); } /** * Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on * each feature of the given featurecollectionevent. Repaints handles at the end. * * @param fce featurecollectionevent with changed features */ @Override public void featuresChanged(final FeatureCollectionEvent fce) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("featuresChanged"); // NOI18N } } final List<Feature> list = new ArrayList<Feature>(); list.addAll(fce.getEventFeatures()); for (final Feature elem : list) { reconsiderFeature(elem); } showHandles(false); } /** * Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls * following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode() * * @param fce featurecollectionevent with features to reconsile */ @Override public void featureReconsiderationRequested(final FeatureCollectionEvent fce) { for (final Feature f : fce.getEventFeatures()) { if (f != null) { final PFeature node = pFeatureHM.get(f); if (node != null) { node.syncGeometry(); node.visualize(); node.resetInfoNodePosition(); node.refreshInfoNode(); repaint(); } } } } /** * Method is deprecated and deactivated. Does nothing!! * * @param fce FeatureCollectionEvent with features to add */ @Override @Deprecated public void featuresAdded(final FeatureCollectionEvent fce) { } /** * Method is deprecated and deactivated. Does nothing!! * * @deprecated DOCUMENT ME! */ @Override @Deprecated public void featureCollectionChanged() { } /** * Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a * checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent. * * @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice */ @Override public void allFeaturesRemoved(final FeatureCollectionEvent fce) { for (final PFeature feature : pFeatureHM.values()) { feature.cleanup(); } stickyPNodes.clear(); pFeatureHM.clear(); featureLayer.removeAllChildren(); // Lösche alle Features in den Gruppen-Layer, aber füge den Gruppen-Layer wieder dem FeatureLayer hinzu for (final PLayer layer : featureGrpLayerMap.values()) { layer.removeAllChildren(); featureLayer.addChild(layer); } checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); } /** * Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining * supporting rasterservices and paints handles at the end. * * @param fce FeatureCollectionEvent with features to remove */ @Override public void featuresRemoved(final FeatureCollectionEvent fce) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("featuresRemoved"); // NOI18N } } removeFeatures(fce.getEventFeatures()); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); showHandles(false); } /** * Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and * which need a refresh. * * @param fce FeatureCollectionEvent with removed features */ private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) { final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>(); for (final Feature f : getFeatureCollection().getAllFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } rasterServices.add(rs); // DANGER } } for (final Feature f : fce.getEventFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } if (rasterServices.contains(rs)) { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r); } } } else { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r); } } } } } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) { getMappingModel().removeLayer(frs); } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) { handleMapService(0, frs, true); } } /** * public void showFeatureCollection(Feature[] features) { com.vividsolutions.jts.geom.Envelope * env=computeFeatureEnvelope(features); showFeatureCollection(features,env); } public void * showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { selectedFeature=null; * handleLayer.removeAllChildren(); //setRasterServiceLayerImagesVisibility(false); Envelope eSquare=null; * HashSet<Feature> featureSet=new HashSet<Feature>(); featureSet.addAll(holdFeatures); * featureSet.addAll(java.util.Arrays.asList(f)); Feature[] features=featureSet.toArray(new Feature[0]); * pFeatureHM.clear(); addFeaturesToMap(features); zoomToFullFeatureCollectionBounds(); }. * * @param groupId DOCUMENT ME! * @param visible DOCUMENT ME! */ public void setGroupLayerVisibility(final String groupId, final boolean visible) { final PLayer layer = this.featureGrpLayerMap.get(groupId); if (layer != null) { layer.setVisible(visible); } } /** * is called when new feature is added to FeatureCollection. * * @param features DOCUMENT ME! */ public void addFeaturesToMap(final Feature[] features) { final double local_clip_offset_y = clip_offset_y; final double local_clip_offset_x = clip_offset_x; /// Hier muss der layer bestimmt werdenn for (int i = 0; i < features.length; ++i) { final Feature feature = features[i]; final PFeature p = new PFeature( feature, getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); try { if (feature instanceof StyledFeature) { p.setTransparency(((StyledFeature)(feature)).getTransparency()); } else { p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); } EventQueue.invokeLater(new Runnable() { @Override public void run() { if (feature instanceof FeatureGroupMember) { final FeatureGroupMember fgm = (FeatureGroupMember)feature; final String groupId = fgm.getGroupId(); PLayer groupLayer = featureGrpLayerMap.get(groupId); if (groupLayer == null) { groupLayer = new PLayer(); featureLayer.addChild(groupLayer); featureGrpLayerMap.put(groupId, groupLayer); if (LOG.isDebugEnabled()) { LOG.debug("created layer for group " + groupId); } } groupLayer.addChild(p); if (fgm.getGeometry() != null) { pFeatureHM.put(fgm.getFeature(), p); pFeatureHM.put(fgm, p); } if (LOG.isDebugEnabled()) { LOG.debug("added feature to group " + groupId); } } } }); } catch (final Exception e) { p.setTransparency(0.8f); LOG.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N } // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) if (!(feature instanceof FeatureGroupMember)) { if (feature.getGeometry() != null) { pFeatureHM.put(p.getFeature(), p); final int ii = i; EventQueue.invokeLater(new Runnable() { @Override public void run() { featureLayer.addChild(p); if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { p.moveToFront(); } } }); } } } EventQueue.invokeLater(new Runnable() { @Override public void run() { rescaleStickyNodes(); repaint(); fireFeaturesAddedToMap(Arrays.asList(features)); // SuchFeatures in den Vordergrund stellen for (final Feature feature : featureCollection.getAllFeatures()) { if (feature instanceof SearchFeature) { final PFeature pFeature = pFeatureHM.get(feature); pFeature.moveToFront(); } } } }); // check whether the feature has a rasterSupportLayer or not for (final Feature f : features) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (!getMappingModel().getRasterServices().containsValue(rs)) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("FeatureAwareRasterServiceAdded"); // NOI18N } } rs.setFeatureCollection(getFeatureCollection()); getMappingModel().addLayer(rs); } } } showHandles(false); } /** * DOCUMENT ME! * * @param cf DOCUMENT ME! */ private void fireFeaturesAddedToMap(final Collection<Feature> cf) { for (final MapListener curMapListener : mapListeners) { curMapListener.featuresAddedToMap(cf); } } /** * Creates an envelope around all features from the given array. * * @param features features to create the envelope around * * @return Envelope com.vividsolutions.jts.geom.Envelope */ private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) { final PNode root = new PNode(); for (int i = 0; i < features.length; ++i) { final PNode p = PNodeFactory.createPFeature(features[i], this); if (p != null) { root.addChild(p); } } final PBounds ext = root.getFullBounds(); final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope( ext.x, ext.x + ext.width, ext.y, ext.y + ext.height); return env; } /** * Zooms in / out to match the bounds of the featurecollection. */ public void zoomToFullFeatureCollectionBounds() { zoomToFeatureCollection(); } /** * Adds a new cursor to the cursor-hashmap. * * @param mode interactionmode as string * @param cursor cursor-object */ public void putCursor(final String mode, final Cursor cursor) { cursors.put(mode, cursor); } /** * Returns the cursor assigned to the given mode. * * @param mode mode as String * * @return Cursor-object or null */ public Cursor getCursor(final String mode) { return cursors.get(mode); } /** * Adds a new PBasicInputEventHandler for a specific interactionmode. * * @param mode interactionmode as string * @param listener new PBasicInputEventHandler */ public void addInputListener(final String mode, final PBasicInputEventHandler listener) { inputEventListener.put(mode, listener); } /** * Returns the PBasicInputEventHandler assigned to the committed interactionmode. * * @param mode interactionmode as string * * @return PBasicInputEventHandler-object or null */ public PInputEventListener getInputListener(final String mode) { final Object o = inputEventListener.get(mode); if (o instanceof PInputEventListener) { return (PInputEventListener)o; } else { return null; } } /** * Returns whether the features are editable or not. * * @return DOCUMENT ME! */ public boolean isReadOnly() { return readOnly; } /** * Sets all Features ReadOnly use Feature.setEditable(boolean) instead. * * @param readOnly DOCUMENT ME! */ public void setReadOnly(final boolean readOnly) { for (final Object f : featureCollection.getAllFeatures()) { ((Feature)f).setEditable(!readOnly); } this.readOnly = readOnly; handleLayer.repaint(); try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } snapHandleLayer.removeAllChildren(); } /** * Returns the current HandleInteractionMode. * * @return DOCUMENT ME! */ public String getHandleInteractionMode() { return handleInteractionMode; } /** * Changes the HandleInteractionMode. Repaints handles. * * @param handleInteractionMode the new HandleInteractionMode */ public void setHandleInteractionMode(final String handleInteractionMode) { this.handleInteractionMode = handleInteractionMode; showHandles(false); } /** * Returns whether the background is enabled or not. * * @return DOCUMENT ME! */ public boolean isBackgroundEnabled() { return backgroundEnabled; } /** * TODO. * * @param backgroundEnabled DOCUMENT ME! */ public void setBackgroundEnabled(final boolean backgroundEnabled) { if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) { featureServiceLayerVisible = featureServiceLayer.getVisible(); } this.mapServicelayer.setVisible(backgroundEnabled); this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible); for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) { featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible); } if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) { this.queryServices(); } this.backgroundEnabled = backgroundEnabled; } /** * Returns the featurelayer. * * @return DOCUMENT ME! */ public PLayer getFeatureLayer() { return featureLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Map<String, PLayer> getFeatureGroupLayers() { return this.featureGrpLayerMap; } /** * Adds a PFeature to the PFeatureHashmap. * * @param p PFeature to add */ public void refreshHM(final PFeature p) { pFeatureHM.put(p.getFeature(), p); } /** * Returns the selectedObjectPresenter (PCanvas). * * @return DOCUMENT ME! */ public PCanvas getSelectedObjectPresenter() { return selectedObjectPresenter; } /** * If f != null it calls the reconsiderFeature()-method of the featurecollection. * * @param f feature to reconcile */ public void reconsiderFeature(final Feature f) { if (f != null) { featureCollection.reconsiderFeature(f); } } /** * Removes all features of the collection from the hashmap. * * @param fc collection of features to remove */ public void removeFeatures(final Collection<Feature> fc) { featureLayer.setVisible(false); for (final Feature elem : fc) { removeFromHM(elem); } featureLayer.setVisible(true); } /** * Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key. * * @param f feature of the Pfeature that should be deleted */ public void removeFromHM(final Feature f) { final PFeature pf = pFeatureHM.get(f); if (pf != null) { pf.cleanup(); pFeatureHM.remove(f); stickyPNodes.remove(pf); try { LOG.info("Entferne Feature " + f); // NOI18N featureLayer.removeChild(pf); for (final PLayer grpLayer : this.featureGrpLayerMap.values()) { if (grpLayer.removeChild(pf) != null) { break; } } } catch (Exception ex) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N } } } } else { LOG.warn("Feature war nicht in pFeatureHM"); // NOI18N } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("pFeatureHM" + pFeatureHM); // NOI18N } } } /** * Zooms to the current selected node. * * @deprecated DOCUMENT ME! */ public void zoomToSelectedNode() { zoomToSelection(); } /** * Zooms to the current selected features. */ public void zoomToSelection() { final Collection<Feature> selection = featureCollection.getSelectedFeatures(); zoomToAFeatureCollection(selection, true, false); } /** * Zooms to a specific featurecollection. * * @param collection the featurecolltion * @param withHistory should the zoomaction be undoable * @param fixedScale fixedScale */ public void zoomToAFeatureCollection(final Collection<Feature> collection, final boolean withHistory, final boolean fixedScale) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("zoomToAFeatureCollection"); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } boolean first = true; Geometry g = null; for (final Feature f : collection) { if (first) { if (f.getGeometry() != null) { g = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode()) .getEnvelope(); if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) { g = g.buffer(((Bufferable)f).getBuffer() + 0.001); } first = false; } } else { if (f.getGeometry() != null) { Geometry geometry = CrsTransformer.transformToGivenCrs(f.getGeometry(), mappingModel.getSrs().getCode()) .getEnvelope(); if ((f instanceof Bufferable) && mappingModel.getSrs().isMetric()) { geometry = geometry.buffer(((Bufferable)f).getBuffer() + 0.001); } g = g.getEnvelope().union(geometry); } } } if (g != null) { // FIXME: we shouldn't only complain but do sth if ((getHeight() == 0) || (getWidth() == 0)) { LOG.warn("DIVISION BY ZERO"); // NOI18N } // dreisatz.de final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10; final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10; double buff = 0; if (hBuff > vBuff) { buff = hBuff; } else { buff = vBuff; } if (buff == 0.0) { if (mappingModel.getSrs().isMetric()) { buff = 1.0; } else { buff = 0.01; } } g = g.buffer(buff); final BoundingBox bb = new BoundingBox(g); final boolean onlyOnePoint = (collection.size() == 1) && (((Feature)(collection.toArray()[0])).getGeometry() instanceof com.vividsolutions.jts.geom.Point); gotoBoundingBox(bb, withHistory, !(fixedScale || (onlyOnePoint && (g.getArea() < 10))), animationDuration); } } /** * Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create * their handles and to add them to the handlelayer. * * @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles */ public void showHandles(final boolean waitTillAllAnimationsAreComplete) { // are there features selected? if (featureCollection.getSelectedFeatures().size() > 0) { // DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf final Runnable handle = new Runnable() { @Override public void run() { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); while (getAnimating() && waitTillAllAnimationsAreComplete) { try { Thread.currentThread().sleep(10); } catch (final Exception e) { LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (featureCollection.areFeaturesEditable() && (getInteractionMode().equals(SELECT) || getInteractionMode().equals(LINEAR_REFERENCING) || getInteractionMode().equals(PAN) || getInteractionMode().equals(ZOOM) || getInteractionMode().equals(ALKIS_PRINT) || getInteractionMode().equals(SPLIT_POLYGON))) { // Handles für alle selektierten Features der Collection hinzufügen if (getHandleInteractionMode().equals(ROTATE_POLYGON)) { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature instanceof Feature) && selectedFeature.isEditable()) { if ((pFeatureHM.get(selectedFeature) != null) && pFeatureHM.get(selectedFeature).getVisible()) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { pFeatureHM.get(selectedFeature).addRotationHandles(handleLayer); } }); } else { LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } } } } else { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature != null) && selectedFeature.isEditable()) { if ((pFeatureHM.get(selectedFeature) != null) && pFeatureHM.get(selectedFeature).getVisible()) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { try { pFeatureHM.get(selectedFeature).addHandles(handleLayer); } catch (final Exception e) { LOG.error("Error bei addHandles: ", e); // NOI18N } } }); } else { LOG.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } // DANGER mit break werden nur die Handles EINES slektierten Features angezeigt // wird break auskommentiert werden jedoch zu viele Handles angezeigt break; } } } } } }; if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("showHandles", new CurrentStackTrace()); // NOI18N } } CismetThreadPool.execute(handle); } else { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); } } /** * Will return a PureNewFeature if there is only one in the featurecollection else null. * * @return DOCUMENT ME! */ public PFeature getSolePureNewFeature() { int counter = 0; PFeature sole = null; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object o = it.next(); if (o instanceof PFeature) { if (((PFeature)o).getFeature() instanceof PureNewFeature) { ++counter; sole = ((PFeature)o); } } } if (counter == 1) { return sole; } else { return null; } } /** * Returns the temporary featurelayer. * * @return DOCUMENT ME! */ public PLayer getTmpFeatureLayer() { return tmpFeatureLayer; } /** * Assigns a new temporary featurelayer. * * @param tmpFeatureLayer PLayer */ public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) { this.tmpFeatureLayer = tmpFeatureLayer; } /** * Returns whether the grid is enabled or not. * * @return DOCUMENT ME! */ public boolean isGridEnabled() { return gridEnabled; } /** * Enables or disables the grid. * * @param gridEnabled true, to enable the grid */ public void setGridEnabled(final boolean gridEnabled) { this.gridEnabled = gridEnabled; } /** * Returns a String from two double-values. Serves the visualization. * * @param x X-coordinate * @param y Y-coordinate * * @return a String-object like "(X,Y)" */ public static String getCoordinateString(final double x, final double y) { final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N final DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); df.setDecimalFormatSymbols(dfs); return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N } /** * DOCUMENT ME! * * @param event DOCUMENT ME! * * @return DOCUMENT ME! */ public com.vividsolutions.jts.geom.Point getPointGeometryFromPInputEvent(final PInputEvent event) { final double xCoord = getWtst().getSourceX(event.getPosition().getX() - getClip_offset_x()); final double yCoord = getWtst().getSourceY(event.getPosition().getY() - getClip_offset_y()); final GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), CrsTransformer.extractSridFromCrs(getMappingModel().getSrs().getCode())); return gf.createPoint(new Coordinate(xCoord, yCoord)); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHandleLayer() { return handleLayer; } /** * DOCUMENT ME! * * @param handleLayer DOCUMENT ME! */ public void setHandleLayer(final PLayer handleLayer) { this.handleLayer = handleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingEnabled() { return visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingEnabled DOCUMENT ME! */ public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) { this.visualizeSnappingEnabled = visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingRectEnabled() { return visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingRectEnabled DOCUMENT ME! */ public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) { this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getSnappingRectSize() { return snappingRectSize; } /** * DOCUMENT ME! * * @param snappingRectSize DOCUMENT ME! */ public void setSnappingRectSize(final int snappingRectSize) { this.snappingRectSize = snappingRectSize; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getSnapHandleLayer() { return snapHandleLayer; } /** * DOCUMENT ME! * * @param snapHandleLayer DOCUMENT ME! */ public void setSnapHandleLayer(final PLayer snapHandleLayer) { this.snapHandleLayer = snapHandleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isSnappingEnabled() { return snappingEnabled; } /** * DOCUMENT ME! * * @param snappingEnabled DOCUMENT ME! */ public void setSnappingEnabled(final boolean snappingEnabled) { this.snappingEnabled = snappingEnabled; setVisualizeSnappingEnabled(snappingEnabled); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getFeatureServiceLayer() { return featureServiceLayer; } /** * DOCUMENT ME! * * @param featureServiceLayer DOCUMENT ME! */ public void setFeatureServiceLayer(final PLayer featureServiceLayer) { this.featureServiceLayer = featureServiceLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getAnimationDuration() { return animationDuration; } /** * DOCUMENT ME! * * @param animationDuration DOCUMENT ME! */ public void setAnimationDuration(final int animationDuration) { this.animationDuration = animationDuration; } /** * DOCUMENT ME! * * @param prefs DOCUMENT ME! */ @Deprecated public void setPreferences(final CismapPreferences prefs) { LOG.warn("involing deprecated operation setPreferences()"); // NOI18N cismapPrefs = prefs; final ActiveLayerModel mm = new ActiveLayerModel(); final LayersPreferences layersPrefs = prefs.getLayersPrefs(); final GlobalPreferences globalPrefs = prefs.getGlobalPrefs(); setSnappingRectSize(globalPrefs.getSnappingRectSize()); setSnappingEnabled(globalPrefs.isSnappingEnabled()); setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled()); setAnimationDuration(globalPrefs.getAnimationDuration()); setInteractionMode(globalPrefs.getStartMode()); mm.addHome(globalPrefs.getInitialBoundingBox()); final Crs crs = new Crs(); crs.setCode(globalPrefs.getInitialBoundingBox().getSrs()); crs.setName(globalPrefs.getInitialBoundingBox().getSrs()); crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs()); mm.setSrs(crs); final TreeMap raster = layersPrefs.getRasterServices(); if (raster != null) { final Iterator it = raster.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = raster.get(key); if (o instanceof MapService) { mm.addLayer((RetrievalServiceLayer)o); } } } final TreeMap features = layersPrefs.getFeatureServices(); if (features != null) { final Iterator it = features.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = features.get(key); if (o instanceof MapService) { // TODO mm.addLayer((RetrievalServiceLayer)o); } } } setMappingModel(mm); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public CismapPreferences getCismapPrefs() { return cismapPrefs; } /** * DOCUMENT ME! * * @param duration DOCUMENT ME! * @param animationDuration DOCUMENT ME! * @param what DOCUMENT ME! * @param number DOCUMENT ME! */ public void flash(final int duration, final int animationDuration, final int what, final int number) { } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getDragPerformanceImproverLayer() { return dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @param dragPerformanceImproverLayer DOCUMENT ME! */ public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) { this.dragPerformanceImproverLayer = dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public PLayer getRasterServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getMapServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @param rasterServiceLayer DOCUMENT ME! */ public void setRasterServiceLayer(final PLayer rasterServiceLayer) { this.mapServicelayer = rasterServiceLayer; } /** * DOCUMENT ME! * * @param f DOCUMENT ME! */ public void showGeometryInfoPanel(final Feature f) { } /** * Adds a PropertyChangeListener to the listener list. * * @param l The listener to add. */ @Override public void addPropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.addPropertyChangeListener(l); } /** * Removes a PropertyChangeListener from the listener list. * * @param l The listener to remove. */ @Override public void removePropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.removePropertyChangeListener(l); } /** * Setter for property taskCounter. former synchronized method */ public void fireActivityChanged() { propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N } /** * Returns true, if there's still one layercontrol running. Else false; former synchronized method * * @return DOCUMENT ME! */ public boolean isRunning() { for (final LayerControl lc : layerControls) { if (lc.isRunning()) { return true; } } return false; } /** * Sets the visibility of all infonodes. * * @param visible true, if infonodes should be visible */ public void setInfoNodesVisible(final boolean visible) { infoNodesVisible = visible; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object elem = it.next(); if (elem instanceof PFeature) { ((PFeature)elem).setInfoNodeVisible(visible); } } if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("setInfoNodesVisible()"); // NOI18N } } rescaleStickyNodes(); } /** * Adds an object to the historymodel. * * @param o Object to add */ @Override public void addToHistory(final Object o) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("addToHistory:" + o.toString()); // NOI18N } } historyModel.addToHistory(o); } /** * Removes a specific HistoryModelListener from the historymodel. * * @param hml HistoryModelListener */ @Override public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.removeHistoryModelListener(hml); } /** * Adds aHistoryModelListener to the historymodel. * * @param hml HistoryModelListener */ @Override public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.addHistoryModelListener(hml); } /** * Sets the maximum value of saved historyactions. * * @param max new integer value */ @Override public void setMaximumPossibilities(final int max) { historyModel.setMaximumPossibilities(max); } /** * Redos the last undone historyaction. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the forward-action */ @Override public Object forward(final boolean external) { final PBounds fwd = (PBounds)historyModel.forward(external); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("HistoryModel.forward():" + fwd); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(fwd); } return fwd; } /** * Undos the last action. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the back-action */ @Override public Object back(final boolean external) { final PBounds back = (PBounds)historyModel.back(external); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("HistoryModel.back():" + back); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(back); } return back; } /** * Returns true, if it's possible to redo an action. * * @return DOCUMENT ME! */ @Override public boolean isForwardPossible() { return historyModel.isForwardPossible(); } /** * Returns true, if it's possible to undo an action. * * @return DOCUMENT ME! */ @Override public boolean isBackPossible() { return historyModel.isBackPossible(); } /** * Returns a vector with all redo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getForwardPossibilities() { return historyModel.getForwardPossibilities(); } /** * Returns the current element of the historymodel. * * @return DOCUMENT ME! */ @Override public Object getCurrentElement() { return historyModel.getCurrentElement(); } /** * Returns a vector with all undo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getBackPossibilities() { return historyModel.getBackPossibilities(); } /** * Returns whether an internallayerwidget is available. * * @return DOCUMENT ME! */ @Deprecated public boolean isInternalLayerWidgetAvailable() { return this.getInternalWidget(LAYERWIDGET) != null; } /** * Sets the variable, if an internallayerwidget is available or not. * * @param internalLayerWidgetAvailable true, if available */ @Deprecated public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) { if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) { this.removeInternalWidget(LAYERWIDGET); } else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) { final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); } } /** * DOCUMENT ME! * * @param mme DOCUMENT ME! */ @Override public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) { } /** * Removes the mapservice from the rasterservicelayer. * * @param rasterService the removing mapservice */ @Override public void mapServiceRemoved(final MapService rasterService) { try { mapServicelayer.removeChild(rasterService.getPNode()); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_REMOVED, rasterService)); } System.gc(); } catch (final Exception e) { LOG.warn("Fehler bei mapServiceRemoved", e); // NOI18N } } /** * Adds the commited mapservice on the last position to the rasterservicelayer. * * @param mapService the new mapservice */ @Override public void mapServiceAdded(final MapService mapService) { addMapService(mapService, mapServicelayer.getChildrenCount()); if (mapService instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection()); } if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) { handleMapService(0, mapService, false); } } /** * Returns the current OGC scale. * * @return DOCUMENT ME! */ public double getCurrentOGCScale() { // funktioniert nur bei metrischen SRS's final double h = getCamera().getViewBounds().getHeight() / getHeight(); final double w = getCamera().getViewBounds().getWidth() / getWidth(); return Math.sqrt((h * h) + (w * w)); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public BoundingBox getCurrentBoundingBox() { return getCurrentBoundingBoxFromCamera(); } /** * <p>Returns the current BoundingBox.</p> * * @return DOCUMENT ME! */ public BoundingBox getCurrentBoundingBoxFromCamera() { if (fixedBoundingBox != null) { return fixedBoundingBox; } else { try { final PBounds bounds = getCamera().getViewBounds(); final double x1 = wtst.getWorldX(bounds.getX()); final double y1 = wtst.getWorldY(bounds.getY()); final double x2 = x1 + bounds.width; final double y2 = y1 - bounds.height; final Crs currentCrs = CismapBroker.getInstance().getSrs(); final boolean metric; // FIXME: this is a hack to overcome the "metric" issue for 4326 default srs if (CrsTransformer.getCurrentSrid() == 4326) { metric = false; } else { metric = currentCrs.isMetric(); } return new XBoundingBox(x1, y1, x2, y2, currentCrs.getCode(), metric); } catch (final Exception e) { LOG.error("cannot create bounding box from current view, return null", e); // NOI18N return null; } } } /** * Returns a BoundingBox with a fixed size. * * @return DOCUMENT ME! */ public BoundingBox getFixedBoundingBox() { return fixedBoundingBox; } /** * Assigns fixedBoundingBox a new value. * * @param fixedBoundingBox new boundingbox */ public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) { this.fixedBoundingBox = fixedBoundingBox; } /** * Paints the outline of the forwarded BoundingBox. * * @param bb BoundingBox */ public void outlineArea(final BoundingBox bb) { outlineArea(bb, null); } /** * Paints the outline of the forwarded PBounds. * * @param b PBounds */ public void outlineArea(final PBounds b) { outlineArea(b, null); } /** * Paints a filled rectangle of the area of the forwarded BoundingBox. * * @param bb BoundingBox * @param fillingPaint Color to fill the rectangle */ public void outlineArea(final BoundingBox bb, final Paint fillingPaint) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } outlineArea(pb, fillingPaint); } /** * Paints a filled rectangle of the area of the forwarded PBounds. * * @param b PBounds to paint * @param fillingColor Color to fill the rectangle */ public void outlineArea(final PBounds b, final Paint fillingColor) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { highlightingLayer.removeAllChildren(); } } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(fillingColor); rectangle.setStroke(new FixedWidthStroke()); rectangle.setStrokePaint(new Color(100, 100, 100, 255)); rectangle.setPathTo(b); highlightingLayer.addChild(rectangle); } } /** * Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally. * * @param bb BoundingBox to highlight */ public void highlightArea(final BoundingBox bb) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } highlightArea(pb); } /** * Highlights the delivered PBounds by painting over with a transparent white. * * @param b PBounds to hightlight */ private void highlightArea(final PBounds b) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { } highlightingLayer.animateToTransparency(0, animationDuration); highlightingLayer.removeAllChildren(); } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(new Color(255, 255, 255, 100)); rectangle.setStroke(null); rectangle.setPathTo(this.getCamera().getViewBounds()); highlightingLayer.addChild(rectangle); rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration); } } /** * Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls * crossHairPoint(Point p) internally. * * @param c coordinate of the crosshair's venue */ public void crossHairPoint(final Coordinate c) { Point p = null; if (c != null) { p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y)); } crossHairPoint(p); } /** * Paints a crosshair at the delivered point. * * @param p point of the crosshair's venue */ public void crossHairPoint(final Point p) { if (p == null) { if (crosshairLayer.getChildrenCount() > 0) { crosshairLayer.removeAllChildren(); } } else { crosshairLayer.removeAllChildren(); crosshairLayer.setTransparency(1); final PPath lineX = new PPath(); final PPath lineY = new PPath(); lineX.setStroke(new FixedWidthStroke()); lineX.setStrokePaint(new Color(100, 100, 100, 255)); lineY.setStroke(new FixedWidthStroke()); lineY.setStrokePaint(new Color(100, 100, 100, 255)); final PBounds current = getCamera().getViewBounds(); final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1); final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2); lineX.setPathTo(x); crosshairLayer.addChild(lineX); lineY.setPathTo(y); crosshairLayer.addChild(lineY); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public Element getConfiguration() { if (LOG.isDebugEnabled()) { LOG.debug("writing configuration <cismapMappingPreferences>"); // NOI18N } final Element ret = new Element("cismapMappingPreferences"); // NOI18N ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N ret.setAttribute( "creationMode", ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON); if (inputListener instanceof CreateSearchGeometryListener) { final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener; ret.setAttribute("createSearchMode", listener.getMode()); } // Position final Element currentPosition = new Element("Position"); // NOI18N currentPosition.addContent(getCurrentBoundingBoxFromCamera().getJDOMElement()); currentPosition.setAttribute("CRS", mappingModel.getSrs().getCode()); ret.addContent(currentPosition); // Crs final Element crsListElement = new Element("crsList"); for (final Crs tmp : crsList) { crsListElement.addContent(tmp.getJDOMElement()); } ret.addContent(crsListElement); if (printingSettingsDialog != null) { ret.addContent(printingSettingsDialog.getConfiguration()); } // save internal widgets status final Element widgets = new Element("InternalWidgets"); // NOI18N for (final String name : this.internalWidgets.keySet()) { final Element widget = new Element("Widget"); // NOI18N widget.setAttribute("name", name); // NOI18N widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N widgets.addContent(widget); } ret.addContent(widgets); return ret; } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void masterConfigure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N // CRS List try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N boolean defaultCrsFound = false; crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); crsList.add(s); if (s.isSelected() && s.isMetric()) { try { if (defaultCrsFound) { LOG.warn("More than one default CRS is set. " + "Please check your master configuration file."); // NOI18N } CismapBroker.getInstance().setDefaultCrs(s.getCode()); defaultCrsFound = true; transformer = new CrsTransformer(s.getCode()); } catch (final Exception ex) { LOG.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (final Exception skip) { LOG.error("Error while reading the crs list", skip); // NOI18N } if (CismapBroker.getInstance().getDefaultCrs() == null) { LOG.fatal("The default CRS is not set. This can lead to almost irreparable data errors. " + "Keep in mind: The default CRS must be metric"); // NOI18N } if (transformer == null) { LOG.error("No metric default crs found. Use EPSG:31466 as default crs"); // NOI18N try { transformer = new CrsTransformer("EPSG:31466"); // NOI18N CismapBroker.getInstance().setDefaultCrs("EPSG:31466"); // NOI18N } catch (final Exception ex) { LOG.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); // NOI18N } } // HOME try { if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N } } while (it.hasNext()) { final Element elem = it.next(); final String srs = elem.getAttribute("srs").getValue(); // NOI18N boolean metric = false; try { metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { LOG.warn("Metric hat falschen Syntax", dce); // NOI18N } boolean defaultVal = false; try { defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { LOG.warn("default hat falschen Syntax", dce); // NOI18N } final XBoundingBox xbox = new XBoundingBox(elem, srs, metric); alm.addHome(xbox); if (defaultVal) { Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(srs)) { crsObject = tmp; break; } } if (crsObject == null) { LOG.error("CRS " + srs + " from the default home is not found in the crs list"); crsObject = new Crs(srs, srs, srs, true, false); crsList.add(crsObject); } alm.setSrs(crsObject); alm.setDefaultHomeSrs(crsObject); CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } } } } catch (final Exception ex) { LOG.error("Fehler beim MasterConfigure der MappingComponent", ex); // NOI18N } try { final Element defaultCrs = prefs.getChild("defaultCrs"); final int defaultCrsInt = Integer.parseInt(defaultCrs.getAttributeValue("geometrySridAlias")); CismapBroker.getInstance().setDefaultCrsAlias(defaultCrsInt); } catch (final Exception ex) { LOG.error("Error while reading the default crs alias from the master configuration file.", ex); } try { final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N scales.clear(); for (final Object elem : scalesList) { if (elem instanceof Element) { final Scale s = new Scale((Element)elem); scales.add(s); } } } catch (final Exception skip) { LOG.error("Fehler beim Lesen von Scale", skip); // NOI18N } // Und jetzt noch die PriningEinstellungen initPrintingDialogs(); printingSettingsDialog.masterConfigure(prefs); } /** * Configurates this MappingComponent. * * @param e JDOM-Element with configuration */ @Override public void configure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); // the crs is equals to an other crs, if the code is equal. If a crs has in the // local configuration file an other name than in the master configuration file, // the old crs will be removed and the local one should be added to use the // local name and short name of the crs. if (crsList.contains(s)) { crsList.remove(s); } crsList.add(s); } } } catch (final Exception skip) { LOG.warn("Error while reading the crs list", skip); // NOI18N } // InteractionMode try { final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N setInteractionMode(interactMode); if (interactMode.equals(MappingComponent.NEW_POLYGON)) { try { final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode); } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des CreationInteractionMode", ex); // NOI18N } } } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des InteractionMode", ex); // NOI18N } try { final String createSearchMode = prefs.getAttribute("createSearchMode").getValue(); final Object inputListener = getInputListener(CREATE_SEARCH_POLYGON); if ((inputListener instanceof CreateSearchGeometryListener) && (createSearchMode != null)) { final CreateSearchGeometryListener listener = (CreateSearchGeometryListener)inputListener; listener.setMode(createSearchMode); } } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des CreateSearchMode", ex); // NOI18N } try { final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N setHandleInteractionMode(handleInterMode); } catch (final Exception ex) { LOG.warn("Fehler beim Setzen des HandleInteractionMode", ex); // NOI18N } try { final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N LOG.info("snapping=" + snapping); // NOI18N setSnappingEnabled(snapping); setVisualizeSnappingEnabled(snapping); setInGlueIdenticalPointsMode(snapping); } catch (final Exception ex) { LOG.warn("Fehler beim setzen von snapping und Konsorten", ex); // NOI18N } // aktuelle Position try { final Element pos = prefs.getChild("Position"); // NOI18N final BoundingBox b = new BoundingBox(pos); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("Position:" + b); // NOI18N } } final PBounds pb = b.getPBounds(getWtst()); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("PositionPb:" + pb); // NOI18N } } if (Double.isNaN(b.getX1()) || Double.isNaN(b.getX2()) || Double.isNaN(b.getY1()) || Double.isNaN(b.getY2())) { LOG.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); addToHistory(new PBoundsWithCleverToString( new PBounds(getMappingModel().getInitialBoundingBox().getPBounds(wtst)), wtst, crsCode)); } else { // set the current crs final Attribute crsAtt = pos.getAttribute("CRS"); if (crsAtt != null) { final String currentCrs = crsAtt.getValue(); Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(currentCrs)) { crsObject = tmp; break; } } if (crsObject == null) { LOG.error("CRS " + currentCrs + " from the position element is not found in the crs list"); } final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); if (alm instanceof ActiveLayerModel) { alm.setSrs(crsObject); } CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } this.initialBoundingBox = b; this.gotoBoundingBox(b, true, true, 0, false); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.fatal("added to History" + b); // NOI18N } } } } catch (final Exception ex) { LOG.warn("Fehler beim lesen der aktuellen Position", ex); // NOI18N this.gotoBoundingBox(getMappingModel().getInitialBoundingBox(), true, true, 0, false); } if (printingSettingsDialog != null) { printingSettingsDialog.configure(prefs); } try { final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N if (widgets != null) { for (final Object widget : widgets.getChildren()) { final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N this.showInternalWidget(name, visible, 0); } } } catch (final Exception ex) { LOG.warn("could not enable internal widgets: " + ex, ex); // NOI18N } } /** * Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent * will only pan to the featurecollection and not zoom. * * @param fixedScale true, if zoom is not allowed */ public void zoomToFeatureCollection(final boolean fixedScale) { zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale); } /** * Zooms to all features of the mappingcomponents featurecollection. */ public void zoomToFeatureCollection() { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("zoomToFeatureCollection"); // NOI18N } } zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration) { gotoBoundingBox(bb, history, scaleToFit, animationDuration, true); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation * @param queryServices true, if the services should be refreshed after animation */ public void gotoBoundingBox(BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration, final boolean queryServices) { if (bb != null) { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (final Exception e) { LOG.warn("Fehler bei removeAllCHildren", e); // NOI18N } if (bb instanceof XBoundingBox) { if (!((XBoundingBox)bb).getSrs().equals(mappingModel.getSrs().getCode())) { try { final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode()); bb = trans.transformBoundingBox((XBoundingBox)bb); } catch (final Exception e) { LOG.warn("Cannot transform the bounding box", e); } } } final double x1 = getWtst().getScreenX(bb.getX1()); final double y1 = getWtst().getScreenY(bb.getY1()); final double x2 = getWtst().getScreenX(bb.getX2()); final double y2 = getWtst().getScreenY(bb.getY2()); final double w; final double h; final Rectangle2D pos = new Rectangle2D.Double(); pos.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { LOG.warn("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } showHandles(true); final Runnable handle = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(10); } catch (final Exception e) { LOG.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (history) { if ((x1 == x2) || (y1 == y2) || !scaleToFit) { setNewViewBounds(getCamera().getViewBounds()); } else { setNewViewBounds(pos); } if (queryServices) { queryServices(); } } else { if (queryServices) { queryServicesWithoutHistory(); } } } }; CismetThreadPool.execute(handle); } else { LOG.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N } } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) { gotoBoundingBoxWithoutHistory(bb, animationDuration); } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox * @param animationDuration the animation duration */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb, final int animationDuration) { gotoBoundingBox(bb, false, true, animationDuration); } /** * Moves the view to the target Boundingbox and saves the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithHistory(final BoundingBox bb) { gotoBoundingBox(bb, true, true, animationDuration); } /** * Returns a BoundingBox of the current view in another scale. * * @param scaleDenominator specific target scale * * @return DOCUMENT ME! */ public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) { return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBoxFromCamera()); } /** * Returns the BoundingBox of the delivered BoundingBox in another scale. * * @param scaleDenominator specific target scale * @param bb source BoundingBox * * @return DOCUMENT ME! */ public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) { final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator; final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator; if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { // transform the given bounding box to a metric coordinate system bb = transformer.transformBoundingBox(bb, mappingModel.getSrs().getCode()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2); final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2); BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2), midY - (realWorldHeightInMeter / 2), midX + (realWorldWidthInMeter / 2), midY + (realWorldHeightInMeter / 2)); if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { // transform the scaled bounding box to the current coordinate system final CrsTransformer trans = new CrsTransformer(mappingModel.getSrs().getCode()); scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } return scaledBox; } /** * Calculate the current scaledenominator. * * @return DOCUMENT ME! */ public double getScaleDenominator() { BoundingBox boundingBox = getCurrentBoundingBoxFromCamera(); final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; if (!mappingModel.getSrs().isMetric() && (transformer != null)) { try { boundingBox = transformer.transformBoundingBox( boundingBox, mappingModel.getSrs().getCode()); } catch (final Exception e) { LOG.error("Cannot transform the current bounding box.", e); } } final double realWorldWidthInMeter = boundingBox.getWidth(); return realWorldWidthInMeter / screenWidthInMeter; } /** * Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code> * DropTarget</code> registered with this listener. * * <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code> * DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data * object(s) to be transfered.</p> * * <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int * dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P> * * <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be * invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData() * method.</P> * * <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the * drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method.</P> * * <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code> * Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only * if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code> * true</code>. Otherwise, the behavior of the call is implementation-dependent.</P> * * @param dtde the <code>DropTargetDropEvent</code> */ @Override public void drop(final DropTargetDropEvent dtde) { if (isDropEnabled(dtde)) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDropOnMap(mde); } catch (final Exception ex) { LOG.error("Error in drop", ex); // NOI18N } } } /** * DOCUMENT ME! * * @param dtde DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean isDropEnabled(final DropTargetDropEvent dtde) { if (ALKIS_PRINT.equals(getInteractionMode())) { for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) { // necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) { return false; } } } return true; } /** * Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site * for the <code>DropTarget</code> registered with this listener. * * @param dte the <code>DropTargetEvent</code> */ @Override public void dragExit(final DropTargetEvent dte) { } /** * Called if the user has modified the current drop gesture. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dropActionChanged(final DropTargetDragEvent dtde) { } /** * Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p * site for the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragOver(final DropTargetDragEvent dtde) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); // TODO: this seems to be buggy! final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDragOverMap(mde); } catch (final Exception ex) { LOG.error("Error in dragOver", ex); // NOI18N } } /** * Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for * the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragEnter(final DropTargetDragEvent dtde) { } /** * Returns the PfeatureHashmap which assigns a Feature to a PFeature. * * @return DOCUMENT ME! */ public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() { return pFeatureHM; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapExtent() { return fixedMapExtent; } /** * DOCUMENT ME! * * @param fixedMapExtent DOCUMENT ME! */ public void setFixedMapExtent(final boolean fixedMapExtent) { this.fixedMapExtent = fixedMapExtent; if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent( StatusEvent.MAP_EXTEND_FIXED, this.fixedMapExtent)); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapScale() { return fixedMapScale; } /** * DOCUMENT ME! * * @param fixedMapScale DOCUMENT ME! */ public void setFixedMapScale(final boolean fixedMapScale) { this.fixedMapScale = fixedMapScale; if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent( StatusEvent.MAP_SCALE_FIXED, this.fixedMapScale)); } } /** * DOCUMENT ME! * * @param one DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public void selectPFeatureManually(final PFeature one) { if (one != null) { featureCollection.select(one.getFeature()); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public PFeature getSelectedNode() { // gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist // deshalb gebe ich mal nur das erste zur�ck if (featureCollection.getSelectedFeatures().size() > 0) { final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0]; if (selF == null) { return null; } return pFeatureHM.get(selF); } else { return null; } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInfoNodesVisible() { return infoNodesVisible; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getPrintingFrameLayer() { return printingFrameLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PrintingSettingsWidget getPrintingSettingsDialog() { return printingSettingsDialog; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInGlueIdenticalPointsMode() { return inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @param inGlueIdenticalPointsMode DOCUMENT ME! */ public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) { this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHighlightingLayer() { return highlightingLayer; } /** * DOCUMENT ME! * * @param anno DOCUMENT ME! */ public void setPointerAnnotation(final PNode anno) { ((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno); } /** * DOCUMENT ME! * * @param visib DOCUMENT ME! */ public void setPointerAnnotationVisibility(final boolean visib) { if (getInputListener(MOTION) != null) { ((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib); } } /** * Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't * equal MOTION. * * @return DOCUMENT ME! */ public boolean isPointerAnnotationVisible() { if (getInputListener(MOTION) != null) { return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible(); } else { return false; } } /** * Returns a vector with different scales. * * @return DOCUMENT ME! */ public List<Scale> getScales() { return scales; } /** * Returns a list with different crs. * * @return DOCUMENT ME! */ public List<Crs> getCrsList() { return crsList; } /** * DOCUMENT ME! * * @return a transformer with the default crs as destination crs. The default crs is the first crs in the * configuration file that has set the selected attribut on true). This crs must be metric. */ public CrsTransformer getMetricTransformer() { return transformer; } /** * Locks the MappingComponent. */ public void lock() { locked = true; } /** * Unlocks the MappingComponent. */ public void unlock() { if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug("unlock"); // NOI18N } } locked = false; // if (DEBUG) { // if (LOG.isDebugEnabled()) { // LOG.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N // } // } gotoBoundingBoxWithHistory(getInitialBoundingBox()); } /** * Returns whether the MappingComponent is locked or not. * * @return DOCUMENT ME! */ public boolean isLocked() { return locked; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isMainMappingComponent() { return mainMappingComponent; } /** * Returns the MementoInterface for redo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemRedo() { return memRedo; } /** * Returns the MementoInterface for undo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemUndo() { return memUndo; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Map<String, PBasicInputEventHandler> getInputEventListener() { return inputEventListener; } /** * DOCUMENT ME! * * @param inputEventListener DOCUMENT ME! */ public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) { this.inputEventListener.clear(); this.inputEventListener.putAll(inputEventListener); } /** * DOCUMENT ME! * * @param event DOCUMENT ME! */ @Override public synchronized void crsChanged(final CrsChangedEvent event) { if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) { if (locked) { return; } final WaitDialog dialog = new WaitDialog(StaticSwingTools.getParentFrame(MappingComponent.this), false, NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).wait"), null); EventQueue.invokeLater(new Runnable() { @Override public void run() { try { StaticSwingTools.showDialog(dialog); // the wtst object should not be null, so the getWtst method will be invoked final WorldToScreenTransform oldWtst = getWtst(); final BoundingBox bbox = getCurrentBoundingBoxFromCamera(); // getCurrentBoundingBox(); final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode()); final BoundingBox newBbox = crsTransformer.transformBoundingBox( bbox, event.getFormerCrs().getCode()); if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); } wtst = null; getWtst(); gotoBoundingBoxWithoutHistory(newBbox, 0); final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures()); featureCollection.removeAllFeatures(); featureCollection.addFeatures(list); if (LOG.isDebugEnabled()) { LOG.debug("debug features added: " + list.size()); } // refresh all wfs layer if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.refreshWebFeatureServices(); alm.refreshShapeFileLayer(); } // transform the highlighting layer for (int i = 0; i < highlightingLayer.getChildrenCount(); ++i) { final PNode node = highlightingLayer.getChild(i); CrsTransformer.transformPNodeToGivenCrs( node, event.getFormerCrs().getCode(), event.getCurrentCrs().getCode(), oldWtst, getWtst()); rescaleStickyNode(node); } } catch (final Exception e) { JOptionPane.showMessageDialog( StaticSwingTools.getParentFrame(MappingComponent.this), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"), JOptionPane.ERROR_MESSAGE); LOG.error( "Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e); resetCrs = true; final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); CismapBroker.getInstance().setSrs(event.getFormerCrs()); } finally { if (dialog != null) { dialog.setVisible(false); } } } }); } else { resetCrs = false; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public JInternalFrame getInternalWidget(final String name) { if (this.internalWidgets.containsKey(name)) { return this.internalWidgets.get(name); } else { LOG.warn("unknown internal widget '" + name + "'"); // NOI18N return null; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public int getInternalWidgetPosition(final String name) { if (this.internalWidgetPositions.containsKey(name)) { return this.internalWidgetPositions.get(name); } else { LOG.warn("unknown position for '" + name + "'"); // NOI18N return -1; } } //~ Inner Classes ---------------------------------------------------------- /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class MappingComponentRasterServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); private final transient ServiceLayer rasterService; private final XPImage pi; private int position = -1; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentRasterServiceListener object. * * @param position DOCUMENT ME! * @param pn DOCUMENT ME! * @param rasterService DOCUMENT ME! */ public MappingComponentRasterServiceListener(final int position, final PNode pn, final ServiceLayer rasterService) { this.position = position; this.rasterService = rasterService; if (pn instanceof XPImage) { this.pi = (XPImage)pn; } else { this.pi = null; } } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { fireActivityChanged(); if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { this.log.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() // NOI18N + " Errors: " // NOI18N + e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N fireActivityChanged(); if (DEBUG) { if (LOG.isDebugEnabled()) { LOG.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { final Point2D localOrigin = getCamera().getViewBounds().getOrigin(); final double localScale = getCamera().getViewScale(); final PBounds localBounds = getCamera().getViewBounds(); final Object o = e.getRetrievedObject(); if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } final Runnable paintImageOnMap = new Runnable() { @Override public void run() { fireActivityChanged(); if ((o instanceof Image) && (e.isHasErrors() == false)) { // TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden if (isBackgroundEnabled()) { final Image i = (Image)o; if (rasterService.getName().startsWith("prefetching")) { // NOI18N final double x = localOrigin.getX() - localBounds.getWidth(); final double y = localOrigin.getY() - localBounds.getHeight(); pi.setImage(i, 0); pi.setScale(3 / localScale); pi.setOffset(x, y); } else { pi.setImage(i, animationDuration * 2); pi.setScale(1 / localScale); pi.setOffset(localOrigin); MappingComponent.this.repaint(); } } } } }; if (EventQueue.isDispatchThread()) { paintImageOnMap.run(); } else { EventQueue.invokeLater(paintImageOnMap); } if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, rasterService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { this.log.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, rasterService)); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getPosition() { return position; } /** * DOCUMENT ME! * * @param position DOCUMENT ME! */ public void setPosition(final int position) { this.position = position; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class DocumentProgressListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); /** Displays the loading progress of Documents, e.g. SHP Files */ private final transient DocumentProgressWidget documentProgressWidget; private transient long requestId = -1; //~ Constructors ------------------------------------------------------- /** * Creates a new DocumentProgressListener object. */ public DocumentProgressListener() { documentProgressWidget = new DocumentProgressWidget(); documentProgressWidget.setVisible(false); if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) { MappingComponent.this.addInternalWidget( MappingComponent.PROGRESSWIDGET, MappingComponent.POSITION_SOUTHWEST, documentProgressWidget); } } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != -1) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = e.getRequestIdentifier(); this.documentProgressWidget.setServiceName(e.getRetrievalService().toString()); this.documentProgressWidget.setProgress(-1); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N } if (DEBUG) { if (log.isDebugEnabled()) { log.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: initialisation progress: " + e.getPercentageDone()); // NOI18N } } this.documentProgressWidget.setProgress(e.getPercentageDone()); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N } e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(100); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { log.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; e.getRetrievalService().removeRetrievalListener(this); this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public long getRequestId() { return this.requestId; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class MappingComponentFeatureServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private final transient Logger log = Logger.getLogger(this.getClass()); private final transient ServiceLayer featureService; private final transient PLayer parent; private long requestIdentifier; private Thread completionThread; private final List deletionCandidates; private final List twins; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentFeatureServiceListener. * * @param featureService the featureretrievalservice * @param parent the featurelayer (PNode) connected with the servicelayer */ public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) { this.featureService = featureService; this.parent = parent; this.deletionCandidates = new ArrayList(); this.twins = new ArrayList(); } //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { requestIdentifier = e.getRequestIdentifier(); } if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N } } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_STARTED, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalProgress(final RetrievalEvent e) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: " + e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress() + ")"); // NOI18N } } fireActivityChanged(); // TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das // flüssiger ist } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalError(final RetrievalEvent e) { this.log.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ERROR, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalComplete(final RetrievalEvent e) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N } } if (e.isInitialisationEvent()) { this.log.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: initialisation complete"); // NOI18N fireActivityChanged(); return; } if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N } ((RetrievalServiceLayer)featureService).setProgress(-1); fireActivityChanged(); return; } final List newFeatures = new ArrayList(); EventQueue.invokeLater(new Runnable() { @Override public void run() { ((RetrievalServiceLayer)featureService).setProgress(-1); parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible()); } }); // clear all old data to delete twins deletionCandidates.clear(); twins.clear(); // if it's a refresh, add all old features which should be deleted in the // newly acquired featurecollection if (!e.isRefreshExisting()) { deletionCandidates.addAll(parent.getChildrenReference()); } if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N } } // only start parsing the features if there are no errors and a correct collection if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) { completionThread = new Thread() { @Override public void run() { // this is the collection with the retrieved features final List features = new ArrayList((Collection)e.getRetrievedObject()); final int size = features.size(); int counter = 0; final Iterator it = features.iterator(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N } } while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted() && it.hasNext()) { counter++; final Object o = it.next(); if (o instanceof Feature) { final PFeature p = new PFeature(((Feature)o), wtst, clip_offset_x, clip_offset_y, MappingComponent.this); PFeature twin = null; for (final Object tester : deletionCandidates) { // if tester and PFeature are FeatureWithId-objects if ((((PFeature)tester).getFeature() instanceof FeatureWithId) && (p.getFeature() instanceof FeatureWithId)) { final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId(); final int id2 = ((FeatureWithId)(p.getFeature())).getId(); if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id if (id1 == id2) { twin = ((PFeature)tester); break; } } else { // else test the geometry for equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } else { // no FeatureWithId, test geometries for // equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } // if a twin is found remove him from the deletion candidates // and add him to the twins if (twin != null) { deletionCandidates.remove(twin); twins.add(twin); } else { // else add the PFeature to the new features newFeatures.add(p); } // calculate the advance of the progressbar // fire event only wheen needed final int currentProgress = (int)((double)counter / (double)size * 100d); if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) { ((RetrievalServiceLayer)featureService).setProgress(currentProgress); fireActivityChanged(); } } } if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) { // after all features are computed do stuff on the EDT EventQueue.invokeLater(new Runnable() { @Override public void run() { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N } } // if it's a refresh, delete all previous features if (e.isRefreshExisting()) { parent.removeAllChildren(); } final List deleteFeatures = new ArrayList(); for (final Object o : newFeatures) { parent.addChild((PNode)o); } // set the prograssbar to full if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: set progress to 100"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(100); fireActivityChanged(); // repaint the featurelayer parent.repaint(); // remove stickyNode from all deletionCandidates and add // each to the new deletefeature-collection for (final Object o : deletionCandidates) { if (o instanceof PFeature) { final PNode p = ((PFeature)o).getPrimaryAnnotationNode(); if (p != null) { removeStickyNode(p); } deleteFeatures.add(o); } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount before:" + parent.getChildrenCount()); // NOI18N } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: deleteFeatures=" + deleteFeatures.size()); // + " :" + // deleteFeatures);//NOI18N } } parent.removeChildren(deleteFeatures); if (DEBUG) { if (log.isDebugEnabled()) { log.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount after:" + parent.getChildrenCount()); // NOI18N } } if (LOG.isInfoEnabled()) { LOG.info( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + parent.getChildrenCount() + " features retrieved or updated"); // NOI18N } rescaleStickyNodes(); } catch (final Exception exception) { log.warn( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Fehler beim Aufr\u00E4umen", exception); // NOI18N } } }); } else { if (DEBUG) { if (log.isDebugEnabled()) { log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } }; completionThread.setPriority(Thread.NORM_PRIORITY); if (requestIdentifier == e.getRequestIdentifier()) { completionThread.start(); } else { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_COMPLETED, featureService)); } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void retrievalAborted(final RetrievalEvent e) { this.log.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: aborted, TaskCounter:" + taskCounter); // NOI18N if (completionThread != null) { completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(-1); } else { if (DEBUG) { if (this.log.isDebugEnabled()) { this.log.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(0); } fireActivityChanged(); if (mainMappingComponent) { CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.RETRIEVAL_ABORTED, featureService)); } } } }
diff --git a/src/uk/ac/nott/mrl/homework/client/ui/DeviceMetadataDialog.java b/src/uk/ac/nott/mrl/homework/client/ui/DeviceMetadataDialog.java index 5a8d369..7cb8c0c 100644 --- a/src/uk/ac/nott/mrl/homework/client/ui/DeviceMetadataDialog.java +++ b/src/uk/ac/nott/mrl/homework/client/ui/DeviceMetadataDialog.java @@ -1,117 +1,117 @@ package uk.ac.nott.mrl.homework.client.ui; import uk.ac.nott.mrl.homework.client.DevicesService; import uk.ac.nott.mrl.homework.client.model.Item; import uk.ac.nott.mrl.homework.client.model.Metadata; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; public abstract class DeviceMetadataDialog extends Composite { private static Metadata metadata = null; private static DeviceMetadataDialogUiBinder uiBinder = GWT .create(DeviceMetadataDialogUiBinder.class); interface DeviceMetadataDialogUiBinder extends UiBinder<Widget, DeviceMetadataDialog> { } @UiField TextBox nameBox; @UiField ListBox typeList; @UiField ListBox ownerList; public DeviceMetadataDialog(Item item, DevicesService service) { initWidget(uiBinder.createAndBindUi(this)); - nameBox.setName(item.getName()); + nameBox.setText(item.getName()); typeList.setVisibleItemCount(1); ownerList.setVisibleItemCount(1); setMetadata(metadata); service.getMetadata(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { try { setMetadata(Metadata.parse(response.getText())); } catch(Exception e) { } } @Override public void onError(Request request, Throwable exception) { } }); } @UiHandler("acceptButton") void accept(ClickEvent event) { accept(); } @UiHandler("cancelButton") void cancel(ClickEvent event) { cancel(); } protected abstract void cancel(); protected abstract void accept(); protected String getName() { return nameBox.getText(); } protected String getOwner() { return ownerList.getItemText(ownerList.getSelectedIndex()); } protected String getType() { return typeList.getItemText(typeList.getSelectedIndex()); } private void setMetadata(Metadata newMetadata) { metadata = newMetadata; if(metadata != null) { typeList.clear(); for(int index = 0; index < metadata.getTypes().length(); index++) { typeList.addItem(metadata.getTypes().get(index)); } ownerList.clear(); for(int index = 0; index < metadata.getOwners().length(); index++) { ownerList.addItem(metadata.getOwners().get(index)); } } } }
true
true
public DeviceMetadataDialog(Item item, DevicesService service) { initWidget(uiBinder.createAndBindUi(this)); nameBox.setName(item.getName()); typeList.setVisibleItemCount(1); ownerList.setVisibleItemCount(1); setMetadata(metadata); service.getMetadata(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { try { setMetadata(Metadata.parse(response.getText())); } catch(Exception e) { } } @Override public void onError(Request request, Throwable exception) { } }); }
public DeviceMetadataDialog(Item item, DevicesService service) { initWidget(uiBinder.createAndBindUi(this)); nameBox.setText(item.getName()); typeList.setVisibleItemCount(1); ownerList.setVisibleItemCount(1); setMetadata(metadata); service.getMetadata(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { try { setMetadata(Metadata.parse(response.getText())); } catch(Exception e) { } } @Override public void onError(Request request, Throwable exception) { } }); }
diff --git a/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java b/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java index cfc91ac6..94aa00ed 100644 --- a/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java +++ b/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java @@ -1,137 +1,137 @@ /** * $Revision: 22540 $ * $Date: 2005-10-10 08:44:25 -0700 (Mon, 10 Oct 2005) $ * * Copyright (C) 1999-2005 Jive Software. All rights reserved. * * This software is the proprietary information of Jive Software. * Use is subject to license terms. */ package com.jivesoftware.spark.plugin.apple; import com.apple.eawt.Application; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import javax.swing.*; import java.awt.*; import org.jivesoftware.spark.plugin.Plugin; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.ui.ChatRoomListener; import org.jivesoftware.MainWindow; import org.jivesoftware.Spark; /** * Plugins for handling Mac OS X specific functionality * * @author Andrew Wright */ public class ApplePlugin implements Plugin { private ChatRoomListener roomListener; public void initialize() { if (Spark.isMac()) { roomListener = new DockRoomListener(); SparkManager.getChatManager().addChatRoomListener(roomListener); // Remove the About Menu Item from the help menu MainWindow mainWindow = SparkManager.getMainWindow(); JMenu helpMenu = mainWindow.getMenuByName("Help"); Component[] menuComponents = helpMenu.getMenuComponents(); Component prev = null; for (int i = 0; i < menuComponents.length; i++) { Component current = menuComponents[i]; if (current instanceof JMenuItem) { JMenuItem item = (JMenuItem) current; if ("About".equals(item.getText())) { helpMenu.remove(item); // We want to remove the seperator if (prev != null && (prev instanceof JSeparator)) { helpMenu.remove(prev); } } } prev = current; } JMenu connectMenu = mainWindow.getMenuByName("Spark"); connectMenu.setText("Connect"); menuComponents = connectMenu.getMenuComponents(); JSeparator lastSeperator = null; for (int i = 0; i < menuComponents.length; i++) { Component current = menuComponents[i]; if (current instanceof JMenuItem) { JMenuItem item = (JMenuItem) current; if ("Preferences".equals(item.getText())) { - connectMenu.remove(item); + //connectMenu.remove(item); } else if ("Log Out".equals(item.getText())) { connectMenu.remove(item); } } else if (current instanceof JSeparator) { lastSeperator = (JSeparator) current; } } if (lastSeperator != null) { connectMenu.remove(lastSeperator); } // register an application listener to show the about box Application application = Application.getApplication(); - application.setEnabledPreferencesMenu(true); - application.addPreferencesMenuItem(); + // application.setEnabledPreferencesMenu(true); + // application.addPreferencesMenuItem(); application.addApplicationListener(new ApplicationAdapter() { public void handlePreferences(ApplicationEvent applicationEvent) { SparkManager.getPreferenceManager().showPreferences(); } public void handleReOpenApplication(ApplicationEvent event) { MainWindow mainWindow = SparkManager.getMainWindow(); if (!mainWindow.isVisible()) { mainWindow.setState(Frame.NORMAL); mainWindow.setVisible(true); } } public void handleQuit(ApplicationEvent applicationEvent) { System.exit(0); } }); new AppleStatusMenu().display(); } } public void shutdown() { if (Spark.isMac()) { SparkManager.getChatManager().removeChatRoomListener(roomListener); roomListener = null; } } public boolean canShutDown() { return false; } public void uninstall() { // No need, since this is internal } }
false
true
public void initialize() { if (Spark.isMac()) { roomListener = new DockRoomListener(); SparkManager.getChatManager().addChatRoomListener(roomListener); // Remove the About Menu Item from the help menu MainWindow mainWindow = SparkManager.getMainWindow(); JMenu helpMenu = mainWindow.getMenuByName("Help"); Component[] menuComponents = helpMenu.getMenuComponents(); Component prev = null; for (int i = 0; i < menuComponents.length; i++) { Component current = menuComponents[i]; if (current instanceof JMenuItem) { JMenuItem item = (JMenuItem) current; if ("About".equals(item.getText())) { helpMenu.remove(item); // We want to remove the seperator if (prev != null && (prev instanceof JSeparator)) { helpMenu.remove(prev); } } } prev = current; } JMenu connectMenu = mainWindow.getMenuByName("Spark"); connectMenu.setText("Connect"); menuComponents = connectMenu.getMenuComponents(); JSeparator lastSeperator = null; for (int i = 0; i < menuComponents.length; i++) { Component current = menuComponents[i]; if (current instanceof JMenuItem) { JMenuItem item = (JMenuItem) current; if ("Preferences".equals(item.getText())) { connectMenu.remove(item); } else if ("Log Out".equals(item.getText())) { connectMenu.remove(item); } } else if (current instanceof JSeparator) { lastSeperator = (JSeparator) current; } } if (lastSeperator != null) { connectMenu.remove(lastSeperator); } // register an application listener to show the about box Application application = Application.getApplication(); application.setEnabledPreferencesMenu(true); application.addPreferencesMenuItem(); application.addApplicationListener(new ApplicationAdapter() { public void handlePreferences(ApplicationEvent applicationEvent) { SparkManager.getPreferenceManager().showPreferences(); } public void handleReOpenApplication(ApplicationEvent event) { MainWindow mainWindow = SparkManager.getMainWindow(); if (!mainWindow.isVisible()) { mainWindow.setState(Frame.NORMAL); mainWindow.setVisible(true); } } public void handleQuit(ApplicationEvent applicationEvent) { System.exit(0); } }); new AppleStatusMenu().display(); } }
public void initialize() { if (Spark.isMac()) { roomListener = new DockRoomListener(); SparkManager.getChatManager().addChatRoomListener(roomListener); // Remove the About Menu Item from the help menu MainWindow mainWindow = SparkManager.getMainWindow(); JMenu helpMenu = mainWindow.getMenuByName("Help"); Component[] menuComponents = helpMenu.getMenuComponents(); Component prev = null; for (int i = 0; i < menuComponents.length; i++) { Component current = menuComponents[i]; if (current instanceof JMenuItem) { JMenuItem item = (JMenuItem) current; if ("About".equals(item.getText())) { helpMenu.remove(item); // We want to remove the seperator if (prev != null && (prev instanceof JSeparator)) { helpMenu.remove(prev); } } } prev = current; } JMenu connectMenu = mainWindow.getMenuByName("Spark"); connectMenu.setText("Connect"); menuComponents = connectMenu.getMenuComponents(); JSeparator lastSeperator = null; for (int i = 0; i < menuComponents.length; i++) { Component current = menuComponents[i]; if (current instanceof JMenuItem) { JMenuItem item = (JMenuItem) current; if ("Preferences".equals(item.getText())) { //connectMenu.remove(item); } else if ("Log Out".equals(item.getText())) { connectMenu.remove(item); } } else if (current instanceof JSeparator) { lastSeperator = (JSeparator) current; } } if (lastSeperator != null) { connectMenu.remove(lastSeperator); } // register an application listener to show the about box Application application = Application.getApplication(); // application.setEnabledPreferencesMenu(true); // application.addPreferencesMenuItem(); application.addApplicationListener(new ApplicationAdapter() { public void handlePreferences(ApplicationEvent applicationEvent) { SparkManager.getPreferenceManager().showPreferences(); } public void handleReOpenApplication(ApplicationEvent event) { MainWindow mainWindow = SparkManager.getMainWindow(); if (!mainWindow.isVisible()) { mainWindow.setState(Frame.NORMAL); mainWindow.setVisible(true); } } public void handleQuit(ApplicationEvent applicationEvent) { System.exit(0); } }); new AppleStatusMenu().display(); } }
diff --git a/src/com/semaphore/smproperties/SMOndemandN4Property.java b/src/com/semaphore/smproperties/SMOndemandN4Property.java index 8a192e0..ab82fed 100644 --- a/src/com/semaphore/smproperties/SMOndemandN4Property.java +++ b/src/com/semaphore/smproperties/SMOndemandN4Property.java @@ -1,59 +1,59 @@ /* Semaphore Manager * * Copyright (c) 2012 - 2013 Stratos Karafotis ([email protected]) * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ package com.semaphore.smproperties; import java.util.List; public class SMOndemandN4Property extends SMOndemandProperty { public SMIntProperty touch_load; public SMIntProperty touch_load_threshold; public SMIntProperty touch_load_duration; public SMOndemandN4Property() { super(); io_is_busy.setDefault(1); sampling_down_factor.setDefault(4); sampling_down_factor.setDynamic(false); sampling_rate.setDefault(20000); sampling_rate.setValue(20000); up_threshold.setDefault(95); up_threshold.setValue(95); - touch_load = new SMIntProperty("o_touch_load", basepath.concat("touch_load"), false, 0, 100, 65); - touch_load_threshold = new SMIntProperty("o_touch_load_threshold", basepath.concat("touch_load_threshold"), false, 0, 100, 12); - touch_load_duration = new SMIntProperty("o_touch_load_duration", basepath.concat("touch_load_duration"), false, 1, 10000, 1300); + touch_load = new SMIntProperty("o_touch_load", basepath.concat("touch_load"), false, 0, 100, 75); + touch_load_threshold = new SMIntProperty("o_touch_load_threshold", basepath.concat("touch_load_threshold"), false, 0, 100, 10); + touch_load_duration = new SMIntProperty("o_touch_load_duration", basepath.concat("touch_load_duration"), false, 1, 10000, 1100); } @Override public void readValue() { super.readValue(); touch_load.readValue(); touch_load_threshold.readValue(); touch_load_duration.readValue(); } @Override public void writeValue() { super.writeValue(); touch_load.writeValue(); touch_load_threshold.writeValue(); touch_load_duration.writeValue(); } @Override public void writeBatch(List<String> cmds) { super.writeBatch(cmds); touch_load.writeBatch(cmds); touch_load_threshold.writeBatch(cmds); touch_load_duration.writeBatch(cmds); } }
true
true
public SMOndemandN4Property() { super(); io_is_busy.setDefault(1); sampling_down_factor.setDefault(4); sampling_down_factor.setDynamic(false); sampling_rate.setDefault(20000); sampling_rate.setValue(20000); up_threshold.setDefault(95); up_threshold.setValue(95); touch_load = new SMIntProperty("o_touch_load", basepath.concat("touch_load"), false, 0, 100, 65); touch_load_threshold = new SMIntProperty("o_touch_load_threshold", basepath.concat("touch_load_threshold"), false, 0, 100, 12); touch_load_duration = new SMIntProperty("o_touch_load_duration", basepath.concat("touch_load_duration"), false, 1, 10000, 1300); }
public SMOndemandN4Property() { super(); io_is_busy.setDefault(1); sampling_down_factor.setDefault(4); sampling_down_factor.setDynamic(false); sampling_rate.setDefault(20000); sampling_rate.setValue(20000); up_threshold.setDefault(95); up_threshold.setValue(95); touch_load = new SMIntProperty("o_touch_load", basepath.concat("touch_load"), false, 0, 100, 75); touch_load_threshold = new SMIntProperty("o_touch_load_threshold", basepath.concat("touch_load_threshold"), false, 0, 100, 10); touch_load_duration = new SMIntProperty("o_touch_load_duration", basepath.concat("touch_load_duration"), false, 1, 10000, 1100); }
diff --git a/GlassLine/src/engine/JaniceCF/agent/ConveyorAgent.java b/GlassLine/src/engine/JaniceCF/agent/ConveyorAgent.java index 9870a7b..abfa405 100644 --- a/GlassLine/src/engine/JaniceCF/agent/ConveyorAgent.java +++ b/GlassLine/src/engine/JaniceCF/agent/ConveyorAgent.java @@ -1,208 +1,209 @@ package engine.JaniceCF.agent; import java.util.*; import java.util.concurrent.Semaphore; import transducer.TChannel; import transducer.TEvent; import transducer.Transducer; import engine.JaniceCF.interfaces.*; import engine.agent.Agent; import engine.agent.shared.*; import engine.agent.shared.Interfaces.*; import engine.ryanCF.interfaces.Bin; public class ConveyorAgent extends Agent implements Conveyor { enum ConveyorStatus {Nothing, GlassAtEnd} TChannel channel; ConveyorStatus status; int conveyorIndex; Machine machine; Bin bin; ConveyorFamily previousCF; Machine previousMachine; Boolean nextFree; Boolean loading = false; boolean started =false; List<Glass> glassList = Collections.synchronizedList(new ArrayList<Glass>()); public ConveyorAgent(String name, Transducer transducer, int index, TChannel channel) { super(name, transducer); conveyorIndex = index; machine = null; bin = null; previousCF = null; previousMachine = null; nextFree = true; this.channel = channel; transducer.register(this, TChannel.SENSOR); transducer.register(this, TChannel.CONVEYOR); transducer.register(this, channel); } //Messages @Override public void msgSpaceAvailable() { if (nextFree == true) { System.err.println(name + ": nextFree should not be true."); } nextFree = true; stateChanged(); } @Override public void msgHereIsGlass(Glass g) { synchronized (glassList) { glassList.add(g); } stateChanged(); } //Scheduler @Override public boolean pickAndExecuteAnAction() { // TODO Auto-generated method stub if(loading==false&&nextFree==true&&status==ConveyorStatus.Nothing&&!started) startConveyor(); if (status == ConveyorStatus.GlassAtEnd) { if (nextFree == true) { passToMachine(); return true; } } return false; } @Override public void eventFired(TChannel channel, TEvent event, Object[] args) { //Sensors if (channel == TChannel.SENSOR) { if (event == TEvent.SENSOR_GUI_PRESSED) { if (args[0].equals(conveyorIndex*2)) { //Front Sensor if (status != ConveyorStatus.GlassAtEnd) { Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; started=true; transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_START, newArgs); stateChanged(); return; } } else if (args[0].equals((conveyorIndex * 2) + 1)) { //End Sensor status = ConveyorStatus.GlassAtEnd; Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; if(!loading) { transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, newArgs); started=false; } stateChanged(); return; } } else if (event == TEvent.SENSOR_GUI_RELEASED) { if (args[0].equals(conveyorIndex*2)) { //Front sensor if (previousCF != null) { previousCF.msgSpaceAvailable(); stateChanged(); return; } else if (bin != null) { bin.msgSpaceAvailable(); stateChanged(); return; } else if (previousMachine != null) { previousMachine.msgSpaceAvailable(); stateChanged(); return; } } else if (args[0].equals((conveyorIndex*2) + 1)) { //end sensor status = ConveyorStatus.Nothing; stateChanged(); return; } } } //Workstation if (channel == this.channel) { if (event == TEvent.WORKSTATION_LOAD_FINISHED) { Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; loading = false; - transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, newArgs ); + if(status==ConveyorStatus.GlassAtEnd) + transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, newArgs ); started=false; return; } } } //Actions private void passToMachine() { nextFree = false; Glass g = glassList.get(0); synchronized (glassList) { glassList.remove(0); } machine.msgHereIsGlass(g); Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer)conveyorIndex; started=true; transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_START, newArgs); loading =true; //transducer.fireEvent(this.channel, TEvent.WORKSTATION_DO_LOAD_GLASS, null); //TODO pass to machine. } private void startConveyor() { Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; started=true; transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_START, newArgs ); stateChanged(); } //Helper Methods. @Override public void setPreviousCF(ConveyorFamily cf) { this.previousCF = cf; } @Override public void setMachine(Machine m) { this.machine = m; } @Override public void setBin(Bin b) { this.bin = b; } @Override public void setPreviousMachine(Machine m) { this.previousMachine = m; } }
true
true
public void eventFired(TChannel channel, TEvent event, Object[] args) { //Sensors if (channel == TChannel.SENSOR) { if (event == TEvent.SENSOR_GUI_PRESSED) { if (args[0].equals(conveyorIndex*2)) { //Front Sensor if (status != ConveyorStatus.GlassAtEnd) { Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; started=true; transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_START, newArgs); stateChanged(); return; } } else if (args[0].equals((conveyorIndex * 2) + 1)) { //End Sensor status = ConveyorStatus.GlassAtEnd; Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; if(!loading) { transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, newArgs); started=false; } stateChanged(); return; } } else if (event == TEvent.SENSOR_GUI_RELEASED) { if (args[0].equals(conveyorIndex*2)) { //Front sensor if (previousCF != null) { previousCF.msgSpaceAvailable(); stateChanged(); return; } else if (bin != null) { bin.msgSpaceAvailable(); stateChanged(); return; } else if (previousMachine != null) { previousMachine.msgSpaceAvailable(); stateChanged(); return; } } else if (args[0].equals((conveyorIndex*2) + 1)) { //end sensor status = ConveyorStatus.Nothing; stateChanged(); return; } } } //Workstation if (channel == this.channel) { if (event == TEvent.WORKSTATION_LOAD_FINISHED) { Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; loading = false; transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, newArgs ); started=false; return; } } }
public void eventFired(TChannel channel, TEvent event, Object[] args) { //Sensors if (channel == TChannel.SENSOR) { if (event == TEvent.SENSOR_GUI_PRESSED) { if (args[0].equals(conveyorIndex*2)) { //Front Sensor if (status != ConveyorStatus.GlassAtEnd) { Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; started=true; transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_START, newArgs); stateChanged(); return; } } else if (args[0].equals((conveyorIndex * 2) + 1)) { //End Sensor status = ConveyorStatus.GlassAtEnd; Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; if(!loading) { transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, newArgs); started=false; } stateChanged(); return; } } else if (event == TEvent.SENSOR_GUI_RELEASED) { if (args[0].equals(conveyorIndex*2)) { //Front sensor if (previousCF != null) { previousCF.msgSpaceAvailable(); stateChanged(); return; } else if (bin != null) { bin.msgSpaceAvailable(); stateChanged(); return; } else if (previousMachine != null) { previousMachine.msgSpaceAvailable(); stateChanged(); return; } } else if (args[0].equals((conveyorIndex*2) + 1)) { //end sensor status = ConveyorStatus.Nothing; stateChanged(); return; } } } //Workstation if (channel == this.channel) { if (event == TEvent.WORKSTATION_LOAD_FINISHED) { Integer[] newArgs = new Integer[1]; newArgs[0] = (Integer) conveyorIndex; loading = false; if(status==ConveyorStatus.GlassAtEnd) transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, newArgs ); started=false; return; } } }
diff --git a/user/src/com/google/gwt/user/client/ui/StackPanel.java b/user/src/com/google/gwt/user/client/ui/StackPanel.java index 47e096851..88b3dbf85 100644 --- a/user/src/com/google/gwt/user/client/ui/StackPanel.java +++ b/user/src/com/google/gwt/user/client/ui/StackPanel.java @@ -1,268 +1,266 @@ /* * Copyright 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.user.client.ui; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; /** * A panel that stacks its children vertically, displaying only one at a time, * with a header for each child which the user can click to display. * <p> * <img class='gallery' src='StackPanel.png'/> * </p> * <h3>CSS Style Rules</h3> * <ul class='css'> * <li>.gwt-StackPanel { the panel itself }</li> * <li>.gwt-StackPanel .gwt-StackPanelItem { unselected items }</li> * <li>.gwt-StackPanel .gwt-StackPanelItem-selected { selected items }</li> * </ul> * <p> * <h3>Example</h3> * {@example com.google.gwt.examples.StackPanelExample} * </p> */ public class StackPanel extends ComplexPanel implements IndexedPanel { private Element body; private int visibleStack = -1; /** * Creates an empty stack panel. */ public StackPanel() { Element table = DOM.createTable(); setElement(table); body = DOM.createTBody(); DOM.appendChild(table, body); DOM.setElementPropertyInt(table, "cellSpacing", 0); DOM.setElementPropertyInt(table, "cellPadding", 0); DOM.sinkEvents(table, Event.ONCLICK); setStyleName("gwt-StackPanel"); } /** * Adds a new child with the given widget. * * @param w the widget to be added */ public void add(Widget w) { // Call this early to ensure that the table doesn't end up partially // constructed when an exception is thrown from adopt(). w.removeFromParent(); int index = getWidgetCount(); Element tr = DOM.createTR(); Element td = DOM.createTD(); DOM.appendChild(body, tr); DOM.appendChild(tr, td); setStyleName(td, "gwt-StackPanelItem", true); DOM.setElementPropertyInt(td, "__index", index); DOM.setElementProperty(td, "height", "1px"); tr = DOM.createTR(); td = DOM.createTD(); DOM.appendChild(body, tr); DOM.appendChild(tr, td); DOM.setElementProperty(td, "height", "100%"); DOM.setElementProperty(td, "vAlign", "top"); super.add(w, td); setStackVisible(index, false); if (visibleStack == -1) { showStack(0); } } /** * Adds a new child with the given widget and header. * * @param w the widget to be added * @param stackText the header text associated with this widget */ public void add(Widget w, String stackText) { add(w, stackText, false); } /** * Adds a new child with the given widget and header, optionally interpreting * the header as HTML. * * @param w the widget to be added * @param stackText the header text associated with this widget * @param asHTML <code>true</code> to treat the specified text as HTML */ public void add(Widget w, String stackText, boolean asHTML) { add(w); setStackText(getWidgetCount() - 1, stackText, asHTML); } /** * Gets the currently selected child index. * * @return selected child */ public int getSelectedIndex() { return visibleStack; } public Widget getWidget(int index) { return getChildren().get(index); } public int getWidgetCount() { return getChildren().size(); } public int getWidgetIndex(Widget child) { return getChildren().indexOf(child); } public void onBrowserEvent(Event event) { if (DOM.eventGetType(event) == Event.ONCLICK) { int index = getDividerIndex(DOM.eventGetTarget(event)); if (index != -1) { showStack(index); } } } public boolean remove(int index) { return remove(getWidget(index), index); } public boolean remove(Widget child) { return remove(child, getWidgetIndex(child)); } /** * Sets the text associated with a child by its index. * * @param index the index of the child whose text is to be set * @param text the text to be associated with it */ public void setStackText(int index, String text) { setStackText(index, text, false); } /** * Sets the text associated with a child by its index. * * @param index the index of the child whose text is to be set * @param text the text to be associated with it * @param asHTML <code>true</code> to treat the specified text as HTML */ public void setStackText(int index, String text, boolean asHTML) { if (index >= getWidgetCount()) { return; } Element td = DOM.getChild(DOM.getChild(body, index * 2), 0); if (asHTML) { DOM.setInnerHTML(td, text); } else { DOM.setInnerText(td, text); } } /** * Shows the widget at the specified child index. * * @param index the index of the child to be shown */ public void showStack(int index) { if ((index >= getWidgetCount()) || (index == visibleStack)) { return; } if (visibleStack >= 0) { setStackVisible(visibleStack, false); } visibleStack = index; setStackVisible(visibleStack, true); } private int getDividerIndex(Element elem) { while ((elem != null) && !DOM.compare(elem, getElement())) { String expando = DOM.getElementProperty(elem, "__index"); if (expando != null) { return Integer.parseInt(expando); } elem = DOM.getParent(elem); } return -1; } private boolean remove(Widget child, int index) { if (child.getParent() != this) { return false; } // Correct visible stack for new location. if (visibleStack == index) { visibleStack = -1; } else if (visibleStack > index) { --visibleStack; } // Calculate which internal table elements to remove. int rowIndex = 2 * index; Element tr = DOM.getChild(body, rowIndex); DOM.removeChild(body, tr); tr = DOM.getChild(body, rowIndex); DOM.removeChild(body, tr); super.remove(child); int rows = getWidgetCount() * 2; // Update all the indexes. for (int i = rowIndex; i < rows; i = i + 2) { Element childTR = DOM.getChild(body, i); Element td = DOM.getFirstChild(childTR); - int curIndex = DOM.getElementPropertyInt(td, "__index"); - assert (curIndex == (i / 2) - 1); DOM.setElementPropertyInt(td, "__index", index); ++index; } return true; } private void setStackVisible(int index, boolean visible) { // Get the first table row containing the widget's selector item. Element tr = DOM.getChild(body, (index * 2)); if (tr == null) { return; } // Style the stack selector item. Element td = DOM.getFirstChild(tr); setStyleName(td, "gwt-StackPanelItem-selected", visible); // Show/hide the contained widget. tr = DOM.getChild(body, (index * 2) + 1); UIObject.setVisible(tr, visible); getWidget(index).setVisible(visible); } }
true
true
private boolean remove(Widget child, int index) { if (child.getParent() != this) { return false; } // Correct visible stack for new location. if (visibleStack == index) { visibleStack = -1; } else if (visibleStack > index) { --visibleStack; } // Calculate which internal table elements to remove. int rowIndex = 2 * index; Element tr = DOM.getChild(body, rowIndex); DOM.removeChild(body, tr); tr = DOM.getChild(body, rowIndex); DOM.removeChild(body, tr); super.remove(child); int rows = getWidgetCount() * 2; // Update all the indexes. for (int i = rowIndex; i < rows; i = i + 2) { Element childTR = DOM.getChild(body, i); Element td = DOM.getFirstChild(childTR); int curIndex = DOM.getElementPropertyInt(td, "__index"); assert (curIndex == (i / 2) - 1); DOM.setElementPropertyInt(td, "__index", index); ++index; } return true; }
private boolean remove(Widget child, int index) { if (child.getParent() != this) { return false; } // Correct visible stack for new location. if (visibleStack == index) { visibleStack = -1; } else if (visibleStack > index) { --visibleStack; } // Calculate which internal table elements to remove. int rowIndex = 2 * index; Element tr = DOM.getChild(body, rowIndex); DOM.removeChild(body, tr); tr = DOM.getChild(body, rowIndex); DOM.removeChild(body, tr); super.remove(child); int rows = getWidgetCount() * 2; // Update all the indexes. for (int i = rowIndex; i < rows; i = i + 2) { Element childTR = DOM.getChild(body, i); Element td = DOM.getFirstChild(childTR); DOM.setElementPropertyInt(td, "__index", index); ++index; } return true; }
diff --git a/snowman-common/src/main/java/com/sun/darkstar/example/snowman/common/util/CollisionManagerImpl.java b/snowman-common/src/main/java/com/sun/darkstar/example/snowman/common/util/CollisionManagerImpl.java index ea6b64a..e45baf3 100644 --- a/snowman-common/src/main/java/com/sun/darkstar/example/snowman/common/util/CollisionManagerImpl.java +++ b/snowman-common/src/main/java/com/sun/darkstar/example/snowman/common/util/CollisionManagerImpl.java @@ -1,220 +1,220 @@ /* * Copyright (c) 2008, Sun Microsystems, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sun.darkstar.example.snowman.common.util; import java.util.ArrayList; import com.jme.intersection.PickData; import com.jme.intersection.PickResults; import com.jme.intersection.TrianglePickResults; import com.jme.math.Ray; import com.jme.math.Vector3f; import com.jme.scene.Node; import com.jme.scene.Spatial; import com.jme.scene.TriMesh; import com.sun.darkstar.example.snowman.common.util.enumn.EStats; /** * <code>CollisionManager</code> is a <code>Manager</code> that is responsible * for processing all collision detection tasks. * * @author Yi Wang (Neakor) * @author Owen Kellett * @version Creation date: 07-02-2008 24:26 EST * @version Modified date: 07-16-2008 11:40 EST */ public class CollisionManagerImpl implements CollisionManager { /** * The <code>CollisionManager</code> instance. */ private static CollisionManager instance; /** * Constructor of <code>CollisionManager</code>. */ protected CollisionManagerImpl() { } /** * Retrieve the <code>CollisionManager</code> instance. * @return The <code>CollisionManager</code> instance. */ public static CollisionManager getInstance() { if (CollisionManagerImpl.instance == null) { CollisionManagerImpl.instance = new CollisionManagerImpl(); } return CollisionManagerImpl.instance; } /** {@inheritDoc} */ public Spatial getIntersectObject(Ray ray, Node root, Class<? extends Spatial> reference, boolean iterate) { PickResults results = new TrianglePickResults(); results.setCheckDistance(true); root.findPick(ray, results); if (iterate) { for (int i = 0; i < results.getNumber(); i++) { Spatial collision = this.validateClass(root, results.getPickData(i).getTargetMesh(), reference); if (collision != null) return collision; } } else if (results.getNumber() > 0) { return this.validateClass(root, results.getPickData(0).getTargetMesh(), reference); } return null; } /** * Retrieve the spatial with given reference class. * @param root The root <code>Node</code> to stop check at. * @param spatial The <code>Spatial</code> to check. * @param reference The <code>Class</code> reference of the expected object. * @return The <code>Spatial</code> that is of the given reference <code>Class</code>. */ private Spatial validateClass(Node root, Spatial spatial, Class<? extends Spatial> reference) { if (spatial.getClass().equals(reference)) { return spatial; } else { while (spatial.getParent() != null) { spatial = spatial.getParent(); if (spatial == root) { return null; // TODO Should throw an exception here saying reached parent. } else if (spatial.getClass().equals(reference)) { return spatial; } } // TODO Should throw an exception here saying that cannot find the referencing class. } return null; } /** {@inheritDoc} */ public Vector3f getIntersection(Ray ray, Spatial parent, Vector3f store, boolean local) { if (store == null) { store = new Vector3f(); } TrianglePickResults results = new TrianglePickResults(); results.setCheckDistance(true); Vector3f[] vertices = new Vector3f[3]; parent.findPick(ray, results); boolean hit = false; if (results.getNumber() > 0) { PickData data = results.getPickData(0); ArrayList<Integer> triangles = data.getTargetTris(); if (!triangles.isEmpty()) { TriMesh mesh = (TriMesh) data.getTargetMesh(); mesh.getTriangle(triangles.get(0).intValue(), vertices); for (int j = 0; j < vertices.length; j++) { mesh.localToWorld(vertices[j], vertices[j]); } hit = ray.intersectWhere(vertices[0], vertices[1], vertices[2], store); if (hit && local) { parent.worldToLocal(store, store); return store; } else if (hit && !local) { return store; } } } return null; } public Vector3f getDestination(float x1, float z1, float x2, float z2, Spatial spatial) { //generate the start and destination points Vector3f start = new Vector3f(x1, EStats.SnowmanHeight.getValue()/2.0f, z1); Vector3f destination = new Vector3f(x2, EStats.SnowmanHeight.getValue()/2.0f, z2); //convert points to world coordinate system spatial.localToWorld(start, start); spatial.localToWorld(destination, destination); //generate Ray for intersection detection Vector3f direction = destination.subtract(start).normalizeLocal(); Ray moveRay = new Ray(start, direction); //calculate the intersection between the move ray and the spatial Vector3f hitPoint = getIntersection(moveRay, spatial, null, false); //if there are no obstacles, return the destination directly if(hitPoint == null) { spatial.worldToLocal(destination, destination); return destination; } else { float originalDistance = destination.distance(start); float newDistance = hitPoint.distance(start); if(originalDistance > newDistance - EStats.BackoffDistance.getValue()) { //we are either trying to go through a hit point - //or get to close to one + //or got too close to one direction.multLocal(EStats.BackoffDistance.getValue()); Vector3f newDestination = hitPoint.subtractLocal(direction); spatial.worldToLocal(newDestination, newDestination); return newDestination; } else { //destination is not close to any hit points so //we can just return it directly spatial.worldToLocal(destination, destination); return destination; } } } public boolean validate(float x1, float z1, float x2, float z2, Spatial spatial) { //generate the start and destination points Vector3f start = new Vector3f(x1, EStats.SnowballHeight.getValue(), z1); Vector3f destination = new Vector3f(x2, EStats.SnowballHeight.getValue(), z2); //convert points to world coordinate system spatial.localToWorld(start, start); spatial.localToWorld(destination, destination); //generate Ray for intersection detection Vector3f direction = destination.subtract(start).normalizeLocal(); Ray moveRay = new Ray(start, direction); //calculate the intersection between the move ray and the spatial Vector3f hitPoint = getIntersection(moveRay, spatial, null, false); //if there is no hit point, it is a valid throw if(hitPoint == null) return true; //if there is a hit point, compare the distances. float distance1 = start.distanceSquared(destination); float distance2 = start.distanceSquared(hitPoint); if(distance1 <= distance2) return true; else return false; } }
true
true
public Vector3f getDestination(float x1, float z1, float x2, float z2, Spatial spatial) { //generate the start and destination points Vector3f start = new Vector3f(x1, EStats.SnowmanHeight.getValue()/2.0f, z1); Vector3f destination = new Vector3f(x2, EStats.SnowmanHeight.getValue()/2.0f, z2); //convert points to world coordinate system spatial.localToWorld(start, start); spatial.localToWorld(destination, destination); //generate Ray for intersection detection Vector3f direction = destination.subtract(start).normalizeLocal(); Ray moveRay = new Ray(start, direction); //calculate the intersection between the move ray and the spatial Vector3f hitPoint = getIntersection(moveRay, spatial, null, false); //if there are no obstacles, return the destination directly if(hitPoint == null) { spatial.worldToLocal(destination, destination); return destination; } else { float originalDistance = destination.distance(start); float newDistance = hitPoint.distance(start); if(originalDistance > newDistance - EStats.BackoffDistance.getValue()) { //we are either trying to go through a hit point //or get to close to one direction.multLocal(EStats.BackoffDistance.getValue()); Vector3f newDestination = hitPoint.subtractLocal(direction); spatial.worldToLocal(newDestination, newDestination); return newDestination; } else { //destination is not close to any hit points so //we can just return it directly spatial.worldToLocal(destination, destination); return destination; } } }
public Vector3f getDestination(float x1, float z1, float x2, float z2, Spatial spatial) { //generate the start and destination points Vector3f start = new Vector3f(x1, EStats.SnowmanHeight.getValue()/2.0f, z1); Vector3f destination = new Vector3f(x2, EStats.SnowmanHeight.getValue()/2.0f, z2); //convert points to world coordinate system spatial.localToWorld(start, start); spatial.localToWorld(destination, destination); //generate Ray for intersection detection Vector3f direction = destination.subtract(start).normalizeLocal(); Ray moveRay = new Ray(start, direction); //calculate the intersection between the move ray and the spatial Vector3f hitPoint = getIntersection(moveRay, spatial, null, false); //if there are no obstacles, return the destination directly if(hitPoint == null) { spatial.worldToLocal(destination, destination); return destination; } else { float originalDistance = destination.distance(start); float newDistance = hitPoint.distance(start); if(originalDistance > newDistance - EStats.BackoffDistance.getValue()) { //we are either trying to go through a hit point //or got too close to one direction.multLocal(EStats.BackoffDistance.getValue()); Vector3f newDestination = hitPoint.subtractLocal(direction); spatial.worldToLocal(newDestination, newDestination); return newDestination; } else { //destination is not close to any hit points so //we can just return it directly spatial.worldToLocal(destination, destination); return destination; } } }
diff --git a/stilts-activity-ui/src/main/java/org/purl/wf4ever/astrotaverna/tjoin/ui/serviceprovider/StiltsServiceProvider.java b/stilts-activity-ui/src/main/java/org/purl/wf4ever/astrotaverna/tjoin/ui/serviceprovider/StiltsServiceProvider.java index 56dbf44..eab2c74 100644 --- a/stilts-activity-ui/src/main/java/org/purl/wf4ever/astrotaverna/tjoin/ui/serviceprovider/StiltsServiceProvider.java +++ b/stilts-activity-ui/src/main/java/org/purl/wf4ever/astrotaverna/tjoin/ui/serviceprovider/StiltsServiceProvider.java @@ -1,186 +1,186 @@ package org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider; import java.net.URI; import java.util.ArrayList; import java.util.List; import javax.swing.Icon; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.AddColumnByExpressionServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.AddSkyCoordsServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.CheckTemplateFillerServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.CoordTransformationServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.FormatConversionServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.GetListFromColumnServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.ResolveCoordsServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.SelectColumnsServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.SelectRowsServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.StiltsServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.StiltsServiceIcon; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.TcatListServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.TcatServiceDesc; import org.purl.wf4ever.astrotaverna.tjoin.ui.serviceprovider.TemplateFillerServiceDesc; import net.sf.taverna.t2.servicedescriptions.ServiceDescription; import net.sf.taverna.t2.servicedescriptions.ServiceDescriptionProvider; public class StiltsServiceProvider implements ServiceDescriptionProvider { //OJO!!!!!!!!!!!!!!!!!!!! //write down a real URI private static final URI providerId = URI .create("http://www.iaa.es/service-provider/tjoin"); /** * Do the actual search for services. Return using the callBack parameter. */ @SuppressWarnings("unchecked") public void findServiceDescriptionsAsync( FindServiceDescriptionsCallBack callBack) { // Use callback.status() for long-running searches // callBack.status("Resolving example services"); List<ServiceDescription> results = new ArrayList<ServiceDescription>(); // FIXME: Implement the actual service search/lookup instead // of dummy for-loop //for (int i = 1; i <= 5; i++) { // StiltsServiceDesc service = new StiltsServiceDesc(); // // Populate the service description bean // service.setExampleString("Example " + i); // service.setExampleUri(URI.create("http://localhost:8192/service")); // // Optional: set description // service.setDescription("Service example number " + i); // results.add(service); //} StiltsServiceDesc service = new StiltsServiceDesc(); service.setTypeOFInput("String"); service.setDescription("Joins two VOTables with the same number of rows"); results.add(service); //ServiceDescription SelectColumnsServiceDesc service2 = new SelectColumnsServiceDesc(); service2.setTypeOfInput("String"); service2.setTypeOfFilter("Column names"); //service2.setDescription("Columns selection in a table"); results.add(service2); SelectRowsServiceDesc service3 = new SelectRowsServiceDesc(); service3.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); //service3.setDescription("Rows selection in a table"); results.add(service3); CoordTransformationServiceDesc service4 = new CoordTransformationServiceDesc(); service4.setTypeOfInput("String"); //service4.setDescription("Coordenates transformation in a table"); results.add(service4); FormatConversionServiceDesc service5 = new FormatConversionServiceDesc(); service5.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); //service5.setDescription("Table format conversion"); results.add(service5); AddColumnByExpressionServiceDesc service6 = new AddColumnByExpressionServiceDesc(); service6.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); service6.setDescription("Adds column to VOTable using a expression"); results.add(service6); AddSkyCoordsServiceDesc service7 = new AddSkyCoordsServiceDesc(); service7.setTypeOfInput("String"); //service7.setDescription("Add sky coordinates"); results.add(service7); ResolveCoordsServiceDesc service8 = new ResolveCoordsServiceDesc(); service8.setTypeOfInput("String"); service8.setDescription("Resolve coordinates from name in VOTable"); results.add(service8); TcatServiceDesc service9 = new TcatServiceDesc(); service9.setTypeOfInput("String"); service9.setDescription("Concats two VOTables with same number of cols"); results.add(service9); TcatListServiceDesc service10 = new TcatListServiceDesc(); service10.setTypeOfInput("String"); service10.setDescription("Concats n VOTables with same number of cols"); results.add(service10); GetListFromColumnServiceDesc service11 = new GetListFromColumnServiceDesc(); service11.setTypeOfInput("String"); //service11.setDescription("Get list from column in a votable"); results.add(service11); TemplateFillerServiceDesc service12 = new TemplateFillerServiceDesc(); service12.setTypeOfInput("String"); //service12.setDescription("Template filler from a votable"); results.add(service12); CheckTemplateFillerServiceDesc service13 = new CheckTemplateFillerServiceDesc(); service13.setTypeOfInput("String"); //service13.setDescription("Check Template filler"); results.add(service13); AddCommonRowToVOTableServiceDesc service14 = new AddCommonRowToVOTableServiceDesc(); service14.setTypeOfInput("String"); service14.setDescription("Add a row to each row of another table"); //service13.setDescription("Check Template filler"); results.add(service14); CrossMatch2ServiceDesc service15 = new CrossMatch2ServiceDesc(); - service14.setTypeOfInput("String"); - service14.setDescription("Crossmatching"); + service15.setTypeOfInput("String"); + service15.setDescription("Crossmatching"); //service13.setDescription("Check Template filler"); results.add(service15); //Put here additional descriptions for other services //............ //............ //............ //............ // partialResults() can also be called several times from inside // for-loop if the full search takes a long time callBack.partialResults(results); // No more results will be coming callBack.finished(); } /** * Icon for service provider */ public Icon getIcon() { return StiltsServiceIcon.getIcon(); } /** * Name of service provider, appears in right click for 'Remove service * provider' */ public String getName() { return "My astro services"; } @Override public String toString() { return getName(); } public String getId() { return providerId.toASCIIString(); } }
true
true
public void findServiceDescriptionsAsync( FindServiceDescriptionsCallBack callBack) { // Use callback.status() for long-running searches // callBack.status("Resolving example services"); List<ServiceDescription> results = new ArrayList<ServiceDescription>(); // FIXME: Implement the actual service search/lookup instead // of dummy for-loop //for (int i = 1; i <= 5; i++) { // StiltsServiceDesc service = new StiltsServiceDesc(); // // Populate the service description bean // service.setExampleString("Example " + i); // service.setExampleUri(URI.create("http://localhost:8192/service")); // // Optional: set description // service.setDescription("Service example number " + i); // results.add(service); //} StiltsServiceDesc service = new StiltsServiceDesc(); service.setTypeOFInput("String"); service.setDescription("Joins two VOTables with the same number of rows"); results.add(service); //ServiceDescription SelectColumnsServiceDesc service2 = new SelectColumnsServiceDesc(); service2.setTypeOfInput("String"); service2.setTypeOfFilter("Column names"); //service2.setDescription("Columns selection in a table"); results.add(service2); SelectRowsServiceDesc service3 = new SelectRowsServiceDesc(); service3.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); //service3.setDescription("Rows selection in a table"); results.add(service3); CoordTransformationServiceDesc service4 = new CoordTransformationServiceDesc(); service4.setTypeOfInput("String"); //service4.setDescription("Coordenates transformation in a table"); results.add(service4); FormatConversionServiceDesc service5 = new FormatConversionServiceDesc(); service5.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); //service5.setDescription("Table format conversion"); results.add(service5); AddColumnByExpressionServiceDesc service6 = new AddColumnByExpressionServiceDesc(); service6.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); service6.setDescription("Adds column to VOTable using a expression"); results.add(service6); AddSkyCoordsServiceDesc service7 = new AddSkyCoordsServiceDesc(); service7.setTypeOfInput("String"); //service7.setDescription("Add sky coordinates"); results.add(service7); ResolveCoordsServiceDesc service8 = new ResolveCoordsServiceDesc(); service8.setTypeOfInput("String"); service8.setDescription("Resolve coordinates from name in VOTable"); results.add(service8); TcatServiceDesc service9 = new TcatServiceDesc(); service9.setTypeOfInput("String"); service9.setDescription("Concats two VOTables with same number of cols"); results.add(service9); TcatListServiceDesc service10 = new TcatListServiceDesc(); service10.setTypeOfInput("String"); service10.setDescription("Concats n VOTables with same number of cols"); results.add(service10); GetListFromColumnServiceDesc service11 = new GetListFromColumnServiceDesc(); service11.setTypeOfInput("String"); //service11.setDescription("Get list from column in a votable"); results.add(service11); TemplateFillerServiceDesc service12 = new TemplateFillerServiceDesc(); service12.setTypeOfInput("String"); //service12.setDescription("Template filler from a votable"); results.add(service12); CheckTemplateFillerServiceDesc service13 = new CheckTemplateFillerServiceDesc(); service13.setTypeOfInput("String"); //service13.setDescription("Check Template filler"); results.add(service13); AddCommonRowToVOTableServiceDesc service14 = new AddCommonRowToVOTableServiceDesc(); service14.setTypeOfInput("String"); service14.setDescription("Add a row to each row of another table"); //service13.setDescription("Check Template filler"); results.add(service14); CrossMatch2ServiceDesc service15 = new CrossMatch2ServiceDesc(); service14.setTypeOfInput("String"); service14.setDescription("Crossmatching"); //service13.setDescription("Check Template filler"); results.add(service15); //Put here additional descriptions for other services //............ //............ //............ //............ // partialResults() can also be called several times from inside // for-loop if the full search takes a long time callBack.partialResults(results); // No more results will be coming callBack.finished(); }
public void findServiceDescriptionsAsync( FindServiceDescriptionsCallBack callBack) { // Use callback.status() for long-running searches // callBack.status("Resolving example services"); List<ServiceDescription> results = new ArrayList<ServiceDescription>(); // FIXME: Implement the actual service search/lookup instead // of dummy for-loop //for (int i = 1; i <= 5; i++) { // StiltsServiceDesc service = new StiltsServiceDesc(); // // Populate the service description bean // service.setExampleString("Example " + i); // service.setExampleUri(URI.create("http://localhost:8192/service")); // // Optional: set description // service.setDescription("Service example number " + i); // results.add(service); //} StiltsServiceDesc service = new StiltsServiceDesc(); service.setTypeOFInput("String"); service.setDescription("Joins two VOTables with the same number of rows"); results.add(service); //ServiceDescription SelectColumnsServiceDesc service2 = new SelectColumnsServiceDesc(); service2.setTypeOfInput("String"); service2.setTypeOfFilter("Column names"); //service2.setDescription("Columns selection in a table"); results.add(service2); SelectRowsServiceDesc service3 = new SelectRowsServiceDesc(); service3.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); //service3.setDescription("Rows selection in a table"); results.add(service3); CoordTransformationServiceDesc service4 = new CoordTransformationServiceDesc(); service4.setTypeOfInput("String"); //service4.setDescription("Coordenates transformation in a table"); results.add(service4); FormatConversionServiceDesc service5 = new FormatConversionServiceDesc(); service5.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); //service5.setDescription("Table format conversion"); results.add(service5); AddColumnByExpressionServiceDesc service6 = new AddColumnByExpressionServiceDesc(); service6.setTypeOfInput("String"); //service3.setTypeOfFilter("Column names"); service6.setDescription("Adds column to VOTable using a expression"); results.add(service6); AddSkyCoordsServiceDesc service7 = new AddSkyCoordsServiceDesc(); service7.setTypeOfInput("String"); //service7.setDescription("Add sky coordinates"); results.add(service7); ResolveCoordsServiceDesc service8 = new ResolveCoordsServiceDesc(); service8.setTypeOfInput("String"); service8.setDescription("Resolve coordinates from name in VOTable"); results.add(service8); TcatServiceDesc service9 = new TcatServiceDesc(); service9.setTypeOfInput("String"); service9.setDescription("Concats two VOTables with same number of cols"); results.add(service9); TcatListServiceDesc service10 = new TcatListServiceDesc(); service10.setTypeOfInput("String"); service10.setDescription("Concats n VOTables with same number of cols"); results.add(service10); GetListFromColumnServiceDesc service11 = new GetListFromColumnServiceDesc(); service11.setTypeOfInput("String"); //service11.setDescription("Get list from column in a votable"); results.add(service11); TemplateFillerServiceDesc service12 = new TemplateFillerServiceDesc(); service12.setTypeOfInput("String"); //service12.setDescription("Template filler from a votable"); results.add(service12); CheckTemplateFillerServiceDesc service13 = new CheckTemplateFillerServiceDesc(); service13.setTypeOfInput("String"); //service13.setDescription("Check Template filler"); results.add(service13); AddCommonRowToVOTableServiceDesc service14 = new AddCommonRowToVOTableServiceDesc(); service14.setTypeOfInput("String"); service14.setDescription("Add a row to each row of another table"); //service13.setDescription("Check Template filler"); results.add(service14); CrossMatch2ServiceDesc service15 = new CrossMatch2ServiceDesc(); service15.setTypeOfInput("String"); service15.setDescription("Crossmatching"); //service13.setDescription("Check Template filler"); results.add(service15); //Put here additional descriptions for other services //............ //............ //............ //............ // partialResults() can also be called several times from inside // for-loop if the full search takes a long time callBack.partialResults(results); // No more results will be coming callBack.finished(); }
diff --git a/src/me/coolblinger/signrank/SignRank.java b/src/me/coolblinger/signrank/SignRank.java index 5f375d4..e5a50e2 100644 --- a/src/me/coolblinger/signrank/SignRank.java +++ b/src/me/coolblinger/signrank/SignRank.java @@ -1,92 +1,97 @@ package me.coolblinger.signrank; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; import com.platymuus.bukkit.permissions.PermissionsPlugin; import me.coolblinger.signrank.listeners.SignRankBlockListener; import me.coolblinger.signrank.listeners.SignRankPlayerListener; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.logging.Logger; public class SignRank extends JavaPlugin{ public Logger log = Logger.getLogger("Minecraft"); public boolean permissions3; public PermissionHandler permissions; private SignRankPlayerListener playerListener = new SignRankPlayerListener(this); private SignRankBlockListener blockListener = new SignRankBlockListener(this); public SignRankPermissionsBukkit permissionsBukkit = new SignRankPermissionsBukkit(); public SignRankConfig signRankConfig = new SignRankConfig(); public SignRankPermissionsBukkitYML signRankPermissionsBukkitYML = new SignRankPermissionsBukkitYML(this); public void onDisable() { } public void onEnable() { PluginDescriptionFile pdFile = this.getDescription(); PluginManager pm = this.getServer().getPluginManager(); Plugin permissionsBukkitPlugin = pm.getPlugin("PermissionsBukkit"); if (permissionsBukkitPlugin == null) { Plugin permissions3Plugin = pm.getPlugin("Permissions"); if (permissions3Plugin == null) { log.severe("PermissionsBukkit nor Permissions3 could be found. SignRank will disable itself."); this.setEnabled(false); return; } else { if (!permissions3Plugin.getDescription().getVersion().contains("3.")) { log.severe("PermissionsBukkit nor Permissions3 could be found. SignRank will disable itself."); log.warning(permissions3Plugin.getDescription().getVersion()); this.setEnabled(false); return; } else { permissions3 = true; permissions = ((Permissions)permissions3Plugin).getHandler(); } } } else { permissions3 = false; permissionsBukkit.plugin = (PermissionsPlugin)permissionsBukkitPlugin; } pm.registerEvent(Event.Type.PLAYER_INTERACT, playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.SIGN_CHANGE, blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Event.Priority.Normal, this); log.info(pdFile.getName() + " version " + pdFile.getVersion() + " loaded!"); + try { + updateCheck(); + } catch (Exception e) { + log.severe("SignRank could not check for updates."); + } } public void updateCheck() throws IOException { URL url = new URL("http://dl.dropbox.com/u/677732/uploads/SignRank.jar"); int urlSize = url.openConnection().getContentLength(); File pluginFile = new File("plugins" + File.separator + "SignRank.jar"); if (!pluginFile.exists()) { log.severe("SignRank has not been installed correctly"); return; } long pluginFileSize = pluginFile.length(); if (urlSize != pluginFileSize) { BukkitScheduler bScheduler = this.getServer().getScheduler(); bScheduler.scheduleSyncDelayedTask(this, new Runnable() { public void run() { log.warning("There has been an update for SignRank."); } }, 600); } } public boolean hasPermission(Player player, String permission) { if (permissions3) { return permissions.has(player, permission); } else { return player.hasPermission(permission); } } }
true
true
public void onEnable() { PluginDescriptionFile pdFile = this.getDescription(); PluginManager pm = this.getServer().getPluginManager(); Plugin permissionsBukkitPlugin = pm.getPlugin("PermissionsBukkit"); if (permissionsBukkitPlugin == null) { Plugin permissions3Plugin = pm.getPlugin("Permissions"); if (permissions3Plugin == null) { log.severe("PermissionsBukkit nor Permissions3 could be found. SignRank will disable itself."); this.setEnabled(false); return; } else { if (!permissions3Plugin.getDescription().getVersion().contains("3.")) { log.severe("PermissionsBukkit nor Permissions3 could be found. SignRank will disable itself."); log.warning(permissions3Plugin.getDescription().getVersion()); this.setEnabled(false); return; } else { permissions3 = true; permissions = ((Permissions)permissions3Plugin).getHandler(); } } } else { permissions3 = false; permissionsBukkit.plugin = (PermissionsPlugin)permissionsBukkitPlugin; } pm.registerEvent(Event.Type.PLAYER_INTERACT, playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.SIGN_CHANGE, blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Event.Priority.Normal, this); log.info(pdFile.getName() + " version " + pdFile.getVersion() + " loaded!"); }
public void onEnable() { PluginDescriptionFile pdFile = this.getDescription(); PluginManager pm = this.getServer().getPluginManager(); Plugin permissionsBukkitPlugin = pm.getPlugin("PermissionsBukkit"); if (permissionsBukkitPlugin == null) { Plugin permissions3Plugin = pm.getPlugin("Permissions"); if (permissions3Plugin == null) { log.severe("PermissionsBukkit nor Permissions3 could be found. SignRank will disable itself."); this.setEnabled(false); return; } else { if (!permissions3Plugin.getDescription().getVersion().contains("3.")) { log.severe("PermissionsBukkit nor Permissions3 could be found. SignRank will disable itself."); log.warning(permissions3Plugin.getDescription().getVersion()); this.setEnabled(false); return; } else { permissions3 = true; permissions = ((Permissions)permissions3Plugin).getHandler(); } } } else { permissions3 = false; permissionsBukkit.plugin = (PermissionsPlugin)permissionsBukkitPlugin; } pm.registerEvent(Event.Type.PLAYER_INTERACT, playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.SIGN_CHANGE, blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Event.Priority.Normal, this); log.info(pdFile.getName() + " version " + pdFile.getVersion() + " loaded!"); try { updateCheck(); } catch (Exception e) { log.severe("SignRank could not check for updates."); } }
diff --git a/src/server/src/main/java/org/apache/accumulo/server/master/LiveTServerSet.java b/src/server/src/main/java/org/apache/accumulo/server/master/LiveTServerSet.java index 49b5d3a0e..d010825d8 100644 --- a/src/server/src/main/java/org/apache/accumulo/server/master/LiveTServerSet.java +++ b/src/server/src/main/java/org/apache/accumulo/server/master/LiveTServerSet.java @@ -1,329 +1,329 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.server.master; import static org.apache.accumulo.core.zookeeper.ZooUtil.NodeMissingPolicy.SKIP; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TimerTask; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.Instance; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.KeyExtent; import org.apache.accumulo.core.master.thrift.TabletServerStatus; import org.apache.accumulo.core.security.thrift.ThriftSecurityException; import org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException; import org.apache.accumulo.core.tabletserver.thrift.TabletClientService; import org.apache.accumulo.core.util.ServerServices; import org.apache.accumulo.core.util.ThriftUtil; import org.apache.accumulo.core.zookeeper.ZooUtil; import org.apache.accumulo.server.conf.ServerConfiguration; import org.apache.accumulo.server.master.state.TServerInstance; import org.apache.accumulo.server.security.SecurityConstants; import org.apache.accumulo.server.util.AddressUtil; import org.apache.accumulo.server.util.Halt; import org.apache.accumulo.server.util.time.SimpleTimer; import org.apache.accumulo.server.zookeeper.ZooCache; import org.apache.accumulo.server.zookeeper.ZooLock; import org.apache.accumulo.server.zookeeper.ZooReaderWriter; import org.apache.hadoop.io.Text; import org.apache.log4j.Logger; import org.apache.thrift.TException; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; public class LiveTServerSet implements Watcher { public interface Listener { void update(LiveTServerSet current, Set<TServerInstance> deleted, Set<TServerInstance> added); } private static final Logger log = Logger.getLogger(LiveTServerSet.class); private final Listener cback; private final Instance instance; private ZooCache zooCache; public class TServerConnection { private final InetSocketAddress address; TabletClientService.Iface client = null; public TServerConnection(InetSocketAddress addr) throws TException { address = addr; } synchronized private TabletClientService.Iface connect() { if (client == null) { try { client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, ServerConfiguration.getSystemConfiguration()); } catch (Exception ex) { client = null; log.error(ex, ex); } } return client; } private String lockString(ZooLock mlock) { return mlock.getLockID().serialize(ZooUtil.getRoot(instance) + Constants.ZMASTER_LOCK); } synchronized public void close() { if (client != null) { ThriftUtil.returnClient(client); client = null; } } synchronized public void assignTablet(ZooLock lock, KeyExtent extent) throws TException { connect().loadTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift()); } synchronized public void unloadTablet(ZooLock lock, KeyExtent extent, boolean save) throws TException { connect().unloadTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift(), save); } synchronized public TabletServerStatus getTableMap() throws TException, ThriftSecurityException { return connect().getTabletServerStatus(null, SecurityConstants.getSystemCredentials()); } synchronized public void halt(ZooLock lock) throws TException, ThriftSecurityException { if (client != null) { client.halt(null, SecurityConstants.getSystemCredentials(), lockString(lock)); } } public void fastHalt(ZooLock lock) throws TException { if (client != null) { client.fastHalt(null, SecurityConstants.getSystemCredentials(), lockString(lock)); } } synchronized public void flush(ZooLock lock, String tableId, byte[] startRow, byte[] endRow) throws TException { connect().flush(null, SecurityConstants.getSystemCredentials(), lockString(lock), tableId, startRow == null ? null : ByteBuffer.wrap(startRow), endRow == null ? null : ByteBuffer.wrap(endRow)); } synchronized public void useLoggers(Set<String> loggers) throws TException { connect().useLoggers(null, SecurityConstants.getSystemCredentials(), loggers); } synchronized public void chop(ZooLock lock, KeyExtent extent) throws TException { connect().chop(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift()); } synchronized public void splitTablet(ZooLock lock, KeyExtent extent, Text splitPoint) throws TException, ThriftSecurityException, NotServingTabletException { connect().splitTablet(null, SecurityConstants.getSystemCredentials(), extent.toThrift(), ByteBuffer.wrap(splitPoint.getBytes(), 0, splitPoint.getLength())); } synchronized public void flushTablet(ZooLock lock, KeyExtent extent) throws TException { connect().flushTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift()); } synchronized public void compact(ZooLock lock, String tableId, byte[] startRow, byte[] endRow) throws TException { connect().compact(null, SecurityConstants.getSystemCredentials(), lockString(lock), tableId, startRow == null ? null : ByteBuffer.wrap(startRow), endRow == null ? null : ByteBuffer.wrap(endRow)); } synchronized public boolean isActive(long tid) throws TException { return connect().isActive(null, tid); } } static class TServerInfo { ZooLock lock; TServerConnection connection; TServerInstance instance; TServerLockWatcher watcher; TServerInfo(ZooLock lock, TServerInstance instance, TServerConnection connection, TServerLockWatcher watcher) { this.lock = lock; this.connection = connection; this.instance = instance; this.watcher = watcher; } void cleanup() throws InterruptedException, KeeperException { lock.tryToCancelAsyncLockOrUnlock(); connection.close(); } }; // Map from tserver master service to server information private Map<String,TServerInfo> current = new HashMap<String,TServerInfo>(); public LiveTServerSet(Instance instance, Listener cback) { this.cback = cback; this.instance = instance; } public synchronized ZooCache getZooCache() { if (zooCache == null) zooCache = new ZooCache(this); return zooCache; } public synchronized void startListeningForTabletServerChanges() { scanServers(); SimpleTimer.getInstance().schedule(new TimerTask() { @Override public void run() { scanServers(); } }, 0, 1000); } public synchronized void scanServers() { try { final Set<TServerInstance> updates = new HashSet<TServerInstance>(); final Set<TServerInstance> doomed = new HashSet<TServerInstance>(); final String path = ZooUtil.getRoot(instance) + Constants.ZTSERVERS; for (String server : getZooCache().getChildren(path)) { // See if we have an async lock in place? TServerInfo info = current.get(server); TServerLockWatcher watcher; ZooLock lock; final String lockPath = path + "/" + server; if (info != null) { // yep: get out the lock/watcher so we can check on it watcher = info.watcher; lock = info.lock; } else { // nope: create a new lock and watcher lock = new ZooLock(lockPath); watcher = new TServerLockWatcher(); lock.lockAsync(watcher, "master".getBytes()); } TServerInstance instance = null; // Did we win the lock yet? if (!lock.isLocked() && !watcher.gotLock && watcher.failureException == null) { // Nope... there's a server out there: is this is a new server? if (info == null) { // Yep: hold onto the information about this server Stat stat = new Stat(); byte[] lockData = ZooLock.getLockData(lockPath, stat); String lockString = new String(lockData == null ? new byte[] {} : lockData); if (lockString.length() > 0 && !lockString.equals("master")) { ServerServices services = new ServerServices(new String(lockData)); InetSocketAddress client = services.getAddress(ServerServices.Service.TSERV_CLIENT); InetSocketAddress addr = AddressUtil.parseAddress(server, Property.TSERV_CLIENTPORT); TServerConnection conn = new TServerConnection(addr); instance = new TServerInstance(client, stat.getEphemeralOwner()); info = new TServerInfo(lock, instance, conn, watcher); current.put(server, info); updates.add(instance); } else { lock.tryToCancelAsyncLockOrUnlock(); } } } else { // Yes... there is no server here any more lock.tryToCancelAsyncLockOrUnlock(); if (info != null) { doomed.add(info.instance); current.remove(server); info.cleanup(); } } } // log.debug("Current: " + current.keySet()); - if (!doomed.isEmpty() && !updates.isEmpty()) + if (!doomed.isEmpty() || !updates.isEmpty()) this.cback.update(this, doomed, updates); } catch (Exception ex) { log.error(ex, ex); } } @Override public void process(WatchedEvent event) { scanServers(); } public synchronized TServerConnection getConnection(TServerInstance server) throws TException { TServerConnection result; synchronized (this) { if (server == null) return null; TServerInfo serverInfo = current.get(server.hostPort()); // lock was lost? if (serverInfo == null) return null; // instance changed? if (!serverInfo.instance.equals(server)) return null; result = serverInfo.connection; } return result; } public synchronized Set<TServerInstance> getCurrentServers() { HashSet<TServerInstance> result = new HashSet<TServerInstance>(); for (TServerInfo c : current.values()) { result.add(c.instance); } return result; } public synchronized int size() { return current.size(); } public synchronized TServerInstance find(String serverName) { TServerInfo serverInfo = current.get(serverName); if (serverInfo != null) { return serverInfo.instance; } return null; } public synchronized boolean isOnline(String serverName) { return current.containsKey(serverName); } public synchronized void remove(TServerInstance server) { TServerInfo remove = current.remove(server.hostPort()); if (remove != null) { try { remove.cleanup(); } catch (Exception e) { log.info("error cleaning up connection to server", e); } } log.info("Removing zookeeper lock for " + server); String zpath = ZooUtil.getRoot(instance) + Constants.ZTSERVERS + "/" + server.hostPort(); try { ZooReaderWriter.getRetryingInstance().recursiveDelete(zpath, SKIP); } catch (Exception e) { String msg = "error removing tablet server lock"; log.fatal(msg, e); Halt.halt(msg, -1); } getZooCache().clear(zpath); } }
true
true
public synchronized void scanServers() { try { final Set<TServerInstance> updates = new HashSet<TServerInstance>(); final Set<TServerInstance> doomed = new HashSet<TServerInstance>(); final String path = ZooUtil.getRoot(instance) + Constants.ZTSERVERS; for (String server : getZooCache().getChildren(path)) { // See if we have an async lock in place? TServerInfo info = current.get(server); TServerLockWatcher watcher; ZooLock lock; final String lockPath = path + "/" + server; if (info != null) { // yep: get out the lock/watcher so we can check on it watcher = info.watcher; lock = info.lock; } else { // nope: create a new lock and watcher lock = new ZooLock(lockPath); watcher = new TServerLockWatcher(); lock.lockAsync(watcher, "master".getBytes()); } TServerInstance instance = null; // Did we win the lock yet? if (!lock.isLocked() && !watcher.gotLock && watcher.failureException == null) { // Nope... there's a server out there: is this is a new server? if (info == null) { // Yep: hold onto the information about this server Stat stat = new Stat(); byte[] lockData = ZooLock.getLockData(lockPath, stat); String lockString = new String(lockData == null ? new byte[] {} : lockData); if (lockString.length() > 0 && !lockString.equals("master")) { ServerServices services = new ServerServices(new String(lockData)); InetSocketAddress client = services.getAddress(ServerServices.Service.TSERV_CLIENT); InetSocketAddress addr = AddressUtil.parseAddress(server, Property.TSERV_CLIENTPORT); TServerConnection conn = new TServerConnection(addr); instance = new TServerInstance(client, stat.getEphemeralOwner()); info = new TServerInfo(lock, instance, conn, watcher); current.put(server, info); updates.add(instance); } else { lock.tryToCancelAsyncLockOrUnlock(); } } } else { // Yes... there is no server here any more lock.tryToCancelAsyncLockOrUnlock(); if (info != null) { doomed.add(info.instance); current.remove(server); info.cleanup(); } } } // log.debug("Current: " + current.keySet()); if (!doomed.isEmpty() && !updates.isEmpty()) this.cback.update(this, doomed, updates); } catch (Exception ex) { log.error(ex, ex); } }
public synchronized void scanServers() { try { final Set<TServerInstance> updates = new HashSet<TServerInstance>(); final Set<TServerInstance> doomed = new HashSet<TServerInstance>(); final String path = ZooUtil.getRoot(instance) + Constants.ZTSERVERS; for (String server : getZooCache().getChildren(path)) { // See if we have an async lock in place? TServerInfo info = current.get(server); TServerLockWatcher watcher; ZooLock lock; final String lockPath = path + "/" + server; if (info != null) { // yep: get out the lock/watcher so we can check on it watcher = info.watcher; lock = info.lock; } else { // nope: create a new lock and watcher lock = new ZooLock(lockPath); watcher = new TServerLockWatcher(); lock.lockAsync(watcher, "master".getBytes()); } TServerInstance instance = null; // Did we win the lock yet? if (!lock.isLocked() && !watcher.gotLock && watcher.failureException == null) { // Nope... there's a server out there: is this is a new server? if (info == null) { // Yep: hold onto the information about this server Stat stat = new Stat(); byte[] lockData = ZooLock.getLockData(lockPath, stat); String lockString = new String(lockData == null ? new byte[] {} : lockData); if (lockString.length() > 0 && !lockString.equals("master")) { ServerServices services = new ServerServices(new String(lockData)); InetSocketAddress client = services.getAddress(ServerServices.Service.TSERV_CLIENT); InetSocketAddress addr = AddressUtil.parseAddress(server, Property.TSERV_CLIENTPORT); TServerConnection conn = new TServerConnection(addr); instance = new TServerInstance(client, stat.getEphemeralOwner()); info = new TServerInfo(lock, instance, conn, watcher); current.put(server, info); updates.add(instance); } else { lock.tryToCancelAsyncLockOrUnlock(); } } } else { // Yes... there is no server here any more lock.tryToCancelAsyncLockOrUnlock(); if (info != null) { doomed.add(info.instance); current.remove(server); info.cleanup(); } } } // log.debug("Current: " + current.keySet()); if (!doomed.isEmpty() || !updates.isEmpty()) this.cback.update(this, doomed, updates); } catch (Exception ex) { log.error(ex, ex); } }
diff --git a/mindunit/src/main/java/org/ow2/mind/unit/Launcher.java b/mindunit/src/main/java/org/ow2/mind/unit/Launcher.java index 98e088d..a0abb81 100644 --- a/mindunit/src/main/java/org/ow2/mind/unit/Launcher.java +++ b/mindunit/src/main/java/org/ow2/mind/unit/Launcher.java @@ -1,1410 +1,1410 @@ /** * Copyright (C) 2013 Schneider-Electric * * This file is part of "Mind Compiler" is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: [email protected] * * Authors: Stephane Seyvoz * Contributors: */ package org.ow2.mind.unit; import static org.ow2.mind.adl.membrane.ControllerInterfaceDecorationHelper.setReferencedInterface; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.io.filefilter.FileFilterUtils; import org.objectweb.fractal.adl.ADLException; import org.objectweb.fractal.adl.CompilerError; import org.objectweb.fractal.adl.Definition; import org.objectweb.fractal.adl.Loader; import org.objectweb.fractal.adl.Node; import org.objectweb.fractal.adl.NodeFactory; import org.objectweb.fractal.adl.error.Error; import org.objectweb.fractal.adl.error.GenericErrors; import org.objectweb.fractal.adl.interfaces.Interface; import org.objectweb.fractal.adl.interfaces.InterfaceContainer; import org.objectweb.fractal.adl.merger.MergeException; import org.objectweb.fractal.adl.merger.NodeMerger; import org.objectweb.fractal.adl.types.TypeInterface; import org.objectweb.fractal.adl.types.TypeInterfaceUtil; import org.objectweb.fractal.adl.util.FractalADLLogManager; import org.ow2.mind.ADLCompiler; import org.ow2.mind.ADLCompiler.CompilationStage; import org.ow2.mind.ForceRegenContextHelper; import org.ow2.mind.adl.annotation.predefined.Singleton; import org.ow2.mind.adl.ast.ASTHelper; import org.ow2.mind.adl.ast.Binding; import org.ow2.mind.adl.ast.BindingContainer; import org.ow2.mind.adl.ast.Component; import org.ow2.mind.adl.ast.ComponentContainer; import org.ow2.mind.adl.ast.DefinitionReference; import org.ow2.mind.adl.ast.ImplementationContainer; import org.ow2.mind.adl.ast.MindInterface; import org.ow2.mind.adl.ast.Source; import org.ow2.mind.adl.idl.InterfaceDefinitionDecorationHelper; import org.ow2.mind.adl.membrane.ControllerInterfaceDecorationHelper; import org.ow2.mind.adl.membrane.ast.Controller; import org.ow2.mind.adl.membrane.ast.ControllerContainer; import org.ow2.mind.adl.membrane.ast.ControllerInterface; import org.ow2.mind.adl.membrane.ast.InternalInterfaceContainer; import org.ow2.mind.adl.membrane.ast.MembraneASTHelper; import org.ow2.mind.annotation.AnnotationHelper; import org.ow2.mind.cli.CmdFlag; import org.ow2.mind.cli.CmdOption; import org.ow2.mind.cli.CmdOptionBooleanEvaluator; import org.ow2.mind.cli.CommandLine; import org.ow2.mind.cli.CommandLineOptionExtensionHelper; import org.ow2.mind.cli.CommandOptionHandler; import org.ow2.mind.cli.InvalidCommandLineException; import org.ow2.mind.cli.Options; import org.ow2.mind.cli.OutPathOptionHandler; import org.ow2.mind.cli.PrintStackTraceOptionHandler; import org.ow2.mind.cli.SrcPathOptionHandler; import org.ow2.mind.error.ErrorManager; import org.ow2.mind.idl.IDLLoader; import org.ow2.mind.idl.ast.IDL; import org.ow2.mind.idl.ast.InterfaceDefinition; import org.ow2.mind.idl.ast.Method; import org.ow2.mind.idl.ast.Parameter; import org.ow2.mind.idl.ast.PrimitiveType; import org.ow2.mind.idl.ast.Type; import org.ow2.mind.inject.GuiceModuleExtensionHelper; import org.ow2.mind.io.OutputFileLocator; import org.ow2.mind.plugin.PluginLoaderModule; import org.ow2.mind.plugin.PluginManager; import org.ow2.mind.unit.annotations.Cleanup; import org.ow2.mind.unit.annotations.Init; import org.ow2.mind.unit.annotations.Test; import org.ow2.mind.unit.annotations.TestSuite; import org.ow2.mind.unit.cli.CUnitModeOptionHandler; import org.ow2.mind.unit.model.Suite; import org.ow2.mind.unit.model.TestCase; import org.ow2.mind.unit.model.TestInfo; import org.ow2.mind.unit.st.BasicSuiteSourceGenerator; import org.ow2.mind.unit.st.SuiteSourceGenerator; import com.google.inject.Guice; import com.google.inject.Injector; //import org.ow2.mind.adl.annotations.DumpASTAnnotationProcessor; public class Launcher { protected static final String PROGRAM_NAME_PROPERTY_NAME = "mindunit.launcher.name"; protected static final String ID_PREFIX = "org.ow2.mind.unit.test."; protected final CmdFlag helpOpt = new CmdFlag( ID_PREFIX + "Help", "h", "help", "Print this help and exit"); protected final CmdFlag versionOpt = new CmdFlag( ID_PREFIX + "Version", "v", "version", "Print version number and exit"); protected final CmdFlag extensionPointsListOpt = new CmdFlag( ID_PREFIX + "PrintExtensionPoints", null, "extension-points", "Print the list of available extension points and exit."); protected final Options options = new Options(); protected static Logger logger = FractalADLLogManager.getLogger("mindunit"); // Used for ADL files listing through directory exploration protected List<File> validTestFoldersList = new ArrayList<File>(); // Used by source-path configuration, as it uses a URLClassLoader protected List<URL> urlList = new ArrayList<URL>(); protected List<String> testFolderADLList = new ArrayList<String>(); protected List<Definition> validTestSuitesDefsList = new ArrayList<Definition>(); protected List<Suite> testSuites = new ArrayList<Suite>(); protected Map<Object, Object> compilerContext = new HashMap<Object, Object>(); protected final String adlName = "org.ow2.mind.unit.MindUnitApplication"; // compiler components : protected Injector injector; protected ErrorManager errorManager; protected ADLCompiler adlCompiler; protected NodeFactory nodeFactoryItf; protected SuiteSourceGenerator suiteCSrcGenerator; protected Loader loaderItf; protected IDLLoader idlLoaderItf; protected OutputFileLocator outputFileLocatorItf; protected NodeMerger nodeMergerItf; // default mode private CUnitMode cunit_mode = CUnitMode.AUTOMATED; // build configuration String exeName = null; String rootAdlName = null; protected void init(final String... args) throws InvalidCommandLineException { List<String> testFoldersList; if (logger.isLoggable(Level.CONFIG)) { for (final String arg : args) { logger.config("[arg] " + arg); } } /****** Initialization of the PluginManager Component *******/ final Injector bootStrapPluginManagerInjector = getBootstrapInjector(); final PluginManager pluginManager = bootStrapPluginManagerInjector .getInstance(PluginManager.class); addOptions(pluginManager); // parse arguments to a CommandLine. final CommandLine cmdLine = CommandLine.parseArgs(options, false, args); checkExclusiveGroups(pluginManager, cmdLine); compilerContext .put(CmdOptionBooleanEvaluator.CMD_LINE_CONTEXT_KEY, cmdLine); invokeOptionHandlers(pluginManager, cmdLine, compilerContext); // If help is asked, print it and exit. if (helpOpt.isPresent(cmdLine)) { printHelp(System.out); System.exit(0); } // If version is asked, print it and exit. if (versionOpt.isPresent(cmdLine)) { printVersion(System.out); System.exit(0); } // If the extension points list is asked, print it and exit. if (extensionPointsListOpt.isPresent(cmdLine)) { printExtensionPoints(pluginManager, System.out); System.exit(0); } // get the test folders list testFoldersList = cmdLine.getArguments(); if (!testFoldersList.isEmpty()) { checkAndStoreValidTargetFolders(testFoldersList); } else { logger.severe("You must specify a target directory."); printHelp(System.out); System.exit(1); } // also add the URL of the generated files folder (for the mindUnitSuite.c file to be accessible) createAndAddGeneratedFilesFolderToPathURLs(); // add the computed test folders to the src-path addTestFoldersToPath(); // initialize compiler initInjector(pluginManager, compilerContext); initCompiler(); /* * We need to force regeneration (which leads to lose incremental compilation advantages... :( ) * In order for: * - The Container not to be reloaded with already existing @TestSuite-s, leading to duplicates * (we don't check for consistency yet) * - The @TestSuites not to be reloaded with already added exported test interfaces (with their internal * dual interface, membrane code with stubs when needed, and internal binding...) * (as previously we want to avoid duplicates since we only ADD elements (no diff/remove), and our check * for no outer interface on @TestSuite-s would fail) * - The MindUnitSuiteDefinition has to be regenerated according to @TestSuite-s and @Test-s, * as the C implementation and client interfaces may change according to what we find * - The Container also has already been completed with according bindings at the previous compile time * and we again do not check for consistency * * TODO: consider incremental compilation solutions ? What we only want to reload every time are * the components containing the user content and not the user files (only when there is change there...). * How to discriminate such behavior ? */ ForceRegenContextHelper.setForceRegen(compilerContext, true); } private void constructTestApplication() { // Build list of ADL files listTestFolderADLs(); /* * Then parse/load them (but stay at CHECK_ADL stage). * We obtain a list of Definition-s */ filterValidTestSuites(); if (validTestSuitesDefsList.isEmpty()) { logger.info("No @TestSuite found: exit"); System.exit(0); } /* * Get the test container */ String testContainerName = "org.ow2.mind.unit.MindUnitContainer"; Definition containerDef = getContainerFromName(testContainerName); /* * Add all test cases to the test container as sub-component instances */ logger.info("Adding TestSuites to the MindUnit container"); // create a component instance for each @TestSuite definition and add it to the container addTestSuitesToContainer(containerDef); /* * Load the application */ logger.info("Preparing the host application"); configureApplicationTemplateFromCUnitMode(); /* * Write the C implementation of the "Suite" component with the good * struct referencing all the TestEntries ("run" method) previously found. * Needs to write an according StringTemplate. If we made all TestCases as * @Singleton, we could reference CALLs (no "this") and create according bindings ? * A bit heavy but more architecture-friendly. And may simplify function names calculations. */ logger.info("@TestSuites introspection - Find @Tests - Export test interfaces - Create internal bindings in the @TestSuites"); // prepare to store information needed to create client interfaces on our Suite component Map<String, String> suiteClientItfsNameSignature = new LinkedHashMap<String, String>(); // prepare to store bindings to be created from suite to @TestSuite-s interfaces in the container // note: only targets will be initialized and the source component name will be configured at addBinding time List<Binding> containerBindings = new ArrayList<Binding>(); // build the Suite list for (Definition currDef : validTestSuitesDefsList) // note: at each iteration the lists are growing // note2: the suite definition will be modified to export interfaces containing @Test-s introspectAndPrepareTestSuite(currDef, suiteClientItfsNameSignature, containerBindings); logger.info("Generating Suite source implementation"); try { // injected (see Module and initInjector) suiteCSrcGenerator.visit(testSuites, compilerContext); } catch (ADLException e1) { logger.severe("Error while generating the C source implementation of the Suite ! Cause:"); e1.printStackTrace(); } logger.info("Creating the Suite component"); /* * Create a primitive with the source file as implementation */ Definition mindUnitSuiteDefinition = createSuiteDefinition(); logger.info("Adding unit-gen/mindUnitSuite.c as source"); addCSourceToDefinition(mindUnitSuiteDefinition, BasicSuiteSourceGenerator.getSuiteFileName()); /* * Create the good client interfaces matching the test ones (need to store the latter !) * And create bindings from the suite client interfaces to the @TestSuite-s */ logger.info("Creating client interfaces on the Suite component"); instantiateNeededClientInterfaces(mindUnitSuiteDefinition, suiteClientItfsNameSignature); logger.info("Adding the Suite to the test container"); /* * Then create a "Suite" component instance and add it to the test container */ String mindUnitSuiteInstanceName = addSuiteToContainer(containerDef, mindUnitSuiteDefinition); logger.info("Creating bindings in the container, from generated Suite component interfaces to @TestSuite-s exported test interfaces"); configureAndAddBindingsFromSuiteToTestSuitesInContainer(containerDef, containerBindings, mindUnitSuiteInstanceName); // Debug //DumpASTAnnotationProcessor.showDefinitionContent(containerDef); /* * Then configure target exe name */ String simpleOutput = "mindUnitOutput"; switch (cunit_mode) { case CONSOLE: exeName = "console_" + simpleOutput; break; case GCOV: exeName = "gcov_" + simpleOutput; break; default: case AUTOMATED: exeName = "automated_" + simpleOutput; break; } // The "compile" method is naturally following in the main when we return... } private void configureAndAddBindingsFromSuiteToTestSuitesInContainer( Definition containerDef, List<Binding> containerBindings, String mindUnitSuiteInstanceName) { assert containerDef instanceof BindingContainer; BindingContainer containerDefAsBdgCtr = (BindingContainer) containerDef; for (Binding currBinding : containerBindings) { currBinding.setFromComponent(mindUnitSuiteInstanceName); containerDefAsBdgCtr.addBinding(currBinding); } } private String addSuiteToContainer(Definition containerDef, Definition mindUnitSuiteDefinition) { DefinitionReference mindUnitSuiteDefRef = ASTHelper.newDefinitionReference(nodeFactoryItf, mindUnitSuiteDefinition.getName()); ASTHelper.setResolvedDefinition(mindUnitSuiteDefRef, mindUnitSuiteDefinition); String mindUnitSuiteInstanceName = mindUnitSuiteDefRef.getName().replace(".", "_") + "Instance"; Component mindUnitSuiteComp = ASTHelper.newComponent(nodeFactoryItf, mindUnitSuiteInstanceName, mindUnitSuiteDefRef); mindUnitSuiteComp.setDefinitionReference(mindUnitSuiteDefRef); ASTHelper.setResolvedComponentDefinition(mindUnitSuiteComp, mindUnitSuiteDefinition); ((ComponentContainer) containerDef).addComponent(mindUnitSuiteComp); return mindUnitSuiteInstanceName; } /** * For each pair of "interface name - signature" create a client interface instance on the Suite. * @param mindUnitSuiteDefinition * @param suiteClientItfsNameSignature */ private void instantiateNeededClientInterfaces( Definition mindUnitSuiteDefinition, Map<String, String> suiteClientItfsNameSignature) { // the newPrimitiveDefinitionNode enforces ImplementationContainer.class compatibility InterfaceContainer mindUnitSuiteDefAsItfCtr = (InterfaceContainer) mindUnitSuiteDefinition; for (String currItfInstanceName : suiteClientItfsNameSignature.keySet()) { String currItfSignature = suiteClientItfsNameSignature.get(currItfInstanceName); // we get the InterfaceDefinition from the compiler's cache (instead of creating a new map...) IDL currIDL = null; try { currIDL = idlLoaderItf.load(currItfSignature, compilerContext); } catch (ADLException e) { logger.severe("Could not load " + currItfSignature + " interface ! - Exit to prevent C suite file inconsistency !"); System.exit(1); } MindInterface newSuiteCltItf = ASTHelper.newClientInterfaceNode(nodeFactoryItf, currItfInstanceName, currItfSignature); assert currIDL instanceof InterfaceDefinition; InterfaceDefinitionDecorationHelper.setResolvedInterfaceDefinition(newSuiteCltItf, (InterfaceDefinition) currIDL); mindUnitSuiteDefAsItfCtr.addInterface(newSuiteCltItf); } } /** * Create a Source node with path pointing to the generated C file and add it to the Suite definition. * @param mindUnitSuiteDefinition The Suite definition. * @param cSuiteFileName The name of the C file implementing the Suite. */ private void addCSourceToDefinition(Definition mindUnitSuiteDefinition, String cSuiteFileName) { ImplementationContainer mindUnitSuiteDefAsImplCtr = (ImplementationContainer) mindUnitSuiteDefinition; Source mindUnitSuiteSource = ASTHelper.newSource(nodeFactoryItf); mindUnitSuiteSource.setPath(cSuiteFileName); mindUnitSuiteDefAsImplCtr.addSource(mindUnitSuiteSource); } /** * Create a @Singleton primitive definition: "MindUnitSuiteDefinition" * @return The new (empty) definition */ private Definition createSuiteDefinition() { Definition mindUnitSuiteDefinition = ASTHelper.newPrimitiveDefinitionNode(nodeFactoryItf, "MindUnitSuiteDefinition", (DefinitionReference[]) null); // it has to be a @Singleton for our test "void func(void) { CALL(itf, meth)(); }" functions to be able to enter the Mind world (no 'mind_this') // both following methods are needed since we won't trigger the Singleton Annotation Processor, and the struct definitions rely on both // ASTHelper.isSingleton doesn't check the "singleton decoration" by the way but the Annotation and is used to name singleton instances. ASTHelper.setSingletonDecoration(mindUnitSuiteDefinition); try { AnnotationHelper.addAnnotation(mindUnitSuiteDefinition, new Singleton()); } catch (ADLException e1) { // will never happen since the exception is raised only when you try to put an annotation two times on a definition... which is not our case } // the newPrimitiveDefinitionNode enforces ImplementationContainer.class compatibility return mindUnitSuiteDefinition; } /** * This method introspects the @TestSuite definition to find @Tests and edit the definition to export them. * As an optimization we also prepare content for later processing. * * @param suiteDef The @TestSuite definition containing @Test-s. The definition will be modified to export interfaces containing @Tests and internal bindings to these interfaces will be created. * @param suiteClientItfsNameSignature A list to keep track of the exported interfaces so as to create matching client interfaces on the @Suite component. * @param containerBindings A return parameter in which are added pre-filled bindings (as exported interfaces are found here) to be completed and added to the container later. */ private void introspectAndPrepareTestSuite(Definition suiteDef, Map<String, String> suiteClientItfsNameSignature, List<Binding> containerBindings) { String description = (AnnotationHelper.getAnnotation(suiteDef, TestSuite.class)).value; if (description == null) description = suiteDef.getName(); if (testSuiteHasExternalInterface(suiteDef)) return; if (suiteDef instanceof ComponentContainer) { // handle all sub-components (no recursion) ComponentContainer currCompContainer = (ComponentContainer) suiteDef; for (Component currComp : currCompContainer.getComponents()) { Definition currCompDef = null; try { currCompDef = ASTHelper.getResolvedComponentDefinition(currComp, loaderItf, compilerContext); } catch (ADLException e) { logger.severe("Could not resolve definition of " + suiteDef.getName() + "." + currComp.getName() + " ! - skip"); continue; } if (currCompDef instanceof InterfaceContainer) { // handle sub-component server interfaces, find the list of @Test-annotated methods InterfaceContainer currItfContainer = (InterfaceContainer) currCompDef; for (Interface currItf : currItfContainer.getInterfaces()) { // according to test interfaces we will not only prepare the current TestSuite where needed // with export interfaces, internal bindings, but also prepare the list of parent container bindings // and matching client interfaces info for them to be created on the client Suite Suite currSuite = introspectInterfaceAndPrepareTestSuite(suiteDef, description, currComp, currItf, suiteClientItfsNameSignature, containerBindings); if (currSuite != null) testSuites.add(currSuite); } } } } } /** * Check if the @TestSuite component has external interfaces. Must have none. * @param currDef The TestSuite to be checked. * @return true on error */ private boolean testSuiteHasExternalInterface(Definition currDef) { assert currDef instanceof InterfaceContainer; InterfaceContainer currDefAsItfCtr = (InterfaceContainer) currDef; if (currDefAsItfCtr.getInterfaces().length > 0) { logger.warning("While handling @TestSuite + " + currDef.getName() + ": A test suite must not have any external interface - skipping"); return true; } return false; } private Suite introspectInterfaceAndPrepareTestSuite(Definition suiteDef, String suiteDescription, Component currComp, Interface currItf, Map<String, String> suiteClientItfsNameSignature, List<Binding> containerBindings) { assert suiteDef instanceof BindingContainer; // should be as a default anyway BindingContainer currDefAsBdgCtr = (BindingContainer) suiteDef; assert suiteDef instanceof InterfaceContainer; // should be as a default anyway InterfaceContainer currDefAsItfCtr = (InterfaceContainer) suiteDef; // as we will want to export interfaces and create internal bindings, we need // to create the dual internal interface and have the definition as an InternalInterfaceContainer // inspired from the CompositeInternalInterfaceLoader turnToInternalInterfaceContainer(suiteDef); InternalInterfaceContainer currDefAsInternalItfCtr = (InternalInterfaceContainer) suiteDef; turnToControllerContainer(suiteDef); ControllerContainer currDefAsCtrlCtr = (ControllerContainer) suiteDef; // return Suite suite = null; // useful vars String currItfInitFuncName = null; String currItfInitMethName = null; String currItfCleanupFuncName = null; String currItfCleanupMethName = null; String itfSignature = null; String itfExportName = null; InterfaceDefinition currItfDef = null; String itfName = currItf.getName(); // prepare test cases list - each TestCase is the same as a CU_TestInfo row List<TestCase> currItfValidTestCases = new ArrayList<TestCase>(); // should be everywhere isn't it ? assert currItf instanceof TypeInterface; TypeInterface currTypeItf = (TypeInterface) currItf; // we only are concerned by server interfaces if (!currTypeItf.getRole().equals(TypeInterface.SERVER_ROLE)) return suite; boolean hasTests = false; itfSignature = currTypeItf.getSignature(); // we need interface details IDL currIDL; try { currIDL = idlLoaderItf.load(itfSignature, compilerContext); } catch (ADLException e) { logger.warning("Could not load interface definition " + itfSignature + " - skipping"); return suite; } assert currIDL instanceof InterfaceDefinition; currItfDef = (InterfaceDefinition) currIDL; // handle methods in the interface to find existing @Test, @Init, @Cleanup for (Method currMethod : currItfDef.getMethods()) { boolean isTest = AnnotationHelper.getAnnotation(currMethod, Test.class) != null; boolean isInit = AnnotationHelper.getAnnotation(currMethod, Init.class) != null; boolean isCleanup = AnnotationHelper.getAnnotation(currMethod, Cleanup.class) != null; // Maybe replace the algorithm for a switch-case ? // ^ = XOR if (isTest ^ isInit ^ isCleanup) { if (isTest) { Test testCase = AnnotationHelper.getAnnotation(currMethod, Test.class); String testDescription = null; if (testCase.value == null) testDescription = currMethod.getName(); else testDescription = testCase.value; // return type should be void Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("void"))) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method return type should be \"void\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method arguments must be \"(void)\" - Skipping method"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) String cRelayFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite simple definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // remember which interfaces should be instantiated as clients on the Suite component itfExportName = suiteDef.getName().replace(".", "_") + "_" + currComp.getName() + "_" + currTypeItf.getName(); suiteClientItfsNameSignature.put( itfExportName, itfSignature); // create the test case currItfValidTestCases.add(new TestCase(testDescription, cRelayFuncName, currMethod.getName())); // need to know if we have to export the interface to the surrounding @TestSuite composite hasTests = true; } else if (isInit) { if (currItfInitFuncName != null) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": An @Init method was already defined - Skipping"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) currItfInitFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // simple name for the CALL currItfInitMethName = currMethod.getName(); - // return type should be void + // return type should be int (according to CUnit) Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("int"))) { - logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method return type should be \"int\" - Adding to test list anyway"); + logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Init method return type should be \"int\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { - logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method arguments must be \"(void)\" - Skipping method"); + logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Init method arguments must be \"(void)\" - Skipping method"); continue; } } else if (isCleanup) { if (currItfCleanupFuncName != null) { - logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": An @Init method was already defined - Skipping"); + logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": An @Cleanup method was already defined - Skipping"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) currItfCleanupFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // simple name for the CALL currItfCleanupMethName = currMethod.getName(); - // return type should be void + // return type should be int (according to CUnit) Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("int"))) { - logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method return type should be \"int\" - Adding to test list anyway"); + logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Cleanup method return type should be \"int\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { - logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method arguments must be \"(void)\" - Skipping method"); + logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Cleanup method arguments must be \"(void)\" - Skipping method"); continue; } } } else if (isTest || isInit || isCleanup) { // if the XOR failed and there was at least one annotation it means we had 2 or more... // and we didn't want to raise an error when there was no annotation at all logger.warning("@Init, @Test and @Cleanup are mutually exclusive - Please clarify " + currItfDef.getName() + "#" + currMethod.getName() + " role - Skipping method"); continue; } } // end for all methods /* * Export interface containing @Test to the surrounding @TestSuite * And create the matching internal binding * And prepare the outer binding (in the container) from the generated Suite component to the current @TestSuite */ if (hasTests) { MindInterface newSuiteServerItf = ASTHelper.newServerInterfaceNode(nodeFactoryItf, itfExportName, itfSignature); InterfaceDefinitionDecorationHelper.setResolvedInterfaceDefinition(newSuiteServerItf, currItfDef); //logger.info("Creating " + newSuiteServerItf.getName() + " interface instance for definition " + currDef.getName() + " with interface definition " + currItfDef.getName()); currDefAsItfCtr.addInterface(newSuiteServerItf); // also create the INTERNAL interface // inspired by the CompositeInternalInterfaceLoader TypeInterface newSuiteServerInternalClientItf = getInternalInterface(newSuiteServerItf); InterfaceDefinitionDecorationHelper.setResolvedInterfaceDefinition((TypeInterface) newSuiteServerInternalClientItf, currItfDef); currDefAsInternalItfCtr.addInternalInterface(newSuiteServerInternalClientItf); //-- the following is for the @TestSuite membrane (_ctrl_impl.c) to have // it's "interface delegator" generated ControllerInterfaceDecorationHelper.setDelegatedInterface(newSuiteServerInternalClientItf, newSuiteServerItf); ControllerInterfaceDecorationHelper.setDelegatedInterface(newSuiteServerItf, newSuiteServerInternalClientItf); // add controller Controller ctrl = newControllerNode(); ControllerInterface externalCtrlItf = newControllerInterfaceNode(newSuiteServerItf.getName(), false); ControllerInterface internalCtrlItf = newControllerInterfaceNode(newSuiteServerItf.getName(), true); ctrl.addControllerInterface(externalCtrlItf); ctrl.addControllerInterface(internalCtrlItf); ctrl.addSource(newSourceNode("InterfaceDelegator")); currDefAsCtrlCtr.addController(ctrl); setReferencedInterface(externalCtrlItf, newSuiteServerItf); // -- create internal binding Binding newInternalBinding = newInternalDelegationBinding(itfExportName, currComp, itfName); // add it to the @TestSuite composite definition currDefAsBdgCtr.addBinding(newInternalBinding); //logger.info("Created binding from the surrounding @TestSuite to the sub-component interface"); // -- create outer binding Binding newOuterBinding = newOuterBinding(itfExportName, suiteDef); containerBindings.add(newOuterBinding); } // build the test suite if (!currItfValidTestCases.isEmpty()) { String structName = "_cu_ti_" + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName(); TestInfo currTestInfo = new TestInfo(structName, currItfValidTestCases); // we want to be able to discriminate Mind Suites where multiple tester component instances provide the same interface String fullSuiteDescription = suiteDescription // @TestSuite description + " - " + currComp.getName() // sub-comp + " - " + currTypeItf.getName(); // itf suite = new Suite(fullSuiteDescription, currItfInitFuncName, currItfInitMethName, currItfCleanupFuncName, currItfCleanupMethName, currTestInfo, itfExportName); } return suite; } /** * Create and initialize an internal delegation binding for our test interface, like: * "binds this.exportItf to tester.itf" where "this" is the current TestSuite. * @param itfExportName The exported interface instance name - A detailed name to keep debug easy. * @param currComp The target tester sub-component. * @param itfName The target test interface. * @return A new internal delegation binding. */ private Binding newInternalDelegationBinding(String itfExportName, Component currComp, String itfName) { Binding newInternalBinding = ASTHelper.newBinding(nodeFactoryItf); newInternalBinding.setFromComponent(Binding.THIS_COMPONENT); newInternalBinding.setFromInterface(itfExportName); // TODO: Support collections ? // setFromInterfaceNumber newInternalBinding.setToComponent(currComp.getName()); newInternalBinding.setToInterface(itfName); // TODO: Support collections ? return newInternalBinding; } /** * Create and initialize a binding for which we know the destination (the currently * exported interface) and its source (that will use the same name) but wish * to configure the source later. * @param itfExportName The source and destination interface instance name. * @param currDef The destination TestSuite definition (we'll compute it's instance name using name convention). * @return A new binding instance to be exported to the test container. */ private Binding newOuterBinding(String itfExportName, Definition currDef) { Binding newOuterBinding = ASTHelper.newBinding(nodeFactoryItf); // no "setFromComponent" since it will be completed later with the Suite instance name // itf name won't change though newOuterBinding.setFromInterface(itfExportName); // TODO: Support collections ? // setFromInterfaceNumber // target instance name is convention-based (see addComponents to the container way before in this code) newOuterBinding.setToComponent(currDef.getName().replace(".", "_") + "Instance"); // same in client and server newOuterBinding.setToInterface(itfExportName); // TODO: Support collections ? // setFromInterfaceNumber return newOuterBinding; } /** * According to command-line configured --cunit-mode, load the * application templated with Console or Automated sub-component. * @return The whole application definition to be compiled in the end. */ private void configureApplicationTemplateFromCUnitMode() { //List<Object> loadedDefs = null; rootAdlName = adlName + "<"; String cunitModeUserInput = (String) compilerContext.get(CUnitModeOptionHandler.CUNITMODE_CONTEXT_KEY); if (cunitModeUserInput.equals("console")) { cunit_mode = CUnitMode.CONSOLE; logger.info("Loading container in Console mode"); rootAdlName += "org.ow2.mind.unit.MindUnitConsole"; } else { if (cunitModeUserInput.equals("gcov")) { cunit_mode = CUnitMode.GCOV; logger.info("Loading container in GCov Automated mode"); } else { cunit_mode = CUnitMode.AUTOMATED; logger.info("Loading container in basic Automated mode"); } rootAdlName += "org.ow2.mind.unit.MindUnitAutomated"; } rootAdlName += ">"; /* * If we wanted to check the application container... try { loadedDefs = adlCompiler.compile(rootAdlName, "", CompilationStage.CHECK_ADL, compilerContext); } catch (ADLException e) { if (!errorManager.getErrors().contains(e.getError())) { // the error has not been logged in the error manager, print it. try { errorManager.logError(e.getError()); } catch (final ADLException e2) { System.exit(1); } } } catch (InterruptedException e) { throw new CompilerError(GenericErrors.INTERNAL_ERROR, "Interrupted while executing compilation tasks"); } */ } /** * Instantiate each @TestSuite as a component instance and add the instance to the container. * @param containerDef The container definition to be filled. */ private void addTestSuitesToContainer(Definition containerDef) { for (Definition currTestDef : validTestSuitesDefsList) { DefinitionReference currTestDefRef = ASTHelper.newDefinitionReference(nodeFactoryItf, currTestDef.getName()); ASTHelper.setResolvedDefinition(currTestDefRef, currTestDef); // Instantiate a component of @TestSuite type Component currComp = ASTHelper.newComponent(nodeFactoryItf, currTestDef.getName().replace(".", "_") + "Instance", currTestDefRef); currComp.setDefinitionReference(currTestDefRef); ASTHelper.setResolvedComponentDefinition(currComp, currTestDef); // Add the component to the container ((ComponentContainer) containerDef).addComponent(currComp); } } private Definition getContainerFromName(String testContainerName) { Definition containerDef = null; try { List<Object> containerDefs = adlCompiler.compile(testContainerName, "", CompilationStage.CHECK_ADL, compilerContext); if (containerDefs == null) { logger.severe("Test container could not be loaded - Check availability of the MindUnit components in your runtime folder/source-path !"); System.exit(1); } // should be size 1 and of course a definition... why would it be different ? if (containerDefs.size() > 1) logger.warning("Container loading returned multiple definitions - Using only the first one"); Object containerObj = containerDefs.get(0); if (!(containerObj instanceof Definition)) { logger.severe("Container type wasn't a definition or could not be loaded"); System.exit(1); } containerDef = (Definition) containerDefs.get(0); if (!ASTHelper.isComposite(containerDef)) { logger.severe("Container wasn't a composite ! Please be serious."); System.exit(1); } } catch (ADLException e) { if (!errorManager.getErrors().contains(e.getError())) { // the error has not been logged in the error manager, print it. try { errorManager.logError(e.getError()); } catch (final ADLException e2) { System.exit(1); } } } catch (InterruptedException e) { throw new CompilerError(GenericErrors.INTERNAL_ERROR, "Interrupted while executing compilation tasks"); } return containerDef; } /** * Filters the testFolderADLList of ADLs to keep only the @TestSuite-annotated ones. * Those TestSuite-s Definitions are added to the validTestSuitesDefsList list. */ private void filterValidTestSuites() { for (String currentADL : testFolderADLList) { List<Object> l; try { // Here the components may be reloaded from the incremental compilation cache // if no modification happened l = adlCompiler.compile(currentADL, "", CompilationStage.CHECK_ADL, compilerContext); if (l != null && !l.isEmpty()) { for (Object currObj : l) { if (!(currObj instanceof Definition)) // error case that should never happen logger.warning("Encountered object \"" + currObj.toString() + "\" while handling " + currentADL + " isn't a definition !"); else { // we've got a definition Definition currDef = (Definition) currObj; // Then keep only if annotated with @TestSuite if (AnnotationHelper.getAnnotation(currDef, TestSuite.class) != null) { validTestSuitesDefsList.add(currDef); logger.info("@TestSuite found: " + currDef.getName()); } } } } else logger.info(currentADL + " definition load failed, invalid ADL"); } catch (ADLException e) { logger.info(currentADL + " definition load failed, invalid ADL"); } catch (InterruptedException e) { logger.info(currentADL + " definition load failed, thread was interrupted ! detailed error below: "); e.printStackTrace(); } } } /** * Create "unit-gen" folder in the user-defined output folder, * then add it to the URL list that will be added to the source-path, * for the generated files to be accessible to loading. */ private void createAndAddGeneratedFilesFolderToPathURLs() { File outDir = OutPathOptionHandler.getOutPath(compilerContext); File genFilesDir = new File(outDir.getAbsolutePath(), "unit-gen"); while (!genFilesDir.exists()) genFilesDir.mkdirs(); try { urlList.add(genFilesDir.toURI().toURL()); } catch (MalformedURLException e2) { logger.severe("Could not access to " + outDir.getPath() + "/" + "unit-gen" + " file generation path !"); } } /** * A method to validate the folders the user provided as command-line arguments. * The valid test folders are then stored in 2 fields: * - List<File> validTestFoldersList: Used for ADL files listing through directory exploration * - List<URL> urlList: Used by source-path configuration, as it uses a URLClassLoader * @param testFoldersList The user-defined target tests folders list. */ private void checkAndStoreValidTargetFolders(List<String> testFoldersList) { for (String testFolder : testFoldersList) { final File testDirectory = new File(testFolder); if (!testDirectory.isDirectory() || !testDirectory.canRead()) { logger.severe(String.format("Cannot read source path '%s' - skipped.", testDirectory.getPath())); } else { validTestFoldersList.add(testDirectory); try { URL testDirURL = testDirectory.toURI().toURL(); urlList.add(testDirURL); } catch (final MalformedURLException e) { // will never happen since we already checked File } } } } /** * Inspired from org.ow2.mind.cli.SrcPathOptionHandler. * We extend the original ClassLoader by using it as a parent to a new ClassLoader. * Valid test folders are taken from this class urlList attribute. * We also extend the ClassLoader to the current jar in order to use local (hidden) * resources. */ protected void addTestFoldersToPath() { // get the --src-path elements URLClassLoader srcPathClassLoader = (URLClassLoader) SrcPathOptionHandler.getSourceClassLoader(compilerContext); // URL array of test path, replace the original source class-loader with our enriched one // and use the original source class-loader as parent so as to keep everything intact ClassLoader srcAndTestPathClassLoader = new URLClassLoader(urlList.toArray(new URL[0]), srcPathClassLoader); // replace the original source classloader with the new one in the context compilerContext.remove("classloader"); compilerContext.put("classloader", srcAndTestPathClassLoader); } /** * Inspired by Mindoc's DocumentationIndexGenerator. * @throws IOException */ protected void listTestFolderADLs() { for (final File directory : validTestFoldersList) { try { exploreDirectory(directory.getCanonicalFile(), null); } catch (IOException e) { logger.severe(String.format("Cannot find directory '%s' - skipped.", directory.getPath())); } } } /** * Recursively find ADL files from the root directory. * Inspired by Mindoc's DocumentationIndexGenerator. * FileFilterUtils comes from Apache commons-io. * @throws IOException */ private void exploreDirectory(final File directory, String currentPackage) { if(directory.isHidden()) return; String subPackage = ""; for (final File file : directory.listFiles((FileFilter) FileFilterUtils.suffixFileFilter(".adl"))) { String compName = file.getName(); // remove ".adl" extension compName = compName.substring(0, compName.length() - 4); // add package compName = currentPackage + "." + compName; // save component info testFolderADLList.add(compName); } for (final File subDirectory: directory.listFiles( new FileFilter() { public boolean accept(final File pathname) { return pathname.isDirectory(); } })) { // base folder if (currentPackage == null) subPackage = subDirectory.getName(); else // already in sub-folder subPackage = currentPackage + "." + subDirectory.getName(); // recursion exploreDirectory(subDirectory, subPackage); } } protected Injector getBootstrapInjector() { return Guice.createInjector(new PluginLoaderModule()); } /** * Here we use the standard compiler initialization + A number of internals usually coming later. */ protected void initCompiler() { errorManager = injector.getInstance(ErrorManager.class); adlCompiler = injector.getInstance(ADLCompiler.class); // Our additions nodeFactoryItf = injector.getInstance(NodeFactory.class); suiteCSrcGenerator = injector.getInstance(SuiteSourceGenerator.class); loaderItf = injector.getInstance(Loader.class); idlLoaderItf = injector.getInstance(IDLLoader.class); outputFileLocatorItf = injector.getInstance(OutputFileLocator.class); nodeMergerItf = injector.getInstance(NodeMerger.class); } protected void initInjector(final PluginManager pluginManager, final Map<Object, Object> compilerContext) { injector = Guice.createInjector(GuiceModuleExtensionHelper.getModules( pluginManager, compilerContext)); } public List<Object> compile(final List<Error> errors, final List<Error> warnings) throws InvalidCommandLineException { logger.info("Launching executable compilation (executable name: " + exeName + ")"); final List<Object> result = new ArrayList<Object>(); try { /*final HashMap<Object, Object> contextMap = new HashMap<Object, Object>( compilerContext);*/ // Force compilation stage to be CompilationStage.COMPILE_EXE final List<Object> l = adlCompiler.compile(rootAdlName, exeName, CompilationStage.COMPILE_EXE, compilerContext); if (l != null) result.addAll(l); } catch (final InterruptedException e1) { throw new CompilerError(GenericErrors.INTERNAL_ERROR, "Interrupted while executing compilation tasks"); } catch (final ADLException e1) { if (!errorManager.getErrors().contains(e1.getError())) { // the error has not been logged in the error manager, print it. try { errorManager.logError(e1.getError()); } catch (final ADLException e2) { // ignore } } } if (errors != null) errors.addAll(errorManager.getErrors()); if (warnings != null) warnings.addAll(errorManager.getWarnings()); return result; } protected void addOptions(final PluginManager pluginManagerItf) { options.addOptions(helpOpt, versionOpt, extensionPointsListOpt); options.addOptions(CommandLineOptionExtensionHelper .getCommandOptions(pluginManagerItf)); } protected void checkExclusiveGroups(final PluginManager pluginManagerItf, final CommandLine cmdLine) throws InvalidCommandLineException { final Collection<Set<String>> exclusiveGroups = CommandLineOptionExtensionHelper .getExclusiveGroups(pluginManagerItf); for (final Set<String> exclusiveGroup : exclusiveGroups) { CmdOption opt = null; for (final String id : exclusiveGroup) { final CmdOption opt1 = cmdLine.getOptions().getById(id); if (opt1.isPresent(cmdLine)) { if (opt != null) { throw new InvalidCommandLineException("Options '" + opt.getPrototype() + "' and '" + opt1.getPrototype() + "' cannot be specified simultaneously on the command line.", 1); } opt = opt1; } } } } protected void invokeOptionHandlers(final PluginManager pluginManagerItf, final CommandLine cmdLine, final Map<Object, Object> context) throws InvalidCommandLineException { final List<CmdOption> toBeExecuted = new LinkedList<CmdOption>(cmdLine .getOptions().getOptions()); final Set<String> executedId = new HashSet<String>(toBeExecuted.size()); while (!toBeExecuted.isEmpty()) { final int toBeExecutedSize = toBeExecuted.size(); final Iterator<CmdOption> iter = toBeExecuted.iterator(); while (iter.hasNext()) { final CmdOption option = iter.next(); final List<String> precedenceIds = CommandLineOptionExtensionHelper .getPrecedenceIds(option, pluginManagerItf); if (executedId.containsAll(precedenceIds)) { // task ready to be executed for (final CommandOptionHandler handler : CommandLineOptionExtensionHelper .getHandler(option, pluginManagerItf)) { handler.processCommandOption(option, cmdLine, context); } executedId.add(option.getId()); iter.remove(); } } if (toBeExecutedSize == toBeExecuted.size()) { // nothing has been executed. there is a circular dependency throw new CompilerError(GenericErrors.GENERIC_ERROR, "Circular dependency in command line option handlers: " + toBeExecuted); } } } // --------------------------------------------------------------------------- // Utility methods // --------------------------------------------------------------------------- //-- new utility methods imported from CompositeInterfaceLoader & AbstractMembraneLoader since there is no helper for this protected TypeInterface getInternalInterface(final Interface itf) { if (!(itf instanceof TypeInterface)) { throw new CompilerError(GenericErrors.INTERNAL_ERROR, itf, "Interface is not a TypeInterface"); } // clone external interface to create its dual internal interface. final TypeInterface internalItf; try { internalItf = (TypeInterface) nodeMergerItf.merge( nodeFactoryItf.newNode("internalInterface", TypeInterface.class.getName()), itf, null); internalItf.astSetSource(itf.astGetSource()); } catch (final ClassNotFoundException e) { throw new CompilerError(GenericErrors.INTERNAL_ERROR, e, "Node factory error"); } catch (final MergeException e) { throw new CompilerError(GenericErrors.INTERNAL_ERROR, e, "Node merge error"); } if (TypeInterfaceUtil.isClient(itf)) internalItf.setRole(TypeInterface.SERVER_ROLE); else internalItf.setRole(TypeInterface.CLIENT_ROLE); return internalItf; } protected Controller newControllerNode() { return MembraneASTHelper.newControllerNode(nodeFactoryItf); } protected ControllerInterface newControllerInterfaceNode( final String itfName, final boolean isInternal) { return MembraneASTHelper.newControllerInterfaceNode(nodeFactoryItf, itfName, isInternal); } protected Source newSourceNode(final String path) { return MembraneASTHelper.newSourceNode(nodeFactoryItf, path); } protected ControllerContainer turnToControllerContainer(final Node node) { return MembraneASTHelper.turnToControllerContainer(node, nodeFactoryItf, nodeMergerItf); } protected InternalInterfaceContainer turnToInternalInterfaceContainer( final Node node) { return MembraneASTHelper.turnToInternalInterfaceContainer(node, nodeFactoryItf, nodeMergerItf); } public enum CUnitMode { AUTOMATED, CONSOLE, GCOV } //-- original utility methods private void printExtensionPoints(final PluginManager pluginManager, final PrintStream out) { final Iterable<String> extensionPoints = pluginManager .getExtensionPointNames(); System.out.println("Supported extension points are : "); for (final String extensionPoint : extensionPoints) { System.out.println("\t'" + extensionPoint + "'"); } } protected static void checkDir(final File d) throws InvalidCommandLineException { if (d.exists() && !d.isDirectory()) throw new InvalidCommandLineException("Invalid build directory '" + d.getAbsolutePath() + "' not a directory", 6); } protected String getVersion() { final String pkgVersion = this.getClass().getPackage() .getImplementationVersion(); return (pkgVersion == null) ? "unknown" : pkgVersion; } protected String getProgramName() { return System.getProperty(PROGRAM_NAME_PROPERTY_NAME, getClass().getName()); } protected void printVersion(final PrintStream ps) { ps.println(getProgramName() + " version " + getVersion()); } protected void printHelp(final PrintStream ps) { printUsage(ps); ps.println(); ps.println("Available options are :"); int maxCol = 0; for (final CmdOption opt : options.getOptions()) { final int col = 2 + opt.getPrototype().length(); if (col > maxCol) maxCol = col; } for (final CmdOption opt : options.getOptions()) { final StringBuffer sb = new StringBuffer(" "); sb.append(opt.getPrototype()); while (sb.length() < maxCol) sb.append(' '); sb.append(" ").append(opt.getDescription()); ps.println(sb); } } protected void printUsage(final PrintStream ps) { ps.println("Usage: " + getProgramName() + " [OPTIONS] (<test_path>)+"); ps.println(" where <test_path> is a path where to find test cases to be ran."); } protected void handleException(final InvalidCommandLineException e) { logger.log(Level.FINER, "Caught an InvalidCommandLineException", e); if (PrintStackTraceOptionHandler.getPrintStackTrace(compilerContext)) { e.printStackTrace(); } else { System.err.println(e.getMessage()); printHelp(System.err); System.exit(e.getExitValue()); } } /** * Entry point. * * @param args */ public static void main(final String... args) { final Launcher l = new Launcher(); try { l.init(args); l.constructTestApplication(); l.compile(null, null); } catch (final InvalidCommandLineException e) { l.handleException(e); } if (!l.errorManager.getErrors().isEmpty()) System.exit(1); } public static void nonExitMain(final String... args) throws InvalidCommandLineException, ADLException { nonExitMain(null, null, args); } public static void nonExitMain(final List<Error> errors, final List<Error> warnings, final String... args) throws InvalidCommandLineException, ADLException { final Launcher l = new Launcher(); l.init(args); l.constructTestApplication(); l.compile(errors, warnings); } }
false
true
private Suite introspectInterfaceAndPrepareTestSuite(Definition suiteDef, String suiteDescription, Component currComp, Interface currItf, Map<String, String> suiteClientItfsNameSignature, List<Binding> containerBindings) { assert suiteDef instanceof BindingContainer; // should be as a default anyway BindingContainer currDefAsBdgCtr = (BindingContainer) suiteDef; assert suiteDef instanceof InterfaceContainer; // should be as a default anyway InterfaceContainer currDefAsItfCtr = (InterfaceContainer) suiteDef; // as we will want to export interfaces and create internal bindings, we need // to create the dual internal interface and have the definition as an InternalInterfaceContainer // inspired from the CompositeInternalInterfaceLoader turnToInternalInterfaceContainer(suiteDef); InternalInterfaceContainer currDefAsInternalItfCtr = (InternalInterfaceContainer) suiteDef; turnToControllerContainer(suiteDef); ControllerContainer currDefAsCtrlCtr = (ControllerContainer) suiteDef; // return Suite suite = null; // useful vars String currItfInitFuncName = null; String currItfInitMethName = null; String currItfCleanupFuncName = null; String currItfCleanupMethName = null; String itfSignature = null; String itfExportName = null; InterfaceDefinition currItfDef = null; String itfName = currItf.getName(); // prepare test cases list - each TestCase is the same as a CU_TestInfo row List<TestCase> currItfValidTestCases = new ArrayList<TestCase>(); // should be everywhere isn't it ? assert currItf instanceof TypeInterface; TypeInterface currTypeItf = (TypeInterface) currItf; // we only are concerned by server interfaces if (!currTypeItf.getRole().equals(TypeInterface.SERVER_ROLE)) return suite; boolean hasTests = false; itfSignature = currTypeItf.getSignature(); // we need interface details IDL currIDL; try { currIDL = idlLoaderItf.load(itfSignature, compilerContext); } catch (ADLException e) { logger.warning("Could not load interface definition " + itfSignature + " - skipping"); return suite; } assert currIDL instanceof InterfaceDefinition; currItfDef = (InterfaceDefinition) currIDL; // handle methods in the interface to find existing @Test, @Init, @Cleanup for (Method currMethod : currItfDef.getMethods()) { boolean isTest = AnnotationHelper.getAnnotation(currMethod, Test.class) != null; boolean isInit = AnnotationHelper.getAnnotation(currMethod, Init.class) != null; boolean isCleanup = AnnotationHelper.getAnnotation(currMethod, Cleanup.class) != null; // Maybe replace the algorithm for a switch-case ? // ^ = XOR if (isTest ^ isInit ^ isCleanup) { if (isTest) { Test testCase = AnnotationHelper.getAnnotation(currMethod, Test.class); String testDescription = null; if (testCase.value == null) testDescription = currMethod.getName(); else testDescription = testCase.value; // return type should be void Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("void"))) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method return type should be \"void\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method arguments must be \"(void)\" - Skipping method"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) String cRelayFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite simple definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // remember which interfaces should be instantiated as clients on the Suite component itfExportName = suiteDef.getName().replace(".", "_") + "_" + currComp.getName() + "_" + currTypeItf.getName(); suiteClientItfsNameSignature.put( itfExportName, itfSignature); // create the test case currItfValidTestCases.add(new TestCase(testDescription, cRelayFuncName, currMethod.getName())); // need to know if we have to export the interface to the surrounding @TestSuite composite hasTests = true; } else if (isInit) { if (currItfInitFuncName != null) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": An @Init method was already defined - Skipping"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) currItfInitFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // simple name for the CALL currItfInitMethName = currMethod.getName(); // return type should be void Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("int"))) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method return type should be \"int\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method arguments must be \"(void)\" - Skipping method"); continue; } } else if (isCleanup) { if (currItfCleanupFuncName != null) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": An @Init method was already defined - Skipping"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) currItfCleanupFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // simple name for the CALL currItfCleanupMethName = currMethod.getName(); // return type should be void Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("int"))) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method return type should be \"int\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method arguments must be \"(void)\" - Skipping method"); continue; } } } else if (isTest || isInit || isCleanup) { // if the XOR failed and there was at least one annotation it means we had 2 or more... // and we didn't want to raise an error when there was no annotation at all logger.warning("@Init, @Test and @Cleanup are mutually exclusive - Please clarify " + currItfDef.getName() + "#" + currMethod.getName() + " role - Skipping method"); continue; } } // end for all methods /* * Export interface containing @Test to the surrounding @TestSuite * And create the matching internal binding * And prepare the outer binding (in the container) from the generated Suite component to the current @TestSuite */ if (hasTests) { MindInterface newSuiteServerItf = ASTHelper.newServerInterfaceNode(nodeFactoryItf, itfExportName, itfSignature); InterfaceDefinitionDecorationHelper.setResolvedInterfaceDefinition(newSuiteServerItf, currItfDef); //logger.info("Creating " + newSuiteServerItf.getName() + " interface instance for definition " + currDef.getName() + " with interface definition " + currItfDef.getName()); currDefAsItfCtr.addInterface(newSuiteServerItf); // also create the INTERNAL interface // inspired by the CompositeInternalInterfaceLoader TypeInterface newSuiteServerInternalClientItf = getInternalInterface(newSuiteServerItf); InterfaceDefinitionDecorationHelper.setResolvedInterfaceDefinition((TypeInterface) newSuiteServerInternalClientItf, currItfDef); currDefAsInternalItfCtr.addInternalInterface(newSuiteServerInternalClientItf); //-- the following is for the @TestSuite membrane (_ctrl_impl.c) to have // it's "interface delegator" generated ControllerInterfaceDecorationHelper.setDelegatedInterface(newSuiteServerInternalClientItf, newSuiteServerItf); ControllerInterfaceDecorationHelper.setDelegatedInterface(newSuiteServerItf, newSuiteServerInternalClientItf); // add controller Controller ctrl = newControllerNode(); ControllerInterface externalCtrlItf = newControllerInterfaceNode(newSuiteServerItf.getName(), false); ControllerInterface internalCtrlItf = newControllerInterfaceNode(newSuiteServerItf.getName(), true); ctrl.addControllerInterface(externalCtrlItf); ctrl.addControllerInterface(internalCtrlItf); ctrl.addSource(newSourceNode("InterfaceDelegator")); currDefAsCtrlCtr.addController(ctrl); setReferencedInterface(externalCtrlItf, newSuiteServerItf); // -- create internal binding Binding newInternalBinding = newInternalDelegationBinding(itfExportName, currComp, itfName); // add it to the @TestSuite composite definition currDefAsBdgCtr.addBinding(newInternalBinding); //logger.info("Created binding from the surrounding @TestSuite to the sub-component interface"); // -- create outer binding Binding newOuterBinding = newOuterBinding(itfExportName, suiteDef); containerBindings.add(newOuterBinding); } // build the test suite if (!currItfValidTestCases.isEmpty()) { String structName = "_cu_ti_" + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName(); TestInfo currTestInfo = new TestInfo(structName, currItfValidTestCases); // we want to be able to discriminate Mind Suites where multiple tester component instances provide the same interface String fullSuiteDescription = suiteDescription // @TestSuite description + " - " + currComp.getName() // sub-comp + " - " + currTypeItf.getName(); // itf suite = new Suite(fullSuiteDescription, currItfInitFuncName, currItfInitMethName, currItfCleanupFuncName, currItfCleanupMethName, currTestInfo, itfExportName); } return suite; }
private Suite introspectInterfaceAndPrepareTestSuite(Definition suiteDef, String suiteDescription, Component currComp, Interface currItf, Map<String, String> suiteClientItfsNameSignature, List<Binding> containerBindings) { assert suiteDef instanceof BindingContainer; // should be as a default anyway BindingContainer currDefAsBdgCtr = (BindingContainer) suiteDef; assert suiteDef instanceof InterfaceContainer; // should be as a default anyway InterfaceContainer currDefAsItfCtr = (InterfaceContainer) suiteDef; // as we will want to export interfaces and create internal bindings, we need // to create the dual internal interface and have the definition as an InternalInterfaceContainer // inspired from the CompositeInternalInterfaceLoader turnToInternalInterfaceContainer(suiteDef); InternalInterfaceContainer currDefAsInternalItfCtr = (InternalInterfaceContainer) suiteDef; turnToControllerContainer(suiteDef); ControllerContainer currDefAsCtrlCtr = (ControllerContainer) suiteDef; // return Suite suite = null; // useful vars String currItfInitFuncName = null; String currItfInitMethName = null; String currItfCleanupFuncName = null; String currItfCleanupMethName = null; String itfSignature = null; String itfExportName = null; InterfaceDefinition currItfDef = null; String itfName = currItf.getName(); // prepare test cases list - each TestCase is the same as a CU_TestInfo row List<TestCase> currItfValidTestCases = new ArrayList<TestCase>(); // should be everywhere isn't it ? assert currItf instanceof TypeInterface; TypeInterface currTypeItf = (TypeInterface) currItf; // we only are concerned by server interfaces if (!currTypeItf.getRole().equals(TypeInterface.SERVER_ROLE)) return suite; boolean hasTests = false; itfSignature = currTypeItf.getSignature(); // we need interface details IDL currIDL; try { currIDL = idlLoaderItf.load(itfSignature, compilerContext); } catch (ADLException e) { logger.warning("Could not load interface definition " + itfSignature + " - skipping"); return suite; } assert currIDL instanceof InterfaceDefinition; currItfDef = (InterfaceDefinition) currIDL; // handle methods in the interface to find existing @Test, @Init, @Cleanup for (Method currMethod : currItfDef.getMethods()) { boolean isTest = AnnotationHelper.getAnnotation(currMethod, Test.class) != null; boolean isInit = AnnotationHelper.getAnnotation(currMethod, Init.class) != null; boolean isCleanup = AnnotationHelper.getAnnotation(currMethod, Cleanup.class) != null; // Maybe replace the algorithm for a switch-case ? // ^ = XOR if (isTest ^ isInit ^ isCleanup) { if (isTest) { Test testCase = AnnotationHelper.getAnnotation(currMethod, Test.class); String testDescription = null; if (testCase.value == null) testDescription = currMethod.getName(); else testDescription = testCase.value; // return type should be void Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("void"))) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method return type should be \"void\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Test method arguments must be \"(void)\" - Skipping method"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) String cRelayFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite simple definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // remember which interfaces should be instantiated as clients on the Suite component itfExportName = suiteDef.getName().replace(".", "_") + "_" + currComp.getName() + "_" + currTypeItf.getName(); suiteClientItfsNameSignature.put( itfExportName, itfSignature); // create the test case currItfValidTestCases.add(new TestCase(testDescription, cRelayFuncName, currMethod.getName())); // need to know if we have to export the interface to the surrounding @TestSuite composite hasTests = true; } else if (isInit) { if (currItfInitFuncName != null) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": An @Init method was already defined - Skipping"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) currItfInitFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // simple name for the CALL currItfInitMethName = currMethod.getName(); // return type should be int (according to CUnit) Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("int"))) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Init method return type should be \"int\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Init method arguments must be \"(void)\" - Skipping method"); continue; } } else if (isCleanup) { if (currItfCleanupFuncName != null) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": An @Cleanup method was already defined - Skipping"); continue; } // compute the relay function name we'll provide to CUnit that will CALL the test // we compute complex names to avoid clashes (as a tester is not needed to be @Singleton) currItfCleanupFuncName = "__cunit_relay_" // prefix + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName() // interface instance + "_" + currMethod.getName(); // method instance // simple name for the CALL currItfCleanupMethName = currMethod.getName(); // return type should be int (according to CUnit) Type methodType = currMethod.getType(); if (!(methodType instanceof PrimitiveType && ((PrimitiveType) methodType).getName().equals("int"))) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Cleanup method return type should be \"int\" - Adding to test list anyway"); } // argument must be void ( = no argument) Parameter[] methodParams = currMethod.getParameters(); if (methodParams.length > 0) { logger.warning("While handling " + currItfDef.getName() + "#" + currMethod.getName() + ": @Cleanup method arguments must be \"(void)\" - Skipping method"); continue; } } } else if (isTest || isInit || isCleanup) { // if the XOR failed and there was at least one annotation it means we had 2 or more... // and we didn't want to raise an error when there was no annotation at all logger.warning("@Init, @Test and @Cleanup are mutually exclusive - Please clarify " + currItfDef.getName() + "#" + currMethod.getName() + " role - Skipping method"); continue; } } // end for all methods /* * Export interface containing @Test to the surrounding @TestSuite * And create the matching internal binding * And prepare the outer binding (in the container) from the generated Suite component to the current @TestSuite */ if (hasTests) { MindInterface newSuiteServerItf = ASTHelper.newServerInterfaceNode(nodeFactoryItf, itfExportName, itfSignature); InterfaceDefinitionDecorationHelper.setResolvedInterfaceDefinition(newSuiteServerItf, currItfDef); //logger.info("Creating " + newSuiteServerItf.getName() + " interface instance for definition " + currDef.getName() + " with interface definition " + currItfDef.getName()); currDefAsItfCtr.addInterface(newSuiteServerItf); // also create the INTERNAL interface // inspired by the CompositeInternalInterfaceLoader TypeInterface newSuiteServerInternalClientItf = getInternalInterface(newSuiteServerItf); InterfaceDefinitionDecorationHelper.setResolvedInterfaceDefinition((TypeInterface) newSuiteServerInternalClientItf, currItfDef); currDefAsInternalItfCtr.addInternalInterface(newSuiteServerInternalClientItf); //-- the following is for the @TestSuite membrane (_ctrl_impl.c) to have // it's "interface delegator" generated ControllerInterfaceDecorationHelper.setDelegatedInterface(newSuiteServerInternalClientItf, newSuiteServerItf); ControllerInterfaceDecorationHelper.setDelegatedInterface(newSuiteServerItf, newSuiteServerInternalClientItf); // add controller Controller ctrl = newControllerNode(); ControllerInterface externalCtrlItf = newControllerInterfaceNode(newSuiteServerItf.getName(), false); ControllerInterface internalCtrlItf = newControllerInterfaceNode(newSuiteServerItf.getName(), true); ctrl.addControllerInterface(externalCtrlItf); ctrl.addControllerInterface(internalCtrlItf); ctrl.addSource(newSourceNode("InterfaceDelegator")); currDefAsCtrlCtr.addController(ctrl); setReferencedInterface(externalCtrlItf, newSuiteServerItf); // -- create internal binding Binding newInternalBinding = newInternalDelegationBinding(itfExportName, currComp, itfName); // add it to the @TestSuite composite definition currDefAsBdgCtr.addBinding(newInternalBinding); //logger.info("Created binding from the surrounding @TestSuite to the sub-component interface"); // -- create outer binding Binding newOuterBinding = newOuterBinding(itfExportName, suiteDef); containerBindings.add(newOuterBinding); } // build the test suite if (!currItfValidTestCases.isEmpty()) { String structName = "_cu_ti_" + suiteDef.getName().substring(suiteDef.getName().lastIndexOf(".") + 1).replace(".", "_") // the @TestSuite definition name + "_" + currComp.getName() // sub-component instance + "_" + currTypeItf.getName(); TestInfo currTestInfo = new TestInfo(structName, currItfValidTestCases); // we want to be able to discriminate Mind Suites where multiple tester component instances provide the same interface String fullSuiteDescription = suiteDescription // @TestSuite description + " - " + currComp.getName() // sub-comp + " - " + currTypeItf.getName(); // itf suite = new Suite(fullSuiteDescription, currItfInitFuncName, currItfInitMethName, currItfCleanupFuncName, currItfCleanupMethName, currTestInfo, itfExportName); } return suite; }
diff --git a/src/org/omegat/core/machinetranslators/Google2Translate.java b/src/org/omegat/core/machinetranslators/Google2Translate.java index 2ed3b10a..db524c90 100644 --- a/src/org/omegat/core/machinetranslators/Google2Translate.java +++ b/src/org/omegat/core/machinetranslators/Google2Translate.java @@ -1,144 +1,149 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2010 Alex Buloichik, Didier Briel 2011 Briac Pilpre, Alex Buloichik Home page: http://www.omegat.org/ Support center: http://groups.yahoo.com/group/OmegaT/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA **************************************************************************/ package org.omegat.core.machinetranslators; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.omegat.util.Language; import org.omegat.util.OStrings; import org.omegat.util.PatternConsts; import org.omegat.util.Preferences; import org.omegat.util.WikiGet; /** * Support of Google Translate API v.2 machine translation. * https://code.google.com/apis/language/translate/v2/getting_started.html * * @author Alex Buloichik ([email protected]) * @author Didier Briel * @author Briac Pilpre */ public class Google2Translate extends BaseTranslate { protected static final String GT_URL = "https://www.googleapis.com/language/translate/v2"; protected static final Pattern RE_UNICODE = Pattern.compile("\\\\u([0-9A-Fa-f]{4})"); protected static final Pattern RE_HTML = Pattern.compile("&#([0-9]+);"); @Override protected String getPreferenceName() { return Preferences.ALLOW_GOOGLE2_TRANSLATE; } public String getName() { return OStrings.getString("MT_ENGINE_GOOGLE2"); } @Override protected String translate(Language sLang, Language tLang, String text) throws Exception { String trText = text.length() > 5000 ? text.substring(0, 4997) + "..." : text; String targetLang = tLang.getLanguageCode(); // Differentiate in target between simplified and traditional Chinese if ((tLang.getLanguage().compareToIgnoreCase("zh-cn") == 0) || (tLang.getLanguage().compareToIgnoreCase("zh-tw") == 0)) targetLang = tLang.getLanguage(); else if ((tLang.getLanguage().compareToIgnoreCase("zh-hk") == 0)) targetLang = "ZH-TW"; // Google doesn't recognize ZH-HK String googleKey = System.getProperty("google.api.key"); Map<String, String> params = new TreeMap<String, String>(); params.put("key", googleKey); params.put("source", sLang.getLanguageCode()); params.put("target", targetLang); params.put("q", trText); Map<String, String> headers = new TreeMap<String, String>(); headers.put("X-HTTP-Method-Override", "GET"); - String v = WikiGet.post(GT_URL, params, headers); + String v; + try { + v = WikiGet.post(GT_URL, params, headers); + } catch (IOException e) { + return e.getLocalizedMessage(); + } while (true) { Matcher m = RE_UNICODE.matcher(v); if (!m.find()) { break; } String g = m.group(); char c = (char) Integer.parseInt(m.group(1), 16); v = v.replace(g, Character.toString(c)); } v = v.replace("&quot;", "&#34;"); v = v.replace("&nbsp;", "&#160;"); v = v.replace("&amp;", "&#38;"); while (true) { Matcher m = RE_HTML.matcher(v); if (!m.find()) { break; } String g = m.group(); char c = (char) Integer.parseInt(m.group(1)); v = v.replace(g, Character.toString(c)); } Pattern pattern = java.util.regex.Pattern.compile("\\{\\s*\"translatedText\"\\s*:\\s*\"(.*?)\"\\s*\\s*\\}\\s*]"); Matcher matcher = pattern.matcher(v); boolean matchFound = matcher.find(); String tr = ""; if (matchFound) { tr = matcher.group(1); } // Attempt to clean spaces added by GT // Spaces after Matcher tag = PatternConsts.OMEGAT_TAG_SPACE.matcher(tr); while (tag.find()) { String searchTag = tag.group(); if (text.indexOf(searchTag) == -1) { // The tag didn't appear with a // trailing space in the source text String replacement = searchTag.substring(0, searchTag.length() - 1); tr = tr.replace(searchTag, replacement); } } // Spaces before tag = PatternConsts.SPACE_OMEGAT_TAG.matcher(tr); while (tag.find()) { String searchTag = tag.group(); if (text.indexOf(searchTag) == -1) { // The tag didn't appear with a // leading space in the source text String replacement = searchTag.substring(1, searchTag.length()); tr = tr.replace(searchTag, replacement); } } return tr; } }
true
true
protected String translate(Language sLang, Language tLang, String text) throws Exception { String trText = text.length() > 5000 ? text.substring(0, 4997) + "..." : text; String targetLang = tLang.getLanguageCode(); // Differentiate in target between simplified and traditional Chinese if ((tLang.getLanguage().compareToIgnoreCase("zh-cn") == 0) || (tLang.getLanguage().compareToIgnoreCase("zh-tw") == 0)) targetLang = tLang.getLanguage(); else if ((tLang.getLanguage().compareToIgnoreCase("zh-hk") == 0)) targetLang = "ZH-TW"; // Google doesn't recognize ZH-HK String googleKey = System.getProperty("google.api.key"); Map<String, String> params = new TreeMap<String, String>(); params.put("key", googleKey); params.put("source", sLang.getLanguageCode()); params.put("target", targetLang); params.put("q", trText); Map<String, String> headers = new TreeMap<String, String>(); headers.put("X-HTTP-Method-Override", "GET"); String v = WikiGet.post(GT_URL, params, headers); while (true) { Matcher m = RE_UNICODE.matcher(v); if (!m.find()) { break; } String g = m.group(); char c = (char) Integer.parseInt(m.group(1), 16); v = v.replace(g, Character.toString(c)); } v = v.replace("&quot;", "&#34;"); v = v.replace("&nbsp;", "&#160;"); v = v.replace("&amp;", "&#38;"); while (true) { Matcher m = RE_HTML.matcher(v); if (!m.find()) { break; } String g = m.group(); char c = (char) Integer.parseInt(m.group(1)); v = v.replace(g, Character.toString(c)); } Pattern pattern = java.util.regex.Pattern.compile("\\{\\s*\"translatedText\"\\s*:\\s*\"(.*?)\"\\s*\\s*\\}\\s*]"); Matcher matcher = pattern.matcher(v); boolean matchFound = matcher.find(); String tr = ""; if (matchFound) { tr = matcher.group(1); } // Attempt to clean spaces added by GT // Spaces after Matcher tag = PatternConsts.OMEGAT_TAG_SPACE.matcher(tr); while (tag.find()) { String searchTag = tag.group(); if (text.indexOf(searchTag) == -1) { // The tag didn't appear with a // trailing space in the source text String replacement = searchTag.substring(0, searchTag.length() - 1); tr = tr.replace(searchTag, replacement); } } // Spaces before tag = PatternConsts.SPACE_OMEGAT_TAG.matcher(tr); while (tag.find()) { String searchTag = tag.group(); if (text.indexOf(searchTag) == -1) { // The tag didn't appear with a // leading space in the source text String replacement = searchTag.substring(1, searchTag.length()); tr = tr.replace(searchTag, replacement); } } return tr; }
protected String translate(Language sLang, Language tLang, String text) throws Exception { String trText = text.length() > 5000 ? text.substring(0, 4997) + "..." : text; String targetLang = tLang.getLanguageCode(); // Differentiate in target between simplified and traditional Chinese if ((tLang.getLanguage().compareToIgnoreCase("zh-cn") == 0) || (tLang.getLanguage().compareToIgnoreCase("zh-tw") == 0)) targetLang = tLang.getLanguage(); else if ((tLang.getLanguage().compareToIgnoreCase("zh-hk") == 0)) targetLang = "ZH-TW"; // Google doesn't recognize ZH-HK String googleKey = System.getProperty("google.api.key"); Map<String, String> params = new TreeMap<String, String>(); params.put("key", googleKey); params.put("source", sLang.getLanguageCode()); params.put("target", targetLang); params.put("q", trText); Map<String, String> headers = new TreeMap<String, String>(); headers.put("X-HTTP-Method-Override", "GET"); String v; try { v = WikiGet.post(GT_URL, params, headers); } catch (IOException e) { return e.getLocalizedMessage(); } while (true) { Matcher m = RE_UNICODE.matcher(v); if (!m.find()) { break; } String g = m.group(); char c = (char) Integer.parseInt(m.group(1), 16); v = v.replace(g, Character.toString(c)); } v = v.replace("&quot;", "&#34;"); v = v.replace("&nbsp;", "&#160;"); v = v.replace("&amp;", "&#38;"); while (true) { Matcher m = RE_HTML.matcher(v); if (!m.find()) { break; } String g = m.group(); char c = (char) Integer.parseInt(m.group(1)); v = v.replace(g, Character.toString(c)); } Pattern pattern = java.util.regex.Pattern.compile("\\{\\s*\"translatedText\"\\s*:\\s*\"(.*?)\"\\s*\\s*\\}\\s*]"); Matcher matcher = pattern.matcher(v); boolean matchFound = matcher.find(); String tr = ""; if (matchFound) { tr = matcher.group(1); } // Attempt to clean spaces added by GT // Spaces after Matcher tag = PatternConsts.OMEGAT_TAG_SPACE.matcher(tr); while (tag.find()) { String searchTag = tag.group(); if (text.indexOf(searchTag) == -1) { // The tag didn't appear with a // trailing space in the source text String replacement = searchTag.substring(0, searchTag.length() - 1); tr = tr.replace(searchTag, replacement); } } // Spaces before tag = PatternConsts.SPACE_OMEGAT_TAG.matcher(tr); while (tag.find()) { String searchTag = tag.group(); if (text.indexOf(searchTag) == -1) { // The tag didn't appear with a // leading space in the source text String replacement = searchTag.substring(1, searchTag.length()); tr = tr.replace(searchTag, replacement); } } return tr; }
diff --git a/src/java/org/wings/session/SessionServlet.java b/src/java/org/wings/session/SessionServlet.java index 14c4e74e..923d7f63 100644 --- a/src/java/org/wings/session/SessionServlet.java +++ b/src/java/org/wings/session/SessionServlet.java @@ -1,683 +1,683 @@ /* * $Id$ * Copyright 2000,2005 wingS development team. * * This file is part of wingS (http://www.j-wings.org). * * wingS 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. * * Please see COPYING for the complete licence. */ package org.wings.session; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wings.*; import org.wings.event.ExitVetoException; import org.wings.event.SRequestEvent; import org.wings.externalizer.ExternalizeManager; import org.wings.externalizer.ExternalizedResource; import org.wings.io.Device; import org.wings.io.DeviceFactory; import org.wings.io.ServletDevice; import org.wings.resource.DynamicCodeResource; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Enumeration; import java.util.Locale; import java.util.Arrays; /** * The servlet engine creates for each user a new HttpSession. This * HttpSession can be accessed by all Serlvets running in the engine. A * WingServlet creates one wings SessionServlet per HTTPSession and stores * it in its context. * <p>As the SessionServlets acts as Wrapper for the WingsServlet, you can * access from there as used the ServletContext and the HttpSession. * Additionally the SessionServlet containts also the wingS-Session with * all important services and the superordinated SFrame. To this SFrame all * wings-Components and hence the complete application state is attached. * The developer can access from any place via the SessionManager a * reference to the wingS-Session. Additionally the SessionServlet * provides access to the all containing HttpSession. * * @author <a href="mailto:[email protected]">Armin Haaf</a> * @version $Revision$ */ final class SessionServlet extends HttpServlet implements HttpSessionBindingListener { private final transient static Log log = LogFactory.getLog(SessionServlet.class); /** * The parent {@link WingServlet} */ protected transient HttpServlet parent = this; /** * This should be a resource .. */ protected String errorTemplateFile; /** * The session. */ private Session session; private boolean firstRequest = true; /** * Default constructor. */ protected SessionServlet() { } /** * Sets the parent servlet contianint this wings session * servlet (WingsServlet, delegating its requests to the SessionServlet). */ protected final void setParent(HttpServlet p) { if (p != null) parent = p; } public final Session getSession() { return session; } /** * Overrides the session set for setLocaleFromHeader by a request parameter. * Hence you can force the wings session to adopt the clients Locale. */ public final void setLocaleFromHeader(String[] args) { if (args == null) return; for (int i = 0; i < args.length; i++) { try { getSession().setLocaleFromHeader(Boolean.valueOf(args[i]).booleanValue()); } catch (Exception e) { log.error("setLocaleFromHeader", e); } } } /** * The Locale of the current wings session servlet is determined by * the locale transmitted by the browser. The request parameter * <PRE>LocaleFromHeader</PRE> can override the behaviour * of a wings session servlet to adopt the clients browsers Locale. * * @param req The request to determine the local from. */ protected final void handleLocale(HttpServletRequest req) { setLocaleFromHeader(req.getParameterValues("LocaleFromHeader")); if (getSession().getLocaleFromHeader()) { for (Enumeration en = req.getLocales(); en.hasMoreElements();) { Locale locale = (Locale) en.nextElement(); try { getSession().setLocale(locale); return; } catch (Exception ex) { log.warn("locale not supported " + locale); } // end of try-catch } // end of for () } } // jetzt kommen alle Servlet Methoden, die an den parent deligiert // werden public ServletContext getServletContext() { if (parent != this) return parent.getServletContext(); else return super.getServletContext(); } public String getInitParameter(String name) { if (parent != this) return parent.getInitParameter(name); else return super.getInitParameter(name); } public Enumeration getInitParameterNames() { if (parent != this) return parent.getInitParameterNames(); else return super.getInitParameterNames(); } /** * Delegates log messages to the according WingsServlet or alternativly * to the HttpServlet logger. * * @param msg The logmessage */ public void log(String msg) { if (parent != this) parent.log(msg); else super.log(msg); } public String getServletInfo() { if (parent != this) return parent.getServletInfo(); else return super.getServletInfo(); } public ServletConfig getServletConfig() { if (parent != this) return parent.getServletConfig(); else return super.getServletConfig(); } // bis hierhin /** * The error template which should be presented on any uncaught Exceptions can be set * via a property <code>wings.error.template</code> in the web.xml file. */ protected void initErrorTemplate(ServletConfig config) { if (errorTemplateFile == null) { errorTemplateFile = config.getInitParameter("wings.error.template"); } } /** * init */ public final void init(ServletConfig config, HttpServletRequest request, HttpServletResponse response) throws ServletException { try { initErrorTemplate(config); session = new Session(); SessionManager.setSession(session); // set request.url in session, if used in constructor of wings main classs if (request.isRequestedSessionIdValid()) { // this will fire an event, if the encoding has changed .. ((PropertyService) session).setProperty("request.url", new RequestURL("", getSessionEncoding(response))); } session.init(config, request); try { String mainClassName = config.getInitParameter("wings.mainclass"); Class mainClass = null; try { mainClass = Class.forName(mainClassName, true, Thread.currentThread() .getContextClassLoader()); } catch (ClassNotFoundException e) { // fallback, in case the servlet container fails to set the // context class loader. mainClass = Class.forName(mainClassName); } Object main = mainClass.newInstance(); } catch (Exception ex) { log.fatal("could not load wings.mainclass: " + config.getInitParameter("wings.mainclass"), ex); throw new ServletException(ex); } } finally { // The session was set by the constructor. After init we // expect that only doPost/doGet is called, which set the // session also. So remove it here. SessionManager.removeSession(); } } /** * this method references to * {@link #doGet(HttpServletRequest, HttpServletResponse)} */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { //value chosen to limit denial of service if (req.getContentLength() > getSession().getMaxContentLength() * 1024) { res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); out.println("<html><head><title>Too big</title></head>"); out.println("<body><h1>Error - content length &gt; " + getSession().getMaxContentLength() + "k"); out.println("</h1></body></html>"); } else { doGet(req, res); } // sollte man den obigen Block nicht durch folgende Zeile ersetzen? //throw new RuntimeException("this method must never be called!"); // bsc: Wieso? } /** * Verarbeitet Informationen vom Browser: * <UL> * <LI> setzt Locale * <LI> Dispatch Get Parameter * <LI> feuert Form Events * </UL> * Ist synchronized, damit nur ein Frame gleichzeitig bearbeitet * werden kann. */ public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) { SessionManager.setSession(session); session.setServletRequest(req); session.setServletResponse(response); session.fireRequestEvent(SRequestEvent.REQUEST_START); // in case, the previous thread did not clean up. SForm.clearArmedComponents(); Device outputDevice = null; ReloadManager reloadManager = session.getReloadManager(); boolean isErrorHandling = false; try { /* * The tomcat 3.x has a bug, in that it does not encode the URL * sometimes. It does so, when there is a cookie, containing some * tomcat sessionid but that is invalid (because, for instance, * we restarted the tomcat in-between). * [I can't think of this being the correct behaviour, so I assume * it is a bug. ] * * So we have to workaround this here: if we actually got the * session id from a cookie, but it is not valid, we don't do * the encodeURL() here: we just leave the requestURL as it is * in the properties .. and this is url-encoded, since * we had set it up in the very beginning of this session * with URL-encoding on (see WingServlet::newSession()). * * Vice versa: if the requestedSessionId is valid, then we can * do the encoding (which then does URL-encoding or not, depending * whether the servlet engine detected a cookie). * (hen) */ RequestURL requestURL = null; if (req.isRequestedSessionIdValid()) { requestURL = new RequestURL("", getSessionEncoding(response)); // this will fire an event, if the encoding has changed .. ((PropertyService) session).setProperty("request.url", requestURL); } if (log.isDebugEnabled()) { log.debug("request URL: " + requestURL); log.debug("HTTP header:"); for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) { String header = (String) en.nextElement(); log.debug(" " + header + ": " + req.getHeader(header)); } } handleLocale(req); Enumeration en = req.getParameterNames(); Cookie[] cookies = req.getCookies(); // are there parameters/low level events to dispatch if (en.hasMoreElements()) { // only fire DISPATCH_START if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_START); if (cookies != null) { //dispatch cookies for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String paramName = (String) cookie.getName(); String value = cookie.getValue(); if (log.isDebugEnabled()) log.debug("dispatching cookie " + paramName + " = " + value); session.getDispatcher().dispatch(paramName, new String[] { value }); } } while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String[] value = req.getParameterValues(paramName); if (log.isDebugEnabled()) log.debug("dispatching " + paramName + " = " + Arrays.asList(value)); session.getDispatcher().dispatch(paramName, value); } SForm.fireEvents(); // only fire DISPATCH DONE if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_DONE); } session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST); // if the user chose to exit the session as a reaction on an // event, we got an URL to redirect after the session. /* * where is the right place? * The right place is * - _after_ we processed the events * (e.g. the 'Pressed Exit-Button'-event or gave * the user the chance to exit this session in the custom * processRequest()) * - but _before_ the rendering of the page, * because otherwise an redirect won't work, since we must * not have sent anything to the output stream). */ if (session.getExitAddress() != null) { try { session.firePrepareExit(); String redirectAddress; if (session.getExitAddress().length() > 0) { // redirect to user requested URL. redirectAddress = session.getExitAddress(); } else { // redirect to a fresh session. redirectAddress = req.getRequestURL().toString(); } req.getSession().invalidate(); // calls destroy implicitly response.sendRedirect(redirectAddress); return; } catch (ExitVetoException ex) { session.exit(null); } // end of try-catch } if (session.getRedirectAddress() != null) { // redirect to user requested URL. response.sendRedirect(session.getRedirectAddress()); session.setRedirectAddress(null); return; } // invalidate frames and resources reloadManager.invalidateResources(); reloadManager.notifyCGs(); // deliver resource. The // externalizer is able to handle static and dynamic resources ExternalizeManager extManager = getSession().getExternalizeManager(); String pathInfo = req.getPathInfo().substring(1); log.debug("pathInfo: " + pathInfo); /* * if we have no path info, or the special '_' path info * (that should be explained somewhere, Holger), then we * deliver the toplevel Frame of this application. */ String externalizeIdentifier = null; if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) { log.debug("delivering default frame"); if (session.getFrames().size() == 0) throw new ServletException("no frame visible"); // get the first frame from the set and walk up the hierarchy. // this should work in most cases. if there are more than one // toplevel frames, the developer has to care about the resource // ids anyway .. SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); Resource resource = defaultFrame.getDynamicResource(DynamicCodeResource.class); externalizeIdentifier = resource.getId(); firstRequest = false; } else { externalizeIdentifier = pathInfo; } // externalized this resource. ExternalizedResource extInfo = extManager .getExternalizedResource(externalizeIdentifier); if (extInfo != null) { outputDevice = DeviceFactory.createDevice(extInfo); //outputDevice = createOutputDevice(req, response, extInfo); session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo); extManager.deliver(extInfo, response, outputDevice); session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo); } else { handleUnknownResourceRequested(req, response); } } catch (Throwable e) { /* * error handling...implement it in SFrame */ SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); if (defaultFrame != null && defaultFrame.handleError(e)) { doGet(req, response); isErrorHandling = true; return; } else { log.fatal("exception: ", e); handleException(response, e); } } finally { - if (session != null || !isErrorHandling) { + if (session != null && !isErrorHandling) { session.fireRequestEvent(SRequestEvent.REQUEST_END); } if (outputDevice != null) { try { outputDevice.close(); } catch (Exception e) { } } /* * the session might be null due to destroy(). */ - if (session != null || !isErrorHandling) { + if (session != null && !isErrorHandling) { reloadManager.clear(); session.setServletRequest(null); session.setServletResponse(null); } // make sure that the session association to the thread is removed // from the SessionManager SessionManager.removeSession(); SForm.clearArmedComponents(); } } /** * create a Device that is used to deliver the content, that is * session specific. * The default * implementation just creates a ServletDevice. You can override this * method to decide yourself what happens to the output. You might, for * instance, write some device, that logs the output for debugging * purposes, or one that creates a gziped output stream to transfer * data more efficiently. You get the request and response as well as * the ExternalizedResource to decide, what kind of device you want to create. * You can rely on the fact, that extInfo is not null. * Further, you can rely on the fact, that noting has been written yet * to the output, so that you can set you own set of Headers. * * @param request the HttpServletRequest that is answered * @param response the HttpServletResponse. * @param extInfo the externalized info of the resource about to be * delivered. */ protected Device createOutputDevice(HttpServletRequest request, HttpServletResponse response, ExternalizedResource extInfo) throws IOException { return new ServletDevice(response.getOutputStream()); } // Exception Handling private SFrame errorFrame; private SLabel errorStackTraceLabel; private SLabel errorMessageLabel; private SLabel versionLabel; /** * In case of an error, display an error page to the user. This is only * done when there is a property <code>wings.error.template</code> present * in the web.xml file. This property must contain a path relative to the * webapp which leads to a wingS template. In this template, placeholders * must be defined for wingS components named * <code>EXCEPTION_STACK_TRACE</code>, * <code>EXCEPTION_MESSAGE</code> and <code>WINGS_VERSION</code>. * @param res the HTTP Response to use * @param e the Exception to report */ protected void handleException(HttpServletResponse res, Throwable e) { try { if (errorFrame == null) { errorFrame = new SFrame(); /* * if we don't have an errorTemplateFile defined, then this * will throw an Exception, so the StackTrace is NOT exposed * to the user (may be security relevant) */ errorFrame.getContentPane().setLayout( new STemplateLayout(SessionManager.getSession() .getServletContext().getRealPath( errorTemplateFile))); errorStackTraceLabel = new SLabel(); errorFrame.getContentPane().add(errorStackTraceLabel, "EXCEPTION_STACK_TRACE"); errorMessageLabel = new SLabel(); errorFrame.getContentPane().add(errorMessageLabel, "EXCEPTION_MESSAGE"); versionLabel = new SLabel(); errorFrame.getContentPane().add(versionLabel, "WINGS_VERSION"); versionLabel.setText("wingS " + Version.getVersion() + " / " + Version.getCompileTime()); } res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); errorStackTraceLabel.setText(getStackTraceString(e)); errorMessageLabel.setText(e.getMessage()!=null?e.getMessage():"none"); errorFrame.write(new ServletDevice(out)); } catch (Exception ex) { log.fatal("Exception handling failed.", ex); } } /** * This method is called, whenever a Resource is requested whose * name is not known within this session. * * @param req the causing HttpServletRequest * @param res the HttpServletResponse of this request */ protected void handleUnknownResourceRequested(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setStatus(HttpServletResponse.SC_NOT_FOUND); res.setContentType("text/html"); res.getOutputStream().println("<h1>404 Not Found</h1>Unknown Resource Requested"); } /** * --- HttpSessionBindingListener --- * */ public void valueBound(HttpSessionBindingEvent event) { } public void valueUnbound(HttpSessionBindingEvent event) { destroy(); } /** * get the Session Encoding, that is appended to each URL. * Basically, this is response.encodeURL(""), but unfortuntatly, this * empty encoding isn't supported by Tomcat 4.x anymore. */ public static String getSessionEncoding(HttpServletResponse response) { if (response == null) return ""; // encode dummy non-empty URL. String enc = response.encodeURL("foo").substring(3); return enc; } public void destroy() { log.info("destroy called"); // Session is needed on destroying the session SessionManager.setSession(session); try { // hint the gc. setParent(null); session.destroy(); session = null; errorFrame = null; errorStackTraceLabel = null; errorMessageLabel = null; } catch (Exception ex) { log.error("destroy", ex); } finally { SessionManager.removeSession(); } } private String getStackTraceString(Throwable e) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); stringWriter.getBuffer().setLength(0); e.printStackTrace(printWriter); return stringWriter.toString(); } }
false
true
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) { SessionManager.setSession(session); session.setServletRequest(req); session.setServletResponse(response); session.fireRequestEvent(SRequestEvent.REQUEST_START); // in case, the previous thread did not clean up. SForm.clearArmedComponents(); Device outputDevice = null; ReloadManager reloadManager = session.getReloadManager(); boolean isErrorHandling = false; try { /* * The tomcat 3.x has a bug, in that it does not encode the URL * sometimes. It does so, when there is a cookie, containing some * tomcat sessionid but that is invalid (because, for instance, * we restarted the tomcat in-between). * [I can't think of this being the correct behaviour, so I assume * it is a bug. ] * * So we have to workaround this here: if we actually got the * session id from a cookie, but it is not valid, we don't do * the encodeURL() here: we just leave the requestURL as it is * in the properties .. and this is url-encoded, since * we had set it up in the very beginning of this session * with URL-encoding on (see WingServlet::newSession()). * * Vice versa: if the requestedSessionId is valid, then we can * do the encoding (which then does URL-encoding or not, depending * whether the servlet engine detected a cookie). * (hen) */ RequestURL requestURL = null; if (req.isRequestedSessionIdValid()) { requestURL = new RequestURL("", getSessionEncoding(response)); // this will fire an event, if the encoding has changed .. ((PropertyService) session).setProperty("request.url", requestURL); } if (log.isDebugEnabled()) { log.debug("request URL: " + requestURL); log.debug("HTTP header:"); for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) { String header = (String) en.nextElement(); log.debug(" " + header + ": " + req.getHeader(header)); } } handleLocale(req); Enumeration en = req.getParameterNames(); Cookie[] cookies = req.getCookies(); // are there parameters/low level events to dispatch if (en.hasMoreElements()) { // only fire DISPATCH_START if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_START); if (cookies != null) { //dispatch cookies for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String paramName = (String) cookie.getName(); String value = cookie.getValue(); if (log.isDebugEnabled()) log.debug("dispatching cookie " + paramName + " = " + value); session.getDispatcher().dispatch(paramName, new String[] { value }); } } while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String[] value = req.getParameterValues(paramName); if (log.isDebugEnabled()) log.debug("dispatching " + paramName + " = " + Arrays.asList(value)); session.getDispatcher().dispatch(paramName, value); } SForm.fireEvents(); // only fire DISPATCH DONE if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_DONE); } session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST); // if the user chose to exit the session as a reaction on an // event, we got an URL to redirect after the session. /* * where is the right place? * The right place is * - _after_ we processed the events * (e.g. the 'Pressed Exit-Button'-event or gave * the user the chance to exit this session in the custom * processRequest()) * - but _before_ the rendering of the page, * because otherwise an redirect won't work, since we must * not have sent anything to the output stream). */ if (session.getExitAddress() != null) { try { session.firePrepareExit(); String redirectAddress; if (session.getExitAddress().length() > 0) { // redirect to user requested URL. redirectAddress = session.getExitAddress(); } else { // redirect to a fresh session. redirectAddress = req.getRequestURL().toString(); } req.getSession().invalidate(); // calls destroy implicitly response.sendRedirect(redirectAddress); return; } catch (ExitVetoException ex) { session.exit(null); } // end of try-catch } if (session.getRedirectAddress() != null) { // redirect to user requested URL. response.sendRedirect(session.getRedirectAddress()); session.setRedirectAddress(null); return; } // invalidate frames and resources reloadManager.invalidateResources(); reloadManager.notifyCGs(); // deliver resource. The // externalizer is able to handle static and dynamic resources ExternalizeManager extManager = getSession().getExternalizeManager(); String pathInfo = req.getPathInfo().substring(1); log.debug("pathInfo: " + pathInfo); /* * if we have no path info, or the special '_' path info * (that should be explained somewhere, Holger), then we * deliver the toplevel Frame of this application. */ String externalizeIdentifier = null; if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) { log.debug("delivering default frame"); if (session.getFrames().size() == 0) throw new ServletException("no frame visible"); // get the first frame from the set and walk up the hierarchy. // this should work in most cases. if there are more than one // toplevel frames, the developer has to care about the resource // ids anyway .. SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); Resource resource = defaultFrame.getDynamicResource(DynamicCodeResource.class); externalizeIdentifier = resource.getId(); firstRequest = false; } else { externalizeIdentifier = pathInfo; } // externalized this resource. ExternalizedResource extInfo = extManager .getExternalizedResource(externalizeIdentifier); if (extInfo != null) { outputDevice = DeviceFactory.createDevice(extInfo); //outputDevice = createOutputDevice(req, response, extInfo); session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo); extManager.deliver(extInfo, response, outputDevice); session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo); } else { handleUnknownResourceRequested(req, response); } } catch (Throwable e) { /* * error handling...implement it in SFrame */ SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); if (defaultFrame != null && defaultFrame.handleError(e)) { doGet(req, response); isErrorHandling = true; return; } else { log.fatal("exception: ", e); handleException(response, e); } } finally { if (session != null || !isErrorHandling) { session.fireRequestEvent(SRequestEvent.REQUEST_END); } if (outputDevice != null) { try { outputDevice.close(); } catch (Exception e) { } } /* * the session might be null due to destroy(). */ if (session != null || !isErrorHandling) { reloadManager.clear(); session.setServletRequest(null); session.setServletResponse(null); } // make sure that the session association to the thread is removed // from the SessionManager SessionManager.removeSession(); SForm.clearArmedComponents(); } }
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) { SessionManager.setSession(session); session.setServletRequest(req); session.setServletResponse(response); session.fireRequestEvent(SRequestEvent.REQUEST_START); // in case, the previous thread did not clean up. SForm.clearArmedComponents(); Device outputDevice = null; ReloadManager reloadManager = session.getReloadManager(); boolean isErrorHandling = false; try { /* * The tomcat 3.x has a bug, in that it does not encode the URL * sometimes. It does so, when there is a cookie, containing some * tomcat sessionid but that is invalid (because, for instance, * we restarted the tomcat in-between). * [I can't think of this being the correct behaviour, so I assume * it is a bug. ] * * So we have to workaround this here: if we actually got the * session id from a cookie, but it is not valid, we don't do * the encodeURL() here: we just leave the requestURL as it is * in the properties .. and this is url-encoded, since * we had set it up in the very beginning of this session * with URL-encoding on (see WingServlet::newSession()). * * Vice versa: if the requestedSessionId is valid, then we can * do the encoding (which then does URL-encoding or not, depending * whether the servlet engine detected a cookie). * (hen) */ RequestURL requestURL = null; if (req.isRequestedSessionIdValid()) { requestURL = new RequestURL("", getSessionEncoding(response)); // this will fire an event, if the encoding has changed .. ((PropertyService) session).setProperty("request.url", requestURL); } if (log.isDebugEnabled()) { log.debug("request URL: " + requestURL); log.debug("HTTP header:"); for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) { String header = (String) en.nextElement(); log.debug(" " + header + ": " + req.getHeader(header)); } } handleLocale(req); Enumeration en = req.getParameterNames(); Cookie[] cookies = req.getCookies(); // are there parameters/low level events to dispatch if (en.hasMoreElements()) { // only fire DISPATCH_START if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_START); if (cookies != null) { //dispatch cookies for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String paramName = (String) cookie.getName(); String value = cookie.getValue(); if (log.isDebugEnabled()) log.debug("dispatching cookie " + paramName + " = " + value); session.getDispatcher().dispatch(paramName, new String[] { value }); } } while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String[] value = req.getParameterValues(paramName); if (log.isDebugEnabled()) log.debug("dispatching " + paramName + " = " + Arrays.asList(value)); session.getDispatcher().dispatch(paramName, value); } SForm.fireEvents(); // only fire DISPATCH DONE if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_DONE); } session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST); // if the user chose to exit the session as a reaction on an // event, we got an URL to redirect after the session. /* * where is the right place? * The right place is * - _after_ we processed the events * (e.g. the 'Pressed Exit-Button'-event or gave * the user the chance to exit this session in the custom * processRequest()) * - but _before_ the rendering of the page, * because otherwise an redirect won't work, since we must * not have sent anything to the output stream). */ if (session.getExitAddress() != null) { try { session.firePrepareExit(); String redirectAddress; if (session.getExitAddress().length() > 0) { // redirect to user requested URL. redirectAddress = session.getExitAddress(); } else { // redirect to a fresh session. redirectAddress = req.getRequestURL().toString(); } req.getSession().invalidate(); // calls destroy implicitly response.sendRedirect(redirectAddress); return; } catch (ExitVetoException ex) { session.exit(null); } // end of try-catch } if (session.getRedirectAddress() != null) { // redirect to user requested URL. response.sendRedirect(session.getRedirectAddress()); session.setRedirectAddress(null); return; } // invalidate frames and resources reloadManager.invalidateResources(); reloadManager.notifyCGs(); // deliver resource. The // externalizer is able to handle static and dynamic resources ExternalizeManager extManager = getSession().getExternalizeManager(); String pathInfo = req.getPathInfo().substring(1); log.debug("pathInfo: " + pathInfo); /* * if we have no path info, or the special '_' path info * (that should be explained somewhere, Holger), then we * deliver the toplevel Frame of this application. */ String externalizeIdentifier = null; if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) { log.debug("delivering default frame"); if (session.getFrames().size() == 0) throw new ServletException("no frame visible"); // get the first frame from the set and walk up the hierarchy. // this should work in most cases. if there are more than one // toplevel frames, the developer has to care about the resource // ids anyway .. SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); Resource resource = defaultFrame.getDynamicResource(DynamicCodeResource.class); externalizeIdentifier = resource.getId(); firstRequest = false; } else { externalizeIdentifier = pathInfo; } // externalized this resource. ExternalizedResource extInfo = extManager .getExternalizedResource(externalizeIdentifier); if (extInfo != null) { outputDevice = DeviceFactory.createDevice(extInfo); //outputDevice = createOutputDevice(req, response, extInfo); session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo); extManager.deliver(extInfo, response, outputDevice); session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo); } else { handleUnknownResourceRequested(req, response); } } catch (Throwable e) { /* * error handling...implement it in SFrame */ SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); if (defaultFrame != null && defaultFrame.handleError(e)) { doGet(req, response); isErrorHandling = true; return; } else { log.fatal("exception: ", e); handleException(response, e); } } finally { if (session != null && !isErrorHandling) { session.fireRequestEvent(SRequestEvent.REQUEST_END); } if (outputDevice != null) { try { outputDevice.close(); } catch (Exception e) { } } /* * the session might be null due to destroy(). */ if (session != null && !isErrorHandling) { reloadManager.clear(); session.setServletRequest(null); session.setServletResponse(null); } // make sure that the session association to the thread is removed // from the SessionManager SessionManager.removeSession(); SForm.clearArmedComponents(); } }
diff --git a/WarpSuite/src/com/mrz/dyndns/server/warpsuite/WarpSuite.java b/WarpSuite/src/com/mrz/dyndns/server/warpsuite/WarpSuite.java index 1863d53..12e1556 100644 --- a/WarpSuite/src/com/mrz/dyndns/server/warpsuite/WarpSuite.java +++ b/WarpSuite/src/com/mrz/dyndns/server/warpsuite/WarpSuite.java @@ -1,124 +1,124 @@ package com.mrz.dyndns.server.warpsuite; import java.util.List; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; import com.mrz.dyndns.server.CommandSystem.CommandSystem; import com.mrz.dyndns.server.CommandSystem.SimpleCommand; import com.mrz.dyndns.server.warpsuite.commands.*; import com.mrz.dyndns.server.warpsuite.listeners.EntityDamageByEntityListener; import com.mrz.dyndns.server.warpsuite.listeners.PlayerMoveListener; import com.mrz.dyndns.server.warpsuite.managers.PendingWarpManager; import com.mrz.dyndns.server.warpsuite.managers.PlayerManager; import com.mrz.dyndns.server.warpsuite.managers.WarpManager; import com.mrz.dyndns.server.warpsuite.permissions.Permissions; import com.mrz.dyndns.server.warpsuite.util.Coloring; import com.mrz.dyndns.server.warpsuite.util.Config; import com.mrz.dyndns.server.warpsuite.util.MyConfig; import com.mrz.dyndns.server.warpsuite.util.Util; public class WarpSuite extends JavaPlugin { private CommandSystem cs; private PlayerManager playerManager; private WarpManager publicWarpManager; private boolean usingMultiverse; private PendingWarpManager pendingWarpManager; @Override public void onEnable() { Util.initialize(this); Util.setDebugging(true); cs = new CommandSystem(this); getConfig().options().copyDefaults(true); saveConfig(); Config.load(getConfig()); playerManager = new PlayerManager(this); publicWarpManager = new WarpManager(new MyConfig("public", this)); pendingWarpManager = new PendingWarpManager(); getServer().getPluginManager().registerEvents(playerManager, this); cs.registerCommand("warp set|add", new SetPlayersOwnWarp(this)); cs.registerCommand("warp", new GoPlayersOwnWarp(this)); final WarpSuite plugin = this; cs.registerCommand("warp reload", new SimpleCommand() { @Override public boolean Execute(String commandName, final CommandSender sender, List<String> args, List<String> variables) { if(Permissions.RELOAD.check(sender)) { getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { plugin.onDisable(); plugin.onEnable(); for(WarpSuitePlayer player : plugin.getPlayerManager().getPlayers()) { player.getConfig().reloadCustomConfig(); } plugin.getLogger().info("Reloaded WarpSuite"); sender.sendMessage(Coloring.POSITIVE_PRIMARY + "Reloaded WarpSuite!"); } }); } else { Util.invalidPermissions(sender); } return true; } }); if(getServer().getPluginManager().getPlugin("Multiverse-Core") != null) { getLogger().info("Hooking into Multiverse"); usingMultiverse = true; } else { usingMultiverse = false; } - getServer().getScheduler().runTaskTimer(this, playerManager, 72000L, 72000L);//every hour seconds + getServer().getScheduler().runTaskTimer(this, playerManager, 72000L, 72000L);//every hour getServer().getPluginManager().registerEvents(new EntityDamageByEntityListener(this), this); getServer().getPluginManager().registerEvents(new PlayerMoveListener(this), this); } @Override public void onDisable() { playerManager.clearPlayers(); cs.close(); } //you will never need it public WarpManager getPublicWarpManager() { return publicWarpManager; } public PlayerManager getPlayerManager() { return playerManager; } public boolean isUsingMultiverse() { return usingMultiverse; } public PendingWarpManager getPendingWarpManager() { return pendingWarpManager; } }
true
true
public void onEnable() { Util.initialize(this); Util.setDebugging(true); cs = new CommandSystem(this); getConfig().options().copyDefaults(true); saveConfig(); Config.load(getConfig()); playerManager = new PlayerManager(this); publicWarpManager = new WarpManager(new MyConfig("public", this)); pendingWarpManager = new PendingWarpManager(); getServer().getPluginManager().registerEvents(playerManager, this); cs.registerCommand("warp set|add", new SetPlayersOwnWarp(this)); cs.registerCommand("warp", new GoPlayersOwnWarp(this)); final WarpSuite plugin = this; cs.registerCommand("warp reload", new SimpleCommand() { @Override public boolean Execute(String commandName, final CommandSender sender, List<String> args, List<String> variables) { if(Permissions.RELOAD.check(sender)) { getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { plugin.onDisable(); plugin.onEnable(); for(WarpSuitePlayer player : plugin.getPlayerManager().getPlayers()) { player.getConfig().reloadCustomConfig(); } plugin.getLogger().info("Reloaded WarpSuite"); sender.sendMessage(Coloring.POSITIVE_PRIMARY + "Reloaded WarpSuite!"); } }); } else { Util.invalidPermissions(sender); } return true; } }); if(getServer().getPluginManager().getPlugin("Multiverse-Core") != null) { getLogger().info("Hooking into Multiverse"); usingMultiverse = true; } else { usingMultiverse = false; } getServer().getScheduler().runTaskTimer(this, playerManager, 72000L, 72000L);//every hour seconds getServer().getPluginManager().registerEvents(new EntityDamageByEntityListener(this), this); getServer().getPluginManager().registerEvents(new PlayerMoveListener(this), this); }
public void onEnable() { Util.initialize(this); Util.setDebugging(true); cs = new CommandSystem(this); getConfig().options().copyDefaults(true); saveConfig(); Config.load(getConfig()); playerManager = new PlayerManager(this); publicWarpManager = new WarpManager(new MyConfig("public", this)); pendingWarpManager = new PendingWarpManager(); getServer().getPluginManager().registerEvents(playerManager, this); cs.registerCommand("warp set|add", new SetPlayersOwnWarp(this)); cs.registerCommand("warp", new GoPlayersOwnWarp(this)); final WarpSuite plugin = this; cs.registerCommand("warp reload", new SimpleCommand() { @Override public boolean Execute(String commandName, final CommandSender sender, List<String> args, List<String> variables) { if(Permissions.RELOAD.check(sender)) { getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { plugin.onDisable(); plugin.onEnable(); for(WarpSuitePlayer player : plugin.getPlayerManager().getPlayers()) { player.getConfig().reloadCustomConfig(); } plugin.getLogger().info("Reloaded WarpSuite"); sender.sendMessage(Coloring.POSITIVE_PRIMARY + "Reloaded WarpSuite!"); } }); } else { Util.invalidPermissions(sender); } return true; } }); if(getServer().getPluginManager().getPlugin("Multiverse-Core") != null) { getLogger().info("Hooking into Multiverse"); usingMultiverse = true; } else { usingMultiverse = false; } getServer().getScheduler().runTaskTimer(this, playerManager, 72000L, 72000L);//every hour getServer().getPluginManager().registerEvents(new EntityDamageByEntityListener(this), this); getServer().getPluginManager().registerEvents(new PlayerMoveListener(this), this); }
diff --git a/src/cat/katzenfabrik/morsecodr/MainThread.java b/src/cat/katzenfabrik/morsecodr/MainThread.java index ac9781b..7938328 100644 --- a/src/cat/katzenfabrik/morsecodr/MainThread.java +++ b/src/cat/katzenfabrik/morsecodr/MainThread.java @@ -1,102 +1,104 @@ package cat.katzenfabrik.morsecodr; import java.io.IOException; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; public class MainThread extends Thread { private final Clip snd; private final Clip otherEndSnd; public static final class KeyMsg { public final boolean pressed; public KeyMsg(boolean pressed) { this.pressed = pressed; } } private LinkedList<KeyMsg> keyMsgQ = new LinkedList<KeyMsg>(); private int noKeyPressCount = 0; private int noKeyReleaseCount = 0; private boolean keyDown = false; private boolean beeping = false; private boolean otherEndBeeping = false; private Sender sender; public MainThread() throws LineUnavailableException { AudioFormat audioFormat = new AudioFormat(8000, 8, 1, true, true); DataLine.Info info = new DataLine.Info(Clip.class, audioFormat); snd = (Clip) AudioSystem.getLine(info); byte[] sample = new byte[31]; for (int i = 0; i < sample.length; i++) { sample[i] = (byte) (64 * Math.sin(i * Math.PI * 2 / sample.length)); } snd.open(audioFormat, sample, 0, sample.length); otherEndSnd = (Clip) AudioSystem.getLine(info); byte[] sample2 = new byte[27]; for (int i = 0; i < sample2.length; i++) { sample2[i] = (byte) (55 * Math.sin(i * Math.PI * 2 / sample2.length)); } otherEndSnd.open(audioFormat, sample2, 0, sample2.length); } public synchronized void send(KeyMsg m) { keyMsgQ.add(m); } public synchronized void setSender(Sender sender) { this.sender = sender; } @Override public void run() { while (true) { synchronized (this) { noKeyPressCount ++; noKeyReleaseCount ++; for (KeyMsg m: keyMsgQ) { if (m.pressed) { noKeyPressCount = 0; } else { noKeyReleaseCount = 0; } keyDown = m.pressed; } keyMsgQ.clear(); if (!beeping && keyDown) { beeping = true; + snd.setFramePosition(0); snd.loop(10000); } else if (beeping && !keyDown && noKeyPressCount > 0) { beeping = false; snd.stop(); } if (sender != null) { sender.write(beeping ? "1" : "0"); } boolean otherEndBeepingNow = false; if (sender != null) { try { otherEndBeepingNow = sender.read().equals("1"); } catch (IOException ex) { sender = null; } } if (!otherEndBeeping && otherEndBeepingNow) { otherEndBeeping = true; + otherEndSnd.setFramePosition(0); otherEndSnd.loop(10000); } if (otherEndBeeping && !otherEndBeepingNow) { otherEndBeeping = false; otherEndSnd.stop(); } } try { Thread.sleep(50); } catch(InterruptedException e) { Thread.interrupted(); } } } }
false
true
public void run() { while (true) { synchronized (this) { noKeyPressCount ++; noKeyReleaseCount ++; for (KeyMsg m: keyMsgQ) { if (m.pressed) { noKeyPressCount = 0; } else { noKeyReleaseCount = 0; } keyDown = m.pressed; } keyMsgQ.clear(); if (!beeping && keyDown) { beeping = true; snd.loop(10000); } else if (beeping && !keyDown && noKeyPressCount > 0) { beeping = false; snd.stop(); } if (sender != null) { sender.write(beeping ? "1" : "0"); } boolean otherEndBeepingNow = false; if (sender != null) { try { otherEndBeepingNow = sender.read().equals("1"); } catch (IOException ex) { sender = null; } } if (!otherEndBeeping && otherEndBeepingNow) { otherEndBeeping = true; otherEndSnd.loop(10000); } if (otherEndBeeping && !otherEndBeepingNow) { otherEndBeeping = false; otherEndSnd.stop(); } } try { Thread.sleep(50); } catch(InterruptedException e) { Thread.interrupted(); } } }
public void run() { while (true) { synchronized (this) { noKeyPressCount ++; noKeyReleaseCount ++; for (KeyMsg m: keyMsgQ) { if (m.pressed) { noKeyPressCount = 0; } else { noKeyReleaseCount = 0; } keyDown = m.pressed; } keyMsgQ.clear(); if (!beeping && keyDown) { beeping = true; snd.setFramePosition(0); snd.loop(10000); } else if (beeping && !keyDown && noKeyPressCount > 0) { beeping = false; snd.stop(); } if (sender != null) { sender.write(beeping ? "1" : "0"); } boolean otherEndBeepingNow = false; if (sender != null) { try { otherEndBeepingNow = sender.read().equals("1"); } catch (IOException ex) { sender = null; } } if (!otherEndBeeping && otherEndBeepingNow) { otherEndBeeping = true; otherEndSnd.setFramePosition(0); otherEndSnd.loop(10000); } if (otherEndBeeping && !otherEndBeepingNow) { otherEndBeeping = false; otherEndSnd.stop(); } } try { Thread.sleep(50); } catch(InterruptedException e) { Thread.interrupted(); } } }
diff --git a/gogrid/src/test/java/org/jclouds/gogrid/GoGridComputeServiceLiveTest.java b/gogrid/src/test/java/org/jclouds/gogrid/GoGridComputeServiceLiveTest.java index 998d997b4..a454bf08b 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/GoGridComputeServiceLiveTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/GoGridComputeServiceLiveTest.java @@ -1,108 +1,108 @@ /** * * Copyright (C) 2010 Cloud Conscious, LLC. <[email protected]> * * ==================================================================== * 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.jclouds.gogrid; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.Map; import org.jclouds.compute.BaseComputeServiceLiveTest; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.domain.Architecture; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Template; import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.domain.Credentials; import org.jclouds.rest.RestContext; import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; /** * @author Oleksiy Yarmula */ @Test(groups = "live", enabled = true, sequential = true, testName = "gogrid.GoGridComputeServiceLiveTest") public class GoGridComputeServiceLiveTest extends BaseComputeServiceLiveTest { @BeforeClass @Override public void setServiceDefaults() { service = "gogrid"; } @Test public void testTemplateBuilder() { Template defaultTemplate = client.templateBuilder().build(); assertEquals(defaultTemplate.getImage().getArchitecture(), Architecture.X86_64); assertEquals(defaultTemplate.getImage().getOsFamily(), OsFamily.CENTOS); assertEquals(defaultTemplate.getLocation().getId(), "SANFRANCISCO"); assertEquals(defaultTemplate.getSize().getCores(), 1.0d); } @Override protected JschSshClientModule getSshModule() { return new JschSshClientModule(); } public void testAssignability() throws Exception { @SuppressWarnings("unused") RestContext<GoGridAsyncClient, GoGridClient> goGridContext = new ComputeServiceContextFactory() .createContext(service, user, password).getProviderSpecificContext(); } @Test(enabled = true) public void endToEndComputeServiceTest() { ComputeService service = context.getComputeService(); Template t = service.templateBuilder().minRam(1024).imageId("1532").build(); assertEquals(t.getImage().getId(), "1532"); service.runNodesWithTag(this.service, 3, t); Map<String, ? extends ComputeMetadata> nodes = service.getNodes(); ComputeMetadata node = Iterables.find(nodes.values(), new Predicate<ComputeMetadata>() { @Override public boolean apply(ComputeMetadata computeMetadata) { return computeMetadata.getName().startsWith(GoGridComputeServiceLiveTest.this.service); } }); NodeMetadata nodeMetadata = service.getNodeMetadata(node); assertEquals(nodeMetadata.getPublicAddresses().size(), 1, "There must be 1 public address for the node"); assertTrue(nodeMetadata.getName().startsWith(this.service)); service.rebootNode(nodeMetadata); // blocks until finished assertEquals(service.getNodeMetadata(nodeMetadata).getState(), NodeState.RUNNING); - client.runScriptOnNodesWithTag("gogrid", null/*no credentials*/, + client.runScriptOnNodesWithTag("gogrid", "mkdir ~/ahha; sleep 3".getBytes(), - new RunScriptOptions.Builder().overrideCredentials(false).build()); + new RunScriptOptions.Builder().overrideCredentials(new Credentials("root", null)).build()); service.destroyNodesWithTag("gogrid"); } }
false
true
public void endToEndComputeServiceTest() { ComputeService service = context.getComputeService(); Template t = service.templateBuilder().minRam(1024).imageId("1532").build(); assertEquals(t.getImage().getId(), "1532"); service.runNodesWithTag(this.service, 3, t); Map<String, ? extends ComputeMetadata> nodes = service.getNodes(); ComputeMetadata node = Iterables.find(nodes.values(), new Predicate<ComputeMetadata>() { @Override public boolean apply(ComputeMetadata computeMetadata) { return computeMetadata.getName().startsWith(GoGridComputeServiceLiveTest.this.service); } }); NodeMetadata nodeMetadata = service.getNodeMetadata(node); assertEquals(nodeMetadata.getPublicAddresses().size(), 1, "There must be 1 public address for the node"); assertTrue(nodeMetadata.getName().startsWith(this.service)); service.rebootNode(nodeMetadata); // blocks until finished assertEquals(service.getNodeMetadata(nodeMetadata).getState(), NodeState.RUNNING); client.runScriptOnNodesWithTag("gogrid", null/*no credentials*/, "mkdir ~/ahha; sleep 3".getBytes(), new RunScriptOptions.Builder().overrideCredentials(false).build()); service.destroyNodesWithTag("gogrid"); }
public void endToEndComputeServiceTest() { ComputeService service = context.getComputeService(); Template t = service.templateBuilder().minRam(1024).imageId("1532").build(); assertEquals(t.getImage().getId(), "1532"); service.runNodesWithTag(this.service, 3, t); Map<String, ? extends ComputeMetadata> nodes = service.getNodes(); ComputeMetadata node = Iterables.find(nodes.values(), new Predicate<ComputeMetadata>() { @Override public boolean apply(ComputeMetadata computeMetadata) { return computeMetadata.getName().startsWith(GoGridComputeServiceLiveTest.this.service); } }); NodeMetadata nodeMetadata = service.getNodeMetadata(node); assertEquals(nodeMetadata.getPublicAddresses().size(), 1, "There must be 1 public address for the node"); assertTrue(nodeMetadata.getName().startsWith(this.service)); service.rebootNode(nodeMetadata); // blocks until finished assertEquals(service.getNodeMetadata(nodeMetadata).getState(), NodeState.RUNNING); client.runScriptOnNodesWithTag("gogrid", "mkdir ~/ahha; sleep 3".getBytes(), new RunScriptOptions.Builder().overrideCredentials(new Credentials("root", null)).build()); service.destroyNodesWithTag("gogrid"); }
diff --git a/ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/images/remote/RemoteImageLoaderHandler.java b/ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/images/remote/RemoteImageLoaderHandler.java index d39c39f..0b9af9a 100755 --- a/ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/images/remote/RemoteImageLoaderHandler.java +++ b/ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/images/remote/RemoteImageLoaderHandler.java @@ -1,98 +1,100 @@ /* Copyright (c) 2009-2011 Matthias Kaeppler * * 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.github.ignition.support.images.remote; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ImageView; public class RemoteImageLoaderHandler extends Handler { public static final int HANDLER_MESSAGE_ID = 0; public static final String BITMAP_EXTRA = "ign:extra_bitmap"; public static final String IMAGE_URL_EXTRA = "ign:extra_image_url"; private ImageView imageView; private String imageUrl; private Drawable errorDrawable; public RemoteImageLoaderHandler(ImageView imageView, String imageUrl, Drawable errorDrawable) { this.imageView = imageView; this.imageUrl = imageUrl; this.errorDrawable = errorDrawable; } @Override public final void handleMessage(Message msg) { if (msg.what == HANDLER_MESSAGE_ID) { handleImageLoadedMessage(msg); } } protected final void handleImageLoadedMessage(Message msg) { Bundle data = msg.getData(); Bitmap bitmap = data.getParcelable(BITMAP_EXTRA); handleImageLoaded(bitmap, msg); } /** * Override this method if you need custom handler logic. Note that this method can actually be * called directly for performance reasons, in which case the message will be null * * @param bitmap * the bitmap returned from the image loader * @param msg * the handler message; can be null * @return true if the view was updated with the new image, false if it was discarded */ protected boolean handleImageLoaded(Bitmap bitmap, Message msg) { // If this handler is used for loading images in a ListAdapter, // the thread will set the image only if it's the right position, // otherwise it won't do anything. String forUrl = (String) imageView.getTag(); - if (imageUrl.equals(forUrl)) { - Bitmap image = (bitmap == null ? ((BitmapDrawable) errorDrawable).getBitmap() : bitmap); - imageView.setImageBitmap(image); + if (bitmap == null && errorDrawable != null) { + bitmap = ((BitmapDrawable) errorDrawable).getBitmap(); + } + if (bitmap != null && imageUrl.equals(forUrl)) { + imageView.setImageBitmap(bitmap); // remove the image URL from the view's tag imageView.setTag(null); return true; } return false; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public ImageView getImageView() { return imageView; } public void setImageView(ImageView imageView) { this.imageView = imageView; } }
true
true
protected boolean handleImageLoaded(Bitmap bitmap, Message msg) { // If this handler is used for loading images in a ListAdapter, // the thread will set the image only if it's the right position, // otherwise it won't do anything. String forUrl = (String) imageView.getTag(); if (imageUrl.equals(forUrl)) { Bitmap image = (bitmap == null ? ((BitmapDrawable) errorDrawable).getBitmap() : bitmap); imageView.setImageBitmap(image); // remove the image URL from the view's tag imageView.setTag(null); return true; } return false; }
protected boolean handleImageLoaded(Bitmap bitmap, Message msg) { // If this handler is used for loading images in a ListAdapter, // the thread will set the image only if it's the right position, // otherwise it won't do anything. String forUrl = (String) imageView.getTag(); if (bitmap == null && errorDrawable != null) { bitmap = ((BitmapDrawable) errorDrawable).getBitmap(); } if (bitmap != null && imageUrl.equals(forUrl)) { imageView.setImageBitmap(bitmap); // remove the image URL from the view's tag imageView.setTag(null); return true; } return false; }
diff --git a/engine/src/main/java/org/camunda/bpm/engine/impl/cfg/StandaloneInMemProcessEngineConfiguration.java b/engine/src/main/java/org/camunda/bpm/engine/impl/cfg/StandaloneInMemProcessEngineConfiguration.java index ca4b5a56d4..f14fc94f8e 100644 --- a/engine/src/main/java/org/camunda/bpm/engine/impl/cfg/StandaloneInMemProcessEngineConfiguration.java +++ b/engine/src/main/java/org/camunda/bpm/engine/impl/cfg/StandaloneInMemProcessEngineConfiguration.java @@ -1,26 +1,26 @@ /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.impl.cfg; /** * @author Tom Baeyens */ public class StandaloneInMemProcessEngineConfiguration extends StandaloneProcessEngineConfiguration { public StandaloneInMemProcessEngineConfiguration() { this.databaseSchemaUpdate = DB_SCHEMA_UPDATE_CREATE_DROP; - this.jdbcUrl = "jdbc:h2:mem:activiti"; + this.jdbcUrl = "jdbc:h2:mem:camunda"; } }
true
true
public StandaloneInMemProcessEngineConfiguration() { this.databaseSchemaUpdate = DB_SCHEMA_UPDATE_CREATE_DROP; this.jdbcUrl = "jdbc:h2:mem:activiti"; }
public StandaloneInMemProcessEngineConfiguration() { this.databaseSchemaUpdate = DB_SCHEMA_UPDATE_CREATE_DROP; this.jdbcUrl = "jdbc:h2:mem:camunda"; }
diff --git a/twitter4j-core/src/main/java/twitter4j/TwitterStream.java b/twitter4j-core/src/main/java/twitter4j/TwitterStream.java index 9d3ea3df..d5ecd3f7 100644 --- a/twitter4j-core/src/main/java/twitter4j/TwitterStream.java +++ b/twitter4j-core/src/main/java/twitter4j/TwitterStream.java @@ -1,496 +1,498 @@ /* Copyright (c) 2007-2010, Yusuke Yamamoto 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 Yusuke Yamamoto 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 Yusuke Yamamoto ``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 Yusuke Yamamoto 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 twitter4j; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationContext; import twitter4j.http.Authorization; import twitter4j.internal.http.HttpClientWrapper; import twitter4j.internal.http.HttpClientWrapperConfiguration; import twitter4j.internal.http.HttpParameter; import twitter4j.internal.logging.Logger; import java.io.IOException; import java.util.Map; /** * A java representation of the <a href="http://apiwiki.twitter.com/Streaming-API-Documentation">Twitter Streaming API</a><br> * Note that this class is NOT compatible with Google App Engine as GAE is not capable of handling requests longer than 30 seconds. * * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.0.4 */ public final class TwitterStream extends TwitterBase implements java.io.Serializable { private final HttpClientWrapper http; private static final Logger logger = Logger.getLogger(TwitterStream.class); private StatusListener statusListener; private StreamHandlingThread handler = null; private static final long serialVersionUID = -762817147320767897L; /** * Constructs a TwitterStream instance. UserID and password should be provided by either twitter4j.properties or system property. * since Twitter4J 2.0.10 * @deprecated use {@link TwitterStreamFactory#getInstance()} instead. */ public TwitterStream() { super(ConfigurationContext.getInstance()); http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); ensureBasicEnabled(); } /** * Constructs a TwitterStream instance. UserID and password should be provided by either twitter4j.properties or system property. * since Twitter4J 2.0.10 * @param screenName screen name * @param password password * @deprecated use {@link TwitterStreamFactory#getInstance()} instead. */ public TwitterStream(String screenName, String password) { super(ConfigurationContext.getInstance(), screenName, password); http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); ensureBasicEnabled(); } /** * Constructs a TwitterStream instance. UserID and password should be provided by either twitter4j.properties or system property. * since Twitter4J 2.0.10 * @param screenName screen name * @param password password * @param listener listener * @deprecated use {@link TwitterStreamFactory#getInstance()} instead. */ public TwitterStream(String screenName, String password, StatusListener listener) { super(ConfigurationContext.getInstance(), screenName, password); this.statusListener = listener; http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); ensureBasicEnabled(); } /*package*/ TwitterStream(Configuration conf, Authorization auth, StatusListener listener) { super(conf, auth); http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); this.statusListener = listener; ensureBasicEnabled(); } /* Streaming API */ /** * Starts listening on all public statuses. Available only to approved parties and requires a signed agreement to access. Please do not contact us about access to the firehose. If your service warrants access to it, we'll contact you. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/firehose">Twitter API Wiki / Streaming API Documentation - firehose</a> * @since Twitter4J 2.0.4 */ public void firehose(final int count) { startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getFirehoseStream(count); } }); } /** * Returns a status stream of all public statuses. Available only to approved parties and requires a signed agreement to access. Please do not contact us about access to the firehose. If your service warrants access to it, we'll contact you. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/firehose">Twitter API Wiki / Streaming API Documentation - firehose</a> * @since Twitter4J 2.0.4 */ public StatusStream getFirehoseStream(int count) throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.post(conf.getStreamBaseURL() + "statuses/firehose.json" , new HttpParameter[]{new HttpParameter("count" , String.valueOf(count))}, auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Starts listening on all public statuses containing links. Available only to approved parties and requires a signed agreement to access. Please do not contact us about access to the links stream. If your service warrants access to it, we'll contact you. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/links">Twitter API Wiki / Streaming API Documentation - links</a> * @since Twitter4J 2.1.1 */ public void links(final int count) { startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getLinksStream(count); } }); } /** * Returns a status stream of all public statuses containing links. Available only to approved parties and requires a signed agreement to access. Please do not contact us about access to the links stream. If your service warrants access to it, we'll contact you. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/links">Twitter API Wiki / Streaming API Documentation - links</a> * @since Twitter4J 2.1.1 */ public StatusStream getLinksStream(int count) throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.post(conf.getStreamBaseURL() + "statuses/links.json" , new HttpParameter[]{new HttpParameter("count" , String.valueOf(count))}, auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Starts listening on all retweets. The retweet stream is not a generally available resource. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case. As of 9/11/2009, the site-wide retweet feature has not yet launched, so there are currently few, if any, retweets on this stream. * * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/retweet">Twitter API Wiki / Streaming API Documentation - retweet</a> * @since Twitter4J 2.0.10 */ public void retweet() { ensureBasicEnabled(); startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getRetweetStream(); } }); } /** * Returns a stream of all retweets. The retweet stream is not a generally available resource. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case. As of 9/11/2009, the site-wide retweet feature has not yet launched, so there are currently few, if any, retweets on this stream. * * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/retweet">Twitter API Wiki / Streaming API Documentation - retweet</a> * @since Twitter4J 2.0.10 */ public StatusStream getRetweetStream() throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.post(conf.getStreamBaseURL() + "statuses/retweet.json" , new HttpParameter[]{}, auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Starts listening on random sample of all public statuses. The default access level provides a small proportion of the Firehose. The "Gardenhose" access level provides a proportion more suitable for data mining and research applications that desire a larger proportion to be statistically significant sample. * * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/sample">Twitter API Wiki / Streaming API Documentation - sample</a> * @since Twitter4J 2.0.10 */ public void sample() { ensureBasicEnabled(); startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getSampleStream(); } }); } /** * Returns a stream of random sample of all public statuses. The default access level provides a small proportion of the Firehose. The "Gardenhose" access level provides a proportion more suitable for data mining and research applications that desire a larger proportion to be statistically significant sample. * * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#Sampling">Twitter API Wiki / Streaming API Documentation - Sampling</a> * @since Twitter4J 2.0.10 */ public StatusStream getSampleStream() throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.get(conf.getStreamBaseURL() + "statuses/sample.json" , auth)); } catch (IOException e) { throw new TwitterException(e); } } public void user () { ensureBasicEnabled(); startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getUserStream(); } }); } public StatusStream getUserStream() throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.get(conf.getUserStreamBaseURL () + "user.json" , auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Start consuming public statuses that match one or more filter predicates. At least one predicate parameter, follow, locations, or track must be specified. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Placing long parameters in the URL may cause the request to be rejected for excessive URL length.<br> * The default access level allows up to 200 track keywords, 400 follow userids and 10 1-degree location boxes. Increased access levels allow 80,000 follow userids ("shadow" role), 400,000 follow userids ("birddog" role), 10,000 track keywords ("restricted track" role), 200,000 track keywords ("partner track" role), and 200 10-degree location boxes ("locRestricted" role). Increased track access levels also pass a higher proportion of statuses before limiting the stream. * * @param query Filter query * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/filter">Twitter API Wiki / Streaming API Documentation - filter</a> * @since Twitter4J 2.1.2 */ public void filter(final FilterQuery query) throws TwitterException { startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getFilterStream(query); } }); } /** * Returns public statuses that match one or more filter predicates. At least one predicate parameter, follow, locations, or track must be specified. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Placing long parameters in the URL may cause the request to be rejected for excessive URL length.<br> * The default access level allows up to 200 track keywords, 400 follow userids and 10 1-degree location boxes. Increased access levels allow 80,000 follow userids ("shadow" role), 400,000 follow userids ("birddog" role), 10,000 track keywords ("restricted track" role), 200,000 track keywords ("partner track" role), and 200 10-degree location boxes ("locRestricted" role). Increased track access levels also pass a higher proportion of statuses before limiting the stream. * * @param query Filter query * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/filter">Twitter API Wiki / Streaming API Documentation - filter</a> * @since Twitter4J 2.1.2 */ public StatusStream getFilterStream(FilterQuery query) throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.post(conf.getStreamBaseURL() + "statuses/filter.json" , query.asHttpParameterArray(), auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Start consuming public statuses that match one or more filter predicates. At least one predicate parameter, follow, locations, or track must be specified. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Placing long parameters in the URL may cause the request to be rejected for excessive URL length.<br> * The default access level allows up to 200 track keywords, 400 follow userids and 10 1-degree location boxes. Increased access levels allow 80,000 follow userids ("shadow" role), 400,000 follow userids ("birddog" role), 10,000 track keywords ("restricted track" role), 200,000 track keywords ("partner track" role), and 200 10-degree location boxes ("locRestricted" role). Increased track access levels also pass a higher proportion of statuses before limiting the stream. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @param follow Specifies the users, by ID, to receive public tweets from. * @param track Specifies keywords to track. * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/filter">Twitter API Wiki / Streaming API Documentation - filter</a> * @since Twitter4J 2.0.10 * @deprecated use {@link #filter(FilterQuery)} instead */ public void filter(final int count, final int[] follow, final String[] track) { startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getFilterStream(count, follow, track); } }); } /** * Returns public statuses that match one or more filter predicates. At least one predicate parameter, follow, locations, or track must be specified. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Placing long parameters in the URL may cause the request to be rejected for excessive URL length.<br> * The default access level allows up to 200 track keywords, 400 follow userids and 10 1-degree location boxes. Increased access levels allow 80,000 follow userids ("shadow" role), 400,000 follow userids ("birddog" role), 10,000 track keywords ("restricted track" role), 200,000 track keywords ("partner track" role), and 200 10-degree location boxes ("locRestricted" role). Increased track access levels also pass a higher proportion of statuses before limiting the stream. * * @param follow Specifies the users, by ID, to receive public tweets from. * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/filter">Twitter API Wiki / Streaming API Documentation - filter</a> * @since Twitter4J 2.0.10 * @deprecated use {@link #getFilterStream(FilterQuery)} instead */ public StatusStream getFilterStream(int count, int[] follow, String[] track) throws TwitterException { return getFilterStream(new FilterQuery(count, follow, track, null)); } private synchronized void startHandler(StreamHandlingThread handler) { cleanup(); if (null == statusListener) { throw new IllegalStateException("StatusListener is not set."); } this.handler = handler; this.handler.start(); } public synchronized void cleanup() { if (null != handler) { try { handler.close(); } catch (IOException ignore) { } } } public void setStatusListener(StatusListener statusListener) { this.statusListener = statusListener; } /* http://apiwiki.twitter.com/Streaming-API-Documentation#Connecting When a network error (TCP/IP level) is encountered, back off linearly. Perhaps start at 250 milliseconds, double, and cap at 16 seconds When a HTTP error (> 200) is returned, back off exponentially. Perhaps start with a 10 second wait, double on each subsequent failure, and finally cap the wait at 240 seconds. Consider sending an alert to a human operator after multiple HTTP errors, as there is probably a client configuration issue that is unlikely to be resolved without human intervention. There's not much point in polling any faster in the face of HTTP error codes and your client is may run afoul of a rate limit. */ private static final int TCP_ERROR_INITIAL_WAIT = 250; private static final int TCP_ERROR_WAIT_CAP = 16 * 1000; private static final int HTTP_ERROR_INITIAL_WAIT = 10 * 1000; private static final int HTTP_ERROR_WAIT_CAP = 240 * 1000; abstract class StreamHandlingThread extends Thread { StatusStream stream = null; private static final String NAME = "Twitter Stream Handling Thread"; private boolean closed = false; StreamHandlingThread() { super(NAME + "[initializing]"); } public void run() { int timeToSleep = 0; while (!closed) { try { if (!closed && null == stream) { // try establishing connection setStatus("[Establishing connection]"); stream = getStream(); // connection established successfully timeToSleep = 0; setStatus("[Receiving stream]"); while (!closed) { stream.next(statusListener); } } } catch (TwitterException te) { if (!closed) { - if (0 == timeToSleep && te.getStatusCode() > 200) { - timeToSleep = HTTP_ERROR_INITIAL_WAIT; - } else { - timeToSleep = TCP_ERROR_INITIAL_WAIT; + if (0 == timeToSleep) { + if (te.getStatusCode() > 200) { + timeToSleep = HTTP_ERROR_INITIAL_WAIT; + } else { + timeToSleep = TCP_ERROR_INITIAL_WAIT; + } } // there was a problem establishing the connection, or the connection closed by peer if (!closed) { // wait for a moment not to overload Twitter API setStatus("[Waiting for " + (timeToSleep) + " milliseconds]"); try { Thread.sleep(timeToSleep); } catch (InterruptedException ignore) { } timeToSleep = Math.min(timeToSleep * 2, (te.getStatusCode() > 200) ? HTTP_ERROR_WAIT_CAP : TCP_ERROR_WAIT_CAP); } stream = null; logger.debug(te.getMessage()); statusListener.onException(te); } } } try { this.stream.close(); } catch (IOException ignore) { } } public synchronized void close() throws IOException { setStatus("[disposing thread]"); closed = true; } private void setStatus(String message) { String actualMessage = NAME + message; setName(actualMessage); logger.debug(actualMessage); } abstract StatusStream getStream() throws TwitterException; } } class StreamingReadTimeoutConfiguration implements HttpClientWrapperConfiguration { Configuration nestedConf; StreamingReadTimeoutConfiguration(Configuration httpConf) { this.nestedConf = httpConf; } public String getHttpProxyHost() { return nestedConf.getHttpProxyHost(); } public int getHttpProxyPort() { return nestedConf.getHttpProxyPort(); } public String getHttpProxyUser() { return nestedConf.getHttpProxyUser(); } public String getHttpProxyPassword() { return nestedConf.getHttpProxyPassword(); } public int getHttpConnectionTimeout() { return nestedConf.getHttpConnectionTimeout(); } public int getHttpReadTimeout() { // this is the trick that overrides connection timeout return nestedConf.getHttpStreamingReadTimeout(); } public int getHttpRetryCount() { return nestedConf.getHttpRetryCount(); } public int getHttpRetryIntervalSeconds() { return nestedConf.getHttpRetryIntervalSeconds(); } public Map<String, String> getRequestHeaders() { return nestedConf.getRequestHeaders(); } }
true
true
public void run() { int timeToSleep = 0; while (!closed) { try { if (!closed && null == stream) { // try establishing connection setStatus("[Establishing connection]"); stream = getStream(); // connection established successfully timeToSleep = 0; setStatus("[Receiving stream]"); while (!closed) { stream.next(statusListener); } } } catch (TwitterException te) { if (!closed) { if (0 == timeToSleep && te.getStatusCode() > 200) { timeToSleep = HTTP_ERROR_INITIAL_WAIT; } else { timeToSleep = TCP_ERROR_INITIAL_WAIT; } // there was a problem establishing the connection, or the connection closed by peer if (!closed) { // wait for a moment not to overload Twitter API setStatus("[Waiting for " + (timeToSleep) + " milliseconds]"); try { Thread.sleep(timeToSleep); } catch (InterruptedException ignore) { } timeToSleep = Math.min(timeToSleep * 2, (te.getStatusCode() > 200) ? HTTP_ERROR_WAIT_CAP : TCP_ERROR_WAIT_CAP); } stream = null; logger.debug(te.getMessage()); statusListener.onException(te); } } } try { this.stream.close(); } catch (IOException ignore) { } }
public void run() { int timeToSleep = 0; while (!closed) { try { if (!closed && null == stream) { // try establishing connection setStatus("[Establishing connection]"); stream = getStream(); // connection established successfully timeToSleep = 0; setStatus("[Receiving stream]"); while (!closed) { stream.next(statusListener); } } } catch (TwitterException te) { if (!closed) { if (0 == timeToSleep) { if (te.getStatusCode() > 200) { timeToSleep = HTTP_ERROR_INITIAL_WAIT; } else { timeToSleep = TCP_ERROR_INITIAL_WAIT; } } // there was a problem establishing the connection, or the connection closed by peer if (!closed) { // wait for a moment not to overload Twitter API setStatus("[Waiting for " + (timeToSleep) + " milliseconds]"); try { Thread.sleep(timeToSleep); } catch (InterruptedException ignore) { } timeToSleep = Math.min(timeToSleep * 2, (te.getStatusCode() > 200) ? HTTP_ERROR_WAIT_CAP : TCP_ERROR_WAIT_CAP); } stream = null; logger.debug(te.getMessage()); statusListener.onException(te); } } } try { this.stream.close(); } catch (IOException ignore) { } }
diff --git a/xjc/facade/com/sun/tools/xjc/ParallelWorldClassLoader.java b/xjc/facade/com/sun/tools/xjc/ParallelWorldClassLoader.java index 65b6ef01..31919ad9 100644 --- a/xjc/facade/com/sun/tools/xjc/ParallelWorldClassLoader.java +++ b/xjc/facade/com/sun/tools/xjc/ParallelWorldClassLoader.java @@ -1,142 +1,151 @@ package com.sun.tools.xjc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.List; import java.util.ArrayList; /** * Load classes/resources from a side folder, so that * classes of the same package can live in a single jar file. * * <p> * For example, with the following jar file: * <pre> * / * +- foo * +- X.class * +- bar * +- X.class * </pre> * <p> * {@link ParallelWorldClassLoader}("foo/") would load <tt>X.class<tt> from * <tt>/foo/X.class</tt> (note that X is defined in the root package, not * <tt>foo.X</tt>. * * <p> * This can be combined with {@link MaskingClassLoader} to mask classes which are loaded by the parent * class loader so that the child class loader * classes living in different folders are loaded * before the parent class loader loads classes living the jar file publicly * visible * For example, with the following jar file: * <pre> * / * +- foo * +- X.class * +- bar * +-foo * +- X.class * </pre> * <p> * {@link ParallelWorldClassLoader}(MaskingClassLoader.class.getClassLoader()) would load <tt>foo.X.class<tt> from * <tt>/bar/foo.X.class</tt> not the <tt>foo.X.class<tt> in the publicly visible place in the jar file, thus * masking the parent classLoader from loading the class from <tt>foo.X.class<tt> * (note that X is defined in the package foo, not * <tt>bar.foo.X</tt>. * * <p> * Don't use any JDK 5 classes in this class! * * @author Kohsuke Kawaguchi */ final class ParallelWorldClassLoader extends ClassLoader { /** * Strings like "prefix/", "abc/"... */ private final String prefix; /** * List of package prefixes we want to mask the * parent classLoader from loading */ private final List packagePrefixes; protected ParallelWorldClassLoader(ClassLoader parent,String prefix) { super(parent); this.prefix = prefix; packagePrefixes = getPackagePrefixes(); } protected Class findClass(String name) throws ClassNotFoundException { StringBuffer sb = new StringBuffer(name.length()+prefix.length()+6); if (prefix.equals("1.0")) sb.append(prefix).append('/').append(name.replace('.','/')).append(".class"); else //2.0 classes reside normally in the jar file without a prefix sb.append(name.replace('.','/')).append(".class"); InputStream is = getParent().getResourceAsStream(sb.toString()); if (is==null) return null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while((len=is.read(buf))>=0) baos.write(buf,0,len); buf = baos.toByteArray(); + int packIndex = name.lastIndexOf('.'); + if (packIndex != -1) { + String pkgname = name.substring(0, packIndex); + // Check if package already loaded. + Package pkg = getPackage(pkgname); + if (pkg == null) { + definePackage(pkgname, null, null, null, null, null, null, null); + } + } return defineClass(name,buf,0,buf.length); } catch (IOException e) { throw new ClassNotFoundException(name,e); } } protected URL findResource(String name) { return getParent().getResource(prefix.concat(name)); } protected Enumeration findResources(String name) throws IOException { return getParent().getResources(prefix.concat(name)); } public Class loadClass (String s) { try { //ToDo check if this can be made faster for (int i = 0; i < packagePrefixes.size(); i++ ) { String packprefix = (String)packagePrefixes.get(i); if (s.startsWith(packprefix) ) return findClass(s); } return getParent().loadClass(s); } catch(Exception e) { e.printStackTrace(); } return null ; } /** * The list of package prefixes we want the * {@link MaskingClassLoader} to prevent the parent * classLoader from loading * @return * List of package prefixes e.g com.sun.tools.xjc.driver */ private List getPackagePrefixes() { ArrayList prefixes = new ArrayList() ; //TODO check if more prefixes need to be added prefixes.add("com.sun.tools.xjc"); return prefixes; } }
true
true
protected Class findClass(String name) throws ClassNotFoundException { StringBuffer sb = new StringBuffer(name.length()+prefix.length()+6); if (prefix.equals("1.0")) sb.append(prefix).append('/').append(name.replace('.','/')).append(".class"); else //2.0 classes reside normally in the jar file without a prefix sb.append(name.replace('.','/')).append(".class"); InputStream is = getParent().getResourceAsStream(sb.toString()); if (is==null) return null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while((len=is.read(buf))>=0) baos.write(buf,0,len); buf = baos.toByteArray(); return defineClass(name,buf,0,buf.length); } catch (IOException e) { throw new ClassNotFoundException(name,e); } }
protected Class findClass(String name) throws ClassNotFoundException { StringBuffer sb = new StringBuffer(name.length()+prefix.length()+6); if (prefix.equals("1.0")) sb.append(prefix).append('/').append(name.replace('.','/')).append(".class"); else //2.0 classes reside normally in the jar file without a prefix sb.append(name.replace('.','/')).append(".class"); InputStream is = getParent().getResourceAsStream(sb.toString()); if (is==null) return null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while((len=is.read(buf))>=0) baos.write(buf,0,len); buf = baos.toByteArray(); int packIndex = name.lastIndexOf('.'); if (packIndex != -1) { String pkgname = name.substring(0, packIndex); // Check if package already loaded. Package pkg = getPackage(pkgname); if (pkg == null) { definePackage(pkgname, null, null, null, null, null, null, null); } } return defineClass(name,buf,0,buf.length); } catch (IOException e) { throw new ClassNotFoundException(name,e); } }
diff --git a/src/com/android/exchange/adapter/AbstractSyncParser.java b/src/com/android/exchange/adapter/AbstractSyncParser.java index 69d4ba4..a67b916 100644 --- a/src/com/android/exchange/adapter/AbstractSyncParser.java +++ b/src/com/android/exchange/adapter/AbstractSyncParser.java @@ -1,242 +1,244 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to 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.exchange.adapter; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent.MailboxColumns; import com.android.emailcommon.provider.Mailbox; import com.android.exchange.CommandStatusException; import com.android.exchange.CommandStatusException.CommandStatus; import com.android.exchange.EasSyncService; import com.android.exchange.ExchangeService; import java.io.IOException; import java.io.InputStream; /** * Base class for the Email and PIM sync parsers * Handles the basic flow of syncKeys, looping to get more data, handling errors, etc. * Each subclass must implement a handful of methods that relate specifically to the data type * */ public abstract class AbstractSyncParser extends Parser { protected EasSyncService mService; protected Mailbox mMailbox; protected Account mAccount; protected Context mContext; protected ContentResolver mContentResolver; protected AbstractSyncAdapter mAdapter; private boolean mLooping; public AbstractSyncParser(InputStream in, AbstractSyncAdapter adapter) throws IOException { super(in); init(adapter); } public AbstractSyncParser(Parser p, AbstractSyncAdapter adapter) throws IOException { super(p); init(adapter); } private void init(AbstractSyncAdapter adapter) { mAdapter = adapter; mService = adapter.mService; mContext = mService.mContext; mContentResolver = mContext.getContentResolver(); mMailbox = mService.mMailbox; mAccount = mService.mAccount; } /** * Read, parse, and act on incoming commands from the Exchange server * @throws IOException if the connection is broken * @throws CommandStatusException */ public abstract void commandsParser() throws IOException, CommandStatusException; /** * Read, parse, and act on server responses * @throws IOException */ public abstract void responsesParser() throws IOException; /** * Commit any changes found during parsing * @throws IOException */ public abstract void commit() throws IOException; public boolean isLooping() { return mLooping; } /** * Skip through tags until we reach the specified end tag * @param endTag the tag we end with * @throws IOException */ public void skipParser(int endTag) throws IOException { while (nextTag(endTag) != END) { skipTag(); } } /** * Loop through the top-level structure coming from the Exchange server * Sync keys and the more available flag are handled here, whereas specific data parsing * is handled by abstract methods implemented for each data class (e.g. Email, Contacts, etc.) * @throws CommandStatusException */ @Override public boolean parse() throws IOException, CommandStatusException { int status; boolean moreAvailable = false; boolean newSyncKey = false; int interval = mMailbox.mSyncInterval; mLooping = false; // If we're not at the top of the xml tree, throw an exception if (nextTag(START_DOCUMENT) != Tags.SYNC_SYNC) { throw new EasParserException(); } boolean mailboxUpdated = false; ContentValues cv = new ContentValues(); // Loop here through the remaining xml while (nextTag(START_DOCUMENT) != END_DOCUMENT) { if (tag == Tags.SYNC_COLLECTION || tag == Tags.SYNC_COLLECTIONS) { // Ignore these tags, since we've only got one collection syncing in this loop } else if (tag == Tags.SYNC_STATUS) { // Status = 1 is success; everything else is a failure status = getValueInt(); if (status != 1) { mService.errorLog("Sync failed: " + CommandStatus.toString(status)); if (status == 3 || CommandStatus.isBadSyncKey(status)) { // Must delete all of the data and start over with syncKey of "0" mAdapter.setSyncKey("0", false); // Make this a push box through the first sync // TODO Make frequency conditional on user settings! mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH; mService.errorLog("Bad sync key; RESET and delete data"); mAdapter.wipe(); // Indicate there's more so that we'll start syncing again moreAvailable = true; - } else if (status == 16) { - // Status 16 indicates a transient server error + } else if (status == 16 || status == 5) { + // Status 16 indicates a transient server error (indeterminate state) + // Status 5 indicates "server error"; this tends to loop for a while so + // throwing IOException will at least provide backoff behavior throw new IOException(); } else if (status == 8 || status == 12) { // Status 8 is Bad; it means the server doesn't recognize the serverId it // sent us. 12 means that we're being asked to refresh the folder list. // We'll do that with 8 also... ExchangeService.reloadFolderList(mContext, mAccount.mId, true); // We don't have any provision for telling the user "wait a minute while // we sync folders"... throw new IOException(); } if (status == 7) { mService.mUpsyncFailed = true; moreAvailable = true; } else { // Access, provisioning, transient, etc. throw new CommandStatusException(status); } } } else if (tag == Tags.SYNC_COMMANDS) { commandsParser(); } else if (tag == Tags.SYNC_RESPONSES) { responsesParser(); } else if (tag == Tags.SYNC_MORE_AVAILABLE) { moreAvailable = true; } else if (tag == Tags.SYNC_SYNC_KEY) { if (mAdapter.getSyncKey().equals("0")) { moreAvailable = true; } String newKey = getValue(); userLog("Parsed key for ", mMailbox.mDisplayName, ": ", newKey); if (!newKey.equals(mMailbox.mSyncKey)) { mAdapter.setSyncKey(newKey, true); cv.put(MailboxColumns.SYNC_KEY, newKey); mailboxUpdated = true; newSyncKey = true; } // If we were pushing (i.e. auto-start), now we'll become ping-triggered if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) { mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PING; } } else { skipTag(); } } // If we don't have a new sync key, ignore moreAvailable (or we'll loop) if (moreAvailable && !newSyncKey) { mLooping = true; } // Commit any changes commit(); boolean abortSyncs = false; // If the sync interval has changed, we need to save it if (mMailbox.mSyncInterval != interval) { cv.put(MailboxColumns.SYNC_INTERVAL, mMailbox.mSyncInterval); mailboxUpdated = true; // If there are changes, and we were bounced from push/ping, try again } else if (mService.mChangeCount > 0 && mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH && mMailbox.mSyncInterval > 0) { userLog("Changes found to ping loop mailbox ", mMailbox.mDisplayName, ": will ping."); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING); mailboxUpdated = true; abortSyncs = true; } if (mailboxUpdated) { synchronized (mService.getSynchronizer()) { if (!mService.isStopped()) { mMailbox.update(mContext, cv); } } } if (abortSyncs) { userLog("Aborting account syncs due to mailbox change to ping..."); ExchangeService.stopAccountSyncs(mAccount.mId); } // Let the caller know that there's more to do if (moreAvailable) { userLog("MoreAvailable"); } return moreAvailable; } void userLog(String ...strings) { mService.userLog(strings); } void userLog(String string, int num, String string2) { mService.userLog(string, num, string2); } }
true
true
public boolean parse() throws IOException, CommandStatusException { int status; boolean moreAvailable = false; boolean newSyncKey = false; int interval = mMailbox.mSyncInterval; mLooping = false; // If we're not at the top of the xml tree, throw an exception if (nextTag(START_DOCUMENT) != Tags.SYNC_SYNC) { throw new EasParserException(); } boolean mailboxUpdated = false; ContentValues cv = new ContentValues(); // Loop here through the remaining xml while (nextTag(START_DOCUMENT) != END_DOCUMENT) { if (tag == Tags.SYNC_COLLECTION || tag == Tags.SYNC_COLLECTIONS) { // Ignore these tags, since we've only got one collection syncing in this loop } else if (tag == Tags.SYNC_STATUS) { // Status = 1 is success; everything else is a failure status = getValueInt(); if (status != 1) { mService.errorLog("Sync failed: " + CommandStatus.toString(status)); if (status == 3 || CommandStatus.isBadSyncKey(status)) { // Must delete all of the data and start over with syncKey of "0" mAdapter.setSyncKey("0", false); // Make this a push box through the first sync // TODO Make frequency conditional on user settings! mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH; mService.errorLog("Bad sync key; RESET and delete data"); mAdapter.wipe(); // Indicate there's more so that we'll start syncing again moreAvailable = true; } else if (status == 16) { // Status 16 indicates a transient server error throw new IOException(); } else if (status == 8 || status == 12) { // Status 8 is Bad; it means the server doesn't recognize the serverId it // sent us. 12 means that we're being asked to refresh the folder list. // We'll do that with 8 also... ExchangeService.reloadFolderList(mContext, mAccount.mId, true); // We don't have any provision for telling the user "wait a minute while // we sync folders"... throw new IOException(); } if (status == 7) { mService.mUpsyncFailed = true; moreAvailable = true; } else { // Access, provisioning, transient, etc. throw new CommandStatusException(status); } } } else if (tag == Tags.SYNC_COMMANDS) { commandsParser(); } else if (tag == Tags.SYNC_RESPONSES) { responsesParser(); } else if (tag == Tags.SYNC_MORE_AVAILABLE) { moreAvailable = true; } else if (tag == Tags.SYNC_SYNC_KEY) { if (mAdapter.getSyncKey().equals("0")) { moreAvailable = true; } String newKey = getValue(); userLog("Parsed key for ", mMailbox.mDisplayName, ": ", newKey); if (!newKey.equals(mMailbox.mSyncKey)) { mAdapter.setSyncKey(newKey, true); cv.put(MailboxColumns.SYNC_KEY, newKey); mailboxUpdated = true; newSyncKey = true; } // If we were pushing (i.e. auto-start), now we'll become ping-triggered if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) { mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PING; } } else { skipTag(); } } // If we don't have a new sync key, ignore moreAvailable (or we'll loop) if (moreAvailable && !newSyncKey) { mLooping = true; } // Commit any changes commit(); boolean abortSyncs = false; // If the sync interval has changed, we need to save it if (mMailbox.mSyncInterval != interval) { cv.put(MailboxColumns.SYNC_INTERVAL, mMailbox.mSyncInterval); mailboxUpdated = true; // If there are changes, and we were bounced from push/ping, try again } else if (mService.mChangeCount > 0 && mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH && mMailbox.mSyncInterval > 0) { userLog("Changes found to ping loop mailbox ", mMailbox.mDisplayName, ": will ping."); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING); mailboxUpdated = true; abortSyncs = true; } if (mailboxUpdated) { synchronized (mService.getSynchronizer()) { if (!mService.isStopped()) { mMailbox.update(mContext, cv); } } } if (abortSyncs) { userLog("Aborting account syncs due to mailbox change to ping..."); ExchangeService.stopAccountSyncs(mAccount.mId); } // Let the caller know that there's more to do if (moreAvailable) { userLog("MoreAvailable"); } return moreAvailable; }
public boolean parse() throws IOException, CommandStatusException { int status; boolean moreAvailable = false; boolean newSyncKey = false; int interval = mMailbox.mSyncInterval; mLooping = false; // If we're not at the top of the xml tree, throw an exception if (nextTag(START_DOCUMENT) != Tags.SYNC_SYNC) { throw new EasParserException(); } boolean mailboxUpdated = false; ContentValues cv = new ContentValues(); // Loop here through the remaining xml while (nextTag(START_DOCUMENT) != END_DOCUMENT) { if (tag == Tags.SYNC_COLLECTION || tag == Tags.SYNC_COLLECTIONS) { // Ignore these tags, since we've only got one collection syncing in this loop } else if (tag == Tags.SYNC_STATUS) { // Status = 1 is success; everything else is a failure status = getValueInt(); if (status != 1) { mService.errorLog("Sync failed: " + CommandStatus.toString(status)); if (status == 3 || CommandStatus.isBadSyncKey(status)) { // Must delete all of the data and start over with syncKey of "0" mAdapter.setSyncKey("0", false); // Make this a push box through the first sync // TODO Make frequency conditional on user settings! mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH; mService.errorLog("Bad sync key; RESET and delete data"); mAdapter.wipe(); // Indicate there's more so that we'll start syncing again moreAvailable = true; } else if (status == 16 || status == 5) { // Status 16 indicates a transient server error (indeterminate state) // Status 5 indicates "server error"; this tends to loop for a while so // throwing IOException will at least provide backoff behavior throw new IOException(); } else if (status == 8 || status == 12) { // Status 8 is Bad; it means the server doesn't recognize the serverId it // sent us. 12 means that we're being asked to refresh the folder list. // We'll do that with 8 also... ExchangeService.reloadFolderList(mContext, mAccount.mId, true); // We don't have any provision for telling the user "wait a minute while // we sync folders"... throw new IOException(); } if (status == 7) { mService.mUpsyncFailed = true; moreAvailable = true; } else { // Access, provisioning, transient, etc. throw new CommandStatusException(status); } } } else if (tag == Tags.SYNC_COMMANDS) { commandsParser(); } else if (tag == Tags.SYNC_RESPONSES) { responsesParser(); } else if (tag == Tags.SYNC_MORE_AVAILABLE) { moreAvailable = true; } else if (tag == Tags.SYNC_SYNC_KEY) { if (mAdapter.getSyncKey().equals("0")) { moreAvailable = true; } String newKey = getValue(); userLog("Parsed key for ", mMailbox.mDisplayName, ": ", newKey); if (!newKey.equals(mMailbox.mSyncKey)) { mAdapter.setSyncKey(newKey, true); cv.put(MailboxColumns.SYNC_KEY, newKey); mailboxUpdated = true; newSyncKey = true; } // If we were pushing (i.e. auto-start), now we'll become ping-triggered if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) { mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PING; } } else { skipTag(); } } // If we don't have a new sync key, ignore moreAvailable (or we'll loop) if (moreAvailable && !newSyncKey) { mLooping = true; } // Commit any changes commit(); boolean abortSyncs = false; // If the sync interval has changed, we need to save it if (mMailbox.mSyncInterval != interval) { cv.put(MailboxColumns.SYNC_INTERVAL, mMailbox.mSyncInterval); mailboxUpdated = true; // If there are changes, and we were bounced from push/ping, try again } else if (mService.mChangeCount > 0 && mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH && mMailbox.mSyncInterval > 0) { userLog("Changes found to ping loop mailbox ", mMailbox.mDisplayName, ": will ping."); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING); mailboxUpdated = true; abortSyncs = true; } if (mailboxUpdated) { synchronized (mService.getSynchronizer()) { if (!mService.isStopped()) { mMailbox.update(mContext, cv); } } } if (abortSyncs) { userLog("Aborting account syncs due to mailbox change to ping..."); ExchangeService.stopAccountSyncs(mAccount.mId); } // Let the caller know that there's more to do if (moreAvailable) { userLog("MoreAvailable"); } return moreAvailable; }
diff --git a/src/java/org/apache/hadoop/dfs/FSImage.java b/src/java/org/apache/hadoop/dfs/FSImage.java index 23507b966..c8db70ae4 100644 --- a/src/java/org/apache/hadoop/dfs/FSImage.java +++ b/src/java/org/apache/hadoop/dfs/FSImage.java @@ -1,336 +1,336 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.dfs; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.Random; import java.util.TreeMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.dfs.FSDirectory.INode; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.io.UTF8; /** * FSImage handles checkpointing and logging of the namespace edits. * * @author Konstantin Shvachko */ class FSImage { private static final String FS_IMAGE = "fsimage"; private static final String NEW_FS_IMAGE = "fsimage.new"; private static final String OLD_FS_IMAGE = "fsimage.old"; private static final String FS_TIME = "fstime"; private File[] imageDirs; /// directories that contains the image file private FSEditLog editLog; // private int namespaceID = 0; /// a persistent attribute of the namespace /** * */ FSImage( File[] fsDirs ) throws IOException { this.imageDirs = new File[fsDirs.length]; for (int idx = 0; idx < imageDirs.length; idx++) { imageDirs[idx] = new File(fsDirs[idx], "image"); if (! imageDirs[idx].exists()) { throw new IOException("NameNode not formatted: " + imageDirs[idx]); } } File[] edits = new File[fsDirs.length]; for (int idx = 0; idx < edits.length; idx++) { edits[idx] = new File(fsDirs[idx], "edits"); } this.editLog = new FSEditLog( edits ); } FSEditLog getEditLog() { return editLog; } /** * Load in the filesystem image. It's a big list of * filenames and blocks. Return whether we should * "re-save" and consolidate the edit-logs */ void loadFSImage( Configuration conf ) throws IOException { FSNamesystem fsNamesys = FSNamesystem.getFSNamesystem(); FSDirectory fsDir = fsNamesys.dir; for (int idx = 0; idx < imageDirs.length; idx++) { // // Atomic move sequence, to recover from interrupted save // File curFile = new File(imageDirs[idx], FS_IMAGE); File newFile = new File(imageDirs[idx], NEW_FS_IMAGE); File oldFile = new File(imageDirs[idx], OLD_FS_IMAGE); // Maybe we were interrupted between 2 and 4 if (oldFile.exists() && curFile.exists()) { oldFile.delete(); if (editLog.exists()) { editLog.deleteAll(); } } else if (oldFile.exists() && newFile.exists()) { // Or maybe between 1 and 2 newFile.renameTo(curFile); oldFile.delete(); } else if (curFile.exists() && newFile.exists()) { // Or else before stage 1, in which case we lose the edits newFile.delete(); } } // Now check all curFiles and see which is the newest File curFile = null; - long maxTimeStamp = 0; + long maxTimeStamp = Long.MIN_VALUE; for (int idx = 0; idx < imageDirs.length; idx++) { File file = new File(imageDirs[idx], FS_IMAGE); if (file.exists()) { long timeStamp = 0; File timeFile = new File(imageDirs[idx], FS_TIME); if (timeFile.exists() && timeFile.canRead()) { DataInputStream in = new DataInputStream( new FileInputStream(timeFile)); try { timeStamp = in.readLong(); } finally { in.close(); } } if (maxTimeStamp < timeStamp) { maxTimeStamp = timeStamp; curFile = file; } } } // // Load in bits // boolean needToSave = true; int imgVersion = FSConstants.DFS_CURRENT_VERSION; if (curFile != null) { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream(curFile))); try { // read image version: first appeared in version -1 imgVersion = in.readInt(); // read namespaceID: first appeared in version -2 if( imgVersion <= -2 ) fsDir.namespaceID = in.readInt(); // read number of files int numFiles = 0; // version 0 does not store version # // starts directly with the number of files if( imgVersion >= 0 ) { numFiles = imgVersion; imgVersion = 0; } else numFiles = in.readInt(); needToSave = ( imgVersion != FSConstants.DFS_CURRENT_VERSION ); if( imgVersion < FSConstants.DFS_CURRENT_VERSION ) // future version throw new IncorrectVersionException(imgVersion, "file system image"); // read file info short replication = (short)conf.getInt("dfs.replication", 3); for (int i = 0; i < numFiles; i++) { UTF8 name = new UTF8(); name.readFields(in); // version 0 does not support per file replication if( !(imgVersion >= 0) ) { replication = in.readShort(); // other versions do replication = FSEditLog.adjustReplication( replication, conf ); } int numBlocks = in.readInt(); Block blocks[] = null; if (numBlocks > 0) { blocks = new Block[numBlocks]; for (int j = 0; j < numBlocks; j++) { blocks[j] = new Block(); blocks[j].readFields(in); } } fsDir.unprotectedAddFile(name, blocks, replication ); } // load datanode info this.loadDatanodes( imgVersion, in ); } finally { in.close(); } } if( fsDir.namespaceID == 0 ) fsDir.namespaceID = newNamespaceID(); needToSave |= ( editLog.exists() && editLog.loadFSEdits(conf) > 0 ); if( needToSave ) saveFSImage(); } /** * Save the contents of the FS image */ void saveFSImage() throws IOException { FSNamesystem fsNamesys = FSNamesystem.getFSNamesystem(); FSDirectory fsDir = fsNamesys.dir; for (int idx = 0; idx < imageDirs.length; idx++) { File newFile = new File(imageDirs[idx], NEW_FS_IMAGE); // // Write out data // DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(newFile))); try { out.writeInt(FSConstants.DFS_CURRENT_VERSION); out.writeInt(fsDir.namespaceID); out.writeInt(fsDir.rootDir.numItemsInTree() - 1); saveImage( "", fsDir.rootDir, out ); saveDatanodes( out ); } finally { out.close(); } } // // Atomic move sequence // for (int idx = 0; idx < imageDirs.length; idx++) { File curFile = new File(imageDirs[idx], FS_IMAGE); File newFile = new File(imageDirs[idx], NEW_FS_IMAGE); File oldFile = new File(imageDirs[idx], OLD_FS_IMAGE); File timeFile = new File(imageDirs[idx], FS_TIME); // 1. Move cur to old and delete timeStamp curFile.renameTo(oldFile); if (timeFile.exists()) { timeFile.delete(); } // 2. Move new to cur and write timestamp newFile.renameTo(curFile); DataOutputStream out = new DataOutputStream( new FileOutputStream(timeFile)); try { out.writeLong(System.currentTimeMillis()); } finally { out.close(); } // 3. Remove pending-edits file (it's been integrated with newFile) editLog.delete(idx); // 4. Delete old oldFile.delete(); } } /** * Generate new namespaceID. * * namespaceID is a persistent attribute of the namespace. * It is generated when the namenode is formatted and remains the same * during the life cycle of the namenode. * When a datanodes register they receive it as the registrationID, * which is checked every time the datanode is communicating with the * namenode. Datanodes that do not 'know' the namespaceID are rejected. * * @return new namespaceID */ private int newNamespaceID() { Random r = new Random(); r.setSeed( System.currentTimeMillis() ); int newID = 0; while( newID == 0) newID = r.nextInt(); return newID; } /** Create new dfs name directory. Caution: this destroys all files * in this filesystem. */ static void format(File dir) throws IOException { File image = new File(dir, "image"); File edits = new File(dir, "edits"); if (!((!image.exists() || FileUtil.fullyDelete(image)) && (!edits.exists() || edits.delete()) && image.mkdirs())) { throw new IOException("Unable to format: "+dir); } } /** * Save file tree image starting from the given root. */ void saveImage( String parentPrefix, FSDirectory.INode root, DataOutputStream out ) throws IOException { String fullName = ""; if( root.getParent() != null) { fullName = parentPrefix + "/" + root.getLocalName(); new UTF8(fullName).write(out); out.writeShort( root.getReplication() ); if( root.isDir() ) { out.writeInt(0); } else { int nrBlocks = root.getBlocks().length; out.writeInt( nrBlocks ); for (int i = 0; i < nrBlocks; i++) root.getBlocks()[i].write(out); } } for(Iterator it = root.getChildren().values().iterator(); it.hasNext(); ) { INode child = (INode) it.next(); saveImage( fullName, child, out ); } } /** * Save list of datanodes contained in {@link FSNamesystem#datanodeMap}. * Only the {@link DatanodeInfo} part is stored. * The {@link DatanodeDescriptor#blocks} is transient. * * @param out output stream * @throws IOException */ void saveDatanodes( DataOutputStream out ) throws IOException { TreeMap datanodeMap = FSNamesystem.getFSNamesystem().datanodeMap; int size = datanodeMap.size(); out.writeInt( size ); for( Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) ((DatanodeDescriptor)it.next()).write( out ); } void loadDatanodes( int version, DataInputStream in ) throws IOException { if( version > -3 ) // pre datanode image version return; FSNamesystem fsNamesys = FSNamesystem.getFSNamesystem(); int size = in.readInt(); for( int i = 0; i < size; i++ ) { DatanodeDescriptor node = new DatanodeDescriptor(); node.readFields(in); fsNamesys.unprotectedAddDatanode( node ); } } }
true
true
void loadFSImage( Configuration conf ) throws IOException { FSNamesystem fsNamesys = FSNamesystem.getFSNamesystem(); FSDirectory fsDir = fsNamesys.dir; for (int idx = 0; idx < imageDirs.length; idx++) { // // Atomic move sequence, to recover from interrupted save // File curFile = new File(imageDirs[idx], FS_IMAGE); File newFile = new File(imageDirs[idx], NEW_FS_IMAGE); File oldFile = new File(imageDirs[idx], OLD_FS_IMAGE); // Maybe we were interrupted between 2 and 4 if (oldFile.exists() && curFile.exists()) { oldFile.delete(); if (editLog.exists()) { editLog.deleteAll(); } } else if (oldFile.exists() && newFile.exists()) { // Or maybe between 1 and 2 newFile.renameTo(curFile); oldFile.delete(); } else if (curFile.exists() && newFile.exists()) { // Or else before stage 1, in which case we lose the edits newFile.delete(); } } // Now check all curFiles and see which is the newest File curFile = null; long maxTimeStamp = 0; for (int idx = 0; idx < imageDirs.length; idx++) { File file = new File(imageDirs[idx], FS_IMAGE); if (file.exists()) { long timeStamp = 0; File timeFile = new File(imageDirs[idx], FS_TIME); if (timeFile.exists() && timeFile.canRead()) { DataInputStream in = new DataInputStream( new FileInputStream(timeFile)); try { timeStamp = in.readLong(); } finally { in.close(); } } if (maxTimeStamp < timeStamp) { maxTimeStamp = timeStamp; curFile = file; } } } // // Load in bits // boolean needToSave = true; int imgVersion = FSConstants.DFS_CURRENT_VERSION; if (curFile != null) { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream(curFile))); try { // read image version: first appeared in version -1 imgVersion = in.readInt(); // read namespaceID: first appeared in version -2 if( imgVersion <= -2 ) fsDir.namespaceID = in.readInt(); // read number of files int numFiles = 0; // version 0 does not store version # // starts directly with the number of files if( imgVersion >= 0 ) { numFiles = imgVersion; imgVersion = 0; } else numFiles = in.readInt(); needToSave = ( imgVersion != FSConstants.DFS_CURRENT_VERSION ); if( imgVersion < FSConstants.DFS_CURRENT_VERSION ) // future version throw new IncorrectVersionException(imgVersion, "file system image"); // read file info short replication = (short)conf.getInt("dfs.replication", 3); for (int i = 0; i < numFiles; i++) { UTF8 name = new UTF8(); name.readFields(in); // version 0 does not support per file replication if( !(imgVersion >= 0) ) { replication = in.readShort(); // other versions do replication = FSEditLog.adjustReplication( replication, conf ); } int numBlocks = in.readInt(); Block blocks[] = null; if (numBlocks > 0) { blocks = new Block[numBlocks]; for (int j = 0; j < numBlocks; j++) { blocks[j] = new Block(); blocks[j].readFields(in); } } fsDir.unprotectedAddFile(name, blocks, replication ); } // load datanode info this.loadDatanodes( imgVersion, in ); } finally { in.close(); } } if( fsDir.namespaceID == 0 ) fsDir.namespaceID = newNamespaceID(); needToSave |= ( editLog.exists() && editLog.loadFSEdits(conf) > 0 ); if( needToSave ) saveFSImage(); }
void loadFSImage( Configuration conf ) throws IOException { FSNamesystem fsNamesys = FSNamesystem.getFSNamesystem(); FSDirectory fsDir = fsNamesys.dir; for (int idx = 0; idx < imageDirs.length; idx++) { // // Atomic move sequence, to recover from interrupted save // File curFile = new File(imageDirs[idx], FS_IMAGE); File newFile = new File(imageDirs[idx], NEW_FS_IMAGE); File oldFile = new File(imageDirs[idx], OLD_FS_IMAGE); // Maybe we were interrupted between 2 and 4 if (oldFile.exists() && curFile.exists()) { oldFile.delete(); if (editLog.exists()) { editLog.deleteAll(); } } else if (oldFile.exists() && newFile.exists()) { // Or maybe between 1 and 2 newFile.renameTo(curFile); oldFile.delete(); } else if (curFile.exists() && newFile.exists()) { // Or else before stage 1, in which case we lose the edits newFile.delete(); } } // Now check all curFiles and see which is the newest File curFile = null; long maxTimeStamp = Long.MIN_VALUE; for (int idx = 0; idx < imageDirs.length; idx++) { File file = new File(imageDirs[idx], FS_IMAGE); if (file.exists()) { long timeStamp = 0; File timeFile = new File(imageDirs[idx], FS_TIME); if (timeFile.exists() && timeFile.canRead()) { DataInputStream in = new DataInputStream( new FileInputStream(timeFile)); try { timeStamp = in.readLong(); } finally { in.close(); } } if (maxTimeStamp < timeStamp) { maxTimeStamp = timeStamp; curFile = file; } } } // // Load in bits // boolean needToSave = true; int imgVersion = FSConstants.DFS_CURRENT_VERSION; if (curFile != null) { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream(curFile))); try { // read image version: first appeared in version -1 imgVersion = in.readInt(); // read namespaceID: first appeared in version -2 if( imgVersion <= -2 ) fsDir.namespaceID = in.readInt(); // read number of files int numFiles = 0; // version 0 does not store version # // starts directly with the number of files if( imgVersion >= 0 ) { numFiles = imgVersion; imgVersion = 0; } else numFiles = in.readInt(); needToSave = ( imgVersion != FSConstants.DFS_CURRENT_VERSION ); if( imgVersion < FSConstants.DFS_CURRENT_VERSION ) // future version throw new IncorrectVersionException(imgVersion, "file system image"); // read file info short replication = (short)conf.getInt("dfs.replication", 3); for (int i = 0; i < numFiles; i++) { UTF8 name = new UTF8(); name.readFields(in); // version 0 does not support per file replication if( !(imgVersion >= 0) ) { replication = in.readShort(); // other versions do replication = FSEditLog.adjustReplication( replication, conf ); } int numBlocks = in.readInt(); Block blocks[] = null; if (numBlocks > 0) { blocks = new Block[numBlocks]; for (int j = 0; j < numBlocks; j++) { blocks[j] = new Block(); blocks[j].readFields(in); } } fsDir.unprotectedAddFile(name, blocks, replication ); } // load datanode info this.loadDatanodes( imgVersion, in ); } finally { in.close(); } } if( fsDir.namespaceID == 0 ) fsDir.namespaceID = newNamespaceID(); needToSave |= ( editLog.exists() && editLog.loadFSEdits(conf) > 0 ); if( needToSave ) saveFSImage(); }
diff --git a/src/java/net/hi117/unique/swingui/MainFrame.java b/src/java/net/hi117/unique/swingui/MainFrame.java index cdb0a26..3f04447 100644 --- a/src/java/net/hi117/unique/swingui/MainFrame.java +++ b/src/java/net/hi117/unique/swingui/MainFrame.java @@ -1,76 +1,78 @@ package net.hi117.unique.swingui; import net.hi117.unique.Game; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; /** * @author Yanus Poluektovich ([email protected]) */ public class MainFrame extends JFrame { private static final String MENU_SCREEN = "Menu screen"; private static final String GAME_SCREEN = "Game screen"; private final CardLayout myCardLayout = new CardLayout(); private final MenuScreen myMenuScreen; private final GameScreen myGameScreen; private volatile GameWorkerThread myGameWorkerThread; public MainFrame() throws InvocationTargetException, InterruptedException { super("Unique"); getContentPane().setLayout(myCardLayout); myMenuScreen = new MenuScreen(new Runnable() { @Override public void run() { myCardLayout.show(getContentPane(), GAME_SCREEN); myGameWorkerThread = new GameWorkerThread(new Game()); myGameWorkerThread.execute(); } }); getContentPane().add(myMenuScreen, MENU_SCREEN); myGameScreen = new GameScreen(new Callback<Boolean>() { @Override public void doWith(final Boolean victory) { myMenuScreen.setLabel(victory); myCardLayout.show(getContentPane(), MENU_SCREEN); } }); getContentPane().add(myGameScreen, GAME_SCREEN); myCardLayout.show(getContentPane(), MENU_SCREEN); setMinimumSize(new Dimension(400, 300)); pack(); addWindowListener( new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { - myGameWorkerThread.cancel(true); - try { - myGameWorkerThread.get(); - } catch (InterruptedException | ExecutionException | - CancellationException ignore) { - // ignore + if (myGameWorkerThread != null) { + myGameWorkerThread.cancel(true); + try { + myGameWorkerThread.get(); + } catch (InterruptedException | ExecutionException | + CancellationException ignore) { + // ignore + } } MainFrame.this.dispose(); } } ); } }
true
true
public MainFrame() throws InvocationTargetException, InterruptedException { super("Unique"); getContentPane().setLayout(myCardLayout); myMenuScreen = new MenuScreen(new Runnable() { @Override public void run() { myCardLayout.show(getContentPane(), GAME_SCREEN); myGameWorkerThread = new GameWorkerThread(new Game()); myGameWorkerThread.execute(); } }); getContentPane().add(myMenuScreen, MENU_SCREEN); myGameScreen = new GameScreen(new Callback<Boolean>() { @Override public void doWith(final Boolean victory) { myMenuScreen.setLabel(victory); myCardLayout.show(getContentPane(), MENU_SCREEN); } }); getContentPane().add(myGameScreen, GAME_SCREEN); myCardLayout.show(getContentPane(), MENU_SCREEN); setMinimumSize(new Dimension(400, 300)); pack(); addWindowListener( new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { myGameWorkerThread.cancel(true); try { myGameWorkerThread.get(); } catch (InterruptedException | ExecutionException | CancellationException ignore) { // ignore } MainFrame.this.dispose(); } } ); }
public MainFrame() throws InvocationTargetException, InterruptedException { super("Unique"); getContentPane().setLayout(myCardLayout); myMenuScreen = new MenuScreen(new Runnable() { @Override public void run() { myCardLayout.show(getContentPane(), GAME_SCREEN); myGameWorkerThread = new GameWorkerThread(new Game()); myGameWorkerThread.execute(); } }); getContentPane().add(myMenuScreen, MENU_SCREEN); myGameScreen = new GameScreen(new Callback<Boolean>() { @Override public void doWith(final Boolean victory) { myMenuScreen.setLabel(victory); myCardLayout.show(getContentPane(), MENU_SCREEN); } }); getContentPane().add(myGameScreen, GAME_SCREEN); myCardLayout.show(getContentPane(), MENU_SCREEN); setMinimumSize(new Dimension(400, 300)); pack(); addWindowListener( new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { if (myGameWorkerThread != null) { myGameWorkerThread.cancel(true); try { myGameWorkerThread.get(); } catch (InterruptedException | ExecutionException | CancellationException ignore) { // ignore } } MainFrame.this.dispose(); } } ); }
diff --git a/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java b/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java index 21fb5e97..78ccdd41 100644 --- a/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java +++ b/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java @@ -1,555 +1,555 @@ package gov.nih.nci.evs.browser.bean; import java.io.File; import gov.nih.nci.evs.browser.utils.MailUtils; import gov.nih.nci.evs.browser.utils.SortUtils; import gov.nih.nci.evs.browser.utils.SearchUtils; import gov.nih.nci.evs.browser.utils.Utils; import gov.nih.nci.evs.browser.properties.NCImBrowserProperties; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.HashSet; import java.util.Date; import javax.faces.context.FacesContext; import javax.faces.event.ValueChangeEvent; import javax.faces.model.SelectItem; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import java.util.Collection; import org.LexGrid.concepts.Concept; import gov.nih.nci.evs.browser.properties.NCImBrowserProperties; import gov.nih.nci.evs.browser.utils.*; import gov.nih.nci.evs.browser.common.Constants; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction with the National Cancer Institute, * and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. 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. * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National Cancer Institute." * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize * the recipient to use any trademarks owned by either NCI or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES 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. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history * Initial implementation [email protected] * */ public class UserSessionBean extends Object { private static Logger KLO_log = Logger.getLogger("UserSessionBean KLO"); private String selectedQuickLink = null; private List quickLinkList = null; public void setSelectedQuickLink(String selectedQuickLink) { this.selectedQuickLink = selectedQuickLink; HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); request.getSession().setAttribute("selectedQuickLink", selectedQuickLink); } public String getSelectedQuickLink() { return this.selectedQuickLink; } public void quickLinkChanged(ValueChangeEvent event) { if (event.getNewValue() == null) return; String newValue = (String) event.getNewValue(); System.out.println("quickLinkChanged; " + newValue); setSelectedQuickLink(newValue); HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); String targetURL = null;//"http://nciterms.nci.nih.gov/"; if (selectedQuickLink.compareTo("NCI Terminology Browser") == 0) { targetURL = "http://nciterms.nci.nih.gov/"; } try { response.sendRedirect(response.encodeRedirectURL(targetURL)); } catch (Exception ex) { ex.printStackTrace(); // send error message } } public List getQuickLinkList() { quickLinkList = new ArrayList(); quickLinkList.add(new SelectItem("Quick Links")); quickLinkList.add(new SelectItem("NCI Terminology Browser")); //quickLinkList.add(new SelectItem(Constants.CODING_SCHEME_NAME)); quickLinkList.add(new SelectItem("EVS Home")); quickLinkList.add(new SelectItem("NCI Terminology Resources")); return quickLinkList; } public String searchAction() { HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); String matchText = (String) request.getParameter("matchText"); if (matchText != null) matchText = matchText.trim(); //[#19965] Error message is not displayed when Search Criteria is not proivded if (matchText == null || matchText.length() == 0) { String message = "Please enter a search string."; request.getSession().setAttribute("message", message); return "message"; } request.getSession().setAttribute("matchText", matchText); String matchAlgorithm = (String) request.getParameter("algorithm"); setSelectedAlgorithm(matchAlgorithm); String matchtype = (String) request.getParameter("matchtype"); if (matchtype == null) matchtype = "string"; //Remove ranking check box (KLO, 092409) //String rankingStr = (String) request.getParameter("ranking"); //boolean ranking = rankingStr != null && rankingStr.equals("on"); //request.getSession().setAttribute("ranking", Boolean.toString(ranking)); String source = (String) request.getParameter("source"); if (source == null) { source = "ALL"; } //request.getSession().setAttribute("source", source); setSelectedSource(source); if (NCImBrowserProperties.debugOn) { try { System.out.println(Utils.SEPARATOR); System.out.println("* criteria: " + matchText); System.out.println("* matchType: " + matchtype); System.out.println("* source: " + source); //System.out.println("* ranking: " + ranking); // System.out.println("* sortOption: " + sortOption); } catch (Exception e) { } } String scheme = Constants.CODING_SCHEME_NAME; String version = null; String max_str = null; int maxToReturn = -1;//1000; try { max_str = NCImBrowserProperties.getInstance().getProperty(NCImBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); } catch (Exception ex) { } Utils.StopWatch stopWatch = new Utils.StopWatch(); Vector<org.LexGrid.concepts.Concept> v = null; //v = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, sortOption, maxToReturn); //ResolvedConceptReferencesIterator iterator = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, ranking, maxToReturn); ResolvedConceptReferencesIterator iterator = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, maxToReturn); request.getSession().setAttribute("vocabulary", scheme); request.getSession().setAttribute("matchAlgorithm", matchAlgorithm); //request.getSession().setAttribute("matchtype", matchtype); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); request.getSession().removeAttribute("concept"); request.getSession().removeAttribute("code"); request.getSession().removeAttribute("codeInNCI"); request.getSession().removeAttribute("AssociationTargetHashMap"); request.getSession().removeAttribute("type"); //if (v != null && v.size() > 1) if (iterator != null) { IteratorBean iteratorBean = (IteratorBean) FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().get("iteratorBean"); if (iteratorBean == null) { iteratorBean = new IteratorBean(iterator); FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().put("iteratorBean", iteratorBean); } else { iteratorBean.setIterator(iterator); } int size = iteratorBean.getSize(); if (size > 1) { request.getSession().setAttribute("search_results", v); String match_size = Integer.toString(size);;//Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); return "search_results"; } else if (size == 1) { request.getSession().setAttribute("singleton", "true"); request.getSession().setAttribute("dictionary", Constants.CODING_SCHEME_NAME); //Concept c = (Concept) v.elementAt(0); int pageNumber = 1; List list = iteratorBean.getData(1); ResolvedConceptReference ref = (ResolvedConceptReference) list.get(0); Concept c = null; if (ref == null) { System.out.println("************ ref = NULL???"); String msg = "Error: Null ResolvedConceptReference encountered."; request.getSession().setAttribute("message", msg); return "message"; } else { c = ref.getReferencedEntry(); if (c == null) { c = DataUtils.getConceptByCode(Constants.CODING_SCHEME_NAME, null, null, ref.getConceptCode()); } } request.getSession().setAttribute("code", ref.getConceptCode()); request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); request.getSession().setAttribute("new_search", Boolean.TRUE); return "concept_details"; } } String message = "No match found."; if (matchAlgorithm.compareTo("exactMatch") == 0) { - message = "No match found. Please try 'Beings With' or 'Contains' search instead."; + message = "No match found. Please try 'Begins With' or 'Contains' search instead."; } request.getSession().setAttribute("message", message); return "message"; } private String selectedResultsPerPage = null; private List resultsPerPageList = null; public List getResultsPerPageList() { resultsPerPageList = new ArrayList(); resultsPerPageList.add(new SelectItem("10")); resultsPerPageList.add(new SelectItem("25")); resultsPerPageList.add(new SelectItem("50")); resultsPerPageList.add(new SelectItem("75")); resultsPerPageList.add(new SelectItem("100")); resultsPerPageList.add(new SelectItem("250")); resultsPerPageList.add(new SelectItem("500")); selectedResultsPerPage = ((SelectItem) resultsPerPageList.get(2)) .getLabel(); // default to 50 for (int i=0; i<selectedResultsPerPage.length(); i++) { SelectItem item = (SelectItem) resultsPerPageList.get(i); String label = item.getLabel(); int k = Integer.parseInt(label); if (k == Constants.DEFAULT_PAGE_SIZE) { selectedResultsPerPage = label; break; } } return resultsPerPageList; } public void setSelectedResultsPerPage(String selectedResultsPerPage) { if (selectedResultsPerPage == null) return; this.selectedResultsPerPage = selectedResultsPerPage; HttpServletRequest request = (HttpServletRequest) FacesContext .getCurrentInstance().getExternalContext().getRequest(); request.getSession().setAttribute("selectedResultsPerPage", selectedResultsPerPage); } public String getSelectedResultsPerPage() { HttpServletRequest request = (HttpServletRequest) FacesContext .getCurrentInstance().getExternalContext().getRequest(); String s = (String) request.getSession().getAttribute( "selectedResultsPerPage"); if (s != null) { this.selectedResultsPerPage = s; } else { this.selectedResultsPerPage = "50"; request.getSession().setAttribute("selectedResultsPerPage", "50"); } return this.selectedResultsPerPage; } public void resultsPerPageChanged(ValueChangeEvent event) { if (event.getNewValue() == null) { return; } String newValue = (String) event.getNewValue(); setSelectedResultsPerPage(newValue); } public String linkAction() { HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); /* String link = (String) request.getParameter("link"); if (link.compareTo("NCI Terminology Browser") == 0) { return "nci_terminology_browser"; } return "message"; */ return ""; } private String selectedAlgorithm = null; private List algorithmList = null; public List getAlgorithmList() { algorithmList = new ArrayList(); algorithmList.add(new SelectItem("exactMatch", "exactMatch")); algorithmList.add(new SelectItem("startsWith", "Begins With")); algorithmList.add(new SelectItem("contains", "Contains")); selectedAlgorithm = ((SelectItem) algorithmList.get(0)).getLabel(); return algorithmList; } public void algorithmChanged(ValueChangeEvent event) { if (event.getNewValue() == null) return; String newValue = (String) event.getNewValue(); //System.out.println("algorithmChanged; " + newValue); setSelectedAlgorithm(newValue); } public void setSelectedAlgorithm(String selectedAlgorithm) { this.selectedAlgorithm = selectedAlgorithm; HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); request.getSession().setAttribute("selectedAlgorithm", selectedAlgorithm); } public String getSelectedAlgorithm() { return this.selectedAlgorithm; } public String contactUs() throws Exception { String msg = "Your message was successfully sent."; HttpServletRequest request = (HttpServletRequest) FacesContext .getCurrentInstance().getExternalContext().getRequest(); try { String subject = request.getParameter("subject"); String message = request.getParameter("message"); String from = request.getParameter("emailaddress"); String recipients[] = MailUtils.getRecipients(); MailUtils.postMail(from, recipients, subject, message); } catch (Exception e) { msg = e.getMessage(); request.setAttribute("errorMsg", Utils.toHtml(msg)); return "error"; } request.getSession().setAttribute("message", Utils.toHtml(msg)); return "message"; } //////////////////////////////////////////////////////////////// // source //////////////////////////////////////////////////////////////// private String selectedSource = "ALL"; private List sourceList = null; private Vector<String> sourceListData = null; public List getSourceList() { if (sourceList != null) return sourceList; String codingSchemeName = Constants.CODING_SCHEME_NAME; String version = null; sourceListData = DataUtils.getSourceListData(codingSchemeName, version); sourceList = new ArrayList(); if (sourceListData != null) { for (int i=0; i<sourceListData.size(); i++) { String t = (String) sourceListData.elementAt(i); sourceList.add(new SelectItem(t)); } } return sourceList; } public void setSelectedSource(String selectedSource) { if (selectedSource == null) return; HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); request.getSession().removeAttribute("selectedSource"); request.getSession().setAttribute("selectedSource", selectedSource); this.selectedSource = selectedSource; } public String getSelectedSource() { if (selectedSource == null) { sourceList = getSourceList(); if (sourceList != null && sourceList.size() > 0) { this.selectedSource = ((SelectItem) sourceList.get(0)).getLabel(); } } return this.selectedSource; } public void sourceSelectionChanged(ValueChangeEvent event) { if (event.getNewValue() != null) { String source = (String) event.getNewValue(); System.out.println("==================== sourceSelectionChanged to: " + source); setSelectedSource(source); } } ////////////////////////////////////////////////////////////////////// /* private String selectedMatchType = null; private List matchTypeList = null; private Vector<String> matchTypeListData = null; public List getMatchTypeList() { String codingSchemeName = "NCI MetaThesaurus"; String version = null; matchTypeListData = DataUtils.getMatchTypeListData(codingSchemeName, version); matchTypeList = new ArrayList(); for (int i=0; i<matchTypeListData.size(); i++) { String t = (String) matchTypeListData.elementAt(i); matchTypeList.add(new SelectItem(t)); } return matchTypeList; } public void setSelectedMatchType(String selectedMatchType) { this.selectedMatchType = selectedMatchType; HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); System.out.println("************* setSelectedMatchType selectedMatchType"); request.getSession().setAttribute("selectedMatchType", selectedMatchType); } public String getSelectedMatchType() { if (selectedMatchType == null) { matchTypeList = getMatchTypeList(); if (matchTypeList != null && matchTypeList.size() > 0) { this.selectedMatchType = ((SelectItem) matchTypeList.get(0)).getLabel(); } } System.out.println("************* getSelectedMatchType selectedMatchType"); return this.selectedMatchType; } public void matchTypeSelectionChanged(ValueChangeEvent event) { if (event.getNewValue() == null) return; String matchType = (String) event.getNewValue(); setSelectedMatchType(matchType); } */ //////////////////////////////////////////////////////////////// // concept sources //////////////////////////////////////////////////////////////// private String selectedConceptSource = null; private List conceptSourceList = null; private Vector<String> conceptSourceListData = null; public List getConceptSourceList() { String codingSchemeName = Constants.CODING_SCHEME_NAME; String version = null; HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); String code = (String) request.getSession().getAttribute("code"); conceptSourceListData = DataUtils.getSources(codingSchemeName, version, null, code); conceptSourceList = new ArrayList(); if (conceptSourceListData == null) return conceptSourceList; for (int i=0; i<conceptSourceListData.size(); i++) { String t = (String) conceptSourceListData.elementAt(i); conceptSourceList.add(new SelectItem(t)); } return conceptSourceList; } public void setSelectedConceptSource(String selectedConceptSource) { this.selectedConceptSource = selectedConceptSource; HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); request.getSession().setAttribute("selectedConceptSource", selectedConceptSource); } public String getSelectedConceptSource() { if (selectedConceptSource == null) { conceptSourceList = getConceptSourceList(); if (conceptSourceList != null && conceptSourceList.size() > 0) { this.selectedConceptSource = ((SelectItem) conceptSourceList.get(0)).getLabel(); } } return this.selectedConceptSource; } public void conceptSourceSelectionChanged(ValueChangeEvent event) { if (event.getNewValue() == null) return; HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); String source = (String) event.getNewValue(); setSelectedConceptSource(source); } public String viewNeighborhoodAction() { HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); //String sab = (String) request.getParameter("selectedConceptSource"); String sab = getSelectedConceptSource(); String code = (String) request.getParameter("code"); //String message = "View Neighborhood in " + sab + " page is under construction."; //request.getSession().setAttribute("message", message); return "neighborhood"; } }
true
true
public String searchAction() { HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); String matchText = (String) request.getParameter("matchText"); if (matchText != null) matchText = matchText.trim(); //[#19965] Error message is not displayed when Search Criteria is not proivded if (matchText == null || matchText.length() == 0) { String message = "Please enter a search string."; request.getSession().setAttribute("message", message); return "message"; } request.getSession().setAttribute("matchText", matchText); String matchAlgorithm = (String) request.getParameter("algorithm"); setSelectedAlgorithm(matchAlgorithm); String matchtype = (String) request.getParameter("matchtype"); if (matchtype == null) matchtype = "string"; //Remove ranking check box (KLO, 092409) //String rankingStr = (String) request.getParameter("ranking"); //boolean ranking = rankingStr != null && rankingStr.equals("on"); //request.getSession().setAttribute("ranking", Boolean.toString(ranking)); String source = (String) request.getParameter("source"); if (source == null) { source = "ALL"; } //request.getSession().setAttribute("source", source); setSelectedSource(source); if (NCImBrowserProperties.debugOn) { try { System.out.println(Utils.SEPARATOR); System.out.println("* criteria: " + matchText); System.out.println("* matchType: " + matchtype); System.out.println("* source: " + source); //System.out.println("* ranking: " + ranking); // System.out.println("* sortOption: " + sortOption); } catch (Exception e) { } } String scheme = Constants.CODING_SCHEME_NAME; String version = null; String max_str = null; int maxToReturn = -1;//1000; try { max_str = NCImBrowserProperties.getInstance().getProperty(NCImBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); } catch (Exception ex) { } Utils.StopWatch stopWatch = new Utils.StopWatch(); Vector<org.LexGrid.concepts.Concept> v = null; //v = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, sortOption, maxToReturn); //ResolvedConceptReferencesIterator iterator = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, ranking, maxToReturn); ResolvedConceptReferencesIterator iterator = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, maxToReturn); request.getSession().setAttribute("vocabulary", scheme); request.getSession().setAttribute("matchAlgorithm", matchAlgorithm); //request.getSession().setAttribute("matchtype", matchtype); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); request.getSession().removeAttribute("concept"); request.getSession().removeAttribute("code"); request.getSession().removeAttribute("codeInNCI"); request.getSession().removeAttribute("AssociationTargetHashMap"); request.getSession().removeAttribute("type"); //if (v != null && v.size() > 1) if (iterator != null) { IteratorBean iteratorBean = (IteratorBean) FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().get("iteratorBean"); if (iteratorBean == null) { iteratorBean = new IteratorBean(iterator); FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().put("iteratorBean", iteratorBean); } else { iteratorBean.setIterator(iterator); } int size = iteratorBean.getSize(); if (size > 1) { request.getSession().setAttribute("search_results", v); String match_size = Integer.toString(size);;//Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); return "search_results"; } else if (size == 1) { request.getSession().setAttribute("singleton", "true"); request.getSession().setAttribute("dictionary", Constants.CODING_SCHEME_NAME); //Concept c = (Concept) v.elementAt(0); int pageNumber = 1; List list = iteratorBean.getData(1); ResolvedConceptReference ref = (ResolvedConceptReference) list.get(0); Concept c = null; if (ref == null) { System.out.println("************ ref = NULL???"); String msg = "Error: Null ResolvedConceptReference encountered."; request.getSession().setAttribute("message", msg); return "message"; } else { c = ref.getReferencedEntry(); if (c == null) { c = DataUtils.getConceptByCode(Constants.CODING_SCHEME_NAME, null, null, ref.getConceptCode()); } } request.getSession().setAttribute("code", ref.getConceptCode()); request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); request.getSession().setAttribute("new_search", Boolean.TRUE); return "concept_details"; } } String message = "No match found."; if (matchAlgorithm.compareTo("exactMatch") == 0) { message = "No match found. Please try 'Beings With' or 'Contains' search instead."; } request.getSession().setAttribute("message", message); return "message"; }
public String searchAction() { HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); String matchText = (String) request.getParameter("matchText"); if (matchText != null) matchText = matchText.trim(); //[#19965] Error message is not displayed when Search Criteria is not proivded if (matchText == null || matchText.length() == 0) { String message = "Please enter a search string."; request.getSession().setAttribute("message", message); return "message"; } request.getSession().setAttribute("matchText", matchText); String matchAlgorithm = (String) request.getParameter("algorithm"); setSelectedAlgorithm(matchAlgorithm); String matchtype = (String) request.getParameter("matchtype"); if (matchtype == null) matchtype = "string"; //Remove ranking check box (KLO, 092409) //String rankingStr = (String) request.getParameter("ranking"); //boolean ranking = rankingStr != null && rankingStr.equals("on"); //request.getSession().setAttribute("ranking", Boolean.toString(ranking)); String source = (String) request.getParameter("source"); if (source == null) { source = "ALL"; } //request.getSession().setAttribute("source", source); setSelectedSource(source); if (NCImBrowserProperties.debugOn) { try { System.out.println(Utils.SEPARATOR); System.out.println("* criteria: " + matchText); System.out.println("* matchType: " + matchtype); System.out.println("* source: " + source); //System.out.println("* ranking: " + ranking); // System.out.println("* sortOption: " + sortOption); } catch (Exception e) { } } String scheme = Constants.CODING_SCHEME_NAME; String version = null; String max_str = null; int maxToReturn = -1;//1000; try { max_str = NCImBrowserProperties.getInstance().getProperty(NCImBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); } catch (Exception ex) { } Utils.StopWatch stopWatch = new Utils.StopWatch(); Vector<org.LexGrid.concepts.Concept> v = null; //v = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, sortOption, maxToReturn); //ResolvedConceptReferencesIterator iterator = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, ranking, maxToReturn); ResolvedConceptReferencesIterator iterator = new SearchUtils().searchByName(scheme, version, matchText, source, matchAlgorithm, maxToReturn); request.getSession().setAttribute("vocabulary", scheme); request.getSession().setAttribute("matchAlgorithm", matchAlgorithm); //request.getSession().setAttribute("matchtype", matchtype); request.getSession().removeAttribute("neighborhood_synonyms"); request.getSession().removeAttribute("neighborhood_atoms"); request.getSession().removeAttribute("concept"); request.getSession().removeAttribute("code"); request.getSession().removeAttribute("codeInNCI"); request.getSession().removeAttribute("AssociationTargetHashMap"); request.getSession().removeAttribute("type"); //if (v != null && v.size() > 1) if (iterator != null) { IteratorBean iteratorBean = (IteratorBean) FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().get("iteratorBean"); if (iteratorBean == null) { iteratorBean = new IteratorBean(iterator); FacesContext.getCurrentInstance().getExternalContext() .getSessionMap().put("iteratorBean", iteratorBean); } else { iteratorBean.setIterator(iterator); } int size = iteratorBean.getSize(); if (size > 1) { request.getSession().setAttribute("search_results", v); String match_size = Integer.toString(size);;//Integer.toString(v.size()); request.getSession().setAttribute("match_size", match_size); request.getSession().setAttribute("page_string", "1"); request.getSession().setAttribute("new_search", Boolean.TRUE); return "search_results"; } else if (size == 1) { request.getSession().setAttribute("singleton", "true"); request.getSession().setAttribute("dictionary", Constants.CODING_SCHEME_NAME); //Concept c = (Concept) v.elementAt(0); int pageNumber = 1; List list = iteratorBean.getData(1); ResolvedConceptReference ref = (ResolvedConceptReference) list.get(0); Concept c = null; if (ref == null) { System.out.println("************ ref = NULL???"); String msg = "Error: Null ResolvedConceptReference encountered."; request.getSession().setAttribute("message", msg); return "message"; } else { c = ref.getReferencedEntry(); if (c == null) { c = DataUtils.getConceptByCode(Constants.CODING_SCHEME_NAME, null, null, ref.getConceptCode()); } } request.getSession().setAttribute("code", ref.getConceptCode()); request.getSession().setAttribute("concept", c); request.getSession().setAttribute("type", "properties"); request.getSession().setAttribute("new_search", Boolean.TRUE); return "concept_details"; } } String message = "No match found."; if (matchAlgorithm.compareTo("exactMatch") == 0) { message = "No match found. Please try 'Begins With' or 'Contains' search instead."; } request.getSession().setAttribute("message", message); return "message"; }
diff --git a/src/de/bananaco/bpermissions/imp/Config.java b/src/de/bananaco/bpermissions/imp/Config.java index 6839a72..4eff318 100644 --- a/src/de/bananaco/bpermissions/imp/Config.java +++ b/src/de/bananaco/bpermissions/imp/Config.java @@ -1,55 +1,56 @@ package de.bananaco.bpermissions.imp; import java.io.File; import org.bukkit.configuration.file.YamlConfiguration; import de.bananaco.permissions.interfaces.PromotionTrack; public class Config { private final File file = new File("plugins/bPermissions/config.yml"); private YamlConfiguration config = new YamlConfiguration(); private String trackType = "multi"; private PromotionTrack track = null; public void load() { try { loadUnsafe(); } catch (Exception e) { e.printStackTrace(); } } private void loadUnsafe() throws Exception { // Your standard create if not exist shizzledizzle if(!file.exists()) { - file.getParentFile().mkdirs(); + if(file.getParentFile() != null) + file.getParentFile().mkdirs(); file.createNewFile(); } config.load(file); // set the value to default config.set("track-type", config.get("track-type", trackType)); // then load it into memory trackType = config.getString("track-type"); // then load our PromotionTrack if(trackType.equalsIgnoreCase("multi")) { track = new MultiGroupPromotion(); } else if(trackType.equalsIgnoreCase("lump")) { track = new LumpGroupPromotion(); } else { track = new SingleGroupPromotion(); } // Load the track track.load(); // finally save the config config.save(file); } public PromotionTrack getPromotionTrack() { return track; } }
true
true
private void loadUnsafe() throws Exception { // Your standard create if not exist shizzledizzle if(!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } config.load(file); // set the value to default config.set("track-type", config.get("track-type", trackType)); // then load it into memory trackType = config.getString("track-type"); // then load our PromotionTrack if(trackType.equalsIgnoreCase("multi")) { track = new MultiGroupPromotion(); } else if(trackType.equalsIgnoreCase("lump")) { track = new LumpGroupPromotion(); } else { track = new SingleGroupPromotion(); } // Load the track track.load(); // finally save the config config.save(file); }
private void loadUnsafe() throws Exception { // Your standard create if not exist shizzledizzle if(!file.exists()) { if(file.getParentFile() != null) file.getParentFile().mkdirs(); file.createNewFile(); } config.load(file); // set the value to default config.set("track-type", config.get("track-type", trackType)); // then load it into memory trackType = config.getString("track-type"); // then load our PromotionTrack if(trackType.equalsIgnoreCase("multi")) { track = new MultiGroupPromotion(); } else if(trackType.equalsIgnoreCase("lump")) { track = new LumpGroupPromotion(); } else { track = new SingleGroupPromotion(); } // Load the track track.load(); // finally save the config config.save(file); }
diff --git a/modules/activiti-rest/src/main/java/org/activiti/rest/api/process/ProcessInstanceActivityMoveResource.java b/modules/activiti-rest/src/main/java/org/activiti/rest/api/process/ProcessInstanceActivityMoveResource.java index 4f6a68cde..8043df6a1 100644 --- a/modules/activiti-rest/src/main/java/org/activiti/rest/api/process/ProcessInstanceActivityMoveResource.java +++ b/modules/activiti-rest/src/main/java/org/activiti/rest/api/process/ProcessInstanceActivityMoveResource.java @@ -1,88 +1,89 @@ package org.activiti.rest.api.process; import java.util.HashMap; import java.util.Map; import org.activiti.engine.ActivitiException; import org.activiti.engine.RuntimeService; import org.activiti.engine.impl.ProcessEngineImpl; import org.activiti.engine.impl.db.DbSqlSession; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity; import org.activiti.engine.impl.pvm.process.ActivityImpl; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.rest.api.ActivitiUtil; import org.activiti.rest.api.SecuredResource; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; import org.restlet.representation.Representation; import org.restlet.resource.Put; public class ProcessInstanceActivityMoveResource extends SecuredResource { @Put public ObjectNode moveCurrentActivity(Representation entity) { ObjectNode responseJSON = new ObjectMapper().createObjectNode(); String processInstanceId = (String) getRequest().getAttributes().get("processInstanceId"); if (processInstanceId == null) { throw new ActivitiException("No process instance is provided"); } try { // check authentication if (authenticate() == false) return null; // extract request parameters Map<String, Object> variables = new HashMap<String, Object>(); String startParams = entity.getText(); if (StringUtils.isNotEmpty(startParams)) { JsonNode startJSON = new ObjectMapper().readTree(startParams); variables.putAll(retrieveVariables(startJSON)); } // extract activity ids String sourceActivityId = (String) variables.remove("sourceActivityId"); String targetActivityId = (String) variables.remove("targetActivityId"); if (sourceActivityId == null || targetActivityId == null) { responseJSON.put("success", false); responseJSON.put("failureReason", "Request is missing sourceActivityId and targetActivityId"); return responseJSON; } RuntimeService runtimeService = ActivitiUtil.getRuntimeService(); ExecutionEntity execution = (ExecutionEntity) runtimeService .createExecutionQuery() .processInstanceId(processInstanceId) .activityId(sourceActivityId).singleResult(); ProcessInstance instance = runtimeService .createProcessInstanceQuery() .processInstanceId(execution.getProcessInstanceId()) .singleResult(); ProcessDefinitionEntity definition = (ProcessDefinitionEntity) ActivitiUtil .getRepositoryService().getProcessDefinition(instance.getProcessDefinitionId()); ActivityImpl targetActivity = definition.findActivity(targetActivityId); execution.setActivity(targetActivity); DbSqlSession ses = (DbSqlSession) ((ProcessEngineImpl) ActivitiUtil.getProcessEngine()).getDbSqlSessionFactory().openSession(); ses.update(execution); - ses.flush(); + ses.flush(); + ses.close(); responseJSON.put("success", true); return responseJSON; } catch (Exception ex) { throw new ActivitiException( "Failed to move current activity for instance id " + processInstanceId, ex); } } }
true
true
public ObjectNode moveCurrentActivity(Representation entity) { ObjectNode responseJSON = new ObjectMapper().createObjectNode(); String processInstanceId = (String) getRequest().getAttributes().get("processInstanceId"); if (processInstanceId == null) { throw new ActivitiException("No process instance is provided"); } try { // check authentication if (authenticate() == false) return null; // extract request parameters Map<String, Object> variables = new HashMap<String, Object>(); String startParams = entity.getText(); if (StringUtils.isNotEmpty(startParams)) { JsonNode startJSON = new ObjectMapper().readTree(startParams); variables.putAll(retrieveVariables(startJSON)); } // extract activity ids String sourceActivityId = (String) variables.remove("sourceActivityId"); String targetActivityId = (String) variables.remove("targetActivityId"); if (sourceActivityId == null || targetActivityId == null) { responseJSON.put("success", false); responseJSON.put("failureReason", "Request is missing sourceActivityId and targetActivityId"); return responseJSON; } RuntimeService runtimeService = ActivitiUtil.getRuntimeService(); ExecutionEntity execution = (ExecutionEntity) runtimeService .createExecutionQuery() .processInstanceId(processInstanceId) .activityId(sourceActivityId).singleResult(); ProcessInstance instance = runtimeService .createProcessInstanceQuery() .processInstanceId(execution.getProcessInstanceId()) .singleResult(); ProcessDefinitionEntity definition = (ProcessDefinitionEntity) ActivitiUtil .getRepositoryService().getProcessDefinition(instance.getProcessDefinitionId()); ActivityImpl targetActivity = definition.findActivity(targetActivityId); execution.setActivity(targetActivity); DbSqlSession ses = (DbSqlSession) ((ProcessEngineImpl) ActivitiUtil.getProcessEngine()).getDbSqlSessionFactory().openSession(); ses.update(execution); ses.flush(); responseJSON.put("success", true); return responseJSON; } catch (Exception ex) { throw new ActivitiException( "Failed to move current activity for instance id " + processInstanceId, ex); } }
public ObjectNode moveCurrentActivity(Representation entity) { ObjectNode responseJSON = new ObjectMapper().createObjectNode(); String processInstanceId = (String) getRequest().getAttributes().get("processInstanceId"); if (processInstanceId == null) { throw new ActivitiException("No process instance is provided"); } try { // check authentication if (authenticate() == false) return null; // extract request parameters Map<String, Object> variables = new HashMap<String, Object>(); String startParams = entity.getText(); if (StringUtils.isNotEmpty(startParams)) { JsonNode startJSON = new ObjectMapper().readTree(startParams); variables.putAll(retrieveVariables(startJSON)); } // extract activity ids String sourceActivityId = (String) variables.remove("sourceActivityId"); String targetActivityId = (String) variables.remove("targetActivityId"); if (sourceActivityId == null || targetActivityId == null) { responseJSON.put("success", false); responseJSON.put("failureReason", "Request is missing sourceActivityId and targetActivityId"); return responseJSON; } RuntimeService runtimeService = ActivitiUtil.getRuntimeService(); ExecutionEntity execution = (ExecutionEntity) runtimeService .createExecutionQuery() .processInstanceId(processInstanceId) .activityId(sourceActivityId).singleResult(); ProcessInstance instance = runtimeService .createProcessInstanceQuery() .processInstanceId(execution.getProcessInstanceId()) .singleResult(); ProcessDefinitionEntity definition = (ProcessDefinitionEntity) ActivitiUtil .getRepositoryService().getProcessDefinition(instance.getProcessDefinitionId()); ActivityImpl targetActivity = definition.findActivity(targetActivityId); execution.setActivity(targetActivity); DbSqlSession ses = (DbSqlSession) ((ProcessEngineImpl) ActivitiUtil.getProcessEngine()).getDbSqlSessionFactory().openSession(); ses.update(execution); ses.flush(); ses.close(); responseJSON.put("success", true); return responseJSON; } catch (Exception ex) { throw new ActivitiException( "Failed to move current activity for instance id " + processInstanceId, ex); } }
diff --git a/src/replicatorg/drivers/reprap/RepRap5DDriver.java b/src/replicatorg/drivers/reprap/RepRap5DDriver.java index bed30c41..28bca974 100644 --- a/src/replicatorg/drivers/reprap/RepRap5DDriver.java +++ b/src/replicatorg/drivers/reprap/RepRap5DDriver.java @@ -1,1331 +1,1331 @@ /* RepRap5DDriver.java This is a driver to control a machine that contains a GCode parser and communicates via Serial Port. Part of the ReplicatorG project - http://www.replicat.org Copyright (c) 2008 Zach Smith 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 */ /* TODOs: * (M6 T0 (Wait for tool to heat up)) - not supported? Rewrite to other code? * * */ package replicatorg.drivers.reprap; import java.io.UnsupportedEncodingException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.EnumSet; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.w3c.dom.Node; import replicatorg.app.Base; import replicatorg.app.tools.XML; import replicatorg.app.util.serial.ByteFifo; import replicatorg.app.util.serial.SerialFifoEventListener; import replicatorg.drivers.RealtimeControl; import replicatorg.drivers.RetryException; import replicatorg.drivers.SerialDriver; import replicatorg.drivers.reprap.ExtrusionUpdater.Direction; import replicatorg.machine.model.AxisId; import replicatorg.machine.model.ToolModel; import replicatorg.util.Point5d; public class RepRap5DDriver extends SerialDriver implements SerialFifoEventListener, RealtimeControl { private static Pattern gcodeCommentPattern = Pattern.compile("\\([^)]*\\)|;.*"); private static Pattern resendLinePattern = Pattern.compile("([0-9]+)"); private static Pattern gcodeLineNumberPattern = Pattern.compile("n\\s*([0-9]+)"); public final AtomicReference<Double> feedrate = new AtomicReference<Double>(0.0); public final AtomicReference<Double> ePosition = new AtomicReference<Double>(0.0); private final ReentrantLock sendCommandLock = new ReentrantLock(); /** true if a line containing the start keyword has been received from the firmware*/ private final AtomicBoolean startReceived = new AtomicBoolean(false); /** true if a line containing the ok keyword has been received from the firmware*/ private final AtomicBoolean okReceived = new AtomicBoolean(false); /** * An above zero level shows more info */ private int debugLevel = 0; /** * Temporary. This allows for purposefully injection of noise to speed up debugging of retransmits and recovery. */ private int introduceNoiseEveryN = -1; private int lineIterator = 0; private int numResends = 0; /** * Enables five D GCodes if true. If false reverts to traditional 3D Gcodes */ private boolean fiveD = true; /** * Adds check-sums on to each gcode line sent to the RepRap. */ private boolean hasChecksums = true; /** * Enables pulsing RTS to restart the RepRap on connect. */ private boolean pulseRTS = true; /** * if true the firmware sends "resend: 1234" and then "ok" for * the same line and we need to eat that extra "ok". Teacup does * not do this but Tonokip, Klimentkip and FiveD do */ private boolean okAfterResend = true; /** * if true the firmware sends "start" followed by "ok" on reset * and we need to eat that extra "ok". Teacup is the only known * firmware with this behavior. */ private boolean okAfterStart = false; /** * if true all E moves are relative, so there's no need to snoop * E moves and ePosition stays at 0.0 all the time. Teacup has * always relative E. */ private boolean alwaysRelativeE = false; /** * if true the driver will wait for a "start" signal when pulsing rts low * before initialising the printer. */ private boolean waitForStart = false; /** * configures the time to wait for the first response from the RepRap in ms. */ private long waitForStartTimeout = 1000; private int waitForStartRetries = 3; /** * This allows for real time adjustment of certain printing variables! */ private boolean realtimeControl = false; private double rcFeedrateMultiply = 1; private double rcTravelFeedrateMultiply = 1; private double rcExtrusionMultiply = 1; private double rcFeedrateLimit = 60*300; // 300mm/s still works on Ultimakers! private final ExtrusionUpdater extrusionUpdater = new ExtrusionUpdater(this); /** * the size of the buffer on the GCode host */ private int maxBufferSize = 128; /** * The commands sent but not yet acknowledged by the firmware. Stored so they can be resent * if there is a checksum problem. */ private LinkedList<String> buffer = new LinkedList<String>(); private ReentrantLock bufferLock = new ReentrantLock(); /** locks the readResponse method to prevent multiple concurrent reads */ private ReentrantLock readResponseLock = new ReentrantLock(); protected DecimalFormat df; private AtomicInteger lineNumber = new AtomicInteger(-1); public RepRap5DDriver() { super(); // Support for emergency stop is not assumed until it is detected. Detection of this feature should be in initialization. hasEmergencyStop = false; // Support for soft stop is not assumed until it is detected. Detection of this feature should be in initialization. hasSoftStop = false; // init our variables. setInitialized(false); //Thank you Alexey (http://replicatorg.lighthouseapp.com/users/166956) DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setDecimalSeparator('.'); df = new DecimalFormat("#.######", dfs); } public String getDriverName() { return "RepRap5D"; } public synchronized void loadXML(Node xml) { super.loadXML(xml); // load from our XML config, if we have it. if (XML.hasChildNode(xml, "waitforstart")) { Node startNode = XML.getChildNodeByName(xml, "waitforstart"); String enabled = XML.getAttributeValue(startNode, "enabled"); if (enabled !=null) waitForStart = Boolean.parseBoolean(enabled); String timeout = XML.getAttributeValue(startNode, "timeout"); if (timeout !=null) waitForStartTimeout = Long.parseLong(timeout); String retries = XML.getAttributeValue(startNode, "retries"); if (retries !=null) waitForStartRetries = Integer.parseInt(retries); } if (XML.hasChildNode(xml, "pulserts")) { pulseRTS = Boolean.parseBoolean(XML.getChildNodeValue(xml, "pulserts")); } if (XML.hasChildNode(xml, "checksums")) { hasChecksums = Boolean.parseBoolean(XML.getChildNodeValue(xml, "checksums")); } if (XML.hasChildNode(xml, "fived")) { fiveD = Boolean.parseBoolean(XML.getChildNodeValue(xml, "fived")); } if (XML.hasChildNode(xml, "debugLevel")) { debugLevel = Integer.parseInt(XML.getChildNodeValue(xml, "debugLevel")); } if (XML.hasChildNode(xml, "limitFeedrate")) { rcFeedrateLimit = Double.parseDouble(XML.getChildNodeValue(xml, "limitFeedrate")); } if (XML.hasChildNode(xml, "okAfterResend")) { okAfterResend = Boolean.parseBoolean(XML.getChildNodeValue(xml, "okAfterResend")); } if (XML.hasChildNode(xml, "okAfterStart")) { okAfterStart = Boolean.parseBoolean(XML.getChildNodeValue(xml, "okAfterStart")); } if (XML.hasChildNode(xml, "alwaysRelativeE")) { alwaysRelativeE = Boolean.parseBoolean(XML.getChildNodeValue(xml, "alwaysRelativeE")); } if (XML.hasChildNode(xml, "hasEmergencyStop")) { hasEmergencyStop = Boolean.parseBoolean(XML.getChildNodeValue(xml, "hasEmergencyStop")); } if (XML.hasChildNode(xml, "hasSoftStop")) { hasSoftStop = Boolean.parseBoolean(XML.getChildNodeValue(xml, "hasSoftStop")); } if (XML.hasChildNode(xml, "introduceNoise")) { double introduceNoise = Double.parseDouble(XML.getChildNodeValue(xml, "introduceNoise")); if(introduceNoise != 0) { Base.logger.warning("Purposefully injecting noise into communications. This is NOT for production."); Base.logger.warning("Turn this off by removing introduceNoise from the machines XML file of your machine."); introduceNoiseEveryN = (int) (1/introduceNoise); } } } public void updateManualControl() { try { extrusionUpdater.update(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Send any gcode needed to synchronize the driver state and * the firmware state. Sent on startup and if we see "start" * indicating an uncommanded firmware reset. */ public void sendInitializationGcode(boolean synchronous) { sendCommand("M110", synchronous); // may be duplicate, that's ok // default us to absolute positioning sendCommand("G90", synchronous); sendCommand("G92 X0 Y0 Z0 E0", synchronous); } public synchronized void initialize() { // declare our serial guy. if (serial == null) { Base.logger.severe("No Serial Port found.\n"); return; } // wait till we're initialised if (!isInitialized()) { Base.logger.info("Initializing Serial."); flushBuffer(); if (pulseRTS) { Base.logger.fine("Resetting RepRap: Pulsing RTS.."); int retriesRemaining = waitForStartRetries+1; retryPulse: do { try { pulseRTS(); Base.logger.finer("start received"); break retryPulse; } catch (TimeoutException e) { retriesRemaining--; } if (retriesRemaining == 0) { this.disconnect(); Base.logger.warning("RepRap not responding to RTS reset. Failed to connect."); return; } else { Base.logger.warning("RepRap not responding to RTS reset. Trying again.."); } } while(true); Base.logger.fine("RepRap Reset. RTS pulsing complete."); } // Send a line # reset command, this allows us to catch the "ok" response. // If we get a "start" while trying this we'll go again. synchronized(okReceived) { okReceived.set(false); while (!okReceived.get()) { sendCommand("M110", false); Base.logger.info("GCode sent. waiting for response.."); try { waitForNotification(okReceived, 10000); } catch (RetryException e) { } catch (TimeoutException e) { this.disconnect(); Base.logger.warning("Firmware not responding to gcode. Failed to connect."); return; } } } Base.logger.fine("GCode response received. RepRap connected."); sendInitializationGcode(true); Base.logger.info("Ready."); this.setInitialized(true); } } private void waitForNotification(AtomicBoolean notifier, long timeout) throws TimeoutException, RetryException { //Wait for the RepRap to respond try { notifier.wait(timeout); } catch (InterruptedException e) { //Presumably we're shutting down Thread.currentThread().interrupt(); return; } if (notifier.get() == true) { return; } else { throw new RetryException(); } } private void pulseRTS() throws TimeoutException { // attempt to reset the device, this may slow down the connection time, but it // increases our chances of successfully connecting dramatically. Base.logger.info("Attempting to reset RepRap (pulsing RTS)"); synchronized (startReceived) { startReceived.set(false); serial.pulseRTSLow(); if (waitForStart == false) return; // Wait for the RepRap to respond to the RTS pulse attempt // or for this to timeout. while (!startReceived.get()) { try { waitForNotification(startReceived, waitForStartTimeout); } catch (RetryException e) { continue; } } } } public boolean isPassthroughDriver() { return true; } /** * Actually execute the GCode we just parsed. */ public void executeGCodeLine(String code) { //If we're not initialized (ie. disconnected) do not execute commands on the disconnected machine. if(!isInitialized()) return; // we *DONT* want to use the parents one, // as that will call all sorts of misc functions. // we'll simply pass it along. // super.execute(); sendCommand(code); } /** * Returns null or the first instance of the matching group */ private String getRegexMatch(String regex, String input, int group) { return getRegexMatch(Pattern.compile(regex), input, group); } private String getRegexMatch(Pattern regex, String input, int group) { Matcher matcher = regex.matcher(input); if (!matcher.find() || matcher.groupCount() < group) return null; return matcher.group(group); } /** * Actually sends command over serial. * * Commands sent here are acknowledged asynchronously in another * thread so as to increase our serial GCode throughput. * * Only one command can be sent at a time. If another command is * being sent this method will block until the previous command * is finished sending. */ protected void sendCommand(String next) { _sendCommand(next, true, false); } protected void sendCommand(String next, boolean synchronous) { _sendCommand(next, synchronous, false); } protected void resendCommand(String command) { synchronized (sendCommandLock) { numResends++; if(debugLevel > 0) Base.logger.warning("Resending: \"" + command + "\". Resends in "+ numResends + " of "+lineIterator+" lines."); _sendCommand(command, false, true); } } /** * inner method. not for use outside sendCommand and resendCommand */ protected void _sendCommand(String next, boolean synchronous, boolean resending) { // If this line is uncommented, it simply sends the next line instead of doing a retransmit! if (!resending) { sendCommandLock.lock(); //assert (isInitialized()); // System.out.println("sending: " + next); next = clean(next); next = fix(next); // make it compatible with older versions of the GCode interpeter // skip empty commands. if (next.length() == 0) { sendCommandLock.unlock(); return; } //update the current feedrate String feedrate = getRegexMatch("F(-[0-9\\.]+)", next, 1); if (feedrate!=null) this.feedrate.set(Double.parseDouble(feedrate)); if (!alwaysRelativeE) { //update the current extruder position String e = getRegexMatch("E([-0-9\\.]+)", next, 1); if (e!=null) this.ePosition.set(Double.parseDouble(e)); } else { ePosition.set(0.0); } // applychecksum replaces the line that was to be retransmitted, into the next line. if (hasChecksums) next = applyNandChecksum(next); Base.logger.finest("sending: "+next); } else { Base.logger.finest("resending: "+next); } // Block until we can fit the command on the Arduino /* synchronized(bufferLock) { //wait for the number of commands queued in the buffer to shrink before //adding the next command to it. // NOTE: must compute bufferSize from buffer elements now while(bufferSize + next.length() + 1 > maxBufferSize) { Base.logger.warning("reprap driver buffer full. gcode write slowed."); try { bufferLock.wait(); } catch (InterruptedException e1) { //Presumably we're shutting down Thread.currentThread().interrupt(); return; } } }*/ // debug... let us know whats up! if(debugLevel > 1) Base.logger.info("Sending: " + next); try { synchronized(next) { // do the actual send. serialInUse.lock(); bufferLock.lock(); // record it in our buffer tracker. buffer.addFirst(next); if((introduceNoiseEveryN != -1) && (lineIterator++) >= introduceNoiseEveryN) { Base.logger.info("Introducing noise (lineIterator==" + lineIterator + ",introduceNoiseEveryN=" + introduceNoiseEveryN + ")"); lineIterator = 0; String noisyNext = next.replace('6','7').replace('7','1') + "\n"; serial.write(noisyNext); } else { serial.write(next + "\n"); } bufferLock.unlock(); serialInUse.unlock(); // Synchronous gcode transfer. Waits for the 'ok' ack to be received. if (synchronous) next.wait(); } } catch (InterruptedException e1) { //Presumably we're shutting down Thread.currentThread().interrupt(); if (!resending) sendCommandLock.unlock(); return; } // Wait for the response (synchronous gcode transmission) //while(!isFinished()) {} if (!resending) sendCommandLock.unlock(); } public String clean(String str) { String clean = str; // trim whitespace clean = clean.trim(); // remove spaces //clean = clean.replaceAll(" ", ""); // remove all comments clean = RepRap5DDriver.gcodeCommentPattern.matcher(clean).replaceAll(""); return clean; } public String fix(String str) { String fixed = str; // The 5D firmware expects E codes for extrusion control instead of M101, M102, M103 Pattern r = Pattern.compile("M01[^0-9]"); Matcher m = r.matcher(fixed); if (m.find()) { return ""; } // Remove M10[123] codes // This piece of code causes problems?!? Restarts? r = Pattern.compile("M10[123](.*)"); m = r.matcher(fixed); if (m.find( )) { // System.out.println("Didn't find pattern in: " + str ); // fixed = m.group(1)+m.group(3)+";"; return ""; } // Reorder E and F codes? F-codes need to go LAST! //requires: import java.util.regex.Matcher; and import java.util.regex.Pattern; r = Pattern.compile("^(.*)(F[0-9\\.]*)\\s?E([0-9\\.]*)$"); m = r.matcher(fixed); if (m.find( )) { fixed = m.group(1)+" E"+m.group(3)+" "+m.group(2); } if(realtimeControl) { // Rescale F value r = Pattern.compile("(.*)F([0-9\\.]*)(.*)"); m = r.matcher(fixed); if (m.find( )) { double newvalue = Double.valueOf(m.group(2).trim()).doubleValue(); // FIXME: kind of an ugly way to test for extrusionless "travel" versus extrusion. if (!fixed.contains("E")) { newvalue *= rcTravelFeedrateMultiply; } else { newvalue *= rcFeedrateMultiply; } if(newvalue > rcFeedrateLimit) newvalue = rcFeedrateLimit; DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setDecimalSeparator('.'); NumberFormat formatter = new DecimalFormat("#0.0", dfs); fixed = m.group(1)+" F"+formatter.format(newvalue)+" "+m.group(3); } /* // Rescale E value r = Pattern.compile("(.*)E([0-9\\.]*)(.*)");//E317.52// Z-moves slower! Extrude 10% less? More and more rapid reversing m = r.matcher(fixed); if (m.find( )) { double newEvalue = Double.valueOf(m.group(2).trim()).doubleValue(); newEvalue = newEvalue * 0.040; DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setDecimalSeparator('.'); NumberFormat formatter = new DecimalFormat("#0.0", dfs); fixed = m.group(1)+" E"+formatter.format(newEvalue)+" "+m.group(3); } */ } return fixed; // no change! } /** * takes a line of gcode and returns that gcode with a line number and checksum */ public String applyNandChecksum(String gcode) { // RepRap Syntax: N<linenumber> <cmd> *<chksum>\n if (gcode.contains("M110")) lineNumber.set(-1); Matcher lineNumberMatcher = gcodeLineNumberPattern.matcher(gcode); if (lineNumberMatcher.matches()) { // reset our line number to the specified one. this is usually a m110 line # reset lineNumber.set( Integer.parseInt( lineNumberMatcher.group(1) ) ); } else { // only add a line number if it is not already specified gcode = "N"+lineNumber.incrementAndGet()+' '+gcode+' '; } return applyChecksum(gcode); } public String applyChecksum(String gcode) { // chksum = 0 xor each byte of the gcode (including the line number and trailing space) byte checksum = 0; byte[] gcodeBytes = gcode.getBytes(); for (int i = 0; i<gcodeBytes.length; i++) { checksum = (byte) (checksum ^ gcodeBytes[i]); } return gcode+'*'+checksum; } public void serialByteReceivedEvent(ByteFifo fifo) { readResponseLock.lock(); serialInUse.lock(); byte[] response = fifo.dequeueLine(); int responseLength = response.length; serialInUse.unlock(); // 0 is now an acceptable value; it merely means that we timed out // waiting for input if (responseLength < 0) { // This signifies EOF. FIXME: How do we handle this? Base.logger.severe("SerialPassthroughDriver.readResponse(): EOF occured"); readResponseLock.unlock(); return; } else if(responseLength!=0) { String line; try { //convert to string and remove any trailing \r or \n's line = new String(response, 0, responseLength, "US-ASCII") .trim().toLowerCase(); } catch (UnsupportedEncodingException e) { Base.logger.severe("US-ASCII required. Terminating."); readResponseLock.unlock(); throw new RuntimeException(e); } //System.out.println("received: " + line); if(debugLevel > 1) Base.logger.info("<< " + line); if (line.length() == 0) Base.logger.fine("empty line received"); else if (line.startsWith("echo:")) { //if echo is turned on relay it to the user for debugging Base.logger.info(line); } else if (line.startsWith("ok t:")||line.startsWith("t:")) { Pattern r = Pattern.compile("t:([0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find( )) { String temp = m.group(1); machine.currentTool().setCurrentTemperature( Double.parseDouble(temp)); } - r = Pattern.compile("^ok.*b:([0-9\\.]+)$"); + r = Pattern.compile("^ok.*b:([0-9\\.]+)"); m = r.matcher(line); if (m.find( )) { String bedTemp = m.group(1); machine.currentTool().setPlatformCurrentTemperature( Double.parseDouble(bedTemp)); } } else if (line.startsWith("ok c:")||line.startsWith("c:")) { Pattern r = Pattern.compile("c: *x:?([-0-9\\.]+) *y:?([-0-9\\.]+) *z:?([-0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find()) { double x = Double.parseDouble(m.group(1)); double y = Double.parseDouble(m.group(2)); double z = Double.parseDouble(m.group(3)); // super to avoid parroting back a G92 try { super.setCurrentPosition(new Point5d(x, y, z)); //Base.logger.fine("setting currentposition to:"+x+","+y+","+z+"."); } catch (RetryException e) { // do or do not, there is no retry } } } if (line.startsWith("ok")) { synchronized(okReceived) { okReceived.set(true); okReceived.notifyAll(); } bufferLock.lock(); //Notify the thread waitining in this gcode's sendCommand method that the gcode has been received. if (buffer.isEmpty()) { Base.logger.severe("Received OK with nothing queued!"); } else { String notifier = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("FW Accepted: " + notifier); synchronized(notifier) { notifier.notifyAll(); } } bufferLock.unlock(); synchronized(bufferLock) { /*let any sendCommand method waiting to send know that the buffer is now smaller and may be able to fit their command.*/ bufferLock.notifyAll(); } } // old arduino firmware sends "start" else if (line.contains("start")) { // Reset line number first in case gcode is sent below lineNumber.set(-1); boolean active = !buffer.isEmpty(); flushBuffer(); if (isInitialized()) { sendInitializationGcode(false); // If there were outstanding commands try to abort any print in progress. // This is a poor test: but do we know if we're printing at this level? // tried setInitialized(false); but that didn't work well if (active) { Base.logger.severe("Firmware reset with active commands!"); setError("Firmware reset with active commands!"); } } if (okAfterStart) { // firmware sends "ok" after start, put something here to consume it: bufferLock.lock(); buffer.addLast(";start-ok"); bufferLock.unlock(); } // todo: set version synchronized (startReceived) { startReceived.set(true); startReceived.notifyAll(); } // Wake up connect task to try again synchronized (okReceived) { okReceived.set(false); okReceived.notifyAll(); } } else if (line.startsWith("extruder fail")) { setError("Extruder failed: cannot extrude as this rate."); } else if (line.startsWith("resend:")||line.startsWith("rs ")) { // Bad checksum, resend requested Matcher badLineMatch = resendLinePattern.matcher(line); // Is it a Dud M or G code? String dudLetter = getRegexMatch("dud ([a-z]) code", line, 1); if (badLineMatch.find()) { int badLineNumber = Integer.parseInt( badLineMatch.group(1) ); if(debugLevel > 1) Base.logger.warning("Received resend request for line " + badLineNumber); Queue<String> resend = new LinkedList<String>(); boolean found = false; // Search backwards for the bad line in our buffer. // Firmware flushed everything after this line, so // build a queue of lines to resend. bufferLock.lock(); lineSearch: while (!buffer.isEmpty()) { String bufferedLine = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("Searching: " + bufferedLine); int bufferedLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, bufferedLine.toLowerCase(), 1) ); if (dudLetter != null && bufferedLineNumber == badLineNumber) { Base.logger.info("Dud "+dudLetter+" code: Dropping " + bufferedLine); synchronized (bufferedLine) { bufferedLine.notifyAll(); } found = true; break lineSearch; } resend.add(bufferedLine); if (bufferedLineNumber == badLineNumber) { found = true; break lineSearch; } } if (okAfterResend) { // firmware sends "ok" after resend, put something here to consume it: buffer.addLast(";resend-ok"); } bufferLock.unlock(); if (!found) { int restartLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, resend.element().toLowerCase(), 1) ); Base.logger.severe("resend for line " + badLineNumber + " not in our buffer. Resuming from " + restartLineNumber); this.resendCommand(applyChecksum("N"+(restartLineNumber-1)+" M110")); } // resend the lines while (!resend.isEmpty()) { String bufferedLine = resend.remove(); this.resendCommand(bufferedLine); } } else { // Malformed resend line request received. Resetting the line number Base.logger.warning("malformed line resend request, " +"resetting line number. Malformed Data: \n"+line); this.resendCommand(applyChecksum("N"+(lineNumber.get()-1)+" M110")); } } else if (line.startsWith("t:") || line.startsWith("c:")) { // temperature, position handled above } else { Base.logger.severe("Unknown: " + line); } } readResponseLock.unlock(); } public boolean isFinished() { return isBufferEmpty(); } /** * Clear the command buffer and send notifications to everyone * waiting for their completion. */ private void flushBuffer() { bufferLock.lock(); while (!buffer.isEmpty()) { String notifier = buffer.removeLast(); if(debugLevel > 1) Base.logger.fine("Flushing dead command: " + notifier); synchronized(notifier) { notifier.notifyAll(); } } bufferLock.unlock(); } /** * Is our buffer empty? If don't have a buffer, its always true. */ public boolean isBufferEmpty() { bufferLock.lock(); boolean isEmpty = buffer.isEmpty(); bufferLock.unlock(); return isEmpty; } /** * What is our queue size? Used by extrusion driver */ public int queueSize() { bufferLock.lock(); int queueSize = buffer.size(); bufferLock.unlock(); return queueSize; } private synchronized void disconnect() { bufferLock.lock(); flushBuffer(); closeSerial(); bufferLock.unlock(); } public synchronized void dispose() { bufferLock.lock(); flushBuffer(); super.dispose(); bufferLock.unlock(); } /*************************************************************************** * commands for interfacing with the driver directly * @throws RetryException **************************************************************************/ public void queuePoint(Point5d p) throws RetryException { String cmd = "G1 F" + df.format(getCurrentFeedrate()); sendCommand(cmd); cmd = "G1 X" + df.format(p.x()) + " Y" + df.format(p.y()) + " Z" + df.format(p.z()) + " F" + df.format(getCurrentFeedrate()); sendCommand(cmd); super.queuePoint(p); } public void setCurrentPosition(Point5d p) throws RetryException { sendCommand("G92 X" + df.format(p.x()) + " Y" + df.format(p.y()) + " Z" + df.format(p.z())); super.setCurrentPosition(p); } @Override public void homeAxes(EnumSet<AxisId> axes, boolean positive, double feedrate) throws RetryException { Base.logger.info("homing "+axes.toString()); StringBuffer buf = new StringBuffer("G28"); for (AxisId axis : axes) { buf.append(" "+axis+"0"); } sendCommand(buf.toString()); invalidatePosition(); super.homeAxes(axes,false,0); } public void delay(long millis) { int seconds = Math.round(millis / 1000); sendCommand("G4 P" + seconds); // no super call requried. } public void openClamp(int clampIndex) { sendCommand("M11 Q" + clampIndex); super.openClamp(clampIndex); } public void closeClamp(int clampIndex) { sendCommand("M10 Q" + clampIndex); super.closeClamp(clampIndex); } public void enableDrives() throws RetryException { sendCommand("M17"); super.enableDrives(); } public void disableDrives() throws RetryException { sendCommand("M18"); sendCommand("M84"); // Klimentkip super.disableDrives(); } public void changeGearRatio(int ratioIndex) { // gear ratio codes are M40-M46 int code = 40 + ratioIndex; code = Math.max(40, code); code = Math.min(46, code); sendCommand("M" + code); super.changeGearRatio(ratioIndex); } protected String _getToolCode() { return "T" + machine.currentTool().getIndex() + " "; } /*************************************************************************** * Motor interface functions * @throws RetryException **************************************************************************/ public void setMotorRPM(double rpm, int toolhead) throws RetryException { if (fiveD == false) { sendCommand(_getToolCode() + "M108 R" + df.format(rpm)); } else { extrusionUpdater.setFeedrate(rpm); } super.setMotorRPM(rpm, toolhead); } public void setMotorSpeedPWM(int pwm) throws RetryException { if (fiveD == false) { sendCommand(_getToolCode() + "M108 S" + df.format(pwm)); } super.setMotorSpeedPWM(pwm); } public synchronized void enableMotor() throws RetryException { String command = _getToolCode(); if (fiveD == false) { if (machine.currentTool().getMotorDirection() == ToolModel.MOTOR_CLOCKWISE) command += "M101"; else command += "M102"; sendCommand(command); } else { extrusionUpdater.setDirection( machine.currentTool().getMotorDirection()==1? Direction.forward : Direction.reverse ); extrusionUpdater.startExtruding(); } super.enableMotor(); } /** * Unified enable+delay+disable to allow us to use G1 E */ public synchronized void enableMotor(long millis) throws RetryException { if (fiveD == false) { super.enableMotor(millis); } else { super.enableMotor(); double feedrate = machine.currentTool().getMotorSpeedRPM(); double distance = millis * feedrate / 60 / 1000; if (machine.currentTool().getMotorDirection() != 1) { distance *= -1; } sendCommand(_getToolCode() + "G1 E" + (ePosition.get() + distance) + " F" + feedrate); super.disableMotor(); } } public void disableMotor() throws RetryException { if (fiveD == false) { sendCommand(_getToolCode() + "M103"); } else { extrusionUpdater.stopExtruding(); } super.disableMotor(); } /*************************************************************************** * Spindle interface functions * @throws RetryException **************************************************************************/ public void setSpindleRPM(double rpm) throws RetryException { sendCommand(_getToolCode() + "S" + df.format(rpm)); super.setSpindleRPM(rpm); } public void enableSpindle() throws RetryException { String command = _getToolCode(); if (machine.currentTool().getSpindleDirection() == ToolModel.MOTOR_CLOCKWISE) command += "M3"; else command += "M4"; sendCommand(command); super.enableSpindle(); } public void disableSpindle() throws RetryException { sendCommand(_getToolCode() + "M5"); super.disableSpindle(); } /*************************************************************************** * Temperature interface functions * @throws RetryException **************************************************************************/ public void setTemperature(double temperature) throws RetryException { sendCommand(_getToolCode() + "M104 S" + df.format(temperature)); super.setTemperature(temperature); } public void readTemperature() { sendCommand(_getToolCode() + "M105"); super.readTemperature(); } public double getPlatformTemperature(){ return machine.currentTool().getPlatformCurrentTemperature(); } public void setPlatformTemperature(double temperature) throws RetryException { sendCommand(_getToolCode() + "M140 S" + df.format(temperature)); super.setPlatformTemperature(temperature); } /*************************************************************************** * Flood Coolant interface functions **************************************************************************/ public void enableFloodCoolant() { sendCommand(_getToolCode() + "M7"); super.enableFloodCoolant(); } public void disableFloodCoolant() { sendCommand(_getToolCode() + "M9"); super.disableFloodCoolant(); } /*************************************************************************** * Mist Coolant interface functions **************************************************************************/ public void enableMistCoolant() { sendCommand(_getToolCode() + "M8"); super.enableMistCoolant(); } public void disableMistCoolant() { sendCommand(_getToolCode() + "M9"); super.disableMistCoolant(); } /*************************************************************************** * Fan interface functions * @throws RetryException **************************************************************************/ public void enableFan() throws RetryException { sendCommand(_getToolCode() + "M106"); super.enableFan(); } public void disableFan() throws RetryException { sendCommand(_getToolCode() + "M107"); super.disableFan(); } /*************************************************************************** * Valve interface functions * @throws RetryException **************************************************************************/ public void openValve() throws RetryException { sendCommand(_getToolCode() + "M126"); super.openValve(); } public void closeValve() throws RetryException { sendCommand(_getToolCode() + "M127"); super.closeValve(); } /*************************************************************************** * Collet interface functions **************************************************************************/ public void openCollet() { sendCommand(_getToolCode() + "M21"); super.openCollet(); } public void closeCollet() { sendCommand(_getToolCode() + "M22"); super.closeCollet(); } public void reset() { Base.logger.info("Reset."); setInitialized(false); initialize(); } public void stop(boolean abort) { // No implementation needed for synchronous machines. //sendCommand("M0"); // M0 is the same as emergency stop: will hang all communications. You don't really want that... invalidatePosition(); Base.logger.info("RepRap/Ultimaker Machine stop called."); } protected Point5d reconcilePosition() { sendCommand("M114"); // If the firmware returned a position then the reply parser // already set the current position. Return null to tell // caller not to touch the position if it is now known. // DO NOT RECURSE into getCurrentPosition() or this is an // infinite loop! return null; } /* =============== * This driver has real time control over feedrate and extrusion parameters, allowing real-time tuning! */ public boolean hasFeatureRealtimeControl() { Base.logger.info("Yes, I have a Realtime Control feature." ); return true; } public void enableRealtimeControl(boolean enable) { realtimeControl = enable; Base.logger.info("Realtime Control (RC) is: "+ realtimeControl ); } public double getExtrusionMultiplier() { return rcExtrusionMultiply; } public double getFeedrateMultiplier() { return rcFeedrateMultiply; } public double getTravelFeedrateMultiplier() { return rcTravelFeedrateMultiply; } public boolean setExtrusionMultiplier(double multiplier) { rcExtrusionMultiply = multiplier; if(debugLevel == 2) Base.logger.info("RC muplipliers: extrusion="+rcExtrusionMultiply+"x, feedrate="+rcFeedrateMultiply+"x" ); return true; } public boolean setFeedrateMultiplier(double multiplier) { rcFeedrateMultiply = multiplier; if(debugLevel == 2) Base.logger.info("RC muplipliers: extrusion="+rcExtrusionMultiply+"x, feedrate="+rcFeedrateMultiply+"x" ); return true; } public boolean setTravelFeedrateMultiplier(double multiplier) { rcTravelFeedrateMultiply = multiplier; if(debugLevel == 2) Base.logger.info("RC muplipliers: extrusion="+rcExtrusionMultiply+"x, feedrate="+rcFeedrateMultiply+"x, travel feedrate="+rcTravelFeedrateMultiply+"x" ); return true; } public void setDebugLevel(int level) { debugLevel = level; } public int getDebugLevel() { return debugLevel; } public double getFeedrateLimit() { return rcFeedrateLimit; } public boolean setFeedrateLimit(double limit) { rcFeedrateLimit = limit; return true; } }
true
true
public void serialByteReceivedEvent(ByteFifo fifo) { readResponseLock.lock(); serialInUse.lock(); byte[] response = fifo.dequeueLine(); int responseLength = response.length; serialInUse.unlock(); // 0 is now an acceptable value; it merely means that we timed out // waiting for input if (responseLength < 0) { // This signifies EOF. FIXME: How do we handle this? Base.logger.severe("SerialPassthroughDriver.readResponse(): EOF occured"); readResponseLock.unlock(); return; } else if(responseLength!=0) { String line; try { //convert to string and remove any trailing \r or \n's line = new String(response, 0, responseLength, "US-ASCII") .trim().toLowerCase(); } catch (UnsupportedEncodingException e) { Base.logger.severe("US-ASCII required. Terminating."); readResponseLock.unlock(); throw new RuntimeException(e); } //System.out.println("received: " + line); if(debugLevel > 1) Base.logger.info("<< " + line); if (line.length() == 0) Base.logger.fine("empty line received"); else if (line.startsWith("echo:")) { //if echo is turned on relay it to the user for debugging Base.logger.info(line); } else if (line.startsWith("ok t:")||line.startsWith("t:")) { Pattern r = Pattern.compile("t:([0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find( )) { String temp = m.group(1); machine.currentTool().setCurrentTemperature( Double.parseDouble(temp)); } r = Pattern.compile("^ok.*b:([0-9\\.]+)$"); m = r.matcher(line); if (m.find( )) { String bedTemp = m.group(1); machine.currentTool().setPlatformCurrentTemperature( Double.parseDouble(bedTemp)); } } else if (line.startsWith("ok c:")||line.startsWith("c:")) { Pattern r = Pattern.compile("c: *x:?([-0-9\\.]+) *y:?([-0-9\\.]+) *z:?([-0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find()) { double x = Double.parseDouble(m.group(1)); double y = Double.parseDouble(m.group(2)); double z = Double.parseDouble(m.group(3)); // super to avoid parroting back a G92 try { super.setCurrentPosition(new Point5d(x, y, z)); //Base.logger.fine("setting currentposition to:"+x+","+y+","+z+"."); } catch (RetryException e) { // do or do not, there is no retry } } } if (line.startsWith("ok")) { synchronized(okReceived) { okReceived.set(true); okReceived.notifyAll(); } bufferLock.lock(); //Notify the thread waitining in this gcode's sendCommand method that the gcode has been received. if (buffer.isEmpty()) { Base.logger.severe("Received OK with nothing queued!"); } else { String notifier = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("FW Accepted: " + notifier); synchronized(notifier) { notifier.notifyAll(); } } bufferLock.unlock(); synchronized(bufferLock) { /*let any sendCommand method waiting to send know that the buffer is now smaller and may be able to fit their command.*/ bufferLock.notifyAll(); } } // old arduino firmware sends "start" else if (line.contains("start")) { // Reset line number first in case gcode is sent below lineNumber.set(-1); boolean active = !buffer.isEmpty(); flushBuffer(); if (isInitialized()) { sendInitializationGcode(false); // If there were outstanding commands try to abort any print in progress. // This is a poor test: but do we know if we're printing at this level? // tried setInitialized(false); but that didn't work well if (active) { Base.logger.severe("Firmware reset with active commands!"); setError("Firmware reset with active commands!"); } } if (okAfterStart) { // firmware sends "ok" after start, put something here to consume it: bufferLock.lock(); buffer.addLast(";start-ok"); bufferLock.unlock(); } // todo: set version synchronized (startReceived) { startReceived.set(true); startReceived.notifyAll(); } // Wake up connect task to try again synchronized (okReceived) { okReceived.set(false); okReceived.notifyAll(); } } else if (line.startsWith("extruder fail")) { setError("Extruder failed: cannot extrude as this rate."); } else if (line.startsWith("resend:")||line.startsWith("rs ")) { // Bad checksum, resend requested Matcher badLineMatch = resendLinePattern.matcher(line); // Is it a Dud M or G code? String dudLetter = getRegexMatch("dud ([a-z]) code", line, 1); if (badLineMatch.find()) { int badLineNumber = Integer.parseInt( badLineMatch.group(1) ); if(debugLevel > 1) Base.logger.warning("Received resend request for line " + badLineNumber); Queue<String> resend = new LinkedList<String>(); boolean found = false; // Search backwards for the bad line in our buffer. // Firmware flushed everything after this line, so // build a queue of lines to resend. bufferLock.lock(); lineSearch: while (!buffer.isEmpty()) { String bufferedLine = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("Searching: " + bufferedLine); int bufferedLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, bufferedLine.toLowerCase(), 1) ); if (dudLetter != null && bufferedLineNumber == badLineNumber) { Base.logger.info("Dud "+dudLetter+" code: Dropping " + bufferedLine); synchronized (bufferedLine) { bufferedLine.notifyAll(); } found = true; break lineSearch; } resend.add(bufferedLine); if (bufferedLineNumber == badLineNumber) { found = true; break lineSearch; } } if (okAfterResend) { // firmware sends "ok" after resend, put something here to consume it: buffer.addLast(";resend-ok"); } bufferLock.unlock(); if (!found) { int restartLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, resend.element().toLowerCase(), 1) ); Base.logger.severe("resend for line " + badLineNumber + " not in our buffer. Resuming from " + restartLineNumber); this.resendCommand(applyChecksum("N"+(restartLineNumber-1)+" M110")); } // resend the lines while (!resend.isEmpty()) { String bufferedLine = resend.remove(); this.resendCommand(bufferedLine); } } else { // Malformed resend line request received. Resetting the line number Base.logger.warning("malformed line resend request, " +"resetting line number. Malformed Data: \n"+line); this.resendCommand(applyChecksum("N"+(lineNumber.get()-1)+" M110")); } } else if (line.startsWith("t:") || line.startsWith("c:")) { // temperature, position handled above } else { Base.logger.severe("Unknown: " + line); } } readResponseLock.unlock(); }
public void serialByteReceivedEvent(ByteFifo fifo) { readResponseLock.lock(); serialInUse.lock(); byte[] response = fifo.dequeueLine(); int responseLength = response.length; serialInUse.unlock(); // 0 is now an acceptable value; it merely means that we timed out // waiting for input if (responseLength < 0) { // This signifies EOF. FIXME: How do we handle this? Base.logger.severe("SerialPassthroughDriver.readResponse(): EOF occured"); readResponseLock.unlock(); return; } else if(responseLength!=0) { String line; try { //convert to string and remove any trailing \r or \n's line = new String(response, 0, responseLength, "US-ASCII") .trim().toLowerCase(); } catch (UnsupportedEncodingException e) { Base.logger.severe("US-ASCII required. Terminating."); readResponseLock.unlock(); throw new RuntimeException(e); } //System.out.println("received: " + line); if(debugLevel > 1) Base.logger.info("<< " + line); if (line.length() == 0) Base.logger.fine("empty line received"); else if (line.startsWith("echo:")) { //if echo is turned on relay it to the user for debugging Base.logger.info(line); } else if (line.startsWith("ok t:")||line.startsWith("t:")) { Pattern r = Pattern.compile("t:([0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find( )) { String temp = m.group(1); machine.currentTool().setCurrentTemperature( Double.parseDouble(temp)); } r = Pattern.compile("^ok.*b:([0-9\\.]+)"); m = r.matcher(line); if (m.find( )) { String bedTemp = m.group(1); machine.currentTool().setPlatformCurrentTemperature( Double.parseDouble(bedTemp)); } } else if (line.startsWith("ok c:")||line.startsWith("c:")) { Pattern r = Pattern.compile("c: *x:?([-0-9\\.]+) *y:?([-0-9\\.]+) *z:?([-0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find()) { double x = Double.parseDouble(m.group(1)); double y = Double.parseDouble(m.group(2)); double z = Double.parseDouble(m.group(3)); // super to avoid parroting back a G92 try { super.setCurrentPosition(new Point5d(x, y, z)); //Base.logger.fine("setting currentposition to:"+x+","+y+","+z+"."); } catch (RetryException e) { // do or do not, there is no retry } } } if (line.startsWith("ok")) { synchronized(okReceived) { okReceived.set(true); okReceived.notifyAll(); } bufferLock.lock(); //Notify the thread waitining in this gcode's sendCommand method that the gcode has been received. if (buffer.isEmpty()) { Base.logger.severe("Received OK with nothing queued!"); } else { String notifier = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("FW Accepted: " + notifier); synchronized(notifier) { notifier.notifyAll(); } } bufferLock.unlock(); synchronized(bufferLock) { /*let any sendCommand method waiting to send know that the buffer is now smaller and may be able to fit their command.*/ bufferLock.notifyAll(); } } // old arduino firmware sends "start" else if (line.contains("start")) { // Reset line number first in case gcode is sent below lineNumber.set(-1); boolean active = !buffer.isEmpty(); flushBuffer(); if (isInitialized()) { sendInitializationGcode(false); // If there were outstanding commands try to abort any print in progress. // This is a poor test: but do we know if we're printing at this level? // tried setInitialized(false); but that didn't work well if (active) { Base.logger.severe("Firmware reset with active commands!"); setError("Firmware reset with active commands!"); } } if (okAfterStart) { // firmware sends "ok" after start, put something here to consume it: bufferLock.lock(); buffer.addLast(";start-ok"); bufferLock.unlock(); } // todo: set version synchronized (startReceived) { startReceived.set(true); startReceived.notifyAll(); } // Wake up connect task to try again synchronized (okReceived) { okReceived.set(false); okReceived.notifyAll(); } } else if (line.startsWith("extruder fail")) { setError("Extruder failed: cannot extrude as this rate."); } else if (line.startsWith("resend:")||line.startsWith("rs ")) { // Bad checksum, resend requested Matcher badLineMatch = resendLinePattern.matcher(line); // Is it a Dud M or G code? String dudLetter = getRegexMatch("dud ([a-z]) code", line, 1); if (badLineMatch.find()) { int badLineNumber = Integer.parseInt( badLineMatch.group(1) ); if(debugLevel > 1) Base.logger.warning("Received resend request for line " + badLineNumber); Queue<String> resend = new LinkedList<String>(); boolean found = false; // Search backwards for the bad line in our buffer. // Firmware flushed everything after this line, so // build a queue of lines to resend. bufferLock.lock(); lineSearch: while (!buffer.isEmpty()) { String bufferedLine = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("Searching: " + bufferedLine); int bufferedLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, bufferedLine.toLowerCase(), 1) ); if (dudLetter != null && bufferedLineNumber == badLineNumber) { Base.logger.info("Dud "+dudLetter+" code: Dropping " + bufferedLine); synchronized (bufferedLine) { bufferedLine.notifyAll(); } found = true; break lineSearch; } resend.add(bufferedLine); if (bufferedLineNumber == badLineNumber) { found = true; break lineSearch; } } if (okAfterResend) { // firmware sends "ok" after resend, put something here to consume it: buffer.addLast(";resend-ok"); } bufferLock.unlock(); if (!found) { int restartLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, resend.element().toLowerCase(), 1) ); Base.logger.severe("resend for line " + badLineNumber + " not in our buffer. Resuming from " + restartLineNumber); this.resendCommand(applyChecksum("N"+(restartLineNumber-1)+" M110")); } // resend the lines while (!resend.isEmpty()) { String bufferedLine = resend.remove(); this.resendCommand(bufferedLine); } } else { // Malformed resend line request received. Resetting the line number Base.logger.warning("malformed line resend request, " +"resetting line number. Malformed Data: \n"+line); this.resendCommand(applyChecksum("N"+(lineNumber.get()-1)+" M110")); } } else if (line.startsWith("t:") || line.startsWith("c:")) { // temperature, position handled above } else { Base.logger.severe("Unknown: " + line); } } readResponseLock.unlock(); }
diff --git a/src/main/java/org/spout/vanilla/controller/object/moving/Item.java b/src/main/java/org/spout/vanilla/controller/object/moving/Item.java index 0311d04a..d8711076 100644 --- a/src/main/java/org/spout/vanilla/controller/object/moving/Item.java +++ b/src/main/java/org/spout/vanilla/controller/object/moving/Item.java @@ -1,151 +1,151 @@ /* * This file is part of Vanilla. * * Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/> * Vanilla is licensed under the SpoutDev License Version 1. * * Vanilla is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * Vanilla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spout.vanilla.controller.object.moving; import org.spout.api.entity.Entity; import org.spout.api.entity.type.ControllerType; import org.spout.api.entity.type.EmptyConstructorControllerType; import org.spout.api.geo.cuboid.Block; import org.spout.api.inventory.ItemStack; import org.spout.api.material.Material; import org.spout.api.math.Vector3; import org.spout.api.player.Player; import org.spout.vanilla.configuration.VanillaConfiguration; import org.spout.vanilla.controller.VanillaControllerTypes; import org.spout.vanilla.controller.living.player.VanillaPlayer; import org.spout.vanilla.controller.object.Substance; import org.spout.vanilla.material.VanillaMaterials; import org.spout.vanilla.protocol.msg.CollectItemMessage; import static org.spout.vanilla.protocol.VanillaNetworkSynchronizer.sendPacketsToNearbyPlayers; /** * Controller that serves as the base for all items that are not in an inventory (dispersed in the world). */ public class Item extends Substance { public static final ControllerType TYPE = new EmptyConstructorControllerType(Item.class, "Item"); private final int distance = (int) VanillaConfiguration.ITEM_PICKUP_RANGE.getDouble(); private final ItemStack is; private int unpickable; /** * Creates an item controller. Intended for deserialization only. */ protected Item() { this(new ItemStack(VanillaMaterials.AIR, 1), Vector3.ZERO); } /** * Creates an item controller * @param itemstack this item controller represents * @param initial velocity that this item has */ public Item(ItemStack itemstack, Vector3 initial) { super(VanillaControllerTypes.DROPPED_ITEM); this.is = itemstack; unpickable = 10; setVelocity(initial); } @Override public void onAttached() { super.onAttached(); if (data().containsKey("Itemstack")) { ItemStack item = (ItemStack) data().get("Itemstack"); is.setMaterial(item.getMaterial(), item.getData()); is.setAmount(item.getAmount()); is.setNBTData(item.getNBTData()); is.getAuxData().putAll(item.getAuxData()); } unpickable = (Integer) data().get("unpickable", unpickable); } @Override public void onTick(float dt) { if (unpickable > 0) { unpickable--; super.onTick(dt); return; } super.onTick(dt); Block block = getParent().getRegion().getBlock(getParent().getPosition().subtract(0, 1, 0)); if (!block.getMaterial().isPlacementObstacle()) { Vector3 next = block.getPosition(); getParent().translate(block.getPosition().multiply(dt)); } Player closestPlayer = getParent().getWorld().getNearestPlayer(getParent(), distance); if (closestPlayer == null) { return; } Entity entity = closestPlayer.getEntity(); if (!(entity.getController() instanceof VanillaPlayer)) { return; } int collected = getParent().getId(); int collector = entity.getId(); - sendPacketsToNearbyPlayers(entity.getPosition(), entity.getViewDistance(), new CollectItemMessage(collector, collected)); + sendPacketsToNearbyPlayers(entity.getPosition(), entity.getViewDistance(), new CollectItemMessage(collected, collector)); ((VanillaPlayer) entity.getController()).getInventory().getBase().addItem(is, true, true); getParent().kill(); } /** * Gets what block the item is. * @return block of item. */ public Material getMaterial() { return is.getMaterial(); } /** * Gets the amount of the block there is in the ItemStack. * @return amount of items */ public int getAmount() { return is.getAmount(); } /** * Gets the data of the item * @return item data */ public short getData() { return is.getData(); } @Override public void onSave() { super.onSave(); data().put("Itemstack", is); data().put("unpickable", unpickable); } }
true
true
public void onTick(float dt) { if (unpickable > 0) { unpickable--; super.onTick(dt); return; } super.onTick(dt); Block block = getParent().getRegion().getBlock(getParent().getPosition().subtract(0, 1, 0)); if (!block.getMaterial().isPlacementObstacle()) { Vector3 next = block.getPosition(); getParent().translate(block.getPosition().multiply(dt)); } Player closestPlayer = getParent().getWorld().getNearestPlayer(getParent(), distance); if (closestPlayer == null) { return; } Entity entity = closestPlayer.getEntity(); if (!(entity.getController() instanceof VanillaPlayer)) { return; } int collected = getParent().getId(); int collector = entity.getId(); sendPacketsToNearbyPlayers(entity.getPosition(), entity.getViewDistance(), new CollectItemMessage(collector, collected)); ((VanillaPlayer) entity.getController()).getInventory().getBase().addItem(is, true, true); getParent().kill(); }
public void onTick(float dt) { if (unpickable > 0) { unpickable--; super.onTick(dt); return; } super.onTick(dt); Block block = getParent().getRegion().getBlock(getParent().getPosition().subtract(0, 1, 0)); if (!block.getMaterial().isPlacementObstacle()) { Vector3 next = block.getPosition(); getParent().translate(block.getPosition().multiply(dt)); } Player closestPlayer = getParent().getWorld().getNearestPlayer(getParent(), distance); if (closestPlayer == null) { return; } Entity entity = closestPlayer.getEntity(); if (!(entity.getController() instanceof VanillaPlayer)) { return; } int collected = getParent().getId(); int collector = entity.getId(); sendPacketsToNearbyPlayers(entity.getPosition(), entity.getViewDistance(), new CollectItemMessage(collected, collector)); ((VanillaPlayer) entity.getController()).getInventory().getBase().addItem(is, true, true); getParent().kill(); }
diff --git a/src/main/java/com/happyelements/hive/web/HadoopClient.java b/src/main/java/com/happyelements/hive/web/HadoopClient.java index 6e65ab6..3837ccb 100755 --- a/src/main/java/com/happyelements/hive/web/HadoopClient.java +++ b/src/main/java/com/happyelements/hive/web/HadoopClient.java @@ -1,510 +1,509 @@ /* * Copyright (c) 2012, someone All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1.Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. 2.Redistributions in binary * form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided * with the distribution. 3.Neither the name of the Happyelements Ltd. nor the * names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.happyelements.hive.web; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.ArrayList; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.common.JavaUtils; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.Driver; import org.apache.hadoop.hive.ql.exec.ExecDriver; import org.apache.hadoop.hive.ql.exec.FetchOperator; import org.apache.hadoop.hive.ql.exec.Task; import org.apache.hadoop.hive.ql.exec.Utilities; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.hive.serde.Constants; import org.apache.hadoop.hive.serde2.DelimitedJSONSerDe; import org.apache.hadoop.hive.serde2.SerDe; import org.apache.hadoop.hive.serde2.objectinspector.InspectableObject; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobID; import org.apache.hadoop.mapred.JobPriority; import org.apache.hadoop.mapred.JobStatus; import org.apache.hadoop.mapred.JobTracker; import org.apache.hadoop.mapred.RunningJob; import org.apache.hadoop.util.ReflectionUtils; /** * wrapper for some hadoop api * @author <a href="mailto:[email protected]">kevin</a> */ public class HadoopClient { private static final Log LOGGER = LogFactory.getLog(HadoopClient.class); private static final long INVALIDATE_PERIOD = 3600000 * 4; /** * query info,include job status and query/user * @author <a href="mailto:[email protected]">kevin</a> */ public static class QueryInfo { public String user; public String query_id; public String query; public String job_id; public long access; public JobStatus status; /** * constructor * @param user * the user name * @param query_id * the query id * @param query * the query string * @param job_id * the job id */ public QueryInfo(String user, String query_id, String query, String job_id) { this.user = user; this.query_id = query_id; this.query = query.replace("\n", " ").replace("\r", " ") .replace("\"", "'").replace("\t", " "); this.job_id = job_id; } /** * {@inheritDoc}} * @see java.lang.Object#toString() */ @Override public String toString() { return "user:" + this.user + " query_id:" + this.query_id + " job_id:" + this.job_id + " query:" + this.query; } } private static final JobClient CLIENT; private static final ConcurrentHashMap<String, ConcurrentHashMap<String, QueryInfo>> USER_JOB_CACHE; private static final ConcurrentHashMap<String, QueryInfo> JOB_CACHE; static { try { CLIENT = new JobClient(new JobConf(new HiveConf())); } catch (Exception e) { throw new RuntimeException(e); } // create user job cache JOB_CACHE = new ConcurrentHashMap<String, HadoopClient.QueryInfo>(); USER_JOB_CACHE = new ConcurrentHashMap<String, ConcurrentHashMap<String, QueryInfo>>(); // schedule user cache update Central.schedule(new Runnable() { private boolean refreshing = false; @Override public void run() { if (this.refreshing) { return; } else { this.refreshing = true; } HadoopClient.LOGGER.info("triger refresh " + Central.now()); try { for (JobStatus status : HadoopClient.CLIENT.getAllJobs()) { if (status.getJobPriority() == JobPriority.HIGH) { LOGGER.info("fetch a job:" + status.getJobID() + " start_time:" + status.getStartTime() + " now:" + Central.now() + " diff:" + (Central.now() - status.getStartTime() >= HadoopClient.INVALIDATE_PERIOD)); } else { continue; } // ignore old guys long start_time = status.getStartTime(); if (start_time > 0 && Central.now() - start_time >= HadoopClient.INVALIDATE_PERIOD) { continue; } // save job id String job_id = status.getJobID().toString(); // update info QueryInfo info = HadoopClient.JOB_CACHE.get(job_id); if (info == null) { JobConf conf = new JobConf(JobTracker .getLocalJobFilePath(status.getJobID())); String query = conf.get("hive.query.string"); String query_id = conf.get("rest.query.id"); String user = conf.get("he.user.name"); // take care of this,use should be empty string if // null info = new QueryInfo(user == null ? "" : user, // query_id == null ? "" : query_id, // query == null ? "" : query, // job_id); if (user != null) { LOGGER.info("new query info of user:" + info); } info.access = Central.now(); QueryInfo old = HadoopClient.JOB_CACHE.putIfAbsent( job_id, info); info = old == null ? info : old; } // update status info.status = status; // tricky way to update user cache,as a none App,user // will be empty if (!info.user.isEmpty()) { // find user cache ConcurrentHashMap<String, HadoopClient.QueryInfo> user_infos = HadoopClient.USER_JOB_CACHE .get(info.user); if (user_infos == null) { user_infos = new ConcurrentHashMap<String, HadoopClient.QueryInfo>(); ConcurrentHashMap<String, QueryInfo> old = HadoopClient.USER_JOB_CACHE .putIfAbsent(info.user, user_infos); user_infos = old == null ? user_infos : old; } // replicate it user_infos.put(info.job_id, info); user_infos.put(info.query_id, info); HadoopClient.LOGGER.info("put query info to cache:" + info); } } } catch (IOException e) { HadoopClient.LOGGER.error("fail to refresh old job", e); } finally { // reset flag this.refreshing = false; } } }, 1); // schedule query info cache clean up Central.schedule(new Runnable() { @Override public void run() { long now = Central.now(); int before_clean_job_cacha = HadoopClient.JOB_CACHE.size(); int before_clean_user_job_cache = HadoopClient.USER_JOB_CACHE .size(); for (Entry<String, QueryInfo> query_info_entry : HadoopClient.JOB_CACHE .entrySet()) { QueryInfo info = query_info_entry.getValue(); if (info == null) { HadoopClient.JOB_CACHE .remove(query_info_entry.getKey()); continue; } // clean expire if (now - info.access >= 3600000 || (info.status.getStartTime() > 0 && now - info.status.getStartTime() >= HadoopClient.INVALIDATE_PERIOD)) { // clean expire info from user cache HadoopClient.JOB_CACHE .remove(query_info_entry.getKey()); // clean related user job cache Map<String, QueryInfo> user_query_info_cache = HadoopClient.USER_JOB_CACHE .get(info.user); // if user query is empty,remove it if (user_query_info_cache != null) { user_query_info_cache.remove(info.job_id); user_query_info_cache.remove(info.query_id); } HadoopClient.LOGGER.info("remove job info:" + info.query_id + " user:" + info.user); } } // remove empty user cache for (Entry<String, ConcurrentHashMap<String, QueryInfo>> user_query_cache_entry : HadoopClient.USER_JOB_CACHE .entrySet()) { if (user_query_cache_entry.getValue().isEmpty()) { HadoopClient.USER_JOB_CACHE .remove(user_query_cache_entry.getKey()); } } HadoopClient.LOGGER.info("job cache:" + HadoopClient.JOB_CACHE.size() + " before:" + before_clean_job_cacha + " user job cache:" + HadoopClient.USER_JOB_CACHE.size() + " before:" + before_clean_user_job_cache); } }, 60); } /** * find query info by either job id or query id * @param id * either job id or query id * @return * the query info */ public static QueryInfo getQueryInfo(String id) { QueryInfo info; // lucky case if ((info = HadoopClient.JOB_CACHE.get(id)) != null) { return info; } // may be a query id loop it for (Entry<String, ConcurrentHashMap<String, QueryInfo>> entry : HadoopClient.USER_JOB_CACHE .entrySet()) { // find match if ((info = entry.getValue().get(id)) != null) { break; } } return info; } /** * get running job status * @param id * the JobID of job * @return * the running job if exist * @throws IOException * thrown when communicate to jobtracker fail */ public static RunningJob getJob(JobID id) throws IOException { return HadoopClient.CLIENT.getJob(id); } /** * get running job status * @param id * the JobID of job * @return * the running job if exist * @throws IOException * thrown when communicate to jobtracker fail */ public static Map<String, QueryInfo> getAllQuerys() throws IOException { return HadoopClient.JOB_CACHE; } /** * get the user query * @param user * the user name * @return * the users name */ public static Map<String, QueryInfo> getUserQuerys(String user) { // trigger refresh return HadoopClient.USER_JOB_CACHE.get(user); } /** /** * async submit a query * @param user * the submit user * @param query_id * the query id * @param query * the query * @param conf * the hive conf * @param priority * the priority */ public static void asyncSubmitQuery(final String query, final HiveConf conf, final File out_file, final JobPriority priority) { Central.getThreadPool().submit(new Runnable() { @Override public void run() { conf.setEnum("mapred.job.priority", priority != null ? priority : JobPriority.NORMAL); SessionState session = new SessionState(conf); session.setIsSilent(true); session.setIsVerbose(true); SessionState.start(session); Driver driver = new Driver(); driver.init(); try { if (driver.run(query).getResponseCode() == 0 && out_file != null) { FileOutputStream file = null; try { ArrayList<String> result = new ArrayList<String>(); driver.getResults(result); JobConf job = new JobConf(conf, ExecDriver.class); FetchOperator operator = new FetchOperator(driver .getPlan().getFetchTask().getWork(), job); String serdeName = HiveConf.getVar(conf, HiveConf.ConfVars.HIVEFETCHOUTPUTSERDE); Class<? extends SerDe> serdeClass = Class .forName(serdeName, true, JavaUtils.getClassLoader()) .asSubclass(SerDe.class); // cast only needed for // Hadoop // 0.17 compatibility SerDe serde = ReflectionUtils.newInstance( serdeClass, null); Properties serdeProp = new Properties(); // this is the default // serialization format if (serde instanceof DelimitedJSONSerDe) { serdeProp.put(Constants.SERIALIZATION_FORMAT, "" + Utilities.tabCode); serdeProp.put( Constants.SERIALIZATION_NULL_FORMAT, driver.getPlan().getFetchTask() .getWork() .getSerializationNullFormat()); } serde.initialize(job, serdeProp); file = new FileOutputStream(out_file); InspectableObject io = operator.getNextRow(); while (io != null) { file.write((((Text) serde .serialize(io.o, io.oi)).toString() + "\n") .getBytes()); io = operator.getNextRow(); } } catch (Exception e) { HadoopClient.LOGGER .error("unexpected exception when writing result to files", e); } finally { try { if (file != null) { file.close(); // try to patch that not generate map reduce job boolean contain_map_redcue = false; for (Task<?> task : driver.getPlan() .getRootTasks()) { if (task.isMapRedTask()) { contain_map_redcue = true; } } // tricky patch if (!contain_map_redcue) { LOGGER.info("not a map reduce query"); // make a query info QueryInfo info = new QueryInfo(conf .get("he.user.name", ""), conf .get("rest.query.id", ""), conf .get("he.query.string", ""), ""); // make a fake status - info.status = new JobStatus(JobID - .forName(""), 1.0f, 1.0f, 1.0f, + info.status = new JobStatus(null, 1.0f, 1.0f, 1.0f, 1.0f, JobStatus.SUCCEEDED, JobPriority.HIGH); // update time info.access = Central.now(); // attatch ConcurrentHashMap<String, QueryInfo> user_querys = USER_JOB_CACHE .get(conf.get("he.user.name")); if (user_querys == null) { ConcurrentHashMap<String, QueryInfo> old = USER_JOB_CACHE.putIfAbsent( conf.get("he.user.name"), new ConcurrentHashMap<String, HadoopClient.QueryInfo>()); user_querys = old != null ? old : user_querys; } user_querys.put( conf.get("rest.query.id"), info); // for some synchronized bugs. // as the cache policy may clear the caches right it was update USER_JOB_CACHE.put(conf.get("he.user.name"), user_querys); - LOGGER.info("not a map reduce query:"+conf.get("he.user.name")); + LOGGER.info("not a map reduce query user.name:"+conf.get("he.user.name")); // sniper for (Entry<String, QueryInfo> entry : getUserQuerys(conf.get("he.user.name")).entrySet()) { LOGGER.info("not a map reduce query info:" + entry.getKey()); } } } } catch (IOException e) { HadoopClient.LOGGER.error("fail to close file:" + file, e); } } } } catch (Exception e) { HadoopClient.LOGGER.error("fail to submit querys", e); } finally { driver.close(); } } }); } /** * async submit a query * @param user * the submit user * @param query_id * the query id * @param query * the query * @param conf * the hive conf */ public static void asyncSubmitQuery(final String query, final HiveConf conf, final File out_file) { HadoopClient.asyncSubmitQuery(query, conf, out_file, JobPriority.HIGH); } }
false
true
public static void asyncSubmitQuery(final String query, final HiveConf conf, final File out_file, final JobPriority priority) { Central.getThreadPool().submit(new Runnable() { @Override public void run() { conf.setEnum("mapred.job.priority", priority != null ? priority : JobPriority.NORMAL); SessionState session = new SessionState(conf); session.setIsSilent(true); session.setIsVerbose(true); SessionState.start(session); Driver driver = new Driver(); driver.init(); try { if (driver.run(query).getResponseCode() == 0 && out_file != null) { FileOutputStream file = null; try { ArrayList<String> result = new ArrayList<String>(); driver.getResults(result); JobConf job = new JobConf(conf, ExecDriver.class); FetchOperator operator = new FetchOperator(driver .getPlan().getFetchTask().getWork(), job); String serdeName = HiveConf.getVar(conf, HiveConf.ConfVars.HIVEFETCHOUTPUTSERDE); Class<? extends SerDe> serdeClass = Class .forName(serdeName, true, JavaUtils.getClassLoader()) .asSubclass(SerDe.class); // cast only needed for // Hadoop // 0.17 compatibility SerDe serde = ReflectionUtils.newInstance( serdeClass, null); Properties serdeProp = new Properties(); // this is the default // serialization format if (serde instanceof DelimitedJSONSerDe) { serdeProp.put(Constants.SERIALIZATION_FORMAT, "" + Utilities.tabCode); serdeProp.put( Constants.SERIALIZATION_NULL_FORMAT, driver.getPlan().getFetchTask() .getWork() .getSerializationNullFormat()); } serde.initialize(job, serdeProp); file = new FileOutputStream(out_file); InspectableObject io = operator.getNextRow(); while (io != null) { file.write((((Text) serde .serialize(io.o, io.oi)).toString() + "\n") .getBytes()); io = operator.getNextRow(); } } catch (Exception e) { HadoopClient.LOGGER .error("unexpected exception when writing result to files", e); } finally { try { if (file != null) { file.close(); // try to patch that not generate map reduce job boolean contain_map_redcue = false; for (Task<?> task : driver.getPlan() .getRootTasks()) { if (task.isMapRedTask()) { contain_map_redcue = true; } } // tricky patch if (!contain_map_redcue) { LOGGER.info("not a map reduce query"); // make a query info QueryInfo info = new QueryInfo(conf .get("he.user.name", ""), conf .get("rest.query.id", ""), conf .get("he.query.string", ""), ""); // make a fake status info.status = new JobStatus(JobID .forName(""), 1.0f, 1.0f, 1.0f, 1.0f, JobStatus.SUCCEEDED, JobPriority.HIGH); // update time info.access = Central.now(); // attatch ConcurrentHashMap<String, QueryInfo> user_querys = USER_JOB_CACHE .get(conf.get("he.user.name")); if (user_querys == null) { ConcurrentHashMap<String, QueryInfo> old = USER_JOB_CACHE.putIfAbsent( conf.get("he.user.name"), new ConcurrentHashMap<String, HadoopClient.QueryInfo>()); user_querys = old != null ? old : user_querys; } user_querys.put( conf.get("rest.query.id"), info); // for some synchronized bugs. // as the cache policy may clear the caches right it was update USER_JOB_CACHE.put(conf.get("he.user.name"), user_querys); LOGGER.info("not a map reduce query:"+conf.get("he.user.name")); // sniper for (Entry<String, QueryInfo> entry : getUserQuerys(conf.get("he.user.name")).entrySet()) { LOGGER.info("not a map reduce query info:" + entry.getKey()); } } } } catch (IOException e) { HadoopClient.LOGGER.error("fail to close file:" + file, e); } } } } catch (Exception e) { HadoopClient.LOGGER.error("fail to submit querys", e); } finally { driver.close(); } } }); }
public static void asyncSubmitQuery(final String query, final HiveConf conf, final File out_file, final JobPriority priority) { Central.getThreadPool().submit(new Runnable() { @Override public void run() { conf.setEnum("mapred.job.priority", priority != null ? priority : JobPriority.NORMAL); SessionState session = new SessionState(conf); session.setIsSilent(true); session.setIsVerbose(true); SessionState.start(session); Driver driver = new Driver(); driver.init(); try { if (driver.run(query).getResponseCode() == 0 && out_file != null) { FileOutputStream file = null; try { ArrayList<String> result = new ArrayList<String>(); driver.getResults(result); JobConf job = new JobConf(conf, ExecDriver.class); FetchOperator operator = new FetchOperator(driver .getPlan().getFetchTask().getWork(), job); String serdeName = HiveConf.getVar(conf, HiveConf.ConfVars.HIVEFETCHOUTPUTSERDE); Class<? extends SerDe> serdeClass = Class .forName(serdeName, true, JavaUtils.getClassLoader()) .asSubclass(SerDe.class); // cast only needed for // Hadoop // 0.17 compatibility SerDe serde = ReflectionUtils.newInstance( serdeClass, null); Properties serdeProp = new Properties(); // this is the default // serialization format if (serde instanceof DelimitedJSONSerDe) { serdeProp.put(Constants.SERIALIZATION_FORMAT, "" + Utilities.tabCode); serdeProp.put( Constants.SERIALIZATION_NULL_FORMAT, driver.getPlan().getFetchTask() .getWork() .getSerializationNullFormat()); } serde.initialize(job, serdeProp); file = new FileOutputStream(out_file); InspectableObject io = operator.getNextRow(); while (io != null) { file.write((((Text) serde .serialize(io.o, io.oi)).toString() + "\n") .getBytes()); io = operator.getNextRow(); } } catch (Exception e) { HadoopClient.LOGGER .error("unexpected exception when writing result to files", e); } finally { try { if (file != null) { file.close(); // try to patch that not generate map reduce job boolean contain_map_redcue = false; for (Task<?> task : driver.getPlan() .getRootTasks()) { if (task.isMapRedTask()) { contain_map_redcue = true; } } // tricky patch if (!contain_map_redcue) { LOGGER.info("not a map reduce query"); // make a query info QueryInfo info = new QueryInfo(conf .get("he.user.name", ""), conf .get("rest.query.id", ""), conf .get("he.query.string", ""), ""); // make a fake status info.status = new JobStatus(null, 1.0f, 1.0f, 1.0f, 1.0f, JobStatus.SUCCEEDED, JobPriority.HIGH); // update time info.access = Central.now(); // attatch ConcurrentHashMap<String, QueryInfo> user_querys = USER_JOB_CACHE .get(conf.get("he.user.name")); if (user_querys == null) { ConcurrentHashMap<String, QueryInfo> old = USER_JOB_CACHE.putIfAbsent( conf.get("he.user.name"), new ConcurrentHashMap<String, HadoopClient.QueryInfo>()); user_querys = old != null ? old : user_querys; } user_querys.put( conf.get("rest.query.id"), info); // for some synchronized bugs. // as the cache policy may clear the caches right it was update USER_JOB_CACHE.put(conf.get("he.user.name"), user_querys); LOGGER.info("not a map reduce query user.name:"+conf.get("he.user.name")); // sniper for (Entry<String, QueryInfo> entry : getUserQuerys(conf.get("he.user.name")).entrySet()) { LOGGER.info("not a map reduce query info:" + entry.getKey()); } } } } catch (IOException e) { HadoopClient.LOGGER.error("fail to close file:" + file, e); } } } } catch (Exception e) { HadoopClient.LOGGER.error("fail to submit querys", e); } finally { driver.close(); } } }); }
diff --git a/mmstudio/src/org/micromanager/acquisition/MMAcquisition.java b/mmstudio/src/org/micromanager/acquisition/MMAcquisition.java index 4be66b9a9..71b7216e5 100644 --- a/mmstudio/src/org/micromanager/acquisition/MMAcquisition.java +++ b/mmstudio/src/org/micromanager/acquisition/MMAcquisition.java @@ -1,729 +1,729 @@ /////////////////////////////////////////////////////////////////////////////// //FILE: MMAcquisition.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio //----------------------------------------------------------------------------- // // AUTHOR: Nico Stuurman, November 2010 // // COPYRIGHT: University of California, San Francisco, 2010 // // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. /* * This class is used to execute most of the acquisition and image display * functionality in the ScriptInterface */ package org.micromanager.acquisition; import ij.ImagePlus; import java.awt.Color; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Iterator; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import mmcorej.CMMCore; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.ImageCache; import org.micromanager.api.TaggedImageStorage; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; public class MMAcquisition { private int numFrames_ = 0; private int numChannels_ = 0; private int numSlices_ = 0; private int numPositions_ = 0; protected String name_; protected int width_ = 0; protected int height_ = 0; protected int depth_ = 1; private boolean initialized_ = false; private long startTimeMs_; private String comment_ = "Acquisition from a script"; private String rootDirectory_; private VirtualAcquisitionDisplay virtAcq_; private final boolean existing_; private final boolean diskCached_; private final boolean show_; private JSONArray channelColors_ = new JSONArray(); private JSONArray channelNames_ = new JSONArray(); private JSONObject summary_ = new JSONObject(); private final String NOTINITIALIZED = "Acquisition was not initialized"; public MMAcquisition(String name, String dir) throws MMScriptException { this(name, dir, false, false, false); } public MMAcquisition(String name, String dir, boolean show) throws MMScriptException { this(name, dir, show, false, false); } public MMAcquisition(String name, String dir, boolean show, boolean diskCached, boolean existing) throws MMScriptException { name_ = name; rootDirectory_ = dir; show_ = show; existing_ = existing; diskCached_ = diskCached; } static private String generateRootName(String name, String baseDir) { // create new acquisition directory int suffixCounter = 0; String testPath; File testDir; String testName; do { testName = name + "_" + suffixCounter; testPath = baseDir + File.separator + testName; suffixCounter++; testDir = new File(testPath); } while (testDir.exists()); return testName; } public void setImagePhysicalDimensions(int width, int height, int depth) throws MMScriptException { if (initialized_) { throw new MMScriptException("Can't image change dimensions - the acquisition is already initialized"); } width_ = width; height_ = height; depth_ = depth; } public int getWidth() { return width_; } public int getHeight() { return height_; } public int getDepth() { return depth_; } public int getFrames() { return numFrames_; } public int getChannels() { return numChannels_; } public int getSlices() { return numSlices_; } public void setDimensions(int frames, int channels, int slices) throws MMScriptException { setDimensions(frames, channels, slices, 0); } public void setDimensions(int frames, int channels, int slices, int positions) throws MMScriptException { if (initialized_) { throw new MMScriptException("Can't change dimensions - the acquisition is already initialized"); } numFrames_ = frames; numChannels_ = channels; numSlices_ = slices; numPositions_ = positions; } public void setRootDirectory(String dir) throws MMScriptException { if (initialized_) { throw new MMScriptException("Can't change root directory - the acquisition is already initialized"); } rootDirectory_ = dir; } public void initialize() throws MMScriptException { if (initialized_) throw new MMScriptException("Acquisition is already initialized"); TaggedImageStorage imageFileManager; String name = name_; if (diskCached_) { String dirName = rootDirectory_ + File.separator + name; if (!existing_ && (new File(dirName)).exists()) { name = generateRootName(name_, rootDirectory_); dirName = rootDirectory_ + File.separator + name; } imageFileManager = new TaggedImageStorageDiskDefault(dirName, !existing_, new JSONObject()); } else { imageFileManager = new TaggedImageStorageRam(null); } MMImageCache imageCache = new MMImageCache(imageFileManager); if (!existing_) { createDefaultAcqSettings(name, imageCache); } virtAcq_ = new VirtualAcquisitionDisplay(imageCache, null, name); if (show_ && diskCached_ && existing_) { // start loading all other images in a background thread PreLoadDataThread t = new PreLoadDataThread(virtAcq_); new Thread(t, "PreLoadDataThread").start(); } if (show_) { virtAcq_.show(); } initialized_ = true; } private void createDefaultAcqSettings(String name, MMImageCache imageCache) { //if (new File(rootDirectory_).exists()) { // name = generateRootName(name, rootDirectory_); //} String keys[] = new String[summary_.length()]; Iterator<String> it = summary_.keys(); int i = 0; while (it.hasNext()) { keys[0] = it.next(); i++; } try { JSONObject summaryMetadata = new JSONObject(summary_, keys); CMMCore core = MMStudioMainFrame.getInstance().getCore(); summaryMetadata.put("BitDepth", core.getImageBitDepth()); summaryMetadata.put("Channels", numChannels_); setDefaultChannelTags(summaryMetadata); summaryMetadata.put("Comment", comment_); String compName = null; try { compName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { ReportingUtils.showError(e); } if (compName != null) summaryMetadata.put("ComputerName",compName); - summaryMetadata.put("Date", new SimpleDateFormat("YYY-MM-dd").format(Calendar.getInstance().getTime())); + summaryMetadata.put("Date", new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())); summaryMetadata.put("Depth", core.getBytesPerPixel()); summaryMetadata.put("Frames", numFrames_); summaryMetadata.put("GridColumn", 0); summaryMetadata.put("GridRow", 0); summaryMetadata.put("Height", height_); int ijType = -1; if (depth_ == 1) ijType = ImagePlus.GRAY8; else if (depth_ == 2) ijType = ImagePlus.GRAY16; else if (depth_==8) ijType = 64; else if (depth_ == 4 && core.getNumberOfComponents() == 1) ijType = ImagePlus.GRAY32; else if(depth_ == 4 && core.getNumberOfComponents() == 4) ijType = ImagePlus.COLOR_RGB; summaryMetadata.put("IJType", ijType); summaryMetadata.put("MetadataVersion", 10); summaryMetadata.put("MicroManagerVersion", MMStudioMainFrame.getInstance().getVersion()); summaryMetadata.put("NumComponents", 1); summaryMetadata.put("Positions", numPositions_); summaryMetadata.put("Source", "Micro-Manager"); summaryMetadata.put("PixelAspect", 1.0); summaryMetadata.put("PixelSize_um", core.getPixelSizeUm()); summaryMetadata.put("PixelType", (core.getNumberOfComponents() == 1 ? "GRAY" : "RGB") + (8*depth_)); summaryMetadata.put("Slices", numSlices_); summaryMetadata.put("StartTime", MDUtils.getCurrentTime()); summaryMetadata.put("Time", Calendar.getInstance().getTime()); summaryMetadata.put("UserName", System.getProperty("user.name")); summaryMetadata.put("UUID",UUID.randomUUID()); summaryMetadata.put("Width", width_); startTimeMs_ = System.currentTimeMillis(); imageCache.setSummaryMetadata(summaryMetadata); } catch (JSONException ex) { ReportingUtils.showError(ex); } } private void setDefaultChannelTags(JSONObject md) { JSONArray channelMaxes = new JSONArray(); JSONArray channelMins = new JSONArray(); // Both channelColors_ and channelNames_ may, or may not yet contain values // Since we don't know the size in the constructor, we can not pre-initialize // the data. Therefore, fill in the blanks with deafults here: for (Integer i = 0; i < numChannels_; i++) { try { channelColors_.get(i); } catch (JSONException ex) { try { channelColors_.put(i, (Object) Color.white.getRGB()); } catch (JSONException exx ) {;} } try { channelNames_.get(i); } catch (JSONException ex) { try { channelNames_.put(i, String.valueOf(i)); } catch (JSONException exx) {;} } try { channelMaxes.put(255); channelMins.put(0); } catch (Exception e) { ReportingUtils.logError(e); } } try { md.put("ChColors", channelColors_); md.put("ChNames", channelNames_); md.put("ChContrastMax", channelMaxes); md.put("ChContrastMin", channelMins); } catch (Exception e) { ReportingUtils.logError(e); } } public void insertImage(Object pixels, int frame, int channel, int slice) throws MMScriptException { insertImage(pixels, frame, channel, slice, 0); } public void insertImage(Object pixels, int frame, int channel, int slice, int position) throws MMScriptException { if (!initialized_) { throw new MMScriptException("Acquisition data must be initialized before inserting images"); } // update acq data try { JSONObject tags = new JSONObject(); tags.put("Channel", getChannelName(channel)); tags.put("ChannelIndex", channel); tags.put("Frame", frame); tags.put("Height", height_); tags.put("PositionIndex", position); // the following influences the format data will be saved! if (numPositions_ > 1) { tags.put("PositionName", "Pos" + position); } tags.put("Slice", slice); tags.put("Width", width_); MDUtils.setPixelTypeFromByteDepth(tags, depth_); TaggedImage tg = new TaggedImage(pixels, tags); insertImage(tg); } catch (JSONException e) { throw new MMScriptException(e); } } public void insertTaggedImage(TaggedImage taggedImg, int frame, int channel, int slice) throws MMScriptException { if (!initialized_) { throw new MMScriptException("Acquisition data must be initialized before inserting images"); } // update acq data try { JSONObject tags = taggedImg.tags; tags.put("FrameIndex", frame); tags.put("Frame", frame); tags.put("ChannelIndex", channel); tags.put("SliceIndex", slice); MDUtils.setPixelTypeFromByteDepth(tags, depth_); tags.put("PositionIndex", 0); insertImage(taggedImg); } catch (JSONException e) { throw new MMScriptException(e); } } public void insertImage(TaggedImage taggedImg) throws MMScriptException { insertImage(taggedImg, show_); } public void insertImage(TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException { insertImage(taggedImg, updateDisplay, true, true); } public void insertImage(TaggedImage taggedImg, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException { insertImage(taggedImg, updateDisplay, waitForDisplay, true); } /* * This is the insertImage version that actually puts data into the acquisition */ public void insertImage(TaggedImage taggedImg, boolean updateDisplay, boolean waitForDisplay, boolean allowContrastToChange) throws MMScriptException { if (!initialized_) { throw new MMScriptException("Acquisition data must be initialized before inserting images"); } try { JSONObject tags = taggedImg.tags; if (! (MDUtils.getWidth(tags) == width_ && MDUtils.getHeight(tags) == height_)) { throw new MMScriptException("Image dimensions do not match MMAcquisition."); } if (! MDUtils.getPixelType(tags).contentEquals(getPixelType(depth_))) { throw new MMScriptException("Pixel type does not match MMAcquisition."); } int channel = tags.getInt("ChannelIndex"); int frame = MDUtils.getFrameIndex(tags); tags.put("Channel", getChannelName(channel)); long elapsedTimeMillis = System.currentTimeMillis() - startTimeMs_; tags.put("ElapsedTime-ms", elapsedTimeMillis); tags.put("Time", MDUtils.getCurrentTime()); CMMCore core = MMStudioMainFrame.getInstance().getCore(); MDUtils.addConfiguration(taggedImg.tags, core.getSystemStateCache()); try { taggedImg.tags.put("Binning", core.getProperty (core.getCameraDevice(), "Binning")); } catch (Exception ex) { } tags.put("BitDepth", core.getImageBitDepth()); tags.put("PixelSizeUm",core.getPixelSizeUm()); tags.put("ROI", MDUtils.getROI(core)); } catch (JSONException ex) { throw new MMScriptException(ex); } try { virtAcq_.imageCache_.putImage(taggedImg); } catch (Exception ex) { throw new MMScriptException(ex); } if (updateDisplay) { try { if (virtAcq_ != null) virtAcq_.showImage(taggedImg.tags, waitForDisplay, allowContrastToChange); } catch (Exception e) { throw new MMScriptException("Unable to show image"); } } } public void close() { if (virtAcq_ != null) { if (virtAcq_.acquisitionIsRunning()) { virtAcq_.abort(); } virtAcq_.imageCache_.finished(); } } public boolean isInitialized() { return initialized_; } /** * Same as close(), but also closes the display */ public void closeImage5D() { close(); if (virtAcq_ != null) virtAcq_.close(); } public void toFront() { virtAcq_.getHyperImage().getWindow().toFront(); } public void setComment(String comment) throws MMScriptException { if (isInitialized()) { try { virtAcq_.imageCache_.getSummaryMetadata().put("COMMENT", comment); } catch (JSONException e) { throw new MMScriptException("Failed to set Comment"); } } else { comment_ = comment; } } public AcquisitionData getAcqData() { return null; } public ImageCache getImageCache() { if (virtAcq_ == null) return null; else return virtAcq_.getImageCache(); } public JSONObject getSummaryMetadata() { if (isInitialized()) return virtAcq_.imageCache_.getSummaryMetadata(); return null; } public String getChannelName(int channel) { if (isInitialized()) { String name = ""; try { name = (String) getSummaryMetadata().getJSONArray("ChNames").get(channel); } catch (JSONException e) { ReportingUtils.logError(e); return ""; } return name; } else { try { return channelNames_.getString(channel); } catch (JSONException ex) { // not found, do nothing } } return ""; } public void setChannelName(int channel, String name) throws MMScriptException { if (isInitialized()) { try { virtAcq_.imageCache_.getDisplayAndComments().getJSONArray("Channels").getJSONObject(channel).put("Name", name); virtAcq_.imageCache_.getSummaryMetadata().getJSONArray("ChNames").put(channel, name); } catch (JSONException e) { throw new MMScriptException("Problem setting Channel name"); } } else { try { channelNames_.put(channel, name); } catch (JSONException ex) { throw new MMScriptException(ex); } } } public void setChannelColor(int channel, int rgb) throws MMScriptException { if (isInitialized()) { try { virtAcq_.setChannelColor(channel, rgb); virtAcq_.imageCache_.getSummaryMetadata().getJSONArray("ChColors").put(channel, rgb); virtAcq_.updateAndDraw(); } catch (JSONException ex) { throw new MMScriptException(ex); } } else { try { channelColors_.put(channel, rgb); } catch (JSONException ex) { throw new MMScriptException(ex); } } } public void promptToSave(boolean promptToSave) { VirtualAcquisitionDisplay.getDisplay(virtAcq_.getHyperImage()).promptToSave(promptToSave); } public void setChannelContrast(int channel, int min, int max) throws MMScriptException { if (isInitialized()) virtAcq_.setChannelDisplayRange(channel, min, max); throw new MMScriptException (NOTINITIALIZED); } public void setContrastBasedOnFrame(int frame, int slice) throws MMScriptException { if (!isInitialized()) throw new MMScriptException (NOTINITIALIZED); ReportingUtils.logError("API call setContrastBasedOnFrame is not implemented!"); // TODO /* try { DisplaySettings[] settings = acqData_.setChannelContrastBasedOnFrameAndSlice(frame, slice); if (imgWin_ != null) { for (int i=0; i<settings.length; i++) imgWin_.getImage5D().setChannelMinMax(i+1, settings[i].min, settings[i].max); } } catch (MMAcqDataException e) { throw new MMScriptException(e); } */ } /* * Set a property in summary metadata */ public void setProperty(String propertyName, String value) throws MMScriptException { if (isInitialized()) { try { virtAcq_.imageCache_.getSummaryMetadata().put(propertyName, value); } catch (JSONException e) { throw new MMScriptException("Failed to set property: " + propertyName); } } else { try { summary_.put(propertyName, value); } catch (JSONException e) { throw new MMScriptException("Failed to set property: " + propertyName); } } } /* * Get a property from the summary metadata */ public String getProperty(String propertyName) throws MMScriptException { if (isInitialized()) { try { return virtAcq_.imageCache_.getSummaryMetadata().getString(propertyName); } catch (JSONException e) { throw new MMScriptException("Failed to get property: " + propertyName); } } else { try { return summary_.getString(propertyName); } catch (JSONException e) { throw new MMScriptException("Failed to get property: " + propertyName); } } } public void setProperty(int frame, int channel, int slice, String propName, String value) throws MMScriptException { if (isInitialized()) { try { JSONObject tags = virtAcq_.imageCache_.getImage(channel, slice, frame, 0).tags; tags.put(propName, value); } catch (JSONException e) { throw new MMScriptException(e); } } else throw new MMScriptException("Can not set property before acquisition is initialized"); } public void setSystemState(int frame, int channel, int slice, JSONObject state) throws MMScriptException { if (isInitialized()) { try { JSONObject tags = virtAcq_.imageCache_.getImage(channel, slice, frame, 0).tags; Iterator<String> iState = state.keys(); while (iState.hasNext()) { String key = iState.next(); tags.put(key, state.get(key)); } } catch (JSONException e) { throw new MMScriptException(e); } } else throw new MMScriptException("Can not set system state before acquisition is initialized"); } public String getProperty(int frame, int channel, int slice, String propName) throws MMScriptException { if (isInitialized()) { try { JSONObject tags = virtAcq_.imageCache_.getImage(channel, slice, frame, 0).tags; return tags.getString(propName); } catch (JSONException ex) { throw new MMScriptException(ex); } } else { } return ""; } public boolean hasActiveImage5D() { return virtAcq_.windowClosed(); } public void setSummaryProperties(JSONObject md) throws MMScriptException { if (isInitialized()) { try { JSONObject tags = virtAcq_.imageCache_.getSummaryMetadata(); Iterator<String> iState = md.keys(); while (iState.hasNext()) { String key = iState.next(); tags.put(key, md.get(key)); } } catch (Exception ex) { throw new MMScriptException(ex); } } else { try { Iterator<String> iState = md.keys(); while (iState.hasNext()) { String key = iState.next(); summary_.put(key, md.get(key)); } } catch (Exception ex) { throw new MMScriptException(ex); } } } public boolean windowClosed() { if (!initialized_) { return false; } if (virtAcq_ != null && !virtAcq_.windowClosed()) { return false; } return true; } public void setSystemState(JSONObject md) throws MMScriptException { throw new UnsupportedOperationException("Not supported yet."); } private static String getPixelType(int depth) { switch (depth) { case 1: return "GRAY8"; case 2: return "GRAY16"; case 4: return "RGB32"; case 8: return "RGB64"; } return null; } public int getLastAcquiredFrame() { return virtAcq_.imageCache_.lastAcquiredFrame(); } public VirtualAcquisitionDisplay getAcquisitionWindow() { return virtAcq_; } }
true
true
private void createDefaultAcqSettings(String name, MMImageCache imageCache) { //if (new File(rootDirectory_).exists()) { // name = generateRootName(name, rootDirectory_); //} String keys[] = new String[summary_.length()]; Iterator<String> it = summary_.keys(); int i = 0; while (it.hasNext()) { keys[0] = it.next(); i++; } try { JSONObject summaryMetadata = new JSONObject(summary_, keys); CMMCore core = MMStudioMainFrame.getInstance().getCore(); summaryMetadata.put("BitDepth", core.getImageBitDepth()); summaryMetadata.put("Channels", numChannels_); setDefaultChannelTags(summaryMetadata); summaryMetadata.put("Comment", comment_); String compName = null; try { compName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { ReportingUtils.showError(e); } if (compName != null) summaryMetadata.put("ComputerName",compName); summaryMetadata.put("Date", new SimpleDateFormat("YYY-MM-dd").format(Calendar.getInstance().getTime())); summaryMetadata.put("Depth", core.getBytesPerPixel()); summaryMetadata.put("Frames", numFrames_); summaryMetadata.put("GridColumn", 0); summaryMetadata.put("GridRow", 0); summaryMetadata.put("Height", height_); int ijType = -1; if (depth_ == 1) ijType = ImagePlus.GRAY8; else if (depth_ == 2) ijType = ImagePlus.GRAY16; else if (depth_==8) ijType = 64; else if (depth_ == 4 && core.getNumberOfComponents() == 1) ijType = ImagePlus.GRAY32; else if(depth_ == 4 && core.getNumberOfComponents() == 4) ijType = ImagePlus.COLOR_RGB; summaryMetadata.put("IJType", ijType); summaryMetadata.put("MetadataVersion", 10); summaryMetadata.put("MicroManagerVersion", MMStudioMainFrame.getInstance().getVersion()); summaryMetadata.put("NumComponents", 1); summaryMetadata.put("Positions", numPositions_); summaryMetadata.put("Source", "Micro-Manager"); summaryMetadata.put("PixelAspect", 1.0); summaryMetadata.put("PixelSize_um", core.getPixelSizeUm()); summaryMetadata.put("PixelType", (core.getNumberOfComponents() == 1 ? "GRAY" : "RGB") + (8*depth_)); summaryMetadata.put("Slices", numSlices_); summaryMetadata.put("StartTime", MDUtils.getCurrentTime()); summaryMetadata.put("Time", Calendar.getInstance().getTime()); summaryMetadata.put("UserName", System.getProperty("user.name")); summaryMetadata.put("UUID",UUID.randomUUID()); summaryMetadata.put("Width", width_); startTimeMs_ = System.currentTimeMillis(); imageCache.setSummaryMetadata(summaryMetadata); } catch (JSONException ex) { ReportingUtils.showError(ex); } }
private void createDefaultAcqSettings(String name, MMImageCache imageCache) { //if (new File(rootDirectory_).exists()) { // name = generateRootName(name, rootDirectory_); //} String keys[] = new String[summary_.length()]; Iterator<String> it = summary_.keys(); int i = 0; while (it.hasNext()) { keys[0] = it.next(); i++; } try { JSONObject summaryMetadata = new JSONObject(summary_, keys); CMMCore core = MMStudioMainFrame.getInstance().getCore(); summaryMetadata.put("BitDepth", core.getImageBitDepth()); summaryMetadata.put("Channels", numChannels_); setDefaultChannelTags(summaryMetadata); summaryMetadata.put("Comment", comment_); String compName = null; try { compName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { ReportingUtils.showError(e); } if (compName != null) summaryMetadata.put("ComputerName",compName); summaryMetadata.put("Date", new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())); summaryMetadata.put("Depth", core.getBytesPerPixel()); summaryMetadata.put("Frames", numFrames_); summaryMetadata.put("GridColumn", 0); summaryMetadata.put("GridRow", 0); summaryMetadata.put("Height", height_); int ijType = -1; if (depth_ == 1) ijType = ImagePlus.GRAY8; else if (depth_ == 2) ijType = ImagePlus.GRAY16; else if (depth_==8) ijType = 64; else if (depth_ == 4 && core.getNumberOfComponents() == 1) ijType = ImagePlus.GRAY32; else if(depth_ == 4 && core.getNumberOfComponents() == 4) ijType = ImagePlus.COLOR_RGB; summaryMetadata.put("IJType", ijType); summaryMetadata.put("MetadataVersion", 10); summaryMetadata.put("MicroManagerVersion", MMStudioMainFrame.getInstance().getVersion()); summaryMetadata.put("NumComponents", 1); summaryMetadata.put("Positions", numPositions_); summaryMetadata.put("Source", "Micro-Manager"); summaryMetadata.put("PixelAspect", 1.0); summaryMetadata.put("PixelSize_um", core.getPixelSizeUm()); summaryMetadata.put("PixelType", (core.getNumberOfComponents() == 1 ? "GRAY" : "RGB") + (8*depth_)); summaryMetadata.put("Slices", numSlices_); summaryMetadata.put("StartTime", MDUtils.getCurrentTime()); summaryMetadata.put("Time", Calendar.getInstance().getTime()); summaryMetadata.put("UserName", System.getProperty("user.name")); summaryMetadata.put("UUID",UUID.randomUUID()); summaryMetadata.put("Width", width_); startTimeMs_ = System.currentTimeMillis(); imageCache.setSummaryMetadata(summaryMetadata); } catch (JSONException ex) { ReportingUtils.showError(ex); } }
diff --git a/src/main/java/org/freecode/irc/votebot/modules/common/VersionModule.java b/src/main/java/org/freecode/irc/votebot/modules/common/VersionModule.java index f130422..0393924 100644 --- a/src/main/java/org/freecode/irc/votebot/modules/common/VersionModule.java +++ b/src/main/java/org/freecode/irc/votebot/modules/common/VersionModule.java @@ -1,49 +1,49 @@ package org.freecode.irc.votebot.modules.common; import org.freecode.irc.Privmsg; import org.freecode.irc.votebot.api.CommandModule; public class VersionModule extends CommandModule { private String version; private String commitMessage; private String commitAuthor; private String commitTime; @Override public void processMessage(Privmsg privmsg) { String[] params = privmsg.getMessage().split(" "); - if (params.length == 0) { + if (params.length == 1) { privmsg.send("Version: " + version); } else { privmsg.send("Version: " + version + ", last commit \"" + commitMessage + "\" by " + commitAuthor + ", " + commitTime); } } @Override public String getName() { return "version"; } @Override protected String getParameterRegex() { return "(full)?"; } public void setVersion(String version) { this.version = version; } public void setCommitMessage(String commitMessage) { this.commitMessage = commitMessage; } public void setCommitAuthor(String commitAuthor) { this.commitAuthor = commitAuthor; } public void setCommitTime(String commitTime) { this.commitTime = commitTime; } }
true
true
public void processMessage(Privmsg privmsg) { String[] params = privmsg.getMessage().split(" "); if (params.length == 0) { privmsg.send("Version: " + version); } else { privmsg.send("Version: " + version + ", last commit \"" + commitMessage + "\" by " + commitAuthor + ", " + commitTime); } }
public void processMessage(Privmsg privmsg) { String[] params = privmsg.getMessage().split(" "); if (params.length == 1) { privmsg.send("Version: " + version); } else { privmsg.send("Version: " + version + ", last commit \"" + commitMessage + "\" by " + commitAuthor + ", " + commitTime); } }
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/observables/SessionIDObservable.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/observables/SessionIDObservable.java index e1d06ef2a..7b0a9b8b5 100644 --- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/observables/SessionIDObservable.java +++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/observables/SessionIDObservable.java @@ -1,17 +1,17 @@ package de.fu_berlin.inf.dpp.observables; import de.fu_berlin.inf.dpp.util.ObservableValue; public class SessionIDObservable extends ObservableValue<String> { public final static String NOT_IN_SESSION = "NOT_IN_SESSION"; public SessionIDObservable() { - super(null); + super(NOT_IN_SESSION); } public boolean isInASession() { return NOT_IN_SESSION.equals(getValue()); } }
true
true
public SessionIDObservable() { super(null); }
public SessionIDObservable() { super(NOT_IN_SESSION); }
diff --git a/Client/mod_Minechem/net/minecraft/src/mod_Minechem.java b/Client/mod_Minechem/net/minecraft/src/mod_Minechem.java index 923dffd..04d89ac 100644 --- a/Client/mod_Minechem/net/minecraft/src/mod_Minechem.java +++ b/Client/mod_Minechem/net/minecraft/src/mod_Minechem.java @@ -1,450 +1,450 @@ package net.minecraft.src; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.Properties; import net.minecraft.client.Minecraft; import net.minecraft.minechem.*; import net.minecraft.src.forge.ForgeHooks; import net.minecraft.src.forge.IOreHandler; import net.minecraft.src.forge.MinecraftForge; import net.minecraft.src.forge.MinecraftForgeClient; import net.minecraft.src.ic2.api.*; public class mod_Minechem extends BaseMod { @MLProp public static int blockIDMinechem = 253; @MLProp public static int itemIDTestTube = 3001; @MLProp public static int itemIDEmptyTestTube = 3000; @MLProp public static int itemIDTableOfElements = 3002; @MLProp public static int itemIDHangableTableOfElements = 3003; @MLProp public static int itemIDChemistryBook = 3004; @MLProp public static boolean requireIC2Power = false; public static Item itemTesttubeEmpty; public static Item itemTesttube; public static Item leadHelmet; public static Item leadTorso; public static Item leadLeggings; public static Item leadBoots; public static Item tableOfElements; public static Item hangableTableOfElements; public static Item chemistryBook; public static Block blockMinechem; public static Map<ItemStack, Molecule[]> electrolysisRecipes; private static File fileChemicalDictionary = new File(Minecraft.getMinecraftDir(), "/minechem/Chemical Dictionary.txt"); private static Properties chemicalDictionary; private static Random random; @MLProp public static String minechemBlocksTexture = "/minechem/blocktextures.png"; public static String minechemItemsTexture = "/minechem/items.png"; public static void initItemsAndBlocks() { itemTesttubeEmpty = new ItemEmptyTestTube(itemIDEmptyTestTube).setItemName("blah"); itemTesttube = new ItemTestTube(itemIDTestTube).setItemName("minechemTesttube"); leadHelmet = new ItemArmor(2161, EnumArmorMaterial.DIAMOND, ModLoader.AddArmor("leadhelmet"), 0); leadTorso = new ItemArmor(2162, EnumArmorMaterial.DIAMOND, ModLoader.AddArmor("leadtorso"), 1); leadLeggings = new ItemArmor(2163, EnumArmorMaterial.DIAMOND, ModLoader.AddArmor("leadleggings"), 2); leadBoots = new ItemArmor(2164, EnumArmorMaterial.DIAMOND, ModLoader.AddArmor("leadboots"), 3); blockMinechem = new BlockMinechem(blockIDMinechem).setBlockName("blockminechem"); itemTesttubeEmpty.iconIndex = ModLoader.addOverride("/gui/items.png", "/minechem/testtube_empty.png"); tableOfElements = new ItemTableOfElements(itemIDTableOfElements); hangableTableOfElements = new ItemHangableTableOfElements(itemIDHangableTableOfElements); chemistryBook = new ItemChemistryBook(itemIDChemistryBook); leadBoots.setItemName("leadboots"); leadLeggings.setItemName("leadleggings"); leadTorso.setItemName("leadTorso"); leadHelmet.setItemName("leadhelmet"); } public mod_Minechem() { random = new Random(); initItemsAndBlocks(); MinecraftForgeClient.preloadTexture(minechemBlocksTexture); MinecraftForgeClient.preloadTexture(minechemItemsTexture); ModLoader.RegisterBlock(blockMinechem); ModLoader.AddName(itemTesttubeEmpty, "Empty Test Tube"); ModLoader.AddName(itemTesttube, "Test Tube"); ModLoader.AddName(tableOfElements, "Table of Elements"); ModLoader.AddName(hangableTableOfElements, "Hangable Table of Elements"); ModLoader.AddName(chemistryBook, "Chemistry Book"); ModLoader.AddName(leadBoots, "Lead Boots"); ModLoader.AddName(leadLeggings, "Lead Leggings"); ModLoader.AddName(leadTorso, "Lead Chestplate"); ModLoader.AddName(leadHelmet, "Lead Helmet"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityElectrolysis.class, "minechem_tileelectrolysis"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityFusion.class, "minechem_tilefusion"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityBonder.class, "minechem_tilebonder"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityUnbonder.class, "minechem_tileunbonder"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityFission.class, "minechem_tilefission"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityMinechemCrafting.class, "minechem_tilecrafting"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityThermite.class, "minechem_tilethermite"); try{ loadChemicalDictionary(); } catch(Exception e){ e.printStackTrace(); } Item.itemsList[blockIDMinechem] = new ItemMinechem(blockIDMinechem-256, blockMinechem).setItemName("itemminechem"); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.electrolysis), new Object[]{ "RRR", "#-#", "#-#", Character.valueOf('R'), Item.redstone, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.fusion), new Object[]{ "#D#", "#R#", "#D#", Character.valueOf('D'), Item.diamond, Character.valueOf('R'), Molecule.elementByFormula("Th", 1).stack, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.bonder), new Object[]{ "#S#", "#S#", "#S#", Character.valueOf('S'), Item.slimeBall, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.unbonder), new Object[]{ "#S#", "#S#", "#S#", Character.valueOf('S'), Block.tnt, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.fission), new Object[]{ "#D#", "#U#", "#D#", Character.valueOf('D'), Item.diamond, Character.valueOf('U'), Molecule.elementByFormula("U", 1).stack, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.crafting), new Object[]{ "#C#", "#H#", "###", Character.valueOf('H'), Molecule.elementByFormula("H", 1).stack, Character.valueOf('#'), Item.ingotIron, Character.valueOf('C'), Block.workbench }); ModLoader.AddRecipe(new ItemStack(itemTesttubeEmpty, 1), new Object[]{ "#--", "#--", "#--", Character.valueOf('#'), Block.glass }); ModLoader.AddRecipe(new ItemStack(leadBoots, 1), new Object[]{ " ", "# #", "# #", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadLeggings, 1), new Object[]{ "###", "# #", "# #", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadTorso, 1), new Object[]{ "# #", "###", "###", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadHelmet, 1), new Object[]{ "###", "# #", " ", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(tableOfElements, 1), new Object[]{ "PPP", "III", "PPP", Character.valueOf('P'), Item.paper, Character.valueOf('I'), itemTesttubeEmpty }); ModLoader.AddRecipe(new ItemStack(hangableTableOfElements, 1), new Object[]{ "S", "T", Character.valueOf('S'), Item.stick, Character.valueOf('T'), tableOfElements }); ModLoader.AddRecipe(new ItemStack(chemistryBook, 1), new Object[]{ "STS", "SBS", "SSS", Character.valueOf('S'), Item.silk, Character.valueOf('T'), tableOfElements, Character.valueOf('B'), Item.book }); electrolysisRecipes = new HashMap<ItemStack, Molecule[]>(); addElectrolysisRecipe(new ItemStack(Item.bucketWater, 1), new Molecule(8, 2), new Molecule(1, 2) ); addElectrolysisRecipe(new ItemStack(Item.potion, 1, 0), new Molecule(8, 2), new Molecule(1, 2) ); addElectrolysisRecipe(new ItemStack(Item.ingotIron, 1), new Molecule(26, 5), new Molecule(26, 5) ); addElectrolysisRecipe(new ItemStack(Item.ingotGold, 1), new Molecule(79, 9), new Molecule(79, 9) ); addElectrolysisRecipe(new ItemStack(Block.oreIron, 1), Molecule.elementByFormula("Fe", 4), Molecule.elementByFormula("Fe", 4) ); addElectrolysisRecipe(new ItemStack(Block.oreGold, 1), Molecule.elementByFormula("Au", 8), Molecule.elementByFormula("Au", 8) ); addElectrolysisRecipe(new ItemStack(Item.diamond, 1), new Molecule(6, 64), new Molecule(6, 64) ); addElectrolysisRecipe(new ItemStack(Item.coal, 1), new Molecule(6, 1), new Molecule(1, 1) ); addElectrolysisRecipe(new ItemStack(Block.sand, 1), new Molecule(14, 1), new Molecule(8, 2) ); addElectrolysisRecipe(new ItemStack(Item.gunpowder, 1), new Molecule(16, 1), Molecule.moleculeByFormula("KNO3") ); addElectrolysisRecipe(new ItemStack(Item.sugar, 1), new Molecule(0, 21, "C2H8O11"), new Molecule(0, 45, "C12H22O11") ); addElectrolysisRecipe(new ItemStack(Item.lightStoneDust, 1), new Molecule(15, 1), new Molecule(15, 1) ); addElectrolysisRecipe(new ItemStack(Item.redstone, 1), Molecule.moleculeByFormula("Cu2O"), Molecule.moleculeByFormula("Cu2O") ); addElectrolysisRecipe(new ItemStack(Item.clay, 1), new Molecule(14, 1), new Molecule(8, 2) ); addElectrolysisRecipe(new ItemStack(Item.flint, 1), Molecule.moleculeByFormula("SiO2"), Molecule.moleculeByFormula("SiO2") ); addElectrolysisRecipe(new ItemStack(Item.silk, 1), new Molecule(6, 1), new Molecule(8, 1) ); addElectrolysisRecipe(new ItemStack(Item.leather, 1), new Molecule(6, 1), new Molecule(7, 1) ); addElectrolysisRecipe(new ItemStack(Item.blazeRod, 1), new Molecule(23, 2), new Molecule(23, 2) ); addElectrolysisRecipe(new ItemStack(Block.tnt, 1), Molecule.moleculeByFormula("C7H5N3O6"), Molecule.moleculeByFormula("C7H5N3O6") ); addElectrolysisRecipe(new ItemStack(Item.slimeBall, 1), new Molecule(92, 1), new Molecule(6, 1) ); addElectrolysisRecipe(new ItemStack(Item.appleRed, 1), Molecule.moleculeByFormula("C6H8O7"), Molecule.moleculeByFormula("C6H8O7") ); addElectrolysisRecipe(new ItemStack(Item.appleGold, 1), Molecule.moleculeByFormula("C6H8O7"), Molecule.elementByFormula("Au", 42) ); addElectrolysisRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.thermite), Molecule.moleculeByFormula("Fe2O3"), Molecule.moleculeByFormula("Fe2O3") ); addElectrolysisRecipe(new ItemStack(Item.bone, 1), Molecule.elementByFormula("Ca", 16), Molecule.elementByFormula("Fe", 2) ); //Lapis addElectrolysisRecipe(new ItemStack(Item.dyePowder, 1, 4), - Molecule.moleculeByFormula("Na4Ca4Al6Si6O24S2"), + Molecule.moleculeByFormula("Na2Ca6Al6Si6O24S2"), Molecule.moleculeByFormula("Na2Ca6Al6Si6O24S2") ); // Add ore dictionary for electrolysis. ItemStack fuelCan = Items.getItem("filledFuelCan"); if(fuelCan != null) { addElectrolysisRecipe(fuelCan.copy(), Molecule.moleculeByFormula("C3H8"), Molecule.moleculeByFormula("C3H8") ); } MinecraftForge.registerOreHandler(new IOreHandler() { @Override public void registerOre(String oreClass, ItemStack ore) { if(oreClass.equals("oreTin")) { addElectrolysisRecipe(ore.copy(), new Molecule(50, 1), new Molecule(50, 1)); } if(oreClass.equals("oreCopper")) { addElectrolysisRecipe(ore.copy(), new Molecule(29, 1), new Molecule(29, 1)); } if(oreClass.equals("oreUranium")) { addElectrolysisRecipe(ore.copy(), new Molecule(92, 1), new Molecule(92, 1)); } if(oreClass.equals("oreSilver")) { addElectrolysisRecipe(ore.copy(), new Molecule(47, 1), new Molecule(47, 1)); } if(oreClass.equals("oreTungsten")) { addElectrolysisRecipe(ore.copy(), new Molecule(74, 1), new Molecule(74, 1)); } if(oreClass.equals("gemRuby")) { addElectrolysisRecipe(ore.copy(), new Molecule(24, 1), new Molecule(13, 2)); } if(oreClass.equals("gemSapphire")) { addElectrolysisRecipe(ore.copy(), new Molecule(22, 1), new Molecule(13, 2)); } if(oreClass.equals("gemEmerald")) { addElectrolysisRecipe(ore.copy(), new Molecule(4, 1), new Molecule(13, 2)); } if(oreClass.equals("itemDropUranium")) { addElectrolysisRecipe(ore.copy(), new Molecule(92, 4), new Molecule(92, 4)); } } }); ModLoader.SetInGameHook(this, true, true); } @Override public void AddRenderer(Map map) { map.put(EntityTableOfElements.class, new RenderTableOfElements()); } /** * Add a recipe for the Electrolysis Kit. * @param input - three of these itemstacks will be needed to generate output. * @param output1 - the molecule put in output 1. * @param output2 - the molecule put in output 2. */ public void addElectrolysisRecipe(ItemStack input, Molecule output1, Molecule output2) { if(input == null) return; Molecule outputs[] = new Molecule[2]; outputs[0] = output1; outputs[1] = output2; electrolysisRecipes.put(input, outputs); // Also create reversable recipe. ItemStack out = input.copy(); out.stackSize = 3; MinechemCraftingRecipe.addRecipe(out, output1, output2); } public void addElectrolysisRandomRecipe(ItemStack input, ItemStack[] outputs, int[] randoms) { } public void loadChemicalDictionary() throws FileNotFoundException, IOException { chemicalDictionary = new Properties(); chemicalDictionary.load(new FileInputStream( fileChemicalDictionary )); } private static String cachedFormula; private static String cachedChemicalName; public static String findChemicalName(String formula) throws IOException { if(chemicalDictionary == null || chemicalDictionary.isEmpty()) return "???"; else return chemicalDictionary.getProperty(formula, "???"); } @Override public boolean OnTickInGame(float f, Minecraft minecraft) { World world = minecraft.theWorld; EntityPlayer player = minecraft.thePlayer; int currentTries = 0; int currentBlock = 0; int tries = 50; int blocklimit = 10; int radius = 8; int posx = MathHelper.floor_double(player.posX); int posy = MathHelper.floor_double(player.posY); int posz = MathHelper.floor_double(player.posZ); while(currentTries < tries) { currentTries++; int x = posx + (random.nextInt(radius * 2) - radius); int y = posy + (random.nextInt(radius * 2) - radius); int z = posz + (random.nextInt(radius * 2) - radius); if(y > 255) y = 255; if(y < 1) y = 1; if(world.getBlockId(x, y, z) == Block.chest.blockID) { TileEntityChest chest = (TileEntityChest)world.getBlockTileEntity(x, y, z); for(int i = 0; i < chest.getSizeInventory(); i++) { ItemStack stack = chest.getStackInSlot(i); if(stack != null && stack.itemID == itemTesttube.shiftedIndex) { stack.getItem().onUpdate(stack, world, player, 0, false); } } } } return true; } @Override public String getVersion() { return "1.2"; } @Override public void load() { } }
true
true
public mod_Minechem() { random = new Random(); initItemsAndBlocks(); MinecraftForgeClient.preloadTexture(minechemBlocksTexture); MinecraftForgeClient.preloadTexture(minechemItemsTexture); ModLoader.RegisterBlock(blockMinechem); ModLoader.AddName(itemTesttubeEmpty, "Empty Test Tube"); ModLoader.AddName(itemTesttube, "Test Tube"); ModLoader.AddName(tableOfElements, "Table of Elements"); ModLoader.AddName(hangableTableOfElements, "Hangable Table of Elements"); ModLoader.AddName(chemistryBook, "Chemistry Book"); ModLoader.AddName(leadBoots, "Lead Boots"); ModLoader.AddName(leadLeggings, "Lead Leggings"); ModLoader.AddName(leadTorso, "Lead Chestplate"); ModLoader.AddName(leadHelmet, "Lead Helmet"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityElectrolysis.class, "minechem_tileelectrolysis"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityFusion.class, "minechem_tilefusion"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityBonder.class, "minechem_tilebonder"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityUnbonder.class, "minechem_tileunbonder"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityFission.class, "minechem_tilefission"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityMinechemCrafting.class, "minechem_tilecrafting"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityThermite.class, "minechem_tilethermite"); try{ loadChemicalDictionary(); } catch(Exception e){ e.printStackTrace(); } Item.itemsList[blockIDMinechem] = new ItemMinechem(blockIDMinechem-256, blockMinechem).setItemName("itemminechem"); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.electrolysis), new Object[]{ "RRR", "#-#", "#-#", Character.valueOf('R'), Item.redstone, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.fusion), new Object[]{ "#D#", "#R#", "#D#", Character.valueOf('D'), Item.diamond, Character.valueOf('R'), Molecule.elementByFormula("Th", 1).stack, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.bonder), new Object[]{ "#S#", "#S#", "#S#", Character.valueOf('S'), Item.slimeBall, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.unbonder), new Object[]{ "#S#", "#S#", "#S#", Character.valueOf('S'), Block.tnt, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.fission), new Object[]{ "#D#", "#U#", "#D#", Character.valueOf('D'), Item.diamond, Character.valueOf('U'), Molecule.elementByFormula("U", 1).stack, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.crafting), new Object[]{ "#C#", "#H#", "###", Character.valueOf('H'), Molecule.elementByFormula("H", 1).stack, Character.valueOf('#'), Item.ingotIron, Character.valueOf('C'), Block.workbench }); ModLoader.AddRecipe(new ItemStack(itemTesttubeEmpty, 1), new Object[]{ "#--", "#--", "#--", Character.valueOf('#'), Block.glass }); ModLoader.AddRecipe(new ItemStack(leadBoots, 1), new Object[]{ " ", "# #", "# #", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadLeggings, 1), new Object[]{ "###", "# #", "# #", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadTorso, 1), new Object[]{ "# #", "###", "###", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadHelmet, 1), new Object[]{ "###", "# #", " ", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(tableOfElements, 1), new Object[]{ "PPP", "III", "PPP", Character.valueOf('P'), Item.paper, Character.valueOf('I'), itemTesttubeEmpty }); ModLoader.AddRecipe(new ItemStack(hangableTableOfElements, 1), new Object[]{ "S", "T", Character.valueOf('S'), Item.stick, Character.valueOf('T'), tableOfElements }); ModLoader.AddRecipe(new ItemStack(chemistryBook, 1), new Object[]{ "STS", "SBS", "SSS", Character.valueOf('S'), Item.silk, Character.valueOf('T'), tableOfElements, Character.valueOf('B'), Item.book }); electrolysisRecipes = new HashMap<ItemStack, Molecule[]>(); addElectrolysisRecipe(new ItemStack(Item.bucketWater, 1), new Molecule(8, 2), new Molecule(1, 2) ); addElectrolysisRecipe(new ItemStack(Item.potion, 1, 0), new Molecule(8, 2), new Molecule(1, 2) ); addElectrolysisRecipe(new ItemStack(Item.ingotIron, 1), new Molecule(26, 5), new Molecule(26, 5) ); addElectrolysisRecipe(new ItemStack(Item.ingotGold, 1), new Molecule(79, 9), new Molecule(79, 9) ); addElectrolysisRecipe(new ItemStack(Block.oreIron, 1), Molecule.elementByFormula("Fe", 4), Molecule.elementByFormula("Fe", 4) ); addElectrolysisRecipe(new ItemStack(Block.oreGold, 1), Molecule.elementByFormula("Au", 8), Molecule.elementByFormula("Au", 8) ); addElectrolysisRecipe(new ItemStack(Item.diamond, 1), new Molecule(6, 64), new Molecule(6, 64) ); addElectrolysisRecipe(new ItemStack(Item.coal, 1), new Molecule(6, 1), new Molecule(1, 1) ); addElectrolysisRecipe(new ItemStack(Block.sand, 1), new Molecule(14, 1), new Molecule(8, 2) ); addElectrolysisRecipe(new ItemStack(Item.gunpowder, 1), new Molecule(16, 1), Molecule.moleculeByFormula("KNO3") ); addElectrolysisRecipe(new ItemStack(Item.sugar, 1), new Molecule(0, 21, "C2H8O11"), new Molecule(0, 45, "C12H22O11") ); addElectrolysisRecipe(new ItemStack(Item.lightStoneDust, 1), new Molecule(15, 1), new Molecule(15, 1) ); addElectrolysisRecipe(new ItemStack(Item.redstone, 1), Molecule.moleculeByFormula("Cu2O"), Molecule.moleculeByFormula("Cu2O") ); addElectrolysisRecipe(new ItemStack(Item.clay, 1), new Molecule(14, 1), new Molecule(8, 2) ); addElectrolysisRecipe(new ItemStack(Item.flint, 1), Molecule.moleculeByFormula("SiO2"), Molecule.moleculeByFormula("SiO2") ); addElectrolysisRecipe(new ItemStack(Item.silk, 1), new Molecule(6, 1), new Molecule(8, 1) ); addElectrolysisRecipe(new ItemStack(Item.leather, 1), new Molecule(6, 1), new Molecule(7, 1) ); addElectrolysisRecipe(new ItemStack(Item.blazeRod, 1), new Molecule(23, 2), new Molecule(23, 2) ); addElectrolysisRecipe(new ItemStack(Block.tnt, 1), Molecule.moleculeByFormula("C7H5N3O6"), Molecule.moleculeByFormula("C7H5N3O6") ); addElectrolysisRecipe(new ItemStack(Item.slimeBall, 1), new Molecule(92, 1), new Molecule(6, 1) ); addElectrolysisRecipe(new ItemStack(Item.appleRed, 1), Molecule.moleculeByFormula("C6H8O7"), Molecule.moleculeByFormula("C6H8O7") ); addElectrolysisRecipe(new ItemStack(Item.appleGold, 1), Molecule.moleculeByFormula("C6H8O7"), Molecule.elementByFormula("Au", 42) ); addElectrolysisRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.thermite), Molecule.moleculeByFormula("Fe2O3"), Molecule.moleculeByFormula("Fe2O3") ); addElectrolysisRecipe(new ItemStack(Item.bone, 1), Molecule.elementByFormula("Ca", 16), Molecule.elementByFormula("Fe", 2) ); //Lapis addElectrolysisRecipe(new ItemStack(Item.dyePowder, 1, 4), Molecule.moleculeByFormula("Na4Ca4Al6Si6O24S2"), Molecule.moleculeByFormula("Na2Ca6Al6Si6O24S2") ); // Add ore dictionary for electrolysis. ItemStack fuelCan = Items.getItem("filledFuelCan"); if(fuelCan != null) { addElectrolysisRecipe(fuelCan.copy(), Molecule.moleculeByFormula("C3H8"), Molecule.moleculeByFormula("C3H8") ); } MinecraftForge.registerOreHandler(new IOreHandler() { @Override public void registerOre(String oreClass, ItemStack ore) { if(oreClass.equals("oreTin")) { addElectrolysisRecipe(ore.copy(), new Molecule(50, 1), new Molecule(50, 1)); } if(oreClass.equals("oreCopper")) { addElectrolysisRecipe(ore.copy(), new Molecule(29, 1), new Molecule(29, 1)); } if(oreClass.equals("oreUranium")) { addElectrolysisRecipe(ore.copy(), new Molecule(92, 1), new Molecule(92, 1)); } if(oreClass.equals("oreSilver")) { addElectrolysisRecipe(ore.copy(), new Molecule(47, 1), new Molecule(47, 1)); } if(oreClass.equals("oreTungsten")) { addElectrolysisRecipe(ore.copy(), new Molecule(74, 1), new Molecule(74, 1)); } if(oreClass.equals("gemRuby")) { addElectrolysisRecipe(ore.copy(), new Molecule(24, 1), new Molecule(13, 2)); } if(oreClass.equals("gemSapphire")) { addElectrolysisRecipe(ore.copy(), new Molecule(22, 1), new Molecule(13, 2)); } if(oreClass.equals("gemEmerald")) { addElectrolysisRecipe(ore.copy(), new Molecule(4, 1), new Molecule(13, 2)); } if(oreClass.equals("itemDropUranium")) { addElectrolysisRecipe(ore.copy(), new Molecule(92, 4), new Molecule(92, 4)); } } }); ModLoader.SetInGameHook(this, true, true); }
public mod_Minechem() { random = new Random(); initItemsAndBlocks(); MinecraftForgeClient.preloadTexture(minechemBlocksTexture); MinecraftForgeClient.preloadTexture(minechemItemsTexture); ModLoader.RegisterBlock(blockMinechem); ModLoader.AddName(itemTesttubeEmpty, "Empty Test Tube"); ModLoader.AddName(itemTesttube, "Test Tube"); ModLoader.AddName(tableOfElements, "Table of Elements"); ModLoader.AddName(hangableTableOfElements, "Hangable Table of Elements"); ModLoader.AddName(chemistryBook, "Chemistry Book"); ModLoader.AddName(leadBoots, "Lead Boots"); ModLoader.AddName(leadLeggings, "Lead Leggings"); ModLoader.AddName(leadTorso, "Lead Chestplate"); ModLoader.AddName(leadHelmet, "Lead Helmet"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityElectrolysis.class, "minechem_tileelectrolysis"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityFusion.class, "minechem_tilefusion"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityBonder.class, "minechem_tilebonder"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityUnbonder.class, "minechem_tileunbonder"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityFission.class, "minechem_tilefission"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityMinechemCrafting.class, "minechem_tilecrafting"); ModLoader.RegisterTileEntity(net.minecraft.minechem.TileEntityThermite.class, "minechem_tilethermite"); try{ loadChemicalDictionary(); } catch(Exception e){ e.printStackTrace(); } Item.itemsList[blockIDMinechem] = new ItemMinechem(blockIDMinechem-256, blockMinechem).setItemName("itemminechem"); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.electrolysis), new Object[]{ "RRR", "#-#", "#-#", Character.valueOf('R'), Item.redstone, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.fusion), new Object[]{ "#D#", "#R#", "#D#", Character.valueOf('D'), Item.diamond, Character.valueOf('R'), Molecule.elementByFormula("Th", 1).stack, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.bonder), new Object[]{ "#S#", "#S#", "#S#", Character.valueOf('S'), Item.slimeBall, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.unbonder), new Object[]{ "#S#", "#S#", "#S#", Character.valueOf('S'), Block.tnt, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.fission), new Object[]{ "#D#", "#U#", "#D#", Character.valueOf('D'), Item.diamond, Character.valueOf('U'), Molecule.elementByFormula("U", 1).stack, Character.valueOf('#'), Item.ingotIron }); ModLoader.AddRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.crafting), new Object[]{ "#C#", "#H#", "###", Character.valueOf('H'), Molecule.elementByFormula("H", 1).stack, Character.valueOf('#'), Item.ingotIron, Character.valueOf('C'), Block.workbench }); ModLoader.AddRecipe(new ItemStack(itemTesttubeEmpty, 1), new Object[]{ "#--", "#--", "#--", Character.valueOf('#'), Block.glass }); ModLoader.AddRecipe(new ItemStack(leadBoots, 1), new Object[]{ " ", "# #", "# #", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadLeggings, 1), new Object[]{ "###", "# #", "# #", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadTorso, 1), new Object[]{ "# #", "###", "###", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(leadHelmet, 1), new Object[]{ "###", "# #", " ", Character.valueOf('#'), Molecule.elementByFormula("Pb", 1).stack }); ModLoader.AddRecipe(new ItemStack(tableOfElements, 1), new Object[]{ "PPP", "III", "PPP", Character.valueOf('P'), Item.paper, Character.valueOf('I'), itemTesttubeEmpty }); ModLoader.AddRecipe(new ItemStack(hangableTableOfElements, 1), new Object[]{ "S", "T", Character.valueOf('S'), Item.stick, Character.valueOf('T'), tableOfElements }); ModLoader.AddRecipe(new ItemStack(chemistryBook, 1), new Object[]{ "STS", "SBS", "SSS", Character.valueOf('S'), Item.silk, Character.valueOf('T'), tableOfElements, Character.valueOf('B'), Item.book }); electrolysisRecipes = new HashMap<ItemStack, Molecule[]>(); addElectrolysisRecipe(new ItemStack(Item.bucketWater, 1), new Molecule(8, 2), new Molecule(1, 2) ); addElectrolysisRecipe(new ItemStack(Item.potion, 1, 0), new Molecule(8, 2), new Molecule(1, 2) ); addElectrolysisRecipe(new ItemStack(Item.ingotIron, 1), new Molecule(26, 5), new Molecule(26, 5) ); addElectrolysisRecipe(new ItemStack(Item.ingotGold, 1), new Molecule(79, 9), new Molecule(79, 9) ); addElectrolysisRecipe(new ItemStack(Block.oreIron, 1), Molecule.elementByFormula("Fe", 4), Molecule.elementByFormula("Fe", 4) ); addElectrolysisRecipe(new ItemStack(Block.oreGold, 1), Molecule.elementByFormula("Au", 8), Molecule.elementByFormula("Au", 8) ); addElectrolysisRecipe(new ItemStack(Item.diamond, 1), new Molecule(6, 64), new Molecule(6, 64) ); addElectrolysisRecipe(new ItemStack(Item.coal, 1), new Molecule(6, 1), new Molecule(1, 1) ); addElectrolysisRecipe(new ItemStack(Block.sand, 1), new Molecule(14, 1), new Molecule(8, 2) ); addElectrolysisRecipe(new ItemStack(Item.gunpowder, 1), new Molecule(16, 1), Molecule.moleculeByFormula("KNO3") ); addElectrolysisRecipe(new ItemStack(Item.sugar, 1), new Molecule(0, 21, "C2H8O11"), new Molecule(0, 45, "C12H22O11") ); addElectrolysisRecipe(new ItemStack(Item.lightStoneDust, 1), new Molecule(15, 1), new Molecule(15, 1) ); addElectrolysisRecipe(new ItemStack(Item.redstone, 1), Molecule.moleculeByFormula("Cu2O"), Molecule.moleculeByFormula("Cu2O") ); addElectrolysisRecipe(new ItemStack(Item.clay, 1), new Molecule(14, 1), new Molecule(8, 2) ); addElectrolysisRecipe(new ItemStack(Item.flint, 1), Molecule.moleculeByFormula("SiO2"), Molecule.moleculeByFormula("SiO2") ); addElectrolysisRecipe(new ItemStack(Item.silk, 1), new Molecule(6, 1), new Molecule(8, 1) ); addElectrolysisRecipe(new ItemStack(Item.leather, 1), new Molecule(6, 1), new Molecule(7, 1) ); addElectrolysisRecipe(new ItemStack(Item.blazeRod, 1), new Molecule(23, 2), new Molecule(23, 2) ); addElectrolysisRecipe(new ItemStack(Block.tnt, 1), Molecule.moleculeByFormula("C7H5N3O6"), Molecule.moleculeByFormula("C7H5N3O6") ); addElectrolysisRecipe(new ItemStack(Item.slimeBall, 1), new Molecule(92, 1), new Molecule(6, 1) ); addElectrolysisRecipe(new ItemStack(Item.appleRed, 1), Molecule.moleculeByFormula("C6H8O7"), Molecule.moleculeByFormula("C6H8O7") ); addElectrolysisRecipe(new ItemStack(Item.appleGold, 1), Molecule.moleculeByFormula("C6H8O7"), Molecule.elementByFormula("Au", 42) ); addElectrolysisRecipe(new ItemStack(blockMinechem, 1, ItemMinechem.thermite), Molecule.moleculeByFormula("Fe2O3"), Molecule.moleculeByFormula("Fe2O3") ); addElectrolysisRecipe(new ItemStack(Item.bone, 1), Molecule.elementByFormula("Ca", 16), Molecule.elementByFormula("Fe", 2) ); //Lapis addElectrolysisRecipe(new ItemStack(Item.dyePowder, 1, 4), Molecule.moleculeByFormula("Na2Ca6Al6Si6O24S2"), Molecule.moleculeByFormula("Na2Ca6Al6Si6O24S2") ); // Add ore dictionary for electrolysis. ItemStack fuelCan = Items.getItem("filledFuelCan"); if(fuelCan != null) { addElectrolysisRecipe(fuelCan.copy(), Molecule.moleculeByFormula("C3H8"), Molecule.moleculeByFormula("C3H8") ); } MinecraftForge.registerOreHandler(new IOreHandler() { @Override public void registerOre(String oreClass, ItemStack ore) { if(oreClass.equals("oreTin")) { addElectrolysisRecipe(ore.copy(), new Molecule(50, 1), new Molecule(50, 1)); } if(oreClass.equals("oreCopper")) { addElectrolysisRecipe(ore.copy(), new Molecule(29, 1), new Molecule(29, 1)); } if(oreClass.equals("oreUranium")) { addElectrolysisRecipe(ore.copy(), new Molecule(92, 1), new Molecule(92, 1)); } if(oreClass.equals("oreSilver")) { addElectrolysisRecipe(ore.copy(), new Molecule(47, 1), new Molecule(47, 1)); } if(oreClass.equals("oreTungsten")) { addElectrolysisRecipe(ore.copy(), new Molecule(74, 1), new Molecule(74, 1)); } if(oreClass.equals("gemRuby")) { addElectrolysisRecipe(ore.copy(), new Molecule(24, 1), new Molecule(13, 2)); } if(oreClass.equals("gemSapphire")) { addElectrolysisRecipe(ore.copy(), new Molecule(22, 1), new Molecule(13, 2)); } if(oreClass.equals("gemEmerald")) { addElectrolysisRecipe(ore.copy(), new Molecule(4, 1), new Molecule(13, 2)); } if(oreClass.equals("itemDropUranium")) { addElectrolysisRecipe(ore.copy(), new Molecule(92, 4), new Molecule(92, 4)); } } }); ModLoader.SetInGameHook(this, true, true); }
diff --git a/src/main/java/nl/topicus/onderwijs/dashboard/modules/google/GoogleEventService.java b/src/main/java/nl/topicus/onderwijs/dashboard/modules/google/GoogleEventService.java index 59eff03..30cb1ce 100644 --- a/src/main/java/nl/topicus/onderwijs/dashboard/modules/google/GoogleEventService.java +++ b/src/main/java/nl/topicus/onderwijs/dashboard/modules/google/GoogleEventService.java @@ -1,148 +1,148 @@ package nl.topicus.onderwijs.dashboard.modules.google; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import nl.topicus.onderwijs.dashboard.datasources.Events; import nl.topicus.onderwijs.dashboard.datatypes.Event; import nl.topicus.onderwijs.dashboard.modules.Key; import nl.topicus.onderwijs.dashboard.modules.Repository; import nl.topicus.onderwijs.dashboard.modules.Settings; import nl.topicus.onderwijs.dashboard.modules.topicus.Retriever; import nl.topicus.onderwijs.dashboard.persistence.config.ConfigurationRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gdata.client.calendar.CalendarQuery; import com.google.gdata.client.calendar.CalendarService; import com.google.gdata.data.DateTime; import com.google.gdata.data.calendar.CalendarEventEntry; import com.google.gdata.data.calendar.CalendarEventFeed; import com.google.gdata.data.extensions.When; public class GoogleEventService implements Retriever { private static final Logger log = LoggerFactory .getLogger(GoogleEventService.class); private static final Pattern TAG_PATTERN = Pattern.compile("#\\w*"); private List<Event> events = new ArrayList<Event>(); @Override public void onConfigure(Repository repository) { Settings settings = getSettings(); Map<Key, Map<String, ?>> serviceSettings = settings .getServiceSettings(GoogleEventService.class); for (Key key : serviceSettings.keySet()) { repository.addDataSource(key, Events.class, new EventsImpl(key, this)); } } private Settings getSettings() { ConfigurationRepository configurationRepository = new ConfigurationRepository(); Settings settings = configurationRepository .getConfiguration(Settings.class); return settings; } @Override public void refreshData() { try { Settings settings = getSettings(); Map<Key, Map<String, ?>> serviceSettings = settings .getServiceSettings(GoogleEventService.class); List<Event> ret = new ArrayList<Event>(); for (Map.Entry<Key, Map<String, ?>> curSettingEntry : serviceSettings .entrySet()) { Map<String, ?> googleSettingsForProject = curSettingEntry .getValue(); String username = googleSettingsForProject.get("username") .toString(); String password = googleSettingsForProject.get("password") .toString(); String calendarId = googleSettingsForProject.get("calendarId") .toString(); CalendarService service = new CalendarService("Dashboard"); service.setUserCredentials(username, password); URL feedUrl = new URL("http://www.google.com/calendar/feeds/" + calendarId + "/private/full"); CalendarQuery myQuery = new CalendarQuery(feedUrl); Calendar cal = Calendar.getInstance(); myQuery.setMinimumStartTime(dateToGDateTime(cal.getTime())); cal.add(Calendar.MONTH, 1); myQuery.setMaximumStartTime(dateToGDateTime(cal.getTime())); myQuery.setMaxResults(100); myQuery.setIntegerCustomParameter("max-results", 100); // Send the request and receive the response: CalendarEventFeed resultFeed; resultFeed = service.query(myQuery, CalendarEventFeed.class); for (CalendarEventEntry eventEntry : resultFeed.getEntries()) { for (When curTime : eventEntry.getTimes()) { Event event = new Event(); event.setKey(curSettingEntry.getKey()); event.setTitle(eventEntry.getTitle().getPlainText()); // event.setOmschrijving(entry.getPlainTextContent()); event.setDateTime(gDateTimeToDate(curTime .getStartTime())); Matcher m = TAG_PATTERN.matcher(eventEntry .getPlainTextContent()); while (m.find()) { String curTag = m.group(); event.getTags().add(curTag); - if ("major".equals(curTag)) + if ("#major".equals(curTag)) event.setMajor(true); } ret.add(event); } } } events = ret; } catch (Exception e) { log.error("Unable to refresh data from google: {} {}", e.getClass() .getSimpleName(), e.getMessage()); } } private Date gDateTimeToDate(DateTime dateTime) { Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(dateTime.getValue()); if (dateTime.isDateOnly()) { cal.add(Calendar.MILLISECOND, -cal.getTimeZone().getOffset( cal.getTimeInMillis())); } return cal.getTime(); } private DateTime dateToGDateTime(Date date) { Calendar cal = new GregorianCalendar(); cal.setTime(date); cal.add(Calendar.MILLISECOND, cal.getTimeZone().getOffset( cal.getTimeInMillis())); return new DateTime(cal.getTime()); } public List<Event> getEvents(Key key) { List<Event> ret = new ArrayList<Event>(); for (Event curEvent : events) { if (curEvent.getKey().equals(key)) ret.add(curEvent); } return ret; } public static void main(String[] args) { new GoogleEventService().refreshData(); } }
true
true
public void refreshData() { try { Settings settings = getSettings(); Map<Key, Map<String, ?>> serviceSettings = settings .getServiceSettings(GoogleEventService.class); List<Event> ret = new ArrayList<Event>(); for (Map.Entry<Key, Map<String, ?>> curSettingEntry : serviceSettings .entrySet()) { Map<String, ?> googleSettingsForProject = curSettingEntry .getValue(); String username = googleSettingsForProject.get("username") .toString(); String password = googleSettingsForProject.get("password") .toString(); String calendarId = googleSettingsForProject.get("calendarId") .toString(); CalendarService service = new CalendarService("Dashboard"); service.setUserCredentials(username, password); URL feedUrl = new URL("http://www.google.com/calendar/feeds/" + calendarId + "/private/full"); CalendarQuery myQuery = new CalendarQuery(feedUrl); Calendar cal = Calendar.getInstance(); myQuery.setMinimumStartTime(dateToGDateTime(cal.getTime())); cal.add(Calendar.MONTH, 1); myQuery.setMaximumStartTime(dateToGDateTime(cal.getTime())); myQuery.setMaxResults(100); myQuery.setIntegerCustomParameter("max-results", 100); // Send the request and receive the response: CalendarEventFeed resultFeed; resultFeed = service.query(myQuery, CalendarEventFeed.class); for (CalendarEventEntry eventEntry : resultFeed.getEntries()) { for (When curTime : eventEntry.getTimes()) { Event event = new Event(); event.setKey(curSettingEntry.getKey()); event.setTitle(eventEntry.getTitle().getPlainText()); // event.setOmschrijving(entry.getPlainTextContent()); event.setDateTime(gDateTimeToDate(curTime .getStartTime())); Matcher m = TAG_PATTERN.matcher(eventEntry .getPlainTextContent()); while (m.find()) { String curTag = m.group(); event.getTags().add(curTag); if ("major".equals(curTag)) event.setMajor(true); } ret.add(event); } } } events = ret; } catch (Exception e) { log.error("Unable to refresh data from google: {} {}", e.getClass() .getSimpleName(), e.getMessage()); } }
public void refreshData() { try { Settings settings = getSettings(); Map<Key, Map<String, ?>> serviceSettings = settings .getServiceSettings(GoogleEventService.class); List<Event> ret = new ArrayList<Event>(); for (Map.Entry<Key, Map<String, ?>> curSettingEntry : serviceSettings .entrySet()) { Map<String, ?> googleSettingsForProject = curSettingEntry .getValue(); String username = googleSettingsForProject.get("username") .toString(); String password = googleSettingsForProject.get("password") .toString(); String calendarId = googleSettingsForProject.get("calendarId") .toString(); CalendarService service = new CalendarService("Dashboard"); service.setUserCredentials(username, password); URL feedUrl = new URL("http://www.google.com/calendar/feeds/" + calendarId + "/private/full"); CalendarQuery myQuery = new CalendarQuery(feedUrl); Calendar cal = Calendar.getInstance(); myQuery.setMinimumStartTime(dateToGDateTime(cal.getTime())); cal.add(Calendar.MONTH, 1); myQuery.setMaximumStartTime(dateToGDateTime(cal.getTime())); myQuery.setMaxResults(100); myQuery.setIntegerCustomParameter("max-results", 100); // Send the request and receive the response: CalendarEventFeed resultFeed; resultFeed = service.query(myQuery, CalendarEventFeed.class); for (CalendarEventEntry eventEntry : resultFeed.getEntries()) { for (When curTime : eventEntry.getTimes()) { Event event = new Event(); event.setKey(curSettingEntry.getKey()); event.setTitle(eventEntry.getTitle().getPlainText()); // event.setOmschrijving(entry.getPlainTextContent()); event.setDateTime(gDateTimeToDate(curTime .getStartTime())); Matcher m = TAG_PATTERN.matcher(eventEntry .getPlainTextContent()); while (m.find()) { String curTag = m.group(); event.getTags().add(curTag); if ("#major".equals(curTag)) event.setMajor(true); } ret.add(event); } } } events = ret; } catch (Exception e) { log.error("Unable to refresh data from google: {} {}", e.getClass() .getSimpleName(), e.getMessage()); } }
diff --git a/java/simple-cassandra-client/src/main/java/com/example/cassandra/BoundStatementsClient.java b/java/simple-cassandra-client/src/main/java/com/example/cassandra/BoundStatementsClient.java index 03e8b93..7ec3077 100644 --- a/java/simple-cassandra-client/src/main/java/com/example/cassandra/BoundStatementsClient.java +++ b/java/simple-cassandra-client/src/main/java/com/example/cassandra/BoundStatementsClient.java @@ -1,95 +1,93 @@ package com.example.cassandra; import java.util.HashSet; import java.util.Set; import java.util.UUID; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; public class BoundStatementsClient extends SimpleClient { public BoundStatementsClient() { } public void loadData() { PreparedStatement statement = getSession().prepare( "INSERT INTO songs " + "(id, title, album, artist, tags) " + "VALUES (?, ?, ?, ?, ?);"); BoundStatement boundStatement = new BoundStatement(statement); Set<String> tags = new HashSet<String>(); tags.add("jazz"); tags.add("2013"); getSession().execute(boundStatement.bind( UUID.fromString("756716f7-2e54-4715-9f00-91dcbea6cf50"), "La Petite Tonkinoise'", "Bye Bye Blackbird'", "Jos�phine Baker", tags ) ); tags = new HashSet<String>(); tags.add("1996"); - tags.add("1996"); tags.add("birds"); getSession().execute(boundStatement.bind( UUID.fromString("f6071e72-48ec-4fcb-bf3e-379c8a696488"), "Die M�sch", "In Gold'", "Willi Ostermann", tags) ); tags = new HashSet<String>(); - tags.add("1996"); - tags.add("1996"); - tags.add("birds"); + tags.add("1970"); + tags.add("soundtrack"); getSession().execute(boundStatement.bind( UUID.fromString("fbdf82ed-0063-4796-9c7c-a3d4f47b4b25"), "Memo From Turner", "Performance", "Mick Jager", tags) ); // playlists table statement = getSession().prepare( "INSERT INTO playlists " + "(id, song_id, title, album, artist) " + "VALUES (?, ?, ?, ?, ?);"); boundStatement = new BoundStatement(statement); getSession().execute(boundStatement.bind( UUID.fromString("2cc9ccb7-6221-4ccb-8387-f22b6a1b354d"), UUID.fromString("756716f7-2e54-4715-9f00-91dcbea6cf50"), "La Petite Tonkinoise", "Bye Bye Blackbird", "Jos�phine Baker") ); getSession().execute(boundStatement.bind( UUID.fromString("2cc9ccb7-6221-4ccb-8387-f22b6a1b354d"), UUID.fromString("f6071e72-48ec-4fcb-bf3e-379c8a696488"), "Die M�sch", "In Gold", "Willi Ostermann") ); getSession().execute(boundStatement.bind( UUID.fromString("3fd2bedf-a8c8-455a-a462-0cd3a4353c54"), UUID.fromString("fbdf82ed-0063-4796-9c7c-a3d4f47b4b25"), "Memo From Turner", "Performance", "Mick Jager") ); } // See https://issues.apache.org/jira/browse/CASSANDRA-5468 // for now create a new session that explicitly connects with a keypsace specified void workaround() { Session session = getSession(); setSession( session.getCluster().connect("simplex") ); session.shutdown(); } public static void main(String[] args) { BoundStatementsClient client = new BoundStatementsClient(); client.connect("127.0.0.1"); client.createSchema(); client.workaround(); client.loadData(); client.querySchema(); client.updateSchema(); client.dropSchema("simplex"); client.close(); } }
false
true
public void loadData() { PreparedStatement statement = getSession().prepare( "INSERT INTO songs " + "(id, title, album, artist, tags) " + "VALUES (?, ?, ?, ?, ?);"); BoundStatement boundStatement = new BoundStatement(statement); Set<String> tags = new HashSet<String>(); tags.add("jazz"); tags.add("2013"); getSession().execute(boundStatement.bind( UUID.fromString("756716f7-2e54-4715-9f00-91dcbea6cf50"), "La Petite Tonkinoise'", "Bye Bye Blackbird'", "Jos�phine Baker", tags ) ); tags = new HashSet<String>(); tags.add("1996"); tags.add("1996"); tags.add("birds"); getSession().execute(boundStatement.bind( UUID.fromString("f6071e72-48ec-4fcb-bf3e-379c8a696488"), "Die M�sch", "In Gold'", "Willi Ostermann", tags) ); tags = new HashSet<String>(); tags.add("1996"); tags.add("1996"); tags.add("birds"); getSession().execute(boundStatement.bind( UUID.fromString("fbdf82ed-0063-4796-9c7c-a3d4f47b4b25"), "Memo From Turner", "Performance", "Mick Jager", tags) ); // playlists table statement = getSession().prepare( "INSERT INTO playlists " + "(id, song_id, title, album, artist) " + "VALUES (?, ?, ?, ?, ?);"); boundStatement = new BoundStatement(statement); getSession().execute(boundStatement.bind( UUID.fromString("2cc9ccb7-6221-4ccb-8387-f22b6a1b354d"), UUID.fromString("756716f7-2e54-4715-9f00-91dcbea6cf50"), "La Petite Tonkinoise", "Bye Bye Blackbird", "Jos�phine Baker") ); getSession().execute(boundStatement.bind( UUID.fromString("2cc9ccb7-6221-4ccb-8387-f22b6a1b354d"), UUID.fromString("f6071e72-48ec-4fcb-bf3e-379c8a696488"), "Die M�sch", "In Gold", "Willi Ostermann") ); getSession().execute(boundStatement.bind( UUID.fromString("3fd2bedf-a8c8-455a-a462-0cd3a4353c54"), UUID.fromString("fbdf82ed-0063-4796-9c7c-a3d4f47b4b25"), "Memo From Turner", "Performance", "Mick Jager") ); }
public void loadData() { PreparedStatement statement = getSession().prepare( "INSERT INTO songs " + "(id, title, album, artist, tags) " + "VALUES (?, ?, ?, ?, ?);"); BoundStatement boundStatement = new BoundStatement(statement); Set<String> tags = new HashSet<String>(); tags.add("jazz"); tags.add("2013"); getSession().execute(boundStatement.bind( UUID.fromString("756716f7-2e54-4715-9f00-91dcbea6cf50"), "La Petite Tonkinoise'", "Bye Bye Blackbird'", "Jos�phine Baker", tags ) ); tags = new HashSet<String>(); tags.add("1996"); tags.add("birds"); getSession().execute(boundStatement.bind( UUID.fromString("f6071e72-48ec-4fcb-bf3e-379c8a696488"), "Die M�sch", "In Gold'", "Willi Ostermann", tags) ); tags = new HashSet<String>(); tags.add("1970"); tags.add("soundtrack"); getSession().execute(boundStatement.bind( UUID.fromString("fbdf82ed-0063-4796-9c7c-a3d4f47b4b25"), "Memo From Turner", "Performance", "Mick Jager", tags) ); // playlists table statement = getSession().prepare( "INSERT INTO playlists " + "(id, song_id, title, album, artist) " + "VALUES (?, ?, ?, ?, ?);"); boundStatement = new BoundStatement(statement); getSession().execute(boundStatement.bind( UUID.fromString("2cc9ccb7-6221-4ccb-8387-f22b6a1b354d"), UUID.fromString("756716f7-2e54-4715-9f00-91dcbea6cf50"), "La Petite Tonkinoise", "Bye Bye Blackbird", "Jos�phine Baker") ); getSession().execute(boundStatement.bind( UUID.fromString("2cc9ccb7-6221-4ccb-8387-f22b6a1b354d"), UUID.fromString("f6071e72-48ec-4fcb-bf3e-379c8a696488"), "Die M�sch", "In Gold", "Willi Ostermann") ); getSession().execute(boundStatement.bind( UUID.fromString("3fd2bedf-a8c8-455a-a462-0cd3a4353c54"), UUID.fromString("fbdf82ed-0063-4796-9c7c-a3d4f47b4b25"), "Memo From Turner", "Performance", "Mick Jager") ); }
diff --git a/server/src/main/java/io/druid/segment/realtime/RealtimeManager.java b/server/src/main/java/io/druid/segment/realtime/RealtimeManager.java index a49760ab5e..bb2b666db2 100644 --- a/server/src/main/java/io/druid/segment/realtime/RealtimeManager.java +++ b/server/src/main/java/io/druid/segment/realtime/RealtimeManager.java @@ -1,264 +1,264 @@ /* * Druid - a distributed column store. * Copyright (C) 2012, 2013 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.druid.segment.realtime; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.Maps; import com.google.common.io.Closeables; import com.google.inject.Inject; import com.metamx.common.exception.FormattedException; import com.metamx.common.lifecycle.LifecycleStart; import com.metamx.common.lifecycle.LifecycleStop; import com.metamx.emitter.EmittingLogger; import io.druid.data.input.Firehose; import io.druid.data.input.InputRow; import io.druid.query.FinalizeResultsQueryRunner; import io.druid.query.NoopQueryRunner; import io.druid.query.Query; import io.druid.query.QueryRunner; import io.druid.query.QueryRunnerFactory; import io.druid.query.QueryRunnerFactoryConglomerate; import io.druid.query.QuerySegmentWalker; import io.druid.query.QueryToolChest; import io.druid.query.SegmentDescriptor; import io.druid.segment.realtime.plumber.Plumber; import io.druid.segment.realtime.plumber.Sink; import org.joda.time.DateTime; import org.joda.time.Interval; import org.joda.time.Period; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; /** */ public class RealtimeManager implements QuerySegmentWalker { private static final EmittingLogger log = new EmittingLogger(RealtimeManager.class); private final List<FireDepartment> fireDepartments; private final QueryRunnerFactoryConglomerate conglomerate; private final Map<String, FireChief> chiefs; @Inject public RealtimeManager( List<FireDepartment> fireDepartments, QueryRunnerFactoryConglomerate conglomerate ) { this.fireDepartments = fireDepartments; this.conglomerate = conglomerate; this.chiefs = Maps.newHashMap(); } @LifecycleStart public void start() throws IOException { for (final FireDepartment fireDepartment : fireDepartments) { Schema schema = fireDepartment.getSchema(); final FireChief chief = new FireChief(fireDepartment); chiefs.put(schema.getDataSource(), chief); chief.setName(String.format("chief-%s", schema.getDataSource())); chief.setDaemon(true); chief.init(); chief.start(); } } @LifecycleStop public void stop() { for (FireChief chief : chiefs.values()) { Closeables.closeQuietly(chief); } } public FireDepartmentMetrics getMetrics(String datasource) { FireChief chief = chiefs.get(datasource); if (chief == null) { return null; } return chief.getMetrics(); } @Override public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals) { final FireChief chief = chiefs.get(query.getDataSource()); return chief == null ? new NoopQueryRunner<T>() : chief.getQueryRunner(query); } @Override public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs) { final FireChief chief = chiefs.get(query.getDataSource()); return chief == null ? new NoopQueryRunner<T>() : chief.getQueryRunner(query); } private class FireChief extends Thread implements Closeable { private final FireDepartment fireDepartment; private final FireDepartmentMetrics metrics; private volatile FireDepartmentConfig config = null; private volatile Firehose firehose = null; private volatile Plumber plumber = null; private volatile boolean normalExit = true; public FireChief( FireDepartment fireDepartment ) { this.fireDepartment = fireDepartment; this.metrics = fireDepartment.getMetrics(); } public void init() throws IOException { config = fireDepartment.getConfig(); synchronized (this) { try { log.info("Calling the FireDepartment and getting a Firehose."); firehose = fireDepartment.connect(); log.info("Firehose acquired!"); log.info("Someone get us a plumber!"); plumber = fireDepartment.findPlumber(); log.info("We have our plumber!"); } catch (IOException e) { throw Throwables.propagate(e); } } } public FireDepartmentMetrics getMetrics() { return metrics; } @Override public void run() { verifyState(); final Period intermediatePersistPeriod = config.getIntermediatePersistPeriod(); try { plumber.startJob(); long nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); while (firehose.hasMore()) { final InputRow inputRow; try { try { inputRow = firehose.nextRow(); } catch (Exception e) { - log.info(e, "thrown away line due to exception"); - metrics.incrementThrownAway(); + log.debug(e, "thrown away line due to exception, considering unparseable"); + metrics.incrementUnparseable(); continue; } final Sink sink = plumber.getSink(inputRow.getTimestampFromEpoch()); if (sink == null) { metrics.incrementThrownAway(); log.debug("Throwing away event[%s]", inputRow); if (System.currentTimeMillis() > nextFlush) { plumber.persist(firehose.commit()); nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); } continue; } int currCount = sink.add(inputRow); if (currCount >= config.getMaxRowsInMemory() || System.currentTimeMillis() > nextFlush) { plumber.persist(firehose.commit()); nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); } metrics.incrementProcessed(); } catch (FormattedException e) { log.info(e, "unparseable line: %s", e.getDetails()); metrics.incrementUnparseable(); continue; } } } catch (RuntimeException e) { log.makeAlert(e, "RuntimeException aborted realtime processing[%s]", fireDepartment.getSchema().getDataSource()) .emit(); normalExit = false; throw e; } catch (Error e) { log.makeAlert(e, "Exception aborted realtime processing[%s]", fireDepartment.getSchema().getDataSource()) .emit(); normalExit = false; throw e; } finally { Closeables.closeQuietly(firehose); if (normalExit) { plumber.finishJob(); plumber = null; firehose = null; } } } private void verifyState() { Preconditions.checkNotNull(config, "config is null, init() must be called first."); Preconditions.checkNotNull(firehose, "firehose is null, init() must be called first."); Preconditions.checkNotNull(plumber, "plumber is null, init() must be called first."); log.info("FireChief[%s] state ok.", fireDepartment.getSchema().getDataSource()); } public <T> QueryRunner<T> getQueryRunner(Query<T> query) { QueryRunnerFactory<T, Query<T>> factory = conglomerate.findFactory(query); QueryToolChest<T, Query<T>> toolChest = factory.getToolchest(); return new FinalizeResultsQueryRunner<T>(plumber.getQueryRunner(query), toolChest); } public void close() throws IOException { synchronized (this) { if (firehose != null) { normalExit = false; firehose.close(); } } } } }
true
true
public void run() { verifyState(); final Period intermediatePersistPeriod = config.getIntermediatePersistPeriod(); try { plumber.startJob(); long nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); while (firehose.hasMore()) { final InputRow inputRow; try { try { inputRow = firehose.nextRow(); } catch (Exception e) { log.info(e, "thrown away line due to exception"); metrics.incrementThrownAway(); continue; } final Sink sink = plumber.getSink(inputRow.getTimestampFromEpoch()); if (sink == null) { metrics.incrementThrownAway(); log.debug("Throwing away event[%s]", inputRow); if (System.currentTimeMillis() > nextFlush) { plumber.persist(firehose.commit()); nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); } continue; } int currCount = sink.add(inputRow); if (currCount >= config.getMaxRowsInMemory() || System.currentTimeMillis() > nextFlush) { plumber.persist(firehose.commit()); nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); } metrics.incrementProcessed(); } catch (FormattedException e) { log.info(e, "unparseable line: %s", e.getDetails()); metrics.incrementUnparseable(); continue; } } } catch (RuntimeException e) { log.makeAlert(e, "RuntimeException aborted realtime processing[%s]", fireDepartment.getSchema().getDataSource()) .emit(); normalExit = false; throw e; } catch (Error e) { log.makeAlert(e, "Exception aborted realtime processing[%s]", fireDepartment.getSchema().getDataSource()) .emit(); normalExit = false; throw e; } finally { Closeables.closeQuietly(firehose); if (normalExit) { plumber.finishJob(); plumber = null; firehose = null; } } }
public void run() { verifyState(); final Period intermediatePersistPeriod = config.getIntermediatePersistPeriod(); try { plumber.startJob(); long nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); while (firehose.hasMore()) { final InputRow inputRow; try { try { inputRow = firehose.nextRow(); } catch (Exception e) { log.debug(e, "thrown away line due to exception, considering unparseable"); metrics.incrementUnparseable(); continue; } final Sink sink = plumber.getSink(inputRow.getTimestampFromEpoch()); if (sink == null) { metrics.incrementThrownAway(); log.debug("Throwing away event[%s]", inputRow); if (System.currentTimeMillis() > nextFlush) { plumber.persist(firehose.commit()); nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); } continue; } int currCount = sink.add(inputRow); if (currCount >= config.getMaxRowsInMemory() || System.currentTimeMillis() > nextFlush) { plumber.persist(firehose.commit()); nextFlush = new DateTime().plus(intermediatePersistPeriod).getMillis(); } metrics.incrementProcessed(); } catch (FormattedException e) { log.info(e, "unparseable line: %s", e.getDetails()); metrics.incrementUnparseable(); continue; } } } catch (RuntimeException e) { log.makeAlert(e, "RuntimeException aborted realtime processing[%s]", fireDepartment.getSchema().getDataSource()) .emit(); normalExit = false; throw e; } catch (Error e) { log.makeAlert(e, "Exception aborted realtime processing[%s]", fireDepartment.getSchema().getDataSource()) .emit(); normalExit = false; throw e; } finally { Closeables.closeQuietly(firehose); if (normalExit) { plumber.finishJob(); plumber = null; firehose = null; } } }
diff --git a/src/com/android/gallery3d/app/OrientationManager.java b/src/com/android/gallery3d/app/OrientationManager.java index a8ef99ad8..0e033ebe4 100644 --- a/src/com/android/gallery3d/app/OrientationManager.java +++ b/src/com/android/gallery3d/app/OrientationManager.java @@ -1,215 +1,223 @@ /* * Copyright (C) 2012 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.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.provider.Settings; import android.view.OrientationEventListener; import android.view.Surface; import com.android.gallery3d.ui.OrientationSource; import java.util.ArrayList; public class OrientationManager implements OrientationSource { private static final String TAG = "OrientationManager"; public interface Listener { public void onOrientationCompensationChanged(); } // Orientation hysteresis amount used in rounding, in degrees private static final int ORIENTATION_HYSTERESIS = 5; private Activity mActivity; private ArrayList<Listener> mListeners; private MyOrientationEventListener mOrientationListener; // The degrees of the device rotated clockwise from its natural orientation. private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; // If the framework orientation is locked. private boolean mOrientationLocked = false; // The orientation compensation: if the framwork orientation is locked, the // device orientation and the framework orientation may be different, so we // need to rotate the UI. For example, if this value is 90, the UI // components should be rotated 90 degrees counter-clockwise. private int mOrientationCompensation = 0; // This is true if "Settings -> Display -> Rotation Lock" is checked. We // don't allow the orientation to be unlocked if the value is true. private boolean mRotationLockedSetting = false; public OrientationManager(Activity activity) { mActivity = activity; mListeners = new ArrayList<Listener>(); mOrientationListener = new MyOrientationEventListener(activity); } public void resume() { ContentResolver resolver = mActivity.getContentResolver(); mRotationLockedSetting = Settings.System.getInt( resolver, Settings.System.ACCELEROMETER_ROTATION, 0) != 1; mOrientationListener.enable(); } public void pause() { mOrientationListener.disable(); } public void addListener(Listener listener) { synchronized (mListeners) { mListeners.add(listener); } } public void removeListener(Listener listener) { synchronized (mListeners) { mListeners.remove(listener); } } //////////////////////////////////////////////////////////////////////////// // Orientation handling // // We can choose to lock the framework orientation or not. If we lock the // framework orientation, we calculate a a compensation value according to // current device orientation and send it to listeners. If we don't lock // the framework orientation, we always set the compensation value to 0. //////////////////////////////////////////////////////////////////////////// // Lock the framework orientation to the current device orientation public void lockOrientation() { if (mOrientationLocked) return; mOrientationLocked = true; + int displayRotation = getDisplayRotation(); // Display rotation >= 180 means we need to use the REVERSE landscape/portrait - boolean standard = getDisplayRotation() < 180; + boolean standard = displayRotation < 180; if (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(TAG, "lock orientation to landscape"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); } else { + if (displayRotation == 90 || displayRotation == 270) { + // If displayRotation = 90 or 270 then we are on a landscape + // device. On landscape devices, portrait is a 90 degree + // clockwise rotation from landscape, so we need + // to flip which portrait we pick as display rotation is counter clockwise + standard = !standard; + } Log.d(TAG, "lock orientation to portrait"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); } updateCompensation(); } // Unlock the framework orientation, so it can change when the device // rotates. public void unlockOrientation() { if (!mOrientationLocked) return; if (mRotationLockedSetting) return; mOrientationLocked = false; Log.d(TAG, "unlock orientation"); mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); disableCompensation(); } // Calculate the compensation value and send it to listeners. private void updateCompensation() { if (mOrientation == OrientationEventListener.ORIENTATION_UNKNOWN) { return; } int orientationCompensation = (mOrientation + getDisplayRotation(mActivity)) % 360; if (mOrientationCompensation != orientationCompensation) { mOrientationCompensation = orientationCompensation; notifyListeners(); } } // Make the compensation value 0 and send it to listeners. private void disableCompensation() { if (mOrientationCompensation != 0) { mOrientationCompensation = 0; notifyListeners(); } } private void notifyListeners() { synchronized (mListeners) { for (int i = 0, n = mListeners.size(); i < n; i++) { mListeners.get(i).onOrientationCompensationChanged(); } } } // This listens to the device orientation, so we can update the compensation. private class MyOrientationEventListener extends OrientationEventListener { public MyOrientationEventListener(Context context) { super(context); } @Override public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user first orient // the camera then point the camera to floor or sky, we still have // the correct orientation. if (orientation == ORIENTATION_UNKNOWN) return; mOrientation = roundOrientation(orientation, mOrientation); // If the framework orientation is locked, we update the // compensation value and notify the listeners. if (mOrientationLocked) updateCompensation(); } } @Override public int getDisplayRotation() { return getDisplayRotation(mActivity); } @Override public int getCompensation() { return mOrientationCompensation; } private static int roundOrientation(int orientation, int orientationHistory) { boolean changeOrientation = false; if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) { changeOrientation = true; } else { int dist = Math.abs(orientation - orientationHistory); dist = Math.min(dist, 360 - dist); changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS); } if (changeOrientation) { return ((orientation + 45) / 90 * 90) % 360; } return orientationHistory; } private static int getDisplayRotation(Activity activity) { int rotation = activity.getWindowManager().getDefaultDisplay() .getRotation(); switch (rotation) { case Surface.ROTATION_0: return 0; case Surface.ROTATION_90: return 90; case Surface.ROTATION_180: return 180; case Surface.ROTATION_270: return 270; } return 0; } }
false
true
public void lockOrientation() { if (mOrientationLocked) return; mOrientationLocked = true; // Display rotation >= 180 means we need to use the REVERSE landscape/portrait boolean standard = getDisplayRotation() < 180; if (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(TAG, "lock orientation to landscape"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); } else { Log.d(TAG, "lock orientation to portrait"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); } updateCompensation(); }
public void lockOrientation() { if (mOrientationLocked) return; mOrientationLocked = true; int displayRotation = getDisplayRotation(); // Display rotation >= 180 means we need to use the REVERSE landscape/portrait boolean standard = displayRotation < 180; if (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(TAG, "lock orientation to landscape"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); } else { if (displayRotation == 90 || displayRotation == 270) { // If displayRotation = 90 or 270 then we are on a landscape // device. On landscape devices, portrait is a 90 degree // clockwise rotation from landscape, so we need // to flip which portrait we pick as display rotation is counter clockwise standard = !standard; } Log.d(TAG, "lock orientation to portrait"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); } updateCompensation(); }
diff --git a/src/main/java/uk/co/revthefox/foxbot/Utils.java b/src/main/java/uk/co/revthefox/foxbot/Utils.java index f032e1a..f00270e 100644 --- a/src/main/java/uk/co/revthefox/foxbot/Utils.java +++ b/src/main/java/uk/co/revthefox/foxbot/Utils.java @@ -1,89 +1,89 @@ package uk.co.revthefox.foxbot; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.Response; import org.pircbotx.Colors; import org.pircbotx.User; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utils { private FoxBot foxbot; private String urlPattern = ".*((https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]).*"; private Pattern patt = Pattern.compile(urlPattern); public Utils(FoxBot foxbot) { this.foxbot = foxbot; } public String parseChatUrl(String stringToParse, User sender) { AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); Matcher matcher; Future<Response> future; Response response; matcher = patt.matcher(stringToParse); if (!matcher.matches()) { return ""; } stringToParse = matcher.group(1); try { - future = asyncHttpClient.prepareGet(stringToParse).execute(); + future = asyncHttpClient.prepareGet(stringToParse).setFollowRedirects(true).execute(); response = future.get(); if (!response.getStatusText().contains("OK") && !response.getStatusText().contains("Moved Permanently")) { return String.format("(%s's URL) %sError: %s%s %s ", sender.getNick(), Colors.RED, Colors.NORMAL,response.getStatusCode(), response.getStatusText()); } } catch (IOException ex) { ex.printStackTrace(); return ""; } catch (InterruptedException ex) { ex.printStackTrace(); return ""; } catch (ExecutionException ex) { System.out.println("That last URL appeared to be invalid..."); return ""; } try { stringToParse = response.getResponseBody(); } catch (IOException ex) { ex.printStackTrace(); } Pattern titlePattern = Pattern.compile(".*?<title.*?>(.*)</title>.*?", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); Matcher titleMatcher = titlePattern.matcher(stringToParse); while (titleMatcher.find()) { stringToParse = titleMatcher.group(1); } if (stringToParse.length() > 100) { return String.format("(%s's URL) Content too big. This would have caused me to flood out.", sender.getNick()); } return String.format("(%s's URL) %sTitle: %s%s %sContent type: %s%s", sender.getNick(), Colors.GREEN, Colors.NORMAL, stringToParse.replace("&#039;", "'"), Colors.GREEN, Colors.NORMAL, response.getContentType().replaceAll("(;.*)", "")); } }
true
true
public String parseChatUrl(String stringToParse, User sender) { AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); Matcher matcher; Future<Response> future; Response response; matcher = patt.matcher(stringToParse); if (!matcher.matches()) { return ""; } stringToParse = matcher.group(1); try { future = asyncHttpClient.prepareGet(stringToParse).execute(); response = future.get(); if (!response.getStatusText().contains("OK") && !response.getStatusText().contains("Moved Permanently")) { return String.format("(%s's URL) %sError: %s%s %s ", sender.getNick(), Colors.RED, Colors.NORMAL,response.getStatusCode(), response.getStatusText()); } } catch (IOException ex) { ex.printStackTrace(); return ""; } catch (InterruptedException ex) { ex.printStackTrace(); return ""; } catch (ExecutionException ex) { System.out.println("That last URL appeared to be invalid..."); return ""; } try { stringToParse = response.getResponseBody(); } catch (IOException ex) { ex.printStackTrace(); } Pattern titlePattern = Pattern.compile(".*?<title.*?>(.*)</title>.*?", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); Matcher titleMatcher = titlePattern.matcher(stringToParse); while (titleMatcher.find()) { stringToParse = titleMatcher.group(1); } if (stringToParse.length() > 100) { return String.format("(%s's URL) Content too big. This would have caused me to flood out.", sender.getNick()); } return String.format("(%s's URL) %sTitle: %s%s %sContent type: %s%s", sender.getNick(), Colors.GREEN, Colors.NORMAL, stringToParse.replace("&#039;", "'"), Colors.GREEN, Colors.NORMAL, response.getContentType().replaceAll("(;.*)", "")); }
public String parseChatUrl(String stringToParse, User sender) { AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); Matcher matcher; Future<Response> future; Response response; matcher = patt.matcher(stringToParse); if (!matcher.matches()) { return ""; } stringToParse = matcher.group(1); try { future = asyncHttpClient.prepareGet(stringToParse).setFollowRedirects(true).execute(); response = future.get(); if (!response.getStatusText().contains("OK") && !response.getStatusText().contains("Moved Permanently")) { return String.format("(%s's URL) %sError: %s%s %s ", sender.getNick(), Colors.RED, Colors.NORMAL,response.getStatusCode(), response.getStatusText()); } } catch (IOException ex) { ex.printStackTrace(); return ""; } catch (InterruptedException ex) { ex.printStackTrace(); return ""; } catch (ExecutionException ex) { System.out.println("That last URL appeared to be invalid..."); return ""; } try { stringToParse = response.getResponseBody(); } catch (IOException ex) { ex.printStackTrace(); } Pattern titlePattern = Pattern.compile(".*?<title.*?>(.*)</title>.*?", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); Matcher titleMatcher = titlePattern.matcher(stringToParse); while (titleMatcher.find()) { stringToParse = titleMatcher.group(1); } if (stringToParse.length() > 100) { return String.format("(%s's URL) Content too big. This would have caused me to flood out.", sender.getNick()); } return String.format("(%s's URL) %sTitle: %s%s %sContent type: %s%s", sender.getNick(), Colors.GREEN, Colors.NORMAL, stringToParse.replace("&#039;", "'"), Colors.GREEN, Colors.NORMAL, response.getContentType().replaceAll("(;.*)", "")); }
diff --git a/splat/src/main/uk/ac/starlink/splat/data/TableColumnChooser.java b/splat/src/main/uk/ac/starlink/splat/data/TableColumnChooser.java index 15732f6ce..b3fbf2845 100644 --- a/splat/src/main/uk/ac/starlink/splat/data/TableColumnChooser.java +++ b/splat/src/main/uk/ac/starlink/splat/data/TableColumnChooser.java @@ -1,162 +1,163 @@ /* * Copyright (C) 2004 Central Laboratory of the Research Councils * * History: * 27-FEB-2004 (Peter W. Draper): * Original version. */ package uk.ac.starlink.splat.data; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * Centralising class for making the choices about what are the coordinates, * data values and data errors columns in tables. * <p> * The choices are controlled by a series of regular expressions that can be * extended as needed. * * @author Peter W. Draper * @version $Id$ */ public class TableColumnChooser { /** The instance of this class */ private static TableColumnChooser instance = null; /** Patterns for the column containing the coordinates */ private static ArrayList coordPatterns = null; /** Patterns for the column containing the data values */ private static ArrayList dataPatterns = null; /** Patterns for the column containing the data errors */ private static ArrayList errorPatterns = null; /** Flags used for any pattern matching */ private static final int flags = Pattern.CASE_INSENSITIVE; /** Singleton class */ private TableColumnChooser() { // Default patterns... Could try matching to things like data // source. Any joy from UCDs and IVOA work? coordPatterns = new ArrayList(); addCoordPattern( "wavelength.*" ); addCoordPattern( "freq.*" ); addCoordPattern( "velo.*" ); addCoordPattern( "redshift.*" ); addCoordPattern( "pos.*" ); addCoordPattern( "x*." ); dataPatterns = new ArrayList(); addDataPattern( "flux.*" ); addDataPattern( "inten.*" ); addDataPattern( "temp.*" ); addDataPattern( "mag.*" ); addDataPattern( "energy.*" ); addDataPattern( "y.*" ); errorPatterns = new ArrayList(); addErrorPattern( "error.*" ); + addErrorPattern( "sigma.*" ); addErrorPattern( "stddev.*" ); } /** * Get reference to the single instance of this class. */ public static TableColumnChooser getInstance() { if ( instance == null ) { instance = new TableColumnChooser(); } return instance; } /** * Return the index of the String that most matches a coordinate. * Returns -1 if no match is located. */ public int getCoordMatch( String[] names ) { return match( coordPatterns, names ); } /** * Return the index of the String that most matches a data value. * Returns -1 if no match is located. */ public int getDataMatch( String[] names ) { return match( dataPatterns, names ); } /** * Return the index of the String that most matches a data error. * Returns -1 if no match is located. */ public int getErrorMatch( String[] names ) { return match( errorPatterns, names ); } /** * Compares the Patterns stored in list against the strings stored in * names and returns the index of the first match in names, otherwise * returns -1. */ protected int match( ArrayList list, String[] names ) { int size = list.size(); Pattern p = null; Matcher m = null; for ( int i = 0; i < size; i++ ) { p = (Pattern) list.get( i ); for ( int j = 0; j < names.length; j++ ) { if ( p.matcher( names[j] ).matches() ) { return j; } } } return -1; } /** Add a new regular expression pattern for matching coordinates.*/ public void addCoordPattern( String pattern ) { coordPatterns.add( Pattern.compile( pattern, flags ) ); } /** Insert a new regular expression pattern for matching coordinates.*/ public void addCoordPattern( String pattern, int index ) { coordPatterns.add( index, Pattern.compile( pattern, flags ) ); } /** Add a new regular expression pattern for matching data values.*/ public void addDataPattern( String pattern ) { dataPatterns.add( Pattern.compile( pattern, flags ) ); } /** Insert a new regular expression pattern for matching data values.*/ public void addDataPattern( String pattern, int index ) { dataPatterns.add( index, Pattern.compile( pattern, flags ) ); } /** Add a new regular expression pattern for matching data errors.*/ public void addErrorPattern( String pattern ) { errorPatterns.add( Pattern.compile( pattern, flags ) ); } /** Insert a new regular expression pattern for matching data errors.*/ public void addErrorPattern( String pattern, int index ) { errorPatterns.add( index, Pattern.compile( pattern, flags ) ); } }
true
true
private TableColumnChooser() { // Default patterns... Could try matching to things like data // source. Any joy from UCDs and IVOA work? coordPatterns = new ArrayList(); addCoordPattern( "wavelength.*" ); addCoordPattern( "freq.*" ); addCoordPattern( "velo.*" ); addCoordPattern( "redshift.*" ); addCoordPattern( "pos.*" ); addCoordPattern( "x*." ); dataPatterns = new ArrayList(); addDataPattern( "flux.*" ); addDataPattern( "inten.*" ); addDataPattern( "temp.*" ); addDataPattern( "mag.*" ); addDataPattern( "energy.*" ); addDataPattern( "y.*" ); errorPatterns = new ArrayList(); addErrorPattern( "error.*" ); addErrorPattern( "stddev.*" ); }
private TableColumnChooser() { // Default patterns... Could try matching to things like data // source. Any joy from UCDs and IVOA work? coordPatterns = new ArrayList(); addCoordPattern( "wavelength.*" ); addCoordPattern( "freq.*" ); addCoordPattern( "velo.*" ); addCoordPattern( "redshift.*" ); addCoordPattern( "pos.*" ); addCoordPattern( "x*." ); dataPatterns = new ArrayList(); addDataPattern( "flux.*" ); addDataPattern( "inten.*" ); addDataPattern( "temp.*" ); addDataPattern( "mag.*" ); addDataPattern( "energy.*" ); addDataPattern( "y.*" ); errorPatterns = new ArrayList(); addErrorPattern( "error.*" ); addErrorPattern( "sigma.*" ); addErrorPattern( "stddev.*" ); }
diff --git a/main/src/main/java/org/geoserver/security/GeoserverUserDao.java b/main/src/main/java/org/geoserver/security/GeoserverUserDao.java index 460132835..ad8d846ef 100644 --- a/main/src/main/java/org/geoserver/security/GeoserverUserDao.java +++ b/main/src/main/java/org/geoserver/security/GeoserverUserDao.java @@ -1,299 +1,299 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.geoserver.security; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.userdetails.User; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UserDetailsService; import org.acegisecurity.userdetails.UsernameNotFoundException; import org.acegisecurity.userdetails.memory.UserAttribute; import org.acegisecurity.userdetails.memory.UserAttributeEditor; import org.geoserver.config.GeoServer; import org.geoserver.config.GeoServerInfo; import org.geoserver.platform.GeoServerExtensions; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.vfny.geoserver.global.GeoserverDataDirectory; /** * A simple DAO reading/writing the user's property files * * @author Andrea Aime - OpenGeo * */ public class GeoserverUserDao implements UserDetailsService { /** logger */ static Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.geoserver.security"); TreeMap<String, User> userMap; PropertyFileWatcher userDefinitionsFile; File securityDir; /** * Returns the {@link GeoserverUserDao} instance registered in the GeoServer Spring context */ public static GeoserverUserDao get() { return GeoServerExtensions.bean(GeoserverUserDao.class); } public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { checkUserMap(); UserDetails user = userMap.get(username); if (user == null) throw new UsernameNotFoundException("Could not find user: " + username); return user; } /** * Either loads the default property file on the first access, or reloads it if it has been * modified since last access. * * @throws DataAccessResourceFailureException */ void checkUserMap() throws DataAccessResourceFailureException { InputStream is = null; OutputStream os = null; - if ((userMap == null) || ((userDefinitionsFile != null) && userDefinitionsFile.isStale())) { + if ((userMap == null) || userDefinitionsFile == null || userDefinitionsFile.isStale()) { try { if (userDefinitionsFile == null) { securityDir = GeoserverDataDirectory.findCreateConfigDir("security"); File propFile = new File(securityDir, "users.properties"); if (!propFile.exists()) { // we're probably dealing with an old data dir, create // the file without // changing the username and password if possible Properties p = new Properties(); GeoServerInfo global = GeoServerExtensions.bean(GeoServer.class).getGlobal(); if ((global != null) && (global.getAdminUsername() != null) && !global.getAdminUsername().trim().equals("")) { p.put(global.getAdminUsername(), global.getAdminPassword() + ",ROLE_ADMINISTRATOR"); } else { p.put("admin", "geoserver,ROLE_ADMINISTRATOR"); } os = new FileOutputStream(propFile); p.store(os, "Format: name=password,ROLE1,...,ROLEN"); os.close(); // setup a sample service.properties File serviceFile = new File(securityDir, "service.properties"); os = new FileOutputStream(serviceFile); is = GeoserverUserDao.class .getResourceAsStream("serviceTemplate.properties"); byte[] buffer = new byte[1024]; int count = 0; while ((count = is.read(buffer)) > 0) { os.write(buffer, 0, count); } } userDefinitionsFile = new PropertyFileWatcher(propFile); } userMap = loadUsersFromProperties(userDefinitionsFile.getProperties()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "An error occurred loading user definitions", e); } finally { if (is != null) try { is.close(); } catch (IOException ei) { /* nothing to do */ } if (os != null) try { os.close(); } catch (IOException eo) { /* nothing to do */ } } } } /** * Get the list of roles currently known by users (there's guarantee the well known * ROLE_ADMINISTRATOR will be part of the lot) */ public List<String> getRoles() { checkUserMap(); Set<String> roles = new TreeSet<String>(); roles.add("ROLE_ADMINISTRATOR"); for (User user : getUsers()) { for (GrantedAuthority ga : user.getAuthorities()) { roles.add(ga.getAuthority()); } } return new ArrayList<String>(roles); } /** * Returns the list of users. To be used for UI editing of users, it's a live map * * @return */ public List<User> getUsers() { checkUserMap(); return new ArrayList(userMap.values()); } /** * Adds a user in the user map * @param user */ public void putUser(User user) { checkUserMap(); if(userMap.containsKey(user.getUsername())) throw new IllegalArgumentException("The user " + user.getUsername() + " already exists"); else userMap.put(user.getUsername(), user); } /** * Updates a user in the user map * @param user */ public void setUser(User user) { checkUserMap(); if(userMap.containsKey(user.getUsername())) userMap.put(user.getUsername(), user); else throw new IllegalArgumentException("The user " + user.getUsername() + " already exists"); } /** * Removes the specified user from the users list * @param username * @return */ public boolean removeUser(String username) { checkUserMap(); return userMap.remove(username) != null; } /** * Writes down the current users map to file system */ public void storeUsers() throws IOException { FileOutputStream os = null; try { // turn back the users into a users map Properties p = storeUsersToProperties(userMap); // write out to the data dir File propFile = new File(securityDir, "users.properties"); os = new FileOutputStream(propFile); p.store(os, null); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else throw (IOException) new IOException( "Could not write updated users list to file system").initCause(e); } finally { if (os != null) os.close(); } } /** * Force the dao to reload its definitions from the file */ public void reload() { userDefinitionsFile = null; } /** * Loads the user from property file into the users map * * @param users * @param props */ TreeMap<String, User> loadUsersFromProperties(Properties props) { TreeMap<String, User> users = new TreeMap<String, User>(); UserAttributeEditor configAttribEd = new UserAttributeEditor(); for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { // the attribute editors parses the list of strings into password, username and enabled // flag String username = (String) iter.next(); configAttribEd.setAsText(props.getProperty(username)); // if the parsing succeeded turn that into a user object UserAttribute attr = (UserAttribute) configAttribEd.getValue(); if (attr != null) { User user = createUserObject(username, attr.getPassword(), attr.isEnabled(), attr.getAuthorities()); users.put(username, user); } } return users; } protected User createUserObject(String username,String password, boolean isEnabled,GrantedAuthority[] authorities) { return new User(username, password, isEnabled, true, true, true, authorities); } /** * Stores the provided user map into a properties object * * @param userMap * @return */ Properties storeUsersToProperties(Map<String, User> userMap) { Properties p = new Properties(); for (User user : userMap.values()) { p.setProperty(user.getUsername(), serializeUser(user)); } return p; } /** * Turns the users password, granted authorities and enabled state into a property file value * * @param user * @return */ String serializeUser(User user) { StringBuffer sb = new StringBuffer(); sb.append(user.getPassword()); sb.append(","); for (GrantedAuthority ga : user.getAuthorities()) { sb.append(ga.getAuthority()); sb.append(","); } sb.append(user.isEnabled() ? "enabled" : "disabled"); return sb.toString(); } }
true
true
void checkUserMap() throws DataAccessResourceFailureException { InputStream is = null; OutputStream os = null; if ((userMap == null) || ((userDefinitionsFile != null) && userDefinitionsFile.isStale())) { try { if (userDefinitionsFile == null) { securityDir = GeoserverDataDirectory.findCreateConfigDir("security"); File propFile = new File(securityDir, "users.properties"); if (!propFile.exists()) { // we're probably dealing with an old data dir, create // the file without // changing the username and password if possible Properties p = new Properties(); GeoServerInfo global = GeoServerExtensions.bean(GeoServer.class).getGlobal(); if ((global != null) && (global.getAdminUsername() != null) && !global.getAdminUsername().trim().equals("")) { p.put(global.getAdminUsername(), global.getAdminPassword() + ",ROLE_ADMINISTRATOR"); } else { p.put("admin", "geoserver,ROLE_ADMINISTRATOR"); } os = new FileOutputStream(propFile); p.store(os, "Format: name=password,ROLE1,...,ROLEN"); os.close(); // setup a sample service.properties File serviceFile = new File(securityDir, "service.properties"); os = new FileOutputStream(serviceFile); is = GeoserverUserDao.class .getResourceAsStream("serviceTemplate.properties"); byte[] buffer = new byte[1024]; int count = 0; while ((count = is.read(buffer)) > 0) { os.write(buffer, 0, count); } } userDefinitionsFile = new PropertyFileWatcher(propFile); } userMap = loadUsersFromProperties(userDefinitionsFile.getProperties()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "An error occurred loading user definitions", e); } finally { if (is != null) try { is.close(); } catch (IOException ei) { /* nothing to do */ } if (os != null) try { os.close(); } catch (IOException eo) { /* nothing to do */ } } } }
void checkUserMap() throws DataAccessResourceFailureException { InputStream is = null; OutputStream os = null; if ((userMap == null) || userDefinitionsFile == null || userDefinitionsFile.isStale()) { try { if (userDefinitionsFile == null) { securityDir = GeoserverDataDirectory.findCreateConfigDir("security"); File propFile = new File(securityDir, "users.properties"); if (!propFile.exists()) { // we're probably dealing with an old data dir, create // the file without // changing the username and password if possible Properties p = new Properties(); GeoServerInfo global = GeoServerExtensions.bean(GeoServer.class).getGlobal(); if ((global != null) && (global.getAdminUsername() != null) && !global.getAdminUsername().trim().equals("")) { p.put(global.getAdminUsername(), global.getAdminPassword() + ",ROLE_ADMINISTRATOR"); } else { p.put("admin", "geoserver,ROLE_ADMINISTRATOR"); } os = new FileOutputStream(propFile); p.store(os, "Format: name=password,ROLE1,...,ROLEN"); os.close(); // setup a sample service.properties File serviceFile = new File(securityDir, "service.properties"); os = new FileOutputStream(serviceFile); is = GeoserverUserDao.class .getResourceAsStream("serviceTemplate.properties"); byte[] buffer = new byte[1024]; int count = 0; while ((count = is.read(buffer)) > 0) { os.write(buffer, 0, count); } } userDefinitionsFile = new PropertyFileWatcher(propFile); } userMap = loadUsersFromProperties(userDefinitionsFile.getProperties()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "An error occurred loading user definitions", e); } finally { if (is != null) try { is.close(); } catch (IOException ei) { /* nothing to do */ } if (os != null) try { os.close(); } catch (IOException eo) { /* nothing to do */ } } } }
diff --git a/goobi1.9/src/de/sub/goobi/export/download/ExportMets.java b/goobi1.9/src/de/sub/goobi/export/download/ExportMets.java index 5c1d3c6ed..ca6c9d191 100644 --- a/goobi1.9/src/de/sub/goobi/export/download/ExportMets.java +++ b/goobi1.9/src/de/sub/goobi/export/download/ExportMets.java @@ -1,332 +1,333 @@ package de.sub.goobi.export.download; /** * This file is part of the Goobi Application - a Workflow tool for the support of mass digitization. * * Visit the websites for more information. * - http://www.goobi.org * - http://launchpad.net/goobi-production * - http://gdz.sub.uni-goettingen.de * - http://www.intranda.com * - http://digiverso.com * * 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 * * Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions * of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to * link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and * conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this * library, you may extend this exception to your version of the library, but you are not obliged to do so. If you do not wish to do so, delete this * exception statement from your version. */ import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import ugh.dl.ContentFile; import ugh.dl.DigitalDocument; import ugh.dl.DocStruct; import ugh.dl.Fileformat; import ugh.dl.Prefs; import ugh.dl.VirtualFileGroup; import ugh.exceptions.DocStructHasNoTypeException; import ugh.exceptions.MetadataTypeNotAllowedException; import ugh.exceptions.PreferencesException; import ugh.exceptions.ReadException; import ugh.exceptions.TypeNotAllowedForParentException; import ugh.exceptions.WriteException; import ugh.fileformats.mets.MetsModsImportExport; import de.sub.goobi.beans.Benutzer; import de.sub.goobi.beans.ProjectFileGroup; import de.sub.goobi.beans.Prozess; import de.sub.goobi.config.ConfigProjects; import de.sub.goobi.export.dms.ExportDms_CorrectRusdml; import de.sub.goobi.forms.LoginForm; import de.sub.goobi.helper.Helper; import de.sub.goobi.helper.VariableReplacer; import de.sub.goobi.helper.exceptions.DAOException; import de.sub.goobi.helper.exceptions.ExportFileException; import de.sub.goobi.helper.exceptions.InvalidImagesException; import de.sub.goobi.helper.exceptions.SwapException; import de.sub.goobi.helper.exceptions.UghHelperException; import de.sub.goobi.metadaten.MetadatenImagesHelper; public class ExportMets { protected Helper help = new Helper(); protected Prefs myPrefs; protected static final Logger myLogger = Logger.getLogger(ExportMets.class); /** * DMS-Export in das Benutzer-Homeverzeichnis * * @param myProzess * @throws InterruptedException * @throws IOException * @throws DAOException * @throws SwapException * @throws ReadException * @throws UghHelperException * @throws ExportFileException * @throws MetadataTypeNotAllowedException * @throws WriteException * @throws PreferencesException * @throws DocStructHasNoTypeException * @throws TypeNotAllowedForParentException */ public boolean startExport(Prozess myProzess) throws IOException, InterruptedException, DocStructHasNoTypeException, PreferencesException, WriteException, MetadataTypeNotAllowedException, ExportFileException, UghHelperException, ReadException, SwapException, DAOException, TypeNotAllowedForParentException { LoginForm login = (LoginForm) Helper.getManagedBeanValue("#{LoginForm}"); String benutzerHome = ""; if (login != null) { benutzerHome = login.getMyBenutzer().getHomeDir(); } return startExport(myProzess, benutzerHome); } /** * DMS-Export an eine gewünschte Stelle * * @param myProzess * @param zielVerzeichnis * @throws InterruptedException * @throws IOException * @throws PreferencesException * @throws WriteException * @throws UghHelperException * @throws ExportFileException * @throws MetadataTypeNotAllowedException * @throws DocStructHasNoTypeException * @throws DAOException * @throws SwapException * @throws ReadException * @throws TypeNotAllowedForParentException */ public boolean startExport(Prozess myProzess, String inZielVerzeichnis) throws IOException, InterruptedException, PreferencesException, WriteException, DocStructHasNoTypeException, MetadataTypeNotAllowedException, ExportFileException, UghHelperException, ReadException, SwapException, DAOException, TypeNotAllowedForParentException { /* * -------------------------------- Read Document -------------------------------- */ this.myPrefs = myProzess.getRegelsatz().getPreferences(); String atsPpnBand = myProzess.getTitel(); Fileformat gdzfile = myProzess.readMetadataFile(); /* nur beim Rusdml-Projekt die Metadaten aufbereiten */ ConfigProjects cp = new ConfigProjects(myProzess.getProjekt().getTitel()); if (cp.getParamList("dmsImport.check").contains("rusdml")) { ExportDms_CorrectRusdml expcorr = new ExportDms_CorrectRusdml(myProzess, this.myPrefs, gdzfile); atsPpnBand = expcorr.correctionStart(); } String zielVerzeichnis = prepareUserDirectory(inZielVerzeichnis); String targetFileName = zielVerzeichnis + atsPpnBand + "_mets.xml"; return writeMetsFile(myProzess, targetFileName, gdzfile, false); } /** * prepare user directory * * @param inTargetFolder * the folder to proove and maybe create it */ protected String prepareUserDirectory(String inTargetFolder) { String target = inTargetFolder; Benutzer myBenutzer = (Benutzer) Helper.getManagedBeanValue("#{LoginForm.myBenutzer}"); try { this.help.createUserDirectory(target, myBenutzer.getLogin()); } catch (Exception e) { Helper.setFehlerMeldung("Export canceled, could not create destination directory: " + inTargetFolder, e); } return target; } /** * write MetsFile to given Path * * @param myProzess * the Process to use * @param targetFileName * the filename where the metsfile should be written * @param gdzfile * the FileFormat-Object to use for Mets-Writing * @throws DAOException * @throws SwapException * @throws InterruptedException * @throws IOException * @throws TypeNotAllowedForParentException */ @SuppressWarnings("deprecation") protected boolean writeMetsFile(Prozess myProzess, String targetFileName, Fileformat gdzfile, boolean writeLocalFilegroup) throws PreferencesException, WriteException, IOException, InterruptedException, SwapException, DAOException, TypeNotAllowedForParentException { MetsModsImportExport mm = new MetsModsImportExport(this.myPrefs); mm.setWriteLocal(writeLocalFilegroup); String imageFolderPath = myProzess.getImagesDirectory(); File imageFolder = new File(imageFolderPath); /* * before creating mets file, change relative path to absolute - */ DigitalDocument dd = gdzfile.getDigitalDocument(); if (dd.getFileSet() == null) { Helper.setMeldung(myProzess.getTitel() + ": digital document does not contain images; temporarily adding them for mets file creation"); MetadatenImagesHelper mih = new MetadatenImagesHelper(this.myPrefs, dd); mih.createPagination(myProzess, null); } /* * get the topstruct element of the digital document depending on anchor property */ DocStruct topElement = dd.getLogicalDocStruct(); if (this.myPrefs.getDocStrctTypeByName(topElement.getType().getName()).isAnchor()) { if (topElement.getAllChildren() == null || topElement.getAllChildren().size() == 0) { throw new PreferencesException(myProzess.getTitel() + ": the topstruct element is marked as anchor, but does not have any children for physical docstrucs"); } else { topElement = topElement.getAllChildren().get(0); } } /* * -------------------------------- if the top element does not have any image related, set them all -------------------------------- */ if (topElement.getAllToReferences("logical_physical") == null || topElement.getAllToReferences("logical_physical").size() == 0) { if (dd.getPhysicalDocStruct() != null && dd.getPhysicalDocStruct().getAllChildren() != null) { Helper.setMeldung(myProzess.getTitel() + ": topstruct element does not have any referenced images yet; temporarily adding them for mets file creation"); for (DocStruct mySeitenDocStruct : dd.getPhysicalDocStruct().getAllChildren()) { topElement.addReferenceTo(mySeitenDocStruct, "logical_physical"); } } else { Helper.setFehlerMeldung(myProzess.getTitel() + ": could not found any referenced images, export aborted"); dd = null; return false; } } // if (dd == null) { // return false; // } else { for (ContentFile cf : dd.getFileSet().getAllFiles()) { String location = cf.getLocation(); // If the file's location string shoes no sign of any protocol, // use the file protocol. if (!location.contains("://")) { location = "file://" + location; } URL url = new URL(location); File f = new File(imageFolder, url.getFile()); cf.setLocation(f.toURI().toString()); } mm.setDigitalDocument(dd); /* * -------------------------------- wenn Filegroups definiert wurden, werden diese jetzt in die Metsstruktur übernommen * -------------------------------- */ // Replace all pathes with the given VariableReplacer, also the file // group pathes! VariableReplacer vp = new VariableReplacer(mm.getDigitalDocument(), this.myPrefs, myProzess, null); Set<ProjectFileGroup> myFilegroups = myProzess.getProjekt().getFilegroups(); if (myFilegroups != null && myFilegroups.size() > 0) { for (ProjectFileGroup pfg : myFilegroups) { // check if source files exists if (pfg.getFolder() != null && pfg.getFolder().length() > 0) { File folder = new File(myProzess.getMethodFromName(pfg.getFolder())); if (folder.exists() && folder.list().length > 0) { VirtualFileGroup v = new VirtualFileGroup(); v.setName(pfg.getName()); v.setPathToFiles(vp.replace(pfg.getPath())); v.setMimetype(pfg.getMimetype()); v.setFileSuffix(pfg.getSuffix()); mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v); } } else { VirtualFileGroup v = new VirtualFileGroup(); v.setName(pfg.getName()); v.setPathToFiles(vp.replace(pfg.getPath())); v.setMimetype(pfg.getMimetype()); v.setFileSuffix(pfg.getSuffix()); mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v); } } } // Replace rights and digiprov entries. mm.setRightsOwner(vp.replace(myProzess.getProjekt().getMetsRightsOwner())); mm.setRightsOwnerLogo(vp.replace(myProzess.getProjekt().getMetsRightsOwnerLogo())); mm.setRightsOwnerSiteURL(vp.replace(myProzess.getProjekt().getMetsRightsOwnerSite())); mm.setRightsOwnerContact(vp.replace(myProzess.getProjekt().getMetsRightsOwnerMail())); mm.setDigiprovPresentation(vp.replace(myProzess.getProjekt().getMetsDigiprovPresentation())); mm.setDigiprovReference(vp.replace(myProzess.getProjekt().getMetsDigiprovReference())); mm.setDigiprovPresentationAnchor(vp.replace(myProzess.getProjekt().getMetsDigiprovPresentationAnchor())); mm.setDigiprovReferenceAnchor(vp.replace(myProzess.getProjekt().getMetsDigiprovReferenceAnchor())); mm.setPurlUrl(vp.replace(myProzess.getProjekt().getMetsPurl())); mm.setContentIDs(vp.replace(myProzess.getProjekt().getMetsContentIDs())); String pointer = myProzess.getProjekt().getMetsPointerPath(); pointer = vp.replace(pointer); mm.setMptrUrl(pointer); String anchor = myProzess.getProjekt().getMetsPointerPathAnchor(); pointer = vp.replace(anchor); mm.setMptrAnchorUrl(pointer); // if (!ConfigMain.getParameter("ImagePrefix", "\\d{8}").equals("\\d{8}")) { - List<String> images = new ArrayList<String>(); +// List<String> images = new ArrayList<String>(); try { // TODO andere Dateigruppen nicht mit image Namen ersetzen - images = new MetadatenImagesHelper(this.myPrefs, dd).getDataFiles(myProzess); + MetadatenImagesHelper mih = new MetadatenImagesHelper(myPrefs, dd); + List<String> images = mih.getDataFiles(myProzess); int sizeOfPagination = dd.getPhysicalDocStruct().getAllChildren().size(); if (images != null) { int sizeOfImages = images.size(); if (sizeOfPagination == sizeOfImages) { dd.overrideContentFiles(images); } else { List<String> param = new ArrayList<String>(); param.add(String.valueOf(sizeOfPagination)); param.add(String.valueOf(sizeOfImages)); Helper.setFehlerMeldung(Helper.getTranslation("imagePaginationError", param)); return false; } } } catch (IndexOutOfBoundsException e) { myLogger.error(e); return false; } catch (InvalidImagesException e) { myLogger.error(e); return false; } mm.write(targetFileName); Helper.setMeldung(null, myProzess.getTitel() + ": ", "Export finished"); return true; // } } // private static String getMimetype(String filename) { // FileNameMap fnm = URLConnection.getFileNameMap(); // return fnm.getContentTypeFor(filename); // } }
false
true
protected boolean writeMetsFile(Prozess myProzess, String targetFileName, Fileformat gdzfile, boolean writeLocalFilegroup) throws PreferencesException, WriteException, IOException, InterruptedException, SwapException, DAOException, TypeNotAllowedForParentException { MetsModsImportExport mm = new MetsModsImportExport(this.myPrefs); mm.setWriteLocal(writeLocalFilegroup); String imageFolderPath = myProzess.getImagesDirectory(); File imageFolder = new File(imageFolderPath); /* * before creating mets file, change relative path to absolute - */ DigitalDocument dd = gdzfile.getDigitalDocument(); if (dd.getFileSet() == null) { Helper.setMeldung(myProzess.getTitel() + ": digital document does not contain images; temporarily adding them for mets file creation"); MetadatenImagesHelper mih = new MetadatenImagesHelper(this.myPrefs, dd); mih.createPagination(myProzess, null); } /* * get the topstruct element of the digital document depending on anchor property */ DocStruct topElement = dd.getLogicalDocStruct(); if (this.myPrefs.getDocStrctTypeByName(topElement.getType().getName()).isAnchor()) { if (topElement.getAllChildren() == null || topElement.getAllChildren().size() == 0) { throw new PreferencesException(myProzess.getTitel() + ": the topstruct element is marked as anchor, but does not have any children for physical docstrucs"); } else { topElement = topElement.getAllChildren().get(0); } } /* * -------------------------------- if the top element does not have any image related, set them all -------------------------------- */ if (topElement.getAllToReferences("logical_physical") == null || topElement.getAllToReferences("logical_physical").size() == 0) { if (dd.getPhysicalDocStruct() != null && dd.getPhysicalDocStruct().getAllChildren() != null) { Helper.setMeldung(myProzess.getTitel() + ": topstruct element does not have any referenced images yet; temporarily adding them for mets file creation"); for (DocStruct mySeitenDocStruct : dd.getPhysicalDocStruct().getAllChildren()) { topElement.addReferenceTo(mySeitenDocStruct, "logical_physical"); } } else { Helper.setFehlerMeldung(myProzess.getTitel() + ": could not found any referenced images, export aborted"); dd = null; return false; } } // if (dd == null) { // return false; // } else { for (ContentFile cf : dd.getFileSet().getAllFiles()) { String location = cf.getLocation(); // If the file's location string shoes no sign of any protocol, // use the file protocol. if (!location.contains("://")) { location = "file://" + location; } URL url = new URL(location); File f = new File(imageFolder, url.getFile()); cf.setLocation(f.toURI().toString()); } mm.setDigitalDocument(dd); /* * -------------------------------- wenn Filegroups definiert wurden, werden diese jetzt in die Metsstruktur übernommen * -------------------------------- */ // Replace all pathes with the given VariableReplacer, also the file // group pathes! VariableReplacer vp = new VariableReplacer(mm.getDigitalDocument(), this.myPrefs, myProzess, null); Set<ProjectFileGroup> myFilegroups = myProzess.getProjekt().getFilegroups(); if (myFilegroups != null && myFilegroups.size() > 0) { for (ProjectFileGroup pfg : myFilegroups) { // check if source files exists if (pfg.getFolder() != null && pfg.getFolder().length() > 0) { File folder = new File(myProzess.getMethodFromName(pfg.getFolder())); if (folder.exists() && folder.list().length > 0) { VirtualFileGroup v = new VirtualFileGroup(); v.setName(pfg.getName()); v.setPathToFiles(vp.replace(pfg.getPath())); v.setMimetype(pfg.getMimetype()); v.setFileSuffix(pfg.getSuffix()); mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v); } } else { VirtualFileGroup v = new VirtualFileGroup(); v.setName(pfg.getName()); v.setPathToFiles(vp.replace(pfg.getPath())); v.setMimetype(pfg.getMimetype()); v.setFileSuffix(pfg.getSuffix()); mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v); } } } // Replace rights and digiprov entries. mm.setRightsOwner(vp.replace(myProzess.getProjekt().getMetsRightsOwner())); mm.setRightsOwnerLogo(vp.replace(myProzess.getProjekt().getMetsRightsOwnerLogo())); mm.setRightsOwnerSiteURL(vp.replace(myProzess.getProjekt().getMetsRightsOwnerSite())); mm.setRightsOwnerContact(vp.replace(myProzess.getProjekt().getMetsRightsOwnerMail())); mm.setDigiprovPresentation(vp.replace(myProzess.getProjekt().getMetsDigiprovPresentation())); mm.setDigiprovReference(vp.replace(myProzess.getProjekt().getMetsDigiprovReference())); mm.setDigiprovPresentationAnchor(vp.replace(myProzess.getProjekt().getMetsDigiprovPresentationAnchor())); mm.setDigiprovReferenceAnchor(vp.replace(myProzess.getProjekt().getMetsDigiprovReferenceAnchor())); mm.setPurlUrl(vp.replace(myProzess.getProjekt().getMetsPurl())); mm.setContentIDs(vp.replace(myProzess.getProjekt().getMetsContentIDs())); String pointer = myProzess.getProjekt().getMetsPointerPath(); pointer = vp.replace(pointer); mm.setMptrUrl(pointer); String anchor = myProzess.getProjekt().getMetsPointerPathAnchor(); pointer = vp.replace(anchor); mm.setMptrAnchorUrl(pointer); // if (!ConfigMain.getParameter("ImagePrefix", "\\d{8}").equals("\\d{8}")) { List<String> images = new ArrayList<String>(); try { // TODO andere Dateigruppen nicht mit image Namen ersetzen images = new MetadatenImagesHelper(this.myPrefs, dd).getDataFiles(myProzess); int sizeOfPagination = dd.getPhysicalDocStruct().getAllChildren().size(); if (images != null) { int sizeOfImages = images.size(); if (sizeOfPagination == sizeOfImages) { dd.overrideContentFiles(images); } else { List<String> param = new ArrayList<String>(); param.add(String.valueOf(sizeOfPagination)); param.add(String.valueOf(sizeOfImages)); Helper.setFehlerMeldung(Helper.getTranslation("imagePaginationError", param)); return false; } } } catch (IndexOutOfBoundsException e) { myLogger.error(e); return false; } catch (InvalidImagesException e) { myLogger.error(e); return false; } mm.write(targetFileName); Helper.setMeldung(null, myProzess.getTitel() + ": ", "Export finished"); return true; // } }
protected boolean writeMetsFile(Prozess myProzess, String targetFileName, Fileformat gdzfile, boolean writeLocalFilegroup) throws PreferencesException, WriteException, IOException, InterruptedException, SwapException, DAOException, TypeNotAllowedForParentException { MetsModsImportExport mm = new MetsModsImportExport(this.myPrefs); mm.setWriteLocal(writeLocalFilegroup); String imageFolderPath = myProzess.getImagesDirectory(); File imageFolder = new File(imageFolderPath); /* * before creating mets file, change relative path to absolute - */ DigitalDocument dd = gdzfile.getDigitalDocument(); if (dd.getFileSet() == null) { Helper.setMeldung(myProzess.getTitel() + ": digital document does not contain images; temporarily adding them for mets file creation"); MetadatenImagesHelper mih = new MetadatenImagesHelper(this.myPrefs, dd); mih.createPagination(myProzess, null); } /* * get the topstruct element of the digital document depending on anchor property */ DocStruct topElement = dd.getLogicalDocStruct(); if (this.myPrefs.getDocStrctTypeByName(topElement.getType().getName()).isAnchor()) { if (topElement.getAllChildren() == null || topElement.getAllChildren().size() == 0) { throw new PreferencesException(myProzess.getTitel() + ": the topstruct element is marked as anchor, but does not have any children for physical docstrucs"); } else { topElement = topElement.getAllChildren().get(0); } } /* * -------------------------------- if the top element does not have any image related, set them all -------------------------------- */ if (topElement.getAllToReferences("logical_physical") == null || topElement.getAllToReferences("logical_physical").size() == 0) { if (dd.getPhysicalDocStruct() != null && dd.getPhysicalDocStruct().getAllChildren() != null) { Helper.setMeldung(myProzess.getTitel() + ": topstruct element does not have any referenced images yet; temporarily adding them for mets file creation"); for (DocStruct mySeitenDocStruct : dd.getPhysicalDocStruct().getAllChildren()) { topElement.addReferenceTo(mySeitenDocStruct, "logical_physical"); } } else { Helper.setFehlerMeldung(myProzess.getTitel() + ": could not found any referenced images, export aborted"); dd = null; return false; } } // if (dd == null) { // return false; // } else { for (ContentFile cf : dd.getFileSet().getAllFiles()) { String location = cf.getLocation(); // If the file's location string shoes no sign of any protocol, // use the file protocol. if (!location.contains("://")) { location = "file://" + location; } URL url = new URL(location); File f = new File(imageFolder, url.getFile()); cf.setLocation(f.toURI().toString()); } mm.setDigitalDocument(dd); /* * -------------------------------- wenn Filegroups definiert wurden, werden diese jetzt in die Metsstruktur übernommen * -------------------------------- */ // Replace all pathes with the given VariableReplacer, also the file // group pathes! VariableReplacer vp = new VariableReplacer(mm.getDigitalDocument(), this.myPrefs, myProzess, null); Set<ProjectFileGroup> myFilegroups = myProzess.getProjekt().getFilegroups(); if (myFilegroups != null && myFilegroups.size() > 0) { for (ProjectFileGroup pfg : myFilegroups) { // check if source files exists if (pfg.getFolder() != null && pfg.getFolder().length() > 0) { File folder = new File(myProzess.getMethodFromName(pfg.getFolder())); if (folder.exists() && folder.list().length > 0) { VirtualFileGroup v = new VirtualFileGroup(); v.setName(pfg.getName()); v.setPathToFiles(vp.replace(pfg.getPath())); v.setMimetype(pfg.getMimetype()); v.setFileSuffix(pfg.getSuffix()); mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v); } } else { VirtualFileGroup v = new VirtualFileGroup(); v.setName(pfg.getName()); v.setPathToFiles(vp.replace(pfg.getPath())); v.setMimetype(pfg.getMimetype()); v.setFileSuffix(pfg.getSuffix()); mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v); } } } // Replace rights and digiprov entries. mm.setRightsOwner(vp.replace(myProzess.getProjekt().getMetsRightsOwner())); mm.setRightsOwnerLogo(vp.replace(myProzess.getProjekt().getMetsRightsOwnerLogo())); mm.setRightsOwnerSiteURL(vp.replace(myProzess.getProjekt().getMetsRightsOwnerSite())); mm.setRightsOwnerContact(vp.replace(myProzess.getProjekt().getMetsRightsOwnerMail())); mm.setDigiprovPresentation(vp.replace(myProzess.getProjekt().getMetsDigiprovPresentation())); mm.setDigiprovReference(vp.replace(myProzess.getProjekt().getMetsDigiprovReference())); mm.setDigiprovPresentationAnchor(vp.replace(myProzess.getProjekt().getMetsDigiprovPresentationAnchor())); mm.setDigiprovReferenceAnchor(vp.replace(myProzess.getProjekt().getMetsDigiprovReferenceAnchor())); mm.setPurlUrl(vp.replace(myProzess.getProjekt().getMetsPurl())); mm.setContentIDs(vp.replace(myProzess.getProjekt().getMetsContentIDs())); String pointer = myProzess.getProjekt().getMetsPointerPath(); pointer = vp.replace(pointer); mm.setMptrUrl(pointer); String anchor = myProzess.getProjekt().getMetsPointerPathAnchor(); pointer = vp.replace(anchor); mm.setMptrAnchorUrl(pointer); // if (!ConfigMain.getParameter("ImagePrefix", "\\d{8}").equals("\\d{8}")) { // List<String> images = new ArrayList<String>(); try { // TODO andere Dateigruppen nicht mit image Namen ersetzen MetadatenImagesHelper mih = new MetadatenImagesHelper(myPrefs, dd); List<String> images = mih.getDataFiles(myProzess); int sizeOfPagination = dd.getPhysicalDocStruct().getAllChildren().size(); if (images != null) { int sizeOfImages = images.size(); if (sizeOfPagination == sizeOfImages) { dd.overrideContentFiles(images); } else { List<String> param = new ArrayList<String>(); param.add(String.valueOf(sizeOfPagination)); param.add(String.valueOf(sizeOfImages)); Helper.setFehlerMeldung(Helper.getTranslation("imagePaginationError", param)); return false; } } } catch (IndexOutOfBoundsException e) { myLogger.error(e); return false; } catch (InvalidImagesException e) { myLogger.error(e); return false; } mm.write(targetFileName); Helper.setMeldung(null, myProzess.getTitel() + ": ", "Export finished"); return true; // } }
diff --git a/grails/src/commons/org/codehaus/groovy/grails/validation/RangeConstraint.java b/grails/src/commons/org/codehaus/groovy/grails/validation/RangeConstraint.java index 7a94c5b30..b4f970408 100644 --- a/grails/src/commons/org/codehaus/groovy/grails/validation/RangeConstraint.java +++ b/grails/src/commons/org/codehaus/groovy/grails/validation/RangeConstraint.java @@ -1,87 +1,87 @@ /* Copyright 2004-2005 Graeme Rocher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.validation; import groovy.lang.Range; import org.codehaus.groovy.grails.commons.GrailsClassUtils; import org.springframework.validation.Errors; /** * A Constraint that validates a range * * @author Graeme Rocher * @since 0.4 * <p/> * Created: Jan 19, 2007 * Time: 8:17:32 AM */ class RangeConstraint extends AbstractConstraint { Range range; /** * @return Returns the range. */ public Range getRange() { return range; } /* (non-Javadoc) * @see org.codehaus.groovy.grails.validation.Constraint#supports(java.lang.Class) */ public boolean supports(Class type) { return type != null && (Comparable.class.isAssignableFrom(type) || GrailsClassUtils.isAssignableOrConvertibleFrom(Number.class, type)); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.validation.ConstrainedProperty.AbstractConstraint#setParameter(java.lang.Object) */ public void setParameter(Object constraintParameter) { if(!(constraintParameter instanceof Range)) throw new IllegalArgumentException("Parameter for constraint ["+ConstrainedProperty.RANGE_CONSTRAINT+"] of property ["+constraintPropertyName+"] of class ["+constraintOwningClass+"] must be a of type [groovy.lang.Range]"); this.range = (Range)constraintParameter; super.setParameter(constraintParameter); } public String getName() { return ConstrainedProperty.RANGE_CONSTRAINT; } protected void processValidate(Object target, Object propertyValue, Errors errors) { if(!this.range.contains(propertyValue)) { Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue, range.getFrom(), range.getTo() }; Comparable from = range.getFrom(); Comparable to = range.getTo(); if(from instanceof Number && propertyValue instanceof Number) { // Upgrade the numbers to Long, so all integer types can be compared. - from = ((Number) from).longValue(); - to = ((Number) to).longValue(); - propertyValue = ((Number) propertyValue).longValue(); + from = new Long(((Number) from).longValue()); + to = new Long(((Number) to).longValue()); + propertyValue = new Long(((Number) propertyValue).longValue()); } if(from.compareTo(propertyValue) > 0) { super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOSMALL_SUFFIX,args ); } else if (to.compareTo(propertyValue) < 0) { super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOBIG_SUFFIX,args ); } } } }
true
true
protected void processValidate(Object target, Object propertyValue, Errors errors) { if(!this.range.contains(propertyValue)) { Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue, range.getFrom(), range.getTo() }; Comparable from = range.getFrom(); Comparable to = range.getTo(); if(from instanceof Number && propertyValue instanceof Number) { // Upgrade the numbers to Long, so all integer types can be compared. from = ((Number) from).longValue(); to = ((Number) to).longValue(); propertyValue = ((Number) propertyValue).longValue(); } if(from.compareTo(propertyValue) > 0) { super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOSMALL_SUFFIX,args ); } else if (to.compareTo(propertyValue) < 0) { super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOBIG_SUFFIX,args ); } } }
protected void processValidate(Object target, Object propertyValue, Errors errors) { if(!this.range.contains(propertyValue)) { Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue, range.getFrom(), range.getTo() }; Comparable from = range.getFrom(); Comparable to = range.getTo(); if(from instanceof Number && propertyValue instanceof Number) { // Upgrade the numbers to Long, so all integer types can be compared. from = new Long(((Number) from).longValue()); to = new Long(((Number) to).longValue()); propertyValue = new Long(((Number) propertyValue).longValue()); } if(from.compareTo(propertyValue) > 0) { super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOSMALL_SUFFIX,args ); } else if (to.compareTo(propertyValue) < 0) { super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOBIG_SUFFIX,args ); } } }
diff --git a/activemq-core/src/main/java/org/apache/activemq/network/ForwardingBridge.java b/activemq-core/src/main/java/org/apache/activemq/network/ForwardingBridge.java index a0f6fd96e..8528d5b54 100755 --- a/activemq-core/src/main/java/org/apache/activemq/network/ForwardingBridge.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/ForwardingBridge.java @@ -1,320 +1,319 @@ /** * * Copyright 2005-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.activemq.network; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.BrokerId; import org.apache.activemq.command.BrokerInfo; import org.apache.activemq.command.Command; import org.apache.activemq.command.ConnectionId; import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.ExceptionResponse; import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessageDispatch; import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.command.Response; import org.apache.activemq.command.SessionInfo; import org.apache.activemq.command.ShutdownInfo; import org.apache.activemq.transport.DefaultTransportListener; import org.apache.activemq.transport.FutureResponse; import org.apache.activemq.transport.ResponseCallback; import org.apache.activemq.transport.Transport; import org.apache.activemq.util.IdGenerator; import org.apache.activemq.util.ServiceStopper; import org.apache.activemq.util.ServiceSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; /** * Forwards all messages from the local broker to the remote broker. * * @org.apache.xbean.XBean * * @version $Revision$ */ public class ForwardingBridge implements Bridge { static final private Log log = LogFactory.getLog(ForwardingBridge.class); private final Transport localBroker; private final Transport remoteBroker; IdGenerator idGenerator = new IdGenerator(); ConnectionInfo connectionInfo; SessionInfo sessionInfo; ProducerInfo producerInfo; ConsumerInfo queueConsumerInfo; ConsumerInfo topicConsumerInfo; private String clientId; private int prefetchSize=1000; private boolean dispatchAsync; private String destinationFilter = ">"; private int queueDispatched; private int topicDispatched; BrokerId localBrokerId; BrokerId remoteBrokerId; public ForwardingBridge(Transport localBroker, Transport remoteBroker) { this.localBroker = localBroker; this.remoteBroker = remoteBroker; } public void start() throws Exception { log.info("Starting a network connection between " + localBroker + " and " + remoteBroker + " has been established."); localBroker.setTransportListener(new DefaultTransportListener(){ public void onCommand(Command command) { serviceLocalCommand(command); } public void onException(IOException error) { serviceLocalException(error); } }); remoteBroker.setTransportListener(new DefaultTransportListener(){ public void onCommand(Command command) { serviceRemoteCommand(command); } public void onException(IOException error) { serviceRemoteException(error); } }); localBroker.start(); remoteBroker.start(); } protected void triggerStartBridge() throws IOException { Thread thead = new Thread() { public void run() { try { startBridge(); } catch (IOException e) { log.error("Failed to start network bridge: " + e, e); } } }; thead.start(); } /** * @throws IOException */ private void startBridge() throws IOException { connectionInfo = new ConnectionInfo(); connectionInfo.setConnectionId(new ConnectionId(idGenerator.generateId())); connectionInfo.setClientId(clientId); localBroker.oneway(connectionInfo); remoteBroker.oneway(connectionInfo); sessionInfo=new SessionInfo(connectionInfo, 1); localBroker.oneway(sessionInfo); remoteBroker.oneway(sessionInfo); queueConsumerInfo = new ConsumerInfo(sessionInfo, 1); queueConsumerInfo.setDispatchAsync(dispatchAsync); queueConsumerInfo.setDestination(new ActiveMQQueue(destinationFilter)); queueConsumerInfo.setPrefetchSize(prefetchSize); queueConsumerInfo.setPriority(ConsumerInfo.NETWORK_CONSUMER_PRIORITY); localBroker.oneway(queueConsumerInfo); producerInfo = new ProducerInfo(sessionInfo, 1); producerInfo.setResponseRequired(false); remoteBroker.oneway(producerInfo); if( connectionInfo.getClientId()!=null ) { topicConsumerInfo = new ConsumerInfo(sessionInfo, 2); topicConsumerInfo.setDispatchAsync(dispatchAsync); topicConsumerInfo.setSubcriptionName("topic-bridge"); topicConsumerInfo.setRetroactive(true); topicConsumerInfo.setDestination(new ActiveMQTopic(destinationFilter)); topicConsumerInfo.setPrefetchSize(prefetchSize); topicConsumerInfo.setPriority(ConsumerInfo.NETWORK_CONSUMER_PRIORITY); localBroker.oneway(topicConsumerInfo); } log.info("Network connection between " + localBroker + " and " + remoteBroker + " has been established."); } public void stop() throws Exception { try { if( connectionInfo!=null ) { localBroker.request(connectionInfo.createRemoveCommand()); remoteBroker.request(connectionInfo.createRemoveCommand()); } localBroker.setTransportListener(null); remoteBroker.setTransportListener(null); localBroker.oneway(new ShutdownInfo()); remoteBroker.oneway(new ShutdownInfo()); } finally { ServiceStopper ss = new ServiceStopper(); ss.stop(localBroker); ss.stop(remoteBroker); ss.throwFirstException(); } } protected void serviceRemoteException(IOException error) { log.info("Unexpected remote exception: "+error); log.debug("Exception trace: ", error); } protected void serviceRemoteCommand(Command command) { try { if(command.isBrokerInfo() ) { synchronized( this ) { remoteBrokerId = ((BrokerInfo)command).getBrokerId(); if( localBrokerId !=null) { if( localBrokerId.equals(remoteBrokerId) ) { log.info("Disconnecting loop back connection."); ServiceSupport.dispose(this); } else { triggerStartBridge(); } } } } else { log.warn("Unexpected remote command: "+command); } } catch (IOException e) { serviceLocalException(e); } } protected void serviceLocalException(Throwable error) { log.info("Unexpected local exception: "+error); log.debug("Exception trace: ", error); } protected void serviceLocalCommand(Command command) { try { if( command.isMessageDispatch() ) { final MessageDispatch md = (MessageDispatch) command; Message message = md.getMessage(); message.setProducerId(producerInfo.getProducerId()); - message.setDestination( md.getDestination() ); if( message.getOriginalTransactionId()==null ) message.setOriginalTransactionId(message.getTransactionId()); message.setTransactionId(null); message.evictMarshlledForm(); if( !message.isResponseRequired() ) { // If the message was originally sent using async send, we will preserve that QOS // by bridging it using an async send (small chance of message loss). remoteBroker.oneway(message); localBroker.oneway(new MessageAck(md,MessageAck.STANDARD_ACK_TYPE,1)); } else { // The message was not sent using async send, so we should only ack the local // broker when we get confirmation that the remote broker has received the message. ResponseCallback callback = new ResponseCallback() { public void onCompletion(FutureResponse future) { try { Response response = future.getResult(); if(response.isException()){ ExceptionResponse er=(ExceptionResponse) response; serviceLocalException(er.getException()); } else { localBroker.oneway(new MessageAck(md,MessageAck.STANDARD_ACK_TYPE,1)); } } catch (IOException e) { serviceLocalException(e); } } }; remoteBroker.asyncRequest(message, callback); } // Ack on every message since we don't know if the broker is blocked due to memory // usage and is waiting for an Ack to un-block him. // Acking a range is more efficient, but also more prone to locking up a server // Perhaps doing something like the following should be policy based. // if( md.getConsumerId().equals(queueConsumerInfo.getConsumerId()) ) { // queueDispatched++; // if( queueDispatched > (queueConsumerInfo.getPrefetchSize()/2) ) { // localBroker.oneway(new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, queueDispatched)); // queueDispatched=0; // } // } else { // topicDispatched++; // if( topicDispatched > (topicConsumerInfo.getPrefetchSize()/2) ) { // localBroker.oneway(new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, topicDispatched)); // topicDispatched=0; // } // } } else if(command.isBrokerInfo() ) { synchronized( this ) { localBrokerId = ((BrokerInfo)command).getBrokerId(); if( remoteBrokerId !=null) { if( remoteBrokerId.equals(localBrokerId) ) { log.info("Disconnecting loop back connection."); ServiceSupport.dispose(this); } else { triggerStartBridge(); } } } } else { log.debug("Unexpected local command: "+command); } } catch (IOException e) { serviceLocalException(e); } } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public int getPrefetchSize() { return prefetchSize; } public void setPrefetchSize(int prefetchSize) { this.prefetchSize = prefetchSize; } public boolean isDispatchAsync() { return dispatchAsync; } public void setDispatchAsync(boolean dispatchAsync) { this.dispatchAsync = dispatchAsync; } public String getDestinationFilter() { return destinationFilter; } public void setDestinationFilter(String destinationFilter) { this.destinationFilter = destinationFilter; } }
true
true
protected void serviceLocalCommand(Command command) { try { if( command.isMessageDispatch() ) { final MessageDispatch md = (MessageDispatch) command; Message message = md.getMessage(); message.setProducerId(producerInfo.getProducerId()); message.setDestination( md.getDestination() ); if( message.getOriginalTransactionId()==null ) message.setOriginalTransactionId(message.getTransactionId()); message.setTransactionId(null); message.evictMarshlledForm(); if( !message.isResponseRequired() ) { // If the message was originally sent using async send, we will preserve that QOS // by bridging it using an async send (small chance of message loss). remoteBroker.oneway(message); localBroker.oneway(new MessageAck(md,MessageAck.STANDARD_ACK_TYPE,1)); } else { // The message was not sent using async send, so we should only ack the local // broker when we get confirmation that the remote broker has received the message. ResponseCallback callback = new ResponseCallback() { public void onCompletion(FutureResponse future) { try { Response response = future.getResult(); if(response.isException()){ ExceptionResponse er=(ExceptionResponse) response; serviceLocalException(er.getException()); } else { localBroker.oneway(new MessageAck(md,MessageAck.STANDARD_ACK_TYPE,1)); } } catch (IOException e) { serviceLocalException(e); } } }; remoteBroker.asyncRequest(message, callback); } // Ack on every message since we don't know if the broker is blocked due to memory // usage and is waiting for an Ack to un-block him. // Acking a range is more efficient, but also more prone to locking up a server // Perhaps doing something like the following should be policy based. // if( md.getConsumerId().equals(queueConsumerInfo.getConsumerId()) ) { // queueDispatched++; // if( queueDispatched > (queueConsumerInfo.getPrefetchSize()/2) ) { // localBroker.oneway(new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, queueDispatched)); // queueDispatched=0; // } // } else { // topicDispatched++; // if( topicDispatched > (topicConsumerInfo.getPrefetchSize()/2) ) { // localBroker.oneway(new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, topicDispatched)); // topicDispatched=0; // } // } } else if(command.isBrokerInfo() ) { synchronized( this ) { localBrokerId = ((BrokerInfo)command).getBrokerId(); if( remoteBrokerId !=null) { if( remoteBrokerId.equals(localBrokerId) ) { log.info("Disconnecting loop back connection."); ServiceSupport.dispose(this); } else { triggerStartBridge(); } } } } else { log.debug("Unexpected local command: "+command); } } catch (IOException e) { serviceLocalException(e); } }
protected void serviceLocalCommand(Command command) { try { if( command.isMessageDispatch() ) { final MessageDispatch md = (MessageDispatch) command; Message message = md.getMessage(); message.setProducerId(producerInfo.getProducerId()); if( message.getOriginalTransactionId()==null ) message.setOriginalTransactionId(message.getTransactionId()); message.setTransactionId(null); message.evictMarshlledForm(); if( !message.isResponseRequired() ) { // If the message was originally sent using async send, we will preserve that QOS // by bridging it using an async send (small chance of message loss). remoteBroker.oneway(message); localBroker.oneway(new MessageAck(md,MessageAck.STANDARD_ACK_TYPE,1)); } else { // The message was not sent using async send, so we should only ack the local // broker when we get confirmation that the remote broker has received the message. ResponseCallback callback = new ResponseCallback() { public void onCompletion(FutureResponse future) { try { Response response = future.getResult(); if(response.isException()){ ExceptionResponse er=(ExceptionResponse) response; serviceLocalException(er.getException()); } else { localBroker.oneway(new MessageAck(md,MessageAck.STANDARD_ACK_TYPE,1)); } } catch (IOException e) { serviceLocalException(e); } } }; remoteBroker.asyncRequest(message, callback); } // Ack on every message since we don't know if the broker is blocked due to memory // usage and is waiting for an Ack to un-block him. // Acking a range is more efficient, but also more prone to locking up a server // Perhaps doing something like the following should be policy based. // if( md.getConsumerId().equals(queueConsumerInfo.getConsumerId()) ) { // queueDispatched++; // if( queueDispatched > (queueConsumerInfo.getPrefetchSize()/2) ) { // localBroker.oneway(new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, queueDispatched)); // queueDispatched=0; // } // } else { // topicDispatched++; // if( topicDispatched > (topicConsumerInfo.getPrefetchSize()/2) ) { // localBroker.oneway(new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, topicDispatched)); // topicDispatched=0; // } // } } else if(command.isBrokerInfo() ) { synchronized( this ) { localBrokerId = ((BrokerInfo)command).getBrokerId(); if( remoteBrokerId !=null) { if( remoteBrokerId.equals(localBrokerId) ) { log.info("Disconnecting loop back connection."); ServiceSupport.dispose(this); } else { triggerStartBridge(); } } } } else { log.debug("Unexpected local command: "+command); } } catch (IOException e) { serviceLocalException(e); } }
diff --git a/src/states/AreaState.java b/src/states/AreaState.java index 4736170..7b5dea2 100644 --- a/src/states/AreaState.java +++ b/src/states/AreaState.java @@ -1,95 +1,95 @@ package states; import java.util.ArrayList; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.tiled.TiledMap; import weapons.Attack; import core.MainGame; import dudes.Monster; import dudes.Player; public class AreaState extends BasicGameState { protected Player[] players; protected TiledMap bgImage; protected ArrayList<Monster> monsters; private int progression; public AreaState(int stateID) { super(); } @Override public void init(GameContainer container, StateBasedGame game) throws SlickException { progression = 0; players = MainGame.players; monsters = new ArrayList<Monster>(); } @Override public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { bgImage.render(-progression % 32, 0, progression / 32, 0, 32 + 1, 24); for (int i = 0; i < players.length; i++) { players[i].render(g); } } @Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { if (container.getInput().isKeyPressed(Input.KEY_ESCAPE)) { container.exit(); } // progression++; for (int i = 0; i < players.length; i++) { if (!players[i].isAttacking) { players[i].move(container.getInput(), delta); } } float backPlayerPos = Math.min(players[0].pos[0], players[1].pos[0]); - if (progression < 32*(200 - 31)) { + if (progression < 32*(200 - 33)) { if (backPlayerPos > MainGame.GAME_WIDTH/3) { float shift = backPlayerPos - MainGame.GAME_WIDTH/3; progression += shift; players[0].pos[0] -= shift; players[1].pos[0] -= shift; } } for (int i = 0; i < players.length; i++) { Player player = players[i]; player.weapon.updateAttacks(); for (Monster monster : this.monsters) { for (Attack attack : player.weapon.attacks) { if (attack.hitbox.intersects(monster.hitbox)) { monster.health -= player.weapon.damage; } if (attack.hitbox.intersects(players[(i + 1) % 2].hitbox)) { players[(i + 1) % 2].flinch(0); } } for(Attack attack : monster.weapon.attacks){ if (attack.hitbox.intersects(player.hitbox)){ player.health -= monster.weapon.damage; } } } } } @Override public int getID() { // TODO Auto-generated method stub return 1; } }
true
true
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { if (container.getInput().isKeyPressed(Input.KEY_ESCAPE)) { container.exit(); } // progression++; for (int i = 0; i < players.length; i++) { if (!players[i].isAttacking) { players[i].move(container.getInput(), delta); } } float backPlayerPos = Math.min(players[0].pos[0], players[1].pos[0]); if (progression < 32*(200 - 31)) { if (backPlayerPos > MainGame.GAME_WIDTH/3) { float shift = backPlayerPos - MainGame.GAME_WIDTH/3; progression += shift; players[0].pos[0] -= shift; players[1].pos[0] -= shift; } } for (int i = 0; i < players.length; i++) { Player player = players[i]; player.weapon.updateAttacks(); for (Monster monster : this.monsters) { for (Attack attack : player.weapon.attacks) { if (attack.hitbox.intersects(monster.hitbox)) { monster.health -= player.weapon.damage; } if (attack.hitbox.intersects(players[(i + 1) % 2].hitbox)) { players[(i + 1) % 2].flinch(0); } } for(Attack attack : monster.weapon.attacks){ if (attack.hitbox.intersects(player.hitbox)){ player.health -= monster.weapon.damage; } } } } }
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { if (container.getInput().isKeyPressed(Input.KEY_ESCAPE)) { container.exit(); } // progression++; for (int i = 0; i < players.length; i++) { if (!players[i].isAttacking) { players[i].move(container.getInput(), delta); } } float backPlayerPos = Math.min(players[0].pos[0], players[1].pos[0]); if (progression < 32*(200 - 33)) { if (backPlayerPos > MainGame.GAME_WIDTH/3) { float shift = backPlayerPos - MainGame.GAME_WIDTH/3; progression += shift; players[0].pos[0] -= shift; players[1].pos[0] -= shift; } } for (int i = 0; i < players.length; i++) { Player player = players[i]; player.weapon.updateAttacks(); for (Monster monster : this.monsters) { for (Attack attack : player.weapon.attacks) { if (attack.hitbox.intersects(monster.hitbox)) { monster.health -= player.weapon.damage; } if (attack.hitbox.intersects(players[(i + 1) % 2].hitbox)) { players[(i + 1) % 2].flinch(0); } } for(Attack attack : monster.weapon.attacks){ if (attack.hitbox.intersects(player.hitbox)){ player.health -= monster.weapon.damage; } } } } }
diff --git a/ui/listShuttle/src/main/java/org/richfaces/renderkit/ListShuttleRendererBase.java b/ui/listShuttle/src/main/java/org/richfaces/renderkit/ListShuttleRendererBase.java index 8082308c..6e949364 100644 --- a/ui/listShuttle/src/main/java/org/richfaces/renderkit/ListShuttleRendererBase.java +++ b/ui/listShuttle/src/main/java/org/richfaces/renderkit/ListShuttleRendererBase.java @@ -1,389 +1,390 @@ /** * License Agreement. * * Rich Faces - Natural Ajax for Java Server Faces (JSF) * * Copyright (C) 2007 Exadel, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * 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 */ package org.richfaces.renderkit; import java.io.IOException; import java.io.StringWriter; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import javax.faces.component.UIComponent; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.convert.Converter; import org.ajax4jsf.component.UIDataAdaptor; import org.ajax4jsf.renderkit.ComponentVariables; import org.ajax4jsf.renderkit.ComponentsVariableResolver; import org.ajax4jsf.renderkit.RendererUtils.HTML; import org.richfaces.component.UIListShuttle; import org.richfaces.component.UIOrderingBaseComponent; import org.richfaces.component.UIOrderingBaseComponent.ItemState; import org.richfaces.component.util.HtmlUtil; import org.richfaces.model.ListShuttleRowKey; /** * @author Nick Belaevski * */ public abstract class ListShuttleRendererBase extends OrderingComponentRendererBase { protected static final String SELECTION_STATE_VAR_NAME = "selectionState"; public final static String FACET_SOURCE_CAPTION = "sourceCaption"; public final static String FACET_TARGET_CAPTION = "targetCaption"; protected static final OrderingComponentRendererBase.ControlsHelper[] SHUTTLE_HELPERS = ListShuttleControlsHelper.HELPERS; protected static final OrderingComponentRendererBase.ControlsHelper[] TL_HELPERS = OrderingComponentControlsHelper.HELPERS; private static final String MESSAGE_BUNDLE_NAME = OrderingListRendererBase.class.getPackage().getName() + ".listShuttle"; private static class ListShuttleRendererTableHolder extends TableHolder { private boolean source; private Converter converter; public ListShuttleRendererTableHolder(UIDataAdaptor table, Converter converter, boolean source) { super(table); this.converter = converter; this.source = source; } public boolean isSource() { return source; } public Converter getConverter() { return converter; } } public ListShuttleRendererBase() { super(MESSAGE_BUNDLE_NAME); } public void encodeSLCaption(FacesContext context, UIOrderingBaseComponent shuttle) throws IOException { encodeCaption(context, shuttle, FACET_SOURCE_CAPTION, "rich-shuttle-source-caption", ListShuttleControlsHelper.ATTRIBUTE_SOURCE_CAPTION_LABEL); } public void encodeTLCaption(FacesContext context, UIComponent shuttle) throws IOException { encodeCaption(context, shuttle, FACET_TARGET_CAPTION, "rich-shuttle-target-caption", ListShuttleControlsHelper.ATTRIBUTE_TARGET_CAPTION_LABEL); } public void encodeSLHeader(FacesContext context, UIOrderingBaseComponent shuttle) throws IOException { encodeHeader(context, shuttle, "rich-table-header", "rich-shuttle-header-tab-cell", "sourceHeaderClass"); } public void encodeTLHeader(FacesContext context, UIOrderingBaseComponent shuttle) throws IOException { encodeHeader(context, shuttle, "rich-table-header", "rich-shuttle-header-tab-cell", "sourceHeaderClass"); } public boolean isHeaderExists(FacesContext context, UIOrderingBaseComponent component) { return isHeaderExists(context, component, "header"); } protected String encodeRows(FacesContext context, UIOrderingBaseComponent shuttle, boolean source) throws IOException { ResponseWriter writer = context.getResponseWriter(); StringWriter stringWriter = new StringWriter(); context.setResponseWriter(writer.cloneWithWriter(stringWriter)); encodeRows(context, shuttle, new ListShuttleRendererTableHolder(shuttle, getConverter(context, shuttle, true), source)); context.getResponseWriter().flush(); context.setResponseWriter(writer); return stringWriter.getBuffer().toString(); } public void encodeOneRow(FacesContext context, TableHolder holder) throws IOException { UIListShuttle table = (UIListShuttle) holder.getTable(); ListShuttleRendererTableHolder shuttleRendererTableHolder = (ListShuttleRendererTableHolder) holder; ListShuttleRowKey listShuttleRowKey = (ListShuttleRowKey) table.getRowKey(); if (listShuttleRowKey != null) { boolean source = shuttleRendererTableHolder.isSource(); if (source == listShuttleRowKey.isFacadeSource()) { ResponseWriter writer = context.getResponseWriter(); String clientId = table.getClientId(context); writer.startElement(HTML.TR_ELEMENT, table); writer.writeAttribute("id", clientId, null); StringBuffer rowClassName = new StringBuffer(); StringBuffer cellClassName = new StringBuffer(); if (source) { rowClassName.append("rich-shuttle-source-row"); cellClassName.append("rich-shuttle-source-cell"); } else { rowClassName.append("rich-shuttle-target-row"); cellClassName.append("rich-shuttle-target-cell"); } String rowClass = holder.getRowClass(); if (rowClass != null) { rowClassName.append(' '); rowClassName.append(rowClass); } ComponentVariables variables = ComponentsVariableResolver.getVariables(this, table); SelectionState selectionState = (SelectionState) variables.getVariable(SELECTION_STATE_VAR_NAME); ItemState itemState = getItemState(context, table, variables); boolean active = itemState.isActive(); boolean selected = itemState.isSelected(); selectionState.addState(selected); if (selected) { if (source) { rowClassName.append(" rich-shuttle-source-row-selected"); cellClassName.append(" rich-shuttle-source-cell-selected"); } else { rowClassName.append(" rich-shuttle-target-row-selected"); cellClassName.append(" rich-shuttle-target-cell-selected"); } } writer.writeAttribute("class", rowClassName.toString(), null); int colCounter = 0; boolean columnRendered = false; for (Iterator iterator = table.columns(); iterator.hasNext();) { UIComponent component = (UIComponent) iterator.next(); if (component.isRendered()) { writer.startElement(HTML.td_ELEM, table); Object width = component.getAttributes().get("width"); if (width != null) { writer.writeAttribute("style", "width: " + HtmlUtil.qualifySize(width.toString()), null); } String columnClass = holder.getColumnClass(colCounter); if (columnClass != null) { writer.writeAttribute("class", cellClassName.toString().concat(" " + columnClass), null); } else { writer.writeAttribute("class", cellClassName.toString(), null); } writer.startElement(HTML.IMG_ELEMENT, table); writer.writeAttribute(HTML.src_ATTRIBUTE, getResource("/org/richfaces/renderkit/html/images/spacer.gif").getUri(context, null), null); writer.writeAttribute(HTML.style_ATTRIBUTE, "width:1px;height:1px;", null); writer.writeAttribute(HTML.alt_ATTRIBUTE, " ", null); writer.endElement(HTML.IMG_ELEMENT); renderChildren(context, component); if (!columnRendered) { writer.startElement(HTML.INPUT_ELEM, table); writer.writeAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN, null); + writer.writeAttribute(HTML.autocomplete_ATTRIBUTE, "off", null); writer.writeAttribute(HTML.NAME_ATTRIBUTE, table.getBaseClientId(context), null); StringBuffer value = new StringBuffer(); if (selected) { value.append('s'); } if (active) { value.append('a'); } value.append(table.getRowKey()); value.append(':'); value.append(shuttleRendererTableHolder.getConverter().getAsString(context, table, table.getRowData())); writer.writeAttribute(HTML.value_ATTRIBUTE, value.toString(), null); writer.writeAttribute(HTML.id_ATTRIBUTE, clientId + "StateInput", null); writer.endElement(HTML.INPUT_ELEM); columnRendered = true; } writer.endElement(HTML.td_ELEM); } colCounter++; } writer.endElement(HTML.TR_ELEMENT); } } } public void encodeChildren(FacesContext context, UIComponent component) throws IOException { if (component.isRendered()) { ResponseWriter writer = context.getResponseWriter(); doEncodeChildren(writer, context, component); } } public void encodeShuttleControlsFacets(FacesContext context, UIOrderingBaseComponent component, SelectionState sourceSelectionState, SelectionState targetSelectionState) throws IOException { boolean needsStrut = true; String clientId = component.getClientId(context); ResponseWriter writer = context.getResponseWriter(); int divider = SHUTTLE_HELPERS.length / 2; for (int i = 0; i < SHUTTLE_HELPERS.length; i++) { SelectionState state = (i < divider ? sourceSelectionState : targetSelectionState); boolean enabled; if (i <= 1 || i >= SHUTTLE_HELPERS.length - 2) { enabled = state.isItemExist(); } else { enabled = state.isSelected(); } if (i % 2 == 1) { enabled = !enabled; } if (SHUTTLE_HELPERS[i].isRendered(context, component)) { needsStrut = false; //proper assumption about helpers ordering encodeControlFacet(context, component, SHUTTLE_HELPERS[i], clientId, writer, enabled, "rich-list-shuttle-button", " rich-shuttle-control"); } } if (needsStrut) { writer.startElement(HTML.SPAN_ELEM, component); writer.endElement(HTML.SPAN_ELEM); } } public void encodeTLControlsFacets(FacesContext context, UIOrderingBaseComponent component, SelectionState selectionState) throws IOException { String clientId = component.getClientId(context); ResponseWriter writer = context.getResponseWriter(); int divider = TL_HELPERS.length / 2; for (int i = 0; i < TL_HELPERS.length; i++) { boolean boundarySelection = i < divider ? selectionState.isFirstSelected() : selectionState.isLastSelected(); boolean enabled = selectionState.isSelected() && !boundarySelection; if (i % 2 == 1) { enabled = !enabled; } if (TL_HELPERS[i].isRendered(context, component)) { //proper assumption about helpers ordering encodeControlFacet(context, component, TL_HELPERS[i], clientId, writer, enabled, "rich-list-shuttle-button", " rich-shuttle-control"); } } } private boolean isEmpty(String s) { return s == null || s.length() == 0; } public void doDecode(FacesContext context, UIComponent component) { UIListShuttle listShuttle = (UIListShuttle) component; String clientId = listShuttle.getBaseClientId(context); ExternalContext externalContext = context.getExternalContext(); Map<String, String[]> requestParameterValuesMap = externalContext .getRequestParameterValuesMap(); String[] strings = (String[]) requestParameterValuesMap.get(clientId); if (strings != null && strings.length != 0) { Set sourceSelection = new HashSet(); Set targetSelection = new HashSet(); Object activeItem = null; Map map = new LinkedHashMap(); boolean facadeSource = true; Converter converter = getConverter(context, listShuttle, false); for (int i = 0; i < strings.length; i++) { String string = strings[i]; if (":".equals(string)) { facadeSource = false; continue; } int idx = string.indexOf(':'); Object value = converter.getAsObject(context, listShuttle, string.substring(idx + 1)); String substring = string.substring(0, idx); idx = 0; boolean source = true; boolean selected = false; if (substring.charAt(idx) == 's') { (facadeSource ? sourceSelection : targetSelection).add(value); idx++; } if (substring.charAt(idx) == 'a') { activeItem = value; idx++; } if (substring.charAt(idx) == 't') { source = false; idx++; } substring = substring.substring(idx); Object key = new ListShuttleRowKey(new Integer(substring), source, facadeSource); map.put(key, value); } listShuttle.setSubmittedStrings(map, sourceSelection, targetSelection, activeItem); } } public String getCaptionDisplay(FacesContext context, UIComponent component) { UIListShuttle shuttle = (UIListShuttle)component; if ((shuttle.getSourceCaptionLabel() != null && !"".equals(shuttle.getSourceCaptionLabel())) || (shuttle.getTargetCaptionLabel() != null && !"".equals(shuttle.getTargetCaptionLabel())) || (shuttle.getFacet("sourceCaption") != null && shuttle.getFacet("sourceCaption").isRendered()) || (shuttle.getFacet("targetCaption") != null && shuttle.getFacet("targetCaption").isRendered())) { return ""; } return "display: none;"; } }
true
true
public void encodeOneRow(FacesContext context, TableHolder holder) throws IOException { UIListShuttle table = (UIListShuttle) holder.getTable(); ListShuttleRendererTableHolder shuttleRendererTableHolder = (ListShuttleRendererTableHolder) holder; ListShuttleRowKey listShuttleRowKey = (ListShuttleRowKey) table.getRowKey(); if (listShuttleRowKey != null) { boolean source = shuttleRendererTableHolder.isSource(); if (source == listShuttleRowKey.isFacadeSource()) { ResponseWriter writer = context.getResponseWriter(); String clientId = table.getClientId(context); writer.startElement(HTML.TR_ELEMENT, table); writer.writeAttribute("id", clientId, null); StringBuffer rowClassName = new StringBuffer(); StringBuffer cellClassName = new StringBuffer(); if (source) { rowClassName.append("rich-shuttle-source-row"); cellClassName.append("rich-shuttle-source-cell"); } else { rowClassName.append("rich-shuttle-target-row"); cellClassName.append("rich-shuttle-target-cell"); } String rowClass = holder.getRowClass(); if (rowClass != null) { rowClassName.append(' '); rowClassName.append(rowClass); } ComponentVariables variables = ComponentsVariableResolver.getVariables(this, table); SelectionState selectionState = (SelectionState) variables.getVariable(SELECTION_STATE_VAR_NAME); ItemState itemState = getItemState(context, table, variables); boolean active = itemState.isActive(); boolean selected = itemState.isSelected(); selectionState.addState(selected); if (selected) { if (source) { rowClassName.append(" rich-shuttle-source-row-selected"); cellClassName.append(" rich-shuttle-source-cell-selected"); } else { rowClassName.append(" rich-shuttle-target-row-selected"); cellClassName.append(" rich-shuttle-target-cell-selected"); } } writer.writeAttribute("class", rowClassName.toString(), null); int colCounter = 0; boolean columnRendered = false; for (Iterator iterator = table.columns(); iterator.hasNext();) { UIComponent component = (UIComponent) iterator.next(); if (component.isRendered()) { writer.startElement(HTML.td_ELEM, table); Object width = component.getAttributes().get("width"); if (width != null) { writer.writeAttribute("style", "width: " + HtmlUtil.qualifySize(width.toString()), null); } String columnClass = holder.getColumnClass(colCounter); if (columnClass != null) { writer.writeAttribute("class", cellClassName.toString().concat(" " + columnClass), null); } else { writer.writeAttribute("class", cellClassName.toString(), null); } writer.startElement(HTML.IMG_ELEMENT, table); writer.writeAttribute(HTML.src_ATTRIBUTE, getResource("/org/richfaces/renderkit/html/images/spacer.gif").getUri(context, null), null); writer.writeAttribute(HTML.style_ATTRIBUTE, "width:1px;height:1px;", null); writer.writeAttribute(HTML.alt_ATTRIBUTE, " ", null); writer.endElement(HTML.IMG_ELEMENT); renderChildren(context, component); if (!columnRendered) { writer.startElement(HTML.INPUT_ELEM, table); writer.writeAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN, null); writer.writeAttribute(HTML.NAME_ATTRIBUTE, table.getBaseClientId(context), null); StringBuffer value = new StringBuffer(); if (selected) { value.append('s'); } if (active) { value.append('a'); } value.append(table.getRowKey()); value.append(':'); value.append(shuttleRendererTableHolder.getConverter().getAsString(context, table, table.getRowData())); writer.writeAttribute(HTML.value_ATTRIBUTE, value.toString(), null); writer.writeAttribute(HTML.id_ATTRIBUTE, clientId + "StateInput", null); writer.endElement(HTML.INPUT_ELEM); columnRendered = true; } writer.endElement(HTML.td_ELEM); } colCounter++; } writer.endElement(HTML.TR_ELEMENT); } } }
public void encodeOneRow(FacesContext context, TableHolder holder) throws IOException { UIListShuttle table = (UIListShuttle) holder.getTable(); ListShuttleRendererTableHolder shuttleRendererTableHolder = (ListShuttleRendererTableHolder) holder; ListShuttleRowKey listShuttleRowKey = (ListShuttleRowKey) table.getRowKey(); if (listShuttleRowKey != null) { boolean source = shuttleRendererTableHolder.isSource(); if (source == listShuttleRowKey.isFacadeSource()) { ResponseWriter writer = context.getResponseWriter(); String clientId = table.getClientId(context); writer.startElement(HTML.TR_ELEMENT, table); writer.writeAttribute("id", clientId, null); StringBuffer rowClassName = new StringBuffer(); StringBuffer cellClassName = new StringBuffer(); if (source) { rowClassName.append("rich-shuttle-source-row"); cellClassName.append("rich-shuttle-source-cell"); } else { rowClassName.append("rich-shuttle-target-row"); cellClassName.append("rich-shuttle-target-cell"); } String rowClass = holder.getRowClass(); if (rowClass != null) { rowClassName.append(' '); rowClassName.append(rowClass); } ComponentVariables variables = ComponentsVariableResolver.getVariables(this, table); SelectionState selectionState = (SelectionState) variables.getVariable(SELECTION_STATE_VAR_NAME); ItemState itemState = getItemState(context, table, variables); boolean active = itemState.isActive(); boolean selected = itemState.isSelected(); selectionState.addState(selected); if (selected) { if (source) { rowClassName.append(" rich-shuttle-source-row-selected"); cellClassName.append(" rich-shuttle-source-cell-selected"); } else { rowClassName.append(" rich-shuttle-target-row-selected"); cellClassName.append(" rich-shuttle-target-cell-selected"); } } writer.writeAttribute("class", rowClassName.toString(), null); int colCounter = 0; boolean columnRendered = false; for (Iterator iterator = table.columns(); iterator.hasNext();) { UIComponent component = (UIComponent) iterator.next(); if (component.isRendered()) { writer.startElement(HTML.td_ELEM, table); Object width = component.getAttributes().get("width"); if (width != null) { writer.writeAttribute("style", "width: " + HtmlUtil.qualifySize(width.toString()), null); } String columnClass = holder.getColumnClass(colCounter); if (columnClass != null) { writer.writeAttribute("class", cellClassName.toString().concat(" " + columnClass), null); } else { writer.writeAttribute("class", cellClassName.toString(), null); } writer.startElement(HTML.IMG_ELEMENT, table); writer.writeAttribute(HTML.src_ATTRIBUTE, getResource("/org/richfaces/renderkit/html/images/spacer.gif").getUri(context, null), null); writer.writeAttribute(HTML.style_ATTRIBUTE, "width:1px;height:1px;", null); writer.writeAttribute(HTML.alt_ATTRIBUTE, " ", null); writer.endElement(HTML.IMG_ELEMENT); renderChildren(context, component); if (!columnRendered) { writer.startElement(HTML.INPUT_ELEM, table); writer.writeAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN, null); writer.writeAttribute(HTML.autocomplete_ATTRIBUTE, "off", null); writer.writeAttribute(HTML.NAME_ATTRIBUTE, table.getBaseClientId(context), null); StringBuffer value = new StringBuffer(); if (selected) { value.append('s'); } if (active) { value.append('a'); } value.append(table.getRowKey()); value.append(':'); value.append(shuttleRendererTableHolder.getConverter().getAsString(context, table, table.getRowData())); writer.writeAttribute(HTML.value_ATTRIBUTE, value.toString(), null); writer.writeAttribute(HTML.id_ATTRIBUTE, clientId + "StateInput", null); writer.endElement(HTML.INPUT_ELEM); columnRendered = true; } writer.endElement(HTML.td_ELEM); } colCounter++; } writer.endElement(HTML.TR_ELEMENT); } } }
diff --git a/src/model/MoveFirstStrategy.java b/src/model/MoveFirstStrategy.java index 371994f..a2658de 100644 --- a/src/model/MoveFirstStrategy.java +++ b/src/model/MoveFirstStrategy.java @@ -1,45 +1,48 @@ package model; import java.util.ArrayList; public class MoveFirstStrategy implements Strategy { public Pawn getNextMove(int currentRoll, ArrayList<Pawn> moveablePawns, Field[] gameBoard) { //normalize pawn position based on home + if(moveablePawns.isEmpty()){ + return null; + } int startPos = moveablePawns.get(0).getOwner().getStartPosition(); Pawn pawn = null; Integer currentVal = null; //go through movable pawns for(Pawn temp : moveablePawns){ //if pawn to return has not be set and the pawn is movable, replace the pawn with the current one Integer value = startPos - temp.getPosition(); if(pawn == null){ pawn = temp; currentVal = value; } if(value == 0 || temp.getPosition() >= 40){ return temp; } if(value > 0 && currentVal > 0){ if(value > currentVal){ currentVal = value; pawn = temp; } }else if(value > 0 && currentVal < 0){ currentVal = value; pawn = temp; }else if(value < 0 && currentVal < 0){ if(value < currentVal){ currentVal = value; pawn = temp; } } } return pawn; } }
true
true
public Pawn getNextMove(int currentRoll, ArrayList<Pawn> moveablePawns, Field[] gameBoard) { //normalize pawn position based on home int startPos = moveablePawns.get(0).getOwner().getStartPosition(); Pawn pawn = null; Integer currentVal = null; //go through movable pawns for(Pawn temp : moveablePawns){ //if pawn to return has not be set and the pawn is movable, replace the pawn with the current one Integer value = startPos - temp.getPosition(); if(pawn == null){ pawn = temp; currentVal = value; } if(value == 0 || temp.getPosition() >= 40){ return temp; } if(value > 0 && currentVal > 0){ if(value > currentVal){ currentVal = value; pawn = temp; } }else if(value > 0 && currentVal < 0){ currentVal = value; pawn = temp; }else if(value < 0 && currentVal < 0){ if(value < currentVal){ currentVal = value; pawn = temp; } } } return pawn; }
public Pawn getNextMove(int currentRoll, ArrayList<Pawn> moveablePawns, Field[] gameBoard) { //normalize pawn position based on home if(moveablePawns.isEmpty()){ return null; } int startPos = moveablePawns.get(0).getOwner().getStartPosition(); Pawn pawn = null; Integer currentVal = null; //go through movable pawns for(Pawn temp : moveablePawns){ //if pawn to return has not be set and the pawn is movable, replace the pawn with the current one Integer value = startPos - temp.getPosition(); if(pawn == null){ pawn = temp; currentVal = value; } if(value == 0 || temp.getPosition() >= 40){ return temp; } if(value > 0 && currentVal > 0){ if(value > currentVal){ currentVal = value; pawn = temp; } }else if(value > 0 && currentVal < 0){ currentVal = value; pawn = temp; }else if(value < 0 && currentVal < 0){ if(value < currentVal){ currentVal = value; pawn = temp; } } } return pawn; }
diff --git a/src/ee/alkohol/juks/sirvid/exporters/ExporterSVG.java b/src/ee/alkohol/juks/sirvid/exporters/ExporterSVG.java index 1e09d36..d2d9d14 100644 --- a/src/ee/alkohol/juks/sirvid/exporters/ExporterSVG.java +++ b/src/ee/alkohol/juks/sirvid/exporters/ExporterSVG.java @@ -1,38 +1,38 @@ package ee.alkohol.juks.sirvid.exporters; import ee.alkohol.juks.sirvid.containers.ICalculator; import ee.alkohol.juks.sirvid.containers.ICalendar; public class ExporterSVG extends Exporter { public ExporterSVG () { super(); this.setFileExtension(".svg"); this.setMimeType("image/svg+xml"); } @Override public String generate(ICalculator icalendar) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"); sb.append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"); - sb.append("<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n"); + sb.append("<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" >\n"); sb.append("<style type=\"text/css\">\n"); sb.append("<![CDATA[\n"); sb.append("line {stroke: black; stroke-width : 1; }\n"); sb.append("polyline, path { stroke: black; stroke-width : 1; fill: none; }\n"); sb.append("]]>\n"); sb.append("</style>\n"); sb.append("<title>"); sb.append(icalendar.iCal.iCalBody.get(ICalendar.Keys.CALENDAR_NAME).value); sb.append("</title>\n"); sb.append("</svg>"); return sb.toString(); } }
true
true
public String generate(ICalculator icalendar) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"); sb.append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"); sb.append("<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n"); sb.append("<style type=\"text/css\">\n"); sb.append("<![CDATA[\n"); sb.append("line {stroke: black; stroke-width : 1; }\n"); sb.append("polyline, path { stroke: black; stroke-width : 1; fill: none; }\n"); sb.append("]]>\n"); sb.append("</style>\n"); sb.append("<title>"); sb.append(icalendar.iCal.iCalBody.get(ICalendar.Keys.CALENDAR_NAME).value); sb.append("</title>\n"); sb.append("</svg>"); return sb.toString(); }
public String generate(ICalculator icalendar) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"); sb.append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"); sb.append("<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" >\n"); sb.append("<style type=\"text/css\">\n"); sb.append("<![CDATA[\n"); sb.append("line {stroke: black; stroke-width : 1; }\n"); sb.append("polyline, path { stroke: black; stroke-width : 1; fill: none; }\n"); sb.append("]]>\n"); sb.append("</style>\n"); sb.append("<title>"); sb.append(icalendar.iCal.iCalBody.get(ICalendar.Keys.CALENDAR_NAME).value); sb.append("</title>\n"); sb.append("</svg>"); return sb.toString(); }
diff --git a/core/src/main/java/org/apache/mahout/vectorizer/SparseVectorsFromSequenceFiles.java b/core/src/main/java/org/apache/mahout/vectorizer/SparseVectorsFromSequenceFiles.java index c4aa9be1..bef19f11 100644 --- a/core/src/main/java/org/apache/mahout/vectorizer/SparseVectorsFromSequenceFiles.java +++ b/core/src/main/java/org/apache/mahout/vectorizer/SparseVectorsFromSequenceFiles.java @@ -1,331 +1,332 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.vectorizer; import java.util.List; import org.apache.commons.cli2.CommandLine; import org.apache.commons.cli2.Group; import org.apache.commons.cli2.Option; import org.apache.commons.cli2.OptionException; import org.apache.commons.cli2.builder.ArgumentBuilder; import org.apache.commons.cli2.builder.DefaultOptionBuilder; import org.apache.commons.cli2.builder.GroupBuilder; import org.apache.commons.cli2.commandline.Parser; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.ToolRunner; import org.apache.lucene.analysis.Analyzer; import org.apache.mahout.common.AbstractJob; import org.apache.mahout.common.ClassUtils; import org.apache.mahout.common.CommandLineUtil; import org.apache.mahout.common.HadoopUtil; import org.apache.mahout.common.Pair; import org.apache.mahout.common.commandline.DefaultOptionCreator; import org.apache.mahout.math.hadoop.stats.BasicStats; import org.apache.mahout.vectorizer.collocations.llr.LLRReducer; import org.apache.mahout.vectorizer.common.PartialVectorMerger; import org.apache.mahout.vectorizer.tfidf.TFIDFConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Converts a given set of sequence files into SparseVectors */ public final class SparseVectorsFromSequenceFiles extends AbstractJob { private static final Logger log = LoggerFactory.getLogger(SparseVectorsFromSequenceFiles.class); public static void main(String[] args) throws Exception { ToolRunner.run(new SparseVectorsFromSequenceFiles(), args); } @Override public int run(String[] args) throws Exception { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputDirOpt = DefaultOptionCreator.inputOption().create(); Option outputDirOpt = DefaultOptionCreator.outputOption().create(); Option minSupportOpt = obuilder.withLongName("minSupport").withArgument( abuilder.withName("minSupport").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional) Minimum Support. Default Value: 2").withShortName("s").create(); Option analyzerNameOpt = obuilder.withLongName("analyzerName").withArgument( abuilder.withName("analyzerName").withMinimum(1).withMaximum(1).create()).withDescription( "The class name of the analyzer").withShortName("a").create(); Option chunkSizeOpt = obuilder.withLongName("chunkSize").withArgument( abuilder.withName("chunkSize").withMinimum(1).withMaximum(1).create()).withDescription( "The chunkSize in MegaBytes. 100-10000 MB").withShortName("chunk").create(); Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument( abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription( "The kind of weight to use. Currently TF or TFIDF").withShortName("wt").create(); Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument( abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription( "The minimum document frequency. Default is 1").withShortName("md").create(); Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument( abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription( "The max percentage of docs for the DF. Can be used to remove really high frequency terms." + " Expressed as an integer between 0 and 100. Default is 99. If maxDFSigma is also set, it will override this value.").withShortName("x").create(); Option maxDFSigmaOpt = obuilder.withLongName("maxDFSigma").withRequired(false).withArgument( abuilder.withName("maxDFSigma").withMinimum(1).withMaximum(1).create()).withDescription( "What portion of the tf (tf-idf) vectors to be used, expressed in times the standard deviation (sigma) of the document frequencies of these vectors." + " Can be used to remove really high frequency terms." + " Expressed as a double value. Good value to be specified is 3.0. In case the value is less then 0 no vectors " + "will be filtered out. Default is -1.0. Overrides maxDFPercent").withShortName("xs").create(); Option minLLROpt = obuilder.withLongName("minLLR").withRequired(false).withArgument( abuilder.withName("minLLR").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional)The minimum Log Likelihood Ratio(Float) Default is " + LLRReducer.DEFAULT_MIN_LLR) .withShortName("ml").create(); Option numReduceTasksOpt = obuilder.withLongName("numReducers").withArgument( abuilder.withName("numReducers").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional) Number of reduce tasks. Default Value: 1").withShortName("nr").create(); Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument( abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription( "The norm to use, expressed as either a float or \"INF\" if you want to use the Infinite norm. " + "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create(); Option logNormalizeOpt = obuilder.withLongName("logNormalize").withRequired(false) .withDescription( "(Optional) Whether output vectors should be logNormalize. If set true else false") .withShortName("lnorm").create(); Option maxNGramSizeOpt = obuilder.withLongName("maxNGramSize").withRequired(false).withArgument( abuilder.withName("ngramSize").withMinimum(1).withMaximum(1).create()) .withDescription( "(Optional) The maximum size of ngrams to create" + " (2 = bigrams, 3 = trigrams, etc) Default Value:1").withShortName("ng").create(); Option sequentialAccessVectorOpt = obuilder.withLongName("sequentialAccessVector").withRequired(false) .withDescription( "(Optional) Whether output vectors should be SequentialAccessVectors. If set true else false") .withShortName("seq").create(); Option namedVectorOpt = obuilder.withLongName("namedVector").withRequired(false) .withDescription( "(Optional) Whether output vectors should be NamedVectors. If set true else false") .withShortName("nv").create(); Option overwriteOutput = obuilder.withLongName("overwrite").withRequired(false).withDescription( "If set, overwrite the output directory").withShortName("ow").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(minSupportOpt).withOption(analyzerNameOpt) .withOption(chunkSizeOpt).withOption(outputDirOpt).withOption(inputDirOpt).withOption(minDFOpt) .withOption(maxDFSigmaOpt).withOption(maxDFPercentOpt).withOption(weightOpt).withOption(powerOpt).withOption(minLLROpt) .withOption(numReduceTasksOpt).withOption(maxNGramSizeOpt).withOption(overwriteOutput) .withOption(helpOpt).withOption(sequentialAccessVectorOpt).withOption(namedVectorOpt) .withOption(logNormalizeOpt) .create(); try { Parser parser = new Parser(); parser.setGroup(group); parser.setHelpOption(helpOpt); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return -1; } Path inputDir = new Path((String) cmdLine.getValue(inputDirOpt)); Path outputDir = new Path((String) cmdLine.getValue(outputDirOpt)); int chunkSize = 100; if (cmdLine.hasOption(chunkSizeOpt)) { chunkSize = Integer.parseInt((String) cmdLine.getValue(chunkSizeOpt)); } int minSupport = 2; if (cmdLine.hasOption(minSupportOpt)) { String minSupportString = (String) cmdLine.getValue(minSupportOpt); minSupport = Integer.parseInt(minSupportString); } int maxNGramSize = 1; if (cmdLine.hasOption(maxNGramSizeOpt)) { try { maxNGramSize = Integer.parseInt(cmdLine.getValue(maxNGramSizeOpt).toString()); } catch (NumberFormatException ex) { log.warn("Could not parse ngram size option"); } } log.info("Maximum n-gram size is: {}", maxNGramSize); if (cmdLine.hasOption(overwriteOutput)) { HadoopUtil.delete(getConf(), outputDir); } float minLLRValue = LLRReducer.DEFAULT_MIN_LLR; if (cmdLine.hasOption(minLLROpt)) { minLLRValue = Float.parseFloat(cmdLine.getValue(minLLROpt).toString()); } log.info("Minimum LLR value: {}", minLLRValue); int reduceTasks = 1; if (cmdLine.hasOption(numReduceTasksOpt)) { reduceTasks = Integer.parseInt(cmdLine.getValue(numReduceTasksOpt).toString()); } log.info("Number of reduce tasks: {}", reduceTasks); Class<? extends Analyzer> analyzerClass = DefaultAnalyzer.class; if (cmdLine.hasOption(analyzerNameOpt)) { String className = cmdLine.getValue(analyzerNameOpt).toString(); analyzerClass = Class.forName(className).asSubclass(Analyzer.class); // try instantiating it, b/c there isn't any point in setting it if // you can't instantiate it ClassUtils.instantiateAs(analyzerClass, Analyzer.class); } boolean processIdf; if (cmdLine.hasOption(weightOpt)) { String wString = cmdLine.getValue(weightOpt).toString(); if ("tf".equalsIgnoreCase(wString)) { processIdf = false; } else if ("tfidf".equalsIgnoreCase(wString)) { processIdf = true; } else { throw new OptionException(weightOpt); } } else { processIdf = true; } int minDf = 1; if (cmdLine.hasOption(minDFOpt)) { minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString()); } int maxDFPercent = 99; if (cmdLine.hasOption(maxDFPercentOpt)) { maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString()); } double maxDFSigma = -1.0; if (cmdLine.hasOption(maxDFSigmaOpt)) { maxDFSigma = Double.parseDouble(cmdLine.getValue(maxDFSigmaOpt).toString()); } float norm = PartialVectorMerger.NO_NORMALIZING; if (cmdLine.hasOption(powerOpt)) { String power = cmdLine.getValue(powerOpt).toString(); if ("INF".equals(power)) { norm = Float.POSITIVE_INFINITY; } else { norm = Float.parseFloat(power); } } boolean logNormalize = false; if (cmdLine.hasOption(logNormalizeOpt)) { logNormalize = true; } Configuration conf = getConf(); Path tokenizedPath = new Path(outputDir, DocumentProcessor.TOKENIZED_DOCUMENT_OUTPUT_FOLDER); //TODO: move this into DictionaryVectorizer , and then fold SparseVectorsFrom with EncodedVectorsFrom to have one framework for all of this. DocumentProcessor.tokenizeDocuments(inputDir, analyzerClass, tokenizedPath, conf); boolean sequentialAccessOutput = false; if (cmdLine.hasOption(sequentialAccessVectorOpt)) { sequentialAccessOutput = true; } boolean namedVectors = false; if (cmdLine.hasOption(namedVectorOpt)) { namedVectors = true; } boolean shouldPrune = maxDFSigma >=0.0; String tfDirName = shouldPrune ? DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER+"-toprune" : DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER; if (!processIdf) { DictionaryVectorizer.createTermFrequencyVectors(tokenizedPath, outputDir, tfDirName, conf, minSupport, maxNGramSize, minLLRValue, norm, logNormalize, reduceTasks, chunkSize, sequentialAccessOutput, namedVectors); } else { DictionaryVectorizer.createTermFrequencyVectors(tokenizedPath, outputDir, tfDirName, conf, minSupport, maxNGramSize, minLLRValue, -1.0f, false, reduceTasks, chunkSize, sequentialAccessOutput, namedVectors); } Pair<Long[], List<Path>> docFrequenciesFeatures = null; // Should document frequency features be processed if (shouldPrune || processIdf) { docFrequenciesFeatures = TFIDFConverter.calculateDF(new Path(outputDir, tfDirName), outputDir, conf, chunkSize); } long maxDF = maxDFPercent;//if we are pruning by std dev, then this will get changed if (shouldPrune) { Path dfDir = new Path(outputDir, TFIDFConverter.WORDCOUNT_OUTPUT_FOLDER); Path stdCalcDir = new Path(outputDir, HighDFWordsPruner.STD_CALC_DIR); // Calculate the standard deviation - double stdDev = BasicStats.stdDevForGivenMean(dfDir, stdCalcDir, 0.0D, conf); - maxDF = (int) (maxDFSigma * stdDev); + double stdDev = BasicStats.stdDevForGivenMean(dfDir, stdCalcDir, 0.0, conf); + long vectorCount = docFrequenciesFeatures.getFirst()[1]; + maxDF = (int) (100.0 * maxDFSigma * stdDev / vectorCount); // Prune the term frequency vectors Path tfDir = new Path(outputDir, tfDirName); Path prunedTFDir = new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER); Path prunedPartialTFDir = new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER + "-partial"); if (processIdf) { HighDFWordsPruner.pruneVectors(tfDir, prunedTFDir, prunedPartialTFDir, maxDF, conf, docFrequenciesFeatures, -1.0f, false, reduceTasks); } else { HighDFWordsPruner.pruneVectors(tfDir, prunedTFDir, prunedPartialTFDir, maxDF, conf, docFrequenciesFeatures, norm, logNormalize, reduceTasks); } HadoopUtil.delete(new Configuration(conf), tfDir); } if (processIdf){ TFIDFConverter.processTfIdf( new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER), outputDir, conf, docFrequenciesFeatures, minDf, maxDF, norm, logNormalize, sequentialAccessOutput, namedVectors, reduceTasks); } } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } return 0; } }
true
true
public int run(String[] args) throws Exception { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputDirOpt = DefaultOptionCreator.inputOption().create(); Option outputDirOpt = DefaultOptionCreator.outputOption().create(); Option minSupportOpt = obuilder.withLongName("minSupport").withArgument( abuilder.withName("minSupport").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional) Minimum Support. Default Value: 2").withShortName("s").create(); Option analyzerNameOpt = obuilder.withLongName("analyzerName").withArgument( abuilder.withName("analyzerName").withMinimum(1).withMaximum(1).create()).withDescription( "The class name of the analyzer").withShortName("a").create(); Option chunkSizeOpt = obuilder.withLongName("chunkSize").withArgument( abuilder.withName("chunkSize").withMinimum(1).withMaximum(1).create()).withDescription( "The chunkSize in MegaBytes. 100-10000 MB").withShortName("chunk").create(); Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument( abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription( "The kind of weight to use. Currently TF or TFIDF").withShortName("wt").create(); Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument( abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription( "The minimum document frequency. Default is 1").withShortName("md").create(); Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument( abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription( "The max percentage of docs for the DF. Can be used to remove really high frequency terms." + " Expressed as an integer between 0 and 100. Default is 99. If maxDFSigma is also set, it will override this value.").withShortName("x").create(); Option maxDFSigmaOpt = obuilder.withLongName("maxDFSigma").withRequired(false).withArgument( abuilder.withName("maxDFSigma").withMinimum(1).withMaximum(1).create()).withDescription( "What portion of the tf (tf-idf) vectors to be used, expressed in times the standard deviation (sigma) of the document frequencies of these vectors." + " Can be used to remove really high frequency terms." + " Expressed as a double value. Good value to be specified is 3.0. In case the value is less then 0 no vectors " + "will be filtered out. Default is -1.0. Overrides maxDFPercent").withShortName("xs").create(); Option minLLROpt = obuilder.withLongName("minLLR").withRequired(false).withArgument( abuilder.withName("minLLR").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional)The minimum Log Likelihood Ratio(Float) Default is " + LLRReducer.DEFAULT_MIN_LLR) .withShortName("ml").create(); Option numReduceTasksOpt = obuilder.withLongName("numReducers").withArgument( abuilder.withName("numReducers").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional) Number of reduce tasks. Default Value: 1").withShortName("nr").create(); Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument( abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription( "The norm to use, expressed as either a float or \"INF\" if you want to use the Infinite norm. " + "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create(); Option logNormalizeOpt = obuilder.withLongName("logNormalize").withRequired(false) .withDescription( "(Optional) Whether output vectors should be logNormalize. If set true else false") .withShortName("lnorm").create(); Option maxNGramSizeOpt = obuilder.withLongName("maxNGramSize").withRequired(false).withArgument( abuilder.withName("ngramSize").withMinimum(1).withMaximum(1).create()) .withDescription( "(Optional) The maximum size of ngrams to create" + " (2 = bigrams, 3 = trigrams, etc) Default Value:1").withShortName("ng").create(); Option sequentialAccessVectorOpt = obuilder.withLongName("sequentialAccessVector").withRequired(false) .withDescription( "(Optional) Whether output vectors should be SequentialAccessVectors. If set true else false") .withShortName("seq").create(); Option namedVectorOpt = obuilder.withLongName("namedVector").withRequired(false) .withDescription( "(Optional) Whether output vectors should be NamedVectors. If set true else false") .withShortName("nv").create(); Option overwriteOutput = obuilder.withLongName("overwrite").withRequired(false).withDescription( "If set, overwrite the output directory").withShortName("ow").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(minSupportOpt).withOption(analyzerNameOpt) .withOption(chunkSizeOpt).withOption(outputDirOpt).withOption(inputDirOpt).withOption(minDFOpt) .withOption(maxDFSigmaOpt).withOption(maxDFPercentOpt).withOption(weightOpt).withOption(powerOpt).withOption(minLLROpt) .withOption(numReduceTasksOpt).withOption(maxNGramSizeOpt).withOption(overwriteOutput) .withOption(helpOpt).withOption(sequentialAccessVectorOpt).withOption(namedVectorOpt) .withOption(logNormalizeOpt) .create(); try { Parser parser = new Parser(); parser.setGroup(group); parser.setHelpOption(helpOpt); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return -1; } Path inputDir = new Path((String) cmdLine.getValue(inputDirOpt)); Path outputDir = new Path((String) cmdLine.getValue(outputDirOpt)); int chunkSize = 100; if (cmdLine.hasOption(chunkSizeOpt)) { chunkSize = Integer.parseInt((String) cmdLine.getValue(chunkSizeOpt)); } int minSupport = 2; if (cmdLine.hasOption(minSupportOpt)) { String minSupportString = (String) cmdLine.getValue(minSupportOpt); minSupport = Integer.parseInt(minSupportString); } int maxNGramSize = 1; if (cmdLine.hasOption(maxNGramSizeOpt)) { try { maxNGramSize = Integer.parseInt(cmdLine.getValue(maxNGramSizeOpt).toString()); } catch (NumberFormatException ex) { log.warn("Could not parse ngram size option"); } } log.info("Maximum n-gram size is: {}", maxNGramSize); if (cmdLine.hasOption(overwriteOutput)) { HadoopUtil.delete(getConf(), outputDir); } float minLLRValue = LLRReducer.DEFAULT_MIN_LLR; if (cmdLine.hasOption(minLLROpt)) { minLLRValue = Float.parseFloat(cmdLine.getValue(minLLROpt).toString()); } log.info("Minimum LLR value: {}", minLLRValue); int reduceTasks = 1; if (cmdLine.hasOption(numReduceTasksOpt)) { reduceTasks = Integer.parseInt(cmdLine.getValue(numReduceTasksOpt).toString()); } log.info("Number of reduce tasks: {}", reduceTasks); Class<? extends Analyzer> analyzerClass = DefaultAnalyzer.class; if (cmdLine.hasOption(analyzerNameOpt)) { String className = cmdLine.getValue(analyzerNameOpt).toString(); analyzerClass = Class.forName(className).asSubclass(Analyzer.class); // try instantiating it, b/c there isn't any point in setting it if // you can't instantiate it ClassUtils.instantiateAs(analyzerClass, Analyzer.class); } boolean processIdf; if (cmdLine.hasOption(weightOpt)) { String wString = cmdLine.getValue(weightOpt).toString(); if ("tf".equalsIgnoreCase(wString)) { processIdf = false; } else if ("tfidf".equalsIgnoreCase(wString)) { processIdf = true; } else { throw new OptionException(weightOpt); } } else { processIdf = true; } int minDf = 1; if (cmdLine.hasOption(minDFOpt)) { minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString()); } int maxDFPercent = 99; if (cmdLine.hasOption(maxDFPercentOpt)) { maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString()); } double maxDFSigma = -1.0; if (cmdLine.hasOption(maxDFSigmaOpt)) { maxDFSigma = Double.parseDouble(cmdLine.getValue(maxDFSigmaOpt).toString()); } float norm = PartialVectorMerger.NO_NORMALIZING; if (cmdLine.hasOption(powerOpt)) { String power = cmdLine.getValue(powerOpt).toString(); if ("INF".equals(power)) { norm = Float.POSITIVE_INFINITY; } else { norm = Float.parseFloat(power); } } boolean logNormalize = false; if (cmdLine.hasOption(logNormalizeOpt)) { logNormalize = true; } Configuration conf = getConf(); Path tokenizedPath = new Path(outputDir, DocumentProcessor.TOKENIZED_DOCUMENT_OUTPUT_FOLDER); //TODO: move this into DictionaryVectorizer , and then fold SparseVectorsFrom with EncodedVectorsFrom to have one framework for all of this. DocumentProcessor.tokenizeDocuments(inputDir, analyzerClass, tokenizedPath, conf); boolean sequentialAccessOutput = false; if (cmdLine.hasOption(sequentialAccessVectorOpt)) { sequentialAccessOutput = true; } boolean namedVectors = false; if (cmdLine.hasOption(namedVectorOpt)) { namedVectors = true; } boolean shouldPrune = maxDFSigma >=0.0; String tfDirName = shouldPrune ? DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER+"-toprune" : DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER; if (!processIdf) { DictionaryVectorizer.createTermFrequencyVectors(tokenizedPath, outputDir, tfDirName, conf, minSupport, maxNGramSize, minLLRValue, norm, logNormalize, reduceTasks, chunkSize, sequentialAccessOutput, namedVectors); } else { DictionaryVectorizer.createTermFrequencyVectors(tokenizedPath, outputDir, tfDirName, conf, minSupport, maxNGramSize, minLLRValue, -1.0f, false, reduceTasks, chunkSize, sequentialAccessOutput, namedVectors); } Pair<Long[], List<Path>> docFrequenciesFeatures = null; // Should document frequency features be processed if (shouldPrune || processIdf) { docFrequenciesFeatures = TFIDFConverter.calculateDF(new Path(outputDir, tfDirName), outputDir, conf, chunkSize); } long maxDF = maxDFPercent;//if we are pruning by std dev, then this will get changed if (shouldPrune) { Path dfDir = new Path(outputDir, TFIDFConverter.WORDCOUNT_OUTPUT_FOLDER); Path stdCalcDir = new Path(outputDir, HighDFWordsPruner.STD_CALC_DIR); // Calculate the standard deviation double stdDev = BasicStats.stdDevForGivenMean(dfDir, stdCalcDir, 0.0D, conf); maxDF = (int) (maxDFSigma * stdDev); // Prune the term frequency vectors Path tfDir = new Path(outputDir, tfDirName); Path prunedTFDir = new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER); Path prunedPartialTFDir = new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER + "-partial"); if (processIdf) { HighDFWordsPruner.pruneVectors(tfDir, prunedTFDir, prunedPartialTFDir, maxDF, conf, docFrequenciesFeatures, -1.0f, false, reduceTasks); } else { HighDFWordsPruner.pruneVectors(tfDir, prunedTFDir, prunedPartialTFDir, maxDF, conf, docFrequenciesFeatures, norm, logNormalize, reduceTasks); } HadoopUtil.delete(new Configuration(conf), tfDir); } if (processIdf){ TFIDFConverter.processTfIdf( new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER), outputDir, conf, docFrequenciesFeatures, minDf, maxDF, norm, logNormalize, sequentialAccessOutput, namedVectors, reduceTasks); } } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } return 0; }
public int run(String[] args) throws Exception { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputDirOpt = DefaultOptionCreator.inputOption().create(); Option outputDirOpt = DefaultOptionCreator.outputOption().create(); Option minSupportOpt = obuilder.withLongName("minSupport").withArgument( abuilder.withName("minSupport").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional) Minimum Support. Default Value: 2").withShortName("s").create(); Option analyzerNameOpt = obuilder.withLongName("analyzerName").withArgument( abuilder.withName("analyzerName").withMinimum(1).withMaximum(1).create()).withDescription( "The class name of the analyzer").withShortName("a").create(); Option chunkSizeOpt = obuilder.withLongName("chunkSize").withArgument( abuilder.withName("chunkSize").withMinimum(1).withMaximum(1).create()).withDescription( "The chunkSize in MegaBytes. 100-10000 MB").withShortName("chunk").create(); Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument( abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription( "The kind of weight to use. Currently TF or TFIDF").withShortName("wt").create(); Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument( abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription( "The minimum document frequency. Default is 1").withShortName("md").create(); Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument( abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription( "The max percentage of docs for the DF. Can be used to remove really high frequency terms." + " Expressed as an integer between 0 and 100. Default is 99. If maxDFSigma is also set, it will override this value.").withShortName("x").create(); Option maxDFSigmaOpt = obuilder.withLongName("maxDFSigma").withRequired(false).withArgument( abuilder.withName("maxDFSigma").withMinimum(1).withMaximum(1).create()).withDescription( "What portion of the tf (tf-idf) vectors to be used, expressed in times the standard deviation (sigma) of the document frequencies of these vectors." + " Can be used to remove really high frequency terms." + " Expressed as a double value. Good value to be specified is 3.0. In case the value is less then 0 no vectors " + "will be filtered out. Default is -1.0. Overrides maxDFPercent").withShortName("xs").create(); Option minLLROpt = obuilder.withLongName("minLLR").withRequired(false).withArgument( abuilder.withName("minLLR").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional)The minimum Log Likelihood Ratio(Float) Default is " + LLRReducer.DEFAULT_MIN_LLR) .withShortName("ml").create(); Option numReduceTasksOpt = obuilder.withLongName("numReducers").withArgument( abuilder.withName("numReducers").withMinimum(1).withMaximum(1).create()).withDescription( "(Optional) Number of reduce tasks. Default Value: 1").withShortName("nr").create(); Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument( abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription( "The norm to use, expressed as either a float or \"INF\" if you want to use the Infinite norm. " + "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create(); Option logNormalizeOpt = obuilder.withLongName("logNormalize").withRequired(false) .withDescription( "(Optional) Whether output vectors should be logNormalize. If set true else false") .withShortName("lnorm").create(); Option maxNGramSizeOpt = obuilder.withLongName("maxNGramSize").withRequired(false).withArgument( abuilder.withName("ngramSize").withMinimum(1).withMaximum(1).create()) .withDescription( "(Optional) The maximum size of ngrams to create" + " (2 = bigrams, 3 = trigrams, etc) Default Value:1").withShortName("ng").create(); Option sequentialAccessVectorOpt = obuilder.withLongName("sequentialAccessVector").withRequired(false) .withDescription( "(Optional) Whether output vectors should be SequentialAccessVectors. If set true else false") .withShortName("seq").create(); Option namedVectorOpt = obuilder.withLongName("namedVector").withRequired(false) .withDescription( "(Optional) Whether output vectors should be NamedVectors. If set true else false") .withShortName("nv").create(); Option overwriteOutput = obuilder.withLongName("overwrite").withRequired(false).withDescription( "If set, overwrite the output directory").withShortName("ow").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(minSupportOpt).withOption(analyzerNameOpt) .withOption(chunkSizeOpt).withOption(outputDirOpt).withOption(inputDirOpt).withOption(minDFOpt) .withOption(maxDFSigmaOpt).withOption(maxDFPercentOpt).withOption(weightOpt).withOption(powerOpt).withOption(minLLROpt) .withOption(numReduceTasksOpt).withOption(maxNGramSizeOpt).withOption(overwriteOutput) .withOption(helpOpt).withOption(sequentialAccessVectorOpt).withOption(namedVectorOpt) .withOption(logNormalizeOpt) .create(); try { Parser parser = new Parser(); parser.setGroup(group); parser.setHelpOption(helpOpt); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return -1; } Path inputDir = new Path((String) cmdLine.getValue(inputDirOpt)); Path outputDir = new Path((String) cmdLine.getValue(outputDirOpt)); int chunkSize = 100; if (cmdLine.hasOption(chunkSizeOpt)) { chunkSize = Integer.parseInt((String) cmdLine.getValue(chunkSizeOpt)); } int minSupport = 2; if (cmdLine.hasOption(minSupportOpt)) { String minSupportString = (String) cmdLine.getValue(minSupportOpt); minSupport = Integer.parseInt(minSupportString); } int maxNGramSize = 1; if (cmdLine.hasOption(maxNGramSizeOpt)) { try { maxNGramSize = Integer.parseInt(cmdLine.getValue(maxNGramSizeOpt).toString()); } catch (NumberFormatException ex) { log.warn("Could not parse ngram size option"); } } log.info("Maximum n-gram size is: {}", maxNGramSize); if (cmdLine.hasOption(overwriteOutput)) { HadoopUtil.delete(getConf(), outputDir); } float minLLRValue = LLRReducer.DEFAULT_MIN_LLR; if (cmdLine.hasOption(minLLROpt)) { minLLRValue = Float.parseFloat(cmdLine.getValue(minLLROpt).toString()); } log.info("Minimum LLR value: {}", minLLRValue); int reduceTasks = 1; if (cmdLine.hasOption(numReduceTasksOpt)) { reduceTasks = Integer.parseInt(cmdLine.getValue(numReduceTasksOpt).toString()); } log.info("Number of reduce tasks: {}", reduceTasks); Class<? extends Analyzer> analyzerClass = DefaultAnalyzer.class; if (cmdLine.hasOption(analyzerNameOpt)) { String className = cmdLine.getValue(analyzerNameOpt).toString(); analyzerClass = Class.forName(className).asSubclass(Analyzer.class); // try instantiating it, b/c there isn't any point in setting it if // you can't instantiate it ClassUtils.instantiateAs(analyzerClass, Analyzer.class); } boolean processIdf; if (cmdLine.hasOption(weightOpt)) { String wString = cmdLine.getValue(weightOpt).toString(); if ("tf".equalsIgnoreCase(wString)) { processIdf = false; } else if ("tfidf".equalsIgnoreCase(wString)) { processIdf = true; } else { throw new OptionException(weightOpt); } } else { processIdf = true; } int minDf = 1; if (cmdLine.hasOption(minDFOpt)) { minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString()); } int maxDFPercent = 99; if (cmdLine.hasOption(maxDFPercentOpt)) { maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString()); } double maxDFSigma = -1.0; if (cmdLine.hasOption(maxDFSigmaOpt)) { maxDFSigma = Double.parseDouble(cmdLine.getValue(maxDFSigmaOpt).toString()); } float norm = PartialVectorMerger.NO_NORMALIZING; if (cmdLine.hasOption(powerOpt)) { String power = cmdLine.getValue(powerOpt).toString(); if ("INF".equals(power)) { norm = Float.POSITIVE_INFINITY; } else { norm = Float.parseFloat(power); } } boolean logNormalize = false; if (cmdLine.hasOption(logNormalizeOpt)) { logNormalize = true; } Configuration conf = getConf(); Path tokenizedPath = new Path(outputDir, DocumentProcessor.TOKENIZED_DOCUMENT_OUTPUT_FOLDER); //TODO: move this into DictionaryVectorizer , and then fold SparseVectorsFrom with EncodedVectorsFrom to have one framework for all of this. DocumentProcessor.tokenizeDocuments(inputDir, analyzerClass, tokenizedPath, conf); boolean sequentialAccessOutput = false; if (cmdLine.hasOption(sequentialAccessVectorOpt)) { sequentialAccessOutput = true; } boolean namedVectors = false; if (cmdLine.hasOption(namedVectorOpt)) { namedVectors = true; } boolean shouldPrune = maxDFSigma >=0.0; String tfDirName = shouldPrune ? DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER+"-toprune" : DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER; if (!processIdf) { DictionaryVectorizer.createTermFrequencyVectors(tokenizedPath, outputDir, tfDirName, conf, minSupport, maxNGramSize, minLLRValue, norm, logNormalize, reduceTasks, chunkSize, sequentialAccessOutput, namedVectors); } else { DictionaryVectorizer.createTermFrequencyVectors(tokenizedPath, outputDir, tfDirName, conf, minSupport, maxNGramSize, minLLRValue, -1.0f, false, reduceTasks, chunkSize, sequentialAccessOutput, namedVectors); } Pair<Long[], List<Path>> docFrequenciesFeatures = null; // Should document frequency features be processed if (shouldPrune || processIdf) { docFrequenciesFeatures = TFIDFConverter.calculateDF(new Path(outputDir, tfDirName), outputDir, conf, chunkSize); } long maxDF = maxDFPercent;//if we are pruning by std dev, then this will get changed if (shouldPrune) { Path dfDir = new Path(outputDir, TFIDFConverter.WORDCOUNT_OUTPUT_FOLDER); Path stdCalcDir = new Path(outputDir, HighDFWordsPruner.STD_CALC_DIR); // Calculate the standard deviation double stdDev = BasicStats.stdDevForGivenMean(dfDir, stdCalcDir, 0.0, conf); long vectorCount = docFrequenciesFeatures.getFirst()[1]; maxDF = (int) (100.0 * maxDFSigma * stdDev / vectorCount); // Prune the term frequency vectors Path tfDir = new Path(outputDir, tfDirName); Path prunedTFDir = new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER); Path prunedPartialTFDir = new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER + "-partial"); if (processIdf) { HighDFWordsPruner.pruneVectors(tfDir, prunedTFDir, prunedPartialTFDir, maxDF, conf, docFrequenciesFeatures, -1.0f, false, reduceTasks); } else { HighDFWordsPruner.pruneVectors(tfDir, prunedTFDir, prunedPartialTFDir, maxDF, conf, docFrequenciesFeatures, norm, logNormalize, reduceTasks); } HadoopUtil.delete(new Configuration(conf), tfDir); } if (processIdf){ TFIDFConverter.processTfIdf( new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER), outputDir, conf, docFrequenciesFeatures, minDf, maxDF, norm, logNormalize, sequentialAccessOutput, namedVectors, reduceTasks); } } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } return 0; }
diff --git a/plugins/org.bigraph.model/src/org/bigraph/model/PointHandler.java b/plugins/org.bigraph.model/src/org/bigraph/model/PointHandler.java index 81fefde3..94697142 100644 --- a/plugins/org.bigraph.model/src/org/bigraph/model/PointHandler.java +++ b/plugins/org.bigraph.model/src/org/bigraph/model/PointHandler.java @@ -1,41 +1,44 @@ package org.bigraph.model; import org.bigraph.model.assistants.PropertyScratchpad; import org.bigraph.model.changes.ChangeRejectedException; import org.bigraph.model.changes.IChange; import org.bigraph.model.changes.IStepExecutor; import org.bigraph.model.changes.IStepValidator; class PointHandler implements IStepExecutor, IStepValidator { @Override public boolean executeChange(IChange b) { if (b instanceof Point.ChangeConnect) { Point.ChangeConnect c = (Point.ChangeConnect)b; c.link.addPoint(c.getCreator()); } else if (b instanceof Point.ChangeDisconnect) { Point.ChangeDisconnect c = (Point.ChangeDisconnect)b; c.getCreator().getLink().removePoint(c.getCreator()); } else return false; return true; } @Override public boolean tryValidateChange(Process process, IChange b) throws ChangeRejectedException { final PropertyScratchpad context = process.getScratch(); if (b instanceof Point.ChangeConnect) { Point.ChangeConnect c = (Point.ChangeConnect)b; - if (c.getCreator().getLink(context) != null) + Point p = c.getCreator(); + Link l = p.getLink(context); + if (l != null) throw new ChangeRejectedException(b, - "Connections can only be established to Points that " + - "aren't already connected"); + "" + p.toString(context) + + " is already connected to " + l.toString(context)); } else if (b instanceof Point.ChangeDisconnect) { Point.ChangeDisconnect c = (Point.ChangeDisconnect)b; - Link l = c.getCreator().getLink(context); + Point p = c.getCreator(); + Link l = p.getLink(context); if (l == null) throw new ChangeRejectedException(b, - "The Point is already disconnected"); + "" + p.toString(context) + " isn't connected"); } else return false; return true; } }
false
true
public boolean tryValidateChange(Process process, IChange b) throws ChangeRejectedException { final PropertyScratchpad context = process.getScratch(); if (b instanceof Point.ChangeConnect) { Point.ChangeConnect c = (Point.ChangeConnect)b; if (c.getCreator().getLink(context) != null) throw new ChangeRejectedException(b, "Connections can only be established to Points that " + "aren't already connected"); } else if (b instanceof Point.ChangeDisconnect) { Point.ChangeDisconnect c = (Point.ChangeDisconnect)b; Link l = c.getCreator().getLink(context); if (l == null) throw new ChangeRejectedException(b, "The Point is already disconnected"); } else return false; return true; }
public boolean tryValidateChange(Process process, IChange b) throws ChangeRejectedException { final PropertyScratchpad context = process.getScratch(); if (b instanceof Point.ChangeConnect) { Point.ChangeConnect c = (Point.ChangeConnect)b; Point p = c.getCreator(); Link l = p.getLink(context); if (l != null) throw new ChangeRejectedException(b, "" + p.toString(context) + " is already connected to " + l.toString(context)); } else if (b instanceof Point.ChangeDisconnect) { Point.ChangeDisconnect c = (Point.ChangeDisconnect)b; Point p = c.getCreator(); Link l = p.getLink(context); if (l == null) throw new ChangeRejectedException(b, "" + p.toString(context) + " isn't connected"); } else return false; return true; }
diff --git a/trunk/CruxHtmlTags/src/br/com/sysmap/crux/tools/htmltags/template/TemplatesScanner.java b/trunk/CruxHtmlTags/src/br/com/sysmap/crux/tools/htmltags/template/TemplatesScanner.java index 8ba9d144e..a7da176dd 100644 --- a/trunk/CruxHtmlTags/src/br/com/sysmap/crux/tools/htmltags/template/TemplatesScanner.java +++ b/trunk/CruxHtmlTags/src/br/com/sysmap/crux/tools/htmltags/template/TemplatesScanner.java @@ -1,183 +1,182 @@ /* * Copyright 2009 Sysmap Solutions Software e Consultoria Ltda. * * 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 br.com.sysmap.crux.tools.htmltags.template; import java.io.IOException; import java.net.URL; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import br.com.sysmap.crux.core.config.ConfigurationFactory; import br.com.sysmap.crux.core.i18n.MessagesFactory; import br.com.sysmap.crux.core.server.scan.ScannerURLS; import br.com.sysmap.crux.core.utils.RegexpPatterns; import br.com.sysmap.crux.scannotation.AbstractScanner; import br.com.sysmap.crux.scannotation.archiveiterator.Filter; import br.com.sysmap.crux.scannotation.archiveiterator.IteratorFactory; import br.com.sysmap.crux.scannotation.archiveiterator.URLIterator; import br.com.sysmap.crux.tools.htmltags.HTMLTagsMessages; /** * * @author Thiago da Rosa de Bustamante <code>[email protected]</code> * */ public class TemplatesScanner extends AbstractScanner { private static final Log logger = LogFactory.getLog(TemplatesScanner.class); private static final TemplatesScanner instance = new TemplatesScanner(); private HTMLTagsMessages messages = MessagesFactory.getMessages(HTMLTagsMessages.class); private DocumentBuilder documentBuilder; private static URL[] urlsForSearch = null; private static final Lock lock = new ReentrantLock(); /** * */ private TemplatesScanner() { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); this.documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new TemplateException(messages.templatesScannerErrorBuilderCanNotBeCreated(), e); } } /** * * @param urls */ private void scanArchives(URL... urls) { - for (URL url : urls) + for (final URL url : urls) { Filter filter = new Filter() { public boolean accepts(String fileName) { if (fileName.endsWith(".template.xml")) { - if (fileName.startsWith("/")) fileName = fileName.substring(1); - if (!ignoreScan(fileName.replace('/', '.'))) + if (!ignoreScan(url, fileName)) { return true; } } return false; } }; try { URLIterator it = IteratorFactory.create(url, filter); URL found; while ((found = it.next()) != null) { try { Document template = documentBuilder.parse(found.openStream()); Templates.registerTemplate(getTemplateId(found.toString()), template); } catch (Exception e) { logger.error(messages.templatesScannerErrorParsingTemplateFile(found.toString()), e); } } } catch (IOException e) { throw new TemplateException(messages.templatesScannerInitializationError(e.getLocalizedMessage()), e); } } } /** * */ public void scanArchives() { if (Boolean.parseBoolean(ConfigurationFactory.getConfigurations().enableWebRootScannerCache())) { if (urlsForSearch == null) { initialize(ScannerURLS.getWebURLsForSearch()); } scanArchives(urlsForSearch); } else { scanArchives(ScannerURLS.getWebURLsForSearch()); } } /** * * @param urls */ public static void initialize(URL[] urls) { lock.lock(); try { urlsForSearch = urls; } finally { lock.unlock(); } } /** * * @param fileName * @return */ private String getTemplateId(String fileName) { fileName = fileName.substring(0, fileName.length() - 13); fileName = RegexpPatterns.REGEXP_BACKSLASH.matcher(fileName).replaceAll("/"); int indexStartId = fileName.lastIndexOf('/'); if (indexStartId > 0) { fileName = fileName.substring(indexStartId+1); } return fileName; } /** * * @return */ public static TemplatesScanner getInstance() { return instance; } }
false
true
private void scanArchives(URL... urls) { for (URL url : urls) { Filter filter = new Filter() { public boolean accepts(String fileName) { if (fileName.endsWith(".template.xml")) { if (fileName.startsWith("/")) fileName = fileName.substring(1); if (!ignoreScan(fileName.replace('/', '.'))) { return true; } } return false; } }; try { URLIterator it = IteratorFactory.create(url, filter); URL found; while ((found = it.next()) != null) { try { Document template = documentBuilder.parse(found.openStream()); Templates.registerTemplate(getTemplateId(found.toString()), template); } catch (Exception e) { logger.error(messages.templatesScannerErrorParsingTemplateFile(found.toString()), e); } } } catch (IOException e) { throw new TemplateException(messages.templatesScannerInitializationError(e.getLocalizedMessage()), e); } } }
private void scanArchives(URL... urls) { for (final URL url : urls) { Filter filter = new Filter() { public boolean accepts(String fileName) { if (fileName.endsWith(".template.xml")) { if (!ignoreScan(url, fileName)) { return true; } } return false; } }; try { URLIterator it = IteratorFactory.create(url, filter); URL found; while ((found = it.next()) != null) { try { Document template = documentBuilder.parse(found.openStream()); Templates.registerTemplate(getTemplateId(found.toString()), template); } catch (Exception e) { logger.error(messages.templatesScannerErrorParsingTemplateFile(found.toString()), e); } } } catch (IOException e) { throw new TemplateException(messages.templatesScannerInitializationError(e.getLocalizedMessage()), e); } } }
diff --git a/src/java/com/sapienter/jbilling/server/process/task/SimpleTaxCompositionTask.java b/src/java/com/sapienter/jbilling/server/process/task/SimpleTaxCompositionTask.java index 7c28ac44..279bfcb1 100644 --- a/src/java/com/sapienter/jbilling/server/process/task/SimpleTaxCompositionTask.java +++ b/src/java/com/sapienter/jbilling/server/process/task/SimpleTaxCompositionTask.java @@ -1,184 +1,184 @@ /* jBilling - The Enterprise Open Source Billing System Copyright (C) 2003-2009 Enterprise jBilling Software Ltd. and Emiliano Conde This file is part of jbilling. jbilling 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. jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>. */ package com.sapienter.jbilling.server.process.task; import com.sapienter.jbilling.server.invoice.NewInvoiceDTO; import com.sapienter.jbilling.server.invoice.db.InvoiceLineDTO; import com.sapienter.jbilling.server.item.ItemBL; import com.sapienter.jbilling.server.item.db.ItemDAS; import com.sapienter.jbilling.server.item.db.ItemDTO; import com.sapienter.jbilling.server.item.db.ItemTypeDTO; import com.sapienter.jbilling.server.pluggableTask.InvoiceCompositionTask; import com.sapienter.jbilling.server.pluggableTask.PluggableTask; import com.sapienter.jbilling.server.pluggableTask.TaskException; import com.sapienter.jbilling.server.process.PeriodOfTime; import com.sapienter.jbilling.server.user.contact.db.ContactDAS; import com.sapienter.jbilling.server.user.contact.db.ContactDTO; import com.sapienter.jbilling.server.user.contact.db.ContactFieldDTO; import com.sapienter.jbilling.server.util.Constants; import org.apache.log4j.Logger; import java.math.BigDecimal; import java.util.Set; /** * This plug-in calculates taxes for invoice. * * Plug-in parameters: * * tax_item_id (required) The item that will be added to an invoice with the taxes * * custom_contact_field_id (optional) The id of CCF that if its value is 'true' or 'yes' for a customer, * then the customer is considered exempt. Exempt customers do not get the tax * added to their invoices. * item_exempt_category_id (optional) The id of an item category that, if the item belongs to, it is * exempt from taxes * * @author Alexander Aksenov * @since 30.04.11 */ public class SimpleTaxCompositionTask extends PluggableTask implements InvoiceCompositionTask { private static final Logger LOG = Logger.getLogger(SimpleTaxCompositionTask.class); // plug-in parameters // mandatory parameters protected final static String PARAM_TAX_ITEM_ID = "tax_item_id"; // optional, may be empty protected final static String PARAM_CUSTOM_CONTACT_FIELD_ID = "custom_contact_field_id"; protected final static String PARAM_ITEM_EXEMPT_CATEGORY_ID = "item_exempt_category_id"; @Override public void apply(NewInvoiceDTO invoice, Integer userId) throws TaskException { ItemDTO taxItem; Integer itemExemptCategoryId = null; Integer customContactFieldId = null; try { String paramValue = getParameter(PARAM_TAX_ITEM_ID, ""); if (paramValue == null || "".equals(paramValue.trim())) { throw new TaskException("Tax item id is not defined!"); } taxItem = new ItemDAS().find(new Integer(paramValue)); if (taxItem == null) { throw new TaskException("Tax item not found!"); } paramValue = getParameter(PARAM_ITEM_EXEMPT_CATEGORY_ID, ""); if (paramValue != null && !"".equals(paramValue.trim())) { itemExemptCategoryId = new Integer(paramValue); } paramValue = getParameter(PARAM_CUSTOM_CONTACT_FIELD_ID, ""); if (paramValue != null && !"".equals(paramValue.trim())) { customContactFieldId = new Integer(paramValue); } } catch (NumberFormatException e) { LOG.error("Incorrect plugin configuration", e); throw new TaskException(e); } if (!isTaxCalculationNeeded(userId, customContactFieldId)) { return; } if (taxItem.getPercentage() != null) { // tax calculation as percentage of full cost //calculate total to include result lines invoice.calculateTotal(); BigDecimal invoiceAmountSum = invoice.getTotal(); //remove carried balance from tax calculation //to avoid double taxation LOG.debug("Carried balance is " + invoice.getCarriedBalance()); if ( null != invoice.getCarriedBalance() ){ invoiceAmountSum = invoiceAmountSum.subtract(invoice.getCarriedBalance()); } LOG.debug("Exempt Category " + itemExemptCategoryId); if (itemExemptCategoryId != null) { // find exemp items and subtract price for (int i = 0; i < invoice.getResultLines().size(); i++) { InvoiceLineDTO invoiceLine = (InvoiceLineDTO) invoice.getResultLines().get(i); ItemDTO item = invoiceLine.getItem(); if (item != null) { Set<ItemTypeDTO> itemTypes = new ItemDAS().find(item.getId()).getItemTypes(); for (ItemTypeDTO itemType : itemTypes) { if (itemType.getId() == itemExemptCategoryId) { LOG.debug("Item " + item.getDescription() + " is Exempt. Category " + itemType.getId()); invoiceAmountSum = invoiceAmountSum.subtract(invoiceLine.getAmount()); break; } } } } } LOG.debug("Calculating tax on = " + invoiceAmountSum); BigDecimal taxValue = invoiceAmountSum.multiply(taxItem.getPercentage()).divide( BigDecimal.valueOf(100L), Constants.BIGDECIMAL_SCALE, Constants.BIGDECIMAL_ROUND ); //if (taxValue.compareTo(BigDecimal.ZERO) > 0) { InvoiceLineDTO invoiceLine = new InvoiceLineDTO(null, "Tax line for percentage tax item " + taxItem.getId(), taxValue, taxValue, BigDecimal.ONE, Constants.INVOICE_LINE_TYPE_TAX, 0, taxItem.getId(), userId, null); invoice.addResultLine(invoiceLine); //} } else { ItemBL itemBL = new ItemBL(taxItem); - BigDecimal price = itemBL.getPriceByCurrency(invoice.getCurrency().getId(), invoice.getEntityId()); + BigDecimal price = itemBL.getPriceByCurrency(taxItem, userId, invoice.getCurrency().getId()); if (price != null && price.compareTo(BigDecimal.ZERO) != 0) { // tax as additional invoiceLine InvoiceLineDTO invoiceLine = new InvoiceLineDTO(null, "Tax line with flat price for tax item " + taxItem.getId(), price, price, BigDecimal.ONE, Constants.INVOICE_LINE_TYPE_TAX, 0, taxItem.getId(), userId, null); invoice.addResultLine(invoiceLine); } } } private boolean isTaxCalculationNeeded(Integer userId, Integer customContactFieldId) { if (customContactFieldId == null) { return true; } ContactDTO contactDto = new ContactDAS().findPrimaryContact(userId); if (contactDto == null) { return true; } for (ContactFieldDTO contactField : contactDto.getFields()) { if (contactField.getType().getId() == customContactFieldId) { String value = contactField.getContent(); if ("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value)) { return false; } } } return true; } @Override public BigDecimal calculatePeriodAmount(BigDecimal fullPrice, PeriodOfTime period) { throw new UnsupportedOperationException("Can't call this method"); } }
true
true
public void apply(NewInvoiceDTO invoice, Integer userId) throws TaskException { ItemDTO taxItem; Integer itemExemptCategoryId = null; Integer customContactFieldId = null; try { String paramValue = getParameter(PARAM_TAX_ITEM_ID, ""); if (paramValue == null || "".equals(paramValue.trim())) { throw new TaskException("Tax item id is not defined!"); } taxItem = new ItemDAS().find(new Integer(paramValue)); if (taxItem == null) { throw new TaskException("Tax item not found!"); } paramValue = getParameter(PARAM_ITEM_EXEMPT_CATEGORY_ID, ""); if (paramValue != null && !"".equals(paramValue.trim())) { itemExemptCategoryId = new Integer(paramValue); } paramValue = getParameter(PARAM_CUSTOM_CONTACT_FIELD_ID, ""); if (paramValue != null && !"".equals(paramValue.trim())) { customContactFieldId = new Integer(paramValue); } } catch (NumberFormatException e) { LOG.error("Incorrect plugin configuration", e); throw new TaskException(e); } if (!isTaxCalculationNeeded(userId, customContactFieldId)) { return; } if (taxItem.getPercentage() != null) { // tax calculation as percentage of full cost //calculate total to include result lines invoice.calculateTotal(); BigDecimal invoiceAmountSum = invoice.getTotal(); //remove carried balance from tax calculation //to avoid double taxation LOG.debug("Carried balance is " + invoice.getCarriedBalance()); if ( null != invoice.getCarriedBalance() ){ invoiceAmountSum = invoiceAmountSum.subtract(invoice.getCarriedBalance()); } LOG.debug("Exempt Category " + itemExemptCategoryId); if (itemExemptCategoryId != null) { // find exemp items and subtract price for (int i = 0; i < invoice.getResultLines().size(); i++) { InvoiceLineDTO invoiceLine = (InvoiceLineDTO) invoice.getResultLines().get(i); ItemDTO item = invoiceLine.getItem(); if (item != null) { Set<ItemTypeDTO> itemTypes = new ItemDAS().find(item.getId()).getItemTypes(); for (ItemTypeDTO itemType : itemTypes) { if (itemType.getId() == itemExemptCategoryId) { LOG.debug("Item " + item.getDescription() + " is Exempt. Category " + itemType.getId()); invoiceAmountSum = invoiceAmountSum.subtract(invoiceLine.getAmount()); break; } } } } } LOG.debug("Calculating tax on = " + invoiceAmountSum); BigDecimal taxValue = invoiceAmountSum.multiply(taxItem.getPercentage()).divide( BigDecimal.valueOf(100L), Constants.BIGDECIMAL_SCALE, Constants.BIGDECIMAL_ROUND ); //if (taxValue.compareTo(BigDecimal.ZERO) > 0) { InvoiceLineDTO invoiceLine = new InvoiceLineDTO(null, "Tax line for percentage tax item " + taxItem.getId(), taxValue, taxValue, BigDecimal.ONE, Constants.INVOICE_LINE_TYPE_TAX, 0, taxItem.getId(), userId, null); invoice.addResultLine(invoiceLine); //} } else { ItemBL itemBL = new ItemBL(taxItem); BigDecimal price = itemBL.getPriceByCurrency(invoice.getCurrency().getId(), invoice.getEntityId()); if (price != null && price.compareTo(BigDecimal.ZERO) != 0) { // tax as additional invoiceLine InvoiceLineDTO invoiceLine = new InvoiceLineDTO(null, "Tax line with flat price for tax item " + taxItem.getId(), price, price, BigDecimal.ONE, Constants.INVOICE_LINE_TYPE_TAX, 0, taxItem.getId(), userId, null); invoice.addResultLine(invoiceLine); } } }
public void apply(NewInvoiceDTO invoice, Integer userId) throws TaskException { ItemDTO taxItem; Integer itemExemptCategoryId = null; Integer customContactFieldId = null; try { String paramValue = getParameter(PARAM_TAX_ITEM_ID, ""); if (paramValue == null || "".equals(paramValue.trim())) { throw new TaskException("Tax item id is not defined!"); } taxItem = new ItemDAS().find(new Integer(paramValue)); if (taxItem == null) { throw new TaskException("Tax item not found!"); } paramValue = getParameter(PARAM_ITEM_EXEMPT_CATEGORY_ID, ""); if (paramValue != null && !"".equals(paramValue.trim())) { itemExemptCategoryId = new Integer(paramValue); } paramValue = getParameter(PARAM_CUSTOM_CONTACT_FIELD_ID, ""); if (paramValue != null && !"".equals(paramValue.trim())) { customContactFieldId = new Integer(paramValue); } } catch (NumberFormatException e) { LOG.error("Incorrect plugin configuration", e); throw new TaskException(e); } if (!isTaxCalculationNeeded(userId, customContactFieldId)) { return; } if (taxItem.getPercentage() != null) { // tax calculation as percentage of full cost //calculate total to include result lines invoice.calculateTotal(); BigDecimal invoiceAmountSum = invoice.getTotal(); //remove carried balance from tax calculation //to avoid double taxation LOG.debug("Carried balance is " + invoice.getCarriedBalance()); if ( null != invoice.getCarriedBalance() ){ invoiceAmountSum = invoiceAmountSum.subtract(invoice.getCarriedBalance()); } LOG.debug("Exempt Category " + itemExemptCategoryId); if (itemExemptCategoryId != null) { // find exemp items and subtract price for (int i = 0; i < invoice.getResultLines().size(); i++) { InvoiceLineDTO invoiceLine = (InvoiceLineDTO) invoice.getResultLines().get(i); ItemDTO item = invoiceLine.getItem(); if (item != null) { Set<ItemTypeDTO> itemTypes = new ItemDAS().find(item.getId()).getItemTypes(); for (ItemTypeDTO itemType : itemTypes) { if (itemType.getId() == itemExemptCategoryId) { LOG.debug("Item " + item.getDescription() + " is Exempt. Category " + itemType.getId()); invoiceAmountSum = invoiceAmountSum.subtract(invoiceLine.getAmount()); break; } } } } } LOG.debug("Calculating tax on = " + invoiceAmountSum); BigDecimal taxValue = invoiceAmountSum.multiply(taxItem.getPercentage()).divide( BigDecimal.valueOf(100L), Constants.BIGDECIMAL_SCALE, Constants.BIGDECIMAL_ROUND ); //if (taxValue.compareTo(BigDecimal.ZERO) > 0) { InvoiceLineDTO invoiceLine = new InvoiceLineDTO(null, "Tax line for percentage tax item " + taxItem.getId(), taxValue, taxValue, BigDecimal.ONE, Constants.INVOICE_LINE_TYPE_TAX, 0, taxItem.getId(), userId, null); invoice.addResultLine(invoiceLine); //} } else { ItemBL itemBL = new ItemBL(taxItem); BigDecimal price = itemBL.getPriceByCurrency(taxItem, userId, invoice.getCurrency().getId()); if (price != null && price.compareTo(BigDecimal.ZERO) != 0) { // tax as additional invoiceLine InvoiceLineDTO invoiceLine = new InvoiceLineDTO(null, "Tax line with flat price for tax item " + taxItem.getId(), price, price, BigDecimal.ONE, Constants.INVOICE_LINE_TYPE_TAX, 0, taxItem.getId(), userId, null); invoice.addResultLine(invoiceLine); } } }
diff --git a/src/main/java/org/oregami/resources/UserResource.java b/src/main/java/org/oregami/resources/UserResource.java index b95e5b3..9859cac 100644 --- a/src/main/java/org/oregami/resources/UserResource.java +++ b/src/main/java/org/oregami/resources/UserResource.java @@ -1,61 +1,61 @@ package org.oregami.resources; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.oregami.data.UserDao; import org.oregami.entities.user.User; import org.oregami.service.IUserService; import org.oregami.service.ServiceResult; import org.oregami.util.MailHelper; import com.google.inject.Inject; @Path("/user") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class UserResource { @Inject private UserDao userDao; @Inject private IUserService userService; MailHelper mailHelper = MailHelper.instance(); @POST public Response createUser(User user) { try { ServiceResult<User> register = userService.register(user); if (register.hasErrors()) { - return Response.status(Status.BAD_REQUEST).type("text/plain") - .entity("Errors: " + register.getErrors()).build(); + return Response.status(Status.BAD_REQUEST) + //.type("text/plain") + .type("text/json") + .entity(register.getErrors()).build(); } -// userDao.save(user); -// mailHelper.sendMail("[email protected]", "test-subject", "Tolle neue Mail!\n" + user); return Response.ok().build(); } catch (Exception e) { return Response.status(javax.ws.rs.core.Response.Status.CONFLICT).type("text/plain") .entity(e.getMessage()).build(); } } @GET public List<User> getUserlist() { List<User> findAll = userDao.findAll(); return findAll; } }
false
true
public Response createUser(User user) { try { ServiceResult<User> register = userService.register(user); if (register.hasErrors()) { return Response.status(Status.BAD_REQUEST).type("text/plain") .entity("Errors: " + register.getErrors()).build(); } // userDao.save(user); // mailHelper.sendMail("[email protected]", "test-subject", "Tolle neue Mail!\n" + user); return Response.ok().build(); } catch (Exception e) { return Response.status(javax.ws.rs.core.Response.Status.CONFLICT).type("text/plain") .entity(e.getMessage()).build(); } }
public Response createUser(User user) { try { ServiceResult<User> register = userService.register(user); if (register.hasErrors()) { return Response.status(Status.BAD_REQUEST) //.type("text/plain") .type("text/json") .entity(register.getErrors()).build(); } return Response.ok().build(); } catch (Exception e) { return Response.status(javax.ws.rs.core.Response.Status.CONFLICT).type("text/plain") .entity(e.getMessage()).build(); } }
diff --git a/engine/src/test/jme3test/terrain/TerrainGridAlphaMapTest.java b/engine/src/test/jme3test/terrain/TerrainGridAlphaMapTest.java index 8a0261bb0..c662dd79c 100644 --- a/engine/src/test/jme3test/terrain/TerrainGridAlphaMapTest.java +++ b/engine/src/test/jme3test/terrain/TerrainGridAlphaMapTest.java @@ -1,286 +1,287 @@ package jme3test.terrain; import java.util.ArrayList; import java.util.List; import com.jme3.app.SimpleApplication; import com.jme3.app.state.ScreenshotAppState; import com.jme3.asset.plugins.HttpZipLocator; import com.jme3.asset.plugins.ZipLocator; import com.jme3.bullet.BulletAppState; import com.jme3.bullet.collision.shapes.CapsuleCollisionShape; import com.jme3.bullet.collision.shapes.HeightfieldCollisionShape; import com.jme3.bullet.control.CharacterControl; import com.jme3.bullet.control.RigidBodyControl; import com.jme3.input.KeyInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.light.AmbientLight; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.shader.VarType; import com.jme3.terrain.geomipmap.TerrainGrid; import com.jme3.terrain.geomipmap.TerrainGridListener; import com.jme3.terrain.geomipmap.TerrainLodControl; import com.jme3.terrain.geomipmap.TerrainQuad; import com.jme3.terrain.heightmap.FractalHeightMapGrid; import com.jme3.terrain.heightmap.ImageBasedHeightMapGrid; import com.jme3.terrain.heightmap.Namer; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; import java.io.File; import org.novyon.noise.ShaderUtils; import org.novyon.noise.basis.FilteredBasis; import org.novyon.noise.filter.IterativeFilter; import org.novyon.noise.filter.OptimizedErode; import org.novyon.noise.filter.PerturbFilter; import org.novyon.noise.filter.SmoothFilter; import org.novyon.noise.fractal.FractalSum; import org.novyon.noise.modulator.NoiseModulator; public class TerrainGridAlphaMapTest extends SimpleApplication { private TerrainGrid terrain; private float grassScale = 64; private float dirtScale = 16; private float rockScale = 128; private boolean usePhysics = true; public static void main(final String[] args) { TerrainGridAlphaMapTest app = new TerrainGridAlphaMapTest(); app.start(); } private CharacterControl player3; private FractalSum base; private PerturbFilter perturb; private OptimizedErode therm; private SmoothFilter smooth; private IterativeFilter iterate; private Material matRock; private Material matWire; @Override public void simpleInitApp() { DirectionalLight sun = new DirectionalLight(); sun.setColor(ColorRGBA.White); sun.setDirection(new Vector3f(-1, -1, -1).normalizeLocal()); rootNode.addLight(sun); AmbientLight al = new AmbientLight(); al.setColor(ColorRGBA.White.mult(1.3f)); rootNode.addLight(al); File file = new File("mountains.zip"); if (!file.exists()) { assetManager.registerLocator("http://jmonkeyengine.googlecode.com/files/mountains.zip", HttpZipLocator.class); } else { assetManager.registerLocator("mountains.zip", ZipLocator.class); } this.flyCam.setMoveSpeed(100f); ScreenshotAppState state = new ScreenshotAppState(); this.stateManager.attach(state); // TERRAIN TEXTURE material matRock = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md"); matRock.setBoolean("useTriPlanarMapping", false); + matRock.setBoolean("isTerrainGrid", true); // GRASS texture Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg"); grass.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap", grass); matRock.setFloat("DiffuseMap_0_scale", grassScale); // DIRT texture Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg"); dirt.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_1", dirt); matRock.setFloat("DiffuseMap_1_scale", dirtScale); // ROCK texture Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg"); rock.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_2", rock); matRock.setFloat("DiffuseMap_2_scale", rockScale); // WIREFRAME material matWire = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); matWire.getAdditionalRenderState().setWireframe(true); matWire.setColor("Color", ColorRGBA.Green); this.base = new FractalSum(); this.base.setRoughness(0.7f); this.base.setFrequency(1.0f); this.base.setAmplitude(1.0f); this.base.setLacunarity(2.12f); this.base.setOctaves(8); this.base.setScale(0.02125f); this.base.addModulator(new NoiseModulator() { @Override public float value(float... in) { return ShaderUtils.clamp(in[0] * 0.5f + 0.5f, 0, 1); } }); FilteredBasis ground = new FilteredBasis(this.base); this.perturb = new PerturbFilter(); this.perturb.setMagnitude(0.119f); this.therm = new OptimizedErode(); this.therm.setRadius(5); this.therm.setTalus(0.011f); this.smooth = new SmoothFilter(); this.smooth.setRadius(1); this.smooth.setEffect(0.7f); this.iterate = new IterativeFilter(); this.iterate.addPreFilter(this.perturb); this.iterate.addPostFilter(this.smooth); this.iterate.setFilter(this.therm); this.iterate.setIterations(1); ground.addPreFilter(this.iterate); this.terrain = new TerrainGrid("terrain", 33, 257, new FractalHeightMapGrid(ground, null, 256)); this.terrain.setMaterial(this.matRock); this.terrain.setLocalTranslation(0, 0, 0); this.terrain.setLocalScale(2f, 1f, 2f); this.rootNode.attachChild(this.terrain); List<Camera> cameras = new ArrayList<Camera>(); cameras.add(this.getCamera()); TerrainLodControl control = new TerrainLodControl(this.terrain, cameras); this.terrain.addControl(control); final BulletAppState bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); this.getCamera().setLocation(new Vector3f(0, 256, 0)); this.viewPort.setBackgroundColor(new ColorRGBA(0.7f, 0.8f, 1f, 1f)); if (usePhysics) { CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(0.5f, 1.8f, 1); player3 = new CharacterControl(capsuleShape, 0.5f); player3.setJumpSpeed(20); player3.setFallSpeed(10); player3.setGravity(10); player3.setPhysicsLocation(new Vector3f(cam.getLocation().x, 256, cam.getLocation().z)); bulletAppState.getPhysicsSpace().add(player3); } terrain.addListener("physicsStartListener", new TerrainGridListener() { public void gridMoved(Vector3f newCenter) { } public Material tileLoaded(Material material, Vector3f cell) { return material; } public void tileAttached(Vector3f cell, TerrainQuad quad) { - Texture alpha = assetManager.loadTexture("Scenes/TerrainAlphaTest/alphamap_" + Math.abs((int) (cell.x % 2)) * 512 + "_" + Math.abs((int) (cell.y % 2) * 512) + ".png"); + Texture alpha = assetManager.loadTexture("Scenes/TerrainAlphaTest/alphamap_" + Math.abs((int) (cell.x % 2)) * 512 + "_" + Math.abs((int) (cell.z % 2) * 512) + ".png"); quad.getMaterial().setTexture("AlphaMap", alpha); if (usePhysics) { quad.addControl(new RigidBodyControl(new HeightfieldCollisionShape(quad.getHeightMap(), terrain.getLocalScale()), 0)); bulletAppState.getPhysicsSpace().add(quad); } } public void tileDetached(Vector3f cell, TerrainQuad quad) { if (usePhysics) { bulletAppState.getPhysicsSpace().remove(quad); quad.removeControl(RigidBodyControl.class); } } }); this.terrain.initialize(cam.getLocation()); this.initKeys(); } private void initKeys() { // You can map one or several inputs to one named action this.inputManager.addMapping("Lefts", new KeyTrigger(KeyInput.KEY_A)); this.inputManager.addMapping("Rights", new KeyTrigger(KeyInput.KEY_D)); this.inputManager.addMapping("Ups", new KeyTrigger(KeyInput.KEY_W)); this.inputManager.addMapping("Downs", new KeyTrigger(KeyInput.KEY_S)); this.inputManager.addMapping("Jumps", new KeyTrigger(KeyInput.KEY_SPACE)); this.inputManager.addListener(this.actionListener, "Lefts"); this.inputManager.addListener(this.actionListener, "Rights"); this.inputManager.addListener(this.actionListener, "Ups"); this.inputManager.addListener(this.actionListener, "Downs"); this.inputManager.addListener(this.actionListener, "Jumps"); } private boolean left; private boolean right; private boolean up; private boolean down; private final ActionListener actionListener = new ActionListener() { @Override public void onAction(final String name, final boolean keyPressed, final float tpf) { if (name.equals("Lefts")) { if (keyPressed) { TerrainGridAlphaMapTest.this.left = true; } else { TerrainGridAlphaMapTest.this.left = false; } } else if (name.equals("Rights")) { if (keyPressed) { TerrainGridAlphaMapTest.this.right = true; } else { TerrainGridAlphaMapTest.this.right = false; } } else if (name.equals("Ups")) { if (keyPressed) { TerrainGridAlphaMapTest.this.up = true; } else { TerrainGridAlphaMapTest.this.up = false; } } else if (name.equals("Downs")) { if (keyPressed) { TerrainGridAlphaMapTest.this.down = true; } else { TerrainGridAlphaMapTest.this.down = false; } } else if (name.equals("Jumps")) { TerrainGridAlphaMapTest.this.player3.jump(); } } }; private final Vector3f walkDirection = new Vector3f(); @Override public void simpleUpdate(final float tpf) { Vector3f camDir = this.cam.getDirection().clone().multLocal(0.6f); Vector3f camLeft = this.cam.getLeft().clone().multLocal(0.4f); this.walkDirection.set(0, 0, 0); if (this.left) { this.walkDirection.addLocal(camLeft); } if (this.right) { this.walkDirection.addLocal(camLeft.negate()); } if (this.up) { this.walkDirection.addLocal(camDir); } if (this.down) { this.walkDirection.addLocal(camDir.negate()); } if (usePhysics) { this.player3.setWalkDirection(this.walkDirection); this.cam.setLocation(this.player3.getPhysicsLocation()); } } }
false
true
public void simpleInitApp() { DirectionalLight sun = new DirectionalLight(); sun.setColor(ColorRGBA.White); sun.setDirection(new Vector3f(-1, -1, -1).normalizeLocal()); rootNode.addLight(sun); AmbientLight al = new AmbientLight(); al.setColor(ColorRGBA.White.mult(1.3f)); rootNode.addLight(al); File file = new File("mountains.zip"); if (!file.exists()) { assetManager.registerLocator("http://jmonkeyengine.googlecode.com/files/mountains.zip", HttpZipLocator.class); } else { assetManager.registerLocator("mountains.zip", ZipLocator.class); } this.flyCam.setMoveSpeed(100f); ScreenshotAppState state = new ScreenshotAppState(); this.stateManager.attach(state); // TERRAIN TEXTURE material matRock = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md"); matRock.setBoolean("useTriPlanarMapping", false); // GRASS texture Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg"); grass.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap", grass); matRock.setFloat("DiffuseMap_0_scale", grassScale); // DIRT texture Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg"); dirt.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_1", dirt); matRock.setFloat("DiffuseMap_1_scale", dirtScale); // ROCK texture Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg"); rock.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_2", rock); matRock.setFloat("DiffuseMap_2_scale", rockScale); // WIREFRAME material matWire = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); matWire.getAdditionalRenderState().setWireframe(true); matWire.setColor("Color", ColorRGBA.Green); this.base = new FractalSum(); this.base.setRoughness(0.7f); this.base.setFrequency(1.0f); this.base.setAmplitude(1.0f); this.base.setLacunarity(2.12f); this.base.setOctaves(8); this.base.setScale(0.02125f); this.base.addModulator(new NoiseModulator() { @Override public float value(float... in) { return ShaderUtils.clamp(in[0] * 0.5f + 0.5f, 0, 1); } }); FilteredBasis ground = new FilteredBasis(this.base); this.perturb = new PerturbFilter(); this.perturb.setMagnitude(0.119f); this.therm = new OptimizedErode(); this.therm.setRadius(5); this.therm.setTalus(0.011f); this.smooth = new SmoothFilter(); this.smooth.setRadius(1); this.smooth.setEffect(0.7f); this.iterate = new IterativeFilter(); this.iterate.addPreFilter(this.perturb); this.iterate.addPostFilter(this.smooth); this.iterate.setFilter(this.therm); this.iterate.setIterations(1); ground.addPreFilter(this.iterate); this.terrain = new TerrainGrid("terrain", 33, 257, new FractalHeightMapGrid(ground, null, 256)); this.terrain.setMaterial(this.matRock); this.terrain.setLocalTranslation(0, 0, 0); this.terrain.setLocalScale(2f, 1f, 2f); this.rootNode.attachChild(this.terrain); List<Camera> cameras = new ArrayList<Camera>(); cameras.add(this.getCamera()); TerrainLodControl control = new TerrainLodControl(this.terrain, cameras); this.terrain.addControl(control); final BulletAppState bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); this.getCamera().setLocation(new Vector3f(0, 256, 0)); this.viewPort.setBackgroundColor(new ColorRGBA(0.7f, 0.8f, 1f, 1f)); if (usePhysics) { CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(0.5f, 1.8f, 1); player3 = new CharacterControl(capsuleShape, 0.5f); player3.setJumpSpeed(20); player3.setFallSpeed(10); player3.setGravity(10); player3.setPhysicsLocation(new Vector3f(cam.getLocation().x, 256, cam.getLocation().z)); bulletAppState.getPhysicsSpace().add(player3); } terrain.addListener("physicsStartListener", new TerrainGridListener() { public void gridMoved(Vector3f newCenter) { } public Material tileLoaded(Material material, Vector3f cell) { return material; } public void tileAttached(Vector3f cell, TerrainQuad quad) { Texture alpha = assetManager.loadTexture("Scenes/TerrainAlphaTest/alphamap_" + Math.abs((int) (cell.x % 2)) * 512 + "_" + Math.abs((int) (cell.y % 2) * 512) + ".png"); quad.getMaterial().setTexture("AlphaMap", alpha); if (usePhysics) { quad.addControl(new RigidBodyControl(new HeightfieldCollisionShape(quad.getHeightMap(), terrain.getLocalScale()), 0)); bulletAppState.getPhysicsSpace().add(quad); } } public void tileDetached(Vector3f cell, TerrainQuad quad) { if (usePhysics) { bulletAppState.getPhysicsSpace().remove(quad); quad.removeControl(RigidBodyControl.class); } } }); this.terrain.initialize(cam.getLocation()); this.initKeys(); }
public void simpleInitApp() { DirectionalLight sun = new DirectionalLight(); sun.setColor(ColorRGBA.White); sun.setDirection(new Vector3f(-1, -1, -1).normalizeLocal()); rootNode.addLight(sun); AmbientLight al = new AmbientLight(); al.setColor(ColorRGBA.White.mult(1.3f)); rootNode.addLight(al); File file = new File("mountains.zip"); if (!file.exists()) { assetManager.registerLocator("http://jmonkeyengine.googlecode.com/files/mountains.zip", HttpZipLocator.class); } else { assetManager.registerLocator("mountains.zip", ZipLocator.class); } this.flyCam.setMoveSpeed(100f); ScreenshotAppState state = new ScreenshotAppState(); this.stateManager.attach(state); // TERRAIN TEXTURE material matRock = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md"); matRock.setBoolean("useTriPlanarMapping", false); matRock.setBoolean("isTerrainGrid", true); // GRASS texture Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg"); grass.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap", grass); matRock.setFloat("DiffuseMap_0_scale", grassScale); // DIRT texture Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg"); dirt.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_1", dirt); matRock.setFloat("DiffuseMap_1_scale", dirtScale); // ROCK texture Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg"); rock.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_2", rock); matRock.setFloat("DiffuseMap_2_scale", rockScale); // WIREFRAME material matWire = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); matWire.getAdditionalRenderState().setWireframe(true); matWire.setColor("Color", ColorRGBA.Green); this.base = new FractalSum(); this.base.setRoughness(0.7f); this.base.setFrequency(1.0f); this.base.setAmplitude(1.0f); this.base.setLacunarity(2.12f); this.base.setOctaves(8); this.base.setScale(0.02125f); this.base.addModulator(new NoiseModulator() { @Override public float value(float... in) { return ShaderUtils.clamp(in[0] * 0.5f + 0.5f, 0, 1); } }); FilteredBasis ground = new FilteredBasis(this.base); this.perturb = new PerturbFilter(); this.perturb.setMagnitude(0.119f); this.therm = new OptimizedErode(); this.therm.setRadius(5); this.therm.setTalus(0.011f); this.smooth = new SmoothFilter(); this.smooth.setRadius(1); this.smooth.setEffect(0.7f); this.iterate = new IterativeFilter(); this.iterate.addPreFilter(this.perturb); this.iterate.addPostFilter(this.smooth); this.iterate.setFilter(this.therm); this.iterate.setIterations(1); ground.addPreFilter(this.iterate); this.terrain = new TerrainGrid("terrain", 33, 257, new FractalHeightMapGrid(ground, null, 256)); this.terrain.setMaterial(this.matRock); this.terrain.setLocalTranslation(0, 0, 0); this.terrain.setLocalScale(2f, 1f, 2f); this.rootNode.attachChild(this.terrain); List<Camera> cameras = new ArrayList<Camera>(); cameras.add(this.getCamera()); TerrainLodControl control = new TerrainLodControl(this.terrain, cameras); this.terrain.addControl(control); final BulletAppState bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); this.getCamera().setLocation(new Vector3f(0, 256, 0)); this.viewPort.setBackgroundColor(new ColorRGBA(0.7f, 0.8f, 1f, 1f)); if (usePhysics) { CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(0.5f, 1.8f, 1); player3 = new CharacterControl(capsuleShape, 0.5f); player3.setJumpSpeed(20); player3.setFallSpeed(10); player3.setGravity(10); player3.setPhysicsLocation(new Vector3f(cam.getLocation().x, 256, cam.getLocation().z)); bulletAppState.getPhysicsSpace().add(player3); } terrain.addListener("physicsStartListener", new TerrainGridListener() { public void gridMoved(Vector3f newCenter) { } public Material tileLoaded(Material material, Vector3f cell) { return material; } public void tileAttached(Vector3f cell, TerrainQuad quad) { Texture alpha = assetManager.loadTexture("Scenes/TerrainAlphaTest/alphamap_" + Math.abs((int) (cell.x % 2)) * 512 + "_" + Math.abs((int) (cell.z % 2) * 512) + ".png"); quad.getMaterial().setTexture("AlphaMap", alpha); if (usePhysics) { quad.addControl(new RigidBodyControl(new HeightfieldCollisionShape(quad.getHeightMap(), terrain.getLocalScale()), 0)); bulletAppState.getPhysicsSpace().add(quad); } } public void tileDetached(Vector3f cell, TerrainQuad quad) { if (usePhysics) { bulletAppState.getPhysicsSpace().remove(quad); quad.removeControl(RigidBodyControl.class); } } }); this.terrain.initialize(cam.getLocation()); this.initKeys(); }
diff --git a/pixi/src/main/java/org/openpixi/pixi/physics/grid/CloudInCell.java b/pixi/src/main/java/org/openpixi/pixi/physics/grid/CloudInCell.java index 500299d4..548c5c92 100644 --- a/pixi/src/main/java/org/openpixi/pixi/physics/grid/CloudInCell.java +++ b/pixi/src/main/java/org/openpixi/pixi/physics/grid/CloudInCell.java @@ -1,68 +1,68 @@ package org.openpixi.pixi.physics.grid; import java.util.ArrayList; import org.openpixi.pixi.physics.Debug; import org.openpixi.pixi.physics.Particle2D; public class CloudInCell extends Interpolator { public CloudInCell() { super(); } - public void interpolateToGrid(ArrayList<Particle2D> particles, SimpleGrid g) { + public void interpolateToGrid(ArrayList<Particle2D> particles, Grid g) { for(Particle2D p : particles) { int xCellPosition = (int) (p.x / g.cellWidth + 1); int yCellPosition = (int) (p.y / g.cellHeight + 1); int xCellPosition2 = xCellPosition; int yCellPosition2 = yCellPosition; if(xCellPosition >= g.numCellsX + 1) { xCellPosition = g.numCellsX + 1; } else if(xCellPosition < 1) { xCellPosition = 1; } if(yCellPosition >= g.numCellsY + 1) { yCellPosition = g.numCellsY + 1; } else if(yCellPosition < 1) { yCellPosition = 1; } if (Debug.asserts) { // Assert conditions for interpolation assert xCellPosition2 * g.cellWidth > p.x; assert p.x > (xCellPosition2 - 1) * g.cellWidth : p.x; assert yCellPosition2 * g.cellHeight > p.y; assert p.y > (yCellPosition2 - 1) * g.cellHeight : p.y; } g.jx[xCellPosition][yCellPosition] += p.charge * p.vx * (xCellPosition2 * g.cellWidth - p.x) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition + 1][yCellPosition] += p.charge * p.vx * (p.x - (xCellPosition2-1) * g.cellWidth) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition][yCellPosition + 1] += p.charge * p.vx * (xCellPosition2 * g.cellWidth - p.x) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition + 1][yCellPosition + 1] += p.charge * p.vx * (p.x - (xCellPosition2-1) * g.cellWidth) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition][yCellPosition] += p.charge * p.vy * (xCellPosition2 * g.cellWidth - p.x) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition + 1][yCellPosition] += p.charge * p.vy * (p.x - (xCellPosition2-1) * g.cellWidth) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition][yCellPosition + 1] += p.charge * p.vy * (xCellPosition2 * g.cellWidth - p.x) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition + 1][yCellPosition + 1] += p.charge * p.vy * (p.x - (xCellPosition2-1) * g.cellWidth) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); } } public void interpolateToParticle(ArrayList<Particle2D> particles) { } }
true
true
public void interpolateToGrid(ArrayList<Particle2D> particles, SimpleGrid g) { for(Particle2D p : particles) { int xCellPosition = (int) (p.x / g.cellWidth + 1); int yCellPosition = (int) (p.y / g.cellHeight + 1); int xCellPosition2 = xCellPosition; int yCellPosition2 = yCellPosition; if(xCellPosition >= g.numCellsX + 1) { xCellPosition = g.numCellsX + 1; } else if(xCellPosition < 1) { xCellPosition = 1; } if(yCellPosition >= g.numCellsY + 1) { yCellPosition = g.numCellsY + 1; } else if(yCellPosition < 1) { yCellPosition = 1; } if (Debug.asserts) { // Assert conditions for interpolation assert xCellPosition2 * g.cellWidth > p.x; assert p.x > (xCellPosition2 - 1) * g.cellWidth : p.x; assert yCellPosition2 * g.cellHeight > p.y; assert p.y > (yCellPosition2 - 1) * g.cellHeight : p.y; } g.jx[xCellPosition][yCellPosition] += p.charge * p.vx * (xCellPosition2 * g.cellWidth - p.x) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition + 1][yCellPosition] += p.charge * p.vx * (p.x - (xCellPosition2-1) * g.cellWidth) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition][yCellPosition + 1] += p.charge * p.vx * (xCellPosition2 * g.cellWidth - p.x) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition + 1][yCellPosition + 1] += p.charge * p.vx * (p.x - (xCellPosition2-1) * g.cellWidth) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition][yCellPosition] += p.charge * p.vy * (xCellPosition2 * g.cellWidth - p.x) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition + 1][yCellPosition] += p.charge * p.vy * (p.x - (xCellPosition2-1) * g.cellWidth) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition][yCellPosition + 1] += p.charge * p.vy * (xCellPosition2 * g.cellWidth - p.x) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition + 1][yCellPosition + 1] += p.charge * p.vy * (p.x - (xCellPosition2-1) * g.cellWidth) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); } }
public void interpolateToGrid(ArrayList<Particle2D> particles, Grid g) { for(Particle2D p : particles) { int xCellPosition = (int) (p.x / g.cellWidth + 1); int yCellPosition = (int) (p.y / g.cellHeight + 1); int xCellPosition2 = xCellPosition; int yCellPosition2 = yCellPosition; if(xCellPosition >= g.numCellsX + 1) { xCellPosition = g.numCellsX + 1; } else if(xCellPosition < 1) { xCellPosition = 1; } if(yCellPosition >= g.numCellsY + 1) { yCellPosition = g.numCellsY + 1; } else if(yCellPosition < 1) { yCellPosition = 1; } if (Debug.asserts) { // Assert conditions for interpolation assert xCellPosition2 * g.cellWidth > p.x; assert p.x > (xCellPosition2 - 1) * g.cellWidth : p.x; assert yCellPosition2 * g.cellHeight > p.y; assert p.y > (yCellPosition2 - 1) * g.cellHeight : p.y; } g.jx[xCellPosition][yCellPosition] += p.charge * p.vx * (xCellPosition2 * g.cellWidth - p.x) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition + 1][yCellPosition] += p.charge * p.vx * (p.x - (xCellPosition2-1) * g.cellWidth) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition][yCellPosition + 1] += p.charge * p.vx * (xCellPosition2 * g.cellWidth - p.x) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jx[xCellPosition + 1][yCellPosition + 1] += p.charge * p.vx * (p.x - (xCellPosition2-1) * g.cellWidth) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition][yCellPosition] += p.charge * p.vy * (xCellPosition2 * g.cellWidth - p.x) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition + 1][yCellPosition] += p.charge * p.vy * (p.x - (xCellPosition2-1) * g.cellWidth) * (yCellPosition2 * g.cellHeight - p.y) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition][yCellPosition + 1] += p.charge * p.vy * (xCellPosition2 * g.cellWidth - p.x) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); g.jy[xCellPosition + 1][yCellPosition + 1] += p.charge * p.vy * (p.x - (xCellPosition2-1) * g.cellWidth) * (p.y - (yCellPosition2-1) * g.cellHeight) / (g.cellWidth * g.cellHeight); } }
diff --git a/src/dasher/TwoButtonDynamicFilter.java b/src/dasher/TwoButtonDynamicFilter.java index 941f9ae..3737b1d 100644 --- a/src/dasher/TwoButtonDynamicFilter.java +++ b/src/dasher/TwoButtonDynamicFilter.java @@ -1,98 +1,98 @@ package dasher; public class TwoButtonDynamicFilter extends CDynamicFilter { private BounceMarker up,down; private boolean m_bDecorationChanged; private double m_dNatsAtLastApply; //for debugging.... private double m_dNatsSinceLastApply; public TwoButtonDynamicFilter(CDasherInterfaceBase iface, CSettingsStore SettingsStore) { super(iface, SettingsStore, 19, "Two-button Dynamic Mode"); createMarkers(); } @Override public boolean DecorateView(CDasherView pView, CDasherInput pInput) { up.Draw(pView, m_dNatsSinceLastApply); down.Draw(pView, m_dNatsSinceLastApply); if (m_bDecorationChanged || BounceMarker.DEBUG_LEARNING) { m_bDecorationChanged=false; return true; } return false; } @Override public boolean TimerImpl(long Time, CDasherView pView,CDasherModel pModel) { m_dNatsSinceLastApply = pModel.GetNats() - m_dNatsAtLastApply; pModel.oneStepTowards(0, GetLongParameter(Elp_parameters.LP_OY), Time, 1.0f); return true; } @Override public void HandleEvent(CEvent evt) { if (evt instanceof CParameterNotificationEvent && ((CParameterNotificationEvent)evt).m_iParameter==Elp_parameters.LP_TWO_BUTTON_OFFSET) createMarkers(); super.HandleEvent(evt); } private void createMarkers() { up = new BounceMarker((int)GetLongParameter(Elp_parameters.LP_TWO_BUTTON_OFFSET)); down = new BounceMarker((int)-GetLongParameter(Elp_parameters.LP_TWO_BUTTON_OFFSET)); m_bDecorationChanged=true; } private final long[] coords=new long[2]; @Override public void KeyDown(long iTime, int iId, CDasherView pView, CDasherInput pInput, CDasherModel pModel) { if (iId==100 && pInput.GetDasherCoords(pView, coords)) iId = (coords[1] < GetLongParameter(Elp_parameters.LP_OY)) ? 0 : 1; super.KeyDown(iTime, iId, pView, pInput, pModel); } @Override public void KeyUp(long iTime, int iId, CDasherView pView, CDasherInput pInput, CDasherModel pModel) { if (iId==100 && pInput.GetDasherCoords(pView, coords)) iId = (coords[1] < GetLongParameter(Elp_parameters.LP_OY)) ? 0 : 1; super.KeyUp(iTime, iId, pView, pInput, pModel); } @Override public void Event(long iTime, int iId, int pressType, CDasherModel pModel) { marker: if (pressType==SINGLE_PRESS && getState()==RUNNING) { BounceMarker pMarker; - if (iId==0) pMarker=up; else if (iId==1) pMarker=down; else break marker; + if (iId==0 || iId==4) pMarker=up; else if (iId==1 || iId==2) pMarker=down; else break marker; //apply offset double dCurBitrate = GetLongParameter(Elp_parameters.LP_MAX_BITRATE) * GetLongParameter(Elp_parameters.LP_BOOSTFACTOR) / 10000.0; int iOffset = pMarker.GetTargetOffset(dCurBitrate); if (pModel.m_iDisplayOffset!=0) System.err.println("Display Offset "+pModel.m_iDisplayOffset+" reducing to "+(iOffset -= pModel.m_iDisplayOffset)); double dNewNats = pModel.GetNats() - m_dNatsAtLastApply; up.NotifyOffset(iOffset, dNewNats); down.NotifyOffset(iOffset, dNewNats); pMarker.addPush(iOffset, dCurBitrate); pModel.Offset(iOffset); m_dNatsAtLastApply = pModel.GetNats(); } super.Event(iTime, iId, pressType, pModel); } @Override public void reverse(long iTime, CDasherModel pModel) { pModel.MatchTarget(); up.clearPushes(); down.clearPushes(); super.reverse(iTime, pModel); } @Override public void Activate() { super.Activate(); m_Interface.SetBoolParameter(Ebp_parameters.BP_DELAY_VIEW, true); } @Override public void Deactivate() { m_Interface.SetBoolParameter(Ebp_parameters.BP_DELAY_VIEW, false); super.Deactivate(); } }
true
true
@Override public void Event(long iTime, int iId, int pressType, CDasherModel pModel) { marker: if (pressType==SINGLE_PRESS && getState()==RUNNING) { BounceMarker pMarker; if (iId==0) pMarker=up; else if (iId==1) pMarker=down; else break marker; //apply offset double dCurBitrate = GetLongParameter(Elp_parameters.LP_MAX_BITRATE) * GetLongParameter(Elp_parameters.LP_BOOSTFACTOR) / 10000.0; int iOffset = pMarker.GetTargetOffset(dCurBitrate); if (pModel.m_iDisplayOffset!=0) System.err.println("Display Offset "+pModel.m_iDisplayOffset+" reducing to "+(iOffset -= pModel.m_iDisplayOffset)); double dNewNats = pModel.GetNats() - m_dNatsAtLastApply; up.NotifyOffset(iOffset, dNewNats); down.NotifyOffset(iOffset, dNewNats); pMarker.addPush(iOffset, dCurBitrate); pModel.Offset(iOffset); m_dNatsAtLastApply = pModel.GetNats(); } super.Event(iTime, iId, pressType, pModel); }
@Override public void Event(long iTime, int iId, int pressType, CDasherModel pModel) { marker: if (pressType==SINGLE_PRESS && getState()==RUNNING) { BounceMarker pMarker; if (iId==0 || iId==4) pMarker=up; else if (iId==1 || iId==2) pMarker=down; else break marker; //apply offset double dCurBitrate = GetLongParameter(Elp_parameters.LP_MAX_BITRATE) * GetLongParameter(Elp_parameters.LP_BOOSTFACTOR) / 10000.0; int iOffset = pMarker.GetTargetOffset(dCurBitrate); if (pModel.m_iDisplayOffset!=0) System.err.println("Display Offset "+pModel.m_iDisplayOffset+" reducing to "+(iOffset -= pModel.m_iDisplayOffset)); double dNewNats = pModel.GetNats() - m_dNatsAtLastApply; up.NotifyOffset(iOffset, dNewNats); down.NotifyOffset(iOffset, dNewNats); pMarker.addPush(iOffset, dCurBitrate); pModel.Offset(iOffset); m_dNatsAtLastApply = pModel.GetNats(); } super.Event(iTime, iId, pressType, pModel); }
diff --git a/src/scripts/clusterManipulations/GenerateCountSHFiles.java b/src/scripts/clusterManipulations/GenerateCountSHFiles.java index 8e357e3d..ee20f051 100644 --- a/src/scripts/clusterManipulations/GenerateCountSHFiles.java +++ b/src/scripts/clusterManipulations/GenerateCountSHFiles.java @@ -1,37 +1,37 @@ /** * Author: [email protected] * This code 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, * provided that any use properly credits the author. * 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 at http://www.gnu.org * * */ package scripts.clusterManipulations; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; public class GenerateCountSHFiles { public static void main(String[] args) throws Exception { BufferedWriter writer = new BufferedWriter( new FileWriter(new File("/projects/afodor/shotgunSequences/runManyCounts.sh"))); for( int x=1; x <=20; x++) { - writer.write("qsub -q \"viper\" -N \"CountJob" + x + " java -cp /users/afodor/metagenomicsTools/bin " + + writer.write("qsub -q \"viper\" -N \"CountJob" + x + "\" java -cp /users/afodor/metagenomicsTools/bin " + "scripts.clusterManipulations.MapBlastHitsToBitScore " + "/projects/afodor/shotgunSequences/SRR061115.fasta_FILE_" + x + "_TO_NCBI.txt.gz " + "/projects/afodor/shotgunSequences/SRR061115_fasta_bitScoreCounts_" + x + ".txt\n"); } writer.flush(); writer.close(); } }
true
true
public static void main(String[] args) throws Exception { BufferedWriter writer = new BufferedWriter( new FileWriter(new File("/projects/afodor/shotgunSequences/runManyCounts.sh"))); for( int x=1; x <=20; x++) { writer.write("qsub -q \"viper\" -N \"CountJob" + x + " java -cp /users/afodor/metagenomicsTools/bin " + "scripts.clusterManipulations.MapBlastHitsToBitScore " + "/projects/afodor/shotgunSequences/SRR061115.fasta_FILE_" + x + "_TO_NCBI.txt.gz " + "/projects/afodor/shotgunSequences/SRR061115_fasta_bitScoreCounts_" + x + ".txt\n"); } writer.flush(); writer.close(); }
public static void main(String[] args) throws Exception { BufferedWriter writer = new BufferedWriter( new FileWriter(new File("/projects/afodor/shotgunSequences/runManyCounts.sh"))); for( int x=1; x <=20; x++) { writer.write("qsub -q \"viper\" -N \"CountJob" + x + "\" java -cp /users/afodor/metagenomicsTools/bin " + "scripts.clusterManipulations.MapBlastHitsToBitScore " + "/projects/afodor/shotgunSequences/SRR061115.fasta_FILE_" + x + "_TO_NCBI.txt.gz " + "/projects/afodor/shotgunSequences/SRR061115_fasta_bitScoreCounts_" + x + ".txt\n"); } writer.flush(); writer.close(); }
diff --git a/52n-sos-importer-core/src/main/java/org/n52/sos/importer/model/xml/Step1ModelHandler.java b/52n-sos-importer-core/src/main/java/org/n52/sos/importer/model/xml/Step1ModelHandler.java index 5af289c1..4b88e34d 100644 --- a/52n-sos-importer-core/src/main/java/org/n52/sos/importer/model/xml/Step1ModelHandler.java +++ b/52n-sos-importer-core/src/main/java/org/n52/sos/importer/model/xml/Step1ModelHandler.java @@ -1,95 +1,95 @@ /** * Copyright (C) 2012 * by 52North Initiative for Geospatial Open Source Software GmbH * * Contact: Andreas Wytzisk * 52 North Initiative for Geospatial Open Source Software GmbH * Martin-Luther-King-Weg 24 * 48155 Muenster, Germany * [email protected] * * This program is free software; you can redistribute and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * * This program is distributed WITHOUT ANY WARRANTY; even without 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 (see gnu-gpl v2.txt). If not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or * visit the Free Software Foundation web page, http://www.fsf.org. */ package org.n52.sos.importer.model.xml; import org.apache.log4j.Logger; import org.n52.sos.importer.model.Step1Model; import org.n52.sos.importer.view.Step1Panel; import org.x52North.sensorweb.sos.importer.x02.CredentialsDocument.Credentials; import org.x52North.sensorweb.sos.importer.x02.DataFileDocument.DataFile; import org.x52North.sensorweb.sos.importer.x02.LocalFileDocument.LocalFile; import org.x52North.sensorweb.sos.importer.x02.RemoteFileDocument.RemoteFile; import org.x52North.sensorweb.sos.importer.x02.SosImportConfigurationDocument.SosImportConfiguration; /** * Get updates from Step1Model<br /> * Provided information: * <ul> * <li>DataFile.LocalFile.Path</li> * </ul> * @author <a href="mailto:[email protected]">Eike Hinderk J&uuml;rrens</a> */ public class Step1ModelHandler implements ModelHandler<Step1Model> { private static final Logger logger = Logger.getLogger(Step1ModelHandler.class); @Override - public void handleModel(Step1Model stepModel, SosImportConfiguration sosImportConf) { + public void handleModel(final Step1Model stepModel, final SosImportConfiguration sosImportConf) { if (logger.isTraceEnabled()) { logger.trace("handleModel()"); } DataFile dF = sosImportConf.getDataFile(); if (dF == null) { dF = sosImportConf.addNewDataFile(); } if (stepModel.getFeedingType() == Step1Panel.CSV_FILE) { if (dF.getRemoteFile() != null) { // TODO remove old dF.setRemoteFile(null); } - LocalFile lF = (dF.getLocalFile() == null) ? dF.addNewLocalFile() : dF.getLocalFile(); - String path = stepModel.getCSVFilePath(); + final LocalFile lF = (dF.getLocalFile() == null) ? dF.addNewLocalFile() : dF.getLocalFile(); + final String path = stepModel.getCSVFilePath(); if (path != null && !path.equals("")) { lF.setPath(path); } else { - String msg = "empty path to CSV file in Step1Model: " + path; + final String msg = "empty path to CSV file in Step1Model: " + path; logger.error(msg); throw new NullPointerException(msg); } } else { if (dF.getLocalFile() != null) { // TODO remove old dF.setLocalFile(null); } - RemoteFile rF = (dF.getRemoteFile() == null)? dF.addNewRemoteFile() : dF.getRemoteFile(); + final RemoteFile rF = (dF.getRemoteFile() == null)? dF.addNewRemoteFile() : dF.getRemoteFile(); String url = stepModel.getUrl(); if (stepModel.getDirectory() != null && url.charAt(url.length() - 1) != '/' && stepModel.getDirectory().charAt(0) != '/') { url += '/'; } url += stepModel.getDirectory(); if (url.charAt(url.length() - 1) != '/' && stepModel.getFilenameSchema().charAt(0) != '/') { url += '/'; } url += stepModel.getFilenameSchema(); rF.setURL(url); - Credentials cDoc = (rF.getCredentials() == null)? rF.addNewCredentials() : rF.getCredentials(); + final Credentials cDoc = (rF.getCredentials() == null)? rF.addNewCredentials() : rF.getCredentials(); cDoc.setUserName(stepModel.getUser()); cDoc.setPassword(stepModel.getPassword()); } - dF.setRefenceIsARegularExpression(stepModel.isRegex()); + dF.setReferenceIsARegularExpression(stepModel.isRegex()); } }
false
true
public void handleModel(Step1Model stepModel, SosImportConfiguration sosImportConf) { if (logger.isTraceEnabled()) { logger.trace("handleModel()"); } DataFile dF = sosImportConf.getDataFile(); if (dF == null) { dF = sosImportConf.addNewDataFile(); } if (stepModel.getFeedingType() == Step1Panel.CSV_FILE) { if (dF.getRemoteFile() != null) { // TODO remove old dF.setRemoteFile(null); } LocalFile lF = (dF.getLocalFile() == null) ? dF.addNewLocalFile() : dF.getLocalFile(); String path = stepModel.getCSVFilePath(); if (path != null && !path.equals("")) { lF.setPath(path); } else { String msg = "empty path to CSV file in Step1Model: " + path; logger.error(msg); throw new NullPointerException(msg); } } else { if (dF.getLocalFile() != null) { // TODO remove old dF.setLocalFile(null); } RemoteFile rF = (dF.getRemoteFile() == null)? dF.addNewRemoteFile() : dF.getRemoteFile(); String url = stepModel.getUrl(); if (stepModel.getDirectory() != null && url.charAt(url.length() - 1) != '/' && stepModel.getDirectory().charAt(0) != '/') { url += '/'; } url += stepModel.getDirectory(); if (url.charAt(url.length() - 1) != '/' && stepModel.getFilenameSchema().charAt(0) != '/') { url += '/'; } url += stepModel.getFilenameSchema(); rF.setURL(url); Credentials cDoc = (rF.getCredentials() == null)? rF.addNewCredentials() : rF.getCredentials(); cDoc.setUserName(stepModel.getUser()); cDoc.setPassword(stepModel.getPassword()); } dF.setRefenceIsARegularExpression(stepModel.isRegex()); }
public void handleModel(final Step1Model stepModel, final SosImportConfiguration sosImportConf) { if (logger.isTraceEnabled()) { logger.trace("handleModel()"); } DataFile dF = sosImportConf.getDataFile(); if (dF == null) { dF = sosImportConf.addNewDataFile(); } if (stepModel.getFeedingType() == Step1Panel.CSV_FILE) { if (dF.getRemoteFile() != null) { // TODO remove old dF.setRemoteFile(null); } final LocalFile lF = (dF.getLocalFile() == null) ? dF.addNewLocalFile() : dF.getLocalFile(); final String path = stepModel.getCSVFilePath(); if (path != null && !path.equals("")) { lF.setPath(path); } else { final String msg = "empty path to CSV file in Step1Model: " + path; logger.error(msg); throw new NullPointerException(msg); } } else { if (dF.getLocalFile() != null) { // TODO remove old dF.setLocalFile(null); } final RemoteFile rF = (dF.getRemoteFile() == null)? dF.addNewRemoteFile() : dF.getRemoteFile(); String url = stepModel.getUrl(); if (stepModel.getDirectory() != null && url.charAt(url.length() - 1) != '/' && stepModel.getDirectory().charAt(0) != '/') { url += '/'; } url += stepModel.getDirectory(); if (url.charAt(url.length() - 1) != '/' && stepModel.getFilenameSchema().charAt(0) != '/') { url += '/'; } url += stepModel.getFilenameSchema(); rF.setURL(url); final Credentials cDoc = (rF.getCredentials() == null)? rF.addNewCredentials() : rF.getCredentials(); cDoc.setUserName(stepModel.getUser()); cDoc.setPassword(stepModel.getPassword()); } dF.setReferenceIsARegularExpression(stepModel.isRegex()); }
diff --git a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/jobs/ListTagsJob.java b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/jobs/ListTagsJob.java index 0baf767a..8a7336f3 100644 --- a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/jobs/ListTagsJob.java +++ b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/jobs/ListTagsJob.java @@ -1,161 +1,162 @@ /******************************************************************************* * Copyright (c) 2012 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.orion.server.git.jobs; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.Map.Entry; import javax.servlet.http.HttpServletResponse; import org.eclipse.core.runtime.*; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.LogCommand; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.*; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.storage.file.FileRepository; import org.eclipse.orion.internal.server.servlets.ProtocolConstants; import org.eclipse.orion.server.core.ServerStatus; import org.eclipse.orion.server.git.GitActivator; import org.eclipse.orion.server.git.GitConstants; import org.eclipse.orion.server.git.objects.Log; import org.eclipse.orion.server.git.objects.Tag; import org.eclipse.orion.server.git.servlets.GitUtils; import org.eclipse.osgi.util.NLS; import org.json.JSONArray; import org.json.JSONObject; /** * This job handles generating tag list * */ public class ListTagsJob extends GitJob { private IPath path; private URI cloneLocation; private int commitsSize; private int pageNo; private int pageSize; private String baseLocation; /** * Creates job with given page range and adding <code>commitsSize</code> commits to every tag. * @param userRunningTask * @param repositoryPath * @param cloneLocation * @param commitsSize user 0 to omit adding any log, only CommitLocation will be attached * @param pageNo * @param pageSize use negative to indicate that all commits need to be returned * @param baseLocation URI used as a base for generating next and previous page links. Should not contain any parameters. */ public ListTagsJob(String userRunningTask, IPath repositoryPath, URI cloneLocation, int commitsSize, int pageNo, int pageSize, String baseLocation) { super(NLS.bind("Generating tags list for {0}", repositoryPath), userRunningTask, NLS.bind("Generating tags list for {0}...", repositoryPath), true, false); this.path = repositoryPath; this.cloneLocation = cloneLocation; this.commitsSize = commitsSize; this.pageNo = pageNo; this.pageSize = pageSize; this.baseLocation = baseLocation; setFinalMessage("Generating tags list completed"); } /** * Creates job returning list of all tags adding <code>commitsSize</code> commits to every tag. * @param userRunningTask * @param repositoryPath * @param cloneLocation * @param commitsSize */ public ListTagsJob(String userRunningTask, IPath repositoryPath, URI cloneLocation, int commitsSize) { this(userRunningTask, repositoryPath, cloneLocation, commitsSize, 1, -1, null); } /** * Creates job returning list of all tags. * @param userRunningTask * @param repositoryPath * @param cloneLocation */ public ListTagsJob(String userRunningTask, IPath repositoryPath, URI cloneLocation) { this(userRunningTask, repositoryPath, cloneLocation, 0); } private ObjectId getCommitObjectId(Repository db, ObjectId oid) throws MissingObjectException, IncorrectObjectTypeException, IOException { RevWalk walk = new RevWalk(db); try { return walk.parseCommit(oid); } finally { walk.release(); } } @Override protected IStatus performJob() { try { // list all tags File gitDir = GitUtils.getGitDir(path); Repository db = new FileRepository(gitDir); // TODO: bug 356943 - revert when bug 360650 is fixed // List<RevTag> revTags = git.tagList().call(); Map<String, Ref> refs = db.getRefDatabase().getRefs(Constants.R_TAGS); JSONObject result = new JSONObject(); List<Tag> tags = new ArrayList<Tag>(); for (Entry<String, Ref> refEntry : refs.entrySet()) { Tag tag = new Tag(cloneLocation, db, refEntry.getValue()); tags.add(tag); } Collections.sort(tags, Tag.COMPARATOR); JSONArray children = new JSONArray(); Git git = new Git(db); int firstTag = pageSize > 0 ? pageSize * (pageNo - 1) : 0; int lastTag = pageSize > 0 ? firstTag + pageSize - 1 : tags.size() - 1; + lastTag = lastTag > tags.size() - 1 ? tags.size() - 1 : lastTag; if (pageNo > 1 && baseLocation != null) { String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev); } if (lastTag < tags.size() - 1) { String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_NEXT_LOCATION, next); } for (int i = firstTag; i <= lastTag; i++) { Tag tag = tags.get(i); if (this.commitsSize == 0) { children.put(tag.toJSON()); } else { LogCommand lc = git.log(); String toCommitName = tag.getRevCommitName(); ObjectId toCommitId = db.resolve(toCommitName); Ref toCommitRef = db.getRef(toCommitName); toCommitId = getCommitObjectId(db, toCommitId); lc.add(toCommitId); lc.setMaxCount(this.commitsSize); Iterable<RevCommit> commits = lc.call(); Log log = new Log(cloneLocation, db, commits, null, null, toCommitRef); children.put(tag.toJSON(log.toJSON(1, commitsSize))); } } result.put(ProtocolConstants.KEY_CHILDREN, children); return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } catch (Exception e) { String msg = NLS.bind("An error occured when listing tags for {0}", path); return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e); } } }
true
true
protected IStatus performJob() { try { // list all tags File gitDir = GitUtils.getGitDir(path); Repository db = new FileRepository(gitDir); // TODO: bug 356943 - revert when bug 360650 is fixed // List<RevTag> revTags = git.tagList().call(); Map<String, Ref> refs = db.getRefDatabase().getRefs(Constants.R_TAGS); JSONObject result = new JSONObject(); List<Tag> tags = new ArrayList<Tag>(); for (Entry<String, Ref> refEntry : refs.entrySet()) { Tag tag = new Tag(cloneLocation, db, refEntry.getValue()); tags.add(tag); } Collections.sort(tags, Tag.COMPARATOR); JSONArray children = new JSONArray(); Git git = new Git(db); int firstTag = pageSize > 0 ? pageSize * (pageNo - 1) : 0; int lastTag = pageSize > 0 ? firstTag + pageSize - 1 : tags.size() - 1; if (pageNo > 1 && baseLocation != null) { String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev); } if (lastTag < tags.size() - 1) { String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_NEXT_LOCATION, next); } for (int i = firstTag; i <= lastTag; i++) { Tag tag = tags.get(i); if (this.commitsSize == 0) { children.put(tag.toJSON()); } else { LogCommand lc = git.log(); String toCommitName = tag.getRevCommitName(); ObjectId toCommitId = db.resolve(toCommitName); Ref toCommitRef = db.getRef(toCommitName); toCommitId = getCommitObjectId(db, toCommitId); lc.add(toCommitId); lc.setMaxCount(this.commitsSize); Iterable<RevCommit> commits = lc.call(); Log log = new Log(cloneLocation, db, commits, null, null, toCommitRef); children.put(tag.toJSON(log.toJSON(1, commitsSize))); } } result.put(ProtocolConstants.KEY_CHILDREN, children); return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } catch (Exception e) { String msg = NLS.bind("An error occured when listing tags for {0}", path); return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e); } }
protected IStatus performJob() { try { // list all tags File gitDir = GitUtils.getGitDir(path); Repository db = new FileRepository(gitDir); // TODO: bug 356943 - revert when bug 360650 is fixed // List<RevTag> revTags = git.tagList().call(); Map<String, Ref> refs = db.getRefDatabase().getRefs(Constants.R_TAGS); JSONObject result = new JSONObject(); List<Tag> tags = new ArrayList<Tag>(); for (Entry<String, Ref> refEntry : refs.entrySet()) { Tag tag = new Tag(cloneLocation, db, refEntry.getValue()); tags.add(tag); } Collections.sort(tags, Tag.COMPARATOR); JSONArray children = new JSONArray(); Git git = new Git(db); int firstTag = pageSize > 0 ? pageSize * (pageNo - 1) : 0; int lastTag = pageSize > 0 ? firstTag + pageSize - 1 : tags.size() - 1; lastTag = lastTag > tags.size() - 1 ? tags.size() - 1 : lastTag; if (pageNo > 1 && baseLocation != null) { String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev); } if (lastTag < tags.size() - 1) { String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_NEXT_LOCATION, next); } for (int i = firstTag; i <= lastTag; i++) { Tag tag = tags.get(i); if (this.commitsSize == 0) { children.put(tag.toJSON()); } else { LogCommand lc = git.log(); String toCommitName = tag.getRevCommitName(); ObjectId toCommitId = db.resolve(toCommitName); Ref toCommitRef = db.getRef(toCommitName); toCommitId = getCommitObjectId(db, toCommitId); lc.add(toCommitId); lc.setMaxCount(this.commitsSize); Iterable<RevCommit> commits = lc.call(); Log log = new Log(cloneLocation, db, commits, null, null, toCommitRef); children.put(tag.toJSON(log.toJSON(1, commitsSize))); } } result.put(ProtocolConstants.KEY_CHILDREN, children); return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } catch (Exception e) { String msg = NLS.bind("An error occured when listing tags for {0}", path); return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e); } }
diff --git a/src/main/java/com/redhat/topicindex/extras/client/local/view/BulkImageUpdaterView.java b/src/main/java/com/redhat/topicindex/extras/client/local/view/BulkImageUpdaterView.java index 45ff1c2..150f502 100644 --- a/src/main/java/com/redhat/topicindex/extras/client/local/view/BulkImageUpdaterView.java +++ b/src/main/java/com/redhat/topicindex/extras/client/local/view/BulkImageUpdaterView.java @@ -1,150 +1,150 @@ package com.redhat.topicindex.extras.client.local.view; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DecoratorPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import com.smartgwt.client.widgets.Progressbar; import com.redhat.topicindex.extras.client.local.presenter.BulkImageUpdaterPresenter; public class BulkImageUpdaterView extends Composite implements BulkImageUpdaterPresenter.Display { public static final String HISTORY_TOKEN = "BulkImageUpdaterView"; private final TextBox topicSearch = new TextBox(); private final Button go = new Button("Search"); private final Button bulkUpdate = new Button("Update All Topics With All Images"); private final Button updateTopic = new Button("Update Selected Topic With All Images"); private final Button updateImage = new Button("Update Selected Topic With Selected Image"); private final ListBox topicMatches = new ListBox(false); private final ListBox imageMatches = new ListBox(false); private final Progressbar progress = new Progressbar(); private final TextArea log = new TextArea(); private final TextArea xml = new TextArea(); public Button getUpdateTopic() { return updateTopic; } public TextArea getXml() { return xml; } public TextArea getLog() { return log; } public Button getBulkUpdate() { return bulkUpdate; } public Progressbar getProgress() { return progress; } public ListBox getTopicMatches() { return topicMatches; } public Button getGo() { return go; } public TextBox getTopicSearch() { return topicSearch; } public ListBox getImageMatches() { return imageMatches; } public BulkImageUpdaterView() { final DecoratorPanel contentTableDecorator = new DecoratorPanel(); initWidget(contentTableDecorator); progress.setVisible(false); log.setReadOnly(true); xml.setReadOnly(true); final Grid layoutGrid = new Grid(5, 2); topicSearch.setWidth("500px"); - final Label topicSearchLabel = new Label("Enter the tag that identifies the topics"); + final Label topicSearchLabel = new Label("Enter the Tag ID That Identifies the Topics"); layoutGrid.setWidget(0, 0, topicSearchLabel); final HorizontalPanel searchPanel = new HorizontalPanel(); searchPanel.setSpacing(10); layoutGrid.setWidget(0, 1, searchPanel); searchPanel.add(topicSearch); searchPanel.add(go); searchPanel.add(progress); - final Label actionsLabel = new Label("Select an action to perform"); + final Label actionsLabel = new Label("Select an Action to Perform"); layoutGrid.setWidget(1, 0, actionsLabel); final HorizontalPanel buttonLayout = new HorizontalPanel(); buttonLayout.setSpacing(10); layoutGrid.setWidget(1, 1, buttonLayout); buttonLayout.add(bulkUpdate); buttonLayout.add(updateTopic); buttonLayout.add(updateImage); topicMatches.setWidth("600px"); topicMatches.setHeight("300px"); topicMatches.setVisibleItemCount(10); imageMatches.setWidth("600px"); imageMatches.setHeight("300px"); imageMatches.setVisibleItemCount(10); - final Label topicMatchLabel = new Label("The following topics have references to images"); + final Label topicMatchLabel = new Label("The Following Topics Have References to Images"); layoutGrid.setWidget(2, 0, topicMatchLabel); final HorizontalPanel listPanel = new HorizontalPanel(); layoutGrid.setWidget(2, 1, listPanel); listPanel.add(topicMatches); listPanel.add(imageMatches); xml.setWidth("1200px"); xml.setHeight("300px"); final Label xmlLabel = new Label("Selected Topic's XML"); layoutGrid.setWidget(3, 0, xmlLabel); layoutGrid.setWidget(3, 1, xml); log.setWidth("1200px"); log.setHeight("300px"); - final Label logLabel = new Label("Log output"); + final Label logLabel = new Label("Log Output"); layoutGrid.setWidget(4, 0, logLabel); layoutGrid.setWidget(4, 1, log); contentTableDecorator.add(layoutGrid); } @Override public Widget asWidget() { return this; } public Button getUpdateImage() { return updateImage; } }
false
true
public BulkImageUpdaterView() { final DecoratorPanel contentTableDecorator = new DecoratorPanel(); initWidget(contentTableDecorator); progress.setVisible(false); log.setReadOnly(true); xml.setReadOnly(true); final Grid layoutGrid = new Grid(5, 2); topicSearch.setWidth("500px"); final Label topicSearchLabel = new Label("Enter the tag that identifies the topics"); layoutGrid.setWidget(0, 0, topicSearchLabel); final HorizontalPanel searchPanel = new HorizontalPanel(); searchPanel.setSpacing(10); layoutGrid.setWidget(0, 1, searchPanel); searchPanel.add(topicSearch); searchPanel.add(go); searchPanel.add(progress); final Label actionsLabel = new Label("Select an action to perform"); layoutGrid.setWidget(1, 0, actionsLabel); final HorizontalPanel buttonLayout = new HorizontalPanel(); buttonLayout.setSpacing(10); layoutGrid.setWidget(1, 1, buttonLayout); buttonLayout.add(bulkUpdate); buttonLayout.add(updateTopic); buttonLayout.add(updateImage); topicMatches.setWidth("600px"); topicMatches.setHeight("300px"); topicMatches.setVisibleItemCount(10); imageMatches.setWidth("600px"); imageMatches.setHeight("300px"); imageMatches.setVisibleItemCount(10); final Label topicMatchLabel = new Label("The following topics have references to images"); layoutGrid.setWidget(2, 0, topicMatchLabel); final HorizontalPanel listPanel = new HorizontalPanel(); layoutGrid.setWidget(2, 1, listPanel); listPanel.add(topicMatches); listPanel.add(imageMatches); xml.setWidth("1200px"); xml.setHeight("300px"); final Label xmlLabel = new Label("Selected Topic's XML"); layoutGrid.setWidget(3, 0, xmlLabel); layoutGrid.setWidget(3, 1, xml); log.setWidth("1200px"); log.setHeight("300px"); final Label logLabel = new Label("Log output"); layoutGrid.setWidget(4, 0, logLabel); layoutGrid.setWidget(4, 1, log); contentTableDecorator.add(layoutGrid); }
public BulkImageUpdaterView() { final DecoratorPanel contentTableDecorator = new DecoratorPanel(); initWidget(contentTableDecorator); progress.setVisible(false); log.setReadOnly(true); xml.setReadOnly(true); final Grid layoutGrid = new Grid(5, 2); topicSearch.setWidth("500px"); final Label topicSearchLabel = new Label("Enter the Tag ID That Identifies the Topics"); layoutGrid.setWidget(0, 0, topicSearchLabel); final HorizontalPanel searchPanel = new HorizontalPanel(); searchPanel.setSpacing(10); layoutGrid.setWidget(0, 1, searchPanel); searchPanel.add(topicSearch); searchPanel.add(go); searchPanel.add(progress); final Label actionsLabel = new Label("Select an Action to Perform"); layoutGrid.setWidget(1, 0, actionsLabel); final HorizontalPanel buttonLayout = new HorizontalPanel(); buttonLayout.setSpacing(10); layoutGrid.setWidget(1, 1, buttonLayout); buttonLayout.add(bulkUpdate); buttonLayout.add(updateTopic); buttonLayout.add(updateImage); topicMatches.setWidth("600px"); topicMatches.setHeight("300px"); topicMatches.setVisibleItemCount(10); imageMatches.setWidth("600px"); imageMatches.setHeight("300px"); imageMatches.setVisibleItemCount(10); final Label topicMatchLabel = new Label("The Following Topics Have References to Images"); layoutGrid.setWidget(2, 0, topicMatchLabel); final HorizontalPanel listPanel = new HorizontalPanel(); layoutGrid.setWidget(2, 1, listPanel); listPanel.add(topicMatches); listPanel.add(imageMatches); xml.setWidth("1200px"); xml.setHeight("300px"); final Label xmlLabel = new Label("Selected Topic's XML"); layoutGrid.setWidget(3, 0, xmlLabel); layoutGrid.setWidget(3, 1, xml); log.setWidth("1200px"); log.setHeight("300px"); final Label logLabel = new Label("Log Output"); layoutGrid.setWidget(4, 0, logLabel); layoutGrid.setWidget(4, 1, log); contentTableDecorator.add(layoutGrid); }
diff --git a/src/org/openmrs/module/report/util/ReportUtil.java b/src/org/openmrs/module/report/util/ReportUtil.java index bffe2db8..9bd62e4a 100644 --- a/src/org/openmrs/module/report/util/ReportUtil.java +++ b/src/org/openmrs/module/report/util/ReportUtil.java @@ -1,225 +1,227 @@ package org.openmrs.module.report.util; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.openmrs.Program; import org.openmrs.api.context.Context; import org.openmrs.module.cohort.definition.AgeCohortDefinition; import org.openmrs.module.cohort.definition.CohortDefinition; import org.openmrs.module.cohort.definition.GenderCohortDefinition; import org.openmrs.module.cohort.definition.ProgramStateCohortDefinition; import org.openmrs.module.cohort.definition.service.CohortDefinitionService; import org.openmrs.module.evaluation.parameter.Mapped; import org.openmrs.module.evaluation.parameter.Parameter; import org.openmrs.module.indicator.CohortIndicator; import org.openmrs.module.indicator.Indicator; import org.openmrs.module.indicator.PeriodCohortIndicator; import org.openmrs.module.indicator.dimension.CohortDefinitionDimension; import org.openmrs.module.indicator.dimension.Dimension; import org.openmrs.module.indicator.service.IndicatorService; public class ReportUtil { public static List<InitialDataElement> getInitialDataElements() { List<InitialDataElement> ret = new ArrayList<InitialDataElement>(); ret.add(new InitialDataElement(CohortDefinition.class, "Female") { public void apply() { GenderCohortDefinition female = new GenderCohortDefinition("F"); female.setName("Female"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(female); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Male") { public void apply() { GenderCohortDefinition male = new GenderCohortDefinition("M"); male.setName("Male"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(male); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Age Range on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.addParameter(new Parameter("minAge", "minAge", Integer.class)); age.addParameter(new Parameter("maxAge", "maxAge", Integer.class)); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Age Range on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Child on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.setMaxAge(14); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Child on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Adult on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.setMinAge(15); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Adult on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); for (final Program program : Context.getProgramWorkflowService().getAllPrograms()) { ret.add(new InitialDataElement(CohortDefinition.class, "Ever in " + program.getName() + " Before Date") { public void apply() { ProgramStateCohortDefinition def = new ProgramStateCohortDefinition(); def.setProgram(program); def.addParameter(new Parameter("untilDate", "untilDate", Date.class)); def.setName("Ever in " + program.getName() + " Before Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); ret.add(new InitialDataElement(CohortDefinition.class, "In " + program.getName() + " Between Dates") { public void apply() { ProgramStateCohortDefinition def = new ProgramStateCohortDefinition(); def.setProgram(program); def.addParameter(new Parameter("sinceDate", "sinceDate", Date.class)); def.addParameter(new Parameter("untilDate", "untilDate", Date.class)); def.setName("In " + program.getName() + " Between Dates"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); } /* ret.add(new InitialDataElement(CohortDefinition.class, "") { public void apply() { Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); */ ret.add(new InitialDataElement(Dimension.class, "Gender") { public void apply() { CohortDefinition female = getCohortDefinition("Female"); CohortDefinition male = getCohortDefinition("Male"); if (male == null || female == null) { throw new IllegalArgumentException("Cannot create Gender dimension without Male and Female cohort definitions"); } CohortDefinitionDimension gender = new CohortDefinitionDimension(); gender.setName("Gender"); gender.addCohortDefinition("female", female, null); gender.addCohortDefinition("male", male, null); Context.getService(IndicatorService.class).saveDimension(gender); } }); for (final Program program : Context.getProgramWorkflowService().getAllPrograms()) { ret.add(new InitialDataElement(Indicator.class, "Cumulative " + program.getName() + " enrollment at start") { public void apply() { CohortDefinition inProg = getCohortDefinition("Ever in " + program.getName() + " Before Date"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("untilDate", "${startDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Cumulative " + program.getName() + " enrollment at start"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Cumulative " + program.getName() + " enrollment at end") { public void apply() { CohortDefinition inProg = getCohortDefinition("Ever in " + program.getName() + " Before Date"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("untilDate", "${endDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Cumulative " + program.getName() + " enrollment at end"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Current " + program.getName() + " enrollment at start") { public void apply() { CohortDefinition inProg = getCohortDefinition("In " + program.getName() + " Between Dates"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); + mappings.put("sinceDate", "${startDate}"); mappings.put("untilDate", "${startDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Current " + program.getName() + " enrollment at start"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Current " + program.getName() + " enrollment at end") { public void apply() { CohortDefinition inProg = getCohortDefinition("In " + program.getName() + " Between Dates"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); + mappings.put("sinceDate", "${endDate}"); mappings.put("untilDate", "${endDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Current " + program.getName() + " enrollment at end"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); } return ret; } private static CohortDefinition getCohortDefinition(String name) { CohortDefinitionService service = Context.getService(CohortDefinitionService.class); for (CohortDefinition def : service.getCohortDefinitions(name, true)) { return def; } return null; } public static abstract class InitialDataElement { private Class<?> clazz; private String name; private Boolean alreadyDone = false; public InitialDataElement(Class<?> clazz, String name) { this.clazz = clazz; this.name = name; } public abstract void apply(); public Class<?> getClazz() { return clazz; } public void setClazz(Class<?> clazz) { this.clazz = clazz; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getAlreadyDone() { return alreadyDone; } public void setAlreadyDone(Boolean alreadyDone) { this.alreadyDone = alreadyDone; } public boolean equals(InitialDataElement other) { return clazz.equals(other.clazz) && name.equals(other.name); } } }
false
true
public static List<InitialDataElement> getInitialDataElements() { List<InitialDataElement> ret = new ArrayList<InitialDataElement>(); ret.add(new InitialDataElement(CohortDefinition.class, "Female") { public void apply() { GenderCohortDefinition female = new GenderCohortDefinition("F"); female.setName("Female"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(female); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Male") { public void apply() { GenderCohortDefinition male = new GenderCohortDefinition("M"); male.setName("Male"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(male); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Age Range on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.addParameter(new Parameter("minAge", "minAge", Integer.class)); age.addParameter(new Parameter("maxAge", "maxAge", Integer.class)); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Age Range on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Child on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.setMaxAge(14); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Child on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Adult on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.setMinAge(15); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Adult on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); for (final Program program : Context.getProgramWorkflowService().getAllPrograms()) { ret.add(new InitialDataElement(CohortDefinition.class, "Ever in " + program.getName() + " Before Date") { public void apply() { ProgramStateCohortDefinition def = new ProgramStateCohortDefinition(); def.setProgram(program); def.addParameter(new Parameter("untilDate", "untilDate", Date.class)); def.setName("Ever in " + program.getName() + " Before Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); ret.add(new InitialDataElement(CohortDefinition.class, "In " + program.getName() + " Between Dates") { public void apply() { ProgramStateCohortDefinition def = new ProgramStateCohortDefinition(); def.setProgram(program); def.addParameter(new Parameter("sinceDate", "sinceDate", Date.class)); def.addParameter(new Parameter("untilDate", "untilDate", Date.class)); def.setName("In " + program.getName() + " Between Dates"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); } /* ret.add(new InitialDataElement(CohortDefinition.class, "") { public void apply() { Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); */ ret.add(new InitialDataElement(Dimension.class, "Gender") { public void apply() { CohortDefinition female = getCohortDefinition("Female"); CohortDefinition male = getCohortDefinition("Male"); if (male == null || female == null) { throw new IllegalArgumentException("Cannot create Gender dimension without Male and Female cohort definitions"); } CohortDefinitionDimension gender = new CohortDefinitionDimension(); gender.setName("Gender"); gender.addCohortDefinition("female", female, null); gender.addCohortDefinition("male", male, null); Context.getService(IndicatorService.class).saveDimension(gender); } }); for (final Program program : Context.getProgramWorkflowService().getAllPrograms()) { ret.add(new InitialDataElement(Indicator.class, "Cumulative " + program.getName() + " enrollment at start") { public void apply() { CohortDefinition inProg = getCohortDefinition("Ever in " + program.getName() + " Before Date"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("untilDate", "${startDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Cumulative " + program.getName() + " enrollment at start"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Cumulative " + program.getName() + " enrollment at end") { public void apply() { CohortDefinition inProg = getCohortDefinition("Ever in " + program.getName() + " Before Date"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("untilDate", "${endDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Cumulative " + program.getName() + " enrollment at end"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Current " + program.getName() + " enrollment at start") { public void apply() { CohortDefinition inProg = getCohortDefinition("In " + program.getName() + " Between Dates"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("untilDate", "${startDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Current " + program.getName() + " enrollment at start"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Current " + program.getName() + " enrollment at end") { public void apply() { CohortDefinition inProg = getCohortDefinition("In " + program.getName() + " Between Dates"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("untilDate", "${endDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Current " + program.getName() + " enrollment at end"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); } return ret; }
public static List<InitialDataElement> getInitialDataElements() { List<InitialDataElement> ret = new ArrayList<InitialDataElement>(); ret.add(new InitialDataElement(CohortDefinition.class, "Female") { public void apply() { GenderCohortDefinition female = new GenderCohortDefinition("F"); female.setName("Female"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(female); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Male") { public void apply() { GenderCohortDefinition male = new GenderCohortDefinition("M"); male.setName("Male"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(male); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Age Range on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.addParameter(new Parameter("minAge", "minAge", Integer.class)); age.addParameter(new Parameter("maxAge", "maxAge", Integer.class)); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Age Range on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Child on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.setMaxAge(14); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Child on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); ret.add(new InitialDataElement(CohortDefinition.class, "Adult on Date") { public void apply() { AgeCohortDefinition age = new AgeCohortDefinition(); age.setMinAge(15); age.addParameter(new Parameter("effectiveDate", "effectiveDate", Date.class)); age.setName("Adult on Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(age); } }); for (final Program program : Context.getProgramWorkflowService().getAllPrograms()) { ret.add(new InitialDataElement(CohortDefinition.class, "Ever in " + program.getName() + " Before Date") { public void apply() { ProgramStateCohortDefinition def = new ProgramStateCohortDefinition(); def.setProgram(program); def.addParameter(new Parameter("untilDate", "untilDate", Date.class)); def.setName("Ever in " + program.getName() + " Before Date"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); ret.add(new InitialDataElement(CohortDefinition.class, "In " + program.getName() + " Between Dates") { public void apply() { ProgramStateCohortDefinition def = new ProgramStateCohortDefinition(); def.setProgram(program); def.addParameter(new Parameter("sinceDate", "sinceDate", Date.class)); def.addParameter(new Parameter("untilDate", "untilDate", Date.class)); def.setName("In " + program.getName() + " Between Dates"); Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); } /* ret.add(new InitialDataElement(CohortDefinition.class, "") { public void apply() { Context.getService(CohortDefinitionService.class).saveCohortDefinition(def); } }); */ ret.add(new InitialDataElement(Dimension.class, "Gender") { public void apply() { CohortDefinition female = getCohortDefinition("Female"); CohortDefinition male = getCohortDefinition("Male"); if (male == null || female == null) { throw new IllegalArgumentException("Cannot create Gender dimension without Male and Female cohort definitions"); } CohortDefinitionDimension gender = new CohortDefinitionDimension(); gender.setName("Gender"); gender.addCohortDefinition("female", female, null); gender.addCohortDefinition("male", male, null); Context.getService(IndicatorService.class).saveDimension(gender); } }); for (final Program program : Context.getProgramWorkflowService().getAllPrograms()) { ret.add(new InitialDataElement(Indicator.class, "Cumulative " + program.getName() + " enrollment at start") { public void apply() { CohortDefinition inProg = getCohortDefinition("Ever in " + program.getName() + " Before Date"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("untilDate", "${startDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Cumulative " + program.getName() + " enrollment at start"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Cumulative " + program.getName() + " enrollment at end") { public void apply() { CohortDefinition inProg = getCohortDefinition("Ever in " + program.getName() + " Before Date"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("untilDate", "${endDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Cumulative " + program.getName() + " enrollment at end"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Current " + program.getName() + " enrollment at start") { public void apply() { CohortDefinition inProg = getCohortDefinition("In " + program.getName() + " Between Dates"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("sinceDate", "${startDate}"); mappings.put("untilDate", "${startDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Current " + program.getName() + " enrollment at start"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); ret.add(new InitialDataElement(Indicator.class, "Current " + program.getName() + " enrollment at end") { public void apply() { CohortDefinition inProg = getCohortDefinition("In " + program.getName() + " Between Dates"); if (inProg == null) throw new IllegalArgumentException("Missing cohort def"); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("sinceDate", "${endDate}"); mappings.put("untilDate", "${endDate}"); PeriodCohortIndicator ind = new PeriodCohortIndicator(); ind.setName("Current " + program.getName() + " enrollment at end"); ind.setCohortDefinition(new Mapped<CohortDefinition>(inProg, mappings)); Context.getService(IndicatorService.class).saveIndicator(ind); } }); } return ret; }
diff --git a/eclipseWorkspace/StrayLight/SocketServer/src/main/java/com/sri/straylight/socketserver/Jmodelica.java b/eclipseWorkspace/StrayLight/SocketServer/src/main/java/com/sri/straylight/socketserver/Jmodelica.java index dad17916..de207c36 100644 --- a/eclipseWorkspace/StrayLight/SocketServer/src/main/java/com/sri/straylight/socketserver/Jmodelica.java +++ b/eclipseWorkspace/StrayLight/SocketServer/src/main/java/com/sri/straylight/socketserver/Jmodelica.java @@ -1,467 +1,467 @@ package com.sri.straylight.socketserver; import java.net.URL; import java.util.List; import java.util.Properties; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.python.util.*; import org.python.core.*; import java.lang.ClassLoader; import java.lang.Runtime; import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileReader; import java.net.URL; public class Jmodelica { private static final String fmuFile = "testFMI.fmu"; public String run(String fmuFileName) { String theOs = System.getProperty("os.name"); String cmd; String arg1; //String fmuFileName = "bouncingBall.fmu"; //String fmuFileName = "testFMI.fmu"; String directory; String[] ary = fmuFileName.split("\\."); int idx2 = ary.length - 1; String resultFile = StringUtils.join(ary, ".", 0, idx2); resultFile += "_result.txt"; System.out.println( "Operating system detected: " + theOs); System.out.println( "resultFile: " + resultFile); if (theOs.matches("Windows 7")) { cmd = "C:\\python\\Python2.7\\python.exe"; arg1 = "C:\\ProgramFiles\\JModelica.org-1.6\\run_simulation.py"; directory = "C:\\ProgramFiles\\JModelica.org-1.6\\fmus"; resultFile = directory + "\\" + resultFile; fmuFileName = directory + "\\" + fmuFileName; } else if (theOs.matches("Windows Server 2008")) { cmd = "C:\\Python27\\python.exe"; arg1 = "C:\\ProgramFiles\\JModelica.org-1.6\\run_simulation.py"; directory = "C:\\ProgramFiles\\JModelica.org-1.6\\fmus"; resultFile = directory + "\\" + resultFile; fmuFileName = directory + "\\" + fmuFileName; } else { cmd = "/opt/packages/jmodelica/jmodelica-install/bin/jm_python.sh"; arg1 = "/opt/packages/jmodelica/jmodelica-install/run_simulation.py"; directory = "/opt/packages/jmodelica/jmodelica-install"; resultFile = directory + "/" + resultFile; fmuFileName = directory + "/" + fmuFileName; } ProcessBuilder pb = new ProcessBuilder("python", arg1, fmuFileName); pb.redirectErrorStream(true); File workingDir = new File(directory); pb.directory(workingDir); String result = "no result"; try { Process p = pb.start(); // File dir = pb.directory(); System.out.println("Process started"); StringBuffer sb = new StringBuffer(); try { BufferedReader outputReader = new BufferedReader( new InputStreamReader(p.getInputStream()) ); BufferedReader errorReader = new BufferedReader( new InputStreamReader(p.getErrorStream()) ); String line; while ((line = outputReader.readLine()) != null) { sb.append(line + "\n"); } System.out.println("Waiting for process"); int exitValue = p.waitFor(); BufferedReader reader; this.outputHTML(outputReader); this.outputHTML(errorReader); - result = "\n*********STATS*********\n\n"; + //result = "\n*********STATS*********\n\n"; result += sb.toString(); - result += "\n*********RESULTS*********\n\n"; - result += this.fileContentsToString(resultFile); + //result += "\n*********RESULTS*********\n\n"; + //result += this.fileContentsToString(resultFile); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } System.out.print( result); result = result.replace("\n", "<br />"); return result; } private void outputHTML(BufferedReader reader) { StringBuffer sb = new StringBuffer(); try { String temp = reader.readLine(); while (temp != null) { sb.append(temp + "<br>\n"); System.out.println(temp); temp = reader.readLine(); } reader.close(); } catch (IOException e) { e.printStackTrace(); } String result = sb.toString(); } private String loadStream(InputStream s) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(s)); StringBuilder sb = new StringBuilder(); String line; while((line=br.readLine()) != null) sb.append(line).append("\n"); return sb.toString(); } private void displayResults(String resultFile) { // TODO Auto-generated method stub String resultsStr = this.fileContentsToString(resultFile); System.out.print(resultsStr); } /** * Read the contents of a file and place them in * a string object. * * @param file path to file. * @return String contents of the file. */ public static String fileContentsToString(String file) { String contents = ""; File f = null; try { f = new File(file); if (f.exists()) { FileReader fr = null; try { fr = new FileReader(f); char[] template = new char[(int) f.length()]; fr.read(template); contents = new String(template); } catch (Exception e) { e.printStackTrace(); } finally { if (fr != null) { fr.close(); } } } } catch (Exception e) { e.printStackTrace(); } return contents; } public void test3() { //Runtime.getRuntime().exec(String command, String[] enviroment, File workingdir) String s; byte buff[] = new byte[1024]; try { String[] command = new String[] {"cmd.exe", "/c", "C:\\ProgramFiles\\JModelica.org-1.6\\ipconfig1.bat"}; Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(command); try { pr.waitFor(); System.out.println(pr.exitValue()); OutputStream os = pr.getOutputStream(); InputStream is = pr.getInputStream(); System.out.println(os.toString()); //os. // String line; // while ((line = is.) != null) // System.out.println(line); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } //try { //Runtime rt = Runtime.getRuntime(); //rt.exec("cd c:\\ProgramFiles\\JModelica.org-1.6"); //rt.exec("cmd /c c:\\ProgramFiles\\JModelica.org-1.6\\test_fmu.bat"); //try { //Runtime.getRuntime().exec("c:\\ProgramFiles\\JModelica.org-1.6\\test_fmu.bat",null,"c:\\ProgramFiles\\JModelica.org-1.6"); //ProcessBuilder pb = new ProcessBuilder("cmd /c test_fmu.bat"); //pb.directory(new File("c:\\ProgramFiles\\JModelica.org-1.6")); //Process p = pb.start(); //int exitStatus = rt.wait(); //} //catch (InterruptedException e) { // e.printStackTrace(); //} //} catch (IOException e) { // Error was detected, close the ChatWebSocket client side //e.printStackTrace(); //} } //public void testJep() { // try { // ClassLoader cl = this.getClass().getClassLoader(); //Jep objJep = new Jep(true, "C:", cl); /* objJep.eval("print 'test 1'"); objJep.eval("print 'test 2'"); objJep.eval("import sys"); objJep.eval("print sys.version_info"); */ //objJep.runScript("C:\\ProgramFiles\\JModelica.org-1.6\\test1.py"); //objJep.runScript("C:\\test1.py"); //objJep.runScript("C:\\test1.py", cl); //objJep.eval("import sys"); //objJep.eval("import os"); //objJep.eval("for p in sys.path:"); //objJep.eval(" print os.listdir( p )"); //objJep.eval("os.putenv('JMODELICA_HOME', 'C:\\ProgramFiles\\JModelica.org-1.6')"); //objJep.eval("os.putenv('IPOPT_HOME', 'C:\\ProgramFiles\\JModelica.org-1.6\\Ipopt-MUMPS')"); //objJep.eval("os.putenv('SUNDIALS_HOME', 'C:\\ProgramFiles\\JModelica.org-1.6\\SUNDIALS')"); //objJep.eval("os.putenv('CPPAD_HOME', 'C:\\ProgramFiles\\JModelica.org-1.6\\CppAD')"); //objJep.eval("os.putenv('MINGW_HOME', 'C:\\ProgramFiles\\JModelica.org-1.6\\mingw')"); // //objJep.eval("help('modules')"); // } catch (JepException ex) { // ex.printStackTrace(); //} //} public void test() { String path = "c:\test"; this.listEngines(); PythonInterpreter interp; ScriptEngineManager mgr = new ScriptEngineManager(); List<ScriptEngineFactory> factoryList = mgr.getEngineFactories(); Properties newProps = new Properties(); String pythonPath = "C:\\ProgramFiles\\jmodelicatest\\Python;C:\\ProgramFiles\\jmodelicatest\\CasADi"; newProps.setProperty("python.path", pythonPath); String pythonHome = "C:\\python\\Python2.7"; newProps.setProperty("python.home", pythonPath); newProps.setProperty("jmodelica.home", "C:\\ProgramFiles\\jmodelicatest"); //JMODELICA_HOME Properties properties = System.getProperties(); PythonInterpreter.initialize(properties, newProps, new String[] {""}); ScriptEngine pyEngine = mgr.getEngineByName("python"); try { pyEngine.eval("print \"Python - Hello, world!\""); } catch (Exception ex) { ex.printStackTrace(); } //return; URL fileUrl = this.getClass().getClassLoader().getResource(fmuFile); String code = "myModel = FMUModel('" + fileUrl.getPath() + "')"; try { pyEngine.eval("import os"); pyEngine.eval("os.putenv('JMODELICA_HOME', 'C:\\ProgramFiles\\jmodelicatest')"); pyEngine.eval("os.putenv('IPOPT_HOME', 'C:\\ProgramFiles\\jmodelicatest\\Ipopt-MUMPS')"); pyEngine.eval("os.putenv('SUNDIALS_HOME', 'C:\\ProgramFiles\\jmodelicatest\\SUNDIALS')"); pyEngine.eval("os.putenv('CPPAD_HOME', 'C:\\ProgramFiles\\jmodelicatest\\CppAD')"); pyEngine.eval("os.putenv('MINGW_HOME', 'C:\\ProgramFiles\\jmodelicatest\\mingw')"); //pyEngine.eval("import jpype"); pyEngine.eval("from jmodelica.fmi import FMUModel"); // pyEngine.eval(code); //pyEngine.eval("myModel.simulate()"); } catch (Exception ex) { ex.printStackTrace(); } /**/ } private static void listEngines(){ ScriptEngineManager mgr = new ScriptEngineManager(); List<ScriptEngineFactory> factories = mgr.getEngineFactories(); for (ScriptEngineFactory factory: factories) { System.out.println("ScriptEngineFactory Info"); String engName = factory.getEngineName(); String engVersion = factory.getEngineVersion(); String langName = factory.getLanguageName(); String langVersion = factory.getLanguageVersion(); System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion); List<String> engNames = factory.getNames(); for(String name: engNames) { System.out.printf("\tEngine Alias: %s\n", name); } System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion); } } }
false
true
public String run(String fmuFileName) { String theOs = System.getProperty("os.name"); String cmd; String arg1; //String fmuFileName = "bouncingBall.fmu"; //String fmuFileName = "testFMI.fmu"; String directory; String[] ary = fmuFileName.split("\\."); int idx2 = ary.length - 1; String resultFile = StringUtils.join(ary, ".", 0, idx2); resultFile += "_result.txt"; System.out.println( "Operating system detected: " + theOs); System.out.println( "resultFile: " + resultFile); if (theOs.matches("Windows 7")) { cmd = "C:\\python\\Python2.7\\python.exe"; arg1 = "C:\\ProgramFiles\\JModelica.org-1.6\\run_simulation.py"; directory = "C:\\ProgramFiles\\JModelica.org-1.6\\fmus"; resultFile = directory + "\\" + resultFile; fmuFileName = directory + "\\" + fmuFileName; } else if (theOs.matches("Windows Server 2008")) { cmd = "C:\\Python27\\python.exe"; arg1 = "C:\\ProgramFiles\\JModelica.org-1.6\\run_simulation.py"; directory = "C:\\ProgramFiles\\JModelica.org-1.6\\fmus"; resultFile = directory + "\\" + resultFile; fmuFileName = directory + "\\" + fmuFileName; } else { cmd = "/opt/packages/jmodelica/jmodelica-install/bin/jm_python.sh"; arg1 = "/opt/packages/jmodelica/jmodelica-install/run_simulation.py"; directory = "/opt/packages/jmodelica/jmodelica-install"; resultFile = directory + "/" + resultFile; fmuFileName = directory + "/" + fmuFileName; } ProcessBuilder pb = new ProcessBuilder("python", arg1, fmuFileName); pb.redirectErrorStream(true); File workingDir = new File(directory); pb.directory(workingDir); String result = "no result"; try { Process p = pb.start(); // File dir = pb.directory(); System.out.println("Process started"); StringBuffer sb = new StringBuffer(); try { BufferedReader outputReader = new BufferedReader( new InputStreamReader(p.getInputStream()) ); BufferedReader errorReader = new BufferedReader( new InputStreamReader(p.getErrorStream()) ); String line; while ((line = outputReader.readLine()) != null) { sb.append(line + "\n"); } System.out.println("Waiting for process"); int exitValue = p.waitFor(); BufferedReader reader; this.outputHTML(outputReader); this.outputHTML(errorReader); result = "\n*********STATS*********\n\n"; result += sb.toString(); result += "\n*********RESULTS*********\n\n"; result += this.fileContentsToString(resultFile); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } System.out.print( result); result = result.replace("\n", "<br />"); return result; }
public String run(String fmuFileName) { String theOs = System.getProperty("os.name"); String cmd; String arg1; //String fmuFileName = "bouncingBall.fmu"; //String fmuFileName = "testFMI.fmu"; String directory; String[] ary = fmuFileName.split("\\."); int idx2 = ary.length - 1; String resultFile = StringUtils.join(ary, ".", 0, idx2); resultFile += "_result.txt"; System.out.println( "Operating system detected: " + theOs); System.out.println( "resultFile: " + resultFile); if (theOs.matches("Windows 7")) { cmd = "C:\\python\\Python2.7\\python.exe"; arg1 = "C:\\ProgramFiles\\JModelica.org-1.6\\run_simulation.py"; directory = "C:\\ProgramFiles\\JModelica.org-1.6\\fmus"; resultFile = directory + "\\" + resultFile; fmuFileName = directory + "\\" + fmuFileName; } else if (theOs.matches("Windows Server 2008")) { cmd = "C:\\Python27\\python.exe"; arg1 = "C:\\ProgramFiles\\JModelica.org-1.6\\run_simulation.py"; directory = "C:\\ProgramFiles\\JModelica.org-1.6\\fmus"; resultFile = directory + "\\" + resultFile; fmuFileName = directory + "\\" + fmuFileName; } else { cmd = "/opt/packages/jmodelica/jmodelica-install/bin/jm_python.sh"; arg1 = "/opt/packages/jmodelica/jmodelica-install/run_simulation.py"; directory = "/opt/packages/jmodelica/jmodelica-install"; resultFile = directory + "/" + resultFile; fmuFileName = directory + "/" + fmuFileName; } ProcessBuilder pb = new ProcessBuilder("python", arg1, fmuFileName); pb.redirectErrorStream(true); File workingDir = new File(directory); pb.directory(workingDir); String result = "no result"; try { Process p = pb.start(); // File dir = pb.directory(); System.out.println("Process started"); StringBuffer sb = new StringBuffer(); try { BufferedReader outputReader = new BufferedReader( new InputStreamReader(p.getInputStream()) ); BufferedReader errorReader = new BufferedReader( new InputStreamReader(p.getErrorStream()) ); String line; while ((line = outputReader.readLine()) != null) { sb.append(line + "\n"); } System.out.println("Waiting for process"); int exitValue = p.waitFor(); BufferedReader reader; this.outputHTML(outputReader); this.outputHTML(errorReader); //result = "\n*********STATS*********\n\n"; result += sb.toString(); //result += "\n*********RESULTS*********\n\n"; //result += this.fileContentsToString(resultFile); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } System.out.print( result); result = result.replace("\n", "<br />"); return result; }
diff --git a/src/org/omegat/util/TMXReader2.java b/src/org/omegat/util/TMXReader2.java index 3d84555d..b179e7c9 100644 --- a/src/org/omegat/util/TMXReader2.java +++ b/src/org/omegat/util/TMXReader2.java @@ -1,589 +1,593 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2010 Alex Buloichik Home page: http://www.omegat.org/ Support center: http://groups.yahoo.com/group/OmegaT/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA **************************************************************************/ package org.omegat.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLReporter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Helper for read TMX files, using StAX. * * @author Alex Buloichik ([email protected]) */ public class TMXReader2 { private final XMLInputFactory factory; private final SimpleDateFormat dateFormat1, dateFormat2, dateFormatOut; /** Segment Type attribute value: "paragraph" */ public static final String SEG_PARAGRAPH = "paragraph"; /** Segment Type attribute value: "sentence" */ public static final String SEG_SENTENCE = "sentence"; /** Creation Tool attribute value of OmegaT TMXs: "OmegaT" */ public static final String CT_OMEGAT = "OmegaT"; private XMLEventReader xml; private boolean isParagraphSegtype = true; private boolean isOmegaT = false; private boolean extTmxLevel2; private boolean useSlash; private boolean isSegmentingEnabled; private int errorsCount, warningsCount; ParsedTu currentTu = new ParsedTu(); // buffers for parse texts StringBuilder propContent = new StringBuilder(); StringBuilder noteContent = new StringBuilder(); StringBuilder segContent = new StringBuilder(); StringBuilder segInlineTag = new StringBuilder(); // map of 'i' attributes to tag numbers Map<String, Integer> pairTags = new TreeMap<String, Integer>(); public TMXReader2() { factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); factory.setXMLReporter(new XMLReporter() { public void report(String message, String error_type, Object info, Location location) throws XMLStreamException { Log.logWarningRB( "TMXR_WARNING_WHILE_PARSING", new Object[] { String.valueOf(location.getLineNumber()), String.valueOf(location.getColumnNumber()) }); Log.log(message + ": " + info); warningsCount++; } }); dateFormat1 = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ENGLISH); dateFormat1.setTimeZone(TimeZone.getTimeZone("UTC")); dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH); dateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); dateFormatOut = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ENGLISH); dateFormatOut.setTimeZone(TimeZone.getTimeZone("UTC")); } /** * Read TMX file. */ public void readTMX(File file, final Language sourceLanguage, final Language targetLanguage, boolean isSegmentingEnabled, final boolean forceOmegaTMX, final boolean extTmxLevel2, final boolean useSlash, final LoadCallback callback) throws Exception { this.extTmxLevel2 = extTmxLevel2; this.useSlash = useSlash; this.isSegmentingEnabled = isSegmentingEnabled; // log the parsing attempt Log.logRB("TMXR_INFO_READING_FILE", new Object[] { file.getAbsolutePath() }); boolean allFound = true; InputStream in = new BufferedInputStream(new FileInputStream(file)); xml = factory.createXMLEventReader(in); try { while (xml.hasNext()) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement eStart = (StartElement) e; if ("tu".equals(eStart.getName().getLocalPart())) { parseTu(eStart); ParsedTuv origTuv = getTuvByLang(sourceLanguage); ParsedTuv targetTuv = getTuvByLang(targetLanguage); allFound &= callback.onEntry(currentTu, origTuv, targetTuv, isParagraphSegtype); } else if ("header".equals(eStart.getName().getLocalPart())) { parseHeader(eStart, sourceLanguage); } break; } } } finally { xml.close(); in.close(); } if (!allFound) { Log.logWarningRB("TMXR_WARNING_SOURCE_NOT_FOUND"); warningsCount++; } Log.logRB("TMXR_INFO_READING_COMPLETE"); Log.log(""); } protected void parseHeader(StartElement element, final Language sourceLanguage) { isParagraphSegtype = SEG_PARAGRAPH.equals(getAttributeValue(element, "segtype")); isOmegaT = CT_OMEGAT.equals(getAttributeValue(element, "creationtool")); // log some details Log.logRB("TMXR_INFO_CREATION_TOOL", new Object[] { getAttributeValue(element, "creationtool") }); Log.logRB("TMXR_INFO_CREATION_TOOL_VERSION", new Object[] { getAttributeValue(element, "creationtoolversion") }); Log.logRB("TMXR_INFO_SEG_TYPE", new Object[] { getAttributeValue(element, "segtype") }); Log.logRB("TMXR_INFO_SOURCE_LANG", new Object[] { getAttributeValue(element, "srclang") }); // give a warning if the TMX source language is // different from the project source language String tmxSourceLanguage = getAttributeValue(element, "srclang"); if (!tmxSourceLanguage.equalsIgnoreCase(sourceLanguage.getLanguage())) { Log.logWarningRB("TMXR_WARNING_INCORRECT_SOURCE_LANG", new Object[] { tmxSourceLanguage, sourceLanguage }); } // give a warning that TMX file will be upgraded to sentence segmentation if (isSegmentingEnabled && isParagraphSegtype) { Log.logWarningRB("TMXR_WARNING_UPGRADE_SENTSEG"); } } protected void parseTu(StartElement element) throws Exception { currentTu.changeid = getAttributeValue(element, "changeid"); currentTu.changedate = parseISO8601date(getAttributeValue(element, "changedate")); currentTu.creationid = getAttributeValue(element, "creationid"); currentTu.creationdate = parseISO8601date(getAttributeValue(element, "creationdate")); currentTu.clear(); while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement eStart = (StartElement) e; if ("tuv".equals(eStart.getName().getLocalPart())) { parseTuv(eStart); } else if ("prop".equals(eStart.getName().getLocalPart())) { parseProp(eStart); } else if ("note".equals(eStart.getName().getLocalPart())) { parseNote(eStart); } break; case XMLEvent.END_ELEMENT: EndElement eEnd = (EndElement) e; if ("tu".equals(eEnd.getName().getLocalPart())) { return; } break; } } } protected void parseTuv(StartElement element) throws Exception { ParsedTuv tuv = new ParsedTuv(); currentTu.tuvs.add(tuv); tuv.changeid = getAttributeValue(element, "changeid"); tuv.changedate = parseISO8601date(getAttributeValue(element, "changedate")); tuv.creationid = getAttributeValue(element, "creationid"); tuv.creationdate = parseISO8601date(getAttributeValue(element, "creationdate")); // find 'lang' or 'xml:lang' attribute for (Iterator<Attribute> it = element.getAttributes(); it.hasNext();) { Attribute a = it.next(); if ("lang".equals(a.getName().getLocalPart())) { tuv.lang = a.getValue(); break; } } while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement eStart = (StartElement) e; if ("seg".equals(eStart.getName().getLocalPart())) { if (isOmegaT) { parseSegOmegaT(); } else if (extTmxLevel2) { parseSegExtLevel2(); } else { parseSegExtLevel1(); } tuv.text = segContent.toString(); } break; case XMLEvent.END_ELEMENT: EndElement eEnd = (EndElement) e; if ("tuv".equals(eEnd.getName().getLocalPart())) { return; } break; } } } protected void parseNote(StartElement element) throws Exception { noteContent.setLength(0); while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.END_ELEMENT: EndElement eEnd = (EndElement) e; if ("note".equals(eEnd.getName().getLocalPart())) { currentTu.note=noteContent.toString(); return; } break; case XMLEvent.CHARACTERS: Characters c = (Characters) e; noteContent.append(c.getData()); break; } } } protected void parseProp(StartElement element) throws Exception { String propType = getAttributeValue(element, "type"); propContent.setLength(0); while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.END_ELEMENT: EndElement eEnd = (EndElement) e; if ("prop".equals(eEnd.getName().getLocalPart())) { currentTu.props.put(propType, propContent.toString()); return; } break; case XMLEvent.CHARACTERS: Characters c = (Characters) e; propContent.append(c.getData()); break; } } } /** * OmegaT TMX - just read full text. */ protected void parseSegOmegaT() throws Exception { segContent.setLength(0); while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.END_ELEMENT: EndElement eEnd = (EndElement) e; if ("seg".equals(eEnd.getName().getLocalPart())) { return; } break; case XMLEvent.CHARACTERS: Characters c = (Characters) e; segContent.append(c.getData()); break; } } } /** * External TMX - level 1. Skip text inside inline tags. */ protected void parseSegExtLevel1() throws Exception { segContent.setLength(0); int inlineLevel = 0; while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: inlineLevel++; break; case XMLEvent.END_ELEMENT: inlineLevel--; EndElement eEnd = (EndElement) e; if ("seg".equals(eEnd.getName().getLocalPart())) { return; } break; case XMLEvent.CHARACTERS: if (inlineLevel == 0) { Characters c = (Characters) e; segContent.append(c.getData()); } break; } } } /** * External TMX - level 2. Replace all tags into shortcuts. */ protected void parseSegExtLevel2() throws Exception { segContent.setLength(0); segInlineTag.setLength(0); pairTags.clear(); int tagNumber = 0; int inlineLevel = 0; String currentI = null; String currentPos = null; while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: inlineLevel++; StartElement eStart = (StartElement) e; segInlineTag.setLength(0); if ("bpt".equals(eStart.getName().getLocalPart())) { currentI = getAttributeValue(eStart, "i"); pairTags.put(currentI, tagNumber); tagNumber++; } else if ("ept".equals(eStart.getName().getLocalPart())) { currentI = getAttributeValue(eStart, "i"); } else if ("it".equals(eStart.getName().getLocalPart())) { currentPos = getAttributeValue(eStart, "pos"); } else { currentI = null; } break; case XMLEvent.END_ELEMENT: inlineLevel--; EndElement eEnd = (EndElement) e; if ("seg".equals(eEnd.getName().getLocalPart())) { return; } boolean slashBefore = false; boolean slashAfter = false; char tagName = getFirstLetter(segInlineTag); Integer tagN; if ("bpt".equals(eEnd.getName().getLocalPart())) { tagN = pairTags.get(currentI); } else if ("ept".equals(eEnd.getName().getLocalPart())) { slashBefore = true; tagN = pairTags.get(currentI); } else if ("it".equals(eEnd.getName().getLocalPart())) { tagN = tagNumber; if ("end".equals(currentPos)) { slashBefore = true; + } else { + if (useSlash) { + slashAfter = true; + } } } else { tagN = tagNumber; if (useSlash) { slashAfter = true; } } if (tagN == null) { // check error of TMX reading Log.logErrorRB("TMX_ERROR_READING_LEVEL2", e.getLocation().getLineNumber(), e .getLocation().getColumnNumber()); errorsCount++; segContent.setLength(0); // wait for end seg while (true) { XMLEvent ev = xml.nextEvent(); switch (ev.getEventType()) { case XMLEvent.END_ELEMENT: EndElement evEnd = (EndElement) ev; if ("seg".equals(evEnd.getName().getLocalPart())) { return; } } } } segContent.append('<'); if (slashBefore) { segContent.append('/'); } segContent.append(tagName); segContent.append(Integer.toString(tagN)); if (slashAfter) { segContent.append('/'); } segContent.append('>'); break; case XMLEvent.CHARACTERS: Characters c = (Characters) e; if (inlineLevel == 0) { segContent.append(c.getData()); } else { segInlineTag.append(c.getData()); } break; } } } protected static char getFirstLetter(StringBuilder s) { char f = 0; for (int i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) { f = Character.toLowerCase(s.charAt(i)); break; } } return f != 0 ? f : 'f'; } /** * Get ParsedTuv from list of Tuv for specific language. * * Language choosed by:<br> * - with the same language+country<br> * - if not exist, then with the same language but without country<br> * - if not exist, then with the same language with whatever country<br> */ protected ParsedTuv getTuvByLang(Language lang) { String langLanguage = lang.getLanguageCode(); String langCountry = lang.getCountryCode(); ParsedTuv tuvLC = null; // Tuv with the same language+country ParsedTuv tuvL = null; // Tuv with the same language only, without country ParsedTuv tuvLW = null; // Tuv with the same language+whatever country for (int i = 0; i < currentTu.tuvs.size(); i++) { ParsedTuv tuv = currentTu.tuvs.get(i); String tuvLang = tuv.lang; if (!langLanguage.regionMatches(true, 0, tuvLang, 0, 2)) { // language not equals - there is no sense to processing continue; } if (tuvLang.length() < 3) { // language only, without country tuvL = tuv; } else if (langCountry.regionMatches(true, 0, tuvLang, 3, 2)) { // the same country tuvLC = tuv; } else { // other country tuvLW = tuv; } } ParsedTuv bestTuv; if (tuvLC != null) { bestTuv = tuvLC; } else if (tuvL != null) { bestTuv = tuvL; } else { bestTuv = tuvLW; } return bestTuv; } public long parseISO8601date(String str) { if (str == null) { return 0; } try { return dateFormat1.parse(str).getTime(); } catch (ParseException ex) { } try { return dateFormat2.parse(str).getTime(); } catch (ParseException ex) { } return 0; } private static String getAttributeValue(StartElement e, String attrName) { Attribute a = e.getAttributeByName(new QName(attrName)); return a != null ? a.getValue() : null; } /** * Callback for receive data from TMX. */ public interface LoadCallback { /** * @return true if TU contains required source and target info */ boolean onEntry(ParsedTu tu, ParsedTuv tuvSource, ParsedTuv tuvTarget, boolean isParagraphSegtype); } public static class ParsedTu { public String changeid; public long changedate; public String creationid; public long creationdate; public String note; public Map<String, String> props = new TreeMap<String, String>(); public List<ParsedTuv> tuvs = new ArrayList<ParsedTuv>(); void clear() { changeid = null; changedate = 0; creationid = null; creationdate = 0; props.clear(); tuvs.clear(); note = null; } } public static class ParsedTuv { public String lang; public String changeid; public long changedate; public String creationid; public long creationdate; public String text; } public static final EntityResolver TMX_DTD_RESOLVER = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.endsWith("tmx11.dtd")) { return new InputSource(TMXReader2.class.getResourceAsStream("/schemas/tmx11.dtd")); } else if (systemId.endsWith("tmx14.dtd")) { return new InputSource(TMXReader2.class.getResourceAsStream("/schemas/tmx14.dtd")); } else { return null; } } }; }
true
true
protected void parseSegExtLevel2() throws Exception { segContent.setLength(0); segInlineTag.setLength(0); pairTags.clear(); int tagNumber = 0; int inlineLevel = 0; String currentI = null; String currentPos = null; while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: inlineLevel++; StartElement eStart = (StartElement) e; segInlineTag.setLength(0); if ("bpt".equals(eStart.getName().getLocalPart())) { currentI = getAttributeValue(eStart, "i"); pairTags.put(currentI, tagNumber); tagNumber++; } else if ("ept".equals(eStart.getName().getLocalPart())) { currentI = getAttributeValue(eStart, "i"); } else if ("it".equals(eStart.getName().getLocalPart())) { currentPos = getAttributeValue(eStart, "pos"); } else { currentI = null; } break; case XMLEvent.END_ELEMENT: inlineLevel--; EndElement eEnd = (EndElement) e; if ("seg".equals(eEnd.getName().getLocalPart())) { return; } boolean slashBefore = false; boolean slashAfter = false; char tagName = getFirstLetter(segInlineTag); Integer tagN; if ("bpt".equals(eEnd.getName().getLocalPart())) { tagN = pairTags.get(currentI); } else if ("ept".equals(eEnd.getName().getLocalPart())) { slashBefore = true; tagN = pairTags.get(currentI); } else if ("it".equals(eEnd.getName().getLocalPart())) { tagN = tagNumber; if ("end".equals(currentPos)) { slashBefore = true; } } else { tagN = tagNumber; if (useSlash) { slashAfter = true; } } if (tagN == null) { // check error of TMX reading Log.logErrorRB("TMX_ERROR_READING_LEVEL2", e.getLocation().getLineNumber(), e .getLocation().getColumnNumber()); errorsCount++; segContent.setLength(0); // wait for end seg while (true) { XMLEvent ev = xml.nextEvent(); switch (ev.getEventType()) { case XMLEvent.END_ELEMENT: EndElement evEnd = (EndElement) ev; if ("seg".equals(evEnd.getName().getLocalPart())) { return; } } } } segContent.append('<'); if (slashBefore) { segContent.append('/'); } segContent.append(tagName); segContent.append(Integer.toString(tagN)); if (slashAfter) { segContent.append('/'); } segContent.append('>'); break; case XMLEvent.CHARACTERS: Characters c = (Characters) e; if (inlineLevel == 0) { segContent.append(c.getData()); } else { segInlineTag.append(c.getData()); } break; } } }
protected void parseSegExtLevel2() throws Exception { segContent.setLength(0); segInlineTag.setLength(0); pairTags.clear(); int tagNumber = 0; int inlineLevel = 0; String currentI = null; String currentPos = null; while (true) { XMLEvent e = xml.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: inlineLevel++; StartElement eStart = (StartElement) e; segInlineTag.setLength(0); if ("bpt".equals(eStart.getName().getLocalPart())) { currentI = getAttributeValue(eStart, "i"); pairTags.put(currentI, tagNumber); tagNumber++; } else if ("ept".equals(eStart.getName().getLocalPart())) { currentI = getAttributeValue(eStart, "i"); } else if ("it".equals(eStart.getName().getLocalPart())) { currentPos = getAttributeValue(eStart, "pos"); } else { currentI = null; } break; case XMLEvent.END_ELEMENT: inlineLevel--; EndElement eEnd = (EndElement) e; if ("seg".equals(eEnd.getName().getLocalPart())) { return; } boolean slashBefore = false; boolean slashAfter = false; char tagName = getFirstLetter(segInlineTag); Integer tagN; if ("bpt".equals(eEnd.getName().getLocalPart())) { tagN = pairTags.get(currentI); } else if ("ept".equals(eEnd.getName().getLocalPart())) { slashBefore = true; tagN = pairTags.get(currentI); } else if ("it".equals(eEnd.getName().getLocalPart())) { tagN = tagNumber; if ("end".equals(currentPos)) { slashBefore = true; } else { if (useSlash) { slashAfter = true; } } } else { tagN = tagNumber; if (useSlash) { slashAfter = true; } } if (tagN == null) { // check error of TMX reading Log.logErrorRB("TMX_ERROR_READING_LEVEL2", e.getLocation().getLineNumber(), e .getLocation().getColumnNumber()); errorsCount++; segContent.setLength(0); // wait for end seg while (true) { XMLEvent ev = xml.nextEvent(); switch (ev.getEventType()) { case XMLEvent.END_ELEMENT: EndElement evEnd = (EndElement) ev; if ("seg".equals(evEnd.getName().getLocalPart())) { return; } } } } segContent.append('<'); if (slashBefore) { segContent.append('/'); } segContent.append(tagName); segContent.append(Integer.toString(tagN)); if (slashAfter) { segContent.append('/'); } segContent.append('>'); break; case XMLEvent.CHARACTERS: Characters c = (Characters) e; if (inlineLevel == 0) { segContent.append(c.getData()); } else { segInlineTag.append(c.getData()); } break; } } }
diff --git a/src/org/rascalmpl/interpreter/matching/IteratorFactory.java b/src/org/rascalmpl/interpreter/matching/IteratorFactory.java index e58e767a50..43f9c03f99 100644 --- a/src/org/rascalmpl/interpreter/matching/IteratorFactory.java +++ b/src/org/rascalmpl/interpreter/matching/IteratorFactory.java @@ -1,171 +1,172 @@ /******************************************************************************* * Copyright (c) 2009-2011 CWI * 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: * * Jurgen J. Vinju - [email protected] - CWI * * Emilie Balland - (CWI) * * Paul Klint - [email protected] - CWI * * Mark Hills - [email protected] (CWI) * * Arnold Lankamp - [email protected] *******************************************************************************/ package org.rascalmpl.interpreter.matching; import java.util.Iterator; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IMap; import org.eclipse.imp.pdb.facts.INode; import org.eclipse.imp.pdb.facts.ISet; import org.eclipse.imp.pdb.facts.ITuple; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.rascalmpl.interpreter.IEvaluatorContext; import org.rascalmpl.interpreter.result.Result; import org.rascalmpl.interpreter.staticErrors.NotEnumerableError; import org.rascalmpl.interpreter.staticErrors.UnexpectedTypeError; import org.rascalmpl.interpreter.staticErrors.UnsupportedOperationError; import org.rascalmpl.interpreter.types.NonTerminalType; import org.rascalmpl.interpreter.types.RascalTypeFactory; import org.rascalmpl.interpreter.types.TypeReachability; import org.rascalmpl.values.uptr.SymbolAdapter; public class IteratorFactory { public static Type elementType(IEvaluatorContext ctx, Result<IValue> subject) { Type subjectType = subject.getType(); if (subjectType.isListType() || subjectType.isSetType()) { return subjectType.getElementType(); } else if (subjectType.isMapType()){ return subjectType.getKeyType(); } else if (subjectType.isExternalType()){ if (subjectType instanceof NonTerminalType){ NonTerminalType nt = (NonTerminalType) subjectType; if (nt.isConcreteListType()){ IConstructor listSymbol = nt.getSymbol(); return RascalTypeFactory.getInstance().nonTerminalType(SymbolAdapter.getSymbol(listSymbol)); } } throw new NotEnumerableError(subjectType.toString(), ctx.getCurrentAST()); } else if (subjectType.isNodeType() || subjectType.isAbstractDataType() || subjectType.isTupleType()) { return TypeFactory.getInstance().valueType(); } throw new NotEnumerableError(subjectType.toString(), ctx.getCurrentAST()); } public static Iterator<IValue> make(IEvaluatorContext ctx, IMatchingResult matchPattern, Result<IValue> subject, boolean shallow){ Type subjectType = subject.getType(); IValue subjectValue = subject.getValue(); Type patType = matchPattern.getType(ctx.getCurrentEnvt(), null); if (subjectType.isValueType()) { System.err.println("???"); } // TODO: this should be a visitor design as well.. // List if(subjectType.isListType()){ //TODO: we could do this more precisely if(shallow){ checkMayOccur(patType, subjectType.getElementType(), ctx); return ((IList) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); // Set } else if(subjectType.isSetType()){ if (shallow){ checkMayOccur(patType, subjectType.getElementType(), ctx); return ((ISet) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); // Map } else if(subjectType.isMapType()){ if (shallow) { checkMayOccur(patType, subjectType.getKeyType(), ctx); return ((IMap) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); } else if (subjectType.isExternalType()) { if (subjectType instanceof NonTerminalType) { // NonTerminal (both pattern and subject are non-terminals, so we can skip layout and stuff) IConstructor tree = (IConstructor) subjectValue; NonTerminalType nt = (NonTerminalType) subjectType; if (!shallow) { return new DescendantReader(tree, patType instanceof NonTerminalType); } else { if (nt.isConcreteListType()){ checkMayOccur(patType, subjectType, ctx); IConstructor ls = nt.getSymbol(); int delta = SymbolAdapter.isSepList(ls) ? (SymbolAdapter.getSeparators(ls).length() + 1) : 1; return new CFListIterator((IList)tree.get(1), delta); } } } throw new NotEnumerableError(subjectType.toString(), ctx.getCurrentAST()); // Node and ADT } else if(subjectType.isNodeType() || subjectType.isAbstractDataType()){ if (shallow){ checkMayOccur(patType, subjectType, ctx); return new NodeChildIterator((INode) subjectValue); } return new DescendantReader(subjectValue, false); } else if(subjectType.isTupleType()){ if(shallow){ int nElems = subjectType.getArity(); for(int i = 0; i < nElems; i++){ if(!subjectType.getFieldType(i).isSubtypeOf(patType)) { throw new UnexpectedTypeError(patType, subjectType.getFieldType(i), ctx.getCurrentAST()); } } return new TupleElementIterator((ITuple)subjectValue); } return new DescendantReader(subjectValue, false); } else if(subjectType.isBoolType() || subjectType.isIntegerType() || subjectType.isRealType() || subjectType.isStringType() || subjectType.isSourceLocationType() || + subjectType.isRationalType() || subjectType.isDateTimeType()) { if (shallow) { throw new NotEnumerableError(subjectType.toString(), ctx.getCurrentAST()); } return new SingleIValueIterator(subjectValue); } else { throw new UnsupportedOperationError("makeIterator", subjectType, ctx.getCurrentAST()); } } private static void checkMayOccur(Type patType, Type rType, IEvaluatorContext ctx){ if(!TypeReachability.mayOccurIn(rType, patType, ctx.getCurrentEnvt())) { throw new UnexpectedTypeError(rType, patType, ctx.getCurrentAST()); } } }
true
true
public static Iterator<IValue> make(IEvaluatorContext ctx, IMatchingResult matchPattern, Result<IValue> subject, boolean shallow){ Type subjectType = subject.getType(); IValue subjectValue = subject.getValue(); Type patType = matchPattern.getType(ctx.getCurrentEnvt(), null); if (subjectType.isValueType()) { System.err.println("???"); } // TODO: this should be a visitor design as well.. // List if(subjectType.isListType()){ //TODO: we could do this more precisely if(shallow){ checkMayOccur(patType, subjectType.getElementType(), ctx); return ((IList) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); // Set } else if(subjectType.isSetType()){ if (shallow){ checkMayOccur(patType, subjectType.getElementType(), ctx); return ((ISet) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); // Map } else if(subjectType.isMapType()){ if (shallow) { checkMayOccur(patType, subjectType.getKeyType(), ctx); return ((IMap) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); } else if (subjectType.isExternalType()) { if (subjectType instanceof NonTerminalType) { // NonTerminal (both pattern and subject are non-terminals, so we can skip layout and stuff) IConstructor tree = (IConstructor) subjectValue; NonTerminalType nt = (NonTerminalType) subjectType; if (!shallow) { return new DescendantReader(tree, patType instanceof NonTerminalType); } else { if (nt.isConcreteListType()){ checkMayOccur(patType, subjectType, ctx); IConstructor ls = nt.getSymbol(); int delta = SymbolAdapter.isSepList(ls) ? (SymbolAdapter.getSeparators(ls).length() + 1) : 1; return new CFListIterator((IList)tree.get(1), delta); } } } throw new NotEnumerableError(subjectType.toString(), ctx.getCurrentAST()); // Node and ADT } else if(subjectType.isNodeType() || subjectType.isAbstractDataType()){ if (shallow){ checkMayOccur(patType, subjectType, ctx); return new NodeChildIterator((INode) subjectValue); } return new DescendantReader(subjectValue, false); } else if(subjectType.isTupleType()){ if(shallow){ int nElems = subjectType.getArity(); for(int i = 0; i < nElems; i++){ if(!subjectType.getFieldType(i).isSubtypeOf(patType)) { throw new UnexpectedTypeError(patType, subjectType.getFieldType(i), ctx.getCurrentAST()); } } return new TupleElementIterator((ITuple)subjectValue); } return new DescendantReader(subjectValue, false); } else if(subjectType.isBoolType() || subjectType.isIntegerType() || subjectType.isRealType() || subjectType.isStringType() || subjectType.isSourceLocationType() || subjectType.isDateTimeType()) { if (shallow) { throw new NotEnumerableError(subjectType.toString(), ctx.getCurrentAST()); } return new SingleIValueIterator(subjectValue); } else { throw new UnsupportedOperationError("makeIterator", subjectType, ctx.getCurrentAST()); } }
public static Iterator<IValue> make(IEvaluatorContext ctx, IMatchingResult matchPattern, Result<IValue> subject, boolean shallow){ Type subjectType = subject.getType(); IValue subjectValue = subject.getValue(); Type patType = matchPattern.getType(ctx.getCurrentEnvt(), null); if (subjectType.isValueType()) { System.err.println("???"); } // TODO: this should be a visitor design as well.. // List if(subjectType.isListType()){ //TODO: we could do this more precisely if(shallow){ checkMayOccur(patType, subjectType.getElementType(), ctx); return ((IList) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); // Set } else if(subjectType.isSetType()){ if (shallow){ checkMayOccur(patType, subjectType.getElementType(), ctx); return ((ISet) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); // Map } else if(subjectType.isMapType()){ if (shallow) { checkMayOccur(patType, subjectType.getKeyType(), ctx); return ((IMap) subjectValue).iterator(); } return new DescendantReader(subjectValue, false); } else if (subjectType.isExternalType()) { if (subjectType instanceof NonTerminalType) { // NonTerminal (both pattern and subject are non-terminals, so we can skip layout and stuff) IConstructor tree = (IConstructor) subjectValue; NonTerminalType nt = (NonTerminalType) subjectType; if (!shallow) { return new DescendantReader(tree, patType instanceof NonTerminalType); } else { if (nt.isConcreteListType()){ checkMayOccur(patType, subjectType, ctx); IConstructor ls = nt.getSymbol(); int delta = SymbolAdapter.isSepList(ls) ? (SymbolAdapter.getSeparators(ls).length() + 1) : 1; return new CFListIterator((IList)tree.get(1), delta); } } } throw new NotEnumerableError(subjectType.toString(), ctx.getCurrentAST()); // Node and ADT } else if(subjectType.isNodeType() || subjectType.isAbstractDataType()){ if (shallow){ checkMayOccur(patType, subjectType, ctx); return new NodeChildIterator((INode) subjectValue); } return new DescendantReader(subjectValue, false); } else if(subjectType.isTupleType()){ if(shallow){ int nElems = subjectType.getArity(); for(int i = 0; i < nElems; i++){ if(!subjectType.getFieldType(i).isSubtypeOf(patType)) { throw new UnexpectedTypeError(patType, subjectType.getFieldType(i), ctx.getCurrentAST()); } } return new TupleElementIterator((ITuple)subjectValue); } return new DescendantReader(subjectValue, false); } else if(subjectType.isBoolType() || subjectType.isIntegerType() || subjectType.isRealType() || subjectType.isStringType() || subjectType.isSourceLocationType() || subjectType.isRationalType() || subjectType.isDateTimeType()) { if (shallow) { throw new NotEnumerableError(subjectType.toString(), ctx.getCurrentAST()); } return new SingleIValueIterator(subjectValue); } else { throw new UnsupportedOperationError("makeIterator", subjectType, ctx.getCurrentAST()); } }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageBreakpointRulerAction.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageBreakpointRulerAction.java index 4eb17f923..9d96e029c 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageBreakpointRulerAction.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageBreakpointRulerAction.java @@ -1,303 +1,304 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui.actions; import java.text.MessageFormat; 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.IFile; import org.eclipse.core.resources.IMarker; 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.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IBreakpointManager; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; 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.debug.core.IJavaLineBreakpoint; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.debug.ui.BreakpointUtils; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IVerticalRulerInfo; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.IUpdate; public class ManageBreakpointRulerAction extends Action implements IUpdate { private IVerticalRulerInfo fRuler; private ITextEditor fTextEditor; private List fMarkers; private String fAddLabel; private String fRemoveLabel; public ManageBreakpointRulerAction(IVerticalRulerInfo ruler, ITextEditor editor) { fRuler= ruler; fTextEditor= editor; fAddLabel= ActionMessages.getString("ManageBreakpointRulerAction.add.label"); //$NON-NLS-1$ fRemoveLabel= ActionMessages.getString("ManageBreakpointRulerAction.remove.label"); //$NON-NLS-1$ } /** * Returns the resource for which to create the marker, * or <code>null</code> if there is no applicable resource. * * @return the resource for which to create the marker or <code>null</code> */ protected IResource getResource() { IEditorInput input= fTextEditor.getEditorInput(); IResource resource= (IResource) input.getAdapter(IFile.class); if (resource == null) { resource= (IResource) input.getAdapter(IResource.class); } return resource; } /** * Checks whether a position includes the ruler's line of activity. * * @param position the position to be checked * @param document the document the position refers to * @return <code>true</code> if the line is included by the given position */ protected boolean includesRulerLine(Position position, IDocument document) { if (position != null) { try { int markerLine= document.getLineOfOffset(position.getOffset()); int line= fRuler.getLineOfLastMouseButtonActivity(); if (line == markerLine) { return true; } } catch (BadLocationException x) { } } return false; } /** * Returns this action's vertical ruler info. * * @return this action's vertical ruler */ protected IVerticalRulerInfo getVerticalRulerInfo() { return fRuler; } /** * Returns this action's editor. * * @return this action's editor */ protected ITextEditor getTextEditor() { return fTextEditor; } /** * Returns the <code>AbstractMarkerAnnotationModel</code> of the editor's input. * * @return the marker annotation model */ protected AbstractMarkerAnnotationModel getAnnotationModel() { IDocumentProvider provider= fTextEditor.getDocumentProvider(); IAnnotationModel model= provider.getAnnotationModel(fTextEditor.getEditorInput()); if (model instanceof AbstractMarkerAnnotationModel) { return (AbstractMarkerAnnotationModel) model; } return null; } /** * Returns the <code>IDocument</code> of the editor's input. * * @return the document of the editor's input */ protected IDocument getDocument() { IDocumentProvider provider= fTextEditor.getDocumentProvider(); return provider.getDocument(fTextEditor.getEditorInput()); } /** * @see IUpdate#update() */ public void update() { fMarkers= getMarkers(); setText(fMarkers.isEmpty() ? fAddLabel : fRemoveLabel); } /** * @see Action#run() */ public void run() { if (fMarkers.isEmpty()) { addMarker(); } else { removeMarkers(fMarkers); } } protected List getMarkers() { List breakpoints= new ArrayList(); IResource resource= getResource(); IDocument document= getDocument(); AbstractMarkerAnnotationModel model= getAnnotationModel(); if (model != null) { try { IMarker[] markers= null; if (resource instanceof IFile) markers= resource.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE); else { IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot(); markers= root.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE); } if (markers != null) { IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); for (int i= 0; i < markers.length; i++) { IBreakpoint breakpoint= breakpointManager.getBreakpoint(markers[i]); if (breakpoint != null && breakpointManager.isRegistered(breakpoint) && includesRulerLine(model.getMarkerPosition(markers[i]), document)) breakpoints.add(markers[i]); } } } catch (CoreException x) { JDIDebugUIPlugin.log(x.getStatus()); } } return breakpoints; } protected void addMarker() { IEditorInput editorInput= getTextEditor().getEditorInput(); try { IDocument document= getDocument(); IRegion line= document.getLineInformation(getVerticalRulerInfo().getLineOfLastMouseButtonActivity()); IType type= null; - IResource resource = null; + IResource resource; IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class); if (classFile != null) { type= classFile.getType(); // bug 34856 - if this is an inner type, ensure the breakpoint is not // being added to the outer type if (type.getDeclaringType() != null) { ISourceRange sourceRange = type.getSourceRange(); int offset = line.getOffset(); int start = sourceRange.getOffset(); int end = start + sourceRange.getLength(); if (offset < start || offset > end) { // not in the inner type IStatusLineManager manager = getTextEditor().getEditorSite().getActionBars().getStatusLineManager(); manager.setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), new String[]{type.getTypeQualifiedName()})); //$NON-NLS-1$ Display.getCurrent().beep(); return; } } resource= BreakpointUtils.getBreakpointResource(type); } else if (editorInput instanceof IFileEditorInput) { IWorkingCopyManager manager= JavaUI.getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(editorInput); if (unit != null) { synchronized (unit) { unit.reconcile(); } IJavaElement e= unit.getElementAt(line.getOffset()); if (e instanceof IType) { type= (IType)e; } else if (e instanceof IMember) { type= ((IMember)e).getDeclaringType(); } } if (type != null) { resource= BreakpointUtils.getBreakpointResource(type); + } else { + resource= ((IFileEditorInput)editorInput).getFile(); } - } - if (resource == null) { + } else { resource= ResourcesPlugin.getWorkspace().getRoot(); } Map attributes= new HashMap(10); String typeName= null; int lineNumber= getVerticalRulerInfo().getLineOfLastMouseButtonActivity() + 1; // Ruler is 0-based; editor is 1-based (nice :-/ ) IJavaLineBreakpoint breakpoint= null; if (type != null) { IJavaProject project= type.getJavaProject(); typeName= type.getFullyQualifiedName(); if (type.exists() && project != null && project.isOnClasspath(type)) { if (JDIDebugModel.lineBreakpointExists(typeName, lineNumber) == null) { int start= line.getOffset(); int end= start + line.getLength() - 1; BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end); } } breakpoint= JDIDebugModel.createLineBreakpoint(resource, typeName, lineNumber, -1, -1, 0, true, attributes); } new BreakpointLocationVerifierJob(document, line.getOffset(), breakpoint, lineNumber, typeName, type, resource).schedule(); } catch (DebugException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } catch (CoreException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } catch (BadLocationException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } } protected void removeMarkers(List markers) { IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); try { Iterator e= markers.iterator(); while (e.hasNext()) { IBreakpoint breakpoint= breakpointManager.getBreakpoint((IMarker) e.next()); breakpointManager.removeBreakpoint(breakpoint, true); } } catch (CoreException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.removing.message1"), e); //$NON-NLS-1$ } } }
false
true
protected void addMarker() { IEditorInput editorInput= getTextEditor().getEditorInput(); try { IDocument document= getDocument(); IRegion line= document.getLineInformation(getVerticalRulerInfo().getLineOfLastMouseButtonActivity()); IType type= null; IResource resource = null; IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class); if (classFile != null) { type= classFile.getType(); // bug 34856 - if this is an inner type, ensure the breakpoint is not // being added to the outer type if (type.getDeclaringType() != null) { ISourceRange sourceRange = type.getSourceRange(); int offset = line.getOffset(); int start = sourceRange.getOffset(); int end = start + sourceRange.getLength(); if (offset < start || offset > end) { // not in the inner type IStatusLineManager manager = getTextEditor().getEditorSite().getActionBars().getStatusLineManager(); manager.setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), new String[]{type.getTypeQualifiedName()})); //$NON-NLS-1$ Display.getCurrent().beep(); return; } } resource= BreakpointUtils.getBreakpointResource(type); } else if (editorInput instanceof IFileEditorInput) { IWorkingCopyManager manager= JavaUI.getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(editorInput); if (unit != null) { synchronized (unit) { unit.reconcile(); } IJavaElement e= unit.getElementAt(line.getOffset()); if (e instanceof IType) { type= (IType)e; } else if (e instanceof IMember) { type= ((IMember)e).getDeclaringType(); } } if (type != null) { resource= BreakpointUtils.getBreakpointResource(type); } } if (resource == null) { resource= ResourcesPlugin.getWorkspace().getRoot(); } Map attributes= new HashMap(10); String typeName= null; int lineNumber= getVerticalRulerInfo().getLineOfLastMouseButtonActivity() + 1; // Ruler is 0-based; editor is 1-based (nice :-/ ) IJavaLineBreakpoint breakpoint= null; if (type != null) { IJavaProject project= type.getJavaProject(); typeName= type.getFullyQualifiedName(); if (type.exists() && project != null && project.isOnClasspath(type)) { if (JDIDebugModel.lineBreakpointExists(typeName, lineNumber) == null) { int start= line.getOffset(); int end= start + line.getLength() - 1; BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end); } } breakpoint= JDIDebugModel.createLineBreakpoint(resource, typeName, lineNumber, -1, -1, 0, true, attributes); } new BreakpointLocationVerifierJob(document, line.getOffset(), breakpoint, lineNumber, typeName, type, resource).schedule(); } catch (DebugException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } catch (CoreException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } catch (BadLocationException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } }
protected void addMarker() { IEditorInput editorInput= getTextEditor().getEditorInput(); try { IDocument document= getDocument(); IRegion line= document.getLineInformation(getVerticalRulerInfo().getLineOfLastMouseButtonActivity()); IType type= null; IResource resource; IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class); if (classFile != null) { type= classFile.getType(); // bug 34856 - if this is an inner type, ensure the breakpoint is not // being added to the outer type if (type.getDeclaringType() != null) { ISourceRange sourceRange = type.getSourceRange(); int offset = line.getOffset(); int start = sourceRange.getOffset(); int end = start + sourceRange.getLength(); if (offset < start || offset > end) { // not in the inner type IStatusLineManager manager = getTextEditor().getEditorSite().getActionBars().getStatusLineManager(); manager.setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), new String[]{type.getTypeQualifiedName()})); //$NON-NLS-1$ Display.getCurrent().beep(); return; } } resource= BreakpointUtils.getBreakpointResource(type); } else if (editorInput instanceof IFileEditorInput) { IWorkingCopyManager manager= JavaUI.getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(editorInput); if (unit != null) { synchronized (unit) { unit.reconcile(); } IJavaElement e= unit.getElementAt(line.getOffset()); if (e instanceof IType) { type= (IType)e; } else if (e instanceof IMember) { type= ((IMember)e).getDeclaringType(); } } if (type != null) { resource= BreakpointUtils.getBreakpointResource(type); } else { resource= ((IFileEditorInput)editorInput).getFile(); } } else { resource= ResourcesPlugin.getWorkspace().getRoot(); } Map attributes= new HashMap(10); String typeName= null; int lineNumber= getVerticalRulerInfo().getLineOfLastMouseButtonActivity() + 1; // Ruler is 0-based; editor is 1-based (nice :-/ ) IJavaLineBreakpoint breakpoint= null; if (type != null) { IJavaProject project= type.getJavaProject(); typeName= type.getFullyQualifiedName(); if (type.exists() && project != null && project.isOnClasspath(type)) { if (JDIDebugModel.lineBreakpointExists(typeName, lineNumber) == null) { int start= line.getOffset(); int end= start + line.getLength() - 1; BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end); } } breakpoint= JDIDebugModel.createLineBreakpoint(resource, typeName, lineNumber, -1, -1, 0, true, attributes); } new BreakpointLocationVerifierJob(document, line.getOffset(), breakpoint, lineNumber, typeName, type, resource).schedule(); } catch (DebugException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } catch (CoreException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } catch (BadLocationException e) { JDIDebugUIPlugin.errorDialog(ActionMessages.getString("ManageBreakpointRulerAction.error.adding.message1"), e); //$NON-NLS-1$ } }
diff --git a/src/edu/umn/cs/spatialHadoop/operations/ClosestPair.java b/src/edu/umn/cs/spatialHadoop/operations/ClosestPair.java index f6106d47..da50b408 100644 --- a/src/edu/umn/cs/spatialHadoop/operations/ClosestPair.java +++ b/src/edu/umn/cs/spatialHadoop/operations/ClosestPair.java @@ -1,336 +1,336 @@ package edu.umn.cs.spatialHadoop.operations; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.ArrayWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapred.ClusterStatus; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.TextOutputFormat; import edu.umn.cs.spatialHadoop.CommandLineArguments; import edu.umn.cs.spatialHadoop.core.CellInfo; import edu.umn.cs.spatialHadoop.core.Point; import edu.umn.cs.spatialHadoop.core.Rectangle; import edu.umn.cs.spatialHadoop.core.Shape; import edu.umn.cs.spatialHadoop.core.SpatialSite; import edu.umn.cs.spatialHadoop.mapred.PairWritable; import edu.umn.cs.spatialHadoop.mapred.ShapeArrayInputFormat; import edu.umn.cs.spatialHadoop.mapred.ShapeInputFormat; import edu.umn.cs.spatialHadoop.mapred.ShapeRecordReader; public class ClosestPair { private static final NullWritable Dummy = NullWritable.get(); static class DistanceAndPair implements Writable { double distance; PairWritable<Point> pair = new PairWritable<Point>(); public DistanceAndPair() { } public DistanceAndPair(double d, Point a, Point b) { distance = d; pair.first = a; pair.second = b; } @Override public void readFields(DataInput in) throws IOException { distance = in.readDouble(); pair.first = new Point(); pair.second = new Point(); pair.readFields(in); } @Override public void write(DataOutput out) throws IOException { out.writeDouble(distance); pair.write(out); } @Override public String toString() { StringBuffer str = new StringBuffer(); str.append(distance); str.append("\n"); str.append(pair.first); str.append("\n"); str.append(pair.second); str.append("\n"); return str.toString(); } } static class DistanceAndBuffer implements Writable { DistanceAndPair delta; Point []buffer; public DistanceAndBuffer() { } public DistanceAndBuffer(DistanceAndPair delta, Point buffer[]) { this.delta = delta; this.buffer = buffer; } @Override public void write(DataOutput out) throws IOException { delta.write(out); out.writeInt(buffer.length); for (Point p : buffer) p.write(out); } @Override public void readFields(DataInput in) throws IOException { delta = new DistanceAndPair(); delta.readFields(in); buffer = new Point[in.readInt()]; for (int i=0; i<buffer.length; i++) { buffer[i] = new Point(); buffer[i].readFields(in); } } @Override public String toString() { return ""; } } /*** * [l, r] inclusive * @param l * @param r * @return */ public static DistanceAndPair nearestNeighbor(Shape[] a, Point[] tmp, int l, int r) { if (l >= r) return new DistanceAndPair(Double.MAX_VALUE, null, null); int mid = (l + r) >> 1; double medianX = ((Point)a[mid]).x; DistanceAndPair delta1 = nearestNeighbor(a, tmp, l, mid); DistanceAndPair delta2 = nearestNeighbor(a, tmp, mid + 1, r); - DistanceAndPair delta = delta1.distance < delta2.distance ? delta1 : delta2; + DistanceAndPair delta = delta1.distance < delta2.distance || delta2.pair.first == null ? delta1 : delta2; int i = l, j = mid + 1, k = l; while (i <= mid && j <= r) if (((Point)a[i]).y < ((Point)a[j]).y) tmp[k++] = (Point)a[i++]; else tmp[k++] = (Point)a[j++]; while(i <= mid) tmp[k++] = (Point)a[i++]; while(j <= r) tmp[k++] = (Point)a[j++]; for (i=l; i<=r; i++) a[i] = tmp[i]; k = l; for (i=l; i<=r; i++) if (Math.abs(tmp[i].x - medianX) <= delta.distance) tmp[k++] = tmp[i]; for (i=l; i<k; i++) for (j=i+1; j<k; j++) { if (tmp[j].y - tmp[i].y >= delta.distance) break; - else if (tmp[i].distanceTo(tmp[j]) < delta.distance) { + else if (tmp[i].distanceTo(tmp[j]) < delta.distance || delta.pair.first == null) { delta.distance = tmp[i].distanceTo(tmp[j]); delta.pair.first = tmp[i]; delta.pair.second = tmp[j]; } } return delta; } public static class Map extends MapReduceBase implements Mapper<CellInfo, ArrayWritable, NullWritable, DistanceAndBuffer> { @Override public void map(CellInfo mbr, ArrayWritable arr, OutputCollector<NullWritable, DistanceAndBuffer> out, Reporter reporter) throws IOException { double x1 = Long.MAX_VALUE, y1 = Long.MAX_VALUE; double x2 = Long.MIN_VALUE, y2 = Long.MIN_VALUE; Shape[] a = (Shape[])arr.get(); Point[] tmp = new Point[a.length]; boolean inBuffer[] = new boolean[a.length]; for (Shape _p : a) { Point p = (Point)_p; if (p.x < x1) x1 = p.x; if (p.y < y1) y1 = p.y; if (p.x > x2) x2 = p.x; if (p.y > y2) y2 = p.y; } Arrays.sort(a); DistanceAndPair delta = nearestNeighbor(a, tmp, 0, a.length - 1); int cnt = 0; for (int i=0; i<a.length; i++) { Point p = (Point)a[i]; if (p.x <= x1 + delta.distance || p.x >= x2 - delta.distance || p.y <= y1 + delta.distance || p.y >= y2 - delta.distance) { inBuffer[i] = true; cnt++; } } Point buffer[] = new Point[cnt]; int ptr = 0; for (int i=0; i<a.length; i++) if (inBuffer[i]) buffer[ptr++] = (Point)a[i]; out.collect(Dummy, new DistanceAndBuffer(delta, buffer)); } } public static class Reduce extends MapReduceBase implements Reducer<NullWritable, DistanceAndBuffer, NullWritable, DistanceAndPair> { @Override public void reduce(NullWritable useless, Iterator<DistanceAndBuffer> it, OutputCollector<NullWritable, DistanceAndPair> out, Reporter reporter) throws IOException { DistanceAndPair delta = null; LinkedList<Point> buffer = new LinkedList<Point>(); while (it.hasNext()) { DistanceAndBuffer localBuffer = it.next(); if (delta == null) delta = localBuffer.delta; else if (localBuffer.delta.distance < delta.distance) delta = localBuffer.delta; for (Point p : localBuffer.buffer) buffer.add(p); } Point a[] = new Point[buffer.size()]; Point tmp[] = new Point[buffer.size()]; a = buffer.toArray(a); Arrays.sort(a); DistanceAndPair delta1 = nearestNeighbor(a, tmp, 0, a.length - 1); if (delta == null || delta1.distance < delta.distance) delta = delta1; out.collect(Dummy, delta); } } /** * Computes the closest pair by reading points from stream * @param p * @throws IOException */ public static <S extends Point> void closestPairStream(S p) throws IOException { ShapeRecordReader<S> reader = new ShapeRecordReader<S>(System.in, 0, Long.MAX_VALUE); ArrayList<Point> points = new ArrayList<Point>(); Rectangle key = new Rectangle(); while (reader.next(key, p)) { points.add(p.clone()); } Shape[] allPoints = points.toArray(new Shape[points.size()]); nearestNeighbor(allPoints, new Point[allPoints.length], 0, allPoints.length-1); } public static <S extends Shape> void closestPairLocal(FileSystem fs, Path file, S stockShape) throws IOException { ShapeRecordReader<S> reader = new ShapeRecordReader<S>(fs.open(file), 0, fs.getFileStatus(file).getLen()); Rectangle rect = new Rectangle(); ArrayList<Shape> cb = new ArrayList<Shape>(); while (reader.next(rect, stockShape)){ cb.add(stockShape.clone()); } System.out.println("here"); Shape []a = cb.toArray(new Point[cb.size()]); Point []tmp = new Point[cb.size()]; Arrays.sort(a); System.out.println("preprocessing is done."); DistanceAndPair delta = nearestNeighbor(a, tmp, 0, a.length - 1); System.out.println(delta); } /** * Counts the exact number of lines in a file by issuing a MapReduce job * that does the thing * @param conf * @param fs * @param file * @return * @throws IOException */ public static <S extends Shape> void closestPair(FileSystem fs, Path file, S stockShape) throws IOException { // Try to get file MBR from the MBRs of blocks JobConf job = new JobConf(ClosestPair.class); Path outputPath; FileSystem outFs = FileSystem.get(job); do { outputPath = new Path(file.getName()+".closest_pair_"+(int)(Math.random()*1000000)); } while (outFs.exists(outputPath)); outFs.delete(outputPath, true); job.setJobName("ClosestPair"); job.setMapOutputKeyClass(NullWritable.class); job.setMapOutputValueClass(DistanceAndBuffer.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); ClusterStatus clusterStatus = new JobClient(job).getClusterStatus(); job.setNumMapTasks(clusterStatus.getMaxMapTasks() * 5); job.setInputFormat(ShapeArrayInputFormat.class); // job.setInputFormat(ShapeInputFormat.class); SpatialSite.setShapeClass(job, stockShape.getClass()); ShapeInputFormat.setInputPaths(job, file); job.setOutputFormat(TextOutputFormat.class); TextOutputFormat.setOutputPath(job, outputPath); // Submit the job JobClient.runJob(job); outFs.delete(outputPath, true); } private static void printUsage() { System.out.println("Finds the average area of all rectangles in an input file"); System.out.println("Parameters: (* marks required parameters)"); System.out.println("<input file>: (*) Path to input file"); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { CommandLineArguments cla = new CommandLineArguments(args); if (cla.getPaths().length == 0 && cla.isLocal()) { long t1 = System.currentTimeMillis(); closestPairStream((Point)cla.getShape(true)); long t2 = System.currentTimeMillis(); System.out.println("Total time: "+(t2-t1)+" millis"); return; } if (args.length == 0) { printUsage(); throw new RuntimeException("Illegal arguments. Input file missing"); } Path inputFile = new Path(args[0]); FileSystem fs = inputFile.getFileSystem(new Configuration()); if (!fs.exists(inputFile)) { printUsage(); throw new RuntimeException("Input file does not exist"); } Shape stockShape = new Point(); if (SpatialSite.getGlobalIndex(fs, inputFile) != null) closestPair(fs, inputFile, stockShape); else ClosestPairHadoop.cloesetPair(fs, inputFile, stockShape); // closestPairLocal(fs, inputFile, stockShape); } }
false
true
public static DistanceAndPair nearestNeighbor(Shape[] a, Point[] tmp, int l, int r) { if (l >= r) return new DistanceAndPair(Double.MAX_VALUE, null, null); int mid = (l + r) >> 1; double medianX = ((Point)a[mid]).x; DistanceAndPair delta1 = nearestNeighbor(a, tmp, l, mid); DistanceAndPair delta2 = nearestNeighbor(a, tmp, mid + 1, r); DistanceAndPair delta = delta1.distance < delta2.distance ? delta1 : delta2; int i = l, j = mid + 1, k = l; while (i <= mid && j <= r) if (((Point)a[i]).y < ((Point)a[j]).y) tmp[k++] = (Point)a[i++]; else tmp[k++] = (Point)a[j++]; while(i <= mid) tmp[k++] = (Point)a[i++]; while(j <= r) tmp[k++] = (Point)a[j++]; for (i=l; i<=r; i++) a[i] = tmp[i]; k = l; for (i=l; i<=r; i++) if (Math.abs(tmp[i].x - medianX) <= delta.distance) tmp[k++] = tmp[i]; for (i=l; i<k; i++) for (j=i+1; j<k; j++) { if (tmp[j].y - tmp[i].y >= delta.distance) break; else if (tmp[i].distanceTo(tmp[j]) < delta.distance) { delta.distance = tmp[i].distanceTo(tmp[j]); delta.pair.first = tmp[i]; delta.pair.second = tmp[j]; } } return delta; }
public static DistanceAndPair nearestNeighbor(Shape[] a, Point[] tmp, int l, int r) { if (l >= r) return new DistanceAndPair(Double.MAX_VALUE, null, null); int mid = (l + r) >> 1; double medianX = ((Point)a[mid]).x; DistanceAndPair delta1 = nearestNeighbor(a, tmp, l, mid); DistanceAndPair delta2 = nearestNeighbor(a, tmp, mid + 1, r); DistanceAndPair delta = delta1.distance < delta2.distance || delta2.pair.first == null ? delta1 : delta2; int i = l, j = mid + 1, k = l; while (i <= mid && j <= r) if (((Point)a[i]).y < ((Point)a[j]).y) tmp[k++] = (Point)a[i++]; else tmp[k++] = (Point)a[j++]; while(i <= mid) tmp[k++] = (Point)a[i++]; while(j <= r) tmp[k++] = (Point)a[j++]; for (i=l; i<=r; i++) a[i] = tmp[i]; k = l; for (i=l; i<=r; i++) if (Math.abs(tmp[i].x - medianX) <= delta.distance) tmp[k++] = tmp[i]; for (i=l; i<k; i++) for (j=i+1; j<k; j++) { if (tmp[j].y - tmp[i].y >= delta.distance) break; else if (tmp[i].distanceTo(tmp[j]) < delta.distance || delta.pair.first == null) { delta.distance = tmp[i].distanceTo(tmp[j]); delta.pair.first = tmp[i]; delta.pair.second = tmp[j]; } } return delta; }
diff --git a/OSLC4JChangeManagement/src/org/eclipse/lyo/oslc4j/changemanagement/servlet/ServiceProviderFactory.java b/OSLC4JChangeManagement/src/org/eclipse/lyo/oslc4j/changemanagement/servlet/ServiceProviderFactory.java index 8a3ed9b..5c4a804 100644 --- a/OSLC4JChangeManagement/src/org/eclipse/lyo/oslc4j/changemanagement/servlet/ServiceProviderFactory.java +++ b/OSLC4JChangeManagement/src/org/eclipse/lyo/oslc4j/changemanagement/servlet/ServiceProviderFactory.java @@ -1,74 +1,76 @@ /******************************************************************************* * Copyright (c) 2012 IBM Corporation. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * * Russell Boykin - initial API and implementation * Alberto Giammaria - initial API and implementation * Chris Peters - initial API and implementation * Gianluca Bernardini - initial API and implementation *******************************************************************************/ package org.eclipse.lyo.oslc4j.changemanagement.servlet; import java.net.URI; import java.net.URISyntaxException; import org.eclipse.lyo.oslc4j.changemanagement.Constants; import org.eclipse.lyo.oslc4j.changemanagement.resources.ChangeRequestResource; import org.eclipse.lyo.oslc4j.client.ServiceProviderRegistryURIs; import org.eclipse.lyo.oslc4j.core.exception.OslcCoreApplicationException; import org.eclipse.lyo.oslc4j.core.model.OslcConstants; import org.eclipse.lyo.oslc4j.core.model.PrefixDefinition; import org.eclipse.lyo.oslc4j.core.model.Publisher; import org.eclipse.lyo.oslc4j.core.model.ServiceProvider; class ServiceProviderFactory { private static Class<?>[] RESOURCE_CLASSES = { ChangeRequestResource.class }; private ServiceProviderFactory() { super(); } public static ServiceProvider createServiceProvider(final String baseURI) throws OslcCoreApplicationException, URISyntaxException { final ServiceProvider serviceProvider = org.eclipse.lyo.oslc4j.core.model.ServiceProviderFactory.createServiceProvider(baseURI, ServiceProviderRegistryURIs.getUIURI(), "OSLC IBM Change Management Service Provider", "Reference Implementation OSLC IBM Change Management Service Provider", - new Publisher("Russell and Chris", "IBM"), + new Publisher("Eclipse Lyo", "urn:oslc:ServiceProvider"), RESOURCE_CLASSES ); + URI detailsURIs[] = {new URI(baseURI)}; + serviceProvider.setDetails(detailsURIs); final PrefixDefinition[] prefixDefinitions = { new PrefixDefinition(OslcConstants.DCTERMS_NAMESPACE_PREFIX, new URI(OslcConstants.DCTERMS_NAMESPACE)), new PrefixDefinition(OslcConstants.OSLC_CORE_NAMESPACE_PREFIX, new URI(OslcConstants.OSLC_CORE_NAMESPACE)), new PrefixDefinition(OslcConstants.OSLC_DATA_NAMESPACE_PREFIX, new URI(OslcConstants.OSLC_DATA_NAMESPACE)), new PrefixDefinition(OslcConstants.RDF_NAMESPACE_PREFIX, new URI(OslcConstants.RDF_NAMESPACE)), new PrefixDefinition(OslcConstants.RDFS_NAMESPACE_PREFIX, new URI(OslcConstants.RDFS_NAMESPACE)), new PrefixDefinition(Constants.CHANGE_MANAGEMENT_NAMESPACE_PREFIX, new URI(Constants.CHANGE_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.FOAF_NAMESPACE_PREFIX, new URI(Constants.FOAF_NAMESPACE)), new PrefixDefinition(Constants.QUALITY_MANAGEMENT_PREFIX, new URI(Constants.QUALITY_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.REQUIREMENTS_MANAGEMENT_PREFIX, new URI(Constants.REQUIREMENTS_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.SOFTWARE_CONFIGURATION_MANAGEMENT_PREFIX, new URI(Constants.SOFTWARE_CONFIGURATION_MANAGEMENT_NAMESPACE)) }; serviceProvider.setPrefixDefinitions(prefixDefinitions); return serviceProvider; } }
false
true
public static ServiceProvider createServiceProvider(final String baseURI) throws OslcCoreApplicationException, URISyntaxException { final ServiceProvider serviceProvider = org.eclipse.lyo.oslc4j.core.model.ServiceProviderFactory.createServiceProvider(baseURI, ServiceProviderRegistryURIs.getUIURI(), "OSLC IBM Change Management Service Provider", "Reference Implementation OSLC IBM Change Management Service Provider", new Publisher("Russell and Chris", "IBM"), RESOURCE_CLASSES ); final PrefixDefinition[] prefixDefinitions = { new PrefixDefinition(OslcConstants.DCTERMS_NAMESPACE_PREFIX, new URI(OslcConstants.DCTERMS_NAMESPACE)), new PrefixDefinition(OslcConstants.OSLC_CORE_NAMESPACE_PREFIX, new URI(OslcConstants.OSLC_CORE_NAMESPACE)), new PrefixDefinition(OslcConstants.OSLC_DATA_NAMESPACE_PREFIX, new URI(OslcConstants.OSLC_DATA_NAMESPACE)), new PrefixDefinition(OslcConstants.RDF_NAMESPACE_PREFIX, new URI(OslcConstants.RDF_NAMESPACE)), new PrefixDefinition(OslcConstants.RDFS_NAMESPACE_PREFIX, new URI(OslcConstants.RDFS_NAMESPACE)), new PrefixDefinition(Constants.CHANGE_MANAGEMENT_NAMESPACE_PREFIX, new URI(Constants.CHANGE_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.FOAF_NAMESPACE_PREFIX, new URI(Constants.FOAF_NAMESPACE)), new PrefixDefinition(Constants.QUALITY_MANAGEMENT_PREFIX, new URI(Constants.QUALITY_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.REQUIREMENTS_MANAGEMENT_PREFIX, new URI(Constants.REQUIREMENTS_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.SOFTWARE_CONFIGURATION_MANAGEMENT_PREFIX, new URI(Constants.SOFTWARE_CONFIGURATION_MANAGEMENT_NAMESPACE)) }; serviceProvider.setPrefixDefinitions(prefixDefinitions); return serviceProvider; }
public static ServiceProvider createServiceProvider(final String baseURI) throws OslcCoreApplicationException, URISyntaxException { final ServiceProvider serviceProvider = org.eclipse.lyo.oslc4j.core.model.ServiceProviderFactory.createServiceProvider(baseURI, ServiceProviderRegistryURIs.getUIURI(), "OSLC IBM Change Management Service Provider", "Reference Implementation OSLC IBM Change Management Service Provider", new Publisher("Eclipse Lyo", "urn:oslc:ServiceProvider"), RESOURCE_CLASSES ); URI detailsURIs[] = {new URI(baseURI)}; serviceProvider.setDetails(detailsURIs); final PrefixDefinition[] prefixDefinitions = { new PrefixDefinition(OslcConstants.DCTERMS_NAMESPACE_PREFIX, new URI(OslcConstants.DCTERMS_NAMESPACE)), new PrefixDefinition(OslcConstants.OSLC_CORE_NAMESPACE_PREFIX, new URI(OslcConstants.OSLC_CORE_NAMESPACE)), new PrefixDefinition(OslcConstants.OSLC_DATA_NAMESPACE_PREFIX, new URI(OslcConstants.OSLC_DATA_NAMESPACE)), new PrefixDefinition(OslcConstants.RDF_NAMESPACE_PREFIX, new URI(OslcConstants.RDF_NAMESPACE)), new PrefixDefinition(OslcConstants.RDFS_NAMESPACE_PREFIX, new URI(OslcConstants.RDFS_NAMESPACE)), new PrefixDefinition(Constants.CHANGE_MANAGEMENT_NAMESPACE_PREFIX, new URI(Constants.CHANGE_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.FOAF_NAMESPACE_PREFIX, new URI(Constants.FOAF_NAMESPACE)), new PrefixDefinition(Constants.QUALITY_MANAGEMENT_PREFIX, new URI(Constants.QUALITY_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.REQUIREMENTS_MANAGEMENT_PREFIX, new URI(Constants.REQUIREMENTS_MANAGEMENT_NAMESPACE)), new PrefixDefinition(Constants.SOFTWARE_CONFIGURATION_MANAGEMENT_PREFIX, new URI(Constants.SOFTWARE_CONFIGURATION_MANAGEMENT_NAMESPACE)) }; serviceProvider.setPrefixDefinitions(prefixDefinitions); return serviceProvider; }
diff --git a/tomcat-main/src/test/java/org/collectionspace/chain/csp/persistence/services/vocab/TestGenerateAuthorities.java b/tomcat-main/src/test/java/org/collectionspace/chain/csp/persistence/services/vocab/TestGenerateAuthorities.java index e35d3daa..7fa3da25 100644 --- a/tomcat-main/src/test/java/org/collectionspace/chain/csp/persistence/services/vocab/TestGenerateAuthorities.java +++ b/tomcat-main/src/test/java/org/collectionspace/chain/csp/persistence/services/vocab/TestGenerateAuthorities.java @@ -1,78 +1,78 @@ package org.collectionspace.chain.csp.persistence.services.vocab; import static org.junit.Assert.*; import org.collectionspace.chain.csp.persistence.TestBase; import org.json.JSONArray; import org.json.JSONObject; import org.junit.AfterClass; import org.junit.Test; import org.mortbay.jetty.testing.HttpTester; import org.mortbay.jetty.testing.ServletTester; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestGenerateAuthorities { private static final Logger log = LoggerFactory .getLogger(TestGenerateAuthorities.class); private static TestBase tester = new TestBase(); static ServletTester jetty; static { try{ jetty=tester.setupJetty(); } catch(Exception ex){ } } @AfterClass public static void testStop() throws Exception { tester.stopJetty(jetty); } @Test public void testSetUp() throws Exception { HttpTester out; log.info("initialize authorities"); //String urltest = "/vocabularies/currency/refresh?datapath=/Users/csm22/Documents/collectionspace/test.txt"; //out = tester.GETData(urltest, jetty); // repopulate the authorities with dummy data //DONOT RUN THIS TEST LOCALLY out = tester.GETData("/reset/", jetty); //do we have any records out = tester.GETData("/authorities/organization/?pageSize=1", jetty); JSONArray resultsOrg = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsOrg.length() > 0); //do we have any records out = tester.GETData("/authorities/person/?pageSize=1", jetty); JSONArray resultsPerson = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsPerson.length() > 0); //do we have any records out = tester.GETData("/authorities/concept/?pageSize=1", jetty); - JSONArray resultsContent = new JSONObject(out.getContent()).getJSONArray("items"); - assertTrue(resultsContent.length() > 0); + JSONArray resultsConcept = new JSONObject(out.getContent()).getJSONArray("items"); + assertTrue(resultsConcept.length() > 0); //do we have any records out = tester.GETData("/authorities/place/?pageSize=1", jetty); JSONArray resultsPlace = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsPlace.length() > 0); //make sure all the vocabs are initialized out = tester.GETData("/authorities/vocab/initialize", jetty); // update and remove fields not in each list within an authority // /chain/vocabularies/person/initialize?datapath=/Users/csm22/Documents/collectionspace/svcapp/cspi-webui/src/main/resources/org/collectionspace/chain/csp/webui/misc/names.txt } }
true
true
public void testSetUp() throws Exception { HttpTester out; log.info("initialize authorities"); //String urltest = "/vocabularies/currency/refresh?datapath=/Users/csm22/Documents/collectionspace/test.txt"; //out = tester.GETData(urltest, jetty); // repopulate the authorities with dummy data //DONOT RUN THIS TEST LOCALLY out = tester.GETData("/reset/", jetty); //do we have any records out = tester.GETData("/authorities/organization/?pageSize=1", jetty); JSONArray resultsOrg = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsOrg.length() > 0); //do we have any records out = tester.GETData("/authorities/person/?pageSize=1", jetty); JSONArray resultsPerson = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsPerson.length() > 0); //do we have any records out = tester.GETData("/authorities/concept/?pageSize=1", jetty); JSONArray resultsContent = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsContent.length() > 0); //do we have any records out = tester.GETData("/authorities/place/?pageSize=1", jetty); JSONArray resultsPlace = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsPlace.length() > 0); //make sure all the vocabs are initialized out = tester.GETData("/authorities/vocab/initialize", jetty); // update and remove fields not in each list within an authority // /chain/vocabularies/person/initialize?datapath=/Users/csm22/Documents/collectionspace/svcapp/cspi-webui/src/main/resources/org/collectionspace/chain/csp/webui/misc/names.txt }
public void testSetUp() throws Exception { HttpTester out; log.info("initialize authorities"); //String urltest = "/vocabularies/currency/refresh?datapath=/Users/csm22/Documents/collectionspace/test.txt"; //out = tester.GETData(urltest, jetty); // repopulate the authorities with dummy data //DONOT RUN THIS TEST LOCALLY out = tester.GETData("/reset/", jetty); //do we have any records out = tester.GETData("/authorities/organization/?pageSize=1", jetty); JSONArray resultsOrg = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsOrg.length() > 0); //do we have any records out = tester.GETData("/authorities/person/?pageSize=1", jetty); JSONArray resultsPerson = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsPerson.length() > 0); //do we have any records out = tester.GETData("/authorities/concept/?pageSize=1", jetty); JSONArray resultsConcept = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsConcept.length() > 0); //do we have any records out = tester.GETData("/authorities/place/?pageSize=1", jetty); JSONArray resultsPlace = new JSONObject(out.getContent()).getJSONArray("items"); assertTrue(resultsPlace.length() > 0); //make sure all the vocabs are initialized out = tester.GETData("/authorities/vocab/initialize", jetty); // update and remove fields not in each list within an authority // /chain/vocabularies/person/initialize?datapath=/Users/csm22/Documents/collectionspace/svcapp/cspi-webui/src/main/resources/org/collectionspace/chain/csp/webui/misc/names.txt }
diff --git a/VisualWAS/src/main/java/com/github/veithen/visualwas/WebSpherePropertiesPanel.java b/VisualWAS/src/main/java/com/github/veithen/visualwas/WebSpherePropertiesPanel.java index 28e36ba..f140528 100644 --- a/VisualWAS/src/main/java/com/github/veithen/visualwas/WebSpherePropertiesPanel.java +++ b/VisualWAS/src/main/java/com/github/veithen/visualwas/WebSpherePropertiesPanel.java @@ -1,302 +1,306 @@ package com.github.veithen.visualwas; import static java.awt.GridBagConstraints.BOTH; import static java.awt.GridBagConstraints.HORIZONTAL; import static java.awt.GridBagConstraints.NONE; import static java.awt.GridBagConstraints.NORTHWEST; import static java.awt.GridBagConstraints.REMAINDER; import static java.awt.GridBagConstraints.WEST; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.MalformedURLException; import java.security.cert.X509Certificate; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.net.ssl.SSLHandshakeException; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.openide.awt.Mnemonics; import org.openide.util.NbBundle; import com.github.veithen.visualwas.env.EnvUtil; import com.github.veithen.visualwas.jmx.soap.SOAPJMXConnector; import com.github.veithen.visualwas.trust.NotTrustedException; import com.sun.tools.visualvm.core.properties.PropertiesPanel; import com.sun.tools.visualvm.core.ui.components.Spacer; public class WebSpherePropertiesPanel extends PropertiesPanel { private static final long serialVersionUID = -5821630337324177997L; private static ImageIcon connectingIcon = new ImageIcon(WebSpherePropertiesPanel.class.getResource("connecting.gif")); private static ImageIcon errorIcon = new ImageIcon(WebSpherePropertiesPanel.class.getResource("error.png")); private static ImageIcon okIcon = new ImageIcon(WebSpherePropertiesPanel.class.getResource("ok.png")); private final JTextField hostField; private final JTextField portField; private final JCheckBox securityCheckbox; private final JTextField usernameField; private final JPasswordField passwordField; private final JCheckBox saveCheckbox; private final JButton testConnectionButton; private final JLabel testConnectionResult; public WebSpherePropertiesPanel() { setLayout(new GridBagLayout()); { JLabel hostLabel = new JLabel(); Mnemonics.setLocalizedText(hostLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Host")); add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); hostField = new JTextField(); hostLabel.setLabelFor(hostField); hostField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(hostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel portLabel = new JLabel(); Mnemonics.setLocalizedText(portLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Port")); add(portLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); portField = new JTextField(6); + // Prevent the field from "collapsing" when the available space is smaller than the preferred size + portField.setMinimumSize(portField.getPreferredSize()); portLabel.setLabelFor(portField); portField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(portField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { securityCheckbox = new JCheckBox(); Mnemonics.setLocalizedText(securityCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Security_enabled")); securityCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); resetConnectionTestResults(); }; }); add(securityCheckbox, new GridBagConstraints(0, 2, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(8, 0, 2, 0), 0, 0)); } { JLabel usernameLabel = new JLabel(); Mnemonics.setLocalizedText(usernameLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Username")); add(usernameLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); usernameField = new JTextField(12); + usernameField.setMinimumSize(usernameField.getPreferredSize()); usernameLabel.setLabelFor(usernameField); usernameField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(usernameField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel passwordLabel = new JLabel(); Mnemonics.setLocalizedText(passwordLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Password")); add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); passwordField = new JPasswordField(12); + passwordField.setMinimumSize(passwordField.getPreferredSize()); passwordLabel.setLabelFor(passwordField); passwordField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(passwordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { saveCheckbox = new JCheckBox(); // NOI18N Mnemonics.setLocalizedText(saveCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Save_security_credentials")); saveCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); }; }); add(saveCheckbox, new GridBagConstraints(0, 5, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); } { testConnectionButton = new JButton(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { testConnection(); } }); Mnemonics.setLocalizedText(testConnectionButton, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Test_connection")); add(testConnectionButton, new GridBagConstraints(0, 6, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(5, 0, 2, 0), 0, 0)); } { testConnectionResult = new JLabel(); testConnectionResult.setBorder(BorderFactory.createEtchedBorder()); testConnectionResult.setBackground(Color.WHITE); testConnectionResult.setOpaque(true); testConnectionResult.setPreferredSize(new Dimension(50, 50)); add(testConnectionResult, new GridBagConstraints(0, 7, REMAINDER, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); } add(Spacer.create(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, NORTHWEST, BOTH, new Insets(0, 0, 0, 0), 0, 0)); update(); } public String getHost() { return hostField.getText(); } public void setHost(String host) { hostField.setText(host); } public int getPort() { try { return Integer.parseInt(portField.getText()); } catch (NumberFormatException ex) { return -1; } } public void setPort(int port) { portField.setText(String.valueOf(port)); } public boolean isSecurityEnabled() { return securityCheckbox.isSelected(); } public void setSecurityEnabled(boolean securityEnabled) { securityCheckbox.setSelected(securityEnabled); } public String getUsername() { return isSecurityEnabled() ? usernameField.getText() : null; } public void setUsername(String username) { usernameField.setText(username); } public char[] getPassword() { return isSecurityEnabled() ? passwordField.getPassword() : null; } public void setPassword(String password) { passwordField.setText(password); } public boolean isSaveCredentials() { return isSecurityEnabled() && saveCheckbox.isSelected(); } public void setSaveCredentials(boolean saveCredentials) { saveCheckbox.setSelected(saveCredentials); } private void update() { int port = getPort(); testConnectionButton.setEnabled(getHost().length() > 0 && port > 0 && port < 1<<16); boolean securityEnabled = securityCheckbox.isSelected(); usernameField.setEnabled(securityEnabled); passwordField.setEnabled(securityEnabled); saveCheckbox.setEnabled(securityEnabled); } private void testConnection() { testConnectionButton.setEnabled(false); testConnectionResult.setIcon(connectingIcon); testConnectionResult.setText(NbBundle.getMessage(WebSpherePropertiesPanel.class, "MSG_Connecting")); final JMXServiceURL serviceURL; try { serviceURL = new JMXServiceURL("soap", getHost(), getPort()); } catch (MalformedURLException ex) { // We should never get here throw new Error(ex); } boolean securityEnabled = isSecurityEnabled(); final Map<String,Object> env = EnvUtil.createEnvironment(securityEnabled); if (securityEnabled) { env.put(JMXConnector.CREDENTIALS, new String[] { getUsername(), new String(getPassword()) }); } env.put(SOAPJMXConnector.CONNECT_TIMEOUT, 8000); new Thread() { @Override public void run() { IOException tmpException = null; try { JMXConnectorFactory.connect(serviceURL, env); } catch (IOException ex) { tmpException = ex; } final IOException exception = tmpException; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { testConnectionButton.setEnabled(true); if (exception == null) { testConnectionResult.setIcon(okIcon); testConnectionResult.setText(NbBundle.getMessage(WebSpherePropertiesPanel.class, "MSG_Connection_successful")); setSettingsValid(true); } else if (exception instanceof SSLHandshakeException && exception.getCause() instanceof NotTrustedException) { X509Certificate[] chain = ((NotTrustedException)exception.getCause()).getChain(); SignerExchangeDialog dialog = new SignerExchangeDialog(SwingUtilities.getWindowAncestor(WebSpherePropertiesPanel.this), chain); if (!dialog.showDialog()) { resetConnectionTestResults(); } else { testConnection(); } } else { exception.printStackTrace(); testConnectionResult.setIcon(errorIcon); testConnectionResult.setText(exception.getClass().getSimpleName() + ": " + exception.getMessage()); setSettingsValid(false); } } }); } }.start(); } private void resetConnectionTestResults() { testConnectionResult.setIcon(null); testConnectionResult.setText(null); setSettingsValid(false); } }
false
true
public WebSpherePropertiesPanel() { setLayout(new GridBagLayout()); { JLabel hostLabel = new JLabel(); Mnemonics.setLocalizedText(hostLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Host")); add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); hostField = new JTextField(); hostLabel.setLabelFor(hostField); hostField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(hostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel portLabel = new JLabel(); Mnemonics.setLocalizedText(portLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Port")); add(portLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); portField = new JTextField(6); portLabel.setLabelFor(portField); portField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(portField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { securityCheckbox = new JCheckBox(); Mnemonics.setLocalizedText(securityCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Security_enabled")); securityCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); resetConnectionTestResults(); }; }); add(securityCheckbox, new GridBagConstraints(0, 2, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(8, 0, 2, 0), 0, 0)); } { JLabel usernameLabel = new JLabel(); Mnemonics.setLocalizedText(usernameLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Username")); add(usernameLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); usernameField = new JTextField(12); usernameLabel.setLabelFor(usernameField); usernameField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(usernameField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel passwordLabel = new JLabel(); Mnemonics.setLocalizedText(passwordLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Password")); add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); passwordField = new JPasswordField(12); passwordLabel.setLabelFor(passwordField); passwordField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(passwordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { saveCheckbox = new JCheckBox(); // NOI18N Mnemonics.setLocalizedText(saveCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Save_security_credentials")); saveCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); }; }); add(saveCheckbox, new GridBagConstraints(0, 5, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); } { testConnectionButton = new JButton(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { testConnection(); } }); Mnemonics.setLocalizedText(testConnectionButton, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Test_connection")); add(testConnectionButton, new GridBagConstraints(0, 6, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(5, 0, 2, 0), 0, 0)); } { testConnectionResult = new JLabel(); testConnectionResult.setBorder(BorderFactory.createEtchedBorder()); testConnectionResult.setBackground(Color.WHITE); testConnectionResult.setOpaque(true); testConnectionResult.setPreferredSize(new Dimension(50, 50)); add(testConnectionResult, new GridBagConstraints(0, 7, REMAINDER, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); } add(Spacer.create(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, NORTHWEST, BOTH, new Insets(0, 0, 0, 0), 0, 0)); update(); }
public WebSpherePropertiesPanel() { setLayout(new GridBagLayout()); { JLabel hostLabel = new JLabel(); Mnemonics.setLocalizedText(hostLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Host")); add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); hostField = new JTextField(); hostLabel.setLabelFor(hostField); hostField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(hostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel portLabel = new JLabel(); Mnemonics.setLocalizedText(portLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Port")); add(portLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); portField = new JTextField(6); // Prevent the field from "collapsing" when the available space is smaller than the preferred size portField.setMinimumSize(portField.getPreferredSize()); portLabel.setLabelFor(portField); portField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(portField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { securityCheckbox = new JCheckBox(); Mnemonics.setLocalizedText(securityCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Security_enabled")); securityCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); resetConnectionTestResults(); }; }); add(securityCheckbox, new GridBagConstraints(0, 2, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(8, 0, 2, 0), 0, 0)); } { JLabel usernameLabel = new JLabel(); Mnemonics.setLocalizedText(usernameLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Username")); add(usernameLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); usernameField = new JTextField(12); usernameField.setMinimumSize(usernameField.getPreferredSize()); usernameLabel.setLabelFor(usernameField); usernameField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(usernameField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel passwordLabel = new JLabel(); Mnemonics.setLocalizedText(passwordLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Password")); add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); passwordField = new JPasswordField(12); passwordField.setMinimumSize(passwordField.getPreferredSize()); passwordLabel.setLabelFor(passwordField); passwordField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(passwordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { saveCheckbox = new JCheckBox(); // NOI18N Mnemonics.setLocalizedText(saveCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Save_security_credentials")); saveCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); }; }); add(saveCheckbox, new GridBagConstraints(0, 5, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); } { testConnectionButton = new JButton(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { testConnection(); } }); Mnemonics.setLocalizedText(testConnectionButton, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Test_connection")); add(testConnectionButton, new GridBagConstraints(0, 6, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(5, 0, 2, 0), 0, 0)); } { testConnectionResult = new JLabel(); testConnectionResult.setBorder(BorderFactory.createEtchedBorder()); testConnectionResult.setBackground(Color.WHITE); testConnectionResult.setOpaque(true); testConnectionResult.setPreferredSize(new Dimension(50, 50)); add(testConnectionResult, new GridBagConstraints(0, 7, REMAINDER, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); } add(Spacer.create(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, NORTHWEST, BOTH, new Insets(0, 0, 0, 0), 0, 0)); update(); }
diff --git a/omod/src/main/java/org/openmrs/module/kenyaemr/fragment/controller/MedicalChartUtilFragmentController.java b/omod/src/main/java/org/openmrs/module/kenyaemr/fragment/controller/MedicalChartUtilFragmentController.java index f192285e..ab0a7995 100644 --- a/omod/src/main/java/org/openmrs/module/kenyaemr/fragment/controller/MedicalChartUtilFragmentController.java +++ b/omod/src/main/java/org/openmrs/module/kenyaemr/fragment/controller/MedicalChartUtilFragmentController.java @@ -1,43 +1,45 @@ /** * 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.module.kenyaemr.fragment.controller; import java.util.ArrayList; import java.util.List; import org.openmrs.Patient; import org.openmrs.api.context.Context; import org.openmrs.ui.framework.SimpleObject; import org.openmrs.ui.framework.UiUtils; import org.openmrs.ui.framework.session.Session; /** * Helpful utility actions for the medical chart app */ public class MedicalChartUtilFragmentController { public List<SimpleObject> recentlyViewed(UiUtils ui,Session session) { List<Integer> recent = session.getAttribute("kenyaemr.medicalChart.recentlyViewedPatients", List.class); List<Patient> pats = new ArrayList<Patient>(); - for (Integer ptId : recent) { - pats.add(Context.getPatientService().getPatient(ptId)); + if (recent != null) { + for (Integer ptId : recent) { + pats.add(Context.getPatientService().getPatient(ptId)); + } } return simplePatientList(ui, pats); } private List<SimpleObject> simplePatientList(UiUtils ui, List<Patient> pts) { return SimpleObject.fromCollection(pts, ui, "patientId", "personName", "age", "birthdate", "gender", "activeIdentifiers.identifierType", "activeIdentifiers.identifier"); } }
true
true
public List<SimpleObject> recentlyViewed(UiUtils ui,Session session) { List<Integer> recent = session.getAttribute("kenyaemr.medicalChart.recentlyViewedPatients", List.class); List<Patient> pats = new ArrayList<Patient>(); for (Integer ptId : recent) { pats.add(Context.getPatientService().getPatient(ptId)); } return simplePatientList(ui, pats); }
public List<SimpleObject> recentlyViewed(UiUtils ui,Session session) { List<Integer> recent = session.getAttribute("kenyaemr.medicalChart.recentlyViewedPatients", List.class); List<Patient> pats = new ArrayList<Patient>(); if (recent != null) { for (Integer ptId : recent) { pats.add(Context.getPatientService().getPatient(ptId)); } } return simplePatientList(ui, pats); }
diff --git a/src/java/davmail/exchange/dav/DavExchangeSession.java b/src/java/davmail/exchange/dav/DavExchangeSession.java index c789339..323ddff 100644 --- a/src/java/davmail/exchange/dav/DavExchangeSession.java +++ b/src/java/davmail/exchange/dav/DavExchangeSession.java @@ -1,1711 +1,1711 @@ /* * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway * Copyright (C) 2010 Mickael Guessant * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package davmail.exchange.dav; import davmail.BundleMessage; import davmail.Settings; import davmail.exception.DavMailAuthenticationException; import davmail.exception.DavMailException; import davmail.exception.HttpNotFoundException; import davmail.exchange.ExchangeSession; import davmail.http.DavGatewayHttpClientFacade; import davmail.ui.tray.DavGatewayTray; import davmail.util.IOUtil; import davmail.util.StringUtil; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.*; import org.apache.commons.httpclient.util.URIUtil; import org.apache.jackrabbit.webdav.DavConstants; import org.apache.jackrabbit.webdav.DavException; import org.apache.jackrabbit.webdav.MultiStatus; import org.apache.jackrabbit.webdav.MultiStatusResponse; import org.apache.jackrabbit.webdav.client.methods.CopyMethod; import org.apache.jackrabbit.webdav.client.methods.MoveMethod; import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; import org.apache.jackrabbit.webdav.client.methods.PropPatchMethod; import org.apache.jackrabbit.webdav.property.DavProperty; import org.apache.jackrabbit.webdav.property.DavPropertyNameSet; import org.apache.jackrabbit.webdav.property.DavPropertySet; import org.w3c.dom.Node; import javax.mail.MessagingException; import java.io.*; import java.net.HttpURLConnection; import java.net.NoRouteToHostException; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.util.*; import java.util.zip.GZIPInputStream; /** * Webdav Exchange adapter. * Compatible with Exchange 2003 and 2007 with webdav available. */ public class DavExchangeSession extends ExchangeSession { protected static enum FolderQueryTraversal { Shallow, Deep } protected static final DavPropertyNameSet WELL_KNOWN_FOLDERS = new DavPropertyNameSet(); static { WELL_KNOWN_FOLDERS.add(Field.getPropertyName("inbox")); WELL_KNOWN_FOLDERS.add(Field.getPropertyName("deleteditems")); WELL_KNOWN_FOLDERS.add(Field.getPropertyName("sentitems")); WELL_KNOWN_FOLDERS.add(Field.getPropertyName("sendmsg")); WELL_KNOWN_FOLDERS.add(Field.getPropertyName("drafts")); WELL_KNOWN_FOLDERS.add(Field.getPropertyName("calendar")); WELL_KNOWN_FOLDERS.add(Field.getPropertyName("contacts")); WELL_KNOWN_FOLDERS.add(Field.getPropertyName("outbox")); } /** * Various standard mail boxes Urls */ protected String inboxUrl; protected String deleteditemsUrl; protected String sentitemsUrl; protected String sendmsgUrl; protected String draftsUrl; protected String calendarUrl; protected String contactsUrl; protected String outboxUrl; protected String inboxName; protected String deleteditemsName; protected String sentitemsName; protected String draftsName; protected String calendarName; protected String contactsName; protected String outboxName; protected static final String USERS = "/users/"; /** * Convert logical or relative folder path to exchange folder path. * * @param folderPath folder name * @return folder path */ public String getFolderPath(String folderPath) { String exchangeFolderPath; // IMAP path if (folderPath.startsWith(INBOX)) { exchangeFolderPath = mailPath + inboxName + folderPath.substring(INBOX.length()); } else if (folderPath.startsWith(TRASH)) { exchangeFolderPath = mailPath + deleteditemsName + folderPath.substring(TRASH.length()); } else if (folderPath.startsWith(DRAFTS)) { exchangeFolderPath = mailPath + draftsName + folderPath.substring(DRAFTS.length()); } else if (folderPath.startsWith(SENT)) { exchangeFolderPath = mailPath + sentitemsName + folderPath.substring(SENT.length()); } else if (folderPath.startsWith(CONTACTS)) { exchangeFolderPath = mailPath + contactsName + folderPath.substring(CONTACTS.length()); } else if (folderPath.startsWith(CALENDAR)) { exchangeFolderPath = mailPath + calendarName + folderPath.substring(CALENDAR.length()); } else if (folderPath.startsWith("public")) { exchangeFolderPath = publicFolderUrl + folderPath.substring("public".length()); // caldav path } else if (folderPath.startsWith(USERS)) { // get requested principal String principal; String localPath; int principalIndex = folderPath.indexOf('/', USERS.length()); if (principalIndex >= 0) { principal = folderPath.substring(USERS.length(), principalIndex); localPath = folderPath.substring(USERS.length() + principal.length() + 1); if (localPath.startsWith(LOWER_CASE_INBOX)) { localPath = inboxName + localPath.substring(LOWER_CASE_INBOX.length()); } else if (localPath.startsWith(CALENDAR)) { localPath = calendarName + localPath.substring(CALENDAR.length()); } else if (localPath.startsWith(CONTACTS)) { localPath = contactsName + localPath.substring(CONTACTS.length()); } else if (localPath.startsWith(ADDRESSBOOK)) { localPath = contactsName + localPath.substring(ADDRESSBOOK.length()); } } else { principal = folderPath.substring(USERS.length()); localPath = ""; } if (principal.length() == 0) { exchangeFolderPath = rootPath; } else if (alias.equalsIgnoreCase(principal) || email.equalsIgnoreCase(principal)) { exchangeFolderPath = mailPath + localPath; } else { LOGGER.debug("Detected shared path for principal " + principal + ", user principal is " + email); exchangeFolderPath = rootPath + principal + '/' + localPath; } // absolute folder path } else if (folderPath.startsWith("/")) { exchangeFolderPath = folderPath; } else { exchangeFolderPath = mailPath + folderPath; } return exchangeFolderPath; } /** * Test if folderPath is inside user mailbox. * * @param folderPath absolute folder path * @return true if folderPath is a public or shared folder */ @Override public boolean isSharedFolder(String folderPath) { return !getFolderPath(folderPath).toLowerCase().startsWith(mailPath.toLowerCase()); } /** * @inheritDoc */ public DavExchangeSession(String url, String userName, String password) throws IOException { super(url, userName, password); } @Override protected void buildSessionInfo(HttpMethod method) throws DavMailException { buildMailPath(method); // get base http mailbox http urls getWellKnownFolders(); } static final String BASE_HREF = "<base href=\""; protected void buildMailPath(HttpMethod method) throws DavMailAuthenticationException { // find base url String line; // get user mail URL from html body (multi frame) BufferedReader mainPageReader = null; try { mainPageReader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); //noinspection StatementWithEmptyBody while ((line = mainPageReader.readLine()) != null && line.toLowerCase().indexOf(BASE_HREF) == -1) { } if (line != null) { int start = line.toLowerCase().indexOf(BASE_HREF) + BASE_HREF.length(); int end = line.indexOf('\"', start); String mailBoxBaseHref = line.substring(start, end); URL baseURL = new URL(mailBoxBaseHref); mailPath = baseURL.getPath(); LOGGER.debug("Base href found in body, mailPath is " + mailPath); buildEmail(method.getURI().getHost()); LOGGER.debug("Current user email is " + email); } else { // failover for Exchange 2007 : build standard mailbox link with email buildEmail(method.getURI().getHost()); mailPath = "/exchange/" + email + '/'; LOGGER.debug("Current user email is " + email + ", mailPath is " + mailPath); } rootPath = mailPath.substring(0, mailPath.lastIndexOf('/', mailPath.length() - 2) + 1); } catch (IOException e) { LOGGER.error("Error parsing main page at " + method.getPath(), e); } finally { if (mainPageReader != null) { try { mainPageReader.close(); } catch (IOException e) { LOGGER.error("Error parsing main page at " + method.getPath()); } } method.releaseConnection(); } if (mailPath == null || email == null) { throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED_PASSWORD_EXPIRED"); } } protected String getURIPropertyIfExists(DavPropertySet properties, String alias) throws URIException { DavProperty property = properties.get(Field.getPropertyName(alias)); if (property == null) { return null; } else { return URIUtil.decode((String) property.getValue()); } } // return last folder name from url protected String getFolderName(String url) { if (url != null) { if (url.endsWith("/")) { return url.substring(url.lastIndexOf('/', url.length() - 2) + 1); } else if (url.indexOf('/') > 0) { return url.substring(url.lastIndexOf('/') + 1); } else { return null; } } else { return null; } } protected void getWellKnownFolders() throws DavMailException { // Retrieve well known URLs MultiStatusResponse[] responses; try { responses = DavGatewayHttpClientFacade.executePropFindMethod( httpClient, URIUtil.encodePath(mailPath), 0, WELL_KNOWN_FOLDERS); if (responses.length == 0) { throw new DavMailException("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER", mailPath); } DavPropertySet properties = responses[0].getProperties(HttpStatus.SC_OK); inboxUrl = getURIPropertyIfExists(properties, "inbox"); inboxName = getFolderName(inboxUrl); deleteditemsUrl = getURIPropertyIfExists(properties, "deleteditems"); deleteditemsName = getFolderName(deleteditemsUrl); sentitemsUrl = getURIPropertyIfExists(properties, "sentitems"); sentitemsName = getFolderName(sentitemsUrl); sendmsgUrl = getURIPropertyIfExists(properties, "sendmsg"); draftsUrl = getURIPropertyIfExists(properties, "drafts"); draftsName = getFolderName(draftsUrl); calendarUrl = getURIPropertyIfExists(properties, "calendar"); calendarName = getFolderName(calendarUrl); contactsUrl = getURIPropertyIfExists(properties, "contacts"); contactsName = getFolderName(contactsUrl); outboxUrl = getURIPropertyIfExists(properties, "outbox"); outboxName = getFolderName(outboxUrl); // junk folder not available over webdav // default public folder path publicFolderUrl = PUBLIC_ROOT; // check public folder access try { if (inboxUrl != null) { // try to build full public URI from inboxUrl URI publicUri = new URI(inboxUrl, false); publicUri.setPath(PUBLIC_ROOT); publicFolderUrl = publicUri.getURI(); } DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet(); davPropertyNameSet.add(Field.getPropertyName("displayname")); PropFindMethod propFindMethod = new PropFindMethod(publicFolderUrl, davPropertyNameSet, 0); try { DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod); } catch (IOException e) { // workaround for NTLM authentication only on /public if (!DavGatewayHttpClientFacade.hasNTLM(httpClient)) { DavGatewayHttpClientFacade.addNTLM(httpClient); DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod); } } // update public folder URI publicFolderUrl = propFindMethod.getURI().getURI(); } catch (IOException e) { LOGGER.warn("Public folders not available: " + (e.getMessage() == null ? e : e.getMessage())); publicFolderUrl = "/public"; } LOGGER.debug("Inbox URL: " + inboxUrl + " Trash URL: " + deleteditemsUrl + " Sent URL: " + sentitemsUrl + " Send URL: " + sendmsgUrl + " Drafts URL: " + draftsUrl + " Calendar URL: " + calendarUrl + " Contacts URL: " + contactsUrl + " Outbox URL: " + outboxUrl + " Public folder URL: " + publicFolderUrl ); } catch (IOException e) { LOGGER.error(e.getMessage()); throw new DavMailAuthenticationException("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER", mailPath); } } /** * @inheritDoc */ @Override public boolean isExpired() throws NoRouteToHostException, UnknownHostException { boolean isExpired = false; try { getFolder(""); } catch (UnknownHostException exc) { throw exc; } catch (NoRouteToHostException exc) { throw exc; } catch (IOException e) { isExpired = true; } return isExpired; } protected static class MultiCondition extends ExchangeSession.MultiCondition { protected MultiCondition(Operator operator, Condition... condition) { super(operator, condition); } public void appendTo(StringBuilder buffer) { boolean first = true; for (Condition condition : conditions) { if (condition != null && !condition.isEmpty()) { if (first) { buffer.append('('); first = false; } else { buffer.append(' ').append(operator).append(' '); } condition.appendTo(buffer); } } // at least one non empty condition if (!first) { buffer.append(')'); } } } protected static class NotCondition extends ExchangeSession.NotCondition { protected NotCondition(Condition condition) { super(condition); } public void appendTo(StringBuilder buffer) { buffer.append("(Not "); condition.appendTo(buffer); buffer.append(')'); } } static final Map<Operator, String> operatorMap = new HashMap<Operator, String>(); static { operatorMap.put(Operator.IsEqualTo, " = "); operatorMap.put(Operator.IsGreaterThanOrEqualTo, " >= "); operatorMap.put(Operator.IsGreaterThan, " > "); operatorMap.put(Operator.IsLowerThanOrEqualTo, " <= "); operatorMap.put(Operator.IsLessThan, " < "); operatorMap.put(Operator.Like, " like "); operatorMap.put(Operator.IsNull, " is null"); operatorMap.put(Operator.IsFalse, " = false"); operatorMap.put(Operator.IsTrue, " = true"); operatorMap.put(Operator.StartsWith, " = "); operatorMap.put(Operator.Contains, " = "); } protected static class AttributeCondition extends ExchangeSession.AttributeCondition { protected boolean isIntValue; protected AttributeCondition(String attributeName, Operator operator, String value) { super(attributeName, operator, value); } protected AttributeCondition(String attributeName, Operator operator, int value) { super(attributeName, operator, String.valueOf(value)); isIntValue = true; } public void appendTo(StringBuilder buffer) { Field field = Field.get(attributeName); buffer.append('"').append(field.getUri()).append('"'); buffer.append(operatorMap.get(operator)); //noinspection VariableNotUsedInsideIf if (field.cast != null) { buffer.append("CAST (\""); } else if (!isIntValue && !field.isIntValue()) { buffer.append('\''); } if (Operator.Like == operator) { buffer.append('%'); } buffer.append(value); if (Operator.Like == operator || Operator.StartsWith == operator) { buffer.append('%'); } if (field.cast != null) { buffer.append("\" as '").append(field.cast).append("')"); } else if (!isIntValue && !field.isIntValue()) { buffer.append('\''); } } } protected static class HeaderCondition extends AttributeCondition { protected HeaderCondition(String attributeName, Operator operator, String value) { super(attributeName, operator, value); } @Override public void appendTo(StringBuilder buffer) { buffer.append('"').append(Field.getHeader(attributeName).getUri()).append('"'); buffer.append(operatorMap.get(operator)); buffer.append('\''); if (Operator.Like == operator) { buffer.append('%'); } buffer.append(value); if (Operator.Like == operator) { buffer.append('%'); } buffer.append('\''); } } protected static class MonoCondition extends ExchangeSession.MonoCondition { protected MonoCondition(String attributeName, Operator operator) { super(attributeName, operator); } public void appendTo(StringBuilder buffer) { buffer.append('"').append(Field.get(attributeName).getUri()).append('"'); buffer.append(operatorMap.get(operator)); } } @Override public ExchangeSession.MultiCondition and(Condition... condition) { return new MultiCondition(Operator.And, condition); } @Override public ExchangeSession.MultiCondition or(Condition... condition) { return new MultiCondition(Operator.Or, condition); } @Override public Condition not(Condition condition) { if (condition == null) { return null; } else { return new NotCondition(condition); } } @Override public Condition equals(String attributeName, String value) { return new AttributeCondition(attributeName, Operator.IsEqualTo, value); } @Override public Condition equals(String attributeName, int value) { return new AttributeCondition(attributeName, Operator.IsEqualTo, value); } @Override public Condition headerEquals(String headerName, String value) { return new HeaderCondition(headerName, Operator.IsEqualTo, value); } @Override public Condition gte(String attributeName, String value) { return new AttributeCondition(attributeName, Operator.IsGreaterThanOrEqualTo, value); } @Override public Condition lte(String attributeName, String value) { return new AttributeCondition(attributeName, Operator.IsLowerThanOrEqualTo, value); } @Override public Condition lt(String attributeName, String value) { return new AttributeCondition(attributeName, Operator.IsLessThan, value); } @Override public Condition gt(String attributeName, String value) { return new AttributeCondition(attributeName, Operator.IsGreaterThan, value); } @Override public Condition contains(String attributeName, String value) { return new AttributeCondition(attributeName, Operator.Like, value); } @Override public Condition startsWith(String attributeName, String value) { return new AttributeCondition(attributeName, Operator.StartsWith, value); } @Override public Condition isNull(String attributeName) { return new MonoCondition(attributeName, Operator.IsNull); } @Override public Condition isTrue(String attributeName) { return new MonoCondition(attributeName, Operator.IsTrue); } @Override public Condition isFalse(String attributeName) { return new MonoCondition(attributeName, Operator.IsFalse); } /** * @inheritDoc */ public class Contact extends ExchangeSession.Contact { /** * Build Contact instance from multistatusResponse info * * @param multiStatusResponse response * @throws URIException on error * @throws DavMailException on error */ public Contact(MultiStatusResponse multiStatusResponse) throws URIException, DavMailException { setHref(URIUtil.decode(multiStatusResponse.getHref())); DavPropertySet properties = multiStatusResponse.getProperties(HttpStatus.SC_OK); permanentUrl = getPropertyIfExists(properties, "permanenturl"); etag = getPropertyIfExists(properties, "etag"); displayName = getPropertyIfExists(properties, "displayname"); for (String attributeName : CONTACT_ATTRIBUTES) { String value = getPropertyIfExists(properties, attributeName); if (value != null) { if ("bday".equals(attributeName) || "anniversary".equals(attributeName) || "lastmodified".equals(attributeName) || "datereceived".equals(attributeName)) { value = convertDateFromExchange(value); } else if ("haspicture".equals(attributeName) || "private".equals(attributeName)) { value = "1".equals(value) ? "true" : "false"; } put(attributeName, value); } } } /** * @inheritDoc */ public Contact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) { super(folderPath, itemName, properties, etag, noneMatch); } protected List<DavConstants> buildProperties() { ArrayList<DavConstants> list = new ArrayList<DavConstants>(); for (Map.Entry<String, String> entry : entrySet()) { String key = entry.getKey(); if (!"photo".equals(key)) { list.add(Field.createDavProperty(key, entry.getValue())); } } return list; } /** * Create or update contact * * @return action result * @throws IOException on error */ public ItemResult createOrUpdate() throws IOException { int status = 0; PropPatchMethod propPatchMethod = new PropPatchMethod(URIUtil.encodePath(getHref()), buildProperties()) { @Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { // ignore response body, sometimes invalid with exchange mapi properties } }; propPatchMethod.setRequestHeader("Translate", "f"); if (etag != null) { propPatchMethod.setRequestHeader("If-Match", etag); } if (noneMatch != null) { propPatchMethod.setRequestHeader("If-None-Match", noneMatch); } try { status = httpClient.executeMethod(propPatchMethod); if (status == HttpStatus.SC_MULTI_STATUS) { //noinspection VariableNotUsedInsideIf if (etag == null) { status = HttpStatus.SC_CREATED; LOGGER.debug("Created contact " + getHref()); } else { status = HttpStatus.SC_OK; LOGGER.debug("Updated contact " + getHref()); } } else { LOGGER.warn("Unable to create or update contact " + status + ' ' + propPatchMethod.getStatusLine()); } } finally { propPatchMethod.releaseConnection(); } ItemResult itemResult = new ItemResult(); // 440 means forbidden on Exchange if (status == 440) { status = HttpStatus.SC_FORBIDDEN; } itemResult.status = status; String contactPictureUrl = URIUtil.encodePath(getHref() + "/ContactPicture.jpg"); String photo = get("photo"); if (photo != null) { // need to update photo byte[] resizedImageBytes = IOUtil.resizeImage(Base64.decodeBase64(photo.getBytes()), 90); final PutMethod putmethod = new PutMethod(contactPictureUrl); putmethod.setRequestHeader("Overwrite", "t"); putmethod.setRequestHeader("Content-Type", "image/jpeg"); putmethod.setRequestEntity(new ByteArrayRequestEntity(resizedImageBytes, "image/jpeg")); try { status = httpClient.executeMethod(putmethod); if (status != HttpStatus.SC_OK && status != HttpStatus.SC_CREATED) { - throw new IOException("Unable to update contact picture"); + throw new IOException("Unable to update contact picture: "+status+ ' ' +putmethod.getStatusLine()); } } catch (IOException e) { LOGGER.error("Error in contact photo create or update", e); throw e; } finally { putmethod.releaseConnection(); } ArrayList<DavConstants> changeList = new ArrayList<DavConstants>(); changeList.add(Field.createDavProperty("attachmentContactPhoto", "true")); changeList.add(Field.createDavProperty("renderingPosition", "-1")); final PropPatchMethod attachmentPropPatchMethod = new PropPatchMethod(contactPictureUrl, changeList); try { status = httpClient.executeMethod(attachmentPropPatchMethod); if (status != HttpStatus.SC_MULTI_STATUS) { throw new IOException("Unable to update contact picture"); } } catch (IOException e) { LOGGER.error("Error in contact photo create or update", e); throw e; } finally { attachmentPropPatchMethod.releaseConnection(); } } else { // try to delete picture DeleteMethod deleteMethod = new DeleteMethod(contactPictureUrl); try { status = httpClient.executeMethod(deleteMethod); if (status != HttpStatus.SC_OK && status != HttpStatus.SC_NOT_FOUND) { throw new IOException("Unable to delete contact picture"); } } catch (IOException e) { LOGGER.error("Error in contact photo delete", e); throw e; } finally { deleteMethod.releaseConnection(); } } // need to retrieve new etag HeadMethod headMethod = new HeadMethod(URIUtil.encodePath(getHref())); try { httpClient.executeMethod(headMethod); if (headMethod.getResponseHeader("ETag") != null) { itemResult.etag = headMethod.getResponseHeader("ETag").getValue(); } } finally { headMethod.releaseConnection(); } return itemResult; } } /** * @inheritDoc */ public class Event extends ExchangeSession.Event { /** * Build Event instance from response info. * * @param multiStatusResponse response * @throws URIException on error */ public Event(MultiStatusResponse multiStatusResponse) throws URIException { setHref(URIUtil.decode(multiStatusResponse.getHref())); DavPropertySet properties = multiStatusResponse.getProperties(HttpStatus.SC_OK); permanentUrl = getPropertyIfExists(properties, "permanenturl"); etag = getPropertyIfExists(properties, "etag"); displayName = getPropertyIfExists(properties, "displayname"); } /** * @inheritDoc */ public Event(String folderPath, String itemName, String contentClass, String itemBody, String etag, String noneMatch) { super(folderPath, itemName, contentClass, itemBody, etag, noneMatch); } protected String getICSFromInternetContentProperty() throws IOException, DavException, MessagingException { String result = null; // PropFind PR_INTERNET_CONTENT DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet(); davPropertyNameSet.add(Field.getPropertyName("internetContent")); PropFindMethod propFindMethod = new PropFindMethod(URIUtil.encodePath(permanentUrl), davPropertyNameSet, 0); try { DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propFindMethod); MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus(); if (responses.getResponses().length > 0) { DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK); String propertyValue = getPropertyIfExists(properties, "internetContent"); if (propertyValue != null) { byte[] byteArray = Base64.decodeBase64(propertyValue.getBytes()); result = getICS(new ByteArrayInputStream(byteArray)); } } } finally { propFindMethod.releaseConnection(); } return result; } /** * Load ICS content from Exchange server. * User Translate: f header to get MIME event content and get ICS attachment from it * * @return ICS (iCalendar) event * @throws HttpException on error */ @Override public String getBody() throws HttpException { String result; LOGGER.debug("Get event: " + permanentUrl); // try to get PR_INTERNET_CONTENT try { result = getICSFromInternetContentProperty(); if (result == null) { GetMethod method = new GetMethod(permanentUrl); method.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); method.setRequestHeader("Translate", "f"); try { DavGatewayHttpClientFacade.executeGetMethod(httpClient, method, true); result = getICS(method.getResponseBodyAsStream()); } finally { method.releaseConnection(); } } } catch (DavException e) { throw buildHttpException(e); } catch (IOException e) { throw buildHttpException(e); } catch (MessagingException e) { throw buildHttpException(e); } return result; } /** * @inheritDoc */ @Override protected ItemResult createOrUpdate(byte[] mimeContent) throws IOException { PutMethod putmethod = new PutMethod(URIUtil.encodePath(getHref())); putmethod.setRequestHeader("Translate", "f"); putmethod.setRequestHeader("Overwrite", "f"); if (etag != null) { putmethod.setRequestHeader("If-Match", etag); } if (noneMatch != null) { putmethod.setRequestHeader("If-None-Match", noneMatch); } putmethod.setRequestHeader("Content-Type", "message/rfc822"); putmethod.setRequestEntity(new ByteArrayRequestEntity(mimeContent, "message/rfc822")); int status; try { status = httpClient.executeMethod(putmethod); if (status == HttpURLConnection.HTTP_OK) { //noinspection VariableNotUsedInsideIf if (etag != null) { LOGGER.debug("Updated event " + getHref()); } else { LOGGER.warn("Overwritten event " + getHref()); } } else if (status != HttpURLConnection.HTTP_CREATED) { LOGGER.warn("Unable to create or update message " + status + ' ' + putmethod.getStatusLine()); } } finally { putmethod.releaseConnection(); } ItemResult itemResult = new ItemResult(); // 440 means forbidden on Exchange if (status == 440) { status = HttpStatus.SC_FORBIDDEN; } itemResult.status = status; if (putmethod.getResponseHeader("GetETag") != null) { itemResult.etag = putmethod.getResponseHeader("GetETag").getValue(); } // trigger activeSync push event, only if davmail.forceActiveSyncUpdate setting is true if ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) && (Settings.getBooleanProperty("davmail.forceActiveSyncUpdate"))) { ArrayList<DavConstants> propertyList = new ArrayList<DavConstants>(); // Set contentclass to make ActiveSync happy propertyList.add(Field.createDavProperty("contentclass", contentClass)); // ... but also set PR_INTERNET_CONTENT to preserve custom properties propertyList.add(Field.createDavProperty("internetContent", new String(Base64.encodeBase64(mimeContent)))); PropPatchMethod propPatchMethod = new PropPatchMethod(URIUtil.encodePath(getHref()), propertyList); int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod); if (patchStatus != HttpStatus.SC_MULTI_STATUS) { LOGGER.warn("Unable to patch event to trigger activeSync push"); } else { // need to retrieve new etag Item newItem = getItem(getHref()); itemResult.etag = newItem.etag; } } return itemResult; } } protected Folder buildFolder(MultiStatusResponse entity) throws IOException { String href = URIUtil.decode(entity.getHref()); Folder folder = new Folder(); DavPropertySet properties = entity.getProperties(HttpStatus.SC_OK); folder.displayName = getPropertyIfExists(properties, "displayname"); folder.folderClass = getPropertyIfExists(properties, "folderclass"); folder.hasChildren = "1".equals(getPropertyIfExists(properties, "hassubs")); folder.noInferiors = "1".equals(getPropertyIfExists(properties, "nosubs")); folder.unreadCount = getIntPropertyIfExists(properties, "unreadcount"); folder.ctag = getPropertyIfExists(properties, "contenttag"); folder.etag = getPropertyIfExists(properties, "lastmodified"); folder.uidNext = getIntPropertyIfExists(properties, "uidNext"); // replace well known folder names if (href.startsWith(inboxUrl)) { folder.folderPath = href.replaceFirst(inboxUrl, INBOX); } else if (href.startsWith(sentitemsUrl)) { folder.folderPath = href.replaceFirst(sentitemsUrl, SENT); } else if (href.startsWith(draftsUrl)) { folder.folderPath = href.replaceFirst(draftsUrl, DRAFTS); } else if (href.startsWith(deleteditemsUrl)) { folder.folderPath = href.replaceFirst(deleteditemsUrl, TRASH); } else if (href.startsWith(calendarUrl)) { folder.folderPath = href.replaceFirst(calendarUrl, CALENDAR); } else if (href.startsWith(contactsUrl)) { folder.folderPath = href.replaceFirst(contactsUrl, CONTACTS); } else { int index = href.indexOf(mailPath.substring(0, mailPath.length() - 1)); if (index >= 0) { if (index + mailPath.length() > href.length()) { folder.folderPath = ""; } else { folder.folderPath = href.substring(index + mailPath.length()); } } else { try { URI folderURI = new URI(href, false); folder.folderPath = folderURI.getPath(); } catch (URIException e) { throw new DavMailException("EXCEPTION_INVALID_FOLDER_URL", href); } } } if (folder.folderPath.endsWith("/")) { folder.folderPath = folder.folderPath.substring(0, folder.folderPath.length() - 1); } return folder; } protected static final Set<String> FOLDER_PROPERTIES = new HashSet<String>(); static { FOLDER_PROPERTIES.add("displayname"); FOLDER_PROPERTIES.add("folderclass"); FOLDER_PROPERTIES.add("hassubs"); FOLDER_PROPERTIES.add("nosubs"); FOLDER_PROPERTIES.add("unreadcount"); FOLDER_PROPERTIES.add("contenttag"); FOLDER_PROPERTIES.add("lastmodified"); FOLDER_PROPERTIES.add("uidNext"); } protected static final DavPropertyNameSet FOLDER_PROPERTIES_NAME_SET = new DavPropertyNameSet(); static { for (String attribute : FOLDER_PROPERTIES) { FOLDER_PROPERTIES_NAME_SET.add(Field.getPropertyName(attribute)); } } /** * @inheritDoc */ @Override public Folder getFolder(String folderPath) throws IOException { MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod( httpClient, URIUtil.encodePath(getFolderPath(folderPath)), 0, FOLDER_PROPERTIES_NAME_SET); Folder folder = null; if (responses.length > 0) { folder = buildFolder(responses[0]); folder.folderPath = folderPath; } return folder; } /** * @inheritDoc */ @Override public List<Folder> getSubFolders(String folderPath, Condition condition, boolean recursive) throws IOException { boolean isPublic = folderPath.startsWith("/public"); FolderQueryTraversal mode = (!isPublic && recursive) ? FolderQueryTraversal.Deep : FolderQueryTraversal.Shallow; List<Folder> folders = new ArrayList<Folder>(); MultiStatusResponse[] responses = searchItems(folderPath, FOLDER_PROPERTIES, and(isTrue("isfolder"), isFalse("ishidden"), condition), mode); for (MultiStatusResponse response : responses) { Folder folder = buildFolder(response); folders.add(buildFolder(response)); if (isPublic && recursive) { getSubFolders(folder.folderPath, condition, recursive); } } return folders; } /** * @inheritDoc */ @Override public void createFolder(String folderPath, String folderClass) throws IOException { ArrayList<DavConstants> list = new ArrayList<DavConstants>(); list.add(Field.createDavProperty("folderclass", folderClass)); // standard MkColMethod does not take properties, override PropPatchMethod instead PropPatchMethod method = new PropPatchMethod(URIUtil.encodePath(getFolderPath(folderPath)), list) { @Override public String getName() { return "MKCOL"; } }; int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method); // ok or already exists if (status != HttpStatus.SC_MULTI_STATUS && status != HttpStatus.SC_METHOD_NOT_ALLOWED) { throw DavGatewayHttpClientFacade.buildHttpException(method); } } /** * @inheritDoc */ @Override public void deleteFolder(String folderPath) throws IOException { DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, URIUtil.encodePath(getFolderPath(folderPath))); } /** * @inheritDoc */ @Override public void moveFolder(String folderPath, String targetPath) throws IOException { MoveMethod method = new MoveMethod(URIUtil.encodePath(getFolderPath(folderPath)), URIUtil.encodePath(getFolderPath(targetPath)), false); try { int statusCode = httpClient.executeMethod(method); if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) { throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_FOLDER"); } else if (statusCode != HttpStatus.SC_CREATED) { throw DavGatewayHttpClientFacade.buildHttpException(method); } } finally { method.releaseConnection(); } } protected String getPropertyIfExists(DavPropertySet properties, String alias) { DavProperty property = properties.get(Field.getResponsePropertyName(alias)); if (property == null) { return null; } else { Object value = property.getValue(); if (value instanceof Node) { return ((Node) value).getTextContent(); } else if (value instanceof List) { StringBuilder buffer = new StringBuilder(); for (Object node : (List) value) { if (buffer.length() > 0) { buffer.append(','); } buffer.append(((Node) node).getTextContent()); } return buffer.toString(); } else { return (String) value; } } } protected int getIntPropertyIfExists(DavPropertySet properties, String alias) { DavProperty property = properties.get(Field.getPropertyName(alias)); if (property == null) { return 0; } else { return Integer.parseInt((String) property.getValue()); } } protected long getLongPropertyIfExists(DavPropertySet properties, String alias) { DavProperty property = properties.get(Field.getPropertyName(alias)); if (property == null) { return 0; } else { return Long.parseLong((String) property.getValue()); } } protected byte[] getBinaryPropertyIfExists(DavPropertySet properties, String alias) { byte[] property = null; String base64Property = getPropertyIfExists(properties, alias); if (base64Property != null) { try { property = Base64.decodeBase64(base64Property.getBytes("ASCII")); } catch (UnsupportedEncodingException e) { LOGGER.warn(e); } } return property; } protected Message buildMessage(MultiStatusResponse responseEntity) throws URIException, DavMailException { Message message = new Message(); message.messageUrl = URIUtil.decode(responseEntity.getHref()); DavPropertySet properties = responseEntity.getProperties(HttpStatus.SC_OK); message.permanentUrl = getPropertyIfExists(properties, "permanenturl"); message.size = getIntPropertyIfExists(properties, "messageSize"); message.uid = getPropertyIfExists(properties, "uid"); message.imapUid = getLongPropertyIfExists(properties, "imapUid"); message.read = "1".equals(getPropertyIfExists(properties, "read")); message.junk = "1".equals(getPropertyIfExists(properties, "junk")); message.flagged = "2".equals(getPropertyIfExists(properties, "flagStatus")); message.draft = (getIntPropertyIfExists(properties, "messageFlags") & 8) != 0; String lastVerbExecuted = getPropertyIfExists(properties, "lastVerbExecuted"); message.answered = "102".equals(lastVerbExecuted) || "103".equals(lastVerbExecuted); message.forwarded = "104".equals(lastVerbExecuted); message.date = convertDateFromExchange(getPropertyIfExists(properties, "date")); message.deleted = "1".equals(getPropertyIfExists(properties, "deleted")); if (LOGGER.isDebugEnabled()) { StringBuilder buffer = new StringBuilder(); buffer.append("Message"); if (message.imapUid != 0) { buffer.append(" IMAP uid: ").append(message.imapUid); } if (message.uid != null) { buffer.append(" uid: ").append(message.uid); } buffer.append(" href: ").append(responseEntity.getHref()).append(" permanenturl:").append(message.permanentUrl); LOGGER.debug(buffer.toString()); } return message; } @Override public MessageList searchMessages(String folderPath, Set<String> attributes, Condition condition) throws IOException { MessageList messages = new MessageList(); MultiStatusResponse[] responses = searchItems(folderPath, attributes, and(isFalse("isfolder"), isFalse("ishidden"), condition), FolderQueryTraversal.Shallow); for (MultiStatusResponse response : responses) { Message message = buildMessage(response); message.messageList = messages; messages.add(message); } Collections.sort(messages); return messages; } /** * @inheritDoc */ @Override public List<ExchangeSession.Contact> searchContacts(String folderPath, Set<String> attributes, Condition condition) throws IOException { List<ExchangeSession.Contact> contacts = new ArrayList<ExchangeSession.Contact>(); MultiStatusResponse[] responses = searchItems(folderPath, attributes, and(equals("outlookmessageclass", "IPM.Contact"), isFalse("isfolder"), isFalse("ishidden"), condition), FolderQueryTraversal.Shallow); for (MultiStatusResponse response : responses) { contacts.add(new Contact(response)); } return contacts; } @Override public List<ExchangeSession.Event> searchEvents(String folderPath, Set<String> attributes, Condition condition) throws IOException { List<ExchangeSession.Event> events = new ArrayList<ExchangeSession.Event>(); MultiStatusResponse[] responses = searchItems(folderPath, attributes, and(isFalse("isfolder"), isFalse("ishidden"), condition), FolderQueryTraversal.Shallow); for (MultiStatusResponse response : responses) { String instancetype = getPropertyIfExists(response.getProperties(HttpStatus.SC_OK), "instancetype"); Event event = new Event(response); //noinspection VariableNotUsedInsideIf if (instancetype == null) { // check ics content try { event.getBody(); // getBody success => add event or task events.add(event); } catch (HttpException e) { // invalid event: exclude from list LOGGER.warn("Invalid event " + event.displayName + " found at " + response.getHref(), e); } } else { events.add(event); } } return events; } protected MultiStatusResponse[] searchItems(String folderPath, Set<String> attributes, Condition condition, FolderQueryTraversal folderQueryTraversal) throws IOException { String folderUrl = getFolderPath(folderPath); StringBuilder searchRequest = new StringBuilder(); searchRequest.append("SELECT ") .append(Field.getRequestPropertyString("permanenturl")); if (attributes != null) { for (String attribute : attributes) { searchRequest.append(',').append(Field.getRequestPropertyString(attribute)); } } searchRequest.append(" FROM SCOPE('").append(folderQueryTraversal).append(" TRAVERSAL OF \"").append(folderUrl).append("\"')"); if (condition != null) { searchRequest.append(" WHERE "); condition.appendTo(searchRequest); } DavGatewayTray.debug(new BundleMessage("LOG_SEARCH_QUERY", searchRequest)); return DavGatewayHttpClientFacade.executeSearchMethod( httpClient, URIUtil.encodePath(folderUrl), searchRequest.toString()); } protected static final DavPropertyNameSet EVENT_REQUEST_PROPERTIES = new DavPropertyNameSet(); static { EVENT_REQUEST_PROPERTIES.add(Field.getPropertyName("permanenturl")); EVENT_REQUEST_PROPERTIES.add(Field.getPropertyName("urlcompname")); EVENT_REQUEST_PROPERTIES.add(Field.getPropertyName("etag")); EVENT_REQUEST_PROPERTIES.add(Field.getPropertyName("contentclass")); EVENT_REQUEST_PROPERTIES.add(Field.getPropertyName("displayname")); } @Override public Item getItem(String folderPath, String itemName) throws IOException { String itemPath = getFolderPath(folderPath) + '/' + convertItemNameToEML(itemName); Item item; try { item = getItem(itemPath); } catch (HttpNotFoundException hnfe) { // failover for Exchange 2007 plus encoding issue String decodedEventName = convertItemNameToEML(itemName).replaceAll("_xF8FF_", "/").replaceAll("_x003F_", "?").replaceAll("'", "''"); LOGGER.debug("Item not found at " + itemPath + ", search by displayname: '" + decodedEventName + '\''); ExchangeSession.MessageList messages = searchMessages(folderPath, equals("displayname", decodedEventName)); if (!messages.isEmpty()) { item = getItem(messages.get(0).getPermanentUrl()); } else { throw hnfe; } } return item; } @Override public ExchangeSession.ContactPhoto getContactPhoto(ExchangeSession.Contact contact) throws IOException { ContactPhoto contactPhoto = null; if ("true".equals(contact.get("haspicture"))) { final GetMethod method = new GetMethod(URIUtil.encodePath(contact.getHref()) + "/ContactPicture.jpg"); method.setRequestHeader("Translate", "f"); method.setRequestHeader("Accept-Encoding", "gzip"); InputStream inputStream = null; try { DavGatewayHttpClientFacade.executeGetMethod(httpClient, method, true); if (isGzipEncoded(method)) { inputStream = (new GZIPInputStream(method.getResponseBodyAsStream())); } else { inputStream = method.getResponseBodyAsStream(); } contactPhoto = new ContactPhoto(); contactPhoto.contentType = "image/jpeg"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream partInputStream = inputStream; byte[] bytes = new byte[8192]; int length; while ((length = partInputStream.read(bytes)) > 0) { baos.write(bytes, 0, length); } contactPhoto.content = new String(Base64.encodeBase64(baos.toByteArray())); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LOGGER.debug(e); } } method.releaseConnection(); } } return contactPhoto; } @Override public int sendEvent(String icsBody) throws IOException { String itemName = UUID.randomUUID().toString() + ".EML"; int status = internalCreateOrUpdateEvent(draftsUrl, itemName, "urn:content-classes:calendarmessage", icsBody, null, null).status; if (status != HttpStatus.SC_CREATED) { return status; } else { MoveMethod method = new MoveMethod(URIUtil.encodePath(draftsUrl + '/' + itemName), URIUtil.encodePath(sendmsgUrl), true); status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method); if (status != HttpStatus.SC_OK) { throw DavGatewayHttpClientFacade.buildHttpException(method); } return status; } } @Override public void deleteItem(String folderPath, String itemName) throws IOException { String eventPath = URIUtil.encodePath(getFolderPath(folderPath) + '/' + convertItemNameToEML(itemName)); DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, eventPath); } @Override public void processItem(String folderPath, String itemName) throws IOException { String eventPath = URIUtil.encodePath(getFolderPath(folderPath) + '/' + convertItemNameToEML(itemName)); // do not delete calendar messages, mark read and processed ArrayList<DavConstants> list = new ArrayList<DavConstants>(); list.add(Field.createDavProperty("processed", "true")); list.add(Field.createDavProperty("read", "1")); PropPatchMethod patchMethod = new PropPatchMethod(eventPath, list); DavGatewayHttpClientFacade.executeMethod(httpClient, patchMethod); } /** * Get item by url * * @param itemPath Event path * @return event object * @throws IOException on error */ public Item getItem(String itemPath) throws IOException { MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(httpClient, URIUtil.encodePath(itemPath), 0, EVENT_REQUEST_PROPERTIES); if (responses.length == 0) { throw new DavMailException("EXCEPTION_ITEM_NOT_FOUND"); } String contentClass = getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "contentclass"); String urlcompname = getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "urlcompname"); if ("urn:content-classes:person".equals(contentClass)) { // retrieve Contact properties List<ExchangeSession.Contact> contacts = searchContacts(itemPath.substring(0, itemPath.lastIndexOf('/')), CONTACT_ATTRIBUTES, equals("urlcompname", urlcompname)); if (contacts.isEmpty()) { throw new DavMailException("EXCEPTION_ITEM_NOT_FOUND"); } return contacts.get(0); } else if ("urn:content-classes:appointment".equals(contentClass) || "urn:content-classes:calendarmessage".equals(contentClass)) { return new Event(responses[0]); } else { throw new DavMailException("EXCEPTION_ITEM_NOT_FOUND"); } } @Override public ItemResult internalCreateOrUpdateEvent(String folderPath, String itemName, String contentClass, String icsBody, String etag, String noneMatch) throws IOException { return new Event(getFolderPath(folderPath), itemName, contentClass, icsBody, etag, noneMatch).createOrUpdate(); } /** * create a fake event to get VTIMEZONE body */ @Override protected void loadVtimezone() { try { VTimezone userTimezone = new VTimezone(); // create temporary folder String folderPath = getFolderPath("davmailtemp"); createCalendarFolder(folderPath); PostMethod postMethod = new PostMethod(URIUtil.encodePath(folderPath)); postMethod.addParameter("Cmd", "saveappt"); postMethod.addParameter("FORMTYPE", "appointment"); String fakeEventUrl = null; try { // create fake event int statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { fakeEventUrl = StringUtil.getToken(postMethod.getResponseBodyAsString(), "<span id=\"itemHREF\">", "</span>"); } } finally { postMethod.releaseConnection(); } // failover for Exchange 2007, use PROPPATCH with forced timezone if (fakeEventUrl == null) { ArrayList<DavConstants> propertyList = new ArrayList<DavConstants>(); propertyList.add(Field.createDavProperty("contentclass", "urn:content-classes:appointment")); propertyList.add(Field.createDavProperty("outlookmessageclass", "IPM.Appointment")); propertyList.add(Field.createDavProperty("instancetype", "0")); // get forced timezone id from settings userTimezone.timezoneId = Settings.getProperty("davmail.timezoneId"); if (userTimezone.timezoneId == null) { // get timezoneid from OWA settings userTimezone.timezoneId = getTimezoneIdFromExchange(); } // without a timezoneId, use Exchange timezone if (userTimezone.timezoneId != null) { propertyList.add(Field.createDavProperty("timezoneid", userTimezone.timezoneId)); } String patchMethodUrl = URIUtil.encodePath(folderPath) + '/' + UUID.randomUUID().toString() + ".EML"; PropPatchMethod patchMethod = new PropPatchMethod(URIUtil.encodePath(patchMethodUrl), propertyList); try { int statusCode = httpClient.executeMethod(patchMethod); if (statusCode == HttpStatus.SC_MULTI_STATUS) { fakeEventUrl = patchMethodUrl; } } finally { patchMethod.releaseConnection(); } } if (fakeEventUrl != null) { // get fake event body GetMethod getMethod = new GetMethod(URIUtil.encodePath(fakeEventUrl)); getMethod.setRequestHeader("Translate", "f"); try { httpClient.executeMethod(getMethod); userTimezone.timezoneBody = "BEGIN:VTIMEZONE" + StringUtil.getToken(getMethod.getResponseBodyAsString(), "BEGIN:VTIMEZONE", "END:VTIMEZONE") + "END:VTIMEZONE\r\n"; userTimezone.timezoneId = StringUtil.getToken(userTimezone.timezoneBody, "TZID:", "\r\n"); } finally { getMethod.releaseConnection(); } } // delete temporary folder deleteFolder("davmailtemp"); this.vTimezone = userTimezone; } catch (IOException e) { LOGGER.warn("Unable to get VTIMEZONE info: " + e, e); } } protected String getTimezoneIdFromExchange() { String timezoneId = null; try { Set<String> attributes = new HashSet<String>(); attributes.add("roamingdictionary"); MultiStatusResponse[] responses = searchItems("/users/" + getEmail() + "/NON_IPM_SUBTREE", attributes, equals("messageclass", "IPM.Configuration.OWA.UserOptions"), DavExchangeSession.FolderQueryTraversal.Deep); if (responses.length == 1) { byte[] roamingdictionary = getBinaryPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "roamingdictionary"); if (roamingdictionary != null) { String roamingdictionaryString = new String(roamingdictionary, "UTF-8"); int startIndex = roamingdictionaryString.lastIndexOf("18-"); if (startIndex >= 0) { int endIndex = roamingdictionaryString.indexOf('"', startIndex); if (endIndex >= 0) { String timezoneName = roamingdictionaryString.substring(startIndex + 3, endIndex); try { timezoneId = ResourceBundle.getBundle("timezoneids").getString(timezoneName); } catch (MissingResourceException mre) { LOGGER.warn("Invalid timezone name: " + timezoneName); } } } } } } catch (UnsupportedEncodingException e) { LOGGER.warn("Unable to retrieve Exchange timezone id: " + e.getMessage(), e); } catch (IOException e) { LOGGER.warn("Unable to retrieve Exchange timezone id: " + e.getMessage(), e); } return timezoneId; } @Override protected ItemResult internalCreateOrUpdateContact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) throws IOException { return new Contact(getFolderPath(folderPath), itemName, properties, etag, noneMatch).createOrUpdate(); } protected List<DavConstants> buildProperties(Map<String, String> properties) { ArrayList<DavConstants> list = new ArrayList<DavConstants>(); if (properties != null) { for (Map.Entry<String, String> entry : properties.entrySet()) { if ("read".equals(entry.getKey())) { list.add(Field.createDavProperty("read", entry.getValue())); } else if ("junk".equals(entry.getKey())) { list.add(Field.createDavProperty("junk", entry.getValue())); } else if ("flagged".equals(entry.getKey())) { list.add(Field.createDavProperty("flagStatus", entry.getValue())); } else if ("answered".equals(entry.getKey())) { list.add(Field.createDavProperty("lastVerbExecuted", entry.getValue())); if ("102".equals(entry.getValue())) { list.add(Field.createDavProperty("iconIndex", "261")); } } else if ("forwarded".equals(entry.getKey())) { list.add(Field.createDavProperty("lastVerbExecuted", entry.getValue())); if ("104".equals(entry.getValue())) { list.add(Field.createDavProperty("iconIndex", "262")); } } else if ("bcc".equals(entry.getKey())) { list.add(Field.createDavProperty("bcc", entry.getValue())); } else if ("deleted".equals(entry.getKey())) { list.add(Field.createDavProperty("deleted", entry.getValue())); } else if ("datereceived".equals(entry.getKey())) { list.add(Field.createDavProperty("datereceived", entry.getValue())); } } } return list; } /** * Create message in specified folder. * Will overwrite an existing message with same messageName in the same folder * * @param folderPath Exchange folder path * @param messageName message name * @param properties message properties (flags) * @param messageBody mail body * @throws IOException when unable to create message */ @Override public void createMessage(String folderPath, String messageName, HashMap<String, String> properties, byte[] messageBody) throws IOException { String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName); PropPatchMethod patchMethod; List<DavConstants> davProperties = buildProperties(properties); if (properties != null && properties.containsKey("draft")) { // note: draft is readonly after create, create the message first with requested messageFlags davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft"))); } if (!davProperties.isEmpty()) { patchMethod = new PropPatchMethod(messageUrl, davProperties); try { // update message with blind carbon copy and other flags int statusCode = httpClient.executeMethod(patchMethod); if (statusCode != HttpStatus.SC_MULTI_STATUS) { throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine()); } } finally { patchMethod.releaseConnection(); } } // update message body PutMethod putmethod = new PutMethod(messageUrl); putmethod.setRequestHeader("Translate", "f"); putmethod.setRequestHeader("Content-Type", "message/rfc822"); try { // use same encoding as client socket reader putmethod.setRequestEntity(new ByteArrayRequestEntity(messageBody)); int code = httpClient.executeMethod(putmethod); if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) { throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ', putmethod.getStatusLine()); } } finally { putmethod.releaseConnection(); } } /** * @inheritDoc */ @Override public void updateMessage(Message message, Map<String, String> properties) throws IOException { PropPatchMethod patchMethod = new PropPatchMethod(message.permanentUrl, buildProperties(properties)) { @Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { // ignore response body, sometimes invalid with exchange mapi properties } }; try { int statusCode = httpClient.executeMethod(patchMethod); if (statusCode != HttpStatus.SC_MULTI_STATUS) { throw new DavMailException("EXCEPTION_UNABLE_TO_UPDATE_MESSAGE"); } } finally { patchMethod.releaseConnection(); } } /** * @inheritDoc */ @Override public void deleteMessage(Message message) throws IOException { LOGGER.debug("Delete " + message.permanentUrl + " (" + message.messageUrl + ')'); DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, message.permanentUrl); } /** * @inheritDoc */ @Override public void sendMessage(byte[] messageBody) throws IOException { String messageName = UUID.randomUUID().toString() + ".EML"; createMessage(sendmsgUrl, messageName, null, messageBody); } protected boolean isGzipEncoded(HttpMethod method) { Header[] contentEncodingHeaders = method.getResponseHeaders("Content-Encoding"); if (contentEncodingHeaders != null) { for (Header header : contentEncodingHeaders) { if ("gzip".equals(header.getValue())) { return true; } } } return false; } /** * @inheritDoc */ @Override protected byte[] getContent(Message message) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream contentInputStream; try { try { contentInputStream = getContentInputStream(message.messageUrl); } catch (HttpNotFoundException e) { LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl"); contentInputStream = getContentInputStream(message.permanentUrl); } } catch (HttpException e) { // other exception if (Settings.getBooleanProperty("davmail.deleteBroken")) { LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl); try { message.delete(); } catch (IOException ioe) { LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl); } } throw e; } try { IOUtil.write(contentInputStream, baos); } finally { contentInputStream.close(); } return baos.toByteArray(); } protected InputStream getContentInputStream(String url) throws IOException { final GetMethod method = new GetMethod(URIUtil.encodePath(url)); method.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); method.setRequestHeader("Translate", "f"); method.setRequestHeader("Accept-Encoding", "gzip"); InputStream inputStream; try { DavGatewayHttpClientFacade.executeGetMethod(httpClient, method, true); if (isGzipEncoded(method)) { inputStream = new GZIPInputStream(method.getResponseBodyAsStream()); } else { inputStream = method.getResponseBodyAsStream(); } inputStream = new FilterInputStream(inputStream) { @Override public int read() throws IOException { return super.read(); } @Override public void close() throws IOException { try { super.close(); } finally { method.releaseConnection(); } } }; } catch (HttpException e) { method.releaseConnection(); LOGGER.warn("Unable to retrieve message at: " + url); throw e; } return inputStream; } /** * @inheritDoc */ @Override public void copyMessage(Message message, String targetFolder) throws IOException { String targetPath = URIUtil.encodePath(getFolderPath(targetFolder)) + '/' + UUID.randomUUID().toString(); CopyMethod method = new CopyMethod(message.permanentUrl, targetPath, false); // allow rename if a message with the same name exists method.addRequestHeader("Allow-Rename", "t"); try { int statusCode = httpClient.executeMethod(method); if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) { throw new DavMailException("EXCEPTION_UNABLE_TO_COPY_MESSAGE"); } else if (statusCode != HttpStatus.SC_CREATED) { throw DavGatewayHttpClientFacade.buildHttpException(method); } } finally { method.releaseConnection(); } } @Override protected void moveToTrash(Message message) throws IOException { String destination = URIUtil.encodePath(deleteditemsUrl) + '/' + UUID.randomUUID().toString(); LOGGER.debug("Deleting : " + message.permanentUrl + " to " + destination); MoveMethod method = new MoveMethod(message.permanentUrl, destination, false); method.addRequestHeader("Allow-rename", "t"); int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method); // do not throw error if already deleted if (status != HttpStatus.SC_CREATED && status != HttpStatus.SC_NOT_FOUND) { throw DavGatewayHttpClientFacade.buildHttpException(method); } if (method.getResponseHeader("Location") != null) { destination = method.getResponseHeader("Location").getValue(); } LOGGER.debug("Deleted to :" + destination); } protected String convertDateFromExchange(String exchangeDateValue) throws DavMailException { String zuluDateValue = null; if (exchangeDateValue != null) { try { zuluDateValue = getZuluDateFormat().format(getExchangeZuluDateFormatMillisecond().parse(exchangeDateValue)); } catch (ParseException e) { throw new DavMailException("EXCEPTION_INVALID_DATE", exchangeDateValue); } } return zuluDateValue; } }
true
true
public ItemResult createOrUpdate() throws IOException { int status = 0; PropPatchMethod propPatchMethod = new PropPatchMethod(URIUtil.encodePath(getHref()), buildProperties()) { @Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { // ignore response body, sometimes invalid with exchange mapi properties } }; propPatchMethod.setRequestHeader("Translate", "f"); if (etag != null) { propPatchMethod.setRequestHeader("If-Match", etag); } if (noneMatch != null) { propPatchMethod.setRequestHeader("If-None-Match", noneMatch); } try { status = httpClient.executeMethod(propPatchMethod); if (status == HttpStatus.SC_MULTI_STATUS) { //noinspection VariableNotUsedInsideIf if (etag == null) { status = HttpStatus.SC_CREATED; LOGGER.debug("Created contact " + getHref()); } else { status = HttpStatus.SC_OK; LOGGER.debug("Updated contact " + getHref()); } } else { LOGGER.warn("Unable to create or update contact " + status + ' ' + propPatchMethod.getStatusLine()); } } finally { propPatchMethod.releaseConnection(); } ItemResult itemResult = new ItemResult(); // 440 means forbidden on Exchange if (status == 440) { status = HttpStatus.SC_FORBIDDEN; } itemResult.status = status; String contactPictureUrl = URIUtil.encodePath(getHref() + "/ContactPicture.jpg"); String photo = get("photo"); if (photo != null) { // need to update photo byte[] resizedImageBytes = IOUtil.resizeImage(Base64.decodeBase64(photo.getBytes()), 90); final PutMethod putmethod = new PutMethod(contactPictureUrl); putmethod.setRequestHeader("Overwrite", "t"); putmethod.setRequestHeader("Content-Type", "image/jpeg"); putmethod.setRequestEntity(new ByteArrayRequestEntity(resizedImageBytes, "image/jpeg")); try { status = httpClient.executeMethod(putmethod); if (status != HttpStatus.SC_OK && status != HttpStatus.SC_CREATED) { throw new IOException("Unable to update contact picture"); } } catch (IOException e) { LOGGER.error("Error in contact photo create or update", e); throw e; } finally { putmethod.releaseConnection(); } ArrayList<DavConstants> changeList = new ArrayList<DavConstants>(); changeList.add(Field.createDavProperty("attachmentContactPhoto", "true")); changeList.add(Field.createDavProperty("renderingPosition", "-1")); final PropPatchMethod attachmentPropPatchMethod = new PropPatchMethod(contactPictureUrl, changeList); try { status = httpClient.executeMethod(attachmentPropPatchMethod); if (status != HttpStatus.SC_MULTI_STATUS) { throw new IOException("Unable to update contact picture"); } } catch (IOException e) { LOGGER.error("Error in contact photo create or update", e); throw e; } finally { attachmentPropPatchMethod.releaseConnection(); } } else { // try to delete picture DeleteMethod deleteMethod = new DeleteMethod(contactPictureUrl); try { status = httpClient.executeMethod(deleteMethod); if (status != HttpStatus.SC_OK && status != HttpStatus.SC_NOT_FOUND) { throw new IOException("Unable to delete contact picture"); } } catch (IOException e) { LOGGER.error("Error in contact photo delete", e); throw e; } finally { deleteMethod.releaseConnection(); } } // need to retrieve new etag HeadMethod headMethod = new HeadMethod(URIUtil.encodePath(getHref())); try { httpClient.executeMethod(headMethod); if (headMethod.getResponseHeader("ETag") != null) { itemResult.etag = headMethod.getResponseHeader("ETag").getValue(); } } finally { headMethod.releaseConnection(); } return itemResult; }
public ItemResult createOrUpdate() throws IOException { int status = 0; PropPatchMethod propPatchMethod = new PropPatchMethod(URIUtil.encodePath(getHref()), buildProperties()) { @Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { // ignore response body, sometimes invalid with exchange mapi properties } }; propPatchMethod.setRequestHeader("Translate", "f"); if (etag != null) { propPatchMethod.setRequestHeader("If-Match", etag); } if (noneMatch != null) { propPatchMethod.setRequestHeader("If-None-Match", noneMatch); } try { status = httpClient.executeMethod(propPatchMethod); if (status == HttpStatus.SC_MULTI_STATUS) { //noinspection VariableNotUsedInsideIf if (etag == null) { status = HttpStatus.SC_CREATED; LOGGER.debug("Created contact " + getHref()); } else { status = HttpStatus.SC_OK; LOGGER.debug("Updated contact " + getHref()); } } else { LOGGER.warn("Unable to create or update contact " + status + ' ' + propPatchMethod.getStatusLine()); } } finally { propPatchMethod.releaseConnection(); } ItemResult itemResult = new ItemResult(); // 440 means forbidden on Exchange if (status == 440) { status = HttpStatus.SC_FORBIDDEN; } itemResult.status = status; String contactPictureUrl = URIUtil.encodePath(getHref() + "/ContactPicture.jpg"); String photo = get("photo"); if (photo != null) { // need to update photo byte[] resizedImageBytes = IOUtil.resizeImage(Base64.decodeBase64(photo.getBytes()), 90); final PutMethod putmethod = new PutMethod(contactPictureUrl); putmethod.setRequestHeader("Overwrite", "t"); putmethod.setRequestHeader("Content-Type", "image/jpeg"); putmethod.setRequestEntity(new ByteArrayRequestEntity(resizedImageBytes, "image/jpeg")); try { status = httpClient.executeMethod(putmethod); if (status != HttpStatus.SC_OK && status != HttpStatus.SC_CREATED) { throw new IOException("Unable to update contact picture: "+status+ ' ' +putmethod.getStatusLine()); } } catch (IOException e) { LOGGER.error("Error in contact photo create or update", e); throw e; } finally { putmethod.releaseConnection(); } ArrayList<DavConstants> changeList = new ArrayList<DavConstants>(); changeList.add(Field.createDavProperty("attachmentContactPhoto", "true")); changeList.add(Field.createDavProperty("renderingPosition", "-1")); final PropPatchMethod attachmentPropPatchMethod = new PropPatchMethod(contactPictureUrl, changeList); try { status = httpClient.executeMethod(attachmentPropPatchMethod); if (status != HttpStatus.SC_MULTI_STATUS) { throw new IOException("Unable to update contact picture"); } } catch (IOException e) { LOGGER.error("Error in contact photo create or update", e); throw e; } finally { attachmentPropPatchMethod.releaseConnection(); } } else { // try to delete picture DeleteMethod deleteMethod = new DeleteMethod(contactPictureUrl); try { status = httpClient.executeMethod(deleteMethod); if (status != HttpStatus.SC_OK && status != HttpStatus.SC_NOT_FOUND) { throw new IOException("Unable to delete contact picture"); } } catch (IOException e) { LOGGER.error("Error in contact photo delete", e); throw e; } finally { deleteMethod.releaseConnection(); } } // need to retrieve new etag HeadMethod headMethod = new HeadMethod(URIUtil.encodePath(getHref())); try { httpClient.executeMethod(headMethod); if (headMethod.getResponseHeader("ETag") != null) { itemResult.etag = headMethod.getResponseHeader("ETag").getValue(); } } finally { headMethod.releaseConnection(); } return itemResult; }
diff --git a/src/main/java/com/vance/quest2012/WebRetriever.java b/src/main/java/com/vance/quest2012/WebRetriever.java index 960a0ea..4b75e0c 100644 --- a/src/main/java/com/vance/quest2012/WebRetriever.java +++ b/src/main/java/com/vance/quest2012/WebRetriever.java @@ -1,23 +1,25 @@ package com.vance.quest2012; /** * Application class for utility to retrieve web content. * * @author srvance */ public class WebRetriever { private String target; private String protocol; public WebRetriever(String target) { this.target = target; + String[] components = target.split(":", 2); + protocol = components[0]; } public String getTarget() { return target; } public String getProtocol() { return protocol; } }
true
true
public WebRetriever(String target) { this.target = target; }
public WebRetriever(String target) { this.target = target; String[] components = target.split(":", 2); protocol = components[0]; }
diff --git a/application/src/org/yaaic/view/MessageListView.java b/application/src/org/yaaic/view/MessageListView.java index 129d2d9..75aeefe 100644 --- a/application/src/org/yaaic/view/MessageListView.java +++ b/application/src/org/yaaic/view/MessageListView.java @@ -1,76 +1,74 @@ /* Yaaic - Yet Another Android IRC Client Copyright 2009-2012 Sebastian Kaspari This file is part of Yaaic. Yaaic 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. Yaaic 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 Yaaic. If not, see <http://www.gnu.org/licenses/>. */ package org.yaaic.view; import org.yaaic.R; import org.yaaic.adapter.MessageListAdapter; import org.yaaic.listener.MessageClickListener; import android.content.Context; import android.widget.ListView; /** * A customized ListView for Messages * * @author Sebastian Kaspari <[email protected]> */ public class MessageListView extends ListView { /** * Create a new MessageListView * * @param context */ public MessageListView(Context context) { super(context); setOnItemClickListener(MessageClickListener.getInstance()); setDivider(null); setCacheColorHint(0x000000); setVerticalFadingEdgeEnabled(false); setBackgroundResource(R.layout.conversation_background); setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET); - setTranscriptMode(TRANSCRIPT_MODE_ALWAYS_SCROLL); // Scale padding by screen density float density = context.getResources().getDisplayMetrics().density; int padding = (int) (5 * density); setPadding(padding, padding, padding, padding); - // XXX: This should be dynamically - setTranscriptMode(TRANSCRIPT_MODE_ALWAYS_SCROLL); + setTranscriptMode(TRANSCRIPT_MODE_NORMAL); } /** * Get the adapter of this MessageListView * (Helper to avoid casting) * * @return The MessageListAdapter */ @Override public MessageListAdapter getAdapter() { return (MessageListAdapter) super.getAdapter(); } }
false
true
public MessageListView(Context context) { super(context); setOnItemClickListener(MessageClickListener.getInstance()); setDivider(null); setCacheColorHint(0x000000); setVerticalFadingEdgeEnabled(false); setBackgroundResource(R.layout.conversation_background); setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET); setTranscriptMode(TRANSCRIPT_MODE_ALWAYS_SCROLL); // Scale padding by screen density float density = context.getResources().getDisplayMetrics().density; int padding = (int) (5 * density); setPadding(padding, padding, padding, padding); // XXX: This should be dynamically setTranscriptMode(TRANSCRIPT_MODE_ALWAYS_SCROLL); }
public MessageListView(Context context) { super(context); setOnItemClickListener(MessageClickListener.getInstance()); setDivider(null); setCacheColorHint(0x000000); setVerticalFadingEdgeEnabled(false); setBackgroundResource(R.layout.conversation_background); setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET); // Scale padding by screen density float density = context.getResources().getDisplayMetrics().density; int padding = (int) (5 * density); setPadding(padding, padding, padding, padding); setTranscriptMode(TRANSCRIPT_MODE_NORMAL); }