Ejemplo n.º 1
0
  public void addTestSuite(Object testSuite) {
    Method beforeMethod = null;
    Method afterMethod = null;
    Method[] methods = testSuite.getClass().getMethods();
    for (Method method : methods) {
      Annotation[] annotations = method.getDeclaredAnnotations();
      for (Annotation annotation : annotations) {
        if (isBeforeMethod(annotation)) {
          beforeMethod = method;
          break;
        }

        if (isAfterMethod(annotation)) {
          afterMethod = method;
          break;
        }
      }
    }

    for (Method method : methods) {
      Annotation[] annotations = method.getDeclaredAnnotations();
      for (Annotation annotation : annotations) {
        if (isTestMethod(annotation)) {
          tests.add(new TestCase(testSuite, beforeMethod, method, afterMethod));
        }
      }
    }
  }
Ejemplo n.º 2
0
  public final ITargetMethod[] GetAllMethods() {
    java.util.ArrayList<ITargetMethod> methods = new java.util.ArrayList<ITargetMethod>();
    if (_target != null) {
      java.lang.reflect.Method[] members =
          _target.getClass().getMethods(/*BindingFlags.Instance | BindingFlags.Public*/ );

      for (int i = 0; i < members.length; i++) {
        java.lang.reflect.Method member = members[i];

        Annotation[] customAttributes =
            member
                .getDeclaredAnnotations(); // member.GetCustomAttributes(TargetMethodAttribute.class, true);

        if (customAttributes != null && customAttributes.length > 0) {
          TargetMethodAttribute targetMethodAttribute =
              (TargetMethodAttribute)
                  ((customAttributes[0] instanceof TargetMethodAttribute)
                      ? customAttributes[0]
                      : null);
          TargetMethod targetMethod =
              new TargetMethod(
                  _target,
                  member,
                  targetMethodAttribute.privateMethod(),
                  targetMethodAttribute.privateOverload());
          methods.add(targetMethod);
        }
      }

      members =
          _target
              .getClass()
              .getSuperclass()
              .getMethods(/*BindingFlags.Instance | BindingFlags.Public*/ );

      for (int i = 0; i < members.length; i++) {
        java.lang.reflect.Method member = members[i];

        Annotation[] customAttributes =
            member
                .getDeclaredAnnotations(); // member.GetCustomAttributes(TargetMethodAttribute.class, true);

        if (customAttributes != null && customAttributes.length > 0) {
          TargetMethodAttribute targetMethodAttribute =
              (TargetMethodAttribute)
                  ((customAttributes[0] instanceof TargetMethodAttribute)
                      ? customAttributes[0]
                      : null);
          TargetMethod targetMethod =
              new TargetMethod(
                  _target,
                  member,
                  targetMethodAttribute.privateMethod(),
                  targetMethodAttribute.privateOverload());
          methods.add(targetMethod);
        }
      }
    }
    return methods.toArray(new ITargetMethod[0]);
  }
Ejemplo n.º 3
0
  private boolean scanForAnnotations(Class<?> clazz) {
    if (clazz != null) {
      while (clazz != Object.class) {
        Field[] fields = clazz.getDeclaredFields();
        if (fields != null) {
          for (Field field : fields) {
            if (field.getAnnotations().length > 0) {
              return true;
            }
          }
        }

        Method[] methods = clazz.getDeclaredMethods();
        if (methods != null) {
          for (Method method : methods) {
            if (method.getDeclaredAnnotations().length > 0) {
              return true;
            }
          }
        }

        clazz = clazz.getSuperclass();
      }
    }

    return false;
  }
Ejemplo n.º 4
0
 public static Object invokeControllerMethod(Method method, Object[] forceArgs) throws Exception {
   if (Modifier.isStatic(method.getModifiers())
       && !method.getDeclaringClass().getName().matches("^controllers\\..*\\$class$")) {
     return invoke(
         method, null, forceArgs == null ? getActionMethodArgs(method, null) : forceArgs);
   } else if (Modifier.isStatic(method.getModifiers())) {
     Object[] args = getActionMethodArgs(method, null);
     args[0] = Http.Request.current().controllerClass.getDeclaredField("MODULE$").get(null);
     return invoke(method, null, args);
   } else {
     Object instance = null;
     try {
       instance = method.getDeclaringClass().getDeclaredField("MODULE$").get(null);
     } catch (Exception e) {
       Annotation[] annotations = method.getDeclaredAnnotations();
       String annotation = Utils.getSimpleNames(annotations);
       if (!StringUtils.isEmpty(annotation)) {
         throw new UnexpectedException(
             "Method public static void "
                 + method.getName()
                 + "() annotated with "
                 + annotation
                 + " in class "
                 + method.getDeclaringClass().getName()
                 + " is not static.");
       }
       // TODO: Find a better error report
       throw new ActionNotFoundException(Http.Request.current().action, e);
     }
     return invoke(
         method, instance, forceArgs == null ? getActionMethodArgs(method, instance) : forceArgs);
   }
 }
Ejemplo n.º 5
0
 /**
  * Method that will add annotations from specified source method to target method, but only if
  * target does not yet have them.
  */
 protected void _addMixUnders(Method src, AnnotatedMethod target) {
   for (Annotation a : src.getDeclaredAnnotations()) {
     if (_annotationIntrospector.isHandled(a)) {
       target.addIfNotPresent(a);
     }
   }
 }
Ejemplo n.º 6
0
  protected Object handleResponse(Message outMessage, Class<?> serviceCls) throws Throwable {
    try {
      Response r = setResponseBuilder(outMessage, outMessage.getExchange()).build();
      ((ResponseImpl) r).setOutMessage(outMessage);
      getState().setResponse(r);

      Method method = outMessage.getExchange().get(Method.class);
      checkResponse(method, r, outMessage);
      if (method.getReturnType() == Void.class || method.getReturnType() == Void.TYPE) {
        return null;
      }
      if (method.getReturnType() == Response.class
          && (r.getEntity() == null
              || InputStream.class.isAssignableFrom(r.getEntity().getClass())
                  && ((InputStream) r.getEntity()).available() == 0)) {
        return r;
      }
      if (PropertyUtils.isTrue(
          super.getConfiguration().getResponseContext().get(BUFFER_PROXY_RESPONSE))) {
        r.bufferEntity();
      }

      Class<?> returnType = method.getReturnType();
      Type genericType =
          InjectionUtils.processGenericTypeIfNeeded(
              serviceCls, returnType, method.getGenericReturnType());
      returnType = InjectionUtils.updateParamClassToTypeIfNeeded(returnType, genericType);
      return readBody(r, outMessage, returnType, genericType, method.getDeclaredAnnotations());
    } finally {
      ClientProviderFactory.getInstance(outMessage).clearThreadLocalProxies();
    }
  }
Ejemplo n.º 7
0
  public final ITargetMethod GetMethod(String methodName, int overload) {
    ITargetMethod targetMethod = null;
    if (_target != null) {
      java.lang.reflect.Method[] members =
          _target
              .getClass()
              .getMethods(); // GetMethods(BindingFlags.Instance | BindingFlags.Public);

      for (int i = 0; i < members.length; i++) {
        java.lang.reflect.Method member = members[i];

        Annotation[] customAttributes = member.getDeclaredAnnotations();
        ; // member.GetCustomAttributes(TargetMethodAttribute.class, true);

        if (customAttributes != null && customAttributes.length > 0) {
          TargetMethodAttribute targetMethodAttribute =
              (TargetMethodAttribute)
                  ((customAttributes[0] instanceof TargetMethodAttribute)
                      ? customAttributes[0]
                      : null);

          if (targetMethodAttribute.privateMethod().equals(methodName)
              && targetMethodAttribute.privateOverload() == overload) {
            targetMethod =
                new TargetMethod(
                    _target,
                    member,
                    targetMethodAttribute.privateMethod(),
                    targetMethodAttribute.privateOverload());
          }
        }
      }
    }
    return targetMethod;
  }
 public boolean passFilter(Method method) {
   Annotation[] annotations = method.getDeclaredAnnotations();
   for (Annotation annotation : annotations) {
     if (annotation.annotationType().isAnnotationPresent(inheritedAnnotation)) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 9
0
 /**
  * Get the annotations associated with given TestCase.
  *
  * @param test
  * @return
  */
 private static Annotation[] getAnnotations(TestCase test) {
   try {
     Method m = test.getClass().getDeclaredMethod(test.getName());
     return m.getDeclaredAnnotations();
   } catch (SecurityException e) {
   } catch (NoSuchMethodException e) {
   }
   return new Annotation[0];
 }
Ejemplo n.º 10
0
  @Override
  public final Set<Descriptor> getDescriptors() {
    Set<Descriptor> capabilities = new HashSet<Descriptor>();

    Collection<?> actions = managedObjects.values();
    for (Object action : actions) {
      Class<?> actionClass = action.getClass();
      Method[] methods = actionClass.getMethods();

      for (Method method : methods) {
        Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
        boolean expose = false;
        for (Annotation declaredAnnotation : declaredAnnotations) {
          if (declaredAnnotation.annotationType() == Exposed.class) {
            expose = true;
            break;
          }
        }
        if (!expose) {
          continue;
        }

        String methodName = method.getName();
        Class<?> returnType = method.getReturnType();

        Class<?>[] parameterTypes = method.getParameterTypes();
        List<String> parameterNames = new ArrayList<String>();

        for (int i = 0; i < parameterTypes.length; i++) {
          Annotation[] parameterAnnotations = method.getParameterAnnotations()[i];
          boolean named = false;
          for (Annotation parameterAnnotation : parameterAnnotations) {
            if (parameterAnnotation instanceof Named) {
              Named namedAnnotation = (Named) parameterAnnotation;
              parameterNames.add(namedAnnotation.value());
              named = true;
              break;
            }
          }
          if (!named) {
            parameterNames.add("arg" + i);
          }
        }

        List<CallDescriptor.Parameter> parameters = new ArrayList<CallDescriptor.Parameter>();
        for (int i = 0; i < parameterTypes.length; i++) {
          parameters.add(
              new CallDescriptor.Parameter(parameterNames.get(i), parameterTypes[i].getName()));
        }

        capabilities.add(new CallDescriptor(methodName, returnType.getName(), parameters));
      }
    }

    return capabilities;
  }
Ejemplo n.º 11
0
  /** java.lang.reflect.Method#getDeclaredAnnotations() */
  public void test_getDeclaredAnnotations() throws Exception {
    Method method = TestMethod.class.getDeclaredMethod("annotatedMethod");
    Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
    assertEquals(2, declaredAnnotations.length);

    Set<Class<?>> annotationSet = new HashSet<Class<?>>();
    annotationSet.add(declaredAnnotations[0].annotationType());
    annotationSet.add(declaredAnnotations[1].annotationType());
    assertTrue("Missing TestAnno annotation", annotationSet.contains(TestAnno.class));
    assertTrue("Missing Deprecated annotation", annotationSet.contains(Deprecated.class));
  }
  boolean isField(Class type, AbstractEnhancedConfig typeConfig) throws ConfigException {
    for (Method method : type.getDeclaredMethods()) {
      Annotation ann[] = method.getDeclaredAnnotations();

      for (int i = 0; ann != null && i < ann.length; i++) {
        if (ann[i] instanceof Basic || ann[i] instanceof Column) return false;
      }
    }

    return true;
  }
 private Map<Class<? extends Annotation>, Annotation> collectAnnotations(
     Iterable<Method> methods) {
   Map<Class<? extends Annotation>, Annotation> annotations = Maps.newLinkedHashMap();
   for (Method method : methods) {
     for (Annotation annotation : method.getDeclaredAnnotations()) {
       // Make sure more specific annotation doesn't get overwritten with less specific one
       if (!annotations.containsKey(annotation.annotationType())) {
         annotations.put(annotation.annotationType(), annotation);
       }
     }
   }
   return Collections.unmodifiableMap(annotations);
 }
Ejemplo n.º 14
0
  Map<Annotation, ActionInterceptor<Annotation>> findInterceptors(Method method) {
    Map<Annotation, ActionInterceptor<Annotation>> interceptors =
        new LinkedHashMap<Annotation, ActionInterceptor<Annotation>>();
    for (Annotation annotation : method.getDeclaredAnnotations()) {
      Class<? extends Annotation> annotationType = annotation.annotationType();
      ActionInterceptor<Annotation> actionInterceptor = interceptor(annotationType);
      if (actionInterceptor != null) {
        interceptors.put(annotation, actionInterceptor);
      }
    }

    return interceptors;
  }
Ejemplo n.º 15
0
    @Override
    public Object invoke(final Object o, final Method method, final Object[] objects)
        throws Throwable {
      if (method.getName().equals("logEvent")) {

        final StringBuilder missing = new StringBuilder();

        final Method[] methods = intrface.getMethods();

        for (final Method _method : methods) {
          final String name =
              NamingUtils.lowerFirst(NamingUtils.getMethodShortName(_method.getName()));

          final Annotation[] annotations = _method.getDeclaredAnnotations();
          for (final Annotation annotation : annotations) {
            final Constraint constraint = (Constraint) annotation;

            if (constraint.required() && msg.get(name) == null) {
              if (missing.length() > 0) {
                missing.append(", ");
              }
              missing.append(name);
            }
          }
        }

        if (missing.length() > 0) {
          throw new IllegalStateException(
              "Event " + msg.getId().getName() + " is missing required attributes " + missing);
        }
        EventLogger.logEvent(msg);
      }
      if (method.getName().equals("setCompletionStatus")) {
        final String name =
            NamingUtils.lowerFirst(NamingUtils.getMethodShortName(method.getName()));
        msg.put(name, objects[0].toString());
      }
      if (method.getName().startsWith("set")) {
        final String name =
            NamingUtils.lowerFirst(NamingUtils.getMethodShortName(method.getName()));

        /*
         * Perform any validation here. Currently the catalog doesn't
         * contain any information on validation rules.
         */
        msg.put(name, objects[0].toString());
      }

      return null;
    }
Ejemplo n.º 16
0
 /** @param addParamAnnotations Whether parameter annotations are to be added as well */
 protected void _addMixOvers(Method mixin, AnnotatedMethod target, boolean addParamAnnotations) {
   for (Annotation a : mixin.getDeclaredAnnotations()) {
     if (_annotationIntrospector.isHandled(a)) {
       target.addOrOverride(a);
     }
   }
   if (addParamAnnotations) {
     Annotation[][] pa = mixin.getParameterAnnotations();
     for (int i = 0, len = pa.length; i < len; ++i) {
       for (Annotation a : pa[i]) {
         target.addOrOverrideParam(i, a);
       }
     }
   }
 }
Ejemplo n.º 17
0
  // Get a list of the names of declared methods with the @Test annotation from the specified class
  public static List<String> getDeclaredTestMethods(Class<?> clazz) {
    List<String> methodNames = new ArrayList<>();

    for (Method method : clazz.getMethods()) {
      List<Annotation> declaredAnnotations = Arrays.asList(method.getDeclaredAnnotations());

      for (Annotation a : declaredAnnotations) {
        if (a.annotationType().isAssignableFrom(org.testng.annotations.Test.class)) {
          methodNames.add(method.getName());
        }
      }
    }

    return methodNames;
  }
Ejemplo n.º 18
0
 public void verificar(Method m, Object o) throws ControleException {
   Annotation[] annotations = m.getDeclaredAnnotations();
   for (Annotation a : annotations) {
     if (a.equals(HorarioComercial.class)) {
       analisarHorarioComercial(o);
     } else {
       if (a.equals(HorarioVIP.class)) {
         analisarHorarioVIP(o);
       } else {
         if (a.equals(LimiteGerente.class)) {
           analisarLimiteGerente(o);
         }
       }
     }
   }
 }
Ejemplo n.º 19
0
  /** Traverse all fields and set up parameters according o @ZkParameters annotation. */
  public static void setupZkParameters(Object instance) {
    for (Field field : ReflectionHelper.getAllFields(instance.getClass())) {
      for (Annotation annotation : field.getDeclaredAnnotations()) {
        if (annotation instanceof ZkParameter)
          setupZkParameter(
              (ZkParameter) annotation,
              getName((ZkParameter) annotation, field),
              field.getType(),
              field,
              null,
              instance);
      }
    }

    for (Method method : ReflectionHelper.getAllMethods(instance.getClass())) {
      for (Annotation annotation : method.getDeclaredAnnotations()) {
        if (annotation instanceof ZkParameter) {
          String paramName = ((ZkParameter) annotation).name();
          if (StringHelper.isNull(paramName)) {
            if (!method.getName().startsWith("set"))
              throw new InstantiationError(
                  "@ZkParameter must be on method in form of setXXX(ParamType p)  (e.g. setParamName). "
                      + "Found: "
                      + method.getName());
            paramName = getMethodLowerCase(method.getName().substring(3));
          }

          if (method.getParameterTypes().length != 1)
            throw new InstantiationError(
                "@ZkParameter must be on method in form of setXXX(ParamType p), wrong number of parameters. "
                    + "Actual number of parameters: "
                    + method.getParameterTypes().length);

          setupZkParameter(
              (ZkParameter) annotation,
              paramName,
              method.getParameterTypes()[0],
              null,
              method,
              instance);
        }
      }
    }
  }
  // TODO stereotypes
  protected Annotation[] extractInterceptorBindings(Object instance, Method method) {
    ArrayList<Annotation> bindings = new ArrayList<Annotation>();

    for (Annotation annotation : instance.getClass().getDeclaredAnnotations()) {
      if (annotation.annotationType().isAnnotationPresent(InterceptorBinding.class)
          && !bindings.contains(annotation)) {
        bindings.add(annotation);
      }
    }

    for (Annotation annotation : method.getDeclaredAnnotations()) {
      if (annotation.annotationType().isAnnotationPresent(InterceptorBinding.class)
          && !bindings.contains(annotation)) {
        bindings.add(annotation);
      }
    }

    return bindings.toArray(new Annotation[bindings.size()]);
  }
Ejemplo n.º 21
0
  public static byte[] fetchContent(
      Context context, String language, String page, boolean readOnly, int templateType) {
    Class[] scriptingClasses = {JavaScriptEngine.class, SchemeEngine.class};

    language = language.toLowerCase();

    ArrayList<String> languages = new ArrayList<>();
    languages.add(BootstrapSiteExporter.LANGUAGE_ALL.toLowerCase());

    if (languages.contains(language) == false) languages.add(language.toLowerCase());

    if (page == null || page.trim().length() == 0) {
      try {
        JSONArray declaredMethods = BootstrapSiteExporter.methodsForLanguage(context, language);

        AssetManager am = context.getAssets();

        String template = "embedded_website/docs/scripting_template.html";

        if (readOnly && templateType == BootstrapSiteExporter.TEMPLATE_TYPE_BOOTSTRAP)
          template = "embedded_website/docs/scripting_template_readonly.html";
        else if (templateType == BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL)
          template = "embedded_website/docs/scripting_template_jekyll.html";

        InputStream in = am.open(template);

        // http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
        Scanner s = new Scanner(in).useDelimiter("\\A");

        String content = "";

        if (s.hasNext()) content = s.next();

        content = content.replace("{{ METHOD_DEFINITIONS }}", declaredMethods.toString(2));
        content = content.replace("{{ LANGUAGE }}", language.toLowerCase());

        return content.getBytes(Charset.forName("UTF-8"));
      } catch (IOException | JSONException e) {
        e.printStackTrace();
      }

      return "404 ERROR".getBytes(Charset.forName("UTF-8"));
    } else {
      if (page.startsWith("all_")) language = "all";

      try {
        AssetManager am = context.getAssets();

        String template = "embedded_website/docs/method_template.html";

        if (readOnly && templateType == BootstrapSiteExporter.TEMPLATE_TYPE_BOOTSTRAP)
          template = "embedded_website/docs/method_template_readonly.html";
        else if (templateType == BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL)
          template = "embedded_website/docs/method_template_jekyll.html";

        InputStream in = am.open(template);

        // http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
        Scanner s = new Scanner(in).useDelimiter("\\A");

        String content = "";

        if (s.hasNext()) content = s.next();

        s.close();

        in = am.open("embedded_website/docs/" + language.toLowerCase() + "/" + page);

        s = new Scanner(in).useDelimiter("\\A");

        String pageContent = "";

        if (s.hasNext()) pageContent = s.next();

        s.close();

        for (Class classObj : scriptingClasses) {
          Method[] methods = classObj.getMethods();

          for (Method method : methods) {
            Annotation[] annotations = method.getDeclaredAnnotations();

            for (Annotation annotation : annotations) {
              if (annotation instanceof ScriptingEngineMethod) {
                ScriptingEngineMethod scriptAnnotation = (ScriptingEngineMethod) annotation;

                if (page.equals(scriptAnnotation.assetPath())) {
                  StringBuilder args = new StringBuilder();

                  for (String argument : ((ScriptingEngineMethod) annotation).arguments()) {
                    if (args.length() > 0) args.append(", ");

                    args.append(argument);
                  }

                  content =
                      content.replace(
                          "{{ METHOD_NAME }}", method.getName() + "(" + args.toString() + ")");
                  content =
                      content.replace(
                          "{{ LANGUAGE }}",
                          ((ScriptingEngineMethod) annotation).language().toLowerCase());
                  content = content.replace("{{ PAGE }}", page);
                }
              }
            }
          }
        }

        content = content.replace("{{ METHOD_DOCUMENTATION }}", pageContent);

        return content.getBytes(Charset.forName("UTF-8"));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return "404 ERROR".getBytes(Charset.forName("UTF-8"));
  }
Ejemplo n.º 22
0
  private static JSONArray methodsForLanguage(Context context, String language) {
    Class[] scriptingClasses = {JavaScriptEngine.class, SchemeEngine.class};

    ArrayList<String> languages = new ArrayList<>();
    languages.add(BootstrapSiteExporter.LANGUAGE_ALL.toLowerCase());

    if (languages.contains(language) == false) languages.add(language.toLowerCase());

    JSONArray declaredMethods = new JSONArray();
    HashSet<String> included = new HashSet<>();

    for (Class classObj : scriptingClasses) {
      Method[] methods = classObj.getMethods();

      for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();

        for (Annotation annotation : annotations) {
          if (annotation instanceof ScriptingEngineMethod) {
            ScriptingEngineMethod scriptAnnotation = (ScriptingEngineMethod) annotation;

            String category = context.getString(scriptAnnotation.category());
            String assetPath = scriptAnnotation.assetPath();
            String scriptLanguage = scriptAnnotation.language();
            String methodName = method.getName();

            if (languages.contains(scriptLanguage.toLowerCase())
                && included.contains(method.toGenericString()) == false) {
              StringBuilder args = new StringBuilder();

              for (String argument : ((ScriptingEngineMethod) annotation).arguments()) {
                if (args.length() > 0) args.append(", ");

                args.append(argument);
              }

              JSONObject methodDef = new JSONObject();

              try {
                methodDef.put(
                    BootstrapSiteExporter.METHOD_NAME, methodName + "(" + args.toString() + ")");
                methodDef.put(BootstrapSiteExporter.METHOD_FULL_NAME, method.toGenericString());
                methodDef.put(BootstrapSiteExporter.METHOD_LANGUAGE, scriptLanguage);
                methodDef.put(BootstrapSiteExporter.METHOD_CATEGORY, category);

                if (assetPath.trim().length() > 0)
                  methodDef.put(BootstrapSiteExporter.METHOD_ASSET_PATH, assetPath);
              } catch (JSONException e) {
                e.printStackTrace();
              }

              declaredMethods.put(methodDef);

              included.add(method.toGenericString());
            }
          }
        }
      }
    }

    return declaredMethods;
  }
  public static void populateObject(
      String operatorName,
      int operatorNum,
      String dataFlowName,
      Map<String, Object> objectProperties,
      Object top,
      EngineImportService engineImportService,
      EPDataFlowOperatorParameterProvider optionalParameterProvider,
      Map<String, Object> optionalParameterURIs)
      throws ExprValidationException {
    Class applicableClass = top.getClass();
    Set<WriteablePropertyDescriptor> writables =
        PropertyHelper.getWritableProperties(applicableClass);
    Set<Field> annotatedFields =
        JavaClassHelper.findAnnotatedFields(top.getClass(), DataFlowOpParameter.class);
    Set<Method> annotatedMethods =
        JavaClassHelper.findAnnotatedMethods(top.getClass(), DataFlowOpParameter.class);

    // find catch-all methods
    Set<Method> catchAllMethods = new LinkedHashSet<Method>();
    if (annotatedMethods != null) {
      for (Method method : annotatedMethods) {
        DataFlowOpParameter anno =
            (DataFlowOpParameter)
                JavaClassHelper.getAnnotations(
                        DataFlowOpParameter.class, method.getDeclaredAnnotations())
                    .get(0);
        if (anno.all()) {
          if (method.getParameterTypes().length == 2
              && method.getParameterTypes()[0] == String.class
              && method.getParameterTypes()[1] == Object.class) {
            catchAllMethods.add(method);
            continue;
          }
          throw new ExprValidationException("Invalid annotation for catch-call");
        }
      }
    }

    // map provided values
    for (Map.Entry<String, Object> property : objectProperties.entrySet()) {
      boolean found = false;
      String propertyName = property.getKey();

      // invoke catch-all setters
      for (Method method : catchAllMethods) {
        try {
          method.invoke(top, new Object[] {propertyName, property.getValue()});
        } catch (IllegalAccessException e) {
          throw new ExprValidationException(
              "Illegal access invoking method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + method.getName(),
              e);
        } catch (InvocationTargetException e) {
          throw new ExprValidationException(
              "Exception invoking method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + method.getName()
                  + ": "
                  + e.getTargetException().getMessage(),
              e);
        }
        found = true;
      }

      if (propertyName.toLowerCase().equals(CLASS_PROPERTY_NAME)) {
        continue;
      }

      // use the writeable property descriptor (appropriate setter method) from writing the property
      WriteablePropertyDescriptor descriptor =
          findDescriptor(applicableClass, propertyName, writables);
      if (descriptor != null) {
        Object coerceProperty =
            coerceProperty(
                propertyName,
                applicableClass,
                property.getValue(),
                descriptor.getType(),
                engineImportService,
                false);

        try {
          descriptor.getWriteMethod().invoke(top, new Object[] {coerceProperty});
        } catch (IllegalArgumentException e) {
          throw new ExprValidationException(
              "Illegal argument invoking setter method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + descriptor.getWriteMethod().getName()
                  + " provided value "
                  + coerceProperty,
              e);
        } catch (IllegalAccessException e) {
          throw new ExprValidationException(
              "Illegal access invoking setter method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + descriptor.getWriteMethod().getName(),
              e);
        } catch (InvocationTargetException e) {
          throw new ExprValidationException(
              "Exception invoking setter method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + descriptor.getWriteMethod().getName()
                  + ": "
                  + e.getTargetException().getMessage(),
              e);
        }
        continue;
      }

      // find the field annotated with {@link @GraphOpProperty}
      for (Field annotatedField : annotatedFields) {
        DataFlowOpParameter anno =
            (DataFlowOpParameter)
                JavaClassHelper.getAnnotations(
                        DataFlowOpParameter.class, annotatedField.getDeclaredAnnotations())
                    .get(0);
        if (anno.name().equals(propertyName) || annotatedField.getName().equals(propertyName)) {
          Object coerceProperty =
              coerceProperty(
                  propertyName,
                  applicableClass,
                  property.getValue(),
                  annotatedField.getType(),
                  engineImportService,
                  true);
          try {
            annotatedField.setAccessible(true);
            annotatedField.set(top, coerceProperty);
          } catch (Exception e) {
            throw new ExprValidationException(
                "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
          }
          found = true;
          break;
        }
      }
      if (found) {
        continue;
      }

      throw new ExprValidationException(
          "Failed to find writable property '"
              + propertyName
              + "' for class "
              + applicableClass.getName());
    }

    // second pass: if a parameter URI - value pairs were provided, check that
    if (optionalParameterURIs != null) {
      for (Field annotatedField : annotatedFields) {
        try {
          annotatedField.setAccessible(true);
          String uri = operatorName + "/" + annotatedField.getName();
          if (optionalParameterURIs.containsKey(uri)) {
            Object value = optionalParameterURIs.get(uri);
            annotatedField.set(top, value);
            if (log.isDebugEnabled()) {
              log.debug(
                  "Found parameter '"
                      + uri
                      + "' for data flow "
                      + dataFlowName
                      + " setting "
                      + value);
            }
          } else {
            if (log.isDebugEnabled()) {
              log.debug("Not found parameter '" + uri + "' for data flow " + dataFlowName);
            }
          }
        } catch (Exception e) {
          throw new ExprValidationException(
              "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
        }
      }
    }

    // third pass: if a parameter provider is provided, use that
    if (optionalParameterProvider != null) {
      for (Field annotatedField : annotatedFields) {
        try {
          annotatedField.setAccessible(true);
          Object provided = annotatedField.get(top);
          Object value =
              optionalParameterProvider.provide(
                  new EPDataFlowOperatorParameterProviderContext(
                      operatorName,
                      annotatedField.getName(),
                      top,
                      operatorNum,
                      provided,
                      dataFlowName));
          if (value != null) {
            annotatedField.set(top, value);
          }
        } catch (Exception e) {
          throw new ExprValidationException(
              "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
        }
      }
    }
  }
Ejemplo n.º 24
0
 protected AnnotatedMethod _constructCreatorMethod(Method m) {
   return new AnnotatedMethod(
       m,
       _collectRelevantAnnotations(m.getDeclaredAnnotations()),
       _collectRelevantAnnotations(m.getParameterAnnotations()));
 }
Ejemplo n.º 25
0
 protected AnnotatedMethod _constructMethod(Method m) {
   /* note: parameter annotations not used for regular (getter, setter)
    * methods; only for creator methods (static factory methods)
    */
   return new AnnotatedMethod(m, _collectRelevantAnnotations(m.getDeclaredAnnotations()), null);
 }
 @Override
 public Annotation[] getDeclaredAnnotations() {
   return getterMethod.getDeclaredAnnotations();
 }
Ejemplo n.º 27
0
  public static void main(String[] args) {
    Mix proxyMe = new Mix();
    Object proxy = createProxy(proxyMe);

    if (!Proxy.isProxyClass(proxy.getClass())) System.err.println("not a proxy class?");
    if (Proxy.getInvocationHandler(proxy) == null)
      System.err.println("ERROR: Proxy.getInvocationHandler is null");

    /* take it for a spin; verifies instanceof constraint */
    Shapes shapes = (Shapes) proxy;
    shapes.circle(3);
    shapes.rectangle(10, 20);
    shapes.blob();
    Quads quads = (Quads) proxy;
    quads.rectangle(15, 25);
    quads.trapezoid(6, 81.18, 4);
    Colors colors = (Colors) proxy;
    colors.red(1.0f);
    colors.blue(777);
    colors.mauve("sorry");
    colors.blob();

    try {
      shapes.upChuck();
      System.out.println("Didn't get expected exception");
    } catch (IndexOutOfBoundsException ioobe) {
      System.out.println("Got expected ioobe");
    }
    try {
      shapes.upCheck();
      System.out.println("Didn't get expected exception");
    } catch (InterruptedException ie) {
      System.out.println("Got expected ie");
    }

    /*
     * Exercise annotations on Proxy classes.  This is mostly to ensure
     * that annotation calls work correctly on generated classes.
     */
    System.out.println("");
    Method[] methods = proxy.getClass().getDeclaredMethods();
    Arrays.sort(
        methods,
        new Comparator<Method>() {
          public int compare(Method o1, Method o2) {
            int result = o1.getName().compareTo(o2.getName());
            if (result != 0) {
              return result;
            }
            return o1.getReturnType().getName().compareTo(o2.getReturnType().getName());
          }
        });
    System.out.println(
        "Proxy interfaces: " + Arrays.deepToString(proxy.getClass().getInterfaces()));
    System.out.println("Proxy methods: " + Arrays.deepToString(methods));
    Method meth = methods[methods.length - 1];
    System.out.println("Decl annos: " + Arrays.deepToString(meth.getDeclaredAnnotations()));
    Annotation[][] paramAnnos = meth.getParameterAnnotations();
    System.out.println(
        "Param annos (" + paramAnnos.length + ") : " + Arrays.deepToString(paramAnnos));
  }