List of usage examples for java.lang.reflect Method isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:com.aw.swing.mvp.binding.component.support.ValidatorBuilder.java
protected void buildValidatorFor(BindingComponent bindingComponent) { String attribute = bindingComponent.getFieldName(); logger.debug("Attribute <" + attribute + ">"); Method method = domainBuilder.getMethodFor(attribute); if (method == null) { return;/*from w ww. j av a 2 s . com*/ } boolean isDate = method.getReturnType().equals(java.util.Date.class); if (isDate) { if (bindingComponent instanceof BndIJTextField) { BndIJTextField bndIJTextField = (BndIJTextField) bindingComponent; if (bndIJTextField.getPropertyBinding().getFormatter() == null) { bndIJTextField.formatAsDate(); } } else if (bindingComponent instanceof BndIJLabelField) { ((BndIJLabelField) bindingComponent).registerAsDateFormatted(); } } PropertyValidator propertyValidator = buildPropertyValidator(method); if (method.isAnnotationPresent(Label.class)) { Label label = method.getAnnotation(Label.class); bindingComponent.setLabelToBeUsedOnError(label.value()); } if (method.isAnnotationPresent(FillFormat.class)) { FillFormat fillFormat = method.getAnnotation(FillFormat.class); Formatter fillerFormatter = new FillerFormat(fillFormat.character(), fillFormat.lenght()); ((BndIJTextField) bindingComponent).formatUsingCustomFormatter(fillerFormatter); ((BndIJTextField) bindingComponent).setLimitTextSize(fillFormat.lenght()); } if (method.isAnnotationPresent(NotChangeCase.class)) { if (bindingComponent instanceof BndIJTextField) { ((BndIJTextField) bindingComponent).setAsNotChangeCase(); } } if (method.isAnnotationPresent(NumberFormat.class)) { NumberFormat numberFormat = method.getAnnotation(NumberFormat.class); if (bindingComponent instanceof BndFormattedComponent) { if (numberFormat.value().length() != 0) { ((BndIJTextField) bindingComponent) .formatUsingCustomFormatter(new NumberFormatter(numberFormat.value())); } else { ((BndIJTextField) bindingComponent).formatAsNumber(); } } } if (method.isAnnotationPresent(MoneyFormat.class)) { MoneyFormat numberFormat = method.getAnnotation(MoneyFormat.class); if (bindingComponent instanceof BndFormattedComponent) { if (numberFormat.value().length() != 0) { ((BndIJTextField) bindingComponent) .formatUsingCustomFormatter(new NumberFormatter(numberFormat.value())); } else { ((BndIJTextField) bindingComponent).formatAsMoney(); } propertyValidator.setMoneyFormat(true); } } if (method.isAnnotationPresent(PercentFormat.class)) { if (bindingComponent instanceof BndFormattedComponent) { ((BndIJTextField) bindingComponent).formatAsPercentage(); } } propertyValidator.setDateFormat(isDate); if (propertyValidator == null || propertyValidator.equals(Validator.EMPTY_VALIDATOR)) return; presenter.getValidatorMgr().registerBasicRule((BndIJTextField) bindingComponent, propertyValidator); }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
private static int getColumnType(Class<?> javaType, Method method, ColumnMetadata foreignReference) { final int dimensions = ReflectionUtils.getArrayDimensions(javaType); javaType = ReflectionUtils.mapType(ReflectionUtils.getComponentType(javaType)); if (dimensions > 1) { throw new UnsupportedColumnTypeError("Arrays of dimension > 1 are not supported"); }//w w w . ja va2s . c o m if (Byte.class.equals(javaType) && dimensions == 0) { return Types.TINYINT; } else if (Short.class.equals(javaType)) { return Types.SMALLINT; } else if (Integer.class.equals(javaType)) { return Types.INTEGER; } else if (Long.class.equals(javaType)) { return Types.BIGINT; } else if (Float.class.equals(javaType)) { return Types.FLOAT; } else if (Double.class.equals(javaType)) { return Types.DOUBLE; } else if (BigDecimal.class.equals(javaType)) { return Types.DECIMAL; } else if (BigInteger.class.equals(javaType)) { return Types.NUMERIC; } else if (Character.class.equals(javaType)) { return Types.CHAR; } else if (String.class.equals(javaType) || Class.class.equals(javaType)) { if (method != null && method.isAnnotationPresent(Column.class) && method.getAnnotation(Column.class).length() > 0) { return Types.VARCHAR; } else { return Types.LONGVARCHAR; } } else if (Date.class.isAssignableFrom(javaType)) { if (javaType.equals(java.sql.Date.class)) { return Types.DATE; } else if (javaType.equals(Time.class)) { return Types.TIME; } else if (javaType.equals(java.sql.Timestamp.class)) { return Types.TIMESTAMP; } final TemporalType temporalType = method != null && method.isAnnotationPresent(Temporal.class) ? method.getAnnotation(Temporal.class).value() : null; return (temporalType == null || temporalType.equals(TemporalType.TIMESTAMP)) ? Types.TIMESTAMP : (temporalType.equals(TemporalType.DATE) ? Types.DATE : Types.TIME); } else if (Byte.class.equals(javaType) && dimensions > 0) { return Types.VARBINARY; } else if (Enum.class.isAssignableFrom(javaType)) { return Types.VARCHAR; } else if (Boolean.class.equals(javaType)) { return Types.BOOLEAN; } else if (Collection.class.isAssignableFrom(javaType) && method.isAnnotationPresent(BasicCollection.class)) { return Types.LONGVARCHAR; } if (foreignReference != null) { return Integer.MIN_VALUE; } return Types.LONGVARCHAR; }
From source file:com.phoenixnap.oss.ramlapisync.parser.SpringMvcResourceParser.java
/** * Checks for instances of @Description annotations in * @param method The method to Inspect/*from w w w.j a v a 2s.c o m*/ * @return a Map of Description and Partial URL Keys */ protected Map<String, String> getPathDescriptionsForMethod(Method method) { Map<String, String> outDescriptions = new HashMap<>(); Description description = getAnnotation(method.getDeclaringClass(), Description.class, true); if (description != null) { for (PathDescription descriptions : description.pathDescriptions()) { outDescriptions.put(NamingHelper.cleanLeadingAndTrailingNewLineAndChars(descriptions.key()), descriptions.value()); } } if (method.isAnnotationPresent(Description.class)) { Description methodDescription = method.getAnnotation(Description.class); for (PathDescription descriptions : methodDescription.pathDescriptions()) { outDescriptions.put(NamingHelper.cleanLeadingAndTrailingNewLineAndChars(descriptions.key()), descriptions.value()); } } return outDescriptions; }
From source file:org.kuali.rice.krad.data.provider.annotation.impl.AnnotationMetadataProviderImpl.java
/** * Handle annotations made at the method level and add their data to the given metadata object. */* w w w . java 2s. c o m*/ * @param clazz the class to process. * @param metadata the metadata for the class. * * @return <b>true</b> if any annotations are found. */ protected boolean processMethodLevelAnnotations(Class<?> clazz, DataObjectMetadataImpl metadata) { boolean fieldAnnotationsFound = false; if (LOG.isDebugEnabled()) { LOG.debug("Processing Method Annotations on " + clazz); } List<DataObjectAttribute> attributes = new ArrayList<DataObjectAttribute>(metadata.getAttributes()); for (Method m : clazz.getDeclaredMethods()) { // we only care about properties which are designated as non-persistent // we don't want to load metadata about everything just because it's there // (E.g., we don't know how expensive all method calls are) if (!m.isAnnotationPresent(NonPersistentProperty.class)) { if (LOG.isTraceEnabled()) { LOG.trace("Rejecting method " + m.getName() + " because does not have NonPersistentProperty annotation"); } continue; } // we only care about getters if (!m.getName().startsWith("get") && !m.getName().startsWith("is")) { if (LOG.isDebugEnabled()) { LOG.debug("Rejecting method " + m.getName() + " because name does not match getter pattern"); } continue; } // we also need it to return a value and have no arguments to be a proper getter if (m.getReturnType() == null || m.getParameterTypes().length > 0) { if (LOG.isDebugEnabled()) { LOG.debug("Rejecting method " + m.getName() + " because has no return type or has arguments"); } continue; } String propertyName = getPropertyNameFromGetterMethod(m); boolean fieldAnnotationFound = false; boolean existingAttribute = true; DataObjectAttributeImpl attr = (DataObjectAttributeImpl) metadata.getAttribute(propertyName); if (attr == null) { existingAttribute = false; attr = new DataObjectAttributeImpl(); attr.setName(propertyName); attr.setType(m.getReturnType()); DataType dataType = DataType.getDataTypeFromClass(m.getReturnType()); if (dataType == null) { dataType = DataType.STRING; } attr.setDataType(dataType); attr.setOwningType(metadata.getType()); } Annotation[] methodAnnotations = m.getDeclaredAnnotations(); if (LOG.isDebugEnabled()) { LOG.debug(m.getDeclaringClass() + "." + m.getName() + " Method-level annotations: " + Arrays.asList(methodAnnotations)); } for (Annotation a : methodAnnotations) { fieldAnnotationFound |= processAnnotationForAttribute(a, attr, metadata); } if (fieldAnnotationFound) { if (!existingAttribute) { attributes.add(attr); } fieldAnnotationsFound = true; } } if (fieldAnnotationsFound) { metadata.setAttributes(attributes); } return fieldAnnotationsFound; }
From source file:com.taobao.itest.listener.TransactionalListener.java
/** * If the test method of the supplied {@link TestContext test context} is * configured to run within a transaction, this method will run * {@link BeforeTransaction @BeforeTransaction methods} and start a new * transaction./*from ww w . ja va 2 s. c o m*/ * <p> * Note that if a {@link BeforeTransaction @BeforeTransaction method} fails, * remaining {@link BeforeTransaction @BeforeTransaction methods} will not * be invoked, and a transaction will not be started. * * @see org.springframework.transaction.annotation.Transactional * @see org.springframework.test.annotation.NotTransactional */ @SuppressWarnings("serial") @Override public void beforeTestMethod(TestContext testContext) throws Exception { final Method testMethod = testContext.getTestMethod(); Assert.notNull(testMethod, "The test method of the supplied TestContext must not be null"); if (this.transactionContextCache.remove(testMethod) != null) { throw new IllegalStateException("Cannot start new transaction without ending existing transaction: " + "Invoke endTransaction() before startNewTransaction()."); } if (testMethod.isAnnotationPresent(NotTransactional.class)) { return; } TransactionAttribute transactionAttribute = this.attributeSource.getTransactionAttribute(testMethod, testContext.getTestClass()); TransactionDefinition transactionDefinition = null; if (transactionAttribute != null) { transactionDefinition = new DelegatingTransactionAttribute(transactionAttribute) { public String getName() { return testMethod.getName(); } }; } if (transactionDefinition != null) { if (logger.isDebugEnabled()) { logger.debug("Explicit transaction definition [" + transactionDefinition + "] found for test context [" + testContext + "]"); } TransactionContext txContext = new TransactionContext(getTransactionManager(testContext), transactionDefinition); runBeforeTransactionMethods(testContext); startNewTransaction(testContext, txContext); this.transactionContextCache.put(testMethod, txContext); } }
From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java
private void performMethodInjection(final Object instance, final Class authorizerClass) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (final Method method : authorizerClass.getMethods()) { if (method.isAnnotationPresent(AuthorizerContext.class)) { // make the method accessible final boolean isAccessible = method.isAccessible(); method.setAccessible(true);// w ww. ja v a 2s .com try { final Class<?>[] argumentTypes = method.getParameterTypes(); // look for setters (single argument) if (argumentTypes.length == 1) { final Class<?> argumentType = argumentTypes[0]; // look for well known types if (NiFiRegistryProperties.class.isAssignableFrom(argumentType)) { // nifi properties injection method.invoke(instance, properties); } } } finally { method.setAccessible(isAccessible); } } } final Class parentClass = authorizerClass.getSuperclass(); if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) { performMethodInjection(instance, parentClass); } }
From source file:com.px100systems.util.serialization.SerializationDefinition.java
private SerializationDefinition(Class<?> cls) { definitions.put(cls, this); if (cls.getName().startsWith("java")) throw new RuntimeException("System classes are not supported: " + cls.getSimpleName()); try {//from w w w .ja v a2 s.c o m constructor = cls.getConstructor(); } catch (NoSuchMethodException e) { throw new RuntimeException("Missing no-arg constructor: " + cls.getSimpleName()); } serializingSetter = ReflectionUtils.findMethod(cls, "setSerializing", boolean.class); for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) { for (Field field : c.getDeclaredFields()) { if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; FieldDefinition fd = new FieldDefinition(); fd.name = field.getName(); fd.type = field.getType(); if (fd.type.isPrimitive()) throw new RuntimeException("Primitives are not supported: " + fd.type.getSimpleName()); Calculated calc = field.getAnnotation(Calculated.class); if (!fd.type.equals(Integer.class) && !fd.type.equals(Long.class) && !fd.type.equals(Double.class) && !fd.type.equals(Boolean.class) && !fd.type.equals(Date.class) && !fd.type.equals(String.class)) if (fd.type.equals(List.class) || fd.type.equals(Set.class)) { SerializedCollection sc = field.getAnnotation(SerializedCollection.class); if (sc == null) throw new RuntimeException( cls.getSimpleName() + "." + fd.name + " is missing @SerializedCollection"); if (calc != null) throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " cannot have a calculator because it is a collection"); fd.collectionType = sc.type(); fd.primitive = fd.collectionType.equals(Integer.class) || fd.collectionType.equals(Long.class) || fd.collectionType.equals(Double.class) || fd.collectionType.equals(Boolean.class) || fd.collectionType.equals(Date.class) || fd.collectionType.equals(String.class); if (!fd.primitive) { if (cls.getName().startsWith("java")) throw new RuntimeException(cls.getSimpleName() + "." + fd.name + ": system collection types are not supported: " + fd.collectionType.getSimpleName()); if (!definitions.containsKey(fd.collectionType)) new SerializationDefinition(fd.collectionType); } } else { if (cls.getName().startsWith("java")) throw new RuntimeException( "System classes are not supported: " + fd.type.getSimpleName()); if (!definitions.containsKey(fd.type)) new SerializationDefinition(fd.type); } else fd.primitive = true; try { fd.accessor = c.getMethod(PropertyAccessor.methodName("get", fd.name)); } catch (NoSuchMethodException e) { throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing getter"); } try { fd.mutator = c.getMethod(PropertyAccessor.methodName("set", fd.name), fd.type); } catch (NoSuchMethodException e) { throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing setter"); } if (calc != null) fd.calculator = new SpelExpressionParser().parseExpression(calc.value()); fields.add(fd); } for (Method method : c.getDeclaredMethods()) if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && method.getName().startsWith("get") && method.isAnnotationPresent(SerializedGetter.class)) { FieldDefinition fd = new FieldDefinition(); fd.name = method.getName().substring(3); fd.name = fd.name.substring(0, 1).toLowerCase() + fd.name.substring(1); fd.type = method.getReturnType(); fd.primitive = fd.type != null && (fd.type.equals(Integer.class) || fd.type.equals(Long.class) || fd.type.equals(Double.class) || fd.type.equals(Boolean.class) || fd.type.equals(Date.class) || fd.type.equals(String.class)); if (!fd.primitive) throw new RuntimeException("Not compact-serializable getter type: " + (fd.type == null ? "void" : fd.type.getSimpleName())); fd.accessor = method; gettersOnly.add(fd); } } }
From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java
private void analyzeService(Method[] methods, RegistryNodeModel model, Wsdl wsdl) { Map<String, EntityModel> models = new HashMap<String, EntityModel>(); List<RelationshipModel> relationships = new ArrayList<RelationshipModel>(); List<ActionModel> actions = new ArrayList<ActionModel>(methods.length); for (Method method : methods) { if (method.isAnnotationPresent(WebMethod.class)) { Service service = new Service(method.getName()); RequestWrapper requestWrapper = method.getAnnotation(RequestWrapper.class); ResponseWrapper responseWrapper = method.getAnnotation(ResponseWrapper.class); String messageName = StringUtils.capitalize(method.getName()); String request = requestWrapper != null ? requestWrapper.localName() : messageName; String response = responseWrapper != null ? responseWrapper.localName() : messageName + "Response"; EntityModel input = createWrapperEntity(request, method, model, true, relationships, models, service);/* ww w . j av a2 s . co m*/ EntityModel output = createWrapperEntity(response, method, model, false, relationships, models, service); ActionModel action = createAction(method.getName(), output, input); actions.add(action); wsdl.addService(service); } } this.packageModel.set(packageStore.findPackage(model.getLookup())); for (EntityModel entity : models.values()) { save(entity); savePackageChanges(entity); } for (RelationshipModel relationship : relationships) { relationshipStore.save(relationship); progress.status("Processing relationship '" + relationship.getName() + "'...", 2, LogLevel.INFO); savePackageChanges(relationship); } for (ActionModel action : actions) { actionStore.save(action); progress.status("Processing Action '" + action.getName() + "'...", 2, LogLevel.INFO); savePackageChanges(action); } }
From source file:de.eidottermihi.rpicheck.activity.MainActivity.java
private void visitExportedMethods(Object object, String keyPrefix, Map<String, String> informationMap) { for (Method method : object.getClass().getMethods()) { if (method.isAnnotationPresent(Exported.class) && method.getParameterTypes().length == 0) { String key = method.getAnnotation(Exported.class).value(); if ("".equals(key)) { key = method.getName();//from www.j ava 2 s. c o m if (key.startsWith("get")) { key = key.substring(3).toLowerCase(); } } try { final Object value = method.invoke(object, new Object[] {}); if (value != null) { if (value instanceof Boolean || value instanceof String || value instanceof Double || value instanceof Long || value instanceof Integer) { informationMap.put(keyPrefix + key, value.toString()); } else if (value instanceof Collection) { Collection collection = (List) value; int counter = 0; for (Object val : collection) { visitExportedMethods(val, String.format("%s[%s].", key, counter++), informationMap); } } else { visitExportedMethods(value, key + ".", informationMap); } } } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } } }
From source file:org.evosuite.setup.TestClusterGenerator.java
public static boolean canUse(Method m, Class<?> ownerClass) { if (m.isBridge()) { logger.debug("Excluding bridge method: {}", m.toString()); return false; }/* w w w.j ava 2s .com*/ if (m.isSynthetic()) { logger.debug("Excluding synthetic method: {}", m.toString()); return false; } if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) { logger.debug("Excluding deprecated method {}", m.getName()); return false; } if (m.isAnnotationPresent(Test.class)) { logger.debug("Excluding test method {}", m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteExclude.class)) { logger.debug("Excluding method with exclusion annotation {}", m.getName()); return false; } if (m.getDeclaringClass().equals(java.lang.Object.class)) { return false; } if (!m.getReturnType().equals(String.class) && !canUse(m.getReturnType())) { return false; } if (m.getDeclaringClass().equals(Enum.class)) { return false; /* if (m.getName().equals("valueOf") || m.getName().equals("values") || m.getName().equals("ordinal")) { logger.debug("Excluding valueOf for Enum " + m.toString()); return false; } // Skip compareTo on enums (like Randoop) if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(Enum.class)) return false; */ } if (m.getDeclaringClass().equals(java.lang.Thread.class)) return false; // Hashcode only if we need to cover it if (m.getName().equals("hashCode") && !m.getDeclaringClass().equals(Properties.getTargetClass())) return false; // Randoop special case: just clumps together a bunch of hashCodes, so skip it if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class)) return false; // Randoop special case: differs too much between JDK installations if (m.getName().equals("getAvailableLocales")) return false; if (m.getName().equals(ClassResetter.STATIC_RESET)) { logger.debug("Ignoring static reset class"); return false; } if (isForbiddenNonDeterministicCall(m)) { return false; } if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) { logger.debug("Ignoring static main method "); return false; } /* if(m.getTypeParameters().length > 0) { logger.debug("Cannot handle generic methods at this point"); if(m.getDeclaringClass().equals(Properties.getTargetClass())) { LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet"); } return false; } */ // If default or if (Modifier.isPublic(m.getModifiers())) { makeAccessible(m); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(m.getModifiers())) { // && !Modifier.isProtected(m.getModifiers())) { String packageName = ClassUtils.getPackageName(ownerClass); String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) { makeAccessible(m); return true; } } return false; }