Esempio n. 1
1
 /**
  * Factory method, equivalent to a "fromXML" for step creation. Looks for a class with the same
  * name as the XML tag, with the first letter capitalized. For example, <call /> is
  * abbot.script.Call.
  */
 public static Step createStep(Resolver resolver, Element el) throws InvalidScriptException {
   String tag = el.getName();
   Map attributes = createAttributeMap(el);
   String name = tag.substring(0, 1).toUpperCase() + tag.substring(1);
   if (tag.equals(TAG_WAIT)) {
     attributes.put(TAG_WAIT, "true");
     name = "Assert";
   }
   try {
     name = "abbot.script." + name;
     Log.debug("Instantiating " + name);
     Class cls = Class.forName(name);
     try {
       // Steps with contents require access to the XML element
       Class[] argTypes = new Class[] {Resolver.class, Element.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, el, attributes});
     } catch (NoSuchMethodException nsm) {
       // All steps must support this ctor
       Class[] argTypes = new Class[] {Resolver.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, attributes});
     }
   } catch (ClassNotFoundException cnf) {
     String msg = Strings.get("step.unknown_tag", new Object[] {tag});
     throw new InvalidScriptException(msg);
   } catch (InvocationTargetException ite) {
     Log.warn(ite);
     throw new InvalidScriptException(ite.getTargetException().getMessage());
   } catch (Exception exc) {
     Log.warn(exc);
     throw new InvalidScriptException(exc.getMessage());
   }
 }
Esempio n. 2
0
 /** evaluate the link function */
 public static Data link(VMethod m, Object[] o) throws VisADException {
   Data ans = null;
   if (o != null) {
     for (int i = 0; i < o.length; i++) {
       // convert VRealTypes to RealTypes
       if (o[i] instanceof VRealType) {
         o[i] = ((VRealType) o[i]).getRealType();
       }
     }
   }
   try {
     ans = (Data) FormulaUtil.invokeMethod(m.getMethod(), o);
   } catch (ClassCastException exc) {
     if (FormulaVar.DEBUG) exc.printStackTrace();
     throw new VisADException("Link error: invalid linked method");
   } catch (IllegalAccessException exc) {
     if (FormulaVar.DEBUG) exc.printStackTrace();
     throw new VisADException("Link error: cannot access linked method");
   } catch (IllegalArgumentException exc) {
     if (FormulaVar.DEBUG) exc.printStackTrace();
     throw new VisADException("Link error: bad method argument");
   } catch (InvocationTargetException exc) {
     if (FormulaVar.DEBUG) exc.getTargetException().printStackTrace();
     throw new VisADException("Link error: linked method threw an exception");
   }
   if (ans == null) {
     throw new VisADException("Link error: linked method returned null data");
   }
   return ans;
 }
Esempio n. 3
0
 /**
  * This method is called when 'Finish' button is pressed in the wizard. We will create an
  * operation and run it using wizard as execution context.
  */
 public boolean performFinish() {
   final String containerName = page.getContainerName();
   final String fileName = page.getFileName();
   IRunnableWithProgress op =
       new IRunnableWithProgress() {
         public void run(IProgressMonitor monitor) throws InvocationTargetException {
           try {
             doFinish(containerName, fileName, monitor);
           } catch (CoreException e) {
             throw new InvocationTargetException(e);
           } finally {
             monitor.done();
           }
         }
       };
   try {
     getContainer().run(true, false, op);
   } catch (InterruptedException e) {
     return false;
   } catch (InvocationTargetException e) {
     Throwable realException = e.getTargetException();
     MessageDialog.openError(getShell(), "Error", realException.getMessage());
     return false;
   }
   return true;
 }
Esempio n. 4
0
  private void bindEventHandler(
      Component componentRoot, Object controller, Method method, UiHandler eventListener) {
    String componentId = eventListener.value();
    Component component = Clara.findComponentById(componentRoot, componentId);
    if (component == null) {
      throw new BinderException("No component found for id: " + componentId + ".");
    }

    Class<?> eventType =
        (method.getParameterTypes().length > 0 ? method.getParameterTypes()[0] : null);
    if (eventType == null) {
      throw new BinderException("Couldn't figure out event type for method " + method + ".");
    }

    Method addListenerMethod = getAddListenerMethod(component.getClass(), eventType);
    if (addListenerMethod != null) {
      try {
        Object listener =
            createListenerProxy(
                addListenerMethod.getParameterTypes()[0], eventType, method, controller);
        addListenerMethod.invoke(component, listener);
        // TODO exception handling
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
Esempio n. 5
0
  private void bindDataSource(
      Component componentRoot, Object controller, Method method, UiDataSource dataSource) {
    String componentId = dataSource.value();
    Component component = Clara.findComponentById(componentRoot, componentId);
    Class<?> dataSourceClass = method.getReturnType();

    try {
      // Vaadin data model consists of Property/Item/Container
      // objects and each of them have a Viewer interface.
      if (isContainer(dataSourceClass) && component instanceof Container.Viewer) {
        ((Container.Viewer) component)
            .setContainerDataSource((Container) method.invoke(controller));
      } else if (isProperty(dataSourceClass) && component instanceof Property.Viewer) {
        ((Property.Viewer) component).setPropertyDataSource((Property) method.invoke(controller));
      } else if (isItem(dataSourceClass) && component instanceof Item.Viewer) {
        ((Item.Viewer) component).setItemDataSource((Item) method.invoke(controller));
      }
      // TODO exception handling
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
Esempio n. 6
0
  /**
   * Set the object to be edited.
   *
   * @param value The object to be edited.
   */
  public void setObject(Object value) {
    if (!(_type.isInstance(value))) {
      throw new IllegalArgumentException(value.getClass() + " is not of type " + _type);
    }
    _value = value;

    // Disable event generation.
    _squelchChangeEvents = true;

    // Iterate over each property, doing a lookup on the associated editor
    // and setting the editor's value to the value of the property.
    Iterator it = _prop2Editor.keySet().iterator();
    while (it.hasNext()) {
      PropertyDescriptor desc = (PropertyDescriptor) it.next();
      PropertyEditor editor = (PropertyEditor) _prop2Editor.get(desc);
      Method reader = desc.getReadMethod();
      if (reader != null) {
        try {
          Object val = reader.invoke(_value, null);
          editor.setValue(val);
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        } catch (InvocationTargetException ex) {
          ex.getTargetException().printStackTrace();
        }
      }
    }

    // Enable event generation.
    _squelchChangeEvents = false;
  }
Esempio n. 7
0
  /**
   * Send an event to all registered listeners, except the named one.
   *
   * @param event the event to be sent: public void method_name( event_class event)
   */
  public void sendEventExcludeSource(java.util.EventObject event) {
    if (!hasListeners) {
      return;
    }

    Object source = event.getSource();
    Object[] args = new Object[1];
    args[0] = event;

    // send event to all listeners except the source
    ListIterator iter = listeners.listIterator();
    while (iter.hasNext()) {
      Object client = iter.next();
      if (client == source) {
        continue;
      }

      try {
        method.invoke(client, args);
      } catch (IllegalAccessException e) {
        iter.remove();
        System.err.println("ListenerManager IllegalAccessException = " + e);
      } catch (IllegalArgumentException e) {
        iter.remove();
        System.err.println("ListenerManager IllegalArgumentException = " + e);
      } catch (InvocationTargetException e) {
        iter.remove();
        System.err.println("ListenerManager InvocationTargetException on " + method);
        System.err.println("   threw exception " + e.getTargetException());
        e.printStackTrace();
      }
    }
  }
Esempio n. 8
0
  /**
   * Returns an instance of a proxy class for the specified interfaces that dispatches method
   * invocations to the specified invocation handler. This method is equivalent to:
   *
   * <pre>
   *     Proxy.getProxyClass(loader, interfaces).
   *         getConstructor(new Class[] { InvocationHandler.class }).
   *         newInstance(new Object[] { handler });
   * </pre>
   *
   * <p>{@code Proxy.newProxyInstance} throws {@code IllegalArgumentException} for the same reasons
   * that {@code Proxy.getProxyClass} does.
   *
   * @param loader the class loader to define the proxy class
   * @param interfaces the list of interfaces for the proxy class to implement
   * @param h the invocation handler to dispatch method invocations to
   * @return a proxy instance with the specified invocation handler of a proxy class that is defined
   *     by the specified class loader and that implements the specified interfaces
   * @throws IllegalArgumentException if any of the restrictions on the parameters that may be
   *     passed to {@code getProxyClass} are violated
   * @throws NullPointerException if the {@code interfaces} array argument or any of its elements
   *     are {@code null}, or if the invocation handler, {@code h}, is {@code null}
   */
  public static Object newProxyInstance(
      ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
      throws IllegalArgumentException {
    if (h == null) {
      throw new NullPointerException();
    }

    /*
     * Look up or generate the designated proxy class.
     */
    Class<?> cl = getProxyClass(loader, interfaces);

    /*
     * Invoke its constructor with the designated invocation handler.
     */
    try {
      Constructor cons = cl.getConstructor(constructorParams);
      return cons.newInstance(new Object[] {h});
    } catch (NoSuchMethodException e) {
      throw new InternalError(e.toString());
    } catch (IllegalAccessException e) {
      throw new InternalError(e.toString());
    } catch (InstantiationException e) {
      throw new InternalError(e.toString());
    } catch (InvocationTargetException e) {
      throw new InternalError(e.toString());
    }
  }
Esempio n. 9
0
 /**
  * Insert the source code details, if available.
  *
  * @param ped The given program element.
  */
 public void addSourcePosition(ProgramElementDoc ped, int indent) {
   if (!addSrcInfo) return;
   if (JDiff.javaVersion.startsWith("1.1")
       || JDiff.javaVersion.startsWith("1.2")
       || JDiff.javaVersion.startsWith("1.3")) {
     return; // position() only appeared in J2SE1.4
   }
   try {
     // Could cache the method for improved performance
     Class c = ProgramElementDoc.class;
     Method m = c.getMethod("position", null);
     Object sp = m.invoke(ped, null);
     if (sp != null) {
       for (int i = 0; i < indent; i++) outputFile.print(" ");
       outputFile.println("src=\"" + sp + "\"");
     }
   } catch (NoSuchMethodException e2) {
     System.err.println("Error: method \"position\" not found");
     e2.printStackTrace();
   } catch (IllegalAccessException e4) {
     System.err.println("Error: class not permitted to be instantiated");
     e4.printStackTrace();
   } catch (InvocationTargetException e5) {
     System.err.println("Error: method \"position\" could not be invoked");
     e5.printStackTrace();
   } catch (Exception e6) {
     System.err.println("Error: ");
     e6.printStackTrace();
   }
 }
  private BrowserLauncher createBrowserLauncher(
      Class c, String browserStartCommand, String sessionId, SeleneseQueue queue) {
    try {
      BrowserLauncher browserLauncher;
      if (null == browserStartCommand) {
        Constructor ctor = c.getConstructor(new Class[] {int.class, String.class});
        Object[] args = new Object[] {new Integer(server.getPort()), sessionId};
        browserLauncher = (BrowserLauncher) ctor.newInstance(args);
      } else {
        Constructor ctor = c.getConstructor(new Class[] {int.class, String.class, String.class});
        Object[] args =
            new Object[] {
              new Integer(SeleniumServer.getPortDriversShouldContact()),
              sessionId,
              browserStartCommand
            };
        browserLauncher = (BrowserLauncher) ctor.newInstance(args);
      }

      if (browserLauncher instanceof SeleneseQueueAware) {
        ((SeleneseQueueAware) browserLauncher).setSeleneseQueue(queue);
      }

      return browserLauncher;
    } catch (InvocationTargetException e) {
      throw new RuntimeException(
          "failed to contruct launcher for "
              + browserStartCommand
              + "for"
              + e.getTargetException());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 11
0
  /**
   * 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. 12
0
  /** Reads the view from the specified uri. */
  @Override
  public void read(URI f, URIChooser chooser) throws IOException {
    try {
      final Drawing drawing = createDrawing();
      InputFormat inputFormat = drawing.getInputFormats().get(0);
      inputFormat.read(f, drawing, true);
      SwingUtilities.invokeAndWait(
          new Runnable() {

            @Override
            public void run() {
              view.getDrawing().removeUndoableEditListener(undo);
              view.setDrawing(drawing);
              view.getDrawing().addUndoableEditListener(undo);
              undo.discardAllEdits();
            }
          });
    } catch (InterruptedException e) {
      InternalError error = new InternalError();
      e.initCause(e);
      throw error;
    } catch (InvocationTargetException e) {
      InternalError error = new InternalError();
      e.initCause(e);
      throw error;
    }
  }
Esempio n. 13
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. 14
0
  public static final void fireEvent(GenericEvent e, Method m, Vector listeners)
      throws PropertyVetoException {
    Object[] snapshot = null;

    synchronized (listeners) {
      snapshot = new Object[listeners.size()];
      listeners.copyInto(snapshot);
    }

    // leighd 04/14/99 - modified for event debugging
    if (gDebugEvents) Engine.debugLog("Event : " + e.toString());

    Object params[] = new Object[] {e};

    for (int i = 0; i < snapshot.length; i++) {
      if ((e instanceof Consumable) && ((Consumable) e).isConsumed()) {
        // leighd 04/14/99
        // note that we don't catch the consumption of the
        // event until we've passed through the loop again,
        // so we reference i-1
        if (gDebugEvents) Engine.debugLog("Consumed By : " + snapshot[i - 1]);
        return;
      }
      try {
        m.invoke(snapshot[i], params);
      } catch (IllegalAccessException iae) {
        iae.printStackTrace();
      } catch (InvocationTargetException ite) {
        Throwable t = ite.getTargetException();
        if (t instanceof PropertyVetoException) throw ((PropertyVetoException) t);
        else t.printStackTrace();
      }
    }
  }
Esempio n. 15
0
 public void callValidator(final AQuery $, final Ajax ajax) throws VolleyError {
   Map<Annotation, java.lang.reflect.Method> method =
       ReflectUtils.getMethodsByAnnotation(Handler.class, getClass());
   for (Map.Entry<Annotation, java.lang.reflect.Method> entry : method.entrySet()) {
     try {
       entry
           .getValue()
           .invoke(
               this,
               ReflectUtils.fillParamsByAnnotations(
                   entry.getValue(),
                   new ReflectUtils.ParamInjector() {
                     @Override
                     public Object onInject(
                         Class paramType, List<? extends Annotation> annotations, int position) {
                       try {
                         return scanAnnotation($, paramType, annotations.get(0), ajax);
                       } catch (Exception e) {
                         $.log.i(e);
                         return null;
                       }
                     }
                   }));
     } catch (InvocationTargetException e) {
       if (e.getTargetException() instanceof VolleyError) {
         throw ((VolleyError) e.getTargetException());
       }
       $.log.i(e.getTargetException());
     } catch (Exception e) {
       $.log.i(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;
   }
 }
Esempio n. 17
0
 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
   try {
     String method = m.getName();
     if ("prepareStatement".equals(method) || "createStatement".equals(method))
       log.info("[SQL] >>> " + args[0]);
     return m.invoke(conn, args);
   } catch (InvocationTargetException e) {
     throw e.getTargetException();
   }
 }
Esempio n. 18
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);
   }
 }
Esempio n. 19
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);
     }
   }
 }
Esempio n. 20
0
 /** invoke the test method */
 protected void invokeTest() throws Throwable {
   Method method = this.methodNamed(this.getZName());
   try {
     method.invoke(this, new Object[0]);
   } catch (IllegalAccessException iae) {
     throw new RuntimeException("The method '" + method + "' (and its class) must be public.");
   } catch (InvocationTargetException ite) {
     ite.fillInStackTrace();
     throw ite.getTargetException();
   }
 }
Esempio n. 21
0
  /**
   * This creates a new <code>{@link Document}</code> from an existing <code>InputStream</code> by
   * letting a DOM parser handle parsing using the supplied stream.
   *
   * @param in <code>InputStream</code> to parse.
   * @param validate <code>boolean</code> to indicate if validation should occur.
   * @return <code>Document</code> - instance ready for use.
   * @throws IOException when I/O error occurs.
   * @throws JDOMException when errors occur in parsing.
   */
  public Document getDocument(InputStream in, boolean validate) throws IOException, JDOMException {

    try {
      // Load the parser class
      Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser");
      Object parser = parserClass.newInstance();

      // Set validation
      Method setFeature =
          parserClass.getMethod("setFeature", new Class[] {java.lang.String.class, boolean.class});
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/validation", new Boolean(validate)});

      // Set namespaces true
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/namespaces", new Boolean(true)});

      // Set the error handler
      if (validate) {
        Method setErrorHandler =
            parserClass.getMethod("setErrorHandler", new Class[] {ErrorHandler.class});
        setErrorHandler.invoke(parser, new Object[] {new BuilderErrorHandler()});
      }

      // Parse the document
      Method parse = parserClass.getMethod("parse", new Class[] {org.xml.sax.InputSource.class});
      parse.invoke(parser, new Object[] {new InputSource(in)});

      // Get the Document object
      Method getDocument = parserClass.getMethod("getDocument", null);
      Document doc = (Document) getDocument.invoke(parser, null);

      return doc;
    } catch (InvocationTargetException e) {
      Throwable targetException = e.getTargetException();
      if (targetException instanceof org.xml.sax.SAXParseException) {
        SAXParseException parseException = (SAXParseException) targetException;
        throw new JDOMException(
            "Error on line "
                + parseException.getLineNumber()
                + " of XML document: "
                + parseException.getMessage(),
            e);
      } else if (targetException instanceof IOException) {
        IOException ioException = (IOException) targetException;
        throw ioException;
      } else {
        throw new JDOMException(targetException.getMessage(), e);
      }
    } catch (Exception e) {
      throw new JDOMException(e.getClass().getName() + ": " + e.getMessage(), e);
    }
  }
 // todo: equals implementation
 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
   Object result;
   try {
     result = m.invoke(this, args);
   } catch (InvocationTargetException e) {
     throw e.getTargetException();
   } catch (Exception e) {
     throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
   } finally {
   }
   return result;
 }
  /**
   * 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. 24
0
 /** {@inheritDoc} */
 public void run(String[] args) {
   try {
     findMain(app).invoke(null, new Object[] {args});
   } catch (NoSuchMethodException e) {
     throw new RuntimeException("can not occur; checked in constructor");
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e);
   } catch (InvocationTargetException e) {
     Throwable t = e.getTargetException();
     if (t instanceof Error) throw (Error) t;
     throw new RuntimeException(t);
   }
 }
Esempio n. 25
0
 /** Try to create a Java object using a one-string-param constructor. */
 public static Object newStringConstructor(String type, String param) throws Exception {
   Constructor c = Utils.getClass(type).getConstructor(String.class);
   try {
     return c.newInstance(param);
   } catch (InvocationTargetException e) {
     Throwable t = e.getTargetException();
     if (t instanceof Exception) {
       throw (Exception) t;
     } else {
       throw e;
     }
   }
 }
 @Override
 public T create() {
   Class<T> concreteClass = type.getConcreteClass();
   try {
     Constructor<T> declaredConstructor = concreteClass.getDeclaredConstructor();
     declaredConstructor.setAccessible(true);
     return declaredConstructor.newInstance();
   } catch (InvocationTargetException e) {
     throw UncheckedException.throwAsUncheckedException(e.getTargetException());
   } catch (Exception e) {
     throw UncheckedException.throwAsUncheckedException(e);
   }
 }
Esempio n. 27
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);
   }
 }
 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);
   }
 }
  /** {@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());
  }