Esempio n. 1
0
File: Macro.java Progetto: bramk/bnd
 private String doCommand(Object target, String method, String[] args) {
   if (target == null) ; // System.err.println("Huh? Target should never be null " +
   // domain);
   else {
     String cname = "_" + method.replaceAll("-", "_");
     try {
       Method m = target.getClass().getMethod(cname, new Class[] {String[].class});
       return (String) m.invoke(target, new Object[] {args});
     } catch (NoSuchMethodException e) {
       // Ignore
     } catch (InvocationTargetException e) {
       if (e.getCause() instanceof IllegalArgumentException) {
         domain.error(
             "%s, for cmd: %s, arguments; %s",
             e.getCause().getMessage(), method, Arrays.toString(args));
       } else {
         domain.warning("Exception in replace: %s", e.getCause());
         e.getCause().printStackTrace();
       }
     } catch (Exception e) {
       domain.warning("Exception in replace: " + e + " method=" + method);
       e.printStackTrace();
     }
   }
   return null;
 }
Esempio n. 2
0
 public static Object invoke(Method method, Object bean, Object... args) {
   try {
     return method.invoke(bean, args);
   } catch (InvocationTargetException e) {
     if (e.getCause() instanceof RuntimeException) throw (RuntimeException) e.getCause();
     else throw new RuntimeException(method.getName() + ": " + e, e.getCause());
   } catch (Exception e) {
     throw new RuntimeException(method.getName() + ": " + e, e);
   }
 }
 public void setFeature(String name, boolean value) throws ParserConfigurationException {
   //     fact.setFeature(name, value);
   try {
     invoke("setFeature", argsSetFeature, new Object[] {name, Boolean.valueOf(value)});
   } catch (InvocationTargetException e) {
     if (e.getCause() instanceof ParserConfigurationException) {
       throw (ParserConfigurationException) e.getCause();
     }
     if (e.getCause() instanceof RuntimeException) {
       throw (RuntimeException) e.getCause();
     }
     throw new RuntimeException(e);
   }
 }
 public boolean getFeature(String name) throws ParserConfigurationException {
   //     return fact.getFeature(name);
   try {
     Object res = invoke("getFeatureccc", argsGetFeature, new Object[] {name});
     return ((Boolean) res).booleanValue();
   } catch (InvocationTargetException e) {
     if (e.getCause() instanceof ParserConfigurationException) {
       throw (ParserConfigurationException) e.getCause();
     }
     if (e.getCause() instanceof RuntimeException) {
       throw (RuntimeException) e.getCause();
     }
     throw new RuntimeException(e);
   }
 }
  /**
   * Calls a particular callback function. The function must previously have been checked using
   * checkCallback().
   *
   * @param sCallback Name of callback
   * @throws OmException If the callback throws an exception or there was an error calling it
   */
  public void callback(String sCallback) throws OmException {
    if (!sCheckedCallbacks.contains(sCallback))
      throw new OmDeveloperException(
          "Error running callback " + sCallback + "(): checkCallback was not called");

    try {
      Method m = getClass().getMethod(sCallback, new Class[0]);
      m.invoke(this, new Object[0]);
    } catch (InvocationTargetException e) {
      if (e.getCause() instanceof OmException) throw (OmException) e.getCause();
      else throw new OmException("Exception in callback " + sCallback + "()", e.getCause());
    } catch (Exception e) {
      throw new OmUnexpectedException(e);
    }
  }
 /**
  * This method returns the maximum representation size of an object. <code>sizeSoFar</code> is the
  * object's size measured so far. <code>f</code> is the field being probed.
  *
  * <p>The returned offset will be the maximum of whatever was measured so far and <code>f</code>
  * field's offset and representation size (unaligned).
  */
 private static long adjustForField(long sizeSoFar, final Field f) {
   final Class<?> type = f.getType();
   final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF;
   if (objectFieldOffsetMethod != null) {
     try {
       final long offsetPlusSize =
           ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize;
       return Math.max(sizeSoFar, offsetPlusSize);
     } catch (IllegalAccessException ex) {
       throw new RuntimeException("Access problem with sun.misc.Unsafe", ex);
     } catch (InvocationTargetException ite) {
       final Throwable cause = ite.getCause();
       if (cause instanceof RuntimeException) throw (RuntimeException) cause;
       if (cause instanceof Error) throw (Error) cause;
       // this should never happen (Unsafe does not declare
       // checked Exceptions for this method), but who knows?
       throw new RuntimeException(
           "Call to Unsafe's objectFieldOffset() throwed "
               + "checked Exception when accessing field "
               + f.getDeclaringClass().getName()
               + "#"
               + f.getName(),
           cause);
     }
   } else {
     // TODO: No alignments based on field type/ subclass fields alignments?
     return sizeSoFar + fsize;
   }
 }
  /**
   * Creates a new entity enumeration icon chooser.
   *
   * @param enumeration the enumeration to display in this combo box
   */
  public EnumerationIconChooser(Class<E> enumeration) {
    super();

    this.enumeration = enumeration;

    try {
      this.icons = (ImageIcon[]) enumeration.getMethod("getIcons").invoke(null);
      for (int i = 0; i < icons.length; i++) {
        addItem(icons[i]);
      }
    } catch (NoSuchMethodException ex) {
      System.err.println(
          "The method 'getIcons()' is missing in enumeration " + enumeration.getName());
      ex.printStackTrace();
      System.exit(1);
    } catch (IllegalAccessException ex) {
      System.err.println(
          "Cannot access method 'getIcons()' in enumeration "
              + enumeration.getName()
              + ": ex.getMessage()");
      ex.printStackTrace();
      System.exit(1);
    } catch (InvocationTargetException ex) {
      ex.getCause().printStackTrace();
      System.exit(1);
    }
  }
Esempio n. 8
0
 public void process(File cFile) {
   try {
     String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile));
     if (!cName.contains("")) return; // Ignore unpackaged classes
     testClass = Class.forName(cName);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   TestMethods testMethods = new TestMethods();
   Method creator = null;
   Method cleanup = null;
   for (Method m : testClass.getDeclaredMethods()) {
     testMethods.addIfTestMethod(m);
     if (creator == null) creator = checkForCreatorMethod(m);
     if (cleanup == null) cleanup = checkForCleanupMethod(m);
   }
   if (testMethods.size() > 0) {
     if (creator == null)
       try {
         if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) {
           Print.print("Error: " + testClass + " default constructor must be public");
           System.exit(1);
         }
       } catch (NoSuchMethodException e) {
         // Synthesized default constructor; OK
       }
     Print.print(testClass.getName());
   }
   for (Method m : testMethods) {
     Print.printnb("  . " + m.getName() + " ");
     try {
       Object testObject = createTestObject(creator);
       boolean success = false;
       try {
         if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject);
         else {
           m.invoke(testObject);
           success = true; // If no assert fails
         }
       } catch (InvocationTargetException e) {
         // Actual exception is inside e:
         Print.print(e.getCause());
       }
       Print.print(success ? "" : "(failed)");
       testsRun++;
       if (!success) {
         failures++;
         failedTests.add(testClass.getName() + ": " + m.getName());
       }
       if (cleanup != null) cleanup.invoke(testObject, testObject);
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
  /**
   * Checks that unacceptable property value prevents SPI from being started.
   *
   * @param spi Spi to test property on.
   * @param propName name of property to check.
   * @param val An illegal value.
   * @param checkExMsg If {@code true} then additional info will be added to failure.
   * @throws Exception If check failed.
   */
  protected void checkNegativeSpiProperty(
      IgniteSpi spi, String propName, Object val, boolean checkExMsg) throws Exception {
    assert spi != null;
    assert propName != null;

    getTestData().getTestResources().inject(spi);

    String mtdName = "set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);

    Method mtd = null;

    for (Method m : spi.getClass().getMethods())
      if (m.getName().equals(mtdName)) {
        mtd = m;

        break;
      }

    assert mtd != null : "The setter is not found for property: " + propName;

    boolean err = false;

    try {
      mtd.invoke(spi, val);
    } catch (InvocationTargetException e) {
      info("SPI property setter thrown exception: " + e);

      if (e.getCause() instanceof IllegalArgumentException) err = true;
      else throw e;
    }

    if (!err)
      try {
        if (!(spi instanceof DiscoverySpi)) spi.getNodeAttributes();

        spi.spiStart(getTestGridName());
      } catch (IgniteSpiException e) {
        info("SPI start thrown exception: " + e);

        if (checkExMsg)
          assert e.getMessage().contains("SPI parameter failed condition check: ")
              : "SPI has returned wrong exception message [propName="
                  + propName
                  + ", msg="
                  + e
                  + ']';

        err = true;
      }

    assert err : "No check for property [property=" + propName + ", value=" + val + ']';
  }
Esempio n. 10
0
 /**
  * Checks if the invocation of the method throws a SQLExceptio as expected.
  *
  * @param LOB the Object that implements the Blob interface
  * @param method the method that needs to be tested to ensure that it throws the correct exception
  * @return true If the method throws the SQLException required after the free method has been
  *     called on the LOB object
  */
 boolean checkIfMethodThrowsSQLException(Object LOB, Method method)
     throws IllegalAccessException, InvocationTargetException {
   try {
     method.invoke(LOB, getNullValues(method.getParameterTypes()));
   } catch (InvocationTargetException ite) {
     Throwable cause = ite.getCause();
     if (cause instanceof SQLException) {
       return ((SQLException) cause).getSQLState().equals("XJ215");
     }
     throw ite;
   }
   return false;
 }
 @Override
 public void exec() {
   if (mParams == null) {
     throw new IllegalArgumentException("Argument unmarshalling has not taken place yet");
   }
   try {
     mResult = mMethodHandle.invokeWithArguments(mParams);
   } catch (final InvocationTargetException e) {
     final Throwable cause = e.getCause();
     throw new MessagingException(cause != null ? cause : e);
   } catch (final Throwable e) {
     throw new MessagingException(e);
   }
 }
  /** {@inheritDoc} */
  @Override
  public void start() throws GridException {
    if (ctx.isEnterprise()) {
      Package pkg = getClass().getPackage();

      if (pkg == null)
        throw new GridException(
            "Internal error (package object was not found) for: " + getClass().getName());

      if (ctx.isEnterprise()) {
        try {
          Class<?> cls = Class.forName(pkg.getName() + ".GridEnterpriseSecureSessionHandler");

          sesHnd =
              (GridSecureSessionHandler)
                  cls.getConstructor(GridSecureSessionSpi[].class)
                      .newInstance(new Object[] {getProxies()});
        } catch (ClassNotFoundException e) {
          throw new GridException(
              "Failed to create enterprise secure session handler (implementing class "
                  + "was not found)",
              e);
        } catch (InvocationTargetException e) {
          throw new GridException(
              "Failed to create enterprise secure session handler (target constructor "
                  + "has thrown an exception",
              e.getCause());
        } catch (InstantiationException e) {
          throw new GridException(
              "Failed to create enterprise secure session handler (object cannot be "
                  + "instantiated)",
              e);
        } catch (NoSuchMethodException e) {
          throw new GridException(
              "Failed to create enterprise secure session handler (target constructor "
                  + "could not be found)",
              e);
        } catch (IllegalAccessException e) {
          throw new GridException(
              "Failed to create enterprise secure session handler (object access is not"
                  + " allowed)",
              e);
        }
      }
    } else sesHnd = new GridCommunitySecureSessionHandler();

    startSpi();

    if (log.isDebugEnabled()) log.debug(startInfo());
  }
Esempio n. 13
0
 /**
  * Invokes a method on a target object, and maps any exceptions to JEQL standard exception
  * classes.
  *
  * @param method
  * @param arg0
  * @param args
  * @return
  * @throws ExecutionException
  */
 public static Object invoke(Method method, Object target, Object[] args) {
   Object result = null;
   try {
     result = method.invoke(target, args);
   } catch (InvocationTargetException ex) {
     Throwable t = ex.getCause();
     if (t instanceof JeqlException) throw (JeqlException) t;
     throwExecutionException(method, args, t);
   } catch (Exception ex) {
     // System.out.println(ex.getMessage());
     throwExecutionException(method, args, ex);
   }
   return result;
 }
    public void invoke(MethodInvocation invocation) throws Throwable {
      Method targetMethod = locateMethod(invocation);
      if (targetMethod == null) {
        return;
      }

      Object returnValue;
      try {
        returnValue = targetMethod.invoke(invocation.getDelegate(), invocation.getParameters());
      } catch (InvocationTargetException e) {
        throw e.getCause();
      }

      invocation.setResult(returnValue);
    }
Esempio n. 15
0
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   final String methodName = method.getName();
   if (methodName.equals("getAttribute")) {
     return getAttribute((ObjectName) args[0], (String) args[1]);
   } else if (methodName.equals("getAttributes")) {
     return getAttributes((ObjectName) args[0], (String[]) args[1]);
   } else if (methodName.equals("flush")) {
     flush();
     return null;
   } else {
     try {
       return method.invoke(conn, args);
     } catch (InvocationTargetException e) {
       throw e.getCause();
     }
   }
 }
 @Override
 public Result attempt(
     final List<AvailObject> args, final Interpreter interpreter, final boolean skipReturnCheck) {
   assert args.size() == 4;
   final A_BasicObject methodPojo = args.get(0);
   final A_Tuple methodArgs = args.get(1);
   final A_Tuple marshaledTypePojos = args.get(2);
   final A_Type expectedType = args.get(3);
   // Marshal the arguments and invoke the method.
   final Method method = (Method) methodPojo.javaObject();
   assert method != null;
   final Object[] marshaledArgs = new Object[methodArgs.tupleSize()];
   try {
     for (int i = 0; i < marshaledArgs.length; i++) {
       final Class<?> marshaledType = (Class<?>) marshaledTypePojos.tupleAt(i + 1).javaObject();
       marshaledArgs[i] = methodArgs.tupleAt(i + 1).marshalToJava(marshaledType);
     }
   } catch (final MarshalingException e) {
     return interpreter.primitiveFailure(
         PojoDescriptor.newPojo(
             RawPojoDescriptor.identityWrap(e), PojoTypeDescriptor.forClass(e.getClass())));
   }
   final Object result;
   try {
     result = method.invoke(null, marshaledArgs);
   } catch (final InvocationTargetException e) {
     final Throwable cause = e.getCause();
     return interpreter.primitiveFailure(
         PojoDescriptor.newPojo(
             RawPojoDescriptor.identityWrap(cause),
             PojoTypeDescriptor.forClass(cause.getClass())));
   } catch (final Throwable e) {
     // This is an unexpected failure.
     error("reflected method call unexpectedly failed");
     throw new Error();
   }
   if (result == null) {
     return interpreter.primitiveSuccess(PojoDescriptor.nullObject());
   }
   final AvailObject unmarshaled = PojoTypeDescriptor.unmarshal(result, expectedType);
   return interpreter.primitiveSuccess(unmarshaled);
 }
 /**
  * Build the documentation, as specified by the given XML element.
  *
  * @param node the XML element that specifies which component to document.
  * @param contentTree content tree to which the documentation will be added
  */
 protected void build(XMLNode node, Content contentTree) {
   String component = node.name;
   try {
     invokeMethod(
         "build" + component,
         new Class<?>[] {XMLNode.class, Content.class},
         new Object[] {node, contentTree});
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
     configuration.root.printError("Unknown element: " + component);
     throw new DocletAbortException(e);
   } catch (InvocationTargetException e) {
     throw new DocletAbortException(e.getCause());
   } catch (Exception e) {
     e.printStackTrace();
     configuration.root.printError(
         "Exception " + e.getClass().getName() + " thrown while processing element: " + component);
     throw new DocletAbortException(e);
   }
 }
Esempio n. 18
0
 /**
  * ** Invokes this MethodAction with the currently specified array/list of arguments ** @return
  * The return Object
  */
 public Object invoke() throws Throwable {
   this.error = null;
   this.rtnValue = null;
   try {
     if (this.method instanceof Constructor) {
       this.rtnValue = ((Constructor) this.method).newInstance(this.getArgs());
     } else if (this.method instanceof Method) {
       this.rtnValue = ((Method) this.method).invoke(this.getTarget(), this.getArgs());
     }
     return this.rtnValue;
   } catch (InvocationTargetException ite) {
     this.error = ite.getCause();
     if (this.error == null) {
       this.error = ite;
     }
     throw this.error;
   } catch (Throwable t) { // trap any remaining method invocation error
     this.error = t;
     throw this.error;
   }
 }
Esempio n. 19
0
  public static void main(String[] args) throws Exception {
    int tests = 0;
    int passed = 0;
    Class testClass = Class.forName(args[0]);
    for (Method m : testClass.getDeclaredMethods()) {
      if (m.isAnnotationPresent(Test.class)) {
        tests++;
        try {
          m.invoke(null);
          passed++;
        } catch (InvocationTargetException wrappedExc) {
          Throwable exc = wrappedExc.getCause();
          System.out.println(m + " failed: " + exc);
        } catch (Exception exc) {
          System.out.println("INVALID @Test: " + m);
        }
      }

      // Array ExceptionTest processing code - Page 174
      if (m.isAnnotationPresent(ExceptionTest.class)) {
        tests++;
        try {
          m.invoke(null);
          System.out.printf("Test %s failed: no exception%n", m);
        } catch (Throwable wrappedExc) {
          Throwable exc = wrappedExc.getCause();
          Class<? extends Exception>[] excTypes = m.getAnnotation(ExceptionTest.class).value();
          int oldPassed = passed;
          for (Class<? extends Exception> excType : excTypes) {
            if (excType.isInstance(exc)) {
              passed++;
              break;
            }
          }
          if (passed == oldPassed) System.out.printf("Test %s failed: %s %n", m, exc);
        }
      }
    }
    System.out.printf("Passed: %d, Failed: %d%n", passed, tests - passed);
  }
Esempio n. 20
0
 /**
  * If the causal chain has a sun.jvm.hotspot.runtime.VMVersionMismatchException, attempt to load
  * VirtualMachineImpl class for target VM version.
  */
 protected static Class handleVMVersionMismatch(InvocationTargetException ite) {
   Throwable cause = ite.getCause();
   if (DEBUG) {
     System.out.println("checking for version mismatch...");
   }
   while (cause != null) {
     try {
       if (isVMVersionMismatch(cause)) {
         if (DEBUG) {
           System.out.println("Triggering cross VM version support...");
         }
         return loadVirtualMachineImplClass(getVMVersion(cause));
       }
     } catch (Exception exp) {
       if (DEBUG) {
         System.out.println("failed to load VirtualMachineImpl class");
         exp.printStackTrace();
       }
       return null;
     }
     cause = cause.getCause();
   }
   return null;
 }
Esempio n. 21
0
  /**
   * オブジェクトのメソッドを呼び出す
   *
   * @param Object o メソッドを呼び出したいオブジェクト
   * @param String methodName 呼び出したいメソッドの名前
   * @param Object... args メソッドのパラメータ
   * @throws NoSuchMethodException
   */
  public static Object invoke(Object o, String methodName, Object... args)
      throws SecurityException, ClassNotFoundException, NoSuchMethodException {
    StringBuffer tempMessage = new StringBuffer();
    Method method = null;

    //		//argsArray:メソッドの引数の型配列
    //		Class<?>[] argsArray = new Class<?>[args.length];
    //		for(int i = 0; i < args.length; i++){
    //			argsArray[i] = getClassObject(args[i]);
    //			//スーパークラスを引数にとれるように修正
    //		}
    //		try {
    //			method = o.getClass().getMethod(methodName, argsArray);
    //		} catch (NoSuchMethodException e) {
    //			try{
    //				method = o.getClass().getDeclaredMethod(methodName, argsArray);
    //			}catch (NoSuchMethodException e2) {
    //					message = "NoSuchMethodException\r\n";
    //					display.append(message);
    //			}
    //		}
    /////////////////////////////////////////
    // argsArray:メソッドの引数の型配列
    Class<?>[] argsArray = new Class<?>[args.length];
    for (int i = 0; i < args.length; i++) {
      argsArray[i] = getClassObject(args[i]);
    }
    method = getMethod(o, args, methodName, argsArray);

    ////////////////////////////////////////
    tempMessage.append("method: " + method.getName() + " is called.\r\n");

    if (Modifier.isPrivate(method.getModifiers())) {
      method.setAccessible(true);
    }
    if (o.equals(null)) {
      if (Modifier.isStatic(method.getModifiers()) == false) {
        throw new NoSuchMethodException();
      }
    }

    try {
      Type returnType = method.getGenericReturnType();
      tempMessage.append("return type: " + returnType.toString() + "\r\n");
      if (returnType.equals(Void.TYPE)) {
        tempMessage.append("return value: " + "なし\r\n");
      } else {
        tempMessage.append("return value: " + method.invoke(o, args).toString() + "\r\n");
      }
      message = tempMessage.toString();
      display.append(message);
      return method.invoke(o, args);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      message = tempMessage.append("IllegalArgumentException\r\n").toString();
      display.append(message);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
      message = tempMessage.append("IllegalAccessException\r\n").toString();
      display.append(message);
    } catch (InvocationTargetException e) {
      e.printStackTrace();
      tempMessage.append("InvocationTargetException\r\n");
      message = tempMessage.append(e.getCause().toString() + "\r\n").toString();
      display.append(message);
    }
    return null;
  }