Example usage for java.lang.reflect Method isAnnotationPresent

List of usage examples for java.lang.reflect Method isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Method isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:org.itest.impl.ITestDefinitionFactoryImpl.java

private void buildDependencies(Class<?> clazz) {
    L: for (Method method : clazz.getDeclaredMethods()) {
        if (method.isAnnotationPresent(ITests.class)) {
            int methodTestCounter = 0;
            for (ITest path : method.getAnnotation(ITests.class).value()) {
                String testName = path.name();
                if (0 == testName.length()) {
                    testName = method.getName() + "#itest" + methodTestCounter;
                }//from  ww w.ja va 2s .c o m
                ITestIdentifier itestIdentifier = new ITestIdentifier(clazz, testName);
                if (null == itestMap.get(itestIdentifier)) {
                    itestMap.put(itestIdentifier, new ITestDeclaration(method, path));
                    Collection<ITestDependency> col = new ArrayList<ITestDependency>();
                    itestDependencyMap.put(itestIdentifier, col);
                    for (ITestRef initRef : path.initRef()) {
                        Class<?> refClass = initRef.useClass() == ITestRef.class ? clazz : initRef.useClass();
                        String refTestName = initRef.use();
                        col.add(new ITestDependency(initRef.assign(),
                                new ITestIdentifier(refClass, refTestName)));
                        if (refClass != clazz) {
                            buildDependencies(refClass);
                        }
                    }
                } else {
                    break L;
                }
                methodTestCounter++;
            }
        }
    }
}

From source file:com.socialize.SocializeActionProxy.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {/*from   w  w w  .  jav a  2  s .  c  om*/
        if (synchronous || method.isAnnotationPresent(Synchronous.class) || !isVoidMethod(method)) {

            Context context = findContext(args);

            if (context != null) {
                synchronized (this) {
                    SocializeService socialize = Socialize.getSocialize();

                    if (!socialize.isInitialized(context)) {
                        socialize.init(context);
                        if (!socialize.isAuthenticated() && !method.isAnnotationPresent(NoAuth.class)) {
                            socialize.authenticateSynchronous(context);
                        }
                    }
                }
            }

            return method.invoke(getBean(), args);
        } else {
            Activity context = findActivity(args);

            if (context != null) {
                SocializeListener listener = findListener(args);

                // Always init to set the context
                invokeWithInit(context, listener, method, args);
            } else {
                throw new MethodNotSupportedException(
                        "No activity found in method arguments for method [" + method.getName() + "]");
            }
        }

        // Always void
        return null;
    } catch (Throwable e) {
        SocializeLogger.e(e.getMessage(), e);
        throw e;
    }
}

From source file:org.wso2.carbon.appmgt.mdm.wso2emm.ApplicationOperationsImpl.java

/**
 *
 * @param applicationOperationAction holds the information needs to perform an action on mdm
 *//*ww  w . j a  v a 2  s.  c om*/

public String performAction(ApplicationOperationAction applicationOperationAction) {

    HashMap<String, String> configProperties = applicationOperationAction.getConfigParams();

    String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    String[] params = applicationOperationAction.getParams();
    JSONArray resources = new JSONArray();
    for (String param : params) {
        resources.add(param);
    }

    String action = applicationOperationAction.getAction();
    String type = applicationOperationAction.getType();
    int tenantId = applicationOperationAction.getTenantId();
    JSONObject requestObj = new JSONObject();
    requestObj.put("action", action);
    requestObj.put("to", type);
    requestObj.put("resources", resources);
    requestObj.put("tenantId", tenantId);

    JSONObject requestApp = new JSONObject();

    App app = applicationOperationAction.getApp();
    Method[] methods = app.getClass().getMethods();

    for (Method method : methods) {

        if (method.isAnnotationPresent(Property.class)) {
            try {
                Object value = method.invoke(app);
                if (value != null) {
                    requestApp.put(method.getAnnotation(Property.class).name(), value);
                }
            } catch (IllegalAccessException e) {
                String errorMessage = "Illegal Action";
                if (log.isDebugEnabled()) {
                    log.error(errorMessage, e);
                } else {
                    log.error(errorMessage);
                }

            } catch (InvocationTargetException e) {
                String errorMessage = "Target invocation failed";
                if (log.isDebugEnabled()) {
                    log.error(errorMessage, e);
                } else {
                    log.error(errorMessage);
                }
            }
        }

    }

    requestObj.put("app", requestApp);

    String requestURL = serverURL + String.format(Constants.API_OPERATION, tenantId);
    HttpClient httpClient = AppManagerUtil.getHttpClient(requestURL);
    StringEntity requestEntity = null;

    if (log.isDebugEnabled())
        log.debug("Request Payload for MDM: " + requestObj.toJSONString());

    try {
        requestEntity = new StringEntity(requestObj.toJSONString(), "UTF-8");
        requestEntity.setContentType(Constants.RestConstants.APPLICATION_JSON);
    } catch (UnsupportedEncodingException e) {
        String errorMessage = "JSON encoding not supported";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }

    HttpPost postMethod = new HttpPost(requestURL);
    postMethod.setEntity(requestEntity);
    postMethod.setHeader(Constants.RestConstants.AUTHORIZATION, Constants.RestConstants.BASIC
            + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes())));

    try {
        if (log.isDebugEnabled())
            log.debug("Sending POST request to perform operation on MDM. Request path:  " + requestURL);
        HttpResponse response = httpClient.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            if (log.isDebugEnabled())
                log.debug(action + " operation on WSO2 EMM performed successfully");
        }

    } catch (IOException e) {
        String errorMessage = "Cannot connect to WSO2 EMM to perform operation";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }

    return null;

}

From source file:gobblin.runtime.cli.PublicMethodsGobblinCliFactory.java

private boolean canUseMethod(Method method) {
    if (!Modifier.isPublic(method.getModifiers())) {
        return false;
    }/*from   w  ww .j a  v  a 2  s  . c  o m*/
    if (BLACKLISTED_FROM_CLI.contains(method.getName())) {
        return false;
    }
    if (method.isAnnotationPresent(NotOnCli.class)) {
        return false;
    }
    Class<?>[] parameters = method.getParameterTypes();
    if (parameters.length > 2) {
        return false;
    }
    if (parameters.length == 1 && parameters[0] != String.class) {
        return false;
    }
    return true;
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ResultSetConverterBlockServiceImpl.java

/**
 * Gets table prefix from @JoinColumn.name()
 * @param method getter method with OneToOne annotation and possibly JoinColumn
 * @return @JoinColumn.name() + "_" or empty string ("") 
 *//*from   w w w  .  j  a  v  a  2 s  . c  o  m*/
private String getTablePrefixFromJoinColumnAnnotation(Method method) {
    String name = "";
    if (method.isAnnotationPresent(JoinColumn.class)) {
        JoinColumn joinColumn = method.getAnnotation(JoinColumn.class);
        if (StringUtils.hasText(joinColumn.table())) {
            name = joinColumn.table() + "_";
        }
    }
    return name;
}

From source file:com.utest.dao.AuditTrailInterceptor.java

@SuppressWarnings("unchecked")
private Field[] getAllFields(final Class objectClass) {

    final List<Field> fields = new ArrayList<Field>();
    for (final Method method : objectClass.getMethods()) {
        if (method.isAnnotationPresent(Audit.class)) {
            try {
                final Field methodField = objectClass.getDeclaredField(
                        method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4));
                if (methodField != null) {
                    fields.add(methodField);
                }/*  w  ww  . j  a  v  a2 s.c om*/
            } catch (final Exception e) {
            }
        }
    }
    for (final Field field : objectClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(Audit.class)) {
            fields.add(field);
        }
    }

    return fields.toArray(new Field[fields.size()]);

}

From source file:org.castor.cpa.jpa.info.JPACallbackHandler.java

/**
 * Invokes callback methods accordingly.
 * // w  w  w .  ja  v a2s  . co m
 * @param annotationClass
 *            the annotation to look for
 * @param object
 *            the object to invoke callbacks on
 * @param <A>
 *            helper annotation generics
 * @throws InvocationTargetException
 *             on callback invocation error
 * @throws IllegalAccessException
 *             on illegal method access error
 */
private <A extends Annotation> void invokeCallbacksFor(final Class<A> annotationClass, final Object object)
        throws InvocationTargetException, IllegalAccessException {
    final Class<?> klass = object.getClass();
    final Method[] declaredMethods = klass.getDeclaredMethods();
    for (Method method : declaredMethods) {
        if (method.isAnnotationPresent(annotationClass)) {
            if (!_overriddenCallbacks.containsKey(method.getName())) {
                invokeCallback(method, object);
            }
        }
    }
}

From source file:org.jahia.bin.TestServlet.java

private boolean isMethodAnnotationPresent(Class<?> checkedClass, Class<? extends Annotation> annotationClass) {
    boolean isPresent = false;
    for (Method method : checkedClass.getMethods()) {
        if (method.isAnnotationPresent(annotationClass)) {
            isPresent = true;/* w w w  .ja v a  2s.c  om*/
            break;
        }
    }
    return isPresent;
}

From source file:org.pepstock.jem.springbatch.tasks.utilities.LauncherTasklet.java

@Override
public RepeatStatus run(StepContribution stepContribution, ChunkContext chunkContext) throws TaskletException {
    if (object == null) {
        LogAppl.getInstance().emit(SpringBatchMessage.JEMS051E, "object");
        throw new TaskletException(SpringBatchMessage.JEMS051E.toMessage().getFormattedMessage("object"));
    }/*from   w w w. j  a  v a 2  s. c om*/

    // load by Class.forName
    Class<?> clazz = object.getClass();
    // executes beans
    try {
        // applies all annotations
        SetFields.applyByAnnotation(object);
        // applies annotation with step contribution and chunk
        applyByAnnotation(clazz, object, stepContribution, chunkContext);

        // check if it's a Tasklet and not JemTasklet. if not,
        // exception occurs.
        if (object instanceof Runnable) {
            run((Runnable) object);
        } else {
            // scans the method to see if there is any method to be executed
            Method method = null;
            for (Method m : clazz.getDeclaredMethods()) {
                // checks if there is the annotation
                // and not already set
                if (m.isAnnotationPresent(ToBeExecuted.class) && method == null) {
                    //set method name
                    method = m;
                }
            }
            // if method is null, means that it doesn't know which method must be executed
            if (method == null) {
                LogAppl.getInstance().emit(SpringBatchMessage.JEMS050E, clazz.getName());
                throw new TaskletException(
                        SpringBatchMessage.JEMS050E.toMessage().getFormattedMessage(clazz.getName()));
            }
            // loads parameters. 
            // if methods doesn't have any parameter, parms to null
            // otherwise step contribution and chunk context must be passed to the method
            Object[] parms;
            if (method.getParameterTypes().length == 0) {
                // if parms not null, will pass the map to the method
                parms = null;
            } else {
                parms = new Object[] { stepContribution, chunkContext };
            }
            // invoke
            method.invoke(object, parms);
        }
    } catch (SecurityException e) {
        throw new TaskletException(e);
    } catch (NamingException e) {
        throw new TaskletException(e);
    } catch (IllegalAccessException e) {
        throw new TaskletException(e);
    } catch (IllegalArgumentException e) {
        throw new TaskletException(e);
    } catch (InvocationTargetException e) {
        throw new TaskletException(e);
    }
    return RepeatStatus.FINISHED;
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ResultSetConverterBlockServiceImpl.java

private List<OneToOneLink> createOneToOneLinks(String parentTablePrefix,
        ParameterConverterService converterService, Class type, StoredProcedureInfo procedureInfo) {
    List<OneToOneLink> oneToOneLinks = new LinkedList<OneToOneLink>();
    for (Method method : type.getMethods()) {
        if (method.isAnnotationPresent(OneToOne.class) || method.isAnnotationPresent(ManyToOne.class)) {
            String tablePrefix = parentTablePrefix + getTablePrefixFromJoinColumnAnnotation(method);
            Class oneToOneClass = method.getReturnType();
            if (LOG.isDebugEnabled()) {
                LOG.debug("        Finded {}.{}", type.getSimpleName(), oneToOneClass.getSimpleName());
            }//from w  w  w . j  av  a2  s.  c om
            Method oneToOneSetterMethod = BlockFactoryUtils.findSetterMethod(type, method);
            List<EntityPropertySetter> oneToOnePropertySetters = createEntityPropertySetters(converterService,
                    oneToOneClass, procedureInfo, tablePrefix);
            ResultSetConverterBlockEntity oneToOneBlock = new ResultSetConverterBlockEntity(oneToOneClass,
                    oneToOnePropertySetters,
                    createOneToOneLinks(tablePrefix, converterService, oneToOneClass, procedureInfo));
            oneToOneLinks.add(new OneToOneLink(oneToOneBlock, oneToOneSetterMethod));
        }
    }
    return oneToOneLinks;
}