Example usage for java.lang Class getAnnotation

List of usage examples for java.lang Class getAnnotation

Introduction

In this page you can find the example usage for java.lang Class getAnnotation.

Prototype

@SuppressWarnings("unchecked")
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) 

Source Link

Usage

From source file:org.smartdeveloperhub.vocabulary.config.Configuration.java

private <T> String getExtensionId(final Class<? extends T> clazz) {
    final ConfigurationExtension annotation = clazz.getAnnotation(ConfigurationExtension.class);
    String id = null;// w  w  w .  j av  a2s  .c o m
    if (annotation != null) {
        id = annotation.value();
    } else {
        id = clazz.getSimpleName();
    }
    Preconditions.checkArgument(id != null, "Unknown extension %s", clazz.getCanonicalName());
    return id;
}

From source file:ditl.cli.App.java

protected String getDefaultName(Class<? extends Trace<?>> klass) {
    return klass.getAnnotation(Trace.Type.class).value();
}

From source file:org.rosenvold.spring.convention.ConventionContextLoader.java

protected String[] modifyLocations(Class<?> clazz, String... locations) {
    final ConventionConfiguration annotation = clazz.getAnnotation(ConventionConfiguration.class);
    if (annotation != null) {
        candidateEvaluator = annotation.candidateEvaluator();
        nameToClassResolver = annotation.nameToClassResolver();
    }/*from   ww  w  .  j  a  v  a 2 s.  c  o  m*/
    return locations;
}

From source file:cn.edu.zju.bigdata.controller.JerseyController.java

@GET
@Path("/_list")
@Produces({ "application/json" })
//@ReturnType("java.lang.List<String>")
public Response listAPI() {

    List<String> apiList = new ArrayList<String>();

    Reflections reflections = new Reflections("cn.edu.zju.bigdata.controller");

    Set<Class<?>> allClasses = reflections.getTypesAnnotatedWith(Path.class);

    for (Class<?> controller : allClasses) {
        String apiPath = controller.getAnnotation(Path.class).value();
        for (Method method : controller.getMethods()) {
            // Filter the API with the @RequestMapping Annotation
            String apiMethod = method.isAnnotationPresent(GET.class) ? "GET"
                    : method.isAnnotationPresent(POST.class) ? "POST"
                            : method.isAnnotationPresent(PUT.class) ? "PUT"
                                    : method.isAnnotationPresent(DELETE.class) ? "DELETE"
                                            : method.isAnnotationPresent(HEAD.class) ? "HEAD" : null;
            if (apiMethod == null)
                continue;

            if (method.isAnnotationPresent(Path.class))
                apiPath += method.getAnnotation(Path.class).value();

            // Filter out /_list itself
            if (apiPath.equals("/_list"))
                continue;

            apiList.add(apiMethod + " " + apiPath);
        }/*from w w w.  j a  v a2 s  . com*/
    }

    return Response.ok().entity(apiList).build();
}

From source file:com.github.rvesse.airline.model.MetadataLoader.java

public static <C> GlobalMetadata<C> loadGlobal(Class<?> cliClass) {
    Annotation annotation = cliClass.getAnnotation(com.github.rvesse.airline.annotations.Cli.class);
    if (annotation == null)
        throw new IllegalArgumentException(
                String.format("Class %s does not have the @Cli annotation", cliClass));

    com.github.rvesse.airline.annotations.Cli cliConfig = (com.github.rvesse.airline.annotations.Cli) annotation;

    // Prepare commands
    CommandMetadata defaultCommand = null;
    if (!cliConfig.defaultCommand().equals(com.github.rvesse.airline.annotations.Cli.NO_DEFAULT.class)) {
        defaultCommand = loadCommand(cliConfig.defaultCommand());
    }/*from  ww  w. ja va  2s  .co  m*/
    List<CommandMetadata> defaultGroupCommands = new ArrayList<CommandMetadata>();
    for (Class<?> cls : cliConfig.commands()) {
        defaultGroupCommands.add(loadCommand(cls));
    }

    // Prepare parser configuration
    ParserMetadata<C> parserConfig = cliConfig.parserConfiguration() != null
            ? MetadataLoader.<C>loadParser(cliConfig.parserConfiguration())
            : MetadataLoader.<C>loadParser(cliClass);

    // Prepare restrictions
    // We find restrictions in the following order:
    // 1 - Those declared via annotations
    // 2 - Those declared via the restrictions field of the @Cli annotation
    // 3 - Standard restrictions if the includeDefaultRestrctions field of
    // the @Cli annotation is true
    List<GlobalRestriction> restrictions = new ArrayList<GlobalRestriction>();
    for (Class<? extends Annotation> annotationClass : RestrictionRegistry
            .getGlobalRestrictionAnnotationClasses()) {
        annotation = cliClass.getAnnotation(annotationClass);
        if (annotation == null)
            continue;
        GlobalRestriction restriction = RestrictionRegistry.getGlobalRestriction(annotationClass, annotation);
        if (restriction != null)
            restrictions.add(restriction);
    }
    for (Class<? extends GlobalRestriction> cls : cliConfig.restrictions()) {
        restrictions.add(ParserUtil.createInstance(cls));
    }
    if (cliConfig.includeDefaultRestrictions()) {
        restrictions.addAll(AirlineUtils.arrayToList(GlobalRestriction.DEFAULTS));
    }

    // Prepare groups
    // We sort sub-groups by name length then lexically
    // This means that when we build the groups hierarchy we'll ensure we
    // build the parent groups first wherever possible
    Map<String, CommandGroupMetadata> subGroups = new TreeMap<String, CommandGroupMetadata>(
            new StringHierarchyComparator());
    List<CommandGroupMetadata> groups = new ArrayList<CommandGroupMetadata>();
    for (Group groupAnno : cliConfig.groups()) {
        String groupName = groupAnno.name();
        String subGroupPath = null;
        if (StringUtils.containsWhitespace(groupName)) {
            // Normalize the path
            subGroupPath = StringUtils.join(StringUtils.split(groupAnno.name()), ' ');
        }

        // Maybe a top level group we've already seen
        CommandGroupMetadata group = CollectionUtils.find(groups, new GroupFinder(groupName));
        if (group == null) {
            // Maybe a sub-group we've already seen
            group = subGroups.get(subGroupPath);
        }

        List<CommandMetadata> groupCommands = new ArrayList<CommandMetadata>();
        for (Class<?> cls : groupAnno.commands()) {
            groupCommands.add(loadCommand(cls));
        }

        if (group == null) {
            // Newly discovered group
            //@formatter:off
            group = loadCommandGroup(subGroupPath != null ? subGroupPath : groupName, groupAnno.description(),
                    groupAnno.hidden(), Collections.<CommandGroupMetadata>emptyList(),
                    !groupAnno.defaultCommand().equals(Group.NO_DEFAULT.class)
                            ? loadCommand(groupAnno.defaultCommand())
                            : null,
                    groupCommands);
            //@formatter:on
            if (subGroupPath == null) {
                groups.add(group);
            } else {
                // Remember sub-groups for later
                subGroups.put(subGroupPath, group);
            }
        } else {
            for (CommandMetadata cmd : groupCommands) {
                group.addCommand(cmd);
            }
        }
    }
    // Build sub-group hierarchy
    buildGroupsHierarchy(groups, subGroups);

    // Find all commands
    List<CommandMetadata> allCommands = new ArrayList<CommandMetadata>();
    allCommands.addAll(defaultGroupCommands);
    if (defaultCommand != null && !defaultGroupCommands.contains(defaultCommand)) {
        allCommands.add(defaultCommand);
    }
    for (CommandGroupMetadata group : groups) {
        allCommands.addAll(group.getCommands());
        if (group.getDefaultCommand() != null) {
            allCommands.add(group.getDefaultCommand());
        }

        Queue<CommandGroupMetadata> subGroupsQueue = new LinkedList<CommandGroupMetadata>();
        subGroupsQueue.addAll(group.getSubGroups());
        while (subGroupsQueue.size() > 0) {
            CommandGroupMetadata subGroup = subGroupsQueue.poll();
            allCommands.addAll(subGroup.getCommands());
            if (subGroup.getDefaultCommand() != null)
                allCommands.add(subGroup.getDefaultCommand());
            subGroupsQueue.addAll(subGroup.getSubGroups());
        }
    }

    // Post-process to find possible further group assignments
    loadCommandsIntoGroupsByAnnotation(allCommands, groups, defaultGroupCommands);

    return loadGlobal(cliConfig.name(), cliConfig.description(), defaultCommand, defaultGroupCommands, groups,
            restrictions, parserConfig);
}

From source file:gemlite.core.internal.context.registryClass.ViewItemRegistry.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from   ww  w.ja  v a2 s .  c  o m
protected void doRegistry(IModuleContext context, RegistryParam param) throws Exception {
    String className = param.getClassName();
    Class<ViewTool> cls = (Class<ViewTool>) context.getLoader().loadClass(className);
    View f = cls.getAnnotation(View.class);
    ViewItem item = new ViewItem();
    //item.setName(f.name());
    String viewName = f.name();
    if (StringUtils.isEmpty(viewName))
        viewName = cls.getSimpleName();

    item.setName(viewName);
    item.setViewType(f.viewType());
    item.setViewToolByCls(cls);
    item.setTriggerType(f.triggerType());
    item.setDelayTime(f.delayTime());
    item.setRegionName(f.regionName());
    item.setIndexName(f.indexName());
    item.setTriggerOn(f.triggerOn());
    GemliteViewContext.getInstance().createViewItem(item);
}

From source file:springfox.documentation.spring.web.plugins.JacksonSerializerConvention.java

private Optional<Type> findAlternate(Class<?> type) {
    Class serializer = Optional.fromNullable(type.getAnnotation(JsonSerialize.class))
            .transform(new Function<JsonSerialize, Class>() {
                @Override//from  ww  w .  ja  va2  s.  c  o m
                public Class apply(JsonSerialize input) {
                    return input.as();
                }
            }).or(Void.class);
    Class deserializer = Optional.fromNullable(type.getAnnotation(JsonDeserialize.class))
            .transform(new Function<JsonDeserialize, Class>() {
                @Override
                public Class apply(JsonDeserialize input) {
                    return input.as();
                }
            }).or(Void.class);
    Type toUse;
    if (serializer != deserializer) {
        LOGGER.warn("The serializer {} and deserializer {} . Picking the serializer by default",
                serializer.getName(), deserializer.getName());
    }
    if (serializer == Void.class && deserializer == Void.class) {
        toUse = null;
    } else if (serializer != Void.class) {
        toUse = serializer;
    } else {
        toUse = deserializer;
    }
    return Optional.fromNullable(toUse);
}

From source file:com.ben12.openhab.model.util.BeanCopy.java

private boolean isCopyable(final Object value) {
    boolean copyable = false;
    if (value != null) {
        final Class<?> type = value.getClass();
        final XmlRootElement xmlElement = type.getAnnotation(XmlRootElement.class);
        copyable = Objects.nonNull(xmlElement);
    }//from   www.  j ava  2  s .c o m
    return copyable;
}

From source file:com.flipkart.foxtrot.server.util.ManagedActionScanner.java

@Override
public void start() throws Exception {
    Reflections reflections = new Reflections("com.flipkart.foxtrot", new SubTypesScanner());
    Set<Class<? extends Action>> actions = reflections.getSubTypesOf(Action.class);
    if (actions.isEmpty()) {
        throw new Exception("No analytics actions found!!");
    }/*from w w w .  jav  a  2  s  .c  om*/
    List<NamedType> types = new Vector<NamedType>();
    for (Class<? extends Action> action : actions) {
        AnalyticsProvider analyticsProvider = action.getAnnotation(AnalyticsProvider.class);
        if (null == analyticsProvider.request() || null == analyticsProvider.opcode()
                || analyticsProvider.opcode().isEmpty() || null == analyticsProvider.response()) {
            throw new Exception("Invalid annotation on " + action.getCanonicalName());
        }
        if (analyticsProvider.opcode().equalsIgnoreCase("default")) {
            logger.warn("Action " + action.getCanonicalName() + " does not specify cache token. "
                    + "Using default cache.");
        }
        analyticsLoader.register(new ActionMetadata(analyticsProvider.request(), action,
                analyticsProvider.cacheable(), analyticsProvider.opcode()));
        types.add(new NamedType(analyticsProvider.request(), analyticsProvider.opcode()));
        types.add(new NamedType(analyticsProvider.response(), analyticsProvider.opcode()));
        logger.info("Registered action: " + action.getCanonicalName());
    }
    SubtypeResolver subtypeResolver = environment.getObjectMapperFactory().getSubtypeResolver();
    subtypeResolver.registerSubtypes(types.toArray(new NamedType[types.size()]));
}

From source file:stormy.pythian.core.description.PythianStateDescriptionFactory.java

public PythianStateDescription createDescription(Class<? extends PythianState> clazz) {
    checkArgument(clazz != null, "PythianState class is mandatory");

    Documentation documentation = clazz.getAnnotation(Documentation.class);
    checkArgument(documentation != null,
            "No documentation found for " + clazz + " but documentation is mandatory!");

    PythianStateDescription description = new PythianStateDescription(clazz, documentation.name(),
            documentation.description());
    description.addProperties(propertyDescriptionFactory.createPropertyDescriptions(clazz));

    return description;
}