private void addRoutes(Object handler) {
    Class clazz = handler.getClass();
    for (Method method : clazz.getMethods()) {
      int modifier = method.getModifiers();
      if (!(Modifier.isPublic(modifier))) continue;

      Class<?>[] paramTypes = method.getParameterTypes();
      if (paramTypes.length != 2
          || !paramTypes[0].equals(Request.class)
          || !paramTypes[1].equals(Response.class)) continue;

      Before beforeAnn = method.getAnnotation(Before.class);
      After afterAnn = method.getAnnotation(After.class);
      Route routeAnn = method.getAnnotation(Route.class);

      if (routeAnn != null) routes.add(new MatchEntity(handler, method, routeAnn));
      else if (beforeAnn != null) before.add(new MatchEntity(handler, method, beforeAnn));
      else if (afterAnn != null) after.add(new MatchEntity(handler, method, afterAnn));
    }

    if (L.isInfoEnabled()) {
      for (MatchEntity e : routes) L.info(null, "route " + ObjectUtils.toString(e));
      for (MatchEntity e : before) L.info(null, "before " + ObjectUtils.toString(e));
      for (MatchEntity e : after) L.info(null, "after " + ObjectUtils.toString(e));
    }
  }
Exemple #2
0
  private void initApiInfo() throws Exception {
    int apiCounter = 0;
    String[] beanNames = applicationContext.getBeanNamesForAnnotation(Controller.class);

    if (beanNames == null) {
      logger.info("No controller bean found. stop server and fix it.");
      throw new Exception("No controller bean found. stop server and fix it.");
    }

    Map<String, Object> checkMap = new HashMap<String, Object>();
    for (String beanName : beanNames) {
      logger.info("Controller bean found: " + beanName);
      Class<?> beanType = applicationContext.getType(beanName);

      Method[] methods = beanType.getMethods();
      for (Method method : methods) {
        if (method.getAnnotation(Api.class) != null
            && method.getAnnotation(RequestMapping.class) != null) {
          logger.info("Controller Api Method found: " + method.getName());
          if (checkMap.get(method.getName()) != null) {
            logger.info("Controller method name is duplicated! stop server and fix it.");
            throw new Exception("Controller method name is duplicated! stop server and fix it.");
          }
          checkMap.put(method.getName(), new Object());
          apiCounter++;
        }
      }
    }
    logger.info("Total {} api listed.", apiCounter);
    this.apiInfoCache = new ConcurrentHashMap<String, ApiInfo>();
  }
Exemple #3
0
  public static OptionSchema newOptionSchema(Class<?> optionHolderType) {
    OptionSchema optionSchema = new OptionSchema();

    // traverses through super classes
    for (Class<?> optionHolderClass = optionHolderType;
        optionHolderClass != null;
        optionHolderClass = optionHolderClass.getSuperclass()) {
      // looks for bean methods annotated with Option or Argument
      for (Method eachMethod : optionHolderClass.getDeclaredMethods()) {
        if (eachMethod.getAnnotation(Option.class) != null) optionSchema.addOptionItem(eachMethod);

        if (eachMethod.getAnnotation(Argument.class) != null)
          optionSchema.addArgumentItem(eachMethod);
      }

      // looks for bean fields annotated with Option or Argument
      for (Field f : optionHolderClass.getDeclaredFields()) {
        if (f.getAnnotation(Option.class) != null) optionSchema.addOptionItem(f);

        if (f.getAnnotation(Argument.class) != null) optionSchema.addArgumentItem(f);
      }

      if (optionHolderClass.getAnnotation(Usage.class) != null) {
        optionSchema.setUsage(optionHolderClass);
      }
    }

    return optionSchema;
  }
 public boolean run(CommandSender sender, String[] args) {
   for (Map.Entry<CommandBase, Method> e : map.entrySet()) {
     if (Util.hasString(args[0], e.getKey().getCommand())) {
       Method method = e.getValue();
       try {
         if (!(sender instanceof Player)
             || sender.hasPermission(
                 ((AddCommand) method.getAnnotation(AddCommand.class)).permission())) {
           return (boolean) method.invoke(method.getDeclaringClass().newInstance(), sender, args);
         } else {
           sender.sendMessage(
               ((AddCommand) method.getAnnotation(AddCommand.class)).permissionmessage());
           return true;
         }
       } catch (IllegalAccessException
           | IllegalArgumentException
           | InvocationTargetException
           | SecurityException
           | InstantiationException e1) {
         e1.printStackTrace();
         return false;
       }
     }
   }
   return false;
 }
Exemple #5
0
  public final Set<Action> listActions() {
    Set<Action> result = new HashSet<Action>();

    /*
     * Search on this entity, climbing up the class hierarchy.
     */
    Class<?> self = this.getClass();
    while (!Object.class.equals(self)) {
      for (Method m : self.getClass().getDeclaredMethods()) {
        if (m.isAnnotationPresent(Action.class)) {
          result.add(m.getAnnotation(Action.class));
        } // if
      } // for
      self = self.getSuperclass();
    } // while

    /*
     * Search on all mixins.
     */
    for (Object o : this.getMixins()) {
      for (Method m : o.getClass().getDeclaredMethods()) {
        if (m.isAnnotationPresent(Action.class)) {
          result.add(m.getAnnotation(Action.class));
        } // if
      } // for
    } // for

    return result;
  }
  private Status getProperties(Class<?> busInterface) throws AnnotationBusException {
    for (Method method : busInterface.getMethods()) {
      if (method.getAnnotation(BusProperty.class) != null) {
        String name = getName(method);
        Property property = properties.get(name);

        BusAnnotations propertyAnnotations = method.getAnnotation(BusAnnotations.class);
        TreeMap<String, String> annotations = new TreeMap<String, String>();
        if (propertyAnnotations != null) {
          for (BusAnnotation propertyAnnotation : propertyAnnotations.value()) {
            annotations.put(propertyAnnotation.name(), propertyAnnotation.value());
          }
        }

        if (property == null) {
          property = new Property(name, getPropertySig(method), annotations);
        } else if (!property.signature.equals(getPropertySig(method))) {
          return Status.BAD_ANNOTATION;
        }

        if (method.getName().startsWith("get")) {
          property.get = method;
        } else if (method.getName().startsWith("set")
            && (method.getGenericReturnType().equals(void.class))) {
          property.set = method;
        } else {
          return Status.BAD_ANNOTATION;
        }
        properties.put(name, property);
      }
    }
    return Status.OK;
  }
Exemple #7
0
  /**
   * Gets an annotation from the property. Checks fields, setters, and getters, in that order, for
   * the annotation specified.
   *
   * @param <T> The annotation type.
   * @param annotationType The type of the annotation
   * @return The first found instance of that annotation, per above.
   */
  public <T extends Annotation> T getAnnotation(final Class<T> annotationType) {
    T annotation = null;

    if (field != null) {
      annotation = this.field.getAnnotation(annotationType);

      if (annotation != null) {
        return annotation;
      }
    }

    if (setter != null) {
      annotation = setter.getAnnotation(annotationType);

      if (annotation != null) {
        return annotation;
      }
    }

    if (getter != null) {
      return getter.getAnnotation(annotationType);
    }

    return null;
  }
Exemple #8
0
 private static void handleAfters(Http.Request request) throws Exception {
   List<Method> afters =
       Java.findAllAnnotatedMethods(Controller.getControllerClass(), After.class);
   ControllerInstrumentation.stopActionCall();
   for (Method after : afters) {
     String[] unless = after.getAnnotation(After.class).unless();
     String[] only = after.getAnnotation(After.class).only();
     boolean skip = false;
     for (String un : only) {
       if (!un.contains(".")) {
         un = after.getDeclaringClass().getName().substring(12) + "." + un;
       }
       if (un.equals(request.action)) {
         skip = false;
         break;
       } else {
         skip = true;
       }
     }
     for (String un : unless) {
       if (!un.contains(".")) {
         un = after.getDeclaringClass().getName().substring(12) + "." + un;
       }
       if (un.equals(request.action)) {
         skip = true;
         break;
       }
     }
     if (!skip) {
       after.setAccessible(true);
       inferResult(invokeControllerMethod(after));
     }
   }
 }
  /** * Internal method to load class methods annotated with {@link MethodMapping} */
  private void loadAnnotatedMethods() {
    Method[] methods = getClass().getDeclaredMethods();
    boolean isUsingAuthAnnot = false;

    for (int i = 0; i < methods.length; i++) {
      Method method = methods[i];
      MethodMapping methodMapped = method.getAnnotation(MethodMapping.class);
      AuthorizeInvocation authorizeInvocation = method.getAnnotation(AuthorizeInvocation.class);

      isUsingAuthAnnot = isUsingAuthAnnot || authorizeInvocation != null;

      if (methodMapped != null) {
        HttpMethod httpMethod = methodMapped.httpMethod();
        MethodMappingInfo urlMappingInfo =
            new MethodMappingInfo(method, getMimeTypeResolver(method));

        if (!isMimeTypesSupported(urlMappingInfo.getMimeInputFormat())
            || !isMimeTypesSupported(urlMappingInfo.getMimeOutputFormat()))
          throw new WicketRuntimeException(
              "Mapped methods use a MIME type not supported by obj serializer/deserializer!");

        mappedMethods.addValue(
            urlMappingInfo.getSegmentsCount() + "_" + httpMethod.getMethod(), urlMappingInfo);
      }
    }
    // if AuthorizeInvocation has been found but no role-checker has been
    // configured, throw an exception
    if (isUsingAuthAnnot && roleCheckingStrategy == null)
      throw new WicketRuntimeException(
          "Annotation AuthorizeInvocation is used but no role-checking strategy has been set for the controller!");
  }
  @Override
  public void beforeTestMethod(TestContext testContext) throws Exception {

    checkInitialized();

    Method testMethod = getTestMethod(testContext);

    Expectations expectations = testMethod.getAnnotation(Expectations.class);
    Expectation expectation = testMethod.getAnnotation(Expectation.class);
    NoQueriesAllowed notAllowedQueries = testMethod.getAnnotation(NoQueriesAllowed.class);

    // If no annotations present, check the test class and its superclasses
    for (Class<?> testClass = testMethod.getDeclaringClass();
        null == expectations
            && null == expectation
            && null == notAllowedQueries
            && !Object.class.equals(testClass);
        testClass = testClass.getSuperclass()) {
      expectations = testClass.getAnnotation(Expectations.class);
      expectation = testClass.getAnnotation(Expectation.class);
      notAllowedQueries = testClass.getAnnotation(NoQueriesAllowed.class);
    }

    if (null != expectation && null != notAllowedQueries) {
      throw new IllegalArgumentException(
          "Cannot specify @Expectation and @NotAllowedQueries on one test method");
    } else if (null != expectations && null != notAllowedQueries) {
      throw new IllegalArgumentException(
          "Cannot specify @Expectations and @NotAllowedQueries on one test method");
    } else if (null != expectations || null != expectation) {

      List<Expectation> expectationList = new ArrayList<Expectation>();

      if (null != expectation) {
        expectationList.add(expectation);
      }

      if (null != expectations) {
        expectationList.addAll(Arrays.asList(expectations.value()));
      }

      for (Expectation expectation1 : expectationList) {
        if (expectation1.value() != -1) {
          if (expectation1.atMost() != -1 || expectation1.atLeast() != -1) {
            throw new IllegalArgumentException(
                "Cannot specify value parameter together with atLeast or atMost parameters");
          }
        }
      }

      setAttribute(testContext, SPY_ATTRIBUTE_NAME, Sniffer.expect(expectationList));

    } else if (null != notAllowedQueries) {
      setAttribute(
          testContext,
          SPY_ATTRIBUTE_NAME,
          Sniffer.expect(
              Collections.singletonList(NoQueriesAllowed.class.getAnnotation(Expectation.class))));
    }
  }
 /** 获取public菜单,未登陆时使用 */
 public static Map<String, List<String[]>> getPublicMenu() {
   Map<String, List<String[]>> map = MENU.get(-10);
   if (map == null) {
     map = new LinkedHashMap<String, List<String[]>>();
     List<String[]> list = new LinkedList<String[]>();
     for (Class<?> clazz : Scans.me().scanPackage("app.module")) {
       if (clazz.getAnnotation(At.class) != null) {
         for (Method method : clazz.getMethods()) {
           Menu menu = method.getAnnotation(Menu.class);
           At at = method.getAnnotation(At.class);
           if (menu != null
               && at != null
               && (clazz.getAnnotation(Public.class) != null
                   || method.getAnnotation(Public.class) != null)) {
             String[] tmp = new String[2];
             tmp[0] = menu.value();
             tmp[1] = clazz.getSimpleName().toLowerCase() + "/" + method.getName().toLowerCase();
             list.add(tmp);
           }
         }
       }
     }
     map.put("", list);
     MENU.put(-10, map);
   }
   return map;
 }
 /*     */ public static Map po2Map(Object po) /*     */ {
   /* 102 */ Map poMap = new HashMap();
   /* 103 */ Map map = new HashMap();
   /*     */ try {
     /* 105 */ map = BeanUtils.describe(po);
     /*     */ } catch (Exception ex) {
     /*     */ }
   /* 108 */ Object[] keyArray = map.keySet().toArray();
   /* 109 */ for (int i = 0; i < keyArray.length; i++) {
     /* 110 */ String str = keyArray[i].toString();
     /* 111 */ if ((str == null) || (str.equals("class")) || /* 112 */ (map.get(str) == null))
       continue;
     /* 113 */ poMap.put(str, map.get(str));
     /*     */ }
   /*     */
   /* 118 */ Method[] ms = po.getClass().getMethods();
   /* 119 */ for (Method m : ms) {
     /* 120 */ String name = m.getName();
     /*     */
     /* 122 */ if (((!name.startsWith("get")) && (!name.startsWith("is")))
         || (
         /* 123 */ (m.getAnnotation(NotDbField.class) == null)
             && (m.getAnnotation(PrimaryKeyField.class) == null))) continue;
     /* 124 */ poMap.remove(getFieldName(name));
     /*     */ }
   /*     */
   /* 133 */ if ((po instanceof DynamicField)) {
     /* 134 */ DynamicField dynamicField = (DynamicField) po;
     /* 135 */ Map fields = dynamicField.getFields();
     /* 136 */ poMap.putAll(fields);
     /*     */ }
   /* 138 */ return poMap;
   /*     */ }
  @Override
  public void onTestStart(ITestResult result) {
    logsResults.clear();
    StringBuilder builder = new StringBuilder();
    String testName = result.getName().toString();
    String className = result.getTestClass().getName().toString();

    Method testMethod = result.getMethod().getConstructorOrMethod().getMethod();

    builder.append("<table>" + "<h1>Class: <em>" + className + "." + testName + " </em></h1>");
    if (testMethod.isAnnotationPresent(RelatedIssue.class)) {
      String issueID = testMethod.getAnnotation(RelatedIssue.class).issueID();
      String jiraUrl = jiraPath + issueID;
      builder.append(
          "<tr class=\"step\"><td>Known failure</td><td><h1><em>"
              + testName
              + " - "
              + "<a href=\""
              + jiraUrl
              + "\">"
              + issueID
              + "</a> "
              + testMethod.getAnnotation(RelatedIssue.class).comment()
              + "</em></h1></td><td> <br/> &nbsp;</td></tr>");
    } else {
      builder.append(
          "<tr class=\"step\"><td>&nbsp</td><td><h1><em>"
              + testName
              + "</em></h1></td><td> <br/> &nbsp;</td></tr>");
    }
    CommonUtils.appendTextToFile(logPath, builder.toString());
    System.out.println(className + " " + testName);
  }
 public ControllerMapping(Class<?> classInfo) {
   try {
     this.classInfo = classInfo;
     this.object = classInfo.newInstance();
     Method[] methods = classInfo.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       Method tmp = methods[i];
       if (tmp.getName().equals("index")) {
         defaultMethod = tmp;
       }
       String methodPath = null;
       if (tmp.isAnnotationPresent(Path.class)) {
         methodPath = tmp.getAnnotation(Path.class).value();
       } else if (tmp.isAnnotationPresent(Code.class)) {
         methodPath = tmp.getAnnotation(Code.class).value();
       } else {
         methodPath = tmp.getName();
       }
       methodPath = methodPath.replaceAll("/", "");
       controllerMethods.put(methodPath.toLowerCase(), tmp);
       controllerMethods.put(methodPath.toUpperCase(), tmp);
       controllerMethods.put(methodPath, tmp);
       Class<?>[] classInfos = tmp.getParameterTypes();
       methodParameters.put(tmp, classInfos);
     }
   } catch (Exception e) {
     logger.error(e.getMessage(), e);
   }
 }
Exemple #15
0
 /**
  * class filter of an action to use it
  *
  * @param p_method method for checking
  * @param p_root root class
  * @return boolean flag of check result
  */
 private static boolean isActionFiltered(final Method p_method, final Class<?> p_root) {
   return p_method.isAnnotationPresent(IAgentActionFilter.class)
       && ((p_method.getAnnotation(IAgentActionFilter.class).classes().length == 0)
           || (Arrays.stream(p_method.getAnnotation(IAgentActionFilter.class).classes())
               .parallel()
               .anyMatch(p_root::equals)));
 }
Exemple #16
0
  protected void handleListenerMethods(Method method, Class managedClass, BundleContext context) {
    se.natusoft.osgi.aps.tools.annotation.activator.ServiceListener serviceListener =
        method.getAnnotation(se.natusoft.osgi.aps.tools.annotation.activator.ServiceListener.class);
    if (serviceListener != null) {
      ServiceListenerWrapper serviceListenerWrapper =
          new ServiceListenerWrapper(method, getManagedInstance(managedClass));
      serviceListenerWrapper.start(context);
      this.listeners.add(serviceListenerWrapper);
    }

    se.natusoft.osgi.aps.tools.annotation.activator.BundleListener bundleListener =
        method.getAnnotation(se.natusoft.osgi.aps.tools.annotation.activator.BundleListener.class);
    if (bundleListener != null) {
      BundleListenerWrapper bundleListenerWrapper =
          new BundleListenerWrapper(method, getManagedInstance(managedClass));
      bundleListenerWrapper.start(context);
      this.listeners.add(bundleListenerWrapper);
    }

    se.natusoft.osgi.aps.tools.annotation.activator.FrameworkListener frameworkListener =
        method.getAnnotation(
            se.natusoft.osgi.aps.tools.annotation.activator.FrameworkListener.class);
    if (frameworkListener != null) {
      FrameworkListenerWrapper frameworkListenerWrapper =
          new FrameworkListenerWrapper(method, getManagedInstance(managedClass));
      frameworkListenerWrapper.start(context);
      this.listeners.add(frameworkListenerWrapper);
    }
  }
Exemple #17
0
  public static void main(String[] args) throws Exception {
    Class clazz = BizHandler.class;
    Method method = clazz.getMethod("handle", new Class[] {});

    BeforeAdvice before = method.getAnnotation(BeforeAdvice.class);
    AfterAdvice after = method.getAnnotation(AfterAdvice.class);
    ExceptionAdvice ex = method.getAnnotation(ExceptionAdvice.class);
    ReturnAdvice ret = method.getAnnotation(ReturnAdvice.class);

    try {
      if (before != null) {
        System.out.println(before.advice());
      }
      method.invoke(new BizHandler(), new Object[] {});
      if (after != null) {
        System.out.println(after.advice());
      }
    } catch (Exception e) {
      if (ex != null) {
        System.out.println(ex.advice());
      }
    } finally {
      if (ret != null) {
        System.out.println(ret.advice());
      }
    }
  }
Exemple #18
0
  private void callBeforeMethods(HttpServletRequest request, HttpServletResponse response) {
    if (!beforeList.isEmpty()) {
      for (Method beforeMethod : beforeList) {
        String[] only = ((Before) beforeMethod.getAnnotation(Before.class)).only();
        if (only.length > 0) {
          for (String path : only) {
            if (path.equals(urlPath(request))) {
              callMethod(beforeMethod, request, response);
            }
          }
        } else {
          String[] unless = ((Before) beforeMethod.getAnnotation(Before.class)).unless();
          if (unless.length > 0) {
            boolean call = true;
            for (String path : unless) {
              if (path.equals(urlPath(request))) {
                call = false;
              }
            }

            if (call) callMethod(beforeMethod, request, response);
          } else callMethod(beforeMethod, request, response);
        }
      }
    }
  }
Exemple #19
0
  @SuppressWarnings("rawtypes")
  public static ApiObjectDoc buildFromAnnotation(ApiObject annotation, Class clazz) {

    final List<ApiObjectFieldDoc> fieldDocs = new ArrayList<ApiObjectFieldDoc>();
    for (Field field : clazz.getDeclaredFields())
      if (field.getAnnotation(ApiObjectField.class) != null)
        fieldDocs.add(
            ApiObjectFieldDoc.buildFromAnnotation(
                field.getAnnotation(ApiObjectField.class), field));

    for (Method getter : clazz.getDeclaredMethods())
      if (getter.getAnnotation(ApiObjectGetter.class) != null
          && getter.getName().startsWith("get")
          && getter.getParameterTypes().length == 0)
        fieldDocs.add(
            ApiObjectFieldDoc.buildFromAnnotation(
                getter.getAnnotation(ApiObjectGetter.class), getter));

    Class<?> c = clazz.getSuperclass();
    if (c != null) {
      if (c.isAnnotationPresent(ApiObject.class)) {
        ApiObjectDoc objDoc = ApiObjectDoc.buildFromAnnotation(c.getAnnotation(ApiObject.class), c);
        fieldDocs.addAll(objDoc.getFields());
      }
    }

    return new ApiObjectDoc(annotation.name(), annotation.description(), fieldDocs);
  }
Exemple #20
0
  private void callAfterMethods(HttpServletRequest request, HttpServletResponse response) {
    if (!afterList.isEmpty()) {
      for (Method afterMethod : afterList) {
        String[] paths = ((After) afterMethod.getAnnotation(After.class)).only();
        if (paths.length > 0) {
          for (String path : paths) {
            if (path.equals(urlPath(request))) {
              callMethod(afterMethod, request, response);
            }
          }
        } else {
          String[] unless = ((After) afterMethod.getAnnotation(After.class)).unless();
          if (unless.length > 0) {
            boolean call = true;
            for (String path : unless) {
              if (path.equals(urlPath(request))) {
                call = false;
              }
            }

            if (call) callMethod(afterMethod, request, response);
          } else callMethod(afterMethod, request, response);
        }
      }
    }
  }
  private List<String> createTreeForStatsProvider(TreeNode parentNode, Object statsProvider) {
    /* construct monitoring tree at PluginPoint using subTreePath */
    List<String> childNodeNames = new ArrayList();

    /* retrieve ManagedAttribute attribute id (v2 compatible) and method names */
    /* Check for custom reset method and store for later to be called instead of
    standard reset methods on Statistic classes*/
    for (Method m : statsProvider.getClass().getMethods()) {
      ManagedAttribute ma = m.getAnnotation(ManagedAttribute.class);
      Reset resetMeth = m.getAnnotation(Reset.class);
      if (resetMeth != null) {
        StatsProviderRegistryElement spre =
            this.statsProviderRegistry.getStatsProviderRegistryElement(statsProvider);
        spre.setResetMethod(m);
      }
      if (ma != null) {
        String methodName = m.getName();
        String id = ma.id();
        if ((id == null) || id.isEmpty()) { // if id not specified, derive from method name
          String methodNameLower = methodName.toLowerCase(Locale.ENGLISH);
          if (methodNameLower.startsWith("get") && methodNameLower.length() > 3) {
            id = methodNameLower.substring(3);
          }
        }

        TreeNode attrNode = TreeNodeFactory.createMethodInvoker(id, statsProvider, id, m);
        parentNode.addChild(attrNode);
        childNodeNames.add(attrNode.getName());
      }
    }
    return childNodeNames;
  }
Exemple #22
0
 private static void findNotImplemented(Class<?> type, Map<String, Method> result) {
   Class<?> superclass = type.getSuperclass();
   if (superclass != null) {
     findNotImplemented(superclass, result);
   }
   for (Method m : type.getDeclaredMethods()) {
     NotImplemented ni = m.getAnnotation(NotImplemented.class);
     if (ni != null) {
       result.put(ni.value(), m);
     } else {
       BindSelector bs = m.getAnnotation(BindSelector.class);
       if (bs != null) {
         result.remove(bs.value());
       } else {
         String mName = m.getName();
         Class<?>[] mParamTypes = m.getParameterTypes();
         for (Iterator<Entry<String, Method>> it = result.entrySet().iterator(); it.hasNext(); ) {
           Entry<String, Method> entry = it.next();
           Method m2 = entry.getValue();
           if (m2.getName().equals(mName) && Arrays.equals(m2.getParameterTypes(), mParamTypes)) {
             it.remove();
           }
         }
       }
     }
   }
 }
  private void populateLifeCycleMethods(Component c) {
    if (!c.methodsScanned) {
      c.methodsScanned = true;
      c.startMethods.clear();
      c.stopMethods.clear();

      List<Method> methods = getAllMethodsViaReflection(c.instance.getClass(), Start.class);
      for (Method m : methods) {
        PrioritizedMethod em = new PrioritizedMethod();
        em.component = c;
        em.method = m;
        em.priority = m.getAnnotation(Start.class).priority();
        c.startMethods.add(em);
      }

      methods = getAllMethodsViaReflection(c.instance.getClass(), Stop.class);
      for (Method m : methods) {
        PrioritizedMethod em = new PrioritizedMethod();
        em.component = c;
        em.method = m;
        em.priority = m.getAnnotation(Stop.class).priority();
        c.stopMethods.add(em);
      }
    }
  }
Exemple #24
0
 private static void findCallbacks(Class<?> type, Map<String, Method> result) {
   ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
   if (!type.isInterface()) {
     // No need to search interfaces since interfaces cannot have
     // static methods and callbacks must be static.
     classes.add(type);
   } else {
     Class<?> objCProxy = allObjCProxyClasses.get(type.getName());
     if (objCProxy != null) {
       classes.add(objCProxy);
     }
   }
   try {
     classes.add(Class.forName(type.getName() + "$Callbacks", true, type.getClassLoader()));
   } catch (ClassNotFoundException ignored) {
   }
   for (Class<?> c : classes) {
     for (Method m : c.getDeclaredMethods()) {
       if (m.getAnnotation(Callback.class) != null) {
         BindSelector bindSelector = m.getAnnotation(BindSelector.class);
         if (bindSelector != null) {
           if (!result.containsKey(bindSelector.value())) {
             result.put(bindSelector.value(), m);
           }
         }
       }
     }
   }
 }
  private void visitProperties(SharpExpression expr, String oldName, String newName) {
    try {
      for (Method m : expr.getClass().getMethods()) {
        if (m.getAnnotation(RdfProperty.class) != null) {
          String propIri = m.getAnnotation(RdfProperty.class).value();
          if ("http://asu.edu/sharpc2b/ops#opCode".equals(propIri)) {
            continue;
          }

          if (Collection.class.isAssignableFrom(m.getReturnType())) {
            Collection coll = (Collection) m.invoke(expr);
            int j = 0;
            for (Object o : coll) {
              if (o instanceof SharpExpression) {
                visit((SharpExpression) o, oldName, newName);
              }
            }
          } else {
            Object o = m.invoke(expr);
            if (o instanceof SharpExpression) {
              visit((SharpExpression) o, oldName, newName);
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public static void process(Object obj) {
   if (obj == null) {
     return;
   }
   Class cl = obj.getClass();
   Method[] methods = cl.getMethods();
   for (int i = 0; i < methods.length; i++) {
     Method method = methods[i];
     EventSubscriber classAnnotation = method.getAnnotation(EventSubscriber.class);
     if (classAnnotation != null) {
       process(classAnnotation, obj, method);
     }
     EventTopicSubscriber topicAnnotation =
         (EventTopicSubscriber) method.getAnnotation(EventTopicSubscriber.class);
     if (topicAnnotation != null) {
       process(topicAnnotation, obj, method);
     }
     EventTopicPatternSubscriber topicPatternAnnotation =
         (EventTopicPatternSubscriber) method.getAnnotation(EventTopicPatternSubscriber.class);
     if (topicPatternAnnotation != null) {
       process(topicPatternAnnotation, obj, method);
     }
     //         Publisher publisherAnnotation = (Publisher) method.getAnnotation(Publisher.class);
     //         if (publisherAnnotation != null) {
     //            process(publisherAnnotation, obj);
     //         }
   }
 }
 /**
  * Create a SagaMethodMessageHandler for the given <code>methodHandler</code>. The
  * SagaMethodMessageHandler add information specific to the behavior of Sagas, such as the
  * association value and creation policy.
  *
  * @param methodHandler The handler for incoming events
  * @return a SagaMethodMessageHandler for the handler
  */
 public static SagaMethodMessageHandler getInstance(MethodMessageHandler methodHandler) {
   Method handlerMethod = methodHandler.getMethod();
   SagaEventHandler handlerAnnotation = handlerMethod.getAnnotation(SagaEventHandler.class);
   String associationPropertyName = handlerAnnotation.associationProperty();
   Method associationProperty;
   try {
     associationProperty =
         methodHandler.getPayloadType().getMethod(methodForProperty(associationPropertyName));
   } catch (NoSuchMethodException e) {
     throw new AxonConfigurationException(
         format(
             "SagaEventHandler %s.%s defines a property %s that is not "
                 + "defined on the Event it declares to handle (%s)",
             methodHandler.getMethod().getDeclaringClass().getName(),
             methodHandler.getMethodName(),
             associationPropertyName,
             methodHandler.getPayloadType().getName()),
         e);
   }
   String associationKey =
       handlerAnnotation.keyName().isEmpty()
           ? associationPropertyName
           : handlerAnnotation.keyName();
   StartSaga startAnnotation = handlerMethod.getAnnotation(StartSaga.class);
   SagaCreationPolicy sagaCreationPolicy;
   if (startAnnotation == null) {
     sagaCreationPolicy = SagaCreationPolicy.NONE;
   } else if (startAnnotation.forceNew()) {
     sagaCreationPolicy = SagaCreationPolicy.ALWAYS;
   } else {
     sagaCreationPolicy = SagaCreationPolicy.IF_NONE_FOUND;
   }
   return new SagaMethodMessageHandler(
       sagaCreationPolicy, methodHandler, associationKey, associationProperty);
 }
  @Override
  public void beforeInvocation(
      IInvokedMethod method, ITestResult testResult, ITestContext context) {
    int failed = findFailed(context);
    if (failed > 0) {
      LOG.error("Masking will not proceed. {} Configurations have failed", failed);
      return;
    }

    Method rmethod = method.getTestMethod().getConstructorOrMethod().getMethod();
    if (rmethod.getAnnotation(Test.class) != null
        || rmethod.getAnnotation(BeforeClass.class) != null
        || rmethod.getAnnotation(BeforeTest.class) != null) {
      if (rmethod.getAnnotation(RunsWithController.class) != null
          || rmethod.getDeclaringClass().getAnnotation(RunsWithController.class) != null) {
        LOG.warn("Method or Class of {} asks Controller to be masked", rmethod.getName());
        AnnotationsHelper p = SteviaContext.getSpringContext().getBean(AnnotationsHelper.class);
        try {
          p.maskExistingController(rmethod);
          masked = true;
        } catch (Throwable e) {
          throw new IllegalStateException("failed to replace controller", e);
        }
      }
    }
  }
 private void processValueRangeAnnotation() {
   Method propertyGetter = variablePropertyAccessor.getReadMethod();
   ValueRange valueRangeAnnotation = propertyGetter.getAnnotation(ValueRange.class);
   ValueRanges valueRangesAnnotation = propertyGetter.getAnnotation(ValueRanges.class);
   if (valueRangeAnnotation != null) {
     if (valueRangesAnnotation != null) {
       throw new IllegalArgumentException(
           "The planningEntityClass ("
               + planningEntityDescriptor.getPlanningEntityClass()
               + ") has a PlanningVariable annotated property ("
               + variablePropertyAccessor.getName()
               + ") that has a @ValueRange and @ValueRanges annotation: fold them into 1 @ValueRanges.");
     }
     valueRangeDescriptor = buildValueRangeDescriptor(valueRangeAnnotation);
   } else {
     if (valueRangesAnnotation == null) {
       throw new IllegalArgumentException(
           "The planningEntityClass ("
               + planningEntityDescriptor.getPlanningEntityClass()
               + ") has a PlanningVariable annotated property ("
               + variablePropertyAccessor.getName()
               + ") that has no @ValueRange or @ValueRanges annotation.");
     }
     List<PlanningValueRangeDescriptor> valueRangeDescriptorList =
         new ArrayList<PlanningValueRangeDescriptor>(valueRangesAnnotation.value().length);
     for (ValueRange partialValueRangeAnnotation : valueRangesAnnotation.value()) {
       valueRangeDescriptorList.add(buildValueRangeDescriptor(partialValueRangeAnnotation));
     }
     valueRangeDescriptor =
         new CompositePlanningValueRangeDescriptor(this, valueRangeDescriptorList);
   }
 }
Exemple #30
0
  /**
   * Gets the specified method from a query module.
   *
   * @param mod query module object
   * @param path path of the module
   * @param name method name
   * @param arity number of arguments
   * @param qc query context
   * @param ii input info
   * @return method if found, {@code null} otherwise
   * @throws QueryException query exception
   */
  private static Method getModMethod(
      final Object mod,
      final String path,
      final String name,
      final long arity,
      final QueryContext qc,
      final InputInfo ii)
      throws QueryException {

    // find method with identical name and arity
    Method meth = null;
    for (final Method m : mod.getClass().getMethods()) {
      if (m.getName().equals(name) && m.getParameterTypes().length == arity) {
        if (meth != null) throw JAVAAMBIG_X.get(ii, "Q{" + path + '}' + name + '#' + arity);
        meth = m;
      }
    }
    if (meth == null) throw FUNCJAVA_X.get(ii, path + ':' + name);

    // check if user has sufficient permissions to call the function
    Perm perm = Perm.ADMIN;
    final QueryModule.Requires req = meth.getAnnotation(QueryModule.Requires.class);
    if (req != null) perm = Perm.get(req.value().name());
    if (!qc.context.user.has(perm)) return null;

    // Add module locks to QueryContext.
    final QueryModule.Lock lock = meth.getAnnotation(QueryModule.Lock.class);
    if (lock != null) {
      for (final String read : lock.read()) qc.readLocks.add(DBLocking.MODULE_PREFIX + read);
      for (final String write : lock.write()) qc.writeLocks.add(DBLocking.MODULE_PREFIX + write);
    }

    return meth;
  }