示例#1
1
 public Container buildContainer(String containerClass) {
   notNull(
       containerClass,
       "Container type " + Arrays.deepToString(Server.values()) + " or container class");
   Class<Container> clazz = null;
   for (Server container : Server.values()) {
     if (container.name().equalsIgnoreCase(containerClass)) {
       clazz = loadServerClass(container.serverClass());
       break;
     }
   }
   if (clazz == null) clazz = loadServerClass(containerClass);
   try {
     return clazz
         .getConstructor(ContainerConfiguration.class)
         .newInstance(ContainerConfiguration.from(this));
   } catch (InvocationTargetException e) {
     if (e.getTargetException() instanceof RuntimeException)
       throw (RuntimeException) e.getTargetException();
     else throw new RuntimeException(e.getTargetException().getMessage(), e.getTargetException());
   } catch (Exception e) {
     throw new IllegalArgumentException(
         "Cannot instanciate class ["
             + clazz
             + "]. Ensure there is a public constructor having a parameter of type "
             + ContainerConfiguration.class.getName(),
         e);
   }
 }
 public Object findAndInvokeMethod(
     Object object, String methodName, Object[] params, Class<?>[] classes) {
   Method findMethod = findMethod(object, methodName, classes);
   try {
     return findMethod.invoke(object, params);
   } catch (IllegalArgumentException e) {
     throw new RuntimeException(
         "Argumentos inválidos ao chamar método "
             + methodName
             + " na classe "
             + object.getClass().getSimpleName(),
         e);
   } catch (IllegalAccessException e) {
     throw new RuntimeException(
         "Acesso ilegal ao chamar método "
             + methodName
             + " na classe "
             + object.getClass().getSimpleName(),
         e);
   } catch (InvocationTargetException e) {
     throw new RuntimeException(
         "Método "
             + methodName
             + " lançou exeção "
             + e.getTargetException().getClass().getSimpleName(),
         e.getTargetException());
   }
 }
示例#3
0
  public static boolean runAndHandle(
      IRunnableContext runnableContext,
      IRunnableWithProgress op,
      boolean isCancellable,
      String errorTitle) {

    try {
      runnableContext.run(true, isCancellable, op);
      return true;
    } catch (InvocationTargetException e) {
      Throwable targetException = e.getTargetException();
      if (targetException instanceof OperationCanceledException) {
        return false;
      }

      CoreException ce;
      if (targetException instanceof CoreException) {
        ce = (CoreException) e.getTargetException();
      } else {
        ce = LangCore.createCoreException("Internal error: ", targetException);
      }
      UIOperationExceptionHandler.handleOperationStatus(errorTitle, ce);
      return false;
    } catch (InterruptedException e) {
      return false;
    }
  }
示例#4
0
 /**
  * Helper function for reflective invocation.
  * 
  * @param cl  class loader
  * @param className  class name
  * @param methodName  method name
  * @param argTypes  arg types (optional)
  * @param args  arguments
  * @return  return value from invoked method
  */
 public static Object invoke(ClassLoader cl, String className,
     String methodName, Class[] argTypes, Object[] args) {
     Class c;
     try {
         c = Class.forName(className, true, cl);
     } catch (ClassNotFoundException e0) {
         System.err.println("Cannot load "+className);
         e0.printStackTrace();
         return null;
     }
     Method m = getDeclaredMethod(c, methodName, argTypes);
     Object result;
     try {
         result = m.invoke(null, args);
     } catch (IllegalArgumentException e2) {
         System.err.println("Illegal argument exception");
         e2.printStackTrace();
         return null;
     } catch (IllegalAccessException e2) {
         System.err.println("Illegal access exception");
         e2.printStackTrace();
         return null;
     } catch (InvocationTargetException e2) {
         if (e2.getTargetException() instanceof RuntimeException)
             throw (RuntimeException) e2.getTargetException();
         if (e2.getTargetException() instanceof Error)
             throw (Error) e2.getTargetException();
         System.err.println("Unexpected exception thrown!");
         e2.getTargetException().printStackTrace();
         return null;
     }
     return result;
 }
示例#5
0
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   Object result = null;
   PoolSocket poolSocket = null;
   boolean clearConn = false;
   try {
     if (!method.getName().equals("setProxyHandle")) {
       poolSocket = connectionProvider.getConnection();
       curPoolSoceket.set(poolSocket);
     }
     result = method.invoke(obj, args);
     return result;
   } catch (InvocationTargetException e) {
     // 这里用于捕获connection reset的异常,获取连接请求,后服务端意外中断
     if (e.getTargetException() instanceof TException) {
       clearConn = true;
     }
     throw e.getTargetException();
   } catch (Exception e) {
     throw e;
   } finally {
     if (clearConn && poolSocket != null) {
       connectionProvider.clearCon(poolSocket);
     } else if (poolSocket != null) {
       connectionProvider.returnCon(poolSocket);
     }
   }
 }
示例#6
0
  public void run() {
    try {
      while (!quit) {
        try {
          CharSequence line = getLine(session.getKeyboard());
          if (line != null) {
            history.add(line);
            if (history.size() > 40) {
              history.remove(0);
            }
            Object result = session.execute(line);
            if (result != null) {
              session.getConsole().println(session.format(result, Converter.INSPECT));
            }
          } else {
            quit = true;
          }

        } catch (InvocationTargetException ite) {
          session.getConsole().println("E: " + ite.getTargetException());
          session.put("exception", ite.getTargetException());
        } catch (Throwable e) {
          if (!quit) {
            session.getConsole().println("E: " + e.getMessage());
            session.put("exception", e);
          }
        }
      }
    } catch (Exception e) {
      if (!quit) {
        e.printStackTrace();
      }
    }
  }
 /* (non-Javadoc)
  * @see com.mg.framework.service.jboss.ApplicationServerServiceMBean#convertDatabase()
  */
 public void convertDatabase() throws Exception {
   Object converter = null;
   try {
     // проверка наличия класса конвертации системы
     Class<?> converterClass = ServerUtils.loadClass("com.mg.framework.service.DatabaseConverter");
     Method getInstanceMethod = converterClass.getMethod("getInstance", String.class);
     converter = getInstanceMethod.invoke(null, databaseName);
   } catch (InvocationTargetException e) {
     log.error("Create database converter failed", e.getTargetException());
     throw new Exception(
         String.format(
             "Create database converter failed with message: %s",
             e.getTargetException().toString()));
   } catch (ClassNotFoundException e) {
     throw new Exception(String.format("Commercial license wanted"));
   }
   try {
     Method convertMethod = converter.getClass().getMethod("convert", Properties.class);
     convertMethod.invoke(converter, getDatabaseProperties());
   } catch (InvocationTargetException e) {
     Throwable targetException = e.getTargetException();
     if (targetException instanceof ApplicationException) {
       log.error("Convert database failed", targetException);
       throw new Exception(
           String.format(
               "Convert database failed with message: %s.", targetException.getMessage()));
     } else {
       log.error("Convert database failed", targetException);
       throw new Exception(
           String.format(
               "Convert database failed with message: %s. The full information is available in the server.log.",
               targetException.toString()));
     }
   }
 }
 @Override
 public Object invokeImpl(Object proxy, Method method, Object[] args) throws SentryUserException {
   Object result = null;
   try {
     if (!method.isAccessible()) {
       method.setAccessible(true);
     }
     // The client is initialized in the first call instead of constructor.
     // This way we can propagate the connection exception to caller cleanly
     if (client == null) {
       renewSentryClient();
     }
     result = method.invoke(client, args);
   } catch (IllegalAccessException e) {
     throw new SentryUserException(e.getMessage(), e.getCause());
   } catch (InvocationTargetException e) {
     if (e.getTargetException() instanceof SentryUserException) {
       throw (SentryUserException) e.getTargetException();
     } else {
       LOGGER.warn(
           THRIFT_EXCEPTION_MESSAGE
               + ": Error in connect current"
               + " service, will retry other service.",
           e);
       if (client != null) {
         client.close();
         client = null;
       }
     }
   } catch (IOException e1) {
     throw new SentryUserException("Error connecting to sentry service " + e1.getMessage(), e1);
   }
   return result;
 }
示例#9
0
    private IStatus doIt(final Object theValue) {
      IStatus res = Status.OK_STATUS;
      for (int cnt = 0; cnt < _subjects.length; cnt++) {
        final Editable thisSubject = _subjects[cnt];
        try {
          _setter.invoke(thisSubject, new Object[] {theValue});
        } catch (final InvocationTargetException e) {
          CorePlugin.logError(
              Status.ERROR,
              "Setter call failed:"
                  + thisSubject.getName()
                  + " Error was:"
                  + e.getTargetException().getMessage(),
              e.getTargetException());
          res = Status.CANCEL_STATUS;
        } catch (final IllegalArgumentException e) {
          CorePlugin.logError(Status.ERROR, "Wrong parameters pass to:" + thisSubject.getName(), e);
          res = Status.CANCEL_STATUS;
        } catch (final IllegalAccessException e) {
          CorePlugin.logError(
              Status.ERROR, "Illegal access problem for:" + thisSubject.getName(), e);
          res = Status.CANCEL_STATUS;
        }
      }

      // and tell everybody (we only need to do this if the previous call
      // works,
      // if an exception is thrown we needn't worry about the update
      fireUpdate();

      return res;
    }
示例#10
0
  static JAXBContext newInstance(Class[] classes, Map properties, Class spFactory)
      throws JAXBException {
    Method m;
    try {
      m = spFactory.getMethod("createContext", Class[].class, Map.class);
    } catch (NoSuchMethodException e) {
      throw new JAXBException(e);
    }
    try {
      Object context = m.invoke(null, classes, properties);
      if (!(context instanceof JAXBContext)) {
        // the cast would fail, so generate an exception with a nice message
        throw handleClassCastException(context.getClass(), JAXBContext.class);
      }
      return (JAXBContext) context;
    } catch (IllegalAccessException e) {
      throw new JAXBException(e);
    } catch (InvocationTargetException e) {
      handleInvocationTargetException(e);

      Throwable x = e;
      if (e.getTargetException() != null) x = e.getTargetException();

      throw new JAXBException(x);
    }
  }
 private Object makeInstance(
     PicoContainer container, Constructor constructor, ComponentMonitor monitor) {
   long startTime = System.currentTimeMillis();
   Constructor constructorToUse =
       monitor.instantiating(container, IterativeInjector.this, constructor);
   Object componentInstance;
   try {
     componentInstance = newInstance(constructorToUse, null);
   } catch (InvocationTargetException e) {
     monitor.instantiationFailed(container, IterativeInjector.this, constructorToUse, e);
     if (e.getTargetException() instanceof RuntimeException) {
       throw (RuntimeException) e.getTargetException();
     } else if (e.getTargetException() instanceof Error) {
       throw (Error) e.getTargetException();
     }
     throw new PicoCompositionException(e.getTargetException());
   } catch (InstantiationException e) {
     return caughtInstantiationException(monitor, constructor, e, container);
   } catch (IllegalAccessException e) {
     return caughtIllegalAccessException(monitor, constructor, e, container);
   }
   monitor.instantiated(
       container,
       IterativeInjector.this,
       constructorToUse,
       componentInstance,
       NONE,
       System.currentTimeMillis() - startTime);
   return componentInstance;
 }
示例#12
0
 @Override
 public void create(String instanceName, String className, Object... args) throws SlimException {
   try {
     context.create(instanceName, className, args);
     // TODO Hack for supporting SlimHelperLibrary, please remove.
     Object newInstance = context.getInstance(instanceName);
     if (newInstance instanceof StatementExecutorConsumer) {
       ((StatementExecutorConsumer) newInstance).setStatementExecutor(this);
     }
   } catch (SlimError e) {
     throw new SlimException(
         format("%s[%d]", className, args.length),
         e,
         SlimServer.COULD_NOT_INVOKE_CONSTRUCTOR,
         true);
   } catch (IllegalArgumentException e) {
     throw new SlimException(
         format("%s[%d]", className, args.length),
         e,
         SlimServer.COULD_NOT_INVOKE_CONSTRUCTOR,
         true);
   } catch (InvocationTargetException e) {
     checkExceptionForStop(e.getTargetException());
     throw new SlimException(e.getTargetException(), true);
   } catch (Throwable e) { // NOSONAR
     checkExceptionForStop(e);
     throw new SlimException(e);
   }
 }
  /**
   * Create a new IRCApplication.
   *
   * @param config the IRC configuration.
   * @param startupConfig the startup configuration.
   * @param source a container in wich the application will display. Maybe null. If null, a new
   *     Frame will be opened.
   */
  public IRCApplication(
      IRCConfiguration config, StartupConfiguration startupConfig, Container source) {
    super(config);
    _container = source;
    _start = startupConfig;
    _plugins = new Vector<Plugin>();
    _pluginsTable = new Hashtable<String, Plugin>();

    String gui = config.getS("gui");
    try {
      Class<?> cl = Class.forName("irc.gui." + gui + ".Interface");
      java.lang.reflect.Constructor<?> ctr =
          cl.getDeclaredConstructor(new Class[] {config.getClass()});
      _interface = (IRCInterface) ctr.newInstance(new Object[] {config});
    } catch (java.lang.reflect.InvocationTargetException iex) {
      iex.getTargetException().printStackTrace();
      throw new Error("Unable to load interface " + gui + " : " + iex.getTargetException());
    } catch (Throwable ex) {
      ex.printStackTrace();
      throw new Error("Unable to load interface " + gui + " : " + ex);
    }

    _servers = new Hashtable<Server, Server>();
    _defaultSource = new DefaultSource(_ircConfiguration);
    DefaultInterpretor defaultInter = new DefaultInterpretor(_ircConfiguration, _start, this, this);
    _defaultSource.setInterpretor(defaultInter);
  }
 /** {@inheritDoc} */
 @Override
 @SuppressWarnings("unchecked")
 public Object invoke(final Object proxy, final Method method, final Object[] args)
     throws Throwable {
   Object retValue = null;
   if ("open".equals(method.getName())) {
     // if the connection has been closed, invoke open
     if (!conn.isOpen()) {
       try {
         openResponse = (Response<Void>) method.invoke(conn, args);
       } catch (InvocationTargetException e) {
         throw e.getTargetException();
       }
     }
     retValue = openResponse;
   } else if ("reopen".equals(method.getName())) {
     try {
       openResponse = (Response<Void>) method.invoke(conn, args);
     } catch (InvocationTargetException e) {
       throw e.getTargetException();
     }
     retValue = openResponse;
   } else if ("close".equals(method.getName())) {
     putConnection((Connection) proxy);
   } else {
     try {
       retValue = method.invoke(conn, args);
     } catch (InvocationTargetException e) {
       throw e.getTargetException();
     }
   }
   return retValue;
 }
示例#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);
     }
   }
 }
 protected Object invokeGetMethod(
     ApiMethod apiMethod,
     Object bean,
     String methodSuffix,
     Properties parameters,
     boolean throwException)
     throws ApiException, Throwable {
   String methodName = null;
   Object result = null;
   try {
     Class[] parameterTypes = new Class[] {Properties.class};
     Class beanClass = bean.getClass();
     methodName =
         (null != methodSuffix)
             ? apiMethod.getSpringBeanMethod() + methodSuffix.trim()
             : apiMethod.getSpringBeanMethod();
     Method method = beanClass.getDeclaredMethod(methodName, parameterTypes);
     result = method.invoke(bean, parameters);
   } catch (NoSuchMethodException e) {
     if (throwException) {
       ApsSystemUtils.logThrowable(
           e,
           this,
           "invokeGetMethod",
           "No such method '" + methodName + "' of class '" + bean.getClass() + "'");
       throw new ApiException(
           IApiErrorCodes.API_METHOD_ERROR,
           "Method not supported - " + this.buildApiSignature(apiMethod));
     }
   } catch (InvocationTargetException e) {
     if (e.getTargetException() instanceof ApiException) {
       throw (ApiException) e.getTargetException();
     } else if (throwException) {
       ApsSystemUtils.logThrowable(
           e.getTargetException(),
           this,
           "invokeGetMethod",
           "Error invoking method '" + methodName + "' of class '" + bean.getClass() + "'");
       throw new ApiException(
           IApiErrorCodes.API_METHOD_ERROR,
           "Error invoking Method - " + this.buildApiSignature(apiMethod));
     }
   } catch (Throwable t) {
     if (throwException) {
       ApsSystemUtils.logThrowable(
           t,
           this,
           "invokeGetMethod",
           "Error invoking method - "
               + this.buildApiSignature(apiMethod)
               + methodName
               + "' of class '"
               + bean.getClass()
               + "'");
       throw t;
     }
   }
   return result;
 }
示例#17
0
  /** Create an instance of a class using the specified ClassLoader */
  static JAXBContext newInstance(
      String contextPath, String className, ClassLoader classLoader, Map properties)
      throws JAXBException {
    try {
      Class spiClass = safeLoadClass(className, classLoader);

      /*
       * javax.xml.bind.context.factory points to a class which has a
       * static method called 'createContext' that
       * returns a javax.xml.JAXBContext.
       */

      Object context = null;

      // first check the method that takes Map as the third parameter.
      // this is added in 2.0.
      try {
        Method m = spiClass.getMethod("createContext", String.class, ClassLoader.class, Map.class);
        // any failure in invoking this method would be considered fatal
        context = m.invoke(null, contextPath, classLoader, properties);
      } catch (NoSuchMethodException e) {
        // it's not an error for the provider not to have this method.
      }

      if (context == null) {
        // try the old method that doesn't take properties. compatible with 1.0.
        // it is an error for an implementation not to have both forms of the createContext method.
        Method m = spiClass.getMethod("createContext", String.class, ClassLoader.class);
        // any failure in invoking this method would be considered fatal
        context = m.invoke(null, contextPath, classLoader);
      }

      if (!(context instanceof JAXBContext)) {
        // the cast would fail, so generate an exception with a nice message
        handleClassCastException(context.getClass(), JAXBContext.class);
      }
      return (JAXBContext) context;
    } catch (ClassNotFoundException x) {
      throw new JAXBException(Messages.format(Messages.PROVIDER_NOT_FOUND, className), x);
    } catch (InvocationTargetException x) {
      handleInvocationTargetException(x);
      // for other exceptions, wrap the internal target exception
      // with a JAXBException
      Throwable e = x;
      if (x.getTargetException() != null) e = x.getTargetException();

      throw new JAXBException(Messages.format(Messages.COULD_NOT_INSTANTIATE, className, e), e);
    } catch (RuntimeException x) {
      // avoid wrapping RuntimeException to JAXBException,
      // because it indicates a bug in this code.
      throw x;
    } catch (Exception x) {
      // can't catch JAXBException because the method is hidden behind
      // reflection.  Root element collisions detected in the call to
      // createContext() are reported as JAXBExceptions - just re-throw it
      // some other type of exception - just wrap it
      throw new JAXBException(Messages.format(Messages.COULD_NOT_INSTANTIATE, className, x), x);
    }
  }
示例#18
0
  public static final Component getComponent(final Node node) {
    Component component;
    String tag = node.getNodeName();
    MyAction action = actions.get(tag);
    if (action != null) {
      component = action.getComponent(node);
      return component;
    }

    Constructor<? extends Component> constructor = cache.get(tag);
    if (constructor == null) {
      if ("PreviewCode".equals(tag)) {
        ScilabCommonsUtils.loadOnUse("SciNotes");
      }

      Class<? extends Component> componentClass;
      try {
        componentClass = Class.forName(X_PACKAGE + tag).asSubclass(Component.class);
      } catch (ClassNotFoundException e) {
        System.err.println(e);
        return new XStub(node, "ClassNotFoundException");
      }

      try {
        // First with a Node as argument
        Class[] parameter = new Class[] {Node.class};
        constructor = componentClass.getConstructor(parameter);
      } catch (NoSuchMethodException e) {
        System.err.println("NoSuchMethodException:" + e);
        return new XStub(node, "NoSuchMethodException");
      } catch (SecurityException e) {
        // Declare failure due to constructor rights (it must be public)
        System.err.println("SecurityException:" + e);
        return new XStub(node, "SecurityException");
      }

      cache.put(tag, constructor);
    }

    try {
      component = (Component) constructor.newInstance(new Object[] {node});
    } catch (InstantiationException e) {
      System.err.println("InstantiationException:" + e);
      return new XStub(node, "InstantiationException");
    } catch (IllegalAccessException e) {
      System.err.println("IllegalAccessException:" + e);
      return new XStub(node, "IllegalAccessException");
    } catch (IllegalArgumentException e) {
      System.err.println("IllegalArgumentException:" + e);
      return new XStub(node, "IllegalArgumentException");
    } catch (InvocationTargetException e) {
      System.err.println("InvocationTargetException:" + e.getTargetException());
      e.getTargetException().printStackTrace();
      return new XStub(node, "InvocationTargetException");
    }

    return component;
  }
 protected Object invokePutPostDeleteMethod(
     ApiMethod apiMethod, Object bean, Properties parameters, Object bodyObject)
     throws ApiException, Throwable {
   Object result = null;
   try {
     if (apiMethod.getHttpMethod().equals(ApiMethod.HttpMethod.DELETE)) {
       result = this.invokeDeleteMethod(apiMethod, bean, parameters);
     } else {
       result = this.invokePutPostMethod(apiMethod, bean, parameters, bodyObject);
     }
     if (null != result) return result;
     BaseApiResponse response = new BaseApiResponse();
     response.setResult(SUCCESS, null);
     result = response;
   } catch (NoSuchMethodException e) {
     ApsSystemUtils.logThrowable(
         e,
         this,
         "invokePutPostDeleteMethod",
         "No such method '"
             + apiMethod.getSpringBeanMethod()
             + "' of class '"
             + bean.getClass()
             + "'");
     throw new ApiException(
         IApiErrorCodes.API_METHOD_ERROR,
         "Method not supported - " + this.buildApiSignature(apiMethod));
   } catch (InvocationTargetException e) {
     if (e.getTargetException() instanceof ApiException) {
       throw (ApiException) e.getTargetException();
     } else {
       ApsSystemUtils.logThrowable(
           e.getTargetException(),
           this,
           "invokePutPostDeleteMethod",
           "Error invoking method '"
               + apiMethod.getSpringBeanMethod()
               + "' of class '"
               + bean.getClass()
               + "'");
       throw new ApiException(
           IApiErrorCodes.API_METHOD_ERROR,
           "Error invoking Method - " + this.buildApiSignature(apiMethod));
     }
   } catch (Throwable t) {
     ApsSystemUtils.logThrowable(
         t,
         this,
         "invokePutPostDeleteMethod",
         "Error invoking method '"
             + apiMethod.getSpringBeanMethod()
             + "' of class '"
             + bean.getClass()
             + "'");
     throw t;
   }
   return result;
 }
示例#20
0
文件: Lang.java 项目: flymichael/nutz
 public static Throwable unwrapThrow(Throwable e) {
   if (e == null) return null;
   if (e instanceof InvocationTargetException) {
     InvocationTargetException itE = (InvocationTargetException) e;
     if (itE.getTargetException() != null) return unwrapThrow(itE.getTargetException());
   }
   if (e.getCause() != null) return unwrapThrow(e.getCause());
   return e;
 }
示例#21
0
  /**
   * Effectively handles a call with content negotiation of the response entity using an annotated
   * method.
   *
   * @param annotationInfo The annotation descriptor.
   * @param variant The response variant expected (can be null).
   * @return The response entity.
   * @throws ResourceException
   */
  private Representation doHandle(AnnotationInfo annotationInfo, Variant variant)
      throws ResourceException {
    Representation result = null;
    Class<?>[] parameterTypes = annotationInfo.getJavaInputTypes();

    // Invoke the annotated method and get the resulting object.
    Object resultObject = null;
    try {
      if (parameterTypes.length > 0) {
        List<Object> parameters = new ArrayList<Object>();
        Object parameter = null;

        for (Class<?> parameterType : parameterTypes) {
          if (Variant.class.equals(parameterType)) {
            parameters.add(variant);
          } else {
            if (getRequestEntity() != null
                && getRequestEntity().isAvailable()
                && getRequestEntity().getSize() != 0) {
              // Assume there is content to be read.
              // NB: it does not handle the case where the size is
              // unknown, but there is no content.
              parameter = toObject(getRequestEntity(), parameterType);

              if (parameter == null) {
                throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
              }
            } else {
              parameter = null;
            }

            parameters.add(parameter);
          }
        }

        resultObject = annotationInfo.getJavaMethod().invoke(this, parameters.toArray());
      } else {
        resultObject = annotationInfo.getJavaMethod().invoke(this);
      }
    } catch (IllegalArgumentException e) {
      throw new ResourceException(e);
    } catch (IllegalAccessException e) {
      throw new ResourceException(e);
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof ResourceException) {
        throw (ResourceException) e.getTargetException();
      }

      throw new ResourceException(e.getTargetException());
    }

    if (resultObject != null) {
      result = toRepresentation(resultObject, variant);
    }

    return result;
  }
  public Object proceed() throws Exception {
    if (currentInterceptor < interceptorInfos.length) {
      int oldInterceptor = currentInterceptor;
      int oldMethod = currentMethod;
      try {
        int curr = currentInterceptor;
        int currMethod = currentMethod++;

        InterceptorInfo info = interceptorInfos[curr];
        if (currMethod == info.getAroundInvokes().length) {
          curr = ++currentInterceptor;
          currentMethod = 0;
          currMethod = currentMethod++;
          info = (curr < interceptorInfos.length) ? interceptorInfos[curr] : null;
        }
        if (info != null) {
          try {
            return info.getAroundInvokes()[currMethod].invoke(instances[curr], this);
          } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof Exception) {
              throw ((Exception) e.getCause());
            } else {
              throw new RuntimeException(e.getCause());
            }
          }
        }
      } finally {
        // so that interceptors like clustering can reinvoke down the chain
        currentInterceptor = oldInterceptor;
        currentMethod = oldMethod;
      }
    }

    if (beanAroundInvokes != null && currentBeanMethod < beanAroundInvokes.length) {
      try {
        int curr = currentBeanMethod++;
        return beanAroundInvokes[curr].invoke(getTarget(), this);
      } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof Exception) {
          throw ((Exception) e.getCause());
        } else {
          throw new RuntimeException(e.getCause());
        }
      } finally {
        currentBeanMethod--;
        ;
      }
    }
    try {
      return wrapped.invokeNext();
    } catch (Exception e) {
      throw e;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
 @Override
 public boolean fileUpdated(File file) throws WatchingException {
   try {
     return (Boolean) fileUpdated.invoke(delegate, file);
   } catch (InvocationTargetException e) { // NOSONAR
     throw new WatchingException(
         e.getTargetException().getMessage(), file, e.getTargetException());
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
示例#24
0
 /** {@inheritDoc} */
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   try {
     return delegate.invoke(proxy, method, args);
   } catch (final InvocationTargetException e) {
     if (e.getTargetException() != null) {
       throw e.getTargetException();
     }
     throw e;
   }
 }
示例#25
0
  @Override
  protected int setupConnection(ImprovedBluetoothDevice device, byte[] readBuffer)
      throws Exception {
    try {
      // Most devices supports using the reflection method
      if (D) Log.d(getDriverName(), "Attempting reflection connect");
      return super.setupConnection(device, readBuffer);
    } catch (Exception ex) {

      if (D) Log.d(getDriverName(), "Reflection connect failed, error: " + ex.getMessage());

      if (D && ex instanceof InvocationTargetException) {
        InvocationTargetException tex = (InvocationTargetException) ex;
        Log.e(
            getDriverName(),
            "TargetInvocation cause: "
                + (tex.getCause() == null ? "<null>" : tex.getCause().toString()));
        Log.e(
            getDriverName(),
            "TargetInvocation target: "
                + (tex.getTargetException() == null
                    ? "<null>"
                    : tex.getTargetException().toString()));
      }

      try {
        if (D) Log.d(getDriverName(), "Attempting createRfcommSocketToServiceRecord connect");

        // In case the reflection method was not present, we try the correct method
        m_socket =
            device.createRfcommSocketToServiceRecord(
                UUID.fromString("8e1f0cf7-508f-4875-b62c-fbb67fd34812"));
        m_socket.connect();

        if (D)
          Log.d(
              getDriverName(),
              "Connected with createRfcommSocketToServiceRecord() to " + m_address);

        m_input = m_socket.getInputStream();
        return m_input.read(readBuffer);

      } catch (Exception ex2) {
        if (D)
          Log.e(
              getDriverName(), "Failed on createRfcommSocketToServiceRecord: " + ex2.getMessage());

        // Report the original error, not the secondary
        throw ex;
      }
    }
  }
示例#26
0
 /**
  * Invoke the specified JDBC API {@link Method} against the supplied target object with the
  * supplied arguments.
  *
  * @param method the method to invoke
  * @param target the target object to invoke the method on
  * @param args the invocation arguments (may be <code>null</code>)
  * @return the invocation result, if any
  * @throws SQLException the JDBC API SQLException to rethrow (if any)
  * @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
  */
 public static Object invokeJdbcMethod(Method method, Object target, Object... args)
     throws SQLException {
   try {
     return method.invoke(target, args);
   } catch (IllegalAccessException ex) {
     handleReflectionException(ex);
   } catch (InvocationTargetException ex) {
     if (ex.getTargetException() instanceof SQLException) {
       throw (SQLException) ex.getTargetException();
     }
     handleInvocationTargetException(ex);
   }
   throw new IllegalStateException("Should never get here");
 }
  private boolean executeExportOperation(final ICProject[] projects) {
    final String dest = getDestinationValue();
    final MultiStatus status =
        new MultiStatus(
            CUIPlugin.PLUGIN_ID, 0, Messages.TeamProjectIndexExportWizardPage_errorExporting, null);
    final boolean exportResourceSnapshot = fResourceSnapshotButton.getSelection();

    IRunnableWithProgress op =
        new IRunnableWithProgress() {
          @Override
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            monitor.beginTask("", projects.length); // $NON-NLS-1$
            for (ICProject project : projects) {
              TeamPDOMExportOperation op = new TeamPDOMExportOperation(project);
              op.setTargetLocation(dest);
              if (exportResourceSnapshot) {
                op.setOptions(TeamPDOMExportOperation.EXPORT_OPTION_RESOURCE_SNAPSHOT);
              }
              try {
                op.run(new SubProgressMonitor(monitor, 1));
              } catch (CoreException e) {
                status.merge(e.getStatus());
              }
            }
          }
        };
    try {
      getContainer().run(true, true, op);
    } catch (InterruptedException e) {
      return false;
    } catch (InvocationTargetException e) {
      CUIPlugin.log(
          Messages.TeamProjectIndexExportWizardPage_errorExporting, e.getTargetException());
      displayErrorDialog(e.getTargetException());
      return false;
    }

    if (!status.isOK()) {
      CUIPlugin.log(status);
      ErrorDialog.openError(
          getContainer().getShell(),
          getErrorDialogTitle(),
          null, // no special message
          status);
      return false;
    }

    return true;
  }
  /** @generated */
  public boolean performFinish() {
    IRunnableWithProgress op =
        new WorkspaceModifyOperation(null) {

          protected void execute(IProgressMonitor monitor)
              throws CoreException, InterruptedException {
            diagram =
                DcdDiagramEditorUtil.createDiagram(
                    diagramModelFilePage.getURI(), domainModelFilePage.getURI(), monitor);
            if (isOpenNewlyCreatedDiagramEditor() && diagram != null) {
              try {
                DcdDiagramEditorUtil.openDiagram(diagram);
              } catch (PartInitException e) {
                PartInitException ce = (PartInitException) e;
                StatusManager.getManager()
                    .handle(
                        new Status(
                            ce.getStatus().getSeverity(),
                            "mil.jpeojtrs.sca.dcd.diagram",
                            Messages.DcdCreationWizardOpenEditorError,
                            e),
                        StatusManager.SHOW | StatusManager.LOG);
              }
            }
          }
        };
    try {
      getContainer().run(false, true, op);
    } catch (InterruptedException e) {
      return false;
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof CoreException) {
        CoreException ce = (CoreException) e.getTargetException();
        StatusManager.getManager()
            .handle(
                new Status(
                    ce.getStatus().getSeverity(),
                    "mil.jpeojtrs.sca.dcd.diagram",
                    Messages.DcdCreationWizardCreationError,
                    e),
                StatusManager.SHOW | StatusManager.LOG);
      } else {
        DcdDiagramEditorPlugin.getInstance()
            .logError("Error creating diagram", e.getTargetException()); // $NON-NLS-1$
      }
      return false;
    }
    return diagram != null;
  }
示例#29
0
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (method.getDeclaringClass() == Locatable.class) return method.invoke(this, args);
      if (Modifier.isStatic(method.getModifiers()))
        // malicious code can pass in a static Method object.
        // doing method.invoke() would end up executing it,
        // so we need to protect against it.
        throw new IllegalArgumentException();

      return method.invoke(core, args);
    } catch (InvocationTargetException e) {
      if (e.getTargetException() != null) throw e.getTargetException();
      throw e;
    }
  }
  /** @generated */
  public boolean performFinish() {
    IRunnableWithProgress op =
        new WorkspaceModifyOperation(null) {

          protected void execute(IProgressMonitor monitor)
              throws CoreException, InterruptedException {
            diagram =
                IOTApplication.diagram.part.ApplicationMetaModelDiagramEditorUtil.createDiagram(
                    diagramModelFilePage.getURI(), domainModelFilePage.getURI(), monitor);
            if (isOpenNewlyCreatedDiagramEditor() && diagram != null) {
              try {
                IOTApplication.diagram.part.ApplicationMetaModelDiagramEditorUtil.openDiagram(
                    diagram);
              } catch (PartInitException e) {
                ErrorDialog.openError(
                    getContainer().getShell(),
                    IOTApplication.diagram
                        .part
                        .Messages
                        .ApplicationMetaModelCreationWizardOpenEditorError,
                    null,
                    e.getStatus());
              }
            }
          }
        };
    try {
      getContainer().run(false, true, op);
    } catch (InterruptedException e) {
      return false;
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof CoreException) {
        ErrorDialog.openError(
            getContainer().getShell(),
            IOTApplication.diagram.part.Messages.ApplicationMetaModelCreationWizardCreationError,
            null,
            ((CoreException) e.getTargetException()).getStatus());
      } else {
        IOTApplication.diagram
            .part
            .ApplicationMetaModelDiagramEditorPlugin
            .getInstance()
            .logError("Error creating diagram", e.getTargetException()); // $NON-NLS-1$
      }
      return false;
    }
    return diagram != null;
  }