Example #1
0
  private void addClass(Class<?> c) {
    if (classes.add(c)) {
      if (c.getSuperclass() != null) {
        addClass(c.getSuperclass());
      }
      for (Class<?> sc : c.getInterfaces()) {
        addClass(sc);
      }
      for (Class<?> dc : c.getDeclaredClasses()) {
        addClass(dc);
      }
      for (Method m : c.getDeclaredMethods()) {
        addClass(m.getReturnType());
        for (Class<?> p : m.getParameterTypes()) {
          addClass(p);
        }
      }

      if (c != void.class && dimensions(c) < 2) {
        Class<?> arrayClass = Array.newInstance(c, 0).getClass();
        arrayClasses.put(c, arrayClass);
        addClass(arrayClass);
      }
    }
  }
Example #2
0
 static Method[] getOverridableMethods(Class<?> clazz) {
   ArrayList<Method> list = new ArrayList<Method>();
   HashSet<String> skip = new HashSet<String>();
   // Check superclasses before interfaces so we always choose
   // implemented methods over abstract ones, even if a subclass
   // re-implements an interface already implemented in a superclass
   // (e.g. java.util.ArrayList)
   for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
     appendOverridableMethods(c, list, skip);
   }
   for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
     for (Class<?> intf : c.getInterfaces()) appendOverridableMethods(intf, list, skip);
   }
   return list.toArray(new Method[list.size()]);
 }
  //
  // Find all the java.sql interfaces implemented by a class and find
  // the methods in those interfaces which raise
  // SQLFeatureNotSupportedException when called on the passed-in candidate object.
  //
  private void vetInterfaces(
      Object candidate,
      Class myClass,
      HashSet<String> unsupportedList,
      HashSet<String> notUnderstoodList)
      throws Exception {
    Class superClass = myClass.getSuperclass();

    if (superClass != null) {
      vetInterfaces(candidate, superClass, unsupportedList, notUnderstoodList);
    }

    //
    // The contract for Class.getInterfaces() states that the interfaces
    // come back in a deterministic order, namely, in the order that
    // they were declared in the "extends" clause.
    //
    Class<?>[] interfaces = myClass.getInterfaces();
    int interfaceCount = interfaces.length;

    for (int i = 0; i < interfaceCount; i++) {
      Class<?> iface = interfaces[i];

      if (iface.getPackage().getName().equals(SQL_PACKAGE_NAME)) {
        vetInterfaceMethods(candidate, iface, unsupportedList, notUnderstoodList);
      }

      vetInterfaces(candidate, iface, unsupportedList, notUnderstoodList);
    }
  }
Example #4
0
 // obj: "object with properties" to write
 private void writeObject(Object obj)
     throws NoSuchMethodException, InstantiationException, InvocationTargetException,
         IllegalAccessException, SecurityException {
   // begin bean encoding:
   this.driver.startElement(DTD.ELEMENT_OBJECT);
   Class cls = obj.getClass();
   final String mappedName = this.context.aliasFor(cls);
   this.driver.setAttribute(
       DTD.ATTRIBUTE_CLASS, (mappedName != null ? mappedName : cls.getName()));
   // encode properties:
   while (cls != Object.class) { // process inheritance:
     for (Field f : cls.getDeclaredFields()) { // process composition:
       if (Modifier.isStatic(f.getModifiers())
           || !ReflectionUtil.hasClassFieldProperty(cls, f)
           || this.context.excluded(f)) {
         continue; // skip static or non-property or excluded field.
       }
       // get property field:
       if (!f.isAccessible()) {
         f.setAccessible(true);
       }
       // write property value:
       final String aliasedFieldName = this.context.aliasFor(f, f.getName());
       this.driver.startElement(aliasedFieldName);
       this.write0(f.get(obj));
       this.driver.endElement();
     }
     cls = cls.getSuperclass();
   }
   // end bean encoding:
   this.driver.endElement();
 }
Example #5
0
 static Method[] getOverridableMethods(Class c) {
   ArrayList<Method> list = new ArrayList<Method>();
   HashSet<String> skip = new HashSet<String>();
   while (c != null) {
     Method[] methods = c.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       String methodKey =
           methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes());
       if (skip.contains(methodKey)) continue; // skip this method
       int mods = methods[i].getModifiers();
       if (Modifier.isStatic(mods)) continue;
       if (Modifier.isFinal(mods)) {
         // Make sure we don't add a final method to the list
         // of overridable methods.
         skip.add(methodKey);
         continue;
       }
       if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) {
         list.add(methods[i]);
         skip.add(methodKey);
       }
     }
     c = c.getSuperclass();
   }
   return list.toArray(new Method[list.size()]);
 }
 private void writeObjectCompatibleRecursive(
     FSTClazzInfo.FSTFieldInfo referencee,
     Object toWrite,
     FSTClazzInfo serializationInfo,
     Class cl)
     throws IOException {
   FSTClazzInfo.FSTCompatibilityInfo fstCompatibilityInfo = serializationInfo.compInfo.get(cl);
   if (!Serializable.class.isAssignableFrom(cl)) {
     return; // ok here, as compatible mode will never be triggered for "forceSerializable"
   }
   writeObjectCompatibleRecursive(referencee, toWrite, serializationInfo, cl.getSuperclass());
   if (fstCompatibilityInfo != null && fstCompatibilityInfo.getWriteMethod() != null) {
     try {
       writeByte(55); // tag this is written with writeMethod
       fstCompatibilityInfo
           .getWriteMethod()
           .invoke(toWrite, getObjectOutputStream(cl, serializationInfo, referencee, toWrite));
     } catch (Exception e) {
       throw FSTUtil.rethrow(e);
     }
   } else {
     if (fstCompatibilityInfo != null) {
       writeByte(66); // tag this is written from here no writeMethod
       writeObjectFields(toWrite, serializationInfo, fstCompatibilityInfo.getFieldArray(), 0, 0);
     }
   }
 }
Example #7
0
  // getField: Borrowed from WorldEdit
  @SuppressWarnings("unchecked")
  public static <T> T getField(Object from, String name) {
    Class<?> checkClass = from.getClass();
    do {
      try {
        Field field = checkClass.getDeclaredField(name);
        field.setAccessible(true);
        return (T) field.get(from);

      } catch (NoSuchFieldException ex) {
      } catch (IllegalAccessException ex) {
      }
    } while (checkClass.getSuperclass() != Object.class
        && ((checkClass = checkClass.getSuperclass()) != null));

    return null;
  }
 private static Field[] getAllFields(Class cls) {
   ArrayList<Field> res = new ArrayList<>();
   Class c = cls;
   while (c != View.class) {
     assert Utils.check(c != null);
     res.addAll(Arrays.asList(c.getDeclaredFields()));
     c = c.getSuperclass();
   }
   return res.toArray(new Field[res.size()]);
 }
 @TestMethod("testAccepts")
 public boolean accepts(Class classObject) {
   Class[] interfaces = classObject.getInterfaces();
   for (int i = 0; i < interfaces.length; i++) {
     if (IChemFile.class.equals(interfaces[i])) return true;
   }
   Class superClass = classObject.getSuperclass();
   if (superClass != null) return this.accepts(superClass);
   return false;
 }
 private Field findSqlMapExecutorDelegate(SqlMapClient sqlMapClient) {
   Class<?> searchType = sqlMapClient.getClass();
   while (!Object.class.equals(searchType) && searchType != null) {
     Field[] fields = searchType.getDeclaredFields();
     for (Field field : fields) {
       if (SqlMapExecutorDelegate.class.isAssignableFrom(field.getType())) return field;
     }
     searchType = searchType.getSuperclass();
   }
   return null;
 }
Example #11
0
 static Method[] getOverridableMethods(Class c) {
   ArrayList list = new ArrayList();
   while (c != null) {
     Method[] methods = c.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       int mods = methods[i].getModifiers();
       if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) continue;
       if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) list.add(methods[i]);
     }
     c = c.getSuperclass();
   }
   return (Method[]) list.toArray(new Method[list.size()]);
 }
Example #12
0
  /**
   * Get the JDBC type constant which matches the supplied <code>Class</code>.
   *
   * @param typeClass the <code>Class</code> to analyse
   * @return the JDBC type constant as an <code>int</code>
   */
  static int getJdbcType(Class typeClass) {
    if (typeClass == null) {
      return java.sql.Types.JAVA_OBJECT;
    }

    Object type = typeMap.get(typeClass);

    if (type == null) {
      // not in typeMap - try recursion through superclass hierarchy
      return getJdbcType(typeClass.getSuperclass());
    }

    return ((Integer) type).intValue();
  }
 private static Method findMethod(
     Class<? extends Object> aClass, String methodName, Class[] params) {
   try {
     final Method method = aClass.getDeclaredMethod(methodName, params);
     method.setAccessible(true);
     return method;
   } catch (NoSuchMethodException ignored) {
   }
   final Class<?> parent = aClass.getSuperclass();
   if (parent == null) {
     return null;
   }
   return findMethod(parent, methodName, params);
 }
Example #14
0
  private void InitFieldCmd(ICmd cmd, Hashtable<FieldCmdKind, Object> fieldsValue) {
    Class c = cmd.getClass(); // Класс рассматриваемой команды.
    Field f[]; // Набор полей рассматриваемого класса.

    while (c != null) {
      f = c.getDeclaredFields();

      for (Field iF : f) {
        setFieldValue(iF, cmd, fieldsValue);
      }

      c = c.getSuperclass();
    }
  }
  public static Object invokeSuperclassMethodImpl(
      BshClassManager bcm, Object instance, String methodName, Object[] args)
      throws UtilEvalError, ReflectError, InvocationTargetException {
    String superName = ClassGeneratorUtil.BSHSUPER + methodName;

    // look for the specially named super delegate method
    Class clas = instance.getClass();
    Method superMethod =
        Reflect.resolveJavaMethod(bcm, clas, superName, Types.getTypes(args), false /*onlyStatic*/);
    if (superMethod != null) return Reflect.invokeMethod(superMethod, instance, args);

    // No super method, try to invoke regular method
    // could be a superfluous "super." which is legal.
    Class superClass = clas.getSuperclass();
    superMethod =
        Reflect.resolveExpectedJavaMethod(
            bcm, superClass, instance, methodName, args, false /*onlyStatic*/);
    return Reflect.invokeMethod(superMethod, instance, args);
  }
Example #16
0
  // Needed by NativeJavaObject serializer
  public static void writeAdapterObject(Object javaObject, ObjectOutputStream out)
      throws IOException {
    Class<?> cl = javaObject.getClass();
    out.writeObject(cl.getSuperclass().getName());

    Class<?>[] interfaces = cl.getInterfaces();
    String[] interfaceNames = new String[interfaces.length];

    for (int i = 0; i < interfaces.length; i++) interfaceNames[i] = interfaces[i].getName();

    out.writeObject(interfaceNames);

    try {
      Object delegee = cl.getField("delegee").get(javaObject);
      out.writeObject(delegee);
      return;
    } catch (IllegalAccessException e) {
    } catch (NoSuchFieldException e) {
    }
    throw new IOException();
  }
    private Method cacheMethod(
        Object obj, String methodName, Class[] methodParameters, HashMap methodCache) {
      Class objClass = obj.getClass();
      Method objMethod = null;

      // Look up inheritance hierarchy
      while (objClass != Object.class) {
        try {
          objMethod = objClass.getDeclaredMethod(methodName, methodParameters);
          objClass = Object.class; // executed only if call succeeds
        } catch (NoSuchMethodException nsmE) {
          objClass = objClass.getSuperclass();
        }
      }

      // Cache result
      if (objMethod == null) {
        methodCache.put(obj.getClass(), NONE);
      } else {
        objMethod.setAccessible(true); // monstrous, monstrous
        methodCache.put(obj.getClass(), objMethod);
      }
      return objMethod;
    }
  /**
   * Process and loop until told to stop. A callback_done will stop the loop and will return a
   * result. Otherwise null is returned.
   */
  public Object run() throws CommandException {
    Object result = null;
    boolean shutdown = false;
    boolean closeWhenDone = true;
    Commands.ValueObject valueObject =
        new Commands.ValueObject(); // Working value object so not continually recreated.
    InvokableValueSender valueSender =
        new InvokableValueSender(); // Working valuesender so not continually recreated.
    try {
      boolean doLoop = true;

      /**
       * Note: In the cases below you will see a lot of finally clauses that null variables out.
       * This is because this is a long running loop, and variables declared within blocks are not
       * garbage collected until the method is terminated, so these variables once set would never
       * be GC'd. The nulling at the end of the case makes sure that any of those objects set are
       * now available for garbage collection when necessary.
       */
      while (doLoop && isConnected()) {
        byte cmd = 0;
        try {
          if (LINUX_1_3) socket.setSoTimeout(1000); // Linux 1.3 bug, see comment on LINUX_1_3
          cmd = in.readByte();
          if (LINUX_1_3 && isConnected())
            socket.setSoTimeout(0); // Linux 1.3 bug, see comment on LINUX_1_3
        } catch (InterruptedIOException e) {
          continue; // Timeout, try again
        }
        switch (cmd) {
          case Commands.QUIT_CONNECTION:
            doLoop = false;
            break; // Close this connection

          case Commands.TERMINATE_SERVER:
            doLoop = false;
            shutdown = true; // Shutdown everything
            break;

          case Commands.GET_CLASS:
            String className = in.readUTF();
            Class aClass = null;
            Class superClass = null;
            String superClassName = null;
            boolean added = false;
            try {
              aClass =
                  Class.forName(
                      className); // Turns out using JNI format for array type will work fine.

              added = server.getIdentityID(aClass, valueObject);
              boolean isInterface = aClass.isInterface();
              boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers());
              superClass = aClass.getSuperclass();
              superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$
              out.writeByte(Commands.GET_CLASS_RETURN);
              out.writeInt(valueObject.objectID);
              out.writeBoolean(isInterface);
              out.writeBoolean(isAbstract);
              out.writeUTF(superClassName);
              out.flush();
            } catch (ClassNotFoundException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.GET_CLASS_NOT_FOUND, valueObject);
            } catch (ExceptionInInitializerError e) {
              sendException(e.getException(), valueObject, out);
            } catch (LinkageError e) {
              sendException(e, valueObject, out);
            } catch (Throwable e) {
              // Something bad, did we add a class? If we did remove it from the table.
              if (added) server.removeObject(server.getObject(valueObject.objectID));
              throw e;
            } finally {
              // clear out for GC to work.
              className = null;
              aClass = null;
              superClass = null;
              superClassName = null;
              valueObject.set();
            }
            break;

          case Commands.GET_CLASS_FROM_ID:
            int classID = in.readInt();
            try {
              aClass = (Class) server.getObject(classID);
              boolean isInterface = aClass.isInterface();
              boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers());
              superClass = aClass.getSuperclass();
              superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$
              out.writeByte(Commands.GET_CLASS_ID_RETURN);
              out.writeUTF(aClass.getName());
              out.writeBoolean(isInterface);
              out.writeBoolean(isAbstract);
              out.writeUTF(superClassName);
              out.flush();
            } catch (ClassCastException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
            } finally {
              // clear out for GC to work.
              aClass = null;
              superClass = null;
              superClassName = null;
              valueObject.set();
            }
            break;

          case Commands.GET_OBJECT_DATA:
            int objectID = in.readInt();
            Object anObject = null;
            try {
              anObject = server.getObject(objectID);
              valueObject.setObjectID(objectID, server.getIdentityID(anObject.getClass()));
              Commands.writeValue(out, valueObject, true);
            } catch (ClassCastException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
            } finally {
              anObject = null; // Clear out for GC to work
              valueObject.set();
            }
            break;

          case Commands.RELEASE_OBJECT:
            int id = in.readInt();
            server.removeObject(server.getObject(id));
            break;

          case Commands.NEW_INIT_STRING:
            classID = in.readInt(); // ID Of class to do new upon.
            String initString = in.readUTF(); // The init string.
            Object newValue = null;
            Class theClass = null;
            try {
              theClass = (Class) server.getObject(classID);
              if (theClass == null) {
                // The class wasn't found. So imply ClassNotFound exception.
                throw new ClassNotFoundException();
              }

              InitializationStringParser parser = null;
              try {
                parser = InitializationStringParser.createParser(initString);
                newValue = parser.evaluate();
                boolean primitive = parser.isPrimitive();
                // If expected class is Void.TYPE, that means don't test the type of the result
                // to verify if correct type, just return what it really is.
                if (theClass != Void.TYPE && primitive != theClass.isPrimitive()) {
                  valueObject.set();
                  Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                  continue; // Goto next command.
                }
                if (primitive) {
                  try {
                    // Need to do special tests for compatibility and assignment.
                    sendObject(
                        newValue,
                        classID != Commands.VOID_TYPE
                            ? classID
                            : server.getIdentityID(parser.getExpectedType()),
                        valueObject,
                        out,
                        true); // This will make sure it goes out as the correct primitive type
                  } catch (ClassCastException e) {
                    // The returned type is not of the correct type for what is expected.
                    valueObject.set();
                    Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                    continue; // Goto next command
                  }
                } else {
                  if (newValue != null) {
                    // Test to see if they are compatible. (Null can be assigned to any object,
                    // so that is why it was tested out above).
                    // If expected class is Void.TYPE, that means don't test the type of the result
                    // to verify if correct type, just return what it really is.
                    if (theClass != Void.TYPE && !theClass.isInstance(newValue)) {
                      // The returned type is not of the correct type for what is expected.
                      valueObject.set();
                      Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                      continue; // Goto next command
                    }
                  }
                  sendObject(
                      newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Send out as an object.
                }
              } catch (InitializationStringEvaluationException e) {
                if (e instanceof EvaluationException) {
                  // Want to return the real exception.
                  sendException(e.getOriginalException(), valueObject, out);
                } else {
                  // Couldn't be evaluated, return an error for this.
                  setExceptionIntoValue(e.getOriginalException(), valueObject);
                  Commands.sendErrorCommand(out, Commands.CANNOT_EVALUATE_STRING, valueObject);
                }
              } finally {
                parser = null; // Clear out for GC to work
              }
            } catch (Throwable e) {
              sendException(e, valueObject, out);
            } finally {
              // Clear out for GC to work
              initString = null;
              theClass = null;
              newValue = null;
              valueObject.set();
            }
            break;

          case Commands.INVOKE:
            Object target = null;
            Object[] parms = null;
            Class returnType = null;
            java.lang.reflect.Method aMethod = null;
            try {
              int methodID = in.readInt(); // ID of method to invoke
              aMethod = (java.lang.reflect.Method) server.getObject(methodID); // Method to invoke
              Commands.readValue(in, valueObject);
              target = getInvokableObject(valueObject);
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parms = (Object[]) valueSender.getArray();
              } else {
                // It is all objects or null, so it should be an Object[] or null. If not, then this
                // is an error.
                parms = (Object[]) valueObject.anObject;
              }

              if (!aMethod.isAccessible())
                aMethod.setAccessible(
                    true); // We will allow all to occur. Let access control be handled by IDE and
                           // compiler.
              newValue = aMethod.invoke(target, parms);
              returnType = aMethod.getReturnType();
              if (returnType.isPrimitive()) {
                int returnTypeID = server.getIdentityID(returnType);
                // Need to tell sendObject the correct primitive type.
                sendObject(newValue, returnTypeID, valueObject, out, true);

              } else {
                sendObject(
                    newValue,
                    NOT_A_PRIMITIVE,
                    valueObject,
                    out,
                    true); // Just send the object back. sendObject knows how to iterpret the type
              }
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (java.lang.reflect.InvocationTargetException e) {
              // This is a wrappered exception. Return the wrappered one so it looks like
              // it was the real one. (Sometimes the method being invoked is on a
              // java.lang.reflect.Constructor.newInstance,
              // which in turn is an InvocationTargetException, so we will go until we don't have an
              // InvocationTargetException.
              Throwable t = e;
              do {
                t = ((java.lang.reflect.InvocationTargetException) t).getTargetException();
              } while (t instanceof java.lang.reflect.InvocationTargetException);
              sendException(t, valueObject, out);
            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              // Clear out for GC to work
              valueObject.set();
              parms = null;
              target = null;
              aMethod = null;
              returnType = null;
              newValue = null;
              valueSender.clear();
            }
            break;

          case Commands.INVOKE_WITH_METHOD_PASSED:
            aClass = null;
            String methodName = null;
            Class[] parmTypes = null;
            target = null;
            parms = null;
            returnType = null;
            aMethod = null;

            try {
              Commands.readValue(in, valueObject);
              aClass = (Class) getInvokableObject(valueObject); // The class that has the method.
              methodName = in.readUTF();
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parmTypes = (Class[]) valueSender.getArray();
              } else {
                // It null, so it should be an null. If not, then this is an error.
                parmTypes = null;
              }
              aMethod = aClass.getMethod(methodName, parmTypes);

              // Now we get the info for the invocation of the method and execute it.
              Commands.readValue(in, valueObject);
              target = getInvokableObject(valueObject);
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parms = (Object[]) valueSender.getArray();
              } else {
                // It is all objects or null, so it should be an Object[] or null. If not, then this
                // is an error.
                parms = (Object[]) valueObject.anObject;
              }

              if (!aMethod.isAccessible())
                aMethod.setAccessible(
                    true); // We will allow all to occur. Let access control be handled by IDE and
                           // compiler.
              newValue = aMethod.invoke(target, parms);
              returnType = aMethod.getReturnType();
              if (returnType.isPrimitive()) {
                int returnTypeID = server.getIdentityID(returnType);
                // Need to tell sendObject the correct primitive type.
                sendObject(newValue, returnTypeID, valueObject, out, true);

              } else {
                sendObject(
                    newValue,
                    NOT_A_PRIMITIVE,
                    valueObject,
                    out,
                    true); // Just send the object back. sendObject knows how to iterpret the type
              }
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (java.lang.reflect.InvocationTargetException e) {
              // This is a wrappered exception. Return the wrappered one so it looks like
              // it was the real one. (Sometimes the method being invoked is on a
              // java.lang.reflect.Constructor.newInstance,
              // which in turn is an InvocationTargetException, so we will go until we don't have an
              // InvocationTargetException.
              Throwable t = e;
              do {
                t = ((java.lang.reflect.InvocationTargetException) t).getTargetException();
              } while (t instanceof java.lang.reflect.InvocationTargetException);
              sendException(t, valueObject, out);

            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              aClass = null;
              methodName = null;
              parmTypes = null;
              // Clear out for GC to work
              valueObject.set();
              parms = null;
              target = null;
              aMethod = null;
              returnType = null;
              newValue = null;
              valueSender.clear();
            }
            break;

          case Commands.GET_ARRAY_CONTENTS:
            try {
              target = server.getObject(in.readInt()); // Array to get the ids for.
              valueObject.setArrayIDS(
                  new ArrayContentsRetriever(target),
                  Array.getLength(target),
                  Commands.OBJECT_CLASS);
              Commands.writeValue(out, valueObject, true); // Write it back as a value command.
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              target = null;
              valueObject.set();
            }
            break;

          case Commands.CALLBACK_DONE:
            try {
              if (connectionThread != null) {
                valueObject.set();
                Commands.sendErrorCommand(out, Commands.UNKNOWN_COMMAND_SENT, valueObject);
              } else {
                try {
                  Commands.readBackValue(in, valueObject, Commands.NO_TYPE_CHECK);
                  if (valueObject.type == Commands.ARRAY_IDS) {
                    // It is an array containing IDs, as it normally would be.
                    valueSender.initialize(valueObject);
                    Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                    result = valueSender.getArray();
                  } else {
                    result = getInvokableObject(valueObject);
                  }
                  doLoop = false; // We need to terminate and return result
                  closeWhenDone = false; // Don't close, we will continue.
                } catch (CommandErrorException e) {
                  // There was an command error on the other side. This means
                  // connection still good, but don't continue the callback processing.
                  doLoop = false; // We need to terminate and return result
                  closeWhenDone = false; // Don't close, we will continue.
                  throw e; // Let it go on out.
                }
              }
            } finally {
              valueObject.set();
              valueSender.clear();
            }
            break;

          case Commands.ERROR:
            try {
              // Got an error command. Don't know what to do but read the
              // value and simply print it out.
              Commands.readValue(in, valueObject);
              result = getInvokableObject(valueObject);
              System.out.println("Error sent to server: Result=" + result); // $NON-NLS-1$
            } finally {
              valueObject.set();
            }
            break;

          case Commands.EXPRESSION_TREE_COMMAND:
            try {
              processExpressionCommand(valueObject, valueSender);
            } finally {
              valueObject.set();
              valueSender.clear();
            }
            break;

          default:
            // Unknown command. We don't know how long it is, so we need to shut the connection
            // down.
            System.err.println("Error: Invalid cmd send to server: Cmd=" + cmd); // $NON-NLS-1$
            doLoop = false;
            closeWhenDone = true;
            break;
        }
      }
    } catch (EOFException e) {
      // This is ok. It means that the connection on the other side was terminated.
      // So just accept this and go down.
    } catch (CommandException e) {
      throw e;
    } catch (SocketException e) {
      if (socket != null)
        throw new UnexpectedExceptionCommandException(
            false, e); // socket null means a valid close request
    } catch (Throwable e) {
      e.printStackTrace();
    } finally {
      if (closeWhenDone) {
        try {
          for (Iterator itr = expressionProcessors.values().iterator(); itr.hasNext(); ) {
            ExpressionProcesserController exp = (ExpressionProcesserController) itr.next();
            exp.close();
          }
        } finally {
          expressionProcessors.clear();
        }

        if (in != null)
          try {
            in.close();
          } catch (Exception e) {
          }
        in = null;
        if (out != null)
          try {
            out.close();
          } catch (Exception e) {
          }
        out = null;
        close();
      }
    }

    if (closeWhenDone && connectionThread != null) server.removeConnectionThread(connectionThread);
    if (shutdown) server.requestShutdown();

    return result;
  }
  public boolean prepareDelegate(
      Object subject, CommandSession session, List<Object> params, CommandArguments args)
      throws Exception {
    args.subject = subject;
    // Introspect
    for (Class type = subject.getClass(); type != null; type = type.getSuperclass()) {
      for (Field field : type.getDeclaredFields()) {
        Option option = field.getAnnotation(Option.class);
        if (option != null) {
          args.options.put(option, field);
        }
        Argument argument = field.getAnnotation(Argument.class);
        if (argument != null) {
          if (Argument.DEFAULT.equals(argument.name())) {
            final Argument delegate = argument;
            final String name = field.getName();
            argument =
                new Argument() {
                  public String name() {
                    return name;
                  }

                  public String description() {
                    return delegate.description();
                  }

                  public boolean required() {
                    return delegate.required();
                  }

                  public int index() {
                    return delegate.index();
                  }

                  public boolean multiValued() {
                    return delegate.multiValued();
                  }

                  public String valueToShowInHelp() {
                    return delegate.valueToShowInHelp();
                  }

                  public Class<? extends Annotation> annotationType() {
                    return delegate.annotationType();
                  }
                };
          }
          args.arguments.put(argument, field);
          int index = argument.index();
          while (args.orderedArguments.size() <= index) {
            args.orderedArguments.add(null);
          }
          if (args.orderedArguments.get(index) != null) {
            throw new IllegalArgumentException("Duplicate argument index: " + index);
          }
          args.orderedArguments.set(index, argument);
        }
      }
    }
    // Check indexes are correct
    for (int i = 0; i < args.orderedArguments.size(); i++) {
      if (args.orderedArguments.get(i) == null) {
        throw new IllegalArgumentException("Missing argument for index: " + i);
      }
    }
    // Populate
    Map<Option, Object> optionValues =
        new TreeMap<Option, Object>(CommandArguments.OPTION_COMPARATOR);
    Map<Argument, Object> argumentValues = new HashMap<Argument, Object>();
    boolean processOptions = true;
    int argIndex = 0;
    for (Iterator<Object> it = params.iterator(); it.hasNext(); ) {
      Object param = it.next();
      // Check for help
      if (HELP.name().equals(param) || Arrays.asList(HELP.aliases()).contains(param)) {
        printUsageDelegate(session, subject, args.options, args.arguments, System.out);
        return false;
      }
      if (processOptions && param instanceof String && ((String) param).startsWith("-")) {
        boolean isKeyValuePair = ((String) param).indexOf('=') != -1;
        String name;
        Object value = null;
        if (isKeyValuePair) {
          name = ((String) param).substring(0, ((String) param).indexOf('='));
          value = ((String) param).substring(((String) param).indexOf('=') + 1);
        } else {
          name = (String) param;
        }
        Option option = null;
        for (Option opt : args.options.keySet()) {
          if (name.equals(opt.name()) || Arrays.asList(opt.aliases()).contains(name)) {
            option = opt;
            break;
          }
        }
        if (option == null) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(" undefined option ")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(param)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Undefined option: " + param);
        }
        Field field = args.options.get(option);
        if (value == null
            && (field.getType() == boolean.class || field.getType() == Boolean.class)) {
          value = Boolean.TRUE;
        }
        if (value == null && it.hasNext()) {
          value = it.next();
        }
        if (value == null) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(" missing value for option ")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(param)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Missing value for option: " + param);
        }
        if (option.multiValued()) {
          List<Object> l = (List<Object>) optionValues.get(option);
          if (l == null) {
            l = new ArrayList<Object>();
            optionValues.put(option, l);
          }
          l.add(value);
        } else {
          optionValues.put(option, value);
        }
      } else {
        processOptions = false;
        if (argIndex >= args.orderedArguments.size()) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(": too many arguments specified")
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Too many arguments specified");
        }
        Argument argument = args.orderedArguments.get(argIndex);
        if (!argument.multiValued()) {
          argIndex++;
        }
        if (argument.multiValued()) {
          List<Object> l = (List<Object>) argumentValues.get(argument);
          if (l == null) {
            l = new ArrayList<Object>();
            argumentValues.put(argument, l);
          }
          l.add(param);
        } else {
          argumentValues.put(argument, param);
        }
      }
    }
    // Check required arguments / options
    for (Option option : args.options.keySet()) {
      if (option.required() && optionValues.get(option) == null) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": option ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(option.name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" is required")
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Option " + option.name() + " is required");
      }
    }
    for (Argument argument : args.arguments.keySet()) {
      if (argument.required() && argumentValues.get(argument) == null) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": argument ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(argument.name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" is required")
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Argument " + argument.name() + " is required");
      }
    }
    // Convert and inject values
    for (Map.Entry<Option, Object> entry : optionValues.entrySet()) {
      Field field = args.options.get(entry.getKey());
      Object value;
      try {
        value = convert(subject, entry.getValue(), field.getGenericType());
      } catch (Exception e) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": unable to convert option ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(entry.getKey().name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" with value '")
                .a(entry.getValue())
                .a("' to type ")
                .a(new GenericType(field.getGenericType()).toString())
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Unable to convert option "
                + entry.getKey().name()
                + " with value '"
                + entry.getValue()
                + "' to type "
                + new GenericType(field.getGenericType()).toString(),
            e);
      }
      field.setAccessible(true);
      field.set(subject, value);
    }
    for (Map.Entry<Argument, Object> entry : argumentValues.entrySet()) {
      Field field = args.arguments.get(entry.getKey());
      Object value;
      try {
        value = convert(subject, entry.getValue(), field.getGenericType());
      } catch (Exception e) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": unable to convert argument ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(entry.getKey().name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" with value '")
                .a(entry.getValue())
                .a("' to type ")
                .a(new GenericType(field.getGenericType()).toString())
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Unable to convert argument "
                + entry.getKey().name()
                + " with value '"
                + entry.getValue()
                + "' to type "
                + new GenericType(field.getGenericType()).toString(),
            e);
      }
      field.setAccessible(true);
      field.set(subject, value);
    }
    return true;
  }
Example #20
0
  private void loadPluginsIntoClassLoader() {
    File pluginsFile = environment.pluginsFile();
    if (!pluginsFile.exists()) {
      return;
    }
    if (!pluginsFile.isDirectory()) {
      return;
    }

    ClassLoader classLoader = settings.getClassLoader();
    Class classLoaderClass = classLoader.getClass();
    Method addURL = null;
    while (!classLoaderClass.equals(Object.class)) {
      try {
        addURL = classLoaderClass.getDeclaredMethod("addURL", URL.class);
        addURL.setAccessible(true);
        break;
      } catch (NoSuchMethodException e) {
        // no method, try the parent
        classLoaderClass = classLoaderClass.getSuperclass();
      }
    }
    if (addURL == null) {
      logger.debug(
          "Failed to find addURL method on classLoader [" + classLoader + "] to add methods");
      return;
    }

    File[] pluginsFiles = pluginsFile.listFiles();
    for (File pluginFile : pluginsFiles) {
      if (!pluginFile.getName().endsWith(".zip")) {
        continue;
      }
      if (logger.isTraceEnabled()) {
        logger.trace("Processing [{}]", pluginFile);
      }

      String pluginNameNoExtension =
          pluginFile.getName().substring(0, pluginFile.getName().lastIndexOf('.'));
      File extractedPluginDir =
          new File(new File(environment.workFile(), "plugins"), pluginNameNoExtension);
      extractedPluginDir.mkdirs();

      File stampsDir = new File(new File(environment.workFile(), "plugins"), "_stamps");
      stampsDir.mkdirs();

      boolean extractPlugin = true;
      File stampFile = new File(stampsDir, pluginNameNoExtension + ".stamp");
      if (stampFile.exists()) {
        // read it, and check if its the same size as the pluginFile
        RandomAccessFile raf = null;
        try {
          raf = new RandomAccessFile(stampFile, "r");
          long size = raf.readLong();
          if (size == pluginFile.length()) {
            extractPlugin = false;
            if (logger.isTraceEnabled()) {
              logger.trace("--- No need to extract plugin, same size [" + size + "]");
            }
          }
        } catch (Exception e) {
          // ignore and extract the plugin
        } finally {
          if (raf != null) {
            try {
              raf.close();
            } catch (IOException e) {
              // ignore
            }
          }
        }
      }

      if (extractPlugin) {
        if (logger.isTraceEnabled()) {
          logger.trace("--- Extracting plugin to [" + extractedPluginDir + "]");
        }
        deleteRecursively(extractedPluginDir, false);

        ZipFile zipFile = null;
        try {
          zipFile = new ZipFile(pluginFile);
          Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
          while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            if (!(zipEntry.getName().endsWith(".jar") || zipEntry.getName().endsWith(".zip"))) {
              continue;
            }
            String name = zipEntry.getName().replace('\\', '/');
            File target = new File(extractedPluginDir, name);
            Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target));
          }
        } catch (Exception e) {
          logger.warn("Failed to extract plugin [" + pluginFile + "], ignoring...", e);
          continue;
        } finally {
          if (zipFile != null) {
            try {
              zipFile.close();
            } catch (IOException e) {
              // ignore
            }
          }
        }

        try {
          RandomAccessFile raf = new RandomAccessFile(stampFile, "rw");
          raf.writeLong(pluginFile.length());
          raf.close();
        } catch (Exception e) {
          // ignore
        }
      }

      try {
        for (File jarToAdd : extractedPluginDir.listFiles()) {
          if (!(jarToAdd.getName().endsWith(".jar") || jarToAdd.getName().endsWith(".zip"))) {
            continue;
          }
          addURL.invoke(classLoader, jarToAdd.toURI().toURL());
        }
      } catch (Exception e) {
        logger.warn("Failed to add plugin [" + pluginFile + "]", e);
      }
    }
  }