Java Code Examples for java.lang.reflect.InvocationTargetException

The following are top voted examples for showing how to use java.lang.reflect.InvocationTargetException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: p1keyboard   File: ImprovedBluetoothDevice.java View source code Vote up 7 votes
public BluetoothSocket createRfcommSocket(int channel) throws Exception {
	if (_createRfcommSocket == null) 
		throw new NoSuchMethodException("createRfcommSocket");
	try {
		return (BluetoothSocket)_createRfcommSocket.invoke(mDevice, channel);
	} catch (InvocationTargetException tex) {
		if (tex.getCause() instanceof Exception)
			throw (Exception)tex.getCause();
		else
			throw tex;
	}
}
 
Example 2
Project: aws-toolkit-eclipse   File: DeployWizardApplicationSelectionPage.java View source code Vote up 6 votes
private IStatus testConnection() {
    try {
        wizardHandle.setMessage("", IStatus.OK);
        wizardHandle.run(true, false, new CheckAccountRunnable(elasticBeanstalkClient));
        wizardHandle.setMessage("", IStatus.OK);
        return Status.OK_STATUS;
    } catch (InvocationTargetException ite) {
        String errorMessage = "Unable to connect to AWS Elastic Beanstalk.  ";
        try {
            throw ite.getCause();
        } catch (AmazonServiceException ase) {
            errorMessage += "Make sure you've registered your AWS account for the AWS Elastic Beanstalk service.";
        } catch (AmazonClientException ace) {
            errorMessage += "Make sure your computer is connected to the internet, and any network firewalls or proxys are configured appropriately.";
        } catch (Throwable t) {}

        return new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, errorMessage, ite.getCause());
    } catch (InterruptedException e) {
        return Status.CANCEL_STATUS;
    }
}
 
Example 3
Project: richfaces   File: PropertyUtils.java View source code Vote up 6 votes
public static Object readPropertyValue(Object bean, PropertyDescriptor descriptor) throws Exception {
    Method readMethod = descriptor.getReadMethod();

    if (readMethod == null) {
        throw new NoSuchMethodException(MessageFormat.format("Read method for property ''{0}'' not found",
            descriptor.getName()));
    }

    try {
        return readMethod.invoke(bean);
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();

        if (cause instanceof Exception) {
            throw (Exception) cause;
        } else if (cause instanceof Error) {
            throw (Error) cause;
        } else {
            throw e;
        }
    }
}
 
Example 4
Project: assertj-db   File: Assertions_BytesContent_Test.java View source code Vote up 6 votes
/**
 * This method should throw an [email protected] AssertJDBException} when the [email protected] InputStream} throw an [email protected] IOException}
 * during the reading.
 * 
 * @throws Throwable
 */
@Test(expected = AssertJDBException.class)
public void should_throw_an_AssertJDBException_when_IOException_during_reading_and_closing() throws Throwable {
  InputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(new byte[0])) {

    @Override
    public synchronized int read() throws IOException {
      throw new IOException();
    }

    @Override
    public void close() throws IOException {
      throw new IOException();
    }
  };
  
  Class<?> assertionClass = Assertions.class;
  Method method = assertionClass.getDeclaredMethod("read", InputStream.class);
  method.setAccessible(true);
  try {
    method.invoke(null, inputStream);
  } catch (InvocationTargetException e) {
    throw e.getCause();
  }
}
 
Example 5
Project: eclipse-integration-commons   File: P2TransportService.java View source code Vote up 6 votes
private void convertException(InvocationTargetException e) throws CoreException {
	if (e.getCause() instanceof CoreException) {
		throw (CoreException) e.getCause();
	}
	else {
		throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, e.getCause().getMessage(),
				e.getCause()));
	}
}
 
Example 6
Project: hadoop_ekg   File: RetryInvocationHandler.java View source code Vote up 6 votes
private Object invokeMethod(Method method, Object[] args) throws Throwable {
  try {
    if (!method.isAccessible()) {
      method.setAccessible(true);
    }
    return method.invoke(implementation, args);
  } catch (InvocationTargetException e) {
    throw e.getCause();
  }
}
 
Example 7
Project: krypton   File: Decorators.java View source code Vote up 6 votes
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	try {
		log.debug("{}: {}", method.getName(), args);
		return method.invoke(anInstance, args);
	} catch (InvocationTargetException e) {
		throw e.getCause();
	}
}
 
Example 8
Project: processing-shellmaker   File: PApplet.java View source code Vote up 6 votes
void handle(Object[] args) {
  for (int i = 0; i < count; i++) {
    try {
      methods[i].invoke(objects[i], args);
    } catch (Exception e) {
      // check for wrapped exception, get root exception
      Throwable t;
      if (e instanceof InvocationTargetException) {
        InvocationTargetException ite = (InvocationTargetException) e;
        t = ite.getCause();
      } else {
        t = e;
      }
      // check for RuntimeException, and allow to bubble up
      if (t instanceof RuntimeException) {
        // re-throw exception
        throw (RuntimeException) t;
      } else {
        // trap and print as usual
        t.printStackTrace();
      }
    }
  }
}
 
Example 9
Project: tuprolog-5   File: PrimitiveInfo.java View source code Vote up 6 votes
/**
 * Evaluates the primitive as a predicate.
 * @throws Exception if invocation primitive failure
 */
public boolean evalAsPredicate(Struct g) throws Throwable {
	for (int i = 0; i < primitive_args.length; i++)
		primitive_args[i] = g.getArg(i);
	try {
		return ((Boolean) method.invoke(source, (Object[]) primitive_args)).booleanValue();
	} catch (InvocationTargetException e) {
		// throw new Exception(e.getCause());
		throw e.getCause();
	}
}
 
Example 10
Project: libreplan   File: ConcurrentModificationHandling.java View source code Vote up 6 votes
private static InvocationHandler handler(final Object toBeWraped,
        final String goToPage) {
    return new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method,
                Object[] args) throws Throwable {
            try {
                return method.invoke(toBeWraped, args);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause instanceof OptimisticLockingFailureException) {
                    OptimisticLockingFailureException optimisticLockingFailureException = (OptimisticLockingFailureException) cause;
                    ConcurrentModificationController.showException(
                            optimisticLockingFailureException, goToPage);
                }
                throw cause;
            }
        }
    };
}
 
Example 11
Project: c10n   File: C10NTest.java View source code Vote up 6 votes
@Test
public void cannotGetMessagesWhenConfigureHasNotBeenCalled() throws Throwable {
    thrown.expect(exceptionClassWithName(C10NException.class.getName()));
    thrown.expectMessage("C10N.configure()");
    URLClassLoader cl = (URLClassLoader) C10N.class.getClassLoader();
    Class<?> c10nClass = new URLClassLoader(cl.getURLs(), null).loadClass(C10N.class.getName());
    try {
        c10nClass.getMethod("get", new Class[]{Class.class}).invoke(null, Messages.class);
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}
 
Example 12
Project: probe   File: ViewProxyBuilder.java View source code Vote up 6 votes
private static RuntimeException launderCause(InvocationTargetException e) {
    final Throwable cause = e.getCause();

    // Errors should be thrown as they are.
    if (cause instanceof Error) {
        throw (Error) cause;
    }

    // RuntimeException can be thrown as-is.
    if (cause instanceof RuntimeException) {
        throw (RuntimeException) cause;
    }

    // Declared exceptions will have to be wrapped.
    throw new UndeclaredThrowableException(cause);
}
 
Example 13
Project: lettuce   File: PooledConnectionInvocationHandler.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {

    if (DISABLED_METHODS.contains(method.getName())) {
        throw new UnsupportedOperationException("Calls to " + method.getName() + " are not supported on pooled connections");
    }

    if (connection == null) {
        throw new RedisException("Connection is deallocated and cannot be used anymore.");
    }

    if (method.getName().equals("close")) {
        pool.freeConnection((T) proxy);
        return null;
    }

    Method targetMethod = methodCache.get(method);

    try {
        return targetMethod.invoke(connection, args);
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}
 
Example 14
Project: java-util   File: UrlInvocationHandler.java View source code Vote up 6 votes
protected static void checkForThrowable(Object object) throws Throwable
{
    if (object instanceof Throwable)
    {
        Throwable t;
        if (object instanceof InvocationTargetException)
        {
            InvocationTargetException i = (InvocationTargetException) object;
            t = i.getTargetException();
            if (t == null)
            {
                t = (Throwable) object;
            }
        }
        else
        {
            t = (Throwable) object;
        }

        t.fillInStackTrace();
        throw t;
    }
}
 
Example 15
Project: webdriver-extensions   File: UnhandledAlertHandlingWrapper.java View source code Vote up 6 votes
@Override
protected Object onErrorGlobal(AbstractWrapper target, Method method, InvocationTargetException e, Object[] args) throws Throwable {
  Throwable te = e.getTargetException();
  if (te instanceof UnhandledAlertException) {
    handleUnhandledAlert((UnhandledAlertException) te);
    // try again
    try {
      return callMethodGlobal(target, method, args);
    } catch (InvocationTargetException e1) {
      throw Throwables.propagate(e1.getTargetException());
    }
  }
  throw Throwables.propagate(te);
}
 
Example 16
Project: ews-java-api   File: TestUtils.java View source code Vote up 6 votes
/**
 * Check that class has only one private constructor without parameters that throws exception during
 * instantiation. It's necessary for util-classes.
 *
 * @param utilClass util-class
 * @throws Throwable exception during instantiation
 */
public static void checkUtilClassConstructor(final Class<?> utilClass) throws Throwable {
  // Check count of available constructors.
  final Constructor<?>[] constructors = utilClass.getDeclaredConstructors();
  Assert.assertEquals(1, constructors.length);

  // Check accessibility.
  final Constructor<?> constructor = constructors[0];
  Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers()));

  // Try to create instance.
  constructor.setAccessible(true);
  try {
    constructor.newInstance();
  } catch (final InvocationTargetException ex) {
    throw ex.getTargetException();
  }

  // We should never get this situation.
  Assert.fail();
}
 
Example 17
Project: ezdb   File: TestEzRocksDbJni.java View source code Vote up 6 votes
@Test
public void testVariationsOfDatasetNormal()
		throws IllegalArgumentException, IllegalAccessException {
	for (Method m : getClass().getDeclaredMethods()) {
		try {
			if (m.getAnnotation(Test.class) != null
					&& !m.getName().startsWith("testVariationsOfDataset")) {
				// System.out.println(m.getName());
				m.invoke(this);
			}
		} catch (InvocationTargetException t) {
			throw new RuntimeException("at: " + m.getName(),
					t.getTargetException());
		}
	}
}
 
Example 18
Project: hibhik   File: CustomGenericLoggingHandler.java View source code Vote up 6 votes
/**
 * Original method shows big error about unsupported feature,
 * but this can be silently ignored (when orginal non-proxied datasource is used no errors appear).
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    try {
        Object r = method.invoke(target, args);
        if (method.getName().equals("prepareCall") || method.getName().equals("prepareStatement"))
            r = wrap(r, (String) args[0]);
        else
            r = wrap(r, null);
        return r;
    } catch (InvocationTargetException te) {
    	if (te.getTargetException() == null) {
            LogUtils.handleException(te, ConnectionLogger.getLogger(), LogUtils.createLogEntry(method, null, null, null));
    	} else {
    		Throwable cause = te.getTargetException();
    		if (cause instanceof java.sql.SQLFeatureNotSupportedException) {
    			ConnectionLogger.getLogger().info("Unsupported SQL feature [" + method.getName() 
    					+ "] called with arguments " + Arrays.toString(args));
    			throw cause; // gets swallowed? does not appear further in logging ...
    		} else {
                LogUtils.handleException(cause, ConnectionLogger.getLogger(), LogUtils.createLogEntry(method, null, null, null));
    		}
    	}
    } catch (Throwable t) {
        LogUtils.handleException(t, ConnectionLogger.getLogger(), LogUtils.createLogEntry(method, null, null, null));
    }
    return null;
}
 
Example 19
Project: NemoVelo   File: WrapperBase.java View source code Vote up 6 votes
public Object invoke(Object proxy, Method method,
		Object[] args) throws Throwable {
	Object result = null;

	try {
		result = method.invoke(invokeOn, args);
		
		if (result != null) {
			result = proxyIfInterfaceIsJdbc(result, 
					result.getClass());
		}
	} catch (InvocationTargetException e) {
		if (e.getTargetException() instanceof SQLException) {
			checkAndFireConnectionError((SQLException) e
					.getTargetException());
		} else {
			throw e;
		}
	}

	return result;
}
 
Example 20
Project: tuprolog-5   File: PrimitiveManager.java View source code Vote up 6 votes
public boolean evalAsDirective(Struct d) {
	PrimitiveInfo pd = ((Struct) identifyDirective(d)).getPrimitive();
	if (pd != null) {
		try {
			return pd.evalAsDirective(d);
		} catch (InvocationTargetException ite) {
			Throwable t = ite.getTargetException();
			engine.warn("An exception occurred during the execution of the " +
					    d.getPredicateIndicator() + " directive:\n" + t.getMessage());
			return false;
		} catch (IllegalAccessException e) {
			engine.warn("Cannot access the method defining the" +
				        d.getPredicateIndicator() + " directive.\n");
			return false;
		}
	} else {
		engine.warn("The directive " + d.getPredicateIndicator() + " is unknown.");
		return false;
	}
}
 
Example 21
Project: erlide   File: ExceptionHandler.java View source code Vote up 6 votes
protected void perform(final InvocationTargetException e,
        final Shell shell, final String title, final String message) {
    final Throwable target = e.getTargetException();
    if (target instanceof CoreException) {
        perform((CoreException) target, shell, title, message);
    } else {
        ErlideUIPlugin.log(e);
        if (e.getMessage() != null && e.getMessage().length() > 0) {
            displayMessageDialog(e.getMessage(), shell, title, message);
        } else {
            displayMessageDialog(target.getMessage(), shell, title, message);
        }
    }
}
 
Example 22
Project: spring-modules-jcr   File: JcrTemplate.java View source code Vote up 6 votes
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	// Invocation on Session interface (or vendor-specific
	// extension) coming in...

	if (method.getName().equals("equals")) {
		// Only consider equal when proxies are identical.
		return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
	}
	else if (method.getName().equals("hashCode")) {
		// Use hashCode of session proxy.
		return new Integer(hashCode());
	}
	else if (method.getName().equals("logout")) {
		// Handle close method: suppress, not valid.
		return null;
	}

	// Invoke method on target Session.
	try {
		Object retVal = method.invoke(this.target, args);

		// TODO: watch out for Query returned
		/*
		 * if (retVal instanceof Query) { prepareQuery(((Query)
		 * retVal)); }
		 */
		return retVal;
	}
	catch (InvocationTargetException ex) {
		throw ex.getTargetException();
	}
}
 
Example 23
Project: Banc   File: WrapperBase.java View source code Vote up 6 votes
public Object invoke(Object proxy, Method method,
		Object[] args) throws Throwable {
	Object result = null;

	try {
		result = method.invoke(invokeOn, args);
		
		if (result != null) {
			result = proxyIfInterfaceIsJdbc(result, 
					result.getClass());
		}
	} catch (InvocationTargetException e) {
		if (e.getTargetException() instanceof SQLException) {
			checkAndFireConnectionError((SQLException) e
					.getTargetException());
		} else {
			throw e;
		}
	}

	return result;
}
 
Example 24
Project: JBound   File: Runner.java View source code Vote up 6 votes
private void acceptOrRethrow(final AccessibleObject context, final InvocationTargetException ite)
{

    final Throwable iteCause = ite.getCause();

    if (iteCause == null)
    {
        // this is a problem with JBound doing a particular exercise
        ite.printStackTrace();
        return;
    }

    if (iteCause.getMessage() != null)
    {
        // we got an exception but it has a message, so it is probably a
        // user crafted one, hence we accept it silently
        return;
    }

    final String contextAsString = context.toString();

    if (accepted.contains(contextAsString))
    {
        // we have be told to accept this as a source of generic exceptions
        return;
    }

    // this is an exception without a message, so most probably a generic
    // one
    final AssertionError assertionError = new AssertionError("Received a generic " + iteCause.getClass()
                                                             + " when calling: " + contextAsString);

    assertionError.initCause(iteCause);
    throw assertionError;
}
 
Example 25
Project: lcm   File: ObjectRecorder.java View source code Vote up 6 votes
/**
 * Makes a record of the state of the object specified in the constructor. The
 * new record is stored in a RingBuffer and contains all retrieveable values
 * of the Object specified in the constructor. Reflection is used to get the
 * values. If a field is private it's value is tried to be taken from the
 * Object by invoking a getter - method conform with the bean - specification:
 * The name of the method has to be "get" followed by the name of the field
 * with first letter upper case.
 */
public void inspect() {
  final ObjectInspection newentry = new ObjectInspection();
  for (final Field mField : this.m_fields) {
    if (ObjectRecorder.VERBOSE) {
      System.out.println(this.getClass().getName() + " inpspecting " + mField.getName() + " of "
          + this.m_toinspect.getClass().getName() + ".");
    }
    try {
      mField.setAccessible(true);
      newentry.add(mField.get(this.m_toinspect));
    } catch (final IllegalAccessException e) {
      if (ObjectRecorder.VERBOSE) {
        System.err.println(this.getClass().getName() + ".inspect(): No public access to "
            + mField.getName() + " of " + this.m_toinspect.getClass().getName());
      }
      // Try to invoke bean- conform getter method.
      String fieldname = mField.getName();
      final char[] fieldnm = fieldname.toCharArray();
      fieldnm[0] = Character.toUpperCase(fieldnm[0]);
      fieldname = new String(fieldnm);
      final String methodname = new StringBuffer("get").append(fieldname).toString();
      // name of method constructed. Now invoke it.
      try {
        final Method toinvoke = this.m_toinspect.getClass().getDeclaredMethod(methodname,
            new Class[] {});
        newentry.add(toinvoke.invoke(this.m_toinspect, new Object[] {}));

      } catch (final NoSuchMethodException f) {
        if (ObjectRecorder.VERBOSE) {
          System.err.println(this.getClass().getName() + ".inspect(): Failure at getting field "
              + mField.getName() + " by trying to invoke a method: " + methodname);
        }
      } catch (final SecurityException g) {
        g.printStackTrace();
      } catch (final IllegalAccessException h) {
        h.printStackTrace();
      } catch (final InvocationTargetException l) {
        l.printStackTrace();
      }
    }
  }
  this.m_buffer.add(newentry);
  this.fireChange();
}
 
Example 26
Project: property-db   File: Robot.java View source code Vote up 6 votes
/** [email protected]} 
 * Waits until all events currently on the event queue have been processed.
 * @throws  IllegalThreadStateException if called on the AWT event dispatching thread
 */
public synchronized void waitForIdle() {
    checkNotDispatchThread();
    // post a dummy event to the queue so we know when
    // all the events before it have been processed
    try {
        SunToolkit.flushPendingEvents();
        EventQueue.invokeAndWait( new Runnable() {
                                        public void run() {
                                            // dummy implementation
                                        }
                                    } );
    } catch(InterruptedException ite) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ite.printStackTrace();
    } catch(InvocationTargetException ine) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ine.printStackTrace();
    }
}
 
Example 27
Project: rabbitmq-java-client   File: JSONUtil.java View source code Vote up 6 votes
/**
    * Ignores reflection exceptions while using reflection to fill
    * public fields and Bean properties of the target object from the
    * source Map.
    */
   public static void tryFill(Object target, Map<String, Object> source) {
try {
    fill(target, source);
} catch (IntrospectionException ie) {
    ie.printStackTrace();
} catch (IllegalAccessException iae) {
    iae.printStackTrace();
} catch (InvocationTargetException ite) {
    ite.printStackTrace();
}
   }
 
Example 28
Project: JDK   File: Robot.java View source code Vote up 6 votes
/**
 * Waits until all events currently on the event queue have been processed.
 * @throws  IllegalThreadStateException if called on the AWT event dispatching thread
 */
public synchronized void waitForIdle() {
    checkNotDispatchThread();
    // post a dummy event to the queue so we know when
    // all the events before it have been processed
    try {
        SunToolkit.flushPendingEvents();
        EventQueue.invokeAndWait( new Runnable() {
                                        public void run() {
                                            // dummy implementation
                                        }
                                    } );
    } catch(InterruptedException ite) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ite.printStackTrace();
    } catch(InvocationTargetException ine) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ine.printStackTrace();
    }
}
 
Example 29
Project: neo4j-jdbc   File: CallProxy.java View source code Vote up 6 votes
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
    if (!method.getDeclaringClass().equals(Object.class))
    {
        String call = method.getDeclaringClass().getSimpleName()+"."+method.getName()+"(";
        if (args != null)
        {
            String comma = "";
            for (Object arg : args)
            {
                call+= comma + (arg == null ? "null": arg.toString());
                comma = ", ";
            }
        }
        call+=")";

        log(call);
        try
        {
            final Object result = method.invoke(next, args);
            if (!method.getReturnType().equals(Void.TYPE))
                log("->"+result+"\n");
            return result;
        } catch (InvocationTargetException e)
        {
            StringWriter str = new StringWriter();
            PrintWriter print = new PrintWriter(str, true);
            e.printStackTrace(print);
            throw e.getTargetException();
        }
    } else
        return method.invoke(next, args);
}
 
Example 30
Project: solmix   File: DataUtils.java View source code Vote up 6 votes
public static Map<String, Object> annotationFilter(Object bean, Class annotationClass) throws Exception {
    if (bean == null)
        return null;
    // if ( bean.getClass().isAnnotation() != true )
    // return null;
    Field[] _fields = bean.getClass().getDeclaredFields();
    if (_fields == null)
        return null;
    Map<String, Object> res = new HashMap<String, Object>();
    for (Field f : _fields) {
        if (f.getAnnotation(annotationClass) != null) {
            Map<String, PropertyDescriptor> properties = getPropertyDescriptors(bean);
            String property = f.getName();
            PropertyDescriptor pd = properties.get(property);
            Method method = pd.getReadMethod();
            if (method != null)
                try {
                    Object value = method.invoke(bean);
                    if (value != null)
                        res.put(property, value);
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
        }

    }
    return res;
}
 
Example 31
Project: jprol   File: PredicateProcessor.java View source code Vote up 6 votes
/**
 * Execute an evaluable predicate linked with the processor
 *
 * @param goal the goal which contain the predicate, must not be null
 * @param predicate the predicate which linked with the processor, must not be
 * null
 * @return the term as the result of the processing
 */
public final Term executeEvaluable(final Goal goal, final TermStruct predicate) {
  try {
    Term[] nonchangeable = null;
    if (templates != null) {
      nonchangeable = checkTemplates(predicate);
    }

    Object result = null;
    result = method.invoke(ownerLibrary, goal, predicate);

    if (nonchangeable != null) {
      final Term[] elements = predicate.getElementsAsArray();
      final int len = elements.length;
      for (int li = 0; li < len; li++) {
        if (nonchangeable[li] == null) {
          continue;
        }
        if (nonchangeable[li].hasAnyDifference(elements[li])) {
          throw new ProlInstantiationErrorException("Nonchangeable element was changed [" + nonchangeable[li] + "<>" + elements[li] + "]", predicate);
        }
      }
    }

    return (Term) result;
  }
  catch (IllegalAccessException ex) {
    throw new ProlCriticalError("Illegal access exception at " + predicate, ex);
  }
  catch (InvocationTargetException thr) {
    thr.printStackTrace();

    final Throwable cause = thr.getCause();

    if (cause instanceof ArithmeticException) {
      throw new ProlEvaluationErrorException(cause.getMessage(), predicate);
    }

    if (cause instanceof ProlAbstractCatcheableException) {
      throw (ProlAbstractCatcheableException) cause;
    }
    if (cause instanceof ProlException) {
      throw (ProlException) cause;
    }
    throw new ProlCriticalError("Exception at [" + goal + ']', cause);
  }
}
 
Example 32
Project: nubes   File: DefaultMethodInvocationHandler.java View source code Vote up 6 votes
@Override
public void handle(RoutingContext routingContext) {
	if (routingContext.response().ended()) {
		return;
	}
	if (routingContext.failed()) {
		return;
	}
	Object[] parameters = null;
	try {
		parameters = getParameters(routingContext);
	} catch (WrongParameterException e) {
		DefaultErrorHandler.badRequest(routingContext, e.getMessage());
		return;
	}
	try {
		@SuppressWarnings("unchecked")
		T returned = (T) method.invoke(instance, parameters);
		if (returnsSomething) {
			boolean contentTypeSet = routingContext.get(ContentTypeProcessor.BEST_CONTENT_TYPE) != null;
			if (returnHandler != null) {
				returnHandler.accept(routingContext, returned);
			} else if (hasNext && contentTypeSet) {
				// try to set as Payload
				Payload<Object> payload = routingContext.get(Payload.DATA_ATTR);
				if (payload == null) {
					payload = new Payload<>();
					routingContext.put(Payload.DATA_ATTR, payload);
				}
				payload.set(returned);
			} else if (returned instanceof String) {
				routingContext.response().end((String) returned);
			}
		}
		if (!usesRoutingContext && hasNext) { // cannot call context.next(), assume the method is sync
			routingContext.next();
		}
	} catch (InvocationTargetException ite) {
		ite.printStackTrace();
		routingContext.fail(ite.getCause());
		return;
	} catch (Throwable others) {
		routingContext.fail(others);
		return;
	}
}
 
Example 33
Project: orson-charts   File: DemoDisplayer.java View source code Vote up 6 votes
/**
 * Runs the task.
 */
@Override
public void run() {
    try {
        Class<?> c = Class.forName(this.demoDescription.getClassName());
        Method m = c.getDeclaredMethod("createDemoPanel", (Class[]) null);
        JPanel panel = (JPanel) m.invoke(null, (Object[]) null);
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(4,4, 4, 4), 
                BorderFactory.createLineBorder(Color.BLACK)));
        this.demoComp.getChartContainer().removeAll();
        this.demoComp.getChartContainer().add(panel);
        this.demoComp.getChartContainer().validate();
        if (panel instanceof DemoPanel) {
            DemoPanel demoPanel = (DemoPanel) panel;
            for (Chart3DPanel cp3d : demoPanel.getChartPanels()) {
                if (demoComp.getChartStyle() != null) {
                    Chart3D chart = (Chart3D) cp3d.getDrawable();
                    chart.setStyle(demoComp.getChartStyle());
                }
                cp3d.zoomToFit(); 
            }
        }
        String f = this.demoDescription.getDescriptionFileName();
        URL descriptionURL = OrsonChartsDemo.class.getResource(f);
        if (descriptionURL != null) {
            try {
                this.demoComp.getChartDescriptionPane().setPage(descriptionURL);
            }
            catch (IOException e) {
                System.err.println("Attempted to read a bad URL: "
                    + descriptionURL);
            }
        }
    }
    catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }
    catch (NoSuchMethodException e2) {
        e2.printStackTrace();
    }
    catch (InvocationTargetException e3) {
        e3.printStackTrace();
    }
    catch (IllegalAccessException e4) {
        e4.printStackTrace();
    }

}
 
Example 34
Project: ikvm-openjdk   File: Robot.java View source code Vote up 6 votes
/**
 * Waits until all events currently on the event queue have been processed.
 * @throws  IllegalThreadStateException if called on the AWT event dispatching thread
 */
public synchronized void waitForIdle() {
    checkNotDispatchThread();
    // post a dummy event to the queue so we know when
    // all the events before it have been processed
    try {
        SunToolkit.flushPendingEvents();
        EventQueue.invokeAndWait( new Runnable() {
                                        public void run() {
                                            // dummy implementation
                                        }
                                    } );
    } catch(InterruptedException ite) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ite.printStackTrace();
    } catch(InvocationTargetException ine) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ine.printStackTrace();
    }
}
 
Example 35
Project: castor   File: DefaultObjectFactory.java View source code Vote up 6 votes
/**
 * Create a new instance of the given type by calling a public constructor
 * of this class, passing the given arguments to the constructor call.
 * @param type The class type to instantiate
 * @param argTypes Argument types.
 * @param args Arguments (to be used as parameters to the constructor class).
 * @return An instance of the class type provided
 * @throws InstantiationException If the given class type does not expose a constructor 
 *  with the given number of argument (types).
 * @throws IllegalAccessException If the given constructor failed during invocation.
 */
private Object instantiateUsingConstructor(Class type, Class[] argTypes, Object[] args) throws InstantiationException, IllegalAccessException {
    try {
        Constructor cons = type.getConstructor(argTypes);
        return cons.newInstance(args);
    }
    catch(java.lang.NoSuchMethodException nsmx) {
        String err = "unable to find matching public constructor for class: " + type.getName();
        err += " with argument types: ";
        for (int i = 0; i < argTypes.length; i++) {
            if (i > 0) err += ", ";
            err += argTypes[i].getName();
        }
        throw new InstantiationException(err);
    } catch(InvocationTargetException ite) {
        throw new CastorIllegalStateException(
                ite.getMessage(), ite.getTargetException());
    }
}
 
Example 36
Project: CodingSpectator   File: ExceptionHandler.java View source code Vote up 6 votes
protected void perform(InvocationTargetException e, Shell shell, String title, String message) {
	Throwable target= e.getTargetException();
	if (target instanceof CoreException) {
		perform((CoreException)target, shell, title, message);
	} else {
		JavaPlugin.log(e);
		if (e.getMessage() != null && e.getMessage().length() > 0) {
			displayMessageDialog(e.getMessage(), shell, title, message);
		} else {
			displayMessageDialog(target.getMessage(), shell, title, message);
		}
	}
}
 
Example 37
Project: eclipse.jdt.core   File: ExceptionHandler.java View source code Vote up 6 votes
protected void perform(InvocationTargetException e, Shell shell, String title, String message) {
	Throwable target= e.getTargetException();
	if (target instanceof CoreException) {
		perform((CoreException)target, shell, title, message);
	} else {
		AptUIPlugin.log(e);
		if (e.getMessage() != null && e.getMessage().length() > 0) {
			displayMessageDialog(e, e.getMessage(), shell, title, message);
		} else {
			displayMessageDialog(e, target.getMessage(), shell, title, message);
		}
	}
}
 
Example 38
Project: Eclipse-Postfix-Code-Completion   File: ExceptionHandler.java View source code Vote up 6 votes
protected void perform(InvocationTargetException e, Shell shell, String title, String message) {
	Throwable target= e.getTargetException();
	if (target instanceof CoreException) {
		perform((CoreException)target, shell, title, message);
	} else {
		JavaPlugin.log(e);
		if (e.getMessage() != null && e.getMessage().length() > 0) {
			displayMessageDialog(e.getMessage(), shell, title, message);
		} else {
			displayMessageDialog(target.getMessage(), shell, title, message);
		}
	}
}
 
Example 39
Project: tern.java   File: ExceptionHandler.java View source code Vote up 6 votes
protected void perform(InvocationTargetException e, Shell shell, String title, String message) {
	Throwable target= e.getTargetException();
	if (target instanceof CoreException) {
		perform((CoreException)target, shell, title, message);
	} else {
		JavaScriptPlugin.log(e);
		if (e.getMessage() != null && e.getMessage().length() > 0) {
			displayMessageDialog(e, e.getMessage(), shell, title, message);
		} else {
			displayMessageDialog(e, target.getMessage(), shell, title, message);
		}
	}
}
 
Example 40
Project: arquillian-eclipse   File: ArquillianWizard.java View source code Vote up 6 votes
private void handleException(InvocationTargetException e, Shell shell, String title, String message) {
	Throwable target= e.getTargetException();
	if (target instanceof CoreException) {
		handleException((CoreException)target, shell, title, message);
	} else {
		ArquillianUIActivator.log(e);
		if (e.getMessage() != null && e.getMessage().length() > 0) {
			displayMessageDialog(e.getMessage(), shell, title, message);
		} else {
			displayMessageDialog(target.getMessage(), shell, title, message);
		}
	}
}
 
Example 41
Project: SmartAndroidSource   File: Bus.java View source code Vote up 6 votes
/**
 * Throw a [email protected] RuntimeException} with given message and cause lifted from an [email protected]
 * InvocationTargetException}. If the specified [email protected] InvocationTargetException} does not have a
 * cause, neither will the [email protected] RuntimeException}.
 */
private static void throwRuntimeException(String msg, InvocationTargetException e) {
  Throwable cause = e.getCause();
  if (cause != null) {
    throw new RuntimeException(msg + ": " + cause.getMessage(), cause);
  } else {
    throw new RuntimeException(msg + ": " + e.getMessage(), e);
  }
}
 
Example 42
Project: otto   File: Bus.java View source code Vote up 6 votes
/**
 * Throw a [email protected] RuntimeException} with given message and cause lifted from an [email protected]
 * InvocationTargetException}. If the specified [email protected] InvocationTargetException} does not have a
 * cause, neither will the [email protected] RuntimeException}.
 */
private static void throwRuntimeException(String msg, InvocationTargetException e) {
  Throwable cause = e.getCause();
  if (cause != null) {
    throw new RuntimeException(msg + ": " + cause.getMessage(), cause);
  } else {
    throw new RuntimeException(msg + ": " + e.getMessage(), e);
  }
}
 
Example 43
Project: c4jplugin   File: ExceptionHandler.java View source code Vote up 6 votes
protected void perform(InvocationTargetException e, Shell shell, String title, String message) {
	Throwable target= e.getTargetException();
	if (target instanceof CoreException) {
		perform((CoreException)target, shell, title, message);
	} else {
		C4JActivator.log(e);
		if (e.getMessage() != null && e.getMessage().length() > 0) {
			displayMessageDialog(e, e.getMessage(), shell, title, message);
		} else {
			displayMessageDialog(e, target.getMessage(), shell, title, message);
		}
	}
}
 
Example 44
Project: platform_tools_motodev   File: WirelessWizard.java View source code Vote up 6 votes
@Override
public boolean performFinish()
{
    boolean isProcessOK = true;
    try
    {
        // execute connection switch and show success message in case everything went fine 
        getContainer().run(true, true, new SwitchFromUSBAndConnectToWirelessRunnable(this));
        EclipseUtils.showInformationDialog(
                RemoteDeviceNLS.WirelessWizard_TitleWirelessConnectionModeWizard,
                RemoteDeviceNLS.WirelessWizard_WirelessDeviceCreatedSuccessfully);
        StudioLogger.collectUsageData(StudioLogger.WHAT_REMOTE_WIRELESS,
                StudioLogger.KIND_REMOTE_DEVICE, StudioLogger.DESCRIPTION_DEFAULT,
                RemoteDevicePlugin.PLUGIN_ID, RemoteDevicePlugin.getDefault().getBundle()
                        .getVersion().toString());
    }
    catch (InvocationTargetException ite)
    {
        // treat case where something went wrong - log, show an error message and set the wizard flag
        StudioLogger.error(this.getClass(), "Problems switching device to TCP/IP.", ite); //$NON-NLS-1$
        IStatus status =
                new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID,
                        ite.getTargetException() != null ? ite.getTargetException()
                                .getMessage() : ite.getMessage());
        EclipseUtils.showErrorDialog(
                RemoteDeviceNLS.WirelessWizard_TitleWirelessConnectionModeWizard,
                RemoteDeviceNLS.WirelessWizard_MsgErrorProblemsSwitchingDeviceToTCPIP, status);
        isProcessOK = false;
    }
    catch (InterruptedException ie)
    {
        // action was canceled by the user, therefore do not close the wizard
        isProcessOK = false;
    }

    return isProcessOK;
}
 
Example 45
Project: RSQLServer   File: SharedSocket.java View source code Vote up 5 votes
/**
 * Creates a [email protected] Socket} through reflection when [email protected] Driver#JDBC3}
 * is <code>true</code>.  Reflection must be used to stay compatible
 * with JDK 1.3.
 *
 * @param connection the connection object
 * @return a socket open to the host and port with the given timeout
 * @throws IOException if socket open fails
 */
private Socket createSocketForJDBC3(ConnectionJDBC2 connection) throws IOException {
    final String host = connection.getServerName();
    final int port = connection.getPortNumber();
    final int loginTimeout = connection.getLoginTimeout();
    final String bindAddress = connection.getBindAddress();
    try {
        // Create the Socket
        Constructor socketConstructor =
                Socket.class.getConstructor(new Class[] {});
        Socket socket =
                (Socket) socketConstructor.newInstance(new Object[] {});

        // Create the InetSocketAddress
        Constructor constructor = Class.forName("java.net.InetSocketAddress")
                .getConstructor(new Class[] {String.class, int.class});
        Object address = constructor.newInstance(
                        new Object[] {host, new Integer(port)});

        // Call Socket.bind(SocketAddress) if bindAddress parameter is set
        if (bindAddress != null && bindAddress.length() > 0) {
            Object localBindAddress = constructor.newInstance(
                    new Object[]{bindAddress, new Integer(0)});
            Method bind = Socket.class.getMethod(
                    "bind", new Class[]{Class.forName("java.net.SocketAddress")});
            bind.invoke(socket, new Object[]{localBindAddress});
        }

        // Call Socket.connect(InetSocketAddress, int)
        Method connect = Socket.class.getMethod("connect", new Class[]
                {Class.forName("java.net.SocketAddress"), int.class});
        connect.invoke(socket,
                new Object[] {address, new Integer(loginTimeout * 1000)});

        return socket;
    } catch (InvocationTargetException ite) {
        // Reflection was OK but invocation of socket.bind() or socket.connect()
        // has failed. Try to report the underlying reason
        Throwable cause = ite.getTargetException();
        if (cause instanceof IOException) {
            // OK was an IOException or subclass so just throw it
            throw (IOException) cause;
        }
        // Something else so return invocation exception anyway
        // (This should not normally occur)
        throw (IOException) Support.linkException(
                new IOException("Could not create socket"), cause);
    } catch (Exception e) {
        // Reflection has failed for some reason e.g. security so
        // try to create a socket in the old way.
        return new Socket(host, port);
    }
}
 
Example 46
Project: openmap   File: ComponentFactory.java View source code Vote up 5 votes
/**
 * Create a single object. If you want it to complain about classes it can't
 * find, then set the 'basic' debug flag.
 * 
 * @param className Class name to instantiate.
 * @param constructorArgs an Object array of arguments to use in the
 *        constructor of the component.
 * @param argClasses an array of classes to use to scope which constructor
 *        to use. If null, then an array will be built from the
 *        constructorArgs.
 * @param prefix Properties prefix to use by the object to scope its
 *        properties.
 * @param properties Properties to use to initialize the object, if the
 *        object is a PropertyConsumer.
 * @return object if all goes well, null if anything bad happens.
 */
protected Object _create(String className, Object[] constructorArgs, Class<?>[] argClasses, String prefix, Properties properties) {
    String errorMessage = null;
    Throwable exceptionCaught = null;
    boolean DEBUG = false;
    try {

        if (logger.isLoggable(Level.FINER)) {
            DEBUG = true;
            logger.finer("creating: " + className);
        }

        // Apparently, this fails in certain cases where OpenMap is being
        // used as a plugin in a NetBeans or Eclipse architecture and the
        // application classloader isn't aware of the plugins classes. It
        // limits the creation of the object to classes in the caller's
        // classloader.
        // Class newObjClass = Class.forName(className.trim());
        // replaced with:

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null) {
            cl = this.getClass().getClassLoader();
        }
        Class<?> newObjClass = Class.forName(className.trim(), true, cl);

        if (DEBUG)
            logger.finer(" - got class for " + className);

        if (argClasses == null) {
            if (constructorArgs != null && constructorArgs.length > 0) {

                argClasses = new Class[constructorArgs.length];
                for (int i = 0; i < argClasses.length; i++) {
                    argClasses[i] = constructorArgs[i].getClass();
                }
            } else {
                // If empty, make null
                constructorArgs = null;
            }
        }

        if (DEBUG) {
            StringBuffer sb = new StringBuffer();
            if (constructorArgs == null) {
                sb.append("null");
            } else {
                for (int i = 0; i < constructorArgs.length; i++) {
                    sb.append(constructorArgs[i].getClass().getName());
                    if (i < constructorArgs.length - 1)
                        sb.append(", ");
                }
            }
            logger.finer(" - created class arguments [" + sb.toString() + "]");
        }

        Constructor<?> constructor = null;
        Object obj = null;

        try {
            constructor = newObjClass.getConstructor(argClasses);

            if (DEBUG)
                logger.finer(" - got constructor");

            // Create component
            obj = constructor.newInstance(constructorArgs);
            if (DEBUG)
                logger.finer(" - got object");

        } catch (NoSuchMethodException nsmei) {
            /*
             * The argClasses may have subclasses of what the desired
             * constructor needs, so we need to check explicitly.
             */
            obj = createWithSubclassConstructorArgs(newObjClass, argClasses, constructorArgs);
            if (DEBUG && obj != null)
                logger.finer(" - got object on try #2");
        }

        if (obj instanceof PropertyConsumer && properties != null) {
            if (DEBUG) {
                logger.finer("  setting properties with prefix \"" + prefix + "\"");
            }
            ((PropertyConsumer) obj).setProperties(prefix, properties);

            if (Debug.debugging(BasicI18n.DEBUG_CREATE)) {
                /*
                 * If we're interested in creating resource bundle files, we
                 * should cause these PropertyConsumers to ask for their
                 * property info, since this is where most of the elective
                 * GUI strings are queried and found.
                 */
                ((PropertyConsumer) obj).getPropertyInfo(null);
            }

            if (DEBUG)
                logger.finer(" - set properties");
        }
        return obj;

    } catch (NoSuchMethodException nsme) {
        exceptionCaught = nsme;
        errorMessage = "NoSuchMethodException: " + nsme.getMessage();
    } catch (InstantiationException ie) {
        exceptionCaught = ie;
        errorMessage = "InstantiationException: " + ie.getMessage() + " - Might be trying to create an abstract class";
    } catch (IllegalAccessException iae) {
        if (DEBUG)
            iae.printStackTrace();
        exceptionCaught = iae;
        errorMessage = "IllegalAccessException: " + iae.getMessage();
    } catch (IllegalArgumentException iae2) {
        if (DEBUG)
            iae2.printStackTrace();
        exceptionCaught = iae2;
        errorMessage = "IllegalArgumentException: " + iae2.getMessage();
    } catch (InvocationTargetException ite) {
        if (DEBUG)
            ite.printStackTrace();
        exceptionCaught = ite;
        errorMessage = "InvocationTargetException: " + ite.getMessage();
    } catch (ClassNotFoundException cnfe) {
        exceptionCaught = cnfe;
        errorMessage = "ClassNotFoundException: " + cnfe.getMessage();
    }

    if (logger.isLoggable(Level.FINE)) {
        logger.fine("Failed to create \"" + className
                + (prefix != null ? "\" using component marker name \"" + prefix + "\"" : "") + " - error message: "
                + errorMessage);

        if (exceptionCaught != null) {
            logger.log(Level.WARNING, "Exception reported is as follows:", exceptionCaught);
        }
    }

    return null;
}
 
Example 47
Project: modeshape   File: JcrMetaDataTeiidSupportTest.java View source code Vote up 5 votes
/**
 * Test all the non-query methods
 * 
 * @throws Exception
 */
@SuppressWarnings( "unchecked" )
@Test
public void testMethodsWithoutParams() throws Exception {
    Class<?> dbmdClass = metadata.getClass();
    // non-query Methods return String, boolean or int
    Method[] methods = dbmdClass.getDeclaredMethods();
    Map<String, Object> expectedMap = new HashMap<String, Object>();

    List<String> failedMessages = new ArrayList<String>();
    expectedMap = getExpected();
    // SYS.out.println(" -- total method == " + methods.length + ", non-query == " + expectedMap.size());
    for (int i = 0; i < methods.length; i++) {
        if (expectedMap.containsKey(methods[i].getName())) {

            Object actualValue = null;
            Object expectedValue = null;
            Object expectedReturn = expectedMap.get(methods[i].getName());
            Object[] params = null;

            if (expectedReturn instanceof List<?>) {
                // has input parameters
                List<Object[]> returned = (List<Object[]>)expectedReturn;
                params = returned.get(1);
                // SYS.out.println(" params == " + params[0]);
                expectedValue = returned.get(0);
                actualValue = methods[i].invoke(metadata, params);
            } else {
                // without params
                expectedValue = expectedReturn;
                try {
                    actualValue = methods[i].invoke(metadata, new Object[0]);
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                    throw e;
                }
            }

            if (expectedValue == null || actualValue == null) {
                if (expectedValue == null && actualValue != null) {
                    failedMessages.add(" Expected doesn't match with actual for method - " + methods[i].getName()
                                       + " expected: <" + expectedValue + "> but was: < " + actualValue + "> ");

                } else if (expectedValue != null && actualValue == null) {
                    failedMessages.add(" Expected doesn't match with actual for method - " + methods[i].getName()
                                       + " expected: <" + expectedValue + "> but was: < " + actualValue + "> ");

                }
            } else if (!expectedValue.equals(actualValue)) {
                failedMessages.add(" Expected doesn't match with actual for method - " + methods[i].getName()
                                   + " expected: <" + expectedValue + "> but was: < " + actualValue + "> ");
            }
        }
    }

    assertThat(failedMessages.toString().trim(), is("[]"));

}
 
Example 48
Project: compomics-utilities   File: IdfileReaderFactory.java View source code Vote up 5 votes
/**
 * This method returns the proper identification file reader depending on
 * the format of the provided file. It is very important to close the file
 * reader after creation.
 *
 * @param aFile the file to parse
 * @return an adapted file reader
 * 
 * @throws SAXException if a SAXException occurs
 * @throws FileNotFoundException if a FileNotFoundException occurs
 * @throws IOException if an IOException occurs
 * @throws OutOfMemoryError thrown if the parser runs out of memory
 */
public IdfileReader getFileReader(File aFile) throws SAXException, FileNotFoundException, IOException, OutOfMemoryError {

    // @TODO: create parsers using waiting handlers and indexed files.
    // The return value, defaulting to null.
    IdfileReader result = null;

    // Get file name of the idfile to process.
    String name = aFile.getName().toLowerCase();

    // Iterator registered IdfileReaders, see who likes this file. First come, first served.
    // @TODO: May want to make this more sophisticated, possibly like the DBLoaders in DBToolkit, 
    //        that get the actual file to read some lines prior to making up their mind; thus constitutes 
    //        an actual format check rather than an extension check.
    Iterator<String> extensions = idFileReaders.keySet().iterator();

    while (extensions.hasNext()) {
        String key = extensions.next();
        String extension = key.toLowerCase();
        if (name.endsWith(extension)) {
            Class idfileReaderClass = idFileReaders.get(key);
            try {
                result = (IdfileReader) idfileReaderClass.getConstructor(File.class).newInstance(aFile);
                break;
            } catch (NoSuchMethodException nsme) {
                logger.error("Unable to find required constructor with single java.io.File parameter in IdfileReader implementation '"
                        + idfileReaderClass.getCanonicalName() + "', matching query extension '" + extension + "'!", nsme);
                nsme.printStackTrace();
            } catch (IllegalAccessException iae) {
                logger.error("Required public constructor with single java.io.File parameter in IdfileReader implementation '"
                        + idfileReaderClass.getCanonicalName() + "', matching query extension '" + extension + "' has incorrect access modifier!", iae);
                iae.printStackTrace();
            } catch (InvocationTargetException ite) {
                if (ite.getCause() instanceof OutOfMemoryError) {
                    ite.printStackTrace();
                    throw (OutOfMemoryError) ite.getCause();
                } else {
                    logger.error("Required constructor with single java.io.File parameter in IdfileReader implementation '"
                            + idfileReaderClass.getCanonicalName() + "', matching query extension '" + extension + "' threw an exception!", ite);
                    ite.printStackTrace();
                }
            } catch (InstantiationException ie) {
                logger.error("Required constructor with single java.io.File parameter in IdfileReader implementation '"
                        + idfileReaderClass.getCanonicalName() + "', matching query extension '" + extension + "' inaccessible; probably abstract class?!", ie);
                ie.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return result;
}
 
Example 49
Project: servletcontainer   File: IntrospectionUtils.java View source code Vote up 5 votes
public static Object getProperty(Object o, String name) {
    String getter = "get" + capitalize(name);
    String isGetter = "is" + capitalize(name);

    try {
        Method methods[] = findMethods(o.getClass());
        Method getPropertyMethod = null;

        // First, the ideal case - a getFoo() method
        for (int i = 0; i < methods.length; i++) {
            Class paramT[] = methods[i].getParameterTypes();
            if (getter.equals(methods[i].getName()) && paramT.length == 0) {
                return methods[i].invoke(o, (Object[]) null);
            }
            if (isGetter.equals(methods[i].getName()) && paramT.length == 0) {
                return methods[i].invoke(o, (Object[]) null);
            }

            if ("getProperty".equals(methods[i].getName())) {
                getPropertyMethod = methods[i];
            }
        }

        // Ok, no setXXX found, try a getProperty("name")
        if (getPropertyMethod != null) {
            Object params[] = new Object[1];
            params[0] = name;
            return getPropertyMethod.invoke(o, params);
        }

    } catch (IllegalArgumentException ex2) {
        log.warn("IAE " + o + " " + name, ex2);
    } catch (SecurityException ex1) {
        if (dbg > 0)
            d("SecurityException for " + o.getClass() + " " + name + ")");
        if (dbg > 1)
            ex1.printStackTrace();
    } catch (IllegalAccessException iae) {
        if (dbg > 0)
            d("IllegalAccessException for " + o.getClass() + " " + name
                    + ")");
        if (dbg > 1)
            iae.printStackTrace();
    } catch (InvocationTargetException ie) {
        if (dbg > 0)
            d("InvocationTargetException for " + o.getClass() + " " + name
                    + ")");
        if (dbg > 1)
            ie.printStackTrace();
    }
    return null;
}