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.LexGrid.LexBIG.test.ContentLoadingTestListener.java

protected boolean loadContent(Method method) {
    List<LoadContent> contents = new ArrayList<LoadContent>();

    if (method.isAnnotationPresent(LoadContent.class)) {
        contents.add(method.getAnnotation(LoadContent.class));
    }//from   ww  w . j  a  v  a 2  s. c  om

    LoadContents loadContents = method.getAnnotation(LoadContents.class);
    if (loadContents != null) {
        contents.addAll(Arrays.asList(loadContents.value()));
    }

    return this.doLoadContent(contents);
}

From source file:org.photovault.replication.VersionedClassDesc.java

/**
 Analyze the annotations in described class and populate this object
 based on results/*from  w  w w .j  a  v a2  s.c o  m*/
 @param cl the clas to analyze
 */
private void analyzeClass(Class cl) {
    Class scl = cl.getSuperclass();
    if (scl != null) {
        analyzeClass(scl);
    }
    Versioned info = (Versioned) cl.getAnnotation(Versioned.class);
    if (info != null) {
        editorIntf = info.editor();
        Class csClass = info.changeSerializer();
        try {
            changeSerializer = (ChangeSerializer) csClass.newInstance();
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (InstantiationException ex) {
            throw new RuntimeException(ex);
        }
    }
    for (Method m : cl.getDeclaredMethods()) {
        if (m.isAnnotationPresent(ValueField.class)) {
            try {
                ValueFieldDesc f = new ValueFieldDesc(this, m, editorIntf);
                fields.put(f.name, f);
            } catch (NoSuchMethodException ex) {
                log.error("Error analyzing method " + cl.getName() + "." + m.getName(), ex);
                throw new IllegalArgumentException("Error analyzing method " + cl.getName() + "." + m.getName(),
                        ex);
            }
        } else if (m.isAnnotationPresent(SetField.class)) {
            try {
                SetFieldDesc f = new SetFieldDesc(this, m, editorIntf);
                fields.put(f.name, f);
            } catch (NoSuchMethodException ex) {
                log.error("Error analyzing method " + cl.getName() + "." + m.getName(), ex);
                throw new IllegalArgumentException("Error analyzing method " + cl.getName() + "." + m.getName(),
                        ex);
            }
        } else if (m.isAnnotationPresent(History.class)) {
            getHistoryMethod = m;
        }
    }
    if (cl.isAnnotationPresent(Versioned.class) && getHistoryMethod == null) {
        throw new IllegalStateException(
                "Versioned class " + cl.getName() + " does not define method for accessing history");
    }
}

From source file:org.LexGrid.LexBIG.caCore.client.proxy.LexEVSProxyHelperImpl.java

/**
 * Returns true if the object is initialized
 *///w w  w .  j av a  2 s .c o m
@SuppressWarnings("unchecked")
@Override
public boolean isInitialized(MethodInvocation invocation) throws Throwable {
    if (invocation.getThis() == null || invocation.getThis() instanceof RemoteShell) {
        return false;
    }

    Class implClass = invocation.getThis().getClass();

    // LexBig objects have methods that must be executed remotely
    if (LexEVSCaCoreUtils.isLexBigClass(implClass)) {
        Method method = invocation.getMethod();
        Method methodImpl = implClass.getMethod(method.getName(), method.getParameterTypes());

        if (methodImpl.isAnnotationPresent(ADMIN_FUNCTION)) {
            throw new UnsupportedOperationException(
                    "Admin functions cannot be executed using the distributed API");
        }

        if (isClientSafe(methodImpl)) {
            log.info("DLB calling locally: " + implClass.getName() + "." + methodImpl.getName());
            return true;
        }

        log.info("DLB calling remotely: " + implClass.getName() + "." + methodImpl.getName());
        return false;
    }

    return true;
}

From source file:org.cleandroid.core.support.v4.Fragment.java

@Override
@CallSuper//from w  ww . j av a 2  s.c o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        ComponentHandler.injectDependencies(this, getActivity());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    InEventsHandler.handle(this);
    for (Method method : getClass().getDeclaredMethods()) {
        if (method.isAnnotationPresent(OnCreate.class)) {
            Object[] parameters = DependencyManager.getMethodDependencies(method, getActivity(),
                    savedInstanceState);
            try {
                method.invoke(this, parameters);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (method.isAnnotationPresent(OnViewCreated.class)) {
            onViewCreatedCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnActivityCreated.class)) {
            onActivityCreatedCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnViewStateRestored.class)) {
            onViewStateRestoredCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnStart.class)) {
            onStartCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnResume.class)) {
            onResumeCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnSaveInstanceState.class)) {
            onSaveInstanceStateCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnStop.class)) {
            onStopCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnDestroyView.class)) {
            onDestroyViewCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnAttach.class)) {
            onAttachCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnDetach.class)) {
            onDetachCallbacks.add(method);
        } else if (method.isAnnotationPresent(OnDestroy.class)) {
            onDestroyCallbacks.add(method);
        }

    }
}

From source file:com.github.kongchen.swagger.docgen.mavenplugin.SpringMavenDocumentSource.java

@Override
public void loadDocuments() throws GenerateException {
    Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>();
    SwaggerConfig swaggerConfig = new SwaggerConfig();
    swaggerConfig.setApiVersion(apiSource.getApiVersion());
    swaggerConfig.setSwaggerVersion(SwaggerSpec.version());
    List<ApiListingReference> apiListingReferences = new ArrayList<ApiListingReference>();
    List<AuthorizationType> authorizationTypes = new ArrayList<AuthorizationType>();

    //relate all methods to one base request mapping if multiple controllers exist for that mapping
    //get all methods from each controller & find their request mapping
    //create map - resource string (after first slash) as key, new SpringResource as value
    for (Class<?> c : apiSource.getValidClasses()) {
        RequestMapping requestMapping = (RequestMapping) c.getAnnotation(RequestMapping.class);
        String description = "";
        if (c.isAnnotationPresent(Api.class)) {
            description = ((Api) c.getAnnotation(Api.class)).value();
        }//from w  w  w  . ja  v a2  s  .c om
        if (requestMapping != null && requestMapping.value().length != 0) {
            //This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError
            //This occurs when a class or method loaded by reflections contains a type that has no dependency
            try {
                resourceMap = analyzeController(c, resourceMap, description);
                List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods()));
                if (c.getSuperclass() != null) {
                    mList.addAll(Arrays.asList(c.getSuperclass().getMethods()));
                }
                for (Method m : mList) {
                    if (m.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping methodReq = m.getAnnotation(RequestMapping.class);
                        //isolate resource name - attempt first by the first part of the mapping
                        if (methodReq != null && methodReq.value().length != 0) {
                            for (int i = 0; i < methodReq.value().length; i++) {
                                String resourceKey = "";
                                String resourceName = Utils.parseResourceName(methodReq.value()[i]);
                                if (!(resourceName.equals(""))) {
                                    String version = Utils.parseVersion(requestMapping.value()[0]);
                                    //get version - first try by class mapping, then method
                                    if (version.equals("")) {
                                        //class mapping failed - use method
                                        version = Utils.parseVersion(methodReq.value()[i]);
                                    }
                                    resourceKey = Utils.createResourceKey(resourceName, version);
                                    if ((!(resourceMap.containsKey(resourceKey)))) {
                                        resourceMap.put(resourceKey,
                                                new SpringResource(c, resourceName, resourceKey, description));
                                    }
                                    resourceMap.get(resourceKey).addMethod(m);
                                }
                            }
                        }
                    }
                }
            } catch (NoClassDefFoundError e) {
                LOG.error(e.getMessage());
                LOG.info(c.getName());
                //exception occurs when a method type or annotation is not recognized by the plugin
            } catch (ClassNotFoundException e) {
                LOG.error(e.getMessage());
                LOG.info(c.getName());
            }

        }
    }
    for (String str : resourceMap.keySet()) {
        ApiListing doc = null;
        SpringResource resource = resourceMap.get(str);

        try {
            doc = getDocFromSpringResource(resource, swaggerConfig);
            setBasePath(doc.basePath());
        } catch (Exception e) {
            LOG.error("DOC NOT GENERATED FOR: " + resource.getResourceName());
            e.printStackTrace();
        }
        if (doc == null)
            continue;
        ApiListingReference apiListingReference = new ApiListingReference(doc.resourcePath(), doc.description(),
                doc.position());
        apiListingReferences.add(apiListingReference);
        acceptDocument(doc);

    }
    // sort apiListingRefernce by position
    Collections.sort(apiListingReferences, new Comparator<ApiListingReference>() {
        @Override
        public int compare(ApiListingReference o1, ApiListingReference o2) {
            if (o1 == null && o2 == null)
                return 0;
            if (o1 == null && o2 != null)
                return -1;
            if (o1 != null && o2 == null)
                return 1;
            return o1.position() - o2.position();
        }
    });
    serviceDocument = new ResourceListing(swaggerConfig.apiVersion(), swaggerConfig.swaggerVersion(),
            scala.collection.immutable.List
                    .fromIterator(JavaConversions.asScalaIterator(apiListingReferences.iterator())),
            scala.collection.immutable.List.fromIterator(
                    JavaConversions.asScalaIterator(authorizationTypes.iterator())),
            swaggerConfig.info());
}

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

/**
 * @param action action of the operation. Eg. install, uninstall, update
 * @param app application object/*from   w  w w .ja v  a  2s .co m*/
 * @param tenantId tenantId
 * @param type type of the resource. Eg: role, user, device
 * @param params ids of the resources which belong to type
 */

public void performAction(User currentUser, String action, App app, int tenantId, String type, String[] params,
        HashMap<String, String> configProperties) {

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

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

    JSONObject requestObj = new JSONObject();
    requestObj.put("action", action);
    requestObj.put("to", type);
    requestObj.put("resources", resources);
    requestObj.put("tenantId", tenantId);

    JSONObject requestApp = new JSONObject();

    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);

    HttpClient httpClient = new HttpClient();
    StringRequestEntity requestEntity = null;

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

    try {
        requestEntity = new StringRequestEntity(requestObj.toJSONString(), "application/json", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        String errorMessage = "JSON encoding not supported";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }

    String requestURL = serverURL + String.format(Constants.API_OPERATION, tenantId);

    PostMethod postMethod = new PostMethod(requestURL);
    postMethod.setRequestEntity(requestEntity);
    postMethod.setRequestHeader("Authorization",
            "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);
        int statusCode = httpClient.executeMethod(postMethod);
        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);
        }
    }

}

From source file:org.springmodules.xt.model.generator.factory.FactoryGeneratorInterceptor.java

private boolean isFactoryMethod(Method method) {
    if (method.isAnnotationPresent(FactoryMethod.class)) {
        return true;
    } else {//  w ww.  j  av  a  2s  . co m
        return false;
    }
}

From source file:de.doncarnage.minecraft.common.commandhandler.manager.impl.DefaultCommandManager.java

private List<ExtractedCommandBean> extractAllCommands(CommandHolder commandHolder) {
    List<ExtractedCommandBean> commandList = new ArrayList<>();
    for (Method method : commandHolder.getClass().getMethods()) {
        if (method.isAnnotationPresent(ExecutableCommand.class)) {
            checkForRightMethodFormat(commandHolder, method);
            ExtractedCommandBean ecb = new ExtractedCommandBean();
            ExecutableCommand ec = method.getAnnotation(ExecutableCommand.class);
            ecb.setCmd(ec.cmd());/*from   ww  w  . ja v a 2 s  .  c o m*/
            ecb.setDescription(ec.desc());
            ecb.setParams(ec.params());
            ecb.setPermissions(ec.permission());
            ecb.setExecutable(method);
            ecb.setInstance(commandHolder);
            if (validate(ecb)) {
                commandList.add(ecb);
            }
        }
    }
    return commandList;
}

From source file:com.evolveum.midpoint.repo.sql.query2.definition.ClassDefinitionParser.java

private ItemPath getJaxbName(Method method) {
    if (method.isAnnotationPresent(JaxbName.class)) {
        JaxbName jaxbName = method.getAnnotation(JaxbName.class);
        return new ItemPath(new QName(jaxbName.namespace(), jaxbName.localPart()));
    } else if (method.isAnnotationPresent(JaxbPath.class)) {
        JaxbPath jaxbPath = method.getAnnotation(JaxbPath.class);
        List<QName> names = new ArrayList<>(jaxbPath.itemPath().length);
        for (JaxbName jaxbName : jaxbPath.itemPath()) {
            names.add(new QName(jaxbName.namespace(), jaxbName.localPart()));
        }//from w  w  w .  j a v  a  2  s .c  o  m
        return new ItemPath(names.toArray(new QName[0]));
    } else {
        return new ItemPath(new QName(SchemaConstantsGenerated.NS_COMMON, getPropertyName(method.getName())));
    }
}

From source file:com.aw.swing.mvp.binding.component.support.ValidatorBuilder.java

public PropertyValidator buildPropertyValidator(Method method) {
    PropertyValidator propertyValidator = new PropertyValidator();
    if (method.isAnnotationPresent(Validation.class)) {
        Validation validation = method.getAnnotation(Validation.class);
        String patterValidator = validation.value();
        logger.debug("Patter Validator = " + patterValidator);
        propertyValidator = PatternRules.buildPropertyValidator(patterValidator);

    }/*  w ww  . jav a 2 s.c  o  m*/

    if (method.isAnnotationPresent(Email.class)) {
        propertyValidator.add(Rule.VALIDATE_EMAIL);
    }
    if (method.isAnnotationPresent(RangeNumber.class)) {
        RangeNumber range = method.getAnnotation(RangeNumber.class);
        propertyValidator.add(Rule.VALIDATE_RANGE);
        propertyValidator.setMinValue(range.min());
        propertyValidator.setMaxValue(range.max());
    }
    if (method.isAnnotationPresent(RangeDate.class)) {
        SimpleDateFormat sdf = new SimpleDateFormat(
                AWBaseContext.instance().getConfigInfoProvider().getDateFormat());
        RangeDate range = method.getAnnotation(RangeDate.class);
        propertyValidator.add(Rule.VALIDATE_RANGE);
        Date from = null;
        Date to = null;
        try {
            if (range.from().equals("today")) {
                from = new Date();
            } else {
                from = sdf.parse(range.from());
            }
            if (range.to().equals("today")) {
                to = new Date();
            } else {
                to = sdf.parse(range.to());
            }

            propertyValidator.setMinValue(from);
            propertyValidator.setMaxValue(to);
        } catch (ParseException e) {
            logger.error("Error execute parse from <" + range.from() + "> to <" + range.to() + ">");
        }
    }
    if (method.isAnnotationPresent(Past.class)) {
        propertyValidator.add(Rule.VALIDATE_LESS_THAN);
        propertyValidator.setMaxValue(new Date());
    }
    if (method.isAnnotationPresent(Future.class)) {
        propertyValidator.add(Rule.VALIDATE_GREATER_THAN);
        propertyValidator.setMinValue(new Date());
    }
    return propertyValidator;
}