List of usage examples for java.lang.reflect AnnotatedElement getAnnotation
<T extends Annotation> T getAnnotation(Class<T> annotationClass);
From source file:org.glassfish.common.util.admin.MapInjectionResolver.java
/** * Convert the List<String> parameter to the specified type. * * @param target the target field//from w ww. j av a 2 s .c o m * @param type the type of class to convert * @param paramValList the List of String values to convert * @return Object */ // package-private, for testing public static Object convertListToObject(AnnotatedElement target, Class type, List<String> paramValList) { Param param = target.getAnnotation(Param.class); // does this parameter type allow multiple values? if (!param.multiple()) { if (paramValList.size() == 1) return convertStringToObject(target, type, paramValList.get(0)); throw new UnacceptableValueException(localStrings.getLocalString("TooManyValues", "Invalid parameter: {0}. This parameter may not have " + "more than one value.", CommandModel.getParamName(param, target))); } Object paramValue = paramValList; if (type.isAssignableFrom(List.class)) { // the default case, nothing to do } else if (type.isAssignableFrom(String[].class)) { paramValue = paramValList.toArray(new String[paramValList.size()]); } else if (type.isAssignableFrom(File[].class)) { paramValue = convertListToFiles(paramValList); } else if (type.isAssignableFrom(Properties.class)) { paramValue = convertListToProperties(paramValList); } // XXX - could handle arrays of other types return paramValue; }
From source file:org.glassfish.common.util.admin.MapInjectionResolver.java
/** * Check if the value string is one of the strings in the list of * acceptable values in the @Param annotation on the target. * * @param target the target field//from www.ja v a 2 s. c om * @param paramValueStr the parameter value */ private static void checkAgainstAcceptableValues(AnnotatedElement target, String paramValueStr) { Param param = target.getAnnotation(Param.class); String acceptable = param.acceptableValues(); String paramName = CommandModel.getParamName(param, target); if (ok(acceptable) && ok(paramValueStr)) { String[] ss = acceptable.split(","); for (String s : ss) { if (paramValueStr.equals(s.trim())) return; // matched, value is good } // didn't match any, error throw new UnacceptableValueException(localStrings.getLocalString("UnacceptableValue", "Invalid parameter: {0}. Its value is {1} " + "but it isn''t one of these acceptable values: {2}", paramName, paramValueStr, acceptable)); } }
From source file:org.gradle.api.internal.project.AnnotationProcessingTaskFactory.java
private void attachValidationAction(PropertyAnnotationHandler handler, PropertyInfo propertyInfo) { final Method method = propertyInfo.method; Class<? extends Annotation> annotationType = handler.getAnnotationType(); if (!isGetter(method)) { if (method.getAnnotation(annotationType) != null) { throw new GradleException(String.format("Cannot attach @%s to non-getter method %s().", annotationType.getSimpleName(), method.getName())); }//from ww w .j a va2s . c om return; } AnnotatedElement annotationTarget = null; if (method.getAnnotation(annotationType) != null) { annotationTarget = method; } else { try { Field field = method.getDeclaringClass().getDeclaredField(propertyInfo.propertyName); if (field.getAnnotation(annotationType) != null) { annotationTarget = field; } } catch (NoSuchFieldException e) { // ok - ignore } } if (annotationTarget == null) { return; } Annotation optional = annotationTarget.getAnnotation(Optional.class); if (optional == null) { propertyInfo.setNotNullValidator(notNullValidator); } propertyInfo.setActions(handler.getActions(annotationTarget, propertyInfo.propertyName)); }
From source file:org.guzz.builder.JPA2AnnotationsBuilder.java
protected static void addIdMapping(GuzzContextImpl gf, POJOBasedObjectMapping map, SimpleTable st, DBGroup dbGroup, String name, Class domainClas, AnnotatedElement element) { javax.persistence.Column pc = (javax.persistence.Column) element .getAnnotation(javax.persistence.Column.class); org.guzz.annotations.Column gc = (org.guzz.annotations.Column) element .getAnnotation(org.guzz.annotations.Column.class); String type = gc == null ? null : gc.type(); String column = pc == null ? null : pc.name(); if (StringUtil.isEmpty(column)) { column = name;//w ww . j a v a2 s .co m } TableColumn col = st.getColumnByPropName(name); boolean newId = false; if (col == null) { newId = true; col = new TableColumn(st); } else { log.info("override @Id in the parent class of [" + st.getBusinessName() + "]."); } col.setColName(column); col.setPropName(name); col.setType(type); col.setAllowInsert(true); col.setAllowUpdate(true); col.setLazy(false); map.initColumnMapping(col, null); if (newId) { st.addPKColumn(col); } //@Id generator javax.persistence.GeneratedValue pgv = (javax.persistence.GeneratedValue) element .getAnnotation(javax.persistence.GeneratedValue.class); if (pgv == null) { pgv = (javax.persistence.GeneratedValue) domainClas .getAnnotation(javax.persistence.GeneratedValue.class); } //If @GeneratedValue is not defined, use auto. GenerationType gt = GenerationType.AUTO; String generatorName = null; if (pgv != null) { gt = pgv.strategy(); generatorName = pgv.generator(); } Properties idProperties = new Properties(); String igCls; if (gt == GenerationType.AUTO) { //??guzz@GenericGenerator if (StringUtil.notEmpty(generatorName)) { GenericGenerator ggg = (GenericGenerator) element.getAnnotation(GenericGenerator.class); if (ggg != null && !generatorName.equals(ggg.name())) { ggg = null; } if (ggg == null) { //retreive @Id from GlobalContext Object g = gf.getGlobalIdGenerator(generatorName); //should be GenericGenerator if (!(g instanceof GenericGenerator)) { throw new IllegalParameterException("The Id Generator [" + generatorName + "] should be of type @org.guzz.annotations.GenericGenerator. domain class:" + domainClas.getName()); } ggg = (GenericGenerator) g; } igCls = ggg.strategy(); Parameter[] ps = ggg.parameters(); for (Parameter p : ps) { idProperties.setProperty(p.name(), p.value()); } } else { //nativegeneratordialect? igCls = "native"; } } else if (gt == GenerationType.IDENTITY) { igCls = "identity"; } else if (gt == GenerationType.SEQUENCE) { igCls = "sequence"; javax.persistence.SequenceGenerator psg = (javax.persistence.SequenceGenerator) element .getAnnotation(javax.persistence.SequenceGenerator.class); if (psg == null) { Object sg = gf.getGlobalIdGenerator(generatorName); Assert.assertNotNull(sg, "@javax.persistence.SequenceGenerator not found for sequenced @Id. domain class:" + domainClas.getName()); if (sg instanceof SequenceGenerator) { psg = (SequenceGenerator) sg; } else { throw new IllegalParameterException("The Id Generator [" + generatorName + "] should be of type @javax.persistence.SequenceGenerator. domain class:" + domainClas.getName()); } } idProperties.setProperty(SequenceIdGenerator.PARAM_SEQUENCE, psg.sequenceName()); idProperties.setProperty("catalog", psg.catalog()); idProperties.setProperty("allocationSize", String.valueOf(psg.allocationSize())); idProperties.setProperty("initialValue", String.valueOf(psg.initialValue())); //we need db_group param, but the JPA won't give us. } else if (gt == GenerationType.TABLE) { igCls = "hilo.multi"; TableGenerator pst = (TableGenerator) element.getAnnotation(TableGenerator.class); if (pst == null) { Object sg = gf.getGlobalIdGenerator(generatorName); Assert.assertNotNull(sg, "@javax.persistence.TableGenerator not found for hilo.multi @Id. domain class:" + domainClas.getName()); if (sg instanceof TableGenerator) { pst = (TableGenerator) sg; } else { throw new IllegalParameterException("The Id Generator [" + generatorName + "] should be of type @javax.persistence.TableGenerator. domain class:" + domainClas.getName()); } } idProperties.setProperty("catalog", pst.catalog()); idProperties.setProperty("schema", pst.schema()); idProperties.setProperty(TableMultiIdGenerator.TABLE, pst.table()); idProperties.setProperty(TableMultiIdGenerator.PK_COLUMN_NAME, pst.pkColumnName()); idProperties.setProperty(TableMultiIdGenerator.PK_COLUMN_VALUE, pst.pkColumnValue()); idProperties.setProperty(TableMultiIdGenerator.COLUMN, pst.valueColumnName()); idProperties.setProperty(TableMultiIdGenerator.MAX_LO, String.valueOf(pst.allocationSize())); //we need db_group param, but the JPA won't give us. idProperties.setProperty("initialValue", String.valueOf(pst.initialValue())); } else { throw new GuzzException("unknown @javax.persistence.GenerationType:" + gt); } if ("native".equals(igCls)) { igCls = dbGroup.getDialect().getNativeIDGenerator(); } String realClassName = (String) IdentifierGeneratorFactory.getGeneratorClass(igCls); Assert.assertNotNull(realClassName, "unknown Id generator:" + igCls); IdentifierGenerator ig = (IdentifierGenerator) BeanCreator.newBeanInstance(realClassName); if (ig instanceof Configurable) { ((Configurable) ig).configure(dbGroup.getDialect(), map, idProperties); } //register callback for GuzzContext's full starting. if (ig instanceof GuzzContextAware) { gf.registerContextStartedAware((GuzzContextAware) ig); } st.setIdentifierGenerator(ig); }
From source file:org.guzz.builder.JPA2AnnotationsBuilder.java
protected static void addPropertyMapping(GuzzContextImpl gf, POJOBasedObjectMapping map, SimpleTable st, String name, AnnotatedElement element, Class dataType) { javax.persistence.Column pc = element.getAnnotation(javax.persistence.Column.class); javax.persistence.Basic pb = element.getAnnotation(javax.persistence.Basic.class); javax.persistence.Enumerated pe = element.getAnnotation(javax.persistence.Enumerated.class); org.guzz.annotations.Column gc = element.getAnnotation(org.guzz.annotations.Column.class); String type = gc == null ? null : gc.type(); String nullValue = gc == null ? null : gc.nullValue(); String column = pc == null ? null : pc.name(); boolean lazy = pb == null ? false : pb.fetch() == FetchType.LAZY; Class loader = gc == null ? null : gc.loader(); if (dataType.isEnum()) { EnumType etype = EnumType.ORDINAL; if (pe != null) { etype = pe.value();/*w ww . j a v a 2s . com*/ } if (etype == EnumType.ORDINAL) { type = "enum.ordinal|" + dataType.getName(); } else { type = "enum.string|" + dataType.getName(); } } boolean insertIt = pc == null ? true : pc.insertable(); boolean updateIt = pc == null ? true : pc.updatable(); if (StringUtil.isEmpty(column)) { column = name; } TableColumn col = st.getColumnByPropName(name); if (col != null) { log.warn("field/property [" + name + "] already exsits in the parent class of [" + st.getBusinessName() + "]. Ignore it."); return; } if (loader == null || NullValue.class.isAssignableFrom(loader)) { loader = null; } try { col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, loader == null ? null : loader.getName()); col.setNullValue(nullValue); col.setAllowInsert(insertIt); col.setAllowUpdate(updateIt); col.setLazy(lazy); st.addColumn(col); } catch (DataTypeException dte) { //???JPA??Map, Set if (log.isDebugEnabled()) { log.debug("Unsupported data type is found in annotation, property is:[" + name + "], business is:[" + st.getBusinessName() + "]. Ignore this property.", dte); } else { log.warn("Ignore unsupported data type in annotation, property is:[" + name + "], business is:[" + st.getBusinessName() + "], msg is:" + dte.getMessage()); } } }
From source file:org.jdto.impl.AnnotationBeanInspector.java
/** * Try to read an annotation of a given type from an annotated element and populate a map. * @param <T>//from www.j a v a2 s. c o m * @param annotations * @param annotationType * @param element */ private <T extends Annotation> void populateAnnotation(HashMap<Class, Annotation> annotations, Class<T> annotationType, AnnotatedElement element) { T annotationInstance = element.getAnnotation(annotationType); if (annotationInstance != null) { annotations.put(annotationType, annotationInstance); } }
From source file:org.jspare.forvertx.web.collector.HandlerCollector.java
@SuppressWarnings("unchecked") private static List<Annotation> getHttpMethodsPresents(AnnotatedElement element) { List<Class<?>> filteredClazz = new ArrayList<>(); filteredClazz.addAll(Arrays.asList(HttpMethodType.values()).stream().map(ht -> ht.getHttpMethodClass()) .collect(Collectors.toList())); filteredClazz.removeIf(clazzHttpMethodType -> !element .isAnnotationPresent((Class<? extends Annotation>) clazzHttpMethodType)); return filteredClazz.stream() .map(httpMethodClazz -> element.getAnnotation((Class<? extends Annotation>) httpMethodClazz)) .collect(Collectors.toList()); }
From source file:org.nuxeo.common.xmap.XMap.java
protected static XObject checkObjectAnnotation(AnnotatedElement ae) { return ae.getAnnotation(XObject.class); }
From source file:org.openengsb.connector.serviceacl.internal.ServiceAclServiceImpl.java
private SecurityAttribute[] findAllSecurityAttributeAnnotations(AnnotatedElement serviceClass) { SecurityAttribute annotation = serviceClass.getAnnotation(SecurityAttribute.class); if (annotation != null) { return new SecurityAttribute[] { annotation }; }//from w ww . ja v a2 s. c o m SecurityAttributes annotations = serviceClass.getAnnotation(SecurityAttributes.class); if (annotations == null) { return new SecurityAttribute[0]; } return annotations.value(); }
From source file:org.sonatype.gshell.util.cli2.CliProcessor.java
private void discoverDescriptor(final Object bean, final AnnotatedElement element) { assert bean != null; assert element != null; Option opt = element.getAnnotation(Option.class); Argument arg = element.getAnnotation(Argument.class); if (opt != null && arg != null) { throw new IllegalAnnotationError( String.format("Element can only implement @Option or @Argument, not both: %s", element)); }/*from w w w.j a va 2s .c o m*/ if (opt != null) { log.trace("Discovered @Option for: {}", element); OptionDescriptor desc = new OptionDescriptor(opt, SetterFactory.create(element, bean)); // If the type is boolean, and its marked as optional or requires args, complain to use Boolean instead if (desc.getSetter().getType() == boolean.class) { if (desc.isArgumentOptional() || desc.getArgs() != 0) { throw new IllegalAnnotationError(String .format("Using Boolean for advanced processing of boolean types, on: %s", element)); } } // Make sure we have unique names for (OptionDescriptor tmp : optionDescriptors) { if (desc.getName() != null && desc.getName().equals(tmp.getName())) { throw new IllegalAnnotationError( String.format("Duplicate @Option name: %s, on: %s", desc.getName(), element)); } if (desc.getLongName() != null && desc.getLongName().equals(tmp.getLongName())) { throw new IllegalAnnotationError( String.format("Duplicate @Option longName: %s, on: %s", desc.getLongName(), element)); } } optionDescriptors.add(desc); } else if (arg != null) { log.trace("Discovered @Argument for: {}", element); ArgumentDescriptor desc = new ArgumentDescriptor(arg, SetterFactory.create(element, bean)); int index = arg.index(); // Make sure the argument will fit in the list while (index >= argumentDescriptors.size()) { argumentDescriptors.add(null); } if (argumentDescriptors.get(index) != null) { throw new IllegalAnnotationError( String.format("Duplicate @Argument index: %s, on: %s", index, element)); } argumentDescriptors.set(index, desc); } }