List of usage examples for java.lang.reflect Method isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java
private String getDeleteCommand(String tableName, String schema, HashMap<Method, String> fieldMapping, HashMap<Integer, Method> indexMapping) { String command = "delete from " + ((schema == null) ? "" : (schema + ".")) + tableName; String fields = ""; int paramIndex = 1; String pkField = null;/*from ww w.j a v a2 s .c om*/ Method pkFieldMethod = null; for (Method dbFieldMethod : fieldMapping.keySet()) { if (dbFieldMethod.isAnnotationPresent(Id.class)) { pkFieldMethod = dbFieldMethod; pkField = (String) fieldMapping.get(pkFieldMethod); } } if (pkFieldMethod == null) { throw new DataQueryException(String.format("Missing Entity Primary Key Field for %s", tableName)); } indexMapping.put(paramIndex, pkFieldMethod); command += " where " + pkField + " = ?"; return command; }
From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java
private String getUpdateCommand(String tableName, String schema, HashMap<Method, String> fieldMapping, HashMap<Integer, Method> indexMapping, List<String> includeFields) { String command = "update " + ((schema == null) ? "" : (schema + ".")) + tableName + " set "; String fields = ""; int paramIndex = 1; String pkField = null;//from w ww . j a v a 2 s. com Method pkFieldMethod = null; for (Method dbFieldMethod : fieldMapping.keySet()) { if (dbFieldMethod.isAnnotationPresent(Id.class)) { pkFieldMethod = dbFieldMethod; pkField = (String) fieldMapping.get(pkFieldMethod); } else { String field = (String) fieldMapping.get(dbFieldMethod); if (includeFields != null) { String incField = dbToFieldName(field); if (includeFields.contains(incField)) { fields += field + "=?,"; indexMapping.put(paramIndex, dbFieldMethod); paramIndex++; } } else { fields += field + "=?,"; indexMapping.put(paramIndex, dbFieldMethod); paramIndex++; } } } if (pkFieldMethod == null) { throw new DataQueryException(String.format("Missing Entity Primary Key Field for %s", tableName)); } indexMapping.put(paramIndex, pkFieldMethod); //@TODO if there is no pkfield..throw exception! fields = fields.substring(0, fields.length() - 1); command += fields + " where " + pkField + " = ?"; return command; }
From source file:org.mayocat.localization.internal.DefaultEntityLocalizationService.java
@Override public <T extends Localized> T localize(T entity, Locale locale) { if (locale == null || entity.getLocalizedVersions() == null || !entity.getLocalizedVersions().containsKey(locale)) { return entity; }//from w w w . j a v a2 s .c om T copiedEntity = SerializationUtils.clone(entity); if (copiedEntity == null) { return entity; } // Special I/O case for loaded attachment : set back the input stream manually if (copiedEntity instanceof LoadedAttachment) { ((LoadedAttachment) copiedEntity) .setData(new AttachmentData(((LoadedAttachment) entity).getData().getStream())); } // Handle entity fields : // - loops over methods, checking for setters, then for each one of them // - infer a field name from found setter // - check if that field has a "LocalizedField" annotation, if not ignore // - if it does, try to find this field in the locale's map of translations // - if found and not null or empty string use the setter to set this as the localized field value for (Method method : copiedEntity.getClass().getDeclaredMethods()) { if (method.getName().startsWith("set") && Character.isUpperCase(method.getName().charAt(3))) { // Found a setter. if (method.getName().length() <= 4) { continue; } String fieldName = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); Field field = null; try { field = copiedEntity.getClass().getDeclaredField(fieldName); } catch (NoSuchFieldException e) { this.logger.debug("Cannot find field for setter {}", method.getName()); } // Check if either field or method has a "LocalizedField" annotation if (field != null && (field.isAnnotationPresent(LocalizedField.class) || method.isAnnotationPresent(LocalizedField.class))) { Object value = null; if (copiedEntity.getLocalizedVersions().get(locale).containsKey(fieldName)) { value = copiedEntity.getLocalizedVersions().get(locale).get(fieldName); if (String.class.isAssignableFrom(value.getClass()) && Strings.isNullOrEmpty((String) value)) { // Ignore empty strings, consider them as nulls continue; } boolean setterAccessible = method.isAccessible(); method.setAccessible(true); try { method.invoke(copiedEntity, value); } catch (IllegalAccessException | InvocationTargetException e) { logger.error("Cannot set property {}", field.getName()); } method.setAccessible(setterAccessible); } } } } // Handle entity addons : // - check if entity has addons and those addons are loaded, and the localized version contains something // for addons // - if yes, then loop over all the entity addons, and for each : // - try to find the equivalent addon in the map of translation // - if found, and its value is not null or empty string, replace the addon value by the localized one if (hasLoadedAddons(copiedEntity) && copiedEntity.getLocalizedVersions().get(locale).containsKey("addons")) { Map<String, AddonGroup> entityAddons = ((HasAddons) copiedEntity).getAddons().get(); final Map<String, Object> localizedAddons = (Map<String, Object>) copiedEntity.getLocalizedVersions() .get(locale).get("addons"); for (AddonGroup addon : entityAddons.values()) { if (localizedAddons.containsKey(addon.getGroup())) { Map<String, Object> localizedGroup = (Map<String, Object>) localizedAddons .get(addon.getGroup()); if (Map.class.isAssignableFrom(addon.getValue().getClass())) { // Non-sequence addons Map<String, Object> value = (Map<String, Object>) addon.getValue(); Map<String, Object> localizedGroupValue = (Map<String, Object>) localizedGroup.get("value"); for (String field : value.keySet()) { Object localizedValue = localizedGroupValue.get(field); if (localizedValue == null || (String.class.isAssignableFrom(localizedValue.getClass()) && Strings.isNullOrEmpty((String) localizedValue))) { // Ignore empty strings, consider them as nulls continue; } ((Map<String, Object>) addon.getValue()).put(field, localizedValue); } } else if (List.class.isAssignableFrom(addon.getValue().getClass())) { // Sequence addons List<Map<String, Object>> values = (List<Map<String, Object>>) addon.getValue(); try { List<Map<String, Object>> localizedGroupValue = (List<Map<String, Object>>) localizedGroup .get("value"); Integer i = 0; for (Map<String, Object> value : values) { Map<String, Object> localizedGroupValueItem = localizedGroupValue.get(i); for (String field : value.keySet()) { Object localizedValue = localizedGroupValueItem.get(field); if (localizedValue == null || (String.class.isAssignableFrom(localizedValue.getClass()) && Strings.isNullOrEmpty((String) localizedValue))) { // Ignore empty strings, consider them as nulls continue; } ((List<Map<String, Object>>) addon.getValue()).get(i).put(field, localizedValue); } i++; } } catch (ClassCastException e) { // Ignore... } } } } } return copiedEntity; }
From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java
/** * Create new handler.// w w w. j a va 2 s.c om * * @param validatorFactory Validator factory. * @param beanClass User input bean class. * @param validationGroups Validation groups to apply during bean * validation, or empty array to use the default group. * * @throws UnavailableException If an error happens. */ UserInputControllerMethodArgHandler(final ValidatorFactory validatorFactory, final Class<?> beanClass, final Class<?>[] validationGroups) throws UnavailableException { this.validatorFactory = validatorFactory; this.beanClass = beanClass; this.validationGroups = validationGroups; try { final BeanInfo beanInfo = Introspector.getBeanInfo(this.beanClass); final PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors(); final List<FieldDesc> beanFields = new ArrayList<>(); for (final PropertyDescriptor propDesc : propDescs) { final String propName = propDesc.getName(); final Class<?> propType = propDesc.getPropertyType(); final Method propGetter = propDesc.getReadMethod(); final Method propSetter = propDesc.getWriteMethod(); if ((propGetter == null) || (propSetter == null)) continue; Field propField = null; for (Class<?> c = this.beanClass; !c.equals(Object.class); c = c.getSuperclass()) { try { propField = c.getDeclaredField(propName); break; } catch (final NoSuchFieldException e) { // nothing, continue the loop } } final boolean noTrim = (((propField != null) && propField.isAnnotationPresent(NoTrim.class)) || (propGetter.isAnnotationPresent(NoTrim.class))); Class<? extends Binder> binderClass = null; String format = null; String errorMessage = Bind.DEFAULT_MESSAGE; Bind bindAnno = null; if (propField != null) bindAnno = propField.getAnnotation(Bind.class); if (bindAnno == null) bindAnno = propGetter.getAnnotation(Bind.class); if (bindAnno != null) { binderClass = bindAnno.binder(); format = bindAnno.format(); errorMessage = bindAnno.message(); } if (binderClass == null) { if ((String.class).isAssignableFrom(propType)) binderClass = StringBinder.class; else if ((Boolean.class).isAssignableFrom(propType) || propType.equals(Boolean.TYPE)) binderClass = BooleanBinder.class; else if ((Integer.class).isAssignableFrom(propType) || propType.equals(Integer.TYPE)) binderClass = IntegerBinder.class; else if (propType.isEnum()) binderClass = EnumBinder.class; else // TODO: add more standard binders throw new UnavailableException( "Unsupported user input bean field type " + propType.getName() + "."); } beanFields.add(new FieldDesc(propDesc, noTrim, binderClass.newInstance(), format, errorMessage)); } this.beanFields = beanFields.toArray(new FieldDesc[beanFields.size()]); } catch (final IntrospectionException e) { this.log.error("error introspecting user input bean", e); throw new UnavailableException("Specified user input bean" + " class could not be introspected."); } catch (final IllegalAccessException | InstantiationException e) { this.log.error("error instatiating binder", e); throw new UnavailableException("Used user input bean field binder" + " could not be instantiated."); } this.beanPool = new FastPool<>(new PoolableObjectFactory<PoolableUserInput>() { @Override public PoolableUserInput makeNew(final FastPool<PoolableUserInput> pool, final int pooledObjectId) { try { return new PoolableUserInput(pool, pooledObjectId, beanClass.newInstance()); } catch (final InstantiationException | IllegalAccessException e) { throw new RuntimeException("Error instatiating user input bean.", e); } } }, "UserInputBeansPool_" + beanClass.getSimpleName()); }
From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java
private String getInsertCommand(String tableName, String schema, HashMap<Method, String> fieldMapping, HashMap<Integer, Method> indexMapping) { String command = "insert into " + ((schema == null) ? "" : (schema + ".")) + tableName; String fields = "("; String values = "("; int paramIndex = 1; for (Method dbFieldMethod : fieldMapping.keySet()) { String fieldName = fieldMapping.get(dbFieldMethod); if (dbFieldMethod.isAnnotationPresent(Id.class)) { if (dbFieldMethod.isAnnotationPresent(GeneratedValue.class)) { //generally do nothing here..simply omit pk field.. GeneratedValue gv = dbFieldMethod.getAnnotation(GeneratedValue.class); fields += fieldName + ","; if (gv.strategy() == GenerationType.AUTO) { values += ((schema == null) ? "" : (schema + ".")) + getSequenceSql("seq_" + tableName) + ","; } else { values += ((schema == null) ? "" : (schema + ".")) + getSequenceSql(gv.generator()) + ","; }/*from www. j av a 2 s. c o m*/ } else { fields += fieldName + ","; values += "?,"; indexMapping.put(paramIndex, dbFieldMethod); paramIndex++; } } else { fields += fieldName + ","; values += "?,"; indexMapping.put(paramIndex, dbFieldMethod); paramIndex++; } } fields = fields.substring(0, fields.length() - 1) + ")"; values = values.substring(0, values.length() - 1) + ")"; command += fields + " values " + values; return command; }
From source file:org.teavm.junit.TeaVMTestRunner.java
private void runChild(Method child, RunNotifier notifier) { notifier.fireTestStarted(describeChild(child)); boolean ran = false; boolean success = true; MethodHolder methodHolder = classHolder.getMethod(getDescriptor(child)); Set<Class<?>> expectedExceptions = new HashSet<>(); for (String exceptionName : testAdapter.getExpectedExceptions(methodHolder)) { try {//w w w. ja va2s. c o m expectedExceptions.add(Class.forName(exceptionName, false, classLoader)); } catch (ClassNotFoundException e) { notifier.fireTestFailure(new Failure(describeChild(child), e)); notifier.fireTestFinished(describeChild(child)); latch.countDown(); return; } } if (!child.isAnnotationPresent(SkipJVM.class) && !child.getDeclaringClass().isAnnotationPresent(SkipJVM.class)) { ran = true; success = runInJvm(child, notifier, expectedExceptions); } Description description = describeChild(child); if (success && outputDir != null) { List<TeaVMTestConfiguration> configurations = getConfigurations(); int[] configurationIndex = new int[] { 0 }; List<Consumer<Boolean>> onSuccess = new ArrayList<>(); List<TestRun> runs = new ArrayList<>(); onSuccess.add(runSuccess -> { if (runSuccess && configurationIndex[0] < runs.size()) { submitRun(runs.get(configurationIndex[0]++)); } else { notifier.fireTestFinished(description); latch.countDown(); } }); for (TeaVMTestConfiguration configuration : configurations) { try { TestRun run = compileByTeaVM(child, notifier, configuration, onSuccess.get(0)); if (run != null) { runs.add(run); } } catch (Throwable e) { notifier.fireTestFailure(new Failure(description, e)); notifier.fireTestFinished(description); latch.countDown(); return; } } onSuccess.get(0).accept(true); } else { if (!ran) { notifier.fireTestIgnored(description); } notifier.fireTestFinished(description); latch.countDown(); } }
From source file:de.cubeisland.engine.core.webapi.ApiServer.java
public void registerApiHandlers(final Module owner, final Object holder) { expectNotNull(holder, "The API holder must not be null!"); for (Method method : holder.getClass().getDeclaredMethods()) { Action aAction = method.getAnnotation(Action.class); if (aAction != null) { String route = aAction.value(); if (route.isEmpty()) { route = StringUtils.deCamelCase(method.getName(), "/"); }//from w w w. ja v a 2 s . c o m route = owner.getId() + "/" + route; route = HttpRequestHandler.normalizePath(route); de.cubeisland.engine.core.permission.Permission perm = null; if (aAction.needsAuth()) { perm = owner.getBasePermission().childWildcard("webapi"); if (method.isAnnotationPresent(ApiPermission.class)) { ApiPermission apiPerm = method.getAnnotation(ApiPermission.class); if (apiPerm.value().isEmpty()) { perm = perm.child(route, apiPerm.permDefault()); } else { perm = perm.child(apiPerm.value(), apiPerm.permDefault()); } } else { perm = perm.child(route, PermDefault.DEFAULT); } } LinkedHashMap<String, Class> params = new LinkedHashMap<>(); Class<?>[] types = method.getParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int i = 1; i < types.length; i++) { Class<?> type = types[i]; Value val = null; for (Annotation annotation : paramAnnotations[i]) { if (annotation instanceof Value) { val = (Value) annotation; break; } } if (val == null) { throw new IllegalArgumentException("Missing Value Annotation for Additional Parameters"); } if (params.put(val.value(), type) != null) { throw new IllegalArgumentException("Duplicate value in Value Annotation"); } } RequestMethod reqMethod = RequestMethod.GET; if (method.isAnnotationPresent(de.cubeisland.engine.core.webapi.Method.class)) { reqMethod = method.getAnnotation(de.cubeisland.engine.core.webapi.Method.class).value(); } this.handlers.put(route, new ReflectedApiHandler(owner, route, perm, params, reqMethod, method, holder)); } } }
From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java
private <T> List<T> commandToRecords(Class objClass, String command, HashMap<Method, String> fieldMapping, Object[] params) {/*from w ww .ja va 2 s. c o m*/ PreparedStatement st = null; ResultSet rs = null; try { ArrayList<T> records = new ArrayList(); st = conn.prepareStatement(command); setParams(st, params); rs = st.executeQuery(); while (rs.next()) { T newObj = (T) objClass.newInstance(); for (Method method : fieldMapping.keySet()) { try { Object val = convertType(rs.getObject((String) fieldMapping.get(method)), method); if (val != null) method.invoke(newObj, val); } catch (Exception ex) { if (!method.isAnnotationPresent(Optional.class)) { throw new NativeQueryException(command, method.getName(), ex); } } } records.add(newObj); } return records; } catch (Exception ex) { if (ex instanceof NativeQueryException) throw (NativeQueryException) ex; else throw new NativeQueryException(command, null, ex); } finally { closeOnFinally(rs, st); } }
From source file:io.coala.json.DynaBean.java
/** * @param referenceType//w ww . j a va 2s .c om * @param <S> * @param <T> * @return */ static final <S, T> JsonDeserializer<T> createJsonDeserializer(final ObjectMapper om, final Class<T> resultType, final Properties... imports) { return new JsonDeserializer<T>() { @Override public T deserializeWithType(final JsonParser jp, final DeserializationContext ctxt, final TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { return deserialize(jp, ctxt); } @Override public T deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; // if( Wrapper.class.isAssignableFrom( resultType ) ) // { // // FIXME // LOG.trace( "deser wrapper intf of {}", jp.getText() ); // return (T) Wrapper.Util.valueOf( jp.getText(), // resultType.asSubclass( Wrapper.class ) ); // } if (Config.class.isAssignableFrom(resultType)) { final Map<String, Object> entries = jp.readValueAs(new TypeReference<Map<String, Object>>() { }); final Iterator<Entry<String, Object>> it = entries.entrySet().iterator(); for (Entry<String, Object> next = null; it.hasNext(); next = it.next()) if (next != null && next.getValue() == null) { LOG.trace("Ignoring null value: {}", next); it.remove(); } return resultType.cast(ConfigFactory.create(resultType.asSubclass(Config.class), entries)); } // else if (Config.class.isAssignableFrom(resultType)) // throw new JsonGenerationException( // "Config does not extend "+Mutable.class.getName()+" required for deserialization: " // + Arrays.asList(resultType // .getInterfaces())); // can't parse directly to interface type final DynaBean bean = new DynaBean(); final TreeNode tree = jp.readValueAsTree(); // override attributes as defined in interface getters final Set<String> attributes = new HashSet<>(); for (Method method : resultType.getMethods()) { if (method.getReturnType().equals(Void.TYPE) || method.getParameterTypes().length != 0) continue; final String attribute = method.getName(); if (attribute.equals("toString") || attribute.equals("hashCode")) continue; attributes.add(attribute); final TreeNode value = tree.get(attribute);// bean.any().get(attributeName); if (value == null) continue; bean.set(method.getName(), om.treeToValue(value, JsonUtil.checkRegistered(om, method.getReturnType(), imports))); } if (tree.isObject()) { // keep superfluous properties as TreeNodes, just in case final Iterator<String> fieldNames = tree.fieldNames(); while (fieldNames.hasNext()) { final String fieldName = fieldNames.next(); if (!attributes.contains(fieldName)) bean.set(fieldName, tree.get(fieldName)); } } else if (tree.isValueNode()) { for (Class<?> type : resultType.getInterfaces()) for (Method method : type.getDeclaredMethods()) { // LOG.trace( "Scanning {}", method ); if (method.isAnnotationPresent(JsonProperty.class)) { final String property = method.getAnnotation(JsonProperty.class).value(); // LOG.trace( "Setting {}: {}", property, // ((ValueNode) tree).textValue() ); bean.set(property, ((ValueNode) tree).textValue()); } } } else throw ExceptionFactory.createUnchecked("Expected {} but parsed: {}", resultType, tree.getClass()); return DynaBean.proxyOf(om, resultType, bean, imports); } }; }
From source file:com.xeiam.xchange.rest.RestMethodMetadata.java
public RestMethodMetadata(Method method, Object[] args) { Consumes consumes = AnnotationUtils.getFromMethodOrClass(method, Consumes.class); this.contentType = consumes != null ? consumes.value()[0] : MediaType.APPLICATION_FORM_URLENCODED; paramsMap = new HashMap<Class<? extends Annotation>, Params>(); for (Class<? extends Annotation> annotationClass : PARAM_ANNOTATION_CLASSES) { Params params = Params.of();/* w w w . j av a 2s . c o m*/ params.setRestMethodMetadata(this); paramsMap.put(annotationClass, params); } Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int i = 0; i < paramAnnotations.length; i++) { Annotation[] paramAnns = paramAnnotations[i]; if (paramAnns.length == 0) { unannanotatedParams.add(args[i]); } for (Annotation paramAnn : paramAnns) { String paramName = getParamName(paramAnn); if (paramName != null) { this.paramsMap.get(paramAnn.annotationType()).add(paramName, args[i]); } } } // Support using method method name as a parameter. for (Class<? extends Annotation> paramAnnotationClass : PARAM_ANNOTATION_CLASSES) { if (method.isAnnotationPresent(paramAnnotationClass)) { Annotation paramAnn = method.getAnnotation(paramAnnotationClass); String paramName = getParamName(paramAnn); this.paramsMap.get(paramAnnotationClass).add(paramName, method.getName()); } } }