Esempio n. 1
1
  protected PsmMethodAction(Class c, String m, Class[] argArray) {
    // This prevents IllegalAccessExceptions when attempting to
    // invoke methods on a class that is in another package and not
    // defined 'public'.
    if (!Modifier.isPublic(c.getModifiers())) {
      throw new IllegalPsmMethodActionException("Action class must be public.");
    }

    try {
      method = c.getMethod(m, argArray);
    } catch (NoSuchMethodException ex) {
      throw new IllegalPsmMethodActionException(ex.toString() + ": method " + m);
    }

    // Check each exception this method declares thrown.  If it declares
    // exceptions, and any of them are not runtime exceptions, abort.
    Class[] exceptionTypes = method.getExceptionTypes();
    for (int i = 0; i < exceptionTypes.length; i++) {
      Class exceptionClass = exceptionTypes[i];
      if (!RuntimeException.class.isAssignableFrom(exceptionClass)) {
        throw new IllegalPsmMethodActionException(
            "Method must not declare non-Runtime " + "exceptions.");
      }
    }

    // Ensure that the method returns PsmEvent
    if (PsmEvent.class != method.getReturnType()) {
      throw new IllegalPsmMethodActionException("Method return type must be PsmEvent");
    }

    // Ensure that both the method is both public and static.
    if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) {
      throw new IllegalPsmMethodActionException("Method " + m + " must be static and public.");
    }
  }
Esempio n. 2
0
  /**
   * Invokes this method with the provided arguments
   *
   * @param args @return @throws WiseException If an unknown exception is received
   * @throws WiseWebServiceException There are 4 known failure conditions - The wsdl (url) could not
   *     be found - The wsdl is password protected - The endpoint (url) could not be found - The
   *     endpoint is password protected
   * @throws InvocationException
   * @throws IllegalArgumentException
   */
  InvocationResultImpl invoke(Map<String, Object> args)
      throws WiseWebServiceException, InvocationException, IllegalArgumentException {
    InvocationResultImpl result = null;
    Map<String, Object> emptyHolder = Collections.emptyMap();

    try {
      EndpointMethodCaller caller =
          new EndpointMethodCaller(
              this.getEndpoint(), this.getMethod(), this.getParametersInRightPositionArray(args));
      Future<Object> invocation = ((WSEndpointImpl) this.getEndpoint()).getService().submit(caller);
      if (isOneWay()) {
        invocation.get();
        result = new InvocationResultImpl(null, null, null, emptyHolder);
      } else {
        result =
            new InvocationResultImpl(
                RESULT, method.getGenericReturnType(), invocation.get(), getHoldersResult(args));
      }
    } catch (java.util.concurrent.ExecutionException wse) {
      Throwable ite = wse.getCause();
      if (ite != null && ite != wse && ite instanceof InvocationTargetException) {
        Throwable t = ite.getCause();

        // unchecked exception ?
        if (t != null && t != ite && t != wse && t instanceof WebServiceException) {
          // authentication exception ?
          if (isAuthenticationException(t, new HashSet<Throwable>())) {
            throw new WiseWebServiceException(
                "Authentication exception", null); // TODO improve this
          }
          throw new WiseWebServiceException(t.getMessage(), t);
        }

        // checked exception ?
        if (t != null && t != ite && t != wse && t instanceof Exception) {
          Method methodPointer = this.getMethod();
          if (methodPointer != null && methodPointer.getExceptionTypes() != null) {
            for (int i = 0; i < methodPointer.getExceptionTypes().length; i++) {
              Class<?> excType = methodPointer.getExceptionTypes()[i];
              if (t.getClass().isAssignableFrom(excType)) {
                // checked exception
                result = new InvocationResultImpl("exception", excType, t, emptyHolder);
                return result;
              }
            }
          }
        }

        throw new InvocationException("Unknown exception received: " + ite.getMessage(), ite);
      }
      throw new WiseWebServiceException(wse.getMessage(), wse);
    } catch (Throwable e) {
      throw new InvocationException("Generic Error during method invocation!", e);
    }
    return result;
  }
Esempio n. 3
0
  public void addMethod(Method method, int access) throws Exception {
    boolean isAbstract = false;

    if (Modifier.isAbstract(access)) {
      access = access & ~Modifier.ABSTRACT;
      isAbstract = true;
    }

    Class<?>[] parameters = method.getParameterTypes();
    Class<?> ret = method.getReturnType();
    String sig = makeSig(ret, parameters);

    String name = method.getName();
    names.add(name);

    Code code = classfile.addMethod(name, sig, access);

    code.aload(0);
    code.ldc(name);

    if (!isAbstract) {
      int tmp = code.getLocal("org/python/core/PyObject");
      code.invokestatic(
          "org/python/compiler/ProxyMaker", "findPython", makeSig($pyObj, $pyProxy, $str));
      code.astore(tmp);
      code.aload(tmp);

      Label callPython = new Label();
      code.ifnonnull(callPython);

      String superClass = mapClass(method.getDeclaringClass());

      callSuper(code, name, superClass, parameters, ret, sig);
      code.label(callPython);
      code.aload(tmp);
      callMethod(code, name, parameters, ret, method.getExceptionTypes());

      addSuperMethod("super__" + name, name, superClass, parameters, ret, sig, access);
    } else {
      code.invokestatic(
          "org/python/compiler/ProxyMaker", "findPython", makeSig($pyObj, $pyProxy, $str));
      code.dup();
      Label returnNull = new Label();
      code.ifnull(returnNull);
      callMethod(code, name, parameters, ret, method.getExceptionTypes());
      code.label(returnNull);
      code.pop();
      doNullReturn(code, ret);
    }
  }
 /** Handles remote methods. */
 private Object invokeRemoteMethod(Object proxy, Method method, Object[] args) throws Exception {
   try {
     if (!(proxy instanceof Remote)) {
       throw new IllegalArgumentException("proxy not Remote instance");
     }
     return ref.invoke((Remote) proxy, method, args, getMethodHash(method));
   } catch (Exception e) {
     if (!(e instanceof RuntimeException)) {
       Class<?> cl = proxy.getClass();
       try {
         method = cl.getMethod(method.getName(), method.getParameterTypes());
       } catch (NoSuchMethodException nsme) {
         throw (IllegalArgumentException) new IllegalArgumentException().initCause(nsme);
       }
       Class<?> thrownType = e.getClass();
       for (Class<?> declaredType : method.getExceptionTypes()) {
         if (declaredType.isAssignableFrom(thrownType)) {
           throw e;
         }
       }
       e = new UnexpectedException("unexpected exception", e);
     }
     throw e;
   }
 }
Esempio n. 5
0
  public void handleMessage(Message msg) {
    Fault fault = (Fault) msg.getContent(Exception.class);

    if (fault.getDetail() != null
        && !MessageUtils.getContextualBoolean(msg, DISABLE_FAULT_MAPPING, false)) {
      processFaultDetail(fault, msg);
      setStackTrace(fault, msg);
    }

    FaultMode faultMode = FaultMode.UNCHECKED_APPLICATION_FAULT;

    // Check if the raised exception is declared in the WSDL or by the JAX-RS resource
    Method m = msg.getExchange().get(Method.class);
    if (m != null) {
      Exception e = msg.getContent(Exception.class);
      for (Class<?> cl : m.getExceptionTypes()) {
        if (cl.isInstance(e)) {
          faultMode = FaultMode.CHECKED_APPLICATION_FAULT;
          break;
        }
      }
    }

    msg.getExchange().put(FaultMode.class, faultMode);
  }
Esempio n. 6
0
 public static JoinPoint.StaticPart makeEncSJP(Member member) {
   Signature sig = null;
   String kind = null;
   if (member instanceof Method) {
     Method method = (Method) member;
     sig =
         new MethodSignatureImpl(
             method.getModifiers(),
             method.getName(),
             method.getDeclaringClass(),
             method.getParameterTypes(),
             new String[method.getParameterTypes().length],
             method.getExceptionTypes(),
             method.getReturnType());
     kind = JoinPoint.METHOD_EXECUTION;
   } else if (member instanceof Constructor) {
     Constructor cons = (Constructor) member;
     sig =
         new ConstructorSignatureImpl(
             cons.getModifiers(),
             cons.getDeclaringClass(),
             cons.getParameterTypes(),
             new String[cons.getParameterTypes().length],
             cons.getExceptionTypes());
     kind = JoinPoint.CONSTRUCTOR_EXECUTION;
   } else {
     throw new IllegalArgumentException("member must be either a method or constructor");
   }
   return new JoinPointImpl.EnclosingStaticPartImpl(-1, kind, sig, null);
 }
 private List<Method> GetMethods(java.lang.reflect.Method[] methods) {
   List<Method> list = new ArrayList<>();
   for (java.lang.reflect.Method mthd : methods) {
     String visibility = this.GetVisibility(mthd.getModifiers());
     boolean isStatic = this.GetIsStatic(mthd.getModifiers());
     boolean isfinal = this.GetIsFinal(mthd.getModifiers());
     String outputType = mthd.getGenericReturnType().toString();
     List<InputParameter> inputParameters = this.GetInputParameters(mthd.getParameters());
     List<String> annotations = this.GetAnnotations(mthd.getAnnotations());
     String name = mthd.getName();
     if (name.contains("_")) continue;
     boolean isThrowExceptions = false;
     if (mthd.getExceptionTypes().length > 0) {
       isThrowExceptions = true;
     }
     Method method =
         ModelFactory.GetMethodWithValue(
             outputType,
             name,
             visibility,
             isfinal,
             isStatic,
             isThrowExceptions,
             inputParameters,
             annotations,
             new ArrayList<>());
     list.add(method);
   }
   return list;
 }
Esempio n. 8
0
  /** java.lang.reflect.Method#getExceptionTypes() */
  public void test_getExceptionTypes() {
    // Test for method java.lang.Class []
    // java.lang.reflect.Method.getExceptionTypes()

    try {
      Method mth = TestMethod.class.getMethod("voidMethod", new Class[0]);
      Class[] ex = mth.getExceptionTypes();
      assertEquals("Returned incorrect number of exceptions", 1, ex.length);
      assertTrue("Returned incorrect exception type", ex[0].equals(IllegalArgumentException.class));
      mth = TestMethod.class.getMethod("intMethod", new Class[0]);
      ex = mth.getExceptionTypes();
      assertEquals("Returned incorrect number of exceptions", 0, ex.length);
    } catch (Exception e) {
      fail("Exception during getExceptionTypes: " + e.toString());
    }
  }
    ReadInvocationHandler(
        final Node node,
        final Method method,
        final String annotationValue,
        final XBProjector projector,
        final boolean absentIsEmpty) {
      super(node, method, annotationValue, projector);
      wrappedInOptional = ReflectionHelper.isOptional(method.getGenericReturnType());
      returnType =
          wrappedInOptional
              ? ReflectionHelper.getParameterType(method.getGenericReturnType())
              : method.getReturnType();
      Class<?>[] exceptionTypes = method.getExceptionTypes();
      exceptionType = exceptionTypes.length > 0 ? exceptionTypes[0] : null;
      this.isConvertable = projector.config().getTypeConverter().isConvertable(returnType);
      this.isReturnAsNode = Node.class.isAssignableFrom(returnType);
      this.isEvaluateAsList =
          List.class.equals(returnType) || ReflectionHelper.isStreamClass(returnType);
      this.isReturnAsStream = ReflectionHelper.isStreamClass(returnType);
      this.isEvaluateAsArray = returnType.isArray();
      if (wrappedInOptional && (isEvaluateAsArray || isEvaluateAsList)) {
        throw new IllegalArgumentException(
            "Method "
                + method
                + " must not declare an optional return type of list or array. Lists and arrays may be empty but will never be null.");
      }
      this.isEvaluateAsSubProjection = returnType.isInterface();
      this.isThrowIfAbsent = exceptionType != null;

      // Throwing exception overrides empty default value.
      this.absentIsEmpty = absentIsEmpty && (!isThrowIfAbsent);
    }
Esempio n. 10
0
  private boolean isDeclared(Exception e, Method m) {
    Class[] types = m.getExceptionTypes();
    for (int i = 0; i < types.length; i++) {
      if (types[i].isAssignableFrom(e.getClass())) return true;
    }

    return false;
  }
Esempio n. 11
0
  /**
   * Recursively finds methods of the specified access level in the supplied class and superclasses.
   *
   * @param c the class to start the search in - nothing is done if this is NULL
   * @param level the access level to look for
   * @param sb the StringBuffer where the results should be added
   */
  private static void recursiveListMethods(Class c, int level, StringBuffer sb) {
    // This is only used while initializing
    if (c == null) {
      return;
    }

    Method[] methods;
    Method method;
    Class[] exceptions;
    StringBuffer temp;

    // ----- Added by Petter for interfaces
    if (level == PUBLIC) {
      // For public access, we can use getMethods() and skip
      // recursion. This ensures that the method works for
      // interface types, and saves some function calls.
      methods = c.getMethods();
    } else {
      methods = c.getDeclaredMethods();
    }
    // ----- End addition by Petter

    for (int index = 0; index < methods.length; index++) {
      method = methods[index];
      if (isAccessible(method.getModifiers(), level)) {
        temp = new StringBuffer(100);
        temp.append(
            printMethod(
                method.getName(), className(method.getReturnType()), method.getParameterTypes()));
        // Add exceptions
        exceptions = method.getExceptionTypes();

        if (exceptions.length > 0) {
          temp.append(printExceptions(exceptions));
        } else {
          temp.append(NIL);
        }
        temp.append(END_PAREN);

        if (sb.toString().lastIndexOf(temp.toString()) == -1) {
          sb.append(temp);
        }
      }
    }

    // ----- Addition by Petter to reduce the number of function
    //       calls and not list non-accessible private fields.
    if (!c.isInterface() && level != PRIVATE && level != PUBLIC) {
      // For interfaces, the getSuperClass() method will return
      // nil, and in any case, the only type of access relevant
      // for interfaces is PUBLIC. For PUBLIC access, the
      // getMethods() call has listed all the relevant members.
      // For PRIVATE access, that is only applicable in the
      // calling class anyway, so we shouldn't do recursion.
      recursiveListMethods(c.getSuperclass(), level, sb);
    }
    // ----- End addition by Petter
  }
Esempio n. 12
0
  boolean isRemoteMethod(java.lang.reflect.Method m) {
    Class[] ex = m.getExceptionTypes();

    for (Class anEx : ex) {
      if (anEx.isAssignableFrom(REMOTE_EXCEPTION)) return true;
    }

    return false;
  }
Esempio n. 13
0
 private static boolean declaresInterruptedEx(Method method) {
   for (Class<?> exType : method.getExceptionTypes()) {
     // debate: == or isAssignableFrom?
     if (exType == InterruptedException.class) {
       return true;
     }
   }
   return false;
 }
Esempio n. 14
0
  /** Validates that the given method's signature meets all of our assumptions. */
  private static void validateMethod(Method method) {
    String desc = method.toString();

    assertTrue(desc, isAnyEnter(method) || isWaitFor(method));

    switch (method.getParameterTypes().length) {
      case 0:
        assertFalse(desc, isGuarded(method));
        assertFalse(desc, isTimed(method));
        break;
      case 1:
        assertTrue(desc, isGuarded(method));
        assertFalse(desc, isTimed(method));
        break;
      case 2:
        assertFalse(desc, isGuarded(method));
        assertTrue(desc, isTimed(method));
        break;
      case 3:
        assertTrue(desc, isGuarded(method));
        assertTrue(desc, isTimed(method));
        break;
      default:
        fail(desc);
    }

    if (method.getReturnType() == void.class) {
      assertFalse(desc, isBoolean(method));
    } else {
      assertTrue(desc, isBoolean(method));
    }

    switch (method.getExceptionTypes().length) {
      case 0:
        assertFalse(desc, isInterruptible(method));
        break;
      case 1:
        assertTrue(desc, isInterruptible(method));
        break;
      default:
        fail(desc);
    }

    if (isEnterIf(method)) {
      assertTrue(desc, isGuarded(method));
      assertTrue(desc, isBoolean(method));
    } else if (isTryEnter(method)) {
      assertFalse(desc, isTimed(method));
      assertTrue(desc, isBoolean(method));
      assertFalse(desc, isInterruptible(method));
    } else if (isWaitFor(method)) {
      assertTrue(desc, isGuarded(method));
      assertEquals(desc, isTimed(method), isBoolean(method));
    } else { // any other enterXxx method
      assertEquals(desc, isTimed(method), isBoolean(method));
    }
  }
Esempio n. 15
0
 /**
  * Determines if a method is a valid lifecycle callback method.
  *
  * @param method The method to test
  * @return <code>true</code> if the method is a valid lifecycle callback method, else <code>false
  *     </code>
  */
 public static boolean isValidLifecycleCallback(Method method) {
   if (method.getParameterTypes().length != 0
       || Modifier.isStatic(method.getModifiers())
       || method.getExceptionTypes().length > 0
       || !method.getReturnType().getName().equals("void")) {
     return false;
   }
   return true;
 }
Esempio n. 16
0
 /**
  * Determine whether the given method explicitly declares the given exception or one of its
  * superclasses, which means that an exception of that type can be propagated as-is within a
  * reflective invocation.
  *
  * @param method the declaring method
  * @param exceptionType the exception to throw
  * @return <code>true</code> if the exception can be thrown as-is; <code>false</code> if it needs
  *     to be wrapped
  */
 public static boolean declaresException(Method method, Class<?> exceptionType) {
   Assert.notNull(method, "Method must not be null");
   Class<?>[] declaredExceptions = method.getExceptionTypes();
   for (Class<?> declaredException : declaredExceptions) {
     if (declaredException.isAssignableFrom(exceptionType)) {
       return true;
     }
   }
   return false;
 }
Esempio n. 17
0
 /**
  * Create a new {@link Function} that is linked with a native function that follows the
  * NativeLibrary's calling convention.
  *
  * <p>The allocated instance represents a pointer to the named native function from the library.
  *
  * @param name Name of the native function to be linked with
  * @param method Method to which the native function is to be mapped
  * @throws UnsatisfiedLinkError if the function is not found
  */
 Function getFunction(String name, Method method) {
   int flags = this.callFlags;
   Class[] etypes = method.getExceptionTypes();
   for (int i = 0; i < etypes.length; i++) {
     if (LastErrorException.class.isAssignableFrom(etypes[i])) {
       flags |= Function.THROW_LAST_ERROR;
     }
   }
   return getFunction(name, flags);
 }
Esempio n. 18
0
  private void checkResponse(Method m, Response r, Message inMessage) throws Throwable {
    Throwable t = null;
    int status = r.getStatus();

    if (status >= 300) {
      Class<?>[] exTypes = m.getExceptionTypes();
      if (exTypes.length == 0) {
        exTypes = new Class[] {WebApplicationException.class};
      }
      for (Class<?> exType : exTypes) {
        ResponseExceptionMapper<?> mapper = findExceptionMapper(inMessage, exType);
        if (mapper != null) {
          t = mapper.fromResponse(r);
          if (t != null) {
            throw t;
          }
        }
      }

      if ((t == null)
          && (m.getReturnType() == Response.class)
          && (m.getExceptionTypes().length == 0)) {
        return;
      }

      t = convertToWebApplicationException(r);

      if (inMessage.getExchange().get(Message.RESPONSE_CODE) == null) {
        throw t;
      }

      Endpoint ep = inMessage.getExchange().getEndpoint();
      inMessage.getExchange().put(InterceptorProvider.class, getConfiguration());
      inMessage.setContent(Exception.class, new Fault(t));
      inMessage.getInterceptorChain().abort();
      if (ep.getInFaultObserver() != null) {
        ep.getInFaultObserver().onMessage(inMessage);
      }

      throw t;
    }
  }
  private static <T> Object doInvoke(
      final EJBInvocationHandler<T> ejbInvocationHandler,
      final boolean async,
      final T proxy,
      final Method method,
      final Object[] args,
      EJBClientContext clientContext)
      throws Throwable {
    final EJBClientInvocationContext invocationContext =
        new EJBClientInvocationContext(ejbInvocationHandler, clientContext, proxy, method, args);

    try {
      // send the request
      sendRequestWithPossibleRetries(invocationContext, true);

      if (!async) {
        // wait for invocation to complete
        final Object value = invocationContext.awaitResponse();
        if (value != EJBClientInvocationContext.PROCEED_ASYNC) {
          return value;
        }
        // proceed asynchronously
      }
      // force async...
      if (method.getReturnType() == Future.class) {
        return invocationContext.getFutureResponse();
      } else if (method.getReturnType() == void.class) {
        invocationContext.setDiscardResult();
        // Void return
        return null;
      } else {
        // wrap return always
        EJBClient.setFutureResult(invocationContext.getFutureResponse());
        return null;
      }
    } catch (Exception e) {
      // AS7-5937 prevent UndeclaredThrowableException
      if (e instanceof RuntimeException) {
        throw e;
      }
      boolean remoteException = false;
      for (Class<?> exception : method.getExceptionTypes()) {
        if (exception.isAssignableFrom(e.getClass())) {
          throw e;
        } else if (RemoteException.class.equals(exception)) {
          remoteException = true;
        }
      }
      if (remoteException) {
        throw new RemoteException("Error", e);
      }
      throw new EJBException(e);
    }
  }
Esempio n. 20
0
 private static boolean isUnicastByDefault(Method addMethod) {
   if (addMethod != null) {
     Class<?>[] exceptionTypes = addMethod.getExceptionTypes();
     for (Class<?> element : exceptionTypes) {
       if (element.equals(TooManyListenersException.class)) {
         return true;
       }
     }
   }
   return false;
 }
Esempio n. 21
0
  /**
   * @param eventName
   * @return
   */
  public FragmentEvent getEvent(final String eventName) {
    if (eventName == null || eventName.trim().equals("")) {
      return null;
    }
    if (this.regEvent == null) {
      return null;
    }
    FragmentEvent event = this.regEvent.find(eventName);
    synchronized (this.regEvent) {
      if (event == null) {
        try {
          final Method method =
              this.getClass().getMethod(eventName, new Class[] {HtmlFragmentRequest.class});
          Class<?>[] exceptions = method.getExceptionTypes();
          boolean hasException = false;
          for (Class<?> exception : exceptions) {
            if (exception.isAssignableFrom(FragmentEventException.class)) {
              hasException = true;
            }
          }
          if (method.getReturnType().isAssignableFrom(HtmlFragmentResponse.class) && hasException) {
            event =
                new FragmentEvent() {
                  private String name = eventName;
                  private Method event = method;

                  @Override
                  public String getName() {
                    return this.name;
                  }

                  @Override
                  public HtmlFragmentResponse execute(HtmlFragmentRequest req, Action action)
                      throws FragmentEventException {
                    try {
                      return (HtmlFragmentResponse) this.event.invoke(action, req);
                    } catch (Exception e) {
                      throw new FragmentEventException(e);
                    }
                  }
                };
            this.regEvent.add(event);
          } else {
            return null;
          }
        } catch (Exception e) {
          return null;
        }
      }
    }
    return this.regEvent.find(eventName);
  }
  /**
   * Visit every class/interface this proxy should implement, and generate the appropriate bytecode
   * for delegation if available.
   *
   * @param clazz an class for which to generate bytecode
   */
  private void visitClass(final Class clazz) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
      Class<?>[] exceptionTypes = method.getExceptionTypes();
      String[] exceptions = new String[exceptionTypes.length];
      for (int i = 0; i < exceptions.length; i++) {
        exceptions[i] = BytecodeHelper.getClassInternalName(exceptionTypes[i]);
      }
      // for each method defined in the class, generate the appropriate delegation bytecode
      visitMethod(
          method.getModifiers(),
          method.getName(),
          BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes()),
          null,
          exceptions);
    }
    Constructor[] constructors = clazz.getDeclaredConstructors();
    for (Constructor method : constructors) {
      Class<?>[] exceptionTypes = method.getExceptionTypes();
      String[] exceptions = new String[exceptionTypes.length];
      for (int i = 0; i < exceptions.length; i++) {
        exceptions[i] = BytecodeHelper.getClassInternalName(exceptionTypes[i]);
      }
      // for each method defined in the class, generate the appropriate delegation bytecode
      visitMethod(
          method.getModifiers(),
          "<init>",
          BytecodeHelper.getMethodDescriptor(Void.TYPE, method.getParameterTypes()),
          null,
          exceptions);
    }

    for (Class intf : clazz.getInterfaces()) {
      visitClass(intf);
    }
    Class superclass = clazz.getSuperclass();
    if (superclass != null) visitClass(superclass);

    // Ultimately, methods can be available in the closure map which are not defined by the
    // superclass
    // nor the interfaces
    for (Map.Entry<String, Boolean> entry : delegatedClosures.entrySet()) {
      Boolean visited = entry.getValue();
      if (!visited) {
        String name = entry.getKey();
        if (!"*".equals(name)) {
          // generate a new method
          visitMethod(ACC_PUBLIC, name, "([Ljava/lang/Object;)Ljava/lang/Object;", null, null);
        }
      }
    }
  }
Esempio n. 23
0
 private Object preprocess(Method method) {
   try {
     return preprocessMethodOrConstructor(
         method.getModifiers(),
         method.getReturnType(),
         method.getDeclaringClass(),
         method.getName(),
         method.getParameterTypes(),
         method.getExceptionTypes());
   } catch (Exception e) {
     return "<" + e + ">";
   }
 }
Esempio n. 24
0
  @Override
  protected void addMethodsFromClass(ClassFile proxyClassType) {
    Method initializerMethod = null;
    int delegateParameterPosition = -1;
    if (delegateInjectionPoint instanceof ParameterInjectionPoint<?, ?>) {
      ParameterInjectionPoint<?, ?> parameterIP =
          (ParameterInjectionPoint<?, ?>) delegateInjectionPoint;
      if (parameterIP.getMember() instanceof Method) {
        initializerMethod = ((Method) parameterIP.getMember());
        delegateParameterPosition = parameterIP.getPosition();
      }
    }
    try {
      if (delegateParameterPosition >= 0) {
        addHandlerInitializerMethod(proxyClassType);
      }
      Class<?> cls = getBeanType();
      while (cls != null) {
        for (Method method : cls.getDeclaredMethods()) {
          MethodInformation methodInfo = new RuntimeMethodInformation(method);
          if (!method.getDeclaringClass().getName().equals("java.lang.Object")
              || method.getName().equals("toString")) {
            Bytecode methodBody = null;
            if ((delegateParameterPosition >= 0) && (initializerMethod.equals(method))) {
              methodBody =
                  createDelegateInitializerCode(
                      proxyClassType, methodInfo, delegateParameterPosition);
            }
            if (Modifier.isAbstract(method.getModifiers())) {
              methodBody = createAbstractMethodCode(proxyClassType, methodInfo);
            }

            if (methodBody != null) {
              log.trace("Adding method " + method);
              proxyClassType.addMethod(
                  MethodUtils.makeMethod(
                      methodInfo,
                      method.getExceptionTypes(),
                      methodBody,
                      proxyClassType.getConstPool()));
            }
          }
        }
        cls = cls.getSuperclass();
      }
    } catch (Exception e) {
      throw new WeldException(e);
    }
  }
Esempio n. 25
0
    AccessType(Method method) {
      int modifier = method.getModifiers();
      if (Modifier.isPrivate(modifier)) {
        throw new UnsupportedOperationException("method = private");
      }
      if (Modifier.isFinal(modifier)) {
        throw new UnsupportedOperationException("method = final");
      }

      this.method = method;

      accesssType = "";
      staticType = "";
      syncType = "";
      methodName = "";

      methodName = method.getName();

      if (Modifier.isProtected(modifier)) {
        accesssType = "protected";
      }
      if (Modifier.isPackage(modifier)) {
        accesssType = "";
      }
      if (Modifier.isPublic(modifier)) {
        accesssType = "public";
      }
      if (Modifier.isStatic(modifier)) {
        staticType = "static";
      }
      if (Modifier.isSynchronized(modifier)) {
        syncType = "synchronized";
      }

      returnType = createParameterName(method.getReturnType());

      Set<String> throwSet = new HashSet<String>();
      for (Class<?> ex : method.getExceptionTypes()) {
        throwSet.add(ex.getSimpleName());
      }
      this.throwSet = throwSet;

      List<Parameter> paramList = new ArrayList<Parameter>();
      for (Class<?> p : method.getParameterTypes()) {
        paramList.add(createParameterName(p));
      }
      this.paramList = paramList;
    }
Esempio n. 26
0
 public ApplicationExceptionDetails getApplicationException(
     Class<?> exceptionClass, Method invokedMethod) {
   ApplicationExceptionDetails applicationException =
       this.applicationExceptions.get(exceptionClass);
   if (applicationException != null) {
     return applicationException;
   }
   // Check if the super class of the passed exception class, is an application exception.
   Class<?> superClass = exceptionClass.getSuperclass();
   while (superClass != null
       && !(superClass.equals(Exception.class) || superClass.equals(Object.class))) {
     applicationException = this.applicationExceptions.get(superClass);
     // check whether the "inherited" attribute is set. A subclass of an application exception
     // is an application exception only if the inherited attribute on the parent application
     // exception
     // is set to true.
     if (applicationException != null) {
       if (applicationException.isInherited()) {
         return applicationException;
       }
       // Once we find a super class which is an application exception,
       // we just stop there (no need to check the grand super class), irrespective of whether the
       // "inherited"
       // is true or false
       return null; // not an application exception, so return null
     }
     // move to next super class
     superClass = superClass.getSuperclass();
   }
   // AS7-1317: examine the throws clause of the method
   // An unchecked-exception is only an application exception if annotated (or described) as such.
   // (see EJB 3.1 FR 14.2.1)
   if (RuntimeException.class.isAssignableFrom(exceptionClass)
       || Error.class.isAssignableFrom(exceptionClass)) return null;
   if (invokedMethod != null) {
     final Class<?>[] exceptionTypes = invokedMethod.getExceptionTypes();
     for (Class<?> type : exceptionTypes) {
       if (type.isAssignableFrom(exceptionClass)) return APPLICATION_EXCEPTION;
     }
   }
   // not an application exception, so return null.
   return null;
 }
  public static void main(String[] args) throws Exception {
    Class cls = RepositoryService.class;
    String line = "";
    Method[] methods = cls.getMethods();
    for (int i = 0; i < methods.length; i++) {
      Method meth = methods[i];
      if (meth.getDeclaringClass() == cls) {
        Class[] exes = meth.getExceptionTypes();

        String retType = typeName(meth.getReturnType().getName());
        line += "public " + retType + " " + meth.getName() + "(";
        Class params[] = meth.getParameterTypes();
        String body = "getService()." + meth.getName() + "(";
        for (int j = 0; j < params.length; j++) {
          String type = params[j].getName();
          type = typeName(type);
          line += type;
          line += " p" + j;
          body += " p" + j;
          if (j < params.length - 1) {
            line += ", ";
            body += ", ";
          }
        }

        body += ");";
        line += ") ";
        if (exes.length > 0) {
          line += "throws " + exes[0].getName();
        }
        line += " {\n";
        if (retType.equals("void")) {
          line += "\t" + body + "\n";
        } else {
          line += "\t return " + body + "\n";
        }
        line += "}\n";
      }
    }
    System.out.println("/** PLACE THE FOLLOWING IN RepositoryServiceServlet.java **/\n");

    System.out.println(line);
  }
  public void doHandle(Class clazz) {
    // Check that the PreDestroy is on a class that we're interested in
    if (Util.supportsPostConstructPreDestroy(clazz)) {
      Method[] methods = clazz.getDeclaredMethods();
      for (int i = 0; i < methods.length; i++) {
        Method m = (Method) methods[i];
        if (m.isAnnotationPresent(PreDestroy.class)) {
          if (m.getParameterTypes().length != 0)
            throw new IllegalStateException(m + " has parameters");
          if (m.getReturnType() != Void.TYPE) throw new IllegalStateException(m + " is not void");
          if (m.getExceptionTypes().length != 0)
            throw new IllegalStateException(m + " throws checked exceptions");
          if (Modifier.isStatic(m.getModifiers()))
            throw new IllegalStateException(m + " is static");

          // ServletSpec 3.0 p80 If web.xml declares even one predestroy then all predestroys
          // in fragments must be ignored. Otherwise, they are additive.
          MetaData metaData = _context.getMetaData();
          Origin origin = metaData.getOrigin("pre-destroy");
          if (origin != null
              && (origin == Origin.WebXml
                  || origin == Origin.WebDefaults
                  || origin == Origin.WebOverride)) return;

          PreDestroyCallback callback = new PreDestroyCallback();
          callback.setTarget(clazz.getName(), m.getName());

          LifeCycleCallbackCollection lifecycles =
              (LifeCycleCallbackCollection)
                  _context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION);
          if (lifecycles == null) {
            lifecycles = new LifeCycleCallbackCollection();
            _context.setAttribute(
                LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION, lifecycles);
          }

          lifecycles.add(callback);
        }
      }
    }
  }
Esempio n. 29
0
  public void configureClassNode(CompileUnit compileUnit, ClassNode classNode) {
    Class clazz = classNode.getTypeClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field f : fields) {
      ClassNode ret = makeClassNode(compileUnit, f.getGenericType(), f.getType());
      classNode.addField(f.getName(), f.getModifiers(), ret, null);
    }
    Method[] methods = clazz.getDeclaredMethods();
    for (Method m : methods) {
      ClassNode ret = makeClassNode(compileUnit, m.getGenericReturnType(), m.getReturnType());
      Parameter[] params =
          makeParameters(compileUnit, m.getGenericParameterTypes(), m.getParameterTypes());
      ClassNode[] exceptions =
          makeClassNodes(compileUnit, m.getGenericExceptionTypes(), m.getExceptionTypes());
      MethodNode mn = new MethodNode(m.getName(), m.getModifiers(), ret, params, exceptions, null);
      setMethodDefaultValue(mn, m);
      setAnnotationMetaData(m.getAnnotations(), mn);
      mn.setGenericsTypes(configureTypeVariable(m.getTypeParameters()));
      classNode.addMethod(mn);
    }
    Constructor[] constructors = clazz.getDeclaredConstructors();
    for (Constructor ctor : constructors) {
      Parameter[] params =
          makeParameters(compileUnit, ctor.getGenericParameterTypes(), ctor.getParameterTypes());
      ClassNode[] exceptions =
          makeClassNodes(compileUnit, ctor.getGenericExceptionTypes(), ctor.getExceptionTypes());
      classNode.addConstructor(ctor.getModifiers(), params, exceptions, null);
    }

    Class sc = clazz.getSuperclass();
    if (sc != null)
      classNode.setUnresolvedSuperClass(
          makeClassNode(compileUnit, clazz.getGenericSuperclass(), sc));
    makeInterfaceTypes(compileUnit, classNode, clazz);
    setAnnotationMetaData(classNode.getTypeClass().getAnnotations(), classNode);

    PackageNode packageNode = classNode.getPackage();
    if (packageNode != null) {
      setAnnotationMetaData(classNode.getTypeClass().getPackage().getAnnotations(), packageNode);
    }
  }
Esempio n. 30
-1
  /**
   * Creates a gateway instance for the given <code>gatewayInterface</code>. The returned instance
   * is a Proxy that implements that interface.
   *
   * @param gatewayInterface The interface declaring the gateway methods
   * @param <T> The interface declaring the gateway methods
   * @return A Proxy implementation implementing the given interface
   */
  @SuppressWarnings("unchecked")
  public <T> T createGateway(Class<T> gatewayInterface) {
    Map<Method, InvocationHandler> dispatchers = new HashMap<Method, InvocationHandler>();
    for (Method gatewayMethod : gatewayInterface.getMethods()) {
      MetaDataExtractor[] extractors = extractMetaData(gatewayMethod.getParameterAnnotations());

      InvocationHandler dispatcher =
          new DispatchOnInvocationHandler(
              commandBus, retryScheduler,
              dispatchInterceptors, extractors);
      final Class<?>[] arguments = gatewayMethod.getParameterTypes();
      if (Future.class.equals(gatewayMethod.getReturnType())) {
        // no wrapping
      } else if (arguments.length >= 3
          && TimeUnit.class.isAssignableFrom(arguments[arguments.length - 1])
          && (long.class.isAssignableFrom(arguments[arguments.length - 2])
              || int.class.isAssignableFrom(arguments[arguments.length - 2]))) {
        dispatcher =
            wrapToReturnWithTimeoutInArguments(
                dispatcher, arguments.length - 2, arguments.length - 1);
      } else {
        Timeout timeout = gatewayMethod.getAnnotation(Timeout.class);
        if (timeout == null) {
          timeout = gatewayMethod.getDeclaringClass().getAnnotation(Timeout.class);
        }
        if (timeout != null) {
          dispatcher = wrapToReturnWithFixedTimeout(dispatcher, timeout.value(), timeout.unit());
        } else if (!Void.TYPE.equals(gatewayMethod.getReturnType())
            || gatewayMethod.getExceptionTypes().length > 0) {
          dispatcher = wrapToWaitForResult(dispatcher);
        } else {
          dispatcher = wrapToFireAndForget(dispatcher);
        }
      }
      Class<?>[] declaredExceptions = gatewayMethod.getExceptionTypes();
      if (!contains(declaredExceptions, TimeoutException.class)) {
        dispatcher = wrapToReturnNullOnTimeout(dispatcher);
      }
      if (!contains(declaredExceptions, InterruptedException.class)) {
        dispatcher = wrapToReturnNullOnInterrupted(dispatcher);
      }
      dispatcher = wrapUndeclaredExceptions(dispatcher, declaredExceptions);
      dispatchers.put(gatewayMethod, dispatcher);
    }

    return gatewayInterface.cast(
        Proxy.newProxyInstance(
            gatewayInterface.getClassLoader(),
            new Class[] {gatewayInterface},
            new GatewayInvocationHandler(
                dispatchers, commandBus, retryScheduler, dispatchInterceptors)));
  }