List of usage examples for java.lang.reflect Method getGenericParameterTypes
@Override
public Type[] getGenericParameterTypes()
From source file:com.centurylink.mdw.service.api.SwaggerAnnotationsReader.java
private void read(ReaderContext context) { final SwaggerDefinition swaggerDefinition = context.getCls().getAnnotation(SwaggerDefinition.class); if (swaggerDefinition != null) { readSwaggerConfig(swaggerDefinition); }/*from w ww . j a v a2s .c om*/ for (Method method : context.getCls().getMethods()) { if (ReflectionUtils.isOverriddenMethod(method, context.getCls())) { continue; } final Operation operation = new Operation(); String operationPath = null; String httpMethod = null; final Type[] genericParameterTypes = method.getGenericParameterTypes(); final Annotation[][] paramAnnotations = method.getParameterAnnotations(); // Avoid java.util.ServiceLoader mechanism which finds ServletReaderExtension // for (ReaderExtension extension : ReaderExtensions.getExtensions()) { for (ReaderExtension extension : getExtensions()) { if (operationPath == null) { operationPath = extension.getPath(context, method); } if (httpMethod == null) { httpMethod = extension.getHttpMethod(context, method); } if (operationPath == null || httpMethod == null) { continue; } if (extension.isReadable(context)) { extension.setDeprecated(operation, method); extension.applyConsumes(context, operation, method); extension.applyProduces(context, operation, method); extension.applyOperationId(operation, method); extension.applySummary(operation, method); extension.applyDescription(operation, method); extension.applySchemes(context, operation, method); extension.applySecurityRequirements(context, operation, method); extension.applyTags(context, operation, method); extension.applyResponses(context, operation, method); extension.applyImplicitParameters(context, operation, method); for (int i = 0; i < genericParameterTypes.length; i++) { extension.applyParameters(context, operation, genericParameterTypes[i], paramAnnotations[i]); } } } if (httpMethod != null && operationPath != null) { if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("OK")); } else { for (String k : operation.getResponses().keySet()) { if (k.equals("200")) { Response response = operation.getResponses().get(k); if ("successful operation".equals(response.getDescription())) response.setDescription("OK"); } } } final Map<String, String> regexMap = new HashMap<String, String>(); final String parsedPath = PathUtils.parsePath(operationPath, regexMap); if (parsedPath != null) { // check for curly path params for (String seg : parsedPath.split("/")) { if (seg.startsWith("{") && seg.endsWith("}")) { String segName = seg.substring(1, seg.length() - 1); boolean declared = false; for (Parameter opParam : operation.getParameters()) { if ("path".equals(opParam.getIn()) && segName.equals(opParam.getName())) { declared = true; break; } } if (!declared) { // add it for free PathParameter pathParam = new PathParameter(); pathParam.setName(segName); pathParam.setRequired(false); pathParam.setDefaultValue(""); operation.parameter(pathParam); } } } } Path path = swagger.getPath(parsedPath); if (path == null) { path = new Path(); swagger.path(parsedPath, path); } path.set(httpMethod.toLowerCase(), operation); } } }
From source file:org.brekka.stillingar.spring.bpp.ConfigurationBeanPostProcessor.java
/** * Encapsulate the 'listener' method that will be invoked once all fields/setter methods have been updated. The * parameters of this method will be added as individual {@link ValueDefinition}'s to <code>valueList</code>. * // ww w. j a v a2s . co m * @param method * the method being encapsulated * @param valueList * the list of value definitions that the new {@link ValueDefinition}s for this field will be added to. * @param bean * the bean being configured. * @return the {@link PostUpdateChangeListener} that will invoke the listener method on configuration update. */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected PostUpdateChangeListener processListenerMethod(Method method, List<ValueDefinition<?, ?>> valueList, Object bean) { Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); List<ParameterValueResolver> argList = new ArrayList<ParameterValueResolver>(); for (int i = 0; i < parameterTypes.length; i++) { ParameterValueResolver arg = null; Annotation[] annotations = parameterAnnotations[i]; Class type = parameterTypes[i]; boolean list = false; if (type == List.class) { type = listType(genericParameterTypes[i]); list = true; } Qualifier qualifier = null; for (Annotation annotation : annotations) { if (annotation instanceof Configured) { Configured paramConfigured = (Configured) annotation; MethodParameterListener mpl = new MethodParameterListener(); ValueDefinition<Object, ?> value; if (list) { value = new ValueListDefinition<Object>(type, paramConfigured.value(), mpl); } else { value = new SingleValueDefinition<Object>(type, paramConfigured.value(), mpl); } valueList.add(value); arg = mpl; break; } else if (annotation instanceof Qualifier) { qualifier = (Qualifier) annotation; } } if (arg == null) { if (qualifier != null) { try { beanFactory.getBean(qualifier.value(), type); arg = new BeanReferenceResolver(beanFactory, qualifier, type); } catch (NoSuchBeanDefinitionException e) { throw new ConfigurationException(format( "Listener method '%s' parameter %d is not marked as %s and no bean " + "definition could be found in the container with the qualifier '%s' and type '%s'.", method.getName(), (i + 1), Configured.class.getSimpleName(), qualifier.value(), type.getName())); } } else { try { beanFactory.getBean(type); arg = new BeanReferenceResolver(beanFactory, type); } catch (NoSuchBeanDefinitionException e) { throw new ConfigurationException(format( "Listener method '%s' parameter %d is not marked as %s and no bean " + "definition could be found in the container with the type '%s'.", method.getName(), (i + 1), Configured.class.getSimpleName(), type.getName())); } } } argList.add(arg); } return new PostUpdateChangeListener(bean, method, argList); }
From source file:org.openmrs.module.sync.SyncUtil.java
/** * This monstrosity looks for getter(s) on the parent object of an OpenmrsObject that return a * collection of the originally passed in OpenmrsObject type. This then explicitly removes the * object from the parent collection, and if the parent is a Patient or Person, calls save on * the parent.// www.j ava 2s. c o m * * @param item -- the OpenmrsObject to remove and save */ private static void removeFromPatientParentCollectionAndSave(OpenmrsObject item) { Field[] f = item.getClass().getDeclaredFields(); for (int k = 0; k < f.length; k++) { Type fieldType = f[k].getGenericType(); if (org.openmrs.OpenmrsObject.class.isAssignableFrom((Class) fieldType)) { //if the property is an OpenmrsObject (excludes lists, etc..) Method getter = getGetterMethod(item.getClass(), f[k].getName()); //get the getters OpenmrsObject parent = null; //the parent object if (getter == null) { continue; //no prob -- eliminates most utility methods on item } try { parent = (OpenmrsObject) getter.invoke(item, null); //get the parent object } catch (Exception ex) { log.debug( "in removeFromParentCollection: getter probably did not return an object that could be case as an OpenmrsObject", ex); } if (parent != null) { Method[] methods = getter.getReturnType().getDeclaredMethods(); //get the Parent's methods to inspect for (Method method : methods) { Type type = method.getGenericReturnType(); //return is a parameterizable and there are 0 arguments to method and the return is a Collection if (ParameterizedType.class.isAssignableFrom(type.getClass()) && method.getGenericParameterTypes().length == 0 && method.getName().contains("get")) { //get the methods on Person that return Lists or Sets ParameterizedType pt = (ParameterizedType) type; for (int i = 0; i < pt.getActualTypeArguments().length; i++) { Type t = pt.getActualTypeArguments()[i]; // if the return type matches the original object, and the return is not a Map if (item.getClass().equals(t) && !pt.getRawType().toString().equals(java.util.Map.class.toString()) && java.util.Collection.class.isAssignableFrom((Class) pt.getRawType())) { try { Object colObj = (Object) method.invoke(parent, null); //get the list if (colObj != null) { java.util.Collection collection = (java.util.Collection) colObj; Iterator it = collection.iterator(); boolean atLeastOneRemoved = false; while (it.hasNext()) { OpenmrsObject omrsobj = (OpenmrsObject) it.next(); if (omrsobj.getUuid() != null && omrsobj.getUuid().equals(item.getUuid())) { //compare uuid of original item with Collection contents it.remove(); atLeastOneRemoved = true; } if (atLeastOneRemoved && (parent instanceof org.openmrs.Patient || parent instanceof org.openmrs.Person)) { // this is commented out because deleting of patients fails if it is here. // we really should not need to call "save", that can only cause problems. // removing the object from the parent collection is the important part, which we're doing above //Context.getService(SyncService.class).saveOrUpdate(parent); } } } } catch (Exception ex) { log.error("Failed to build new collection", ex); } } } } } } } } }
From source file:io.limberest.api.SwaggerReader.java
private void read(ReaderContext context) { final SwaggerDefinition swaggerDefinition = context.getCls().getAnnotation(SwaggerDefinition.class); if (swaggerDefinition != null) { readSwaggerConfig(swaggerDefinition); }//from ww w.j a v a2s . co m for (Method method : context.getCls().getMethods()) { // TODO: how to smartly limit extension processing // if (ReflectionUtils.isOverriddenMethod(method, context.getCls())) { // continue; // } final Operation operation = new Operation(); String operationPath = null; String httpMethod = null; final Type[] genericParameterTypes = method.getGenericParameterTypes(); final Annotation[][] paramAnnotations = method.getParameterAnnotations(); // Avoid java.util.ServiceLoader mechanism which finds ServletReaderExtension // for (ReaderExtension extension : ReaderExtensions.getExtensions()) { for (ReaderExtension extension : getExtensions()) { if (operationPath == null) { operationPath = extension.getPath(context, method); } if (httpMethod == null) { httpMethod = extension.getHttpMethod(context, method); } if (operationPath == null || httpMethod == null) { continue; } if (extension.isReadable(context)) { extension.setDeprecated(operation, method); extension.applyConsumes(context, operation, method); extension.applyProduces(context, operation, method); extension.applyOperationId(operation, method); extension.applySummary(operation, method); extension.applyDescription(operation, method); extension.applySchemes(context, operation, method); extension.applySecurityRequirements(context, operation, method); extension.applyTags(context, operation, method); extension.applyResponses(context, operation, method); extension.applyImplicitParameters(context, operation, method); for (int i = 0; i < genericParameterTypes.length; i++) { extension.applyParameters(context, operation, genericParameterTypes[i], paramAnnotations[i]); } } } if (httpMethod != null && operationPath != null) { if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("OK")); } else { for (String k : operation.getResponses().keySet()) { if (k.equals("200")) { Response response = operation.getResponses().get(k); if ("successful operation".equals(response.getDescription())) response.setDescription("OK"); } } } final Map<String, String> regexMap = new HashMap<String, String>(); final String parsedPath = PathUtils.parsePath(operationPath, regexMap); if (parsedPath != null) { // Check for curly path params -- these are added for free if not annotated. for (String seg : parsedPath.split("/")) { if (seg.startsWith("{") && seg.endsWith("}")) { String segName = seg.substring(1, seg.length() - 1); boolean declared = false; for (Parameter opParam : operation.getParameters()) { if ("path".equals(opParam.getIn()) && segName.equals(opParam.getName())) { declared = true; break; } } if (!declared) { PathParameter pathParam = new PathParameter(); pathParam.setName(segName); pathParam.setRequired(false); pathParam.setDefaultValue(""); operation.parameter(pathParam); } } } } Path path = swagger.getPath(parsedPath); if (path == null) { path = new Path(); swagger.path(parsedPath, path); } path.set(httpMethod.toLowerCase(), operation); } } }
From source file:com.wavemaker.tools.javaservice.JavaServiceDefinition.java
private void initOperation(Method method, TypeState typeState) { ServiceOperation so = new ServiceOperation(); so.setName(method.getName());// ww w . ja v a2 s . c om if (!method.getReturnType().equals(void.class)) { so.setReturnType(ReflectTypeUtils.getFieldDefinition(method, typeState, false, null)); checkAddType(so.getReturnType().getTypeDefinition()); } List<String> paramNames = ServerUtils.getParameterNames(method); Type[] types = method.getGenericParameterTypes(); List<FieldDefinition> params = new ArrayList<FieldDefinition>(types.length); so.setParameterTypes(params); for (int i = 0; i < types.length; i++) { params.add(ReflectTypeUtils.getFieldDefinition(types[i], typeState, false, paramNames.get(i))); checkAddType(params.get(i).getTypeDefinition()); } this.operations.add(so); }
From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java
/** * Return ComponentType, might need to look at the GenericType * @param pd ParameterDesc or null if return * @param operationDesc OperationDescription * @param msrd MarshalServiceRuntimeDescription * @return/*from www . j av a 2s . c o m*/ */ private static Class getComponentType(ParameterDescription pd, OperationDescription operationDesc, MarshalServiceRuntimeDescription msrd) { Class componentType = null; if (log.isDebugEnabled()) { log.debug("start getComponentType"); log.debug(" ParameterDescription=" + pd); } // Determine if array, list, or other Class cls = null; if (pd == null) { cls = operationDesc.getResultActualType(); } else { cls = pd.getParameterActualType(); } if (cls != null) { if (cls.isArray()) { componentType = cls.getComponentType(); } else if (List.class.isAssignableFrom(cls)) { if (log.isDebugEnabled()) { log.debug("Parameter is a List: " + cls); } Method method = msrd.getMethod(operationDesc); if (log.isDebugEnabled()) { log.debug("Method is: " + method); } Type genericType = null; if (pd == null) { genericType = method.getGenericReturnType(); } else { ParameterDescription[] pds = operationDesc.getParameterDescriptions(); for (int i = 0; i < pds.length; i++) { if (pds[i] == pd) { genericType = method.getGenericParameterTypes()[i]; } } } if (log.isDebugEnabled()) { log.debug("genericType is: " + genericType.getClass() + " " + genericType); } if (genericType instanceof Class) { if (log.isDebugEnabled()) { log.debug(" genericType instanceof Class"); } componentType = String.class; } else if (genericType instanceof ParameterizedType) { if (log.isDebugEnabled()) { log.debug(" genericType instanceof ParameterizedType"); } ParameterizedType pt = (ParameterizedType) genericType; if (pt.getRawType() == Holder.class) { if (log.isDebugEnabled()) { log.debug(" strip off holder"); } genericType = pt.getActualTypeArguments()[0]; if (genericType instanceof Class) { componentType = String.class; } else if (genericType instanceof ParameterizedType) { pt = (ParameterizedType) genericType; } } if (componentType == null) { Type comp = pt.getActualTypeArguments()[0]; if (log.isDebugEnabled()) { log.debug(" comp =" + comp.getClass() + " " + comp); } if (comp instanceof Class) { componentType = (Class) comp; } else if (comp instanceof ParameterizedType) { componentType = (Class) ((ParameterizedType) comp).getRawType(); } } } } } if (log.isDebugEnabled()) { log.debug("end getComponentType=" + componentType); } return componentType; }
From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java
private void validateSetter(ModelSchemaExtractionContext<?> extractionContext, ModelType<?> propertyType, Method setter) { if (!Modifier.isAbstract(setter.getModifiers())) { throw invalidMethod(extractionContext, "non-abstract setters are not allowed", setter); }// www . j av a2s . com if (!setter.getReturnType().equals(void.class)) { throw invalidMethod(extractionContext, "setter method must have void return type", setter); } Type[] setterParameterTypes = setter.getGenericParameterTypes(); if (setterParameterTypes.length != 1) { throw invalidMethod(extractionContext, "setter method must have exactly one parameter", setter); } ModelType<?> setterType = ModelType.paramType(setter, 0); if (!setterType.equals(propertyType)) { String message = "setter method param must be of exactly the same type as the getter returns (expected: " + propertyType + ", found: " + setterType + ")"; throw invalidMethod(extractionContext, message, setter); } }
From source file:com.tyro.oss.pact.spring4.pact.provider.PactTestRunner.java
@Deprecated private void setUpProviderState(Object testInstance, Interaction interaction) throws Exception { Pact.ProviderState providerState = interaction.getProviderState(); if (providerState != null) { if (testInstance instanceof ObjectStringConverterSource) { providerState.setJsonConverter(((ObjectStringConverterSource) testInstance).getConverter()); } else {// w ww. ja va 2 s .c om providerState.setJsonConverter(jsonConverter); } Method providerStateSetupMethod = providerStateMethods.get(providerState.getDescription()); if (providerStateSetupMethod == null) { throw new IllegalStateException( "Cannot find a setup method for provider state " + providerState.getDescription()); } providerStateSetupMethod.invoke(testInstance, providerState.getStates(providerStateSetupMethod.getGenericParameterTypes())); } }
From source file:org.ut.biolab.medsavant.MedSavantServlet.java
public String json_invoke(String adapter, String method, String jsonStr) throws IllegalArgumentException { adapter = adapter + "Adapter"; Field selectedAdapter = null; for (Field f : MedSavantServlet.class.getDeclaredFields()) { if (f.getType().getSimpleName().equalsIgnoreCase(adapter)) { selectedAdapter = f;//w w w. j av a2 s .com } } if (selectedAdapter == null) { throw new IllegalArgumentException("The adapter " + adapter + " does not exist"); } JsonParser parser = new JsonParser(); JsonArray gArray = parser.parse(jsonStr).getAsJsonArray(); JsonElement jse = parser.parse(jsonStr); JsonArray jsonArray; if (jse.isJsonArray()) { jsonArray = jse.getAsJsonArray(); } else { throw new IllegalArgumentException("The json method arguments are not an array"); } Method selectedMethod = null; for (Method m : selectedAdapter.getType().getMethods()) { if (m.getName().equalsIgnoreCase(method) && m.getGenericParameterTypes().length == (jsonArray.size() + 1)) { selectedMethod = m; } } if (selectedMethod == null) { throw new IllegalArgumentException("The method " + method + " in adapter " + adapter + " with " + jsonArray.size() + " arguments does not exist"); } int i = 0; Object[] methodArgs = new Object[selectedMethod.getParameterTypes().length]; try { for (Type t : selectedMethod.getGenericParameterTypes()) { LOG.debug("Field " + i + " is " + t.toString() + " for method " + selectedMethod.toString()); methodArgs[i] = (i > 0) ? gson.fromJson(gArray.get(i - 1), t) : session.getSessionId(); ++i; } } catch (JsonParseException je) { LOG.error(je); } Object selectedAdapterInstance = null; try { selectedAdapterInstance = selectedAdapter.get(this); if (selectedAdapterInstance == null) { throw new NullPointerException( "Requested adapter " + selectedAdapter.getName() + " was not initialized."); } MethodInvocation methodInvocation = new MethodInvocation(session, gson, selectedAdapterInstance, selectedMethod, methodArgs); return methodInvocation.invoke(); } catch (IllegalAccessException iae) { throw new IllegalArgumentException("Couldn't execute method with given arguments: " + iae.getMessage()); } catch (LockException lex) { //this shouldn't happen, as locking exceptions can only be thrown by queued method invocations, which //are intercepted in the BlockingQueueManager. String msg = "Unexpected locking exception thrown in unqueued method invocation."; LOG.error(msg); throw new IllegalArgumentException(msg + ": " + lex.getMessage()); } }
From source file:com.sun.socialsite.util.DebugBeanJsonConverter.java
@SuppressWarnings("boxing") private <T> void callSetterWithValue(T pojo, Method method, JSONObject jsonObject, String fieldName) throws IllegalAccessException, InvocationTargetException, NoSuchFieldException, JSONException { log.debug("Calling setter [" + method.getName() + "]"); Class<?> expectedType = method.getParameterTypes()[0]; Object value = null;/*ww w. j av a 2s. c om*/ if (!jsonObject.has(fieldName)) { // Skip } else if (expectedType.equals(List.class)) { ParameterizedType genericListType = (ParameterizedType) method.getGenericParameterTypes()[0]; Type type = genericListType.getActualTypeArguments()[0]; Class<?> rawType; Class<?> listElementClass; if (type instanceof ParameterizedType) { listElementClass = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]; rawType = (Class<?>) ((ParameterizedType) type).getRawType(); } else { listElementClass = (Class<?>) type; rawType = listElementClass; } List<Object> list = Lists.newArrayList(); JSONArray jsonArray = jsonObject.getJSONArray(fieldName); for (int i = 0; i < jsonArray.length(); i++) { if (org.apache.shindig.protocol.model.Enum.class.isAssignableFrom(rawType)) { list.add(convertEnum(listElementClass, jsonArray.getJSONObject(i))); } else { list.add(convertToObject(jsonArray.getString(i), listElementClass)); } } value = list; } else if (expectedType.equals(Map.class)) { ParameterizedType genericListType = (ParameterizedType) method.getGenericParameterTypes()[0]; Type[] types = genericListType.getActualTypeArguments(); Class<?> valueClass = (Class<?>) types[1]; // We only support keys being typed as Strings. // Nothing else really makes sense in json. Map<String, Object> map = Maps.newHashMap(); JSONObject jsonMap = jsonObject.getJSONObject(fieldName); Iterator<?> keys = jsonMap.keys(); while (keys.hasNext()) { String keyName = (String) keys.next(); map.put(keyName, convertToObject(jsonMap.getString(keyName), valueClass)); } value = map; } else if (org.apache.shindig.protocol.model.Enum.class.isAssignableFrom(expectedType)) { // TODO Need to stop using Enum as a class name :( value = convertEnum((Class<?>) ((ParameterizedType) method.getGenericParameterTypes()[0]) .getActualTypeArguments()[0], jsonObject.getJSONObject(fieldName)); } else if (expectedType.isEnum()) { if (jsonObject.has(fieldName)) { for (Object v : expectedType.getEnumConstants()) { if (v.toString().equals(jsonObject.getString(fieldName))) { value = v; break; } } if (value == null) { throw new IllegalArgumentException("No enum value '" + jsonObject.getString(fieldName) + "' in " + expectedType.getName()); } } } else if (expectedType.equals(String.class)) { value = jsonObject.getString(fieldName); } else if (expectedType.equals(Date.class)) { // Use JODA ISO parsing for the conversion value = new DateTime(jsonObject.getString(fieldName)).toDate(); } else if (expectedType.equals(Long.class) || expectedType.equals(Long.TYPE)) { value = jsonObject.getLong(fieldName); } else if (expectedType.equals(Integer.class) || expectedType.equals(Integer.TYPE)) { value = jsonObject.getInt(fieldName); } else if (expectedType.equals(Boolean.class) || expectedType.equals(Boolean.TYPE)) { value = jsonObject.getBoolean(fieldName); } else if (expectedType.equals(Float.class) || expectedType.equals(Float.TYPE)) { value = ((Double) jsonObject.getDouble(fieldName)).floatValue(); } else if (expectedType.equals(Double.class) || expectedType.equals(Double.TYPE)) { value = jsonObject.getDouble(fieldName); } else { // Assume its an injected type value = convertToObject(jsonObject.getJSONObject(fieldName).toString(), expectedType); } if (value != null) { method.invoke(pojo, value); } }