List of usage examples for java.lang.reflect Method getGenericReturnType
public Type getGenericReturnType()
From source file:com.msopentech.odatajclient.proxy.api.impl.AbstractInvocationHandler.java
protected Object functionImport(final Operation annotation, final Method method, final Object[] args, final URI target, final com.msopentech.odatajclient.engine.metadata.edm.v3.FunctionImport funcImp) throws InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { // 1. invoke params (if present) final Map<String, ODataValue> parameters = new HashMap<String, ODataValue>(); if (!ArrayUtils.isEmpty(args)) { final Annotation[][] parAnnots = method.getParameterAnnotations(); final Class<?>[] parTypes = method.getParameterTypes(); for (int i = 0; i < args.length; i++) { if (!(parAnnots[i][0] instanceof Parameter)) { throw new IllegalArgumentException("Paramter " + i + " is not annotated as @Param"); }/*from w w w .j ava 2 s . c o m*/ final Parameter parAnnot = (Parameter) parAnnots[i][0]; if (!parAnnot.nullable() && args[i] == null) { throw new IllegalArgumentException( "Parameter " + parAnnot.name() + " is not nullable but a null value was provided"); } final ODataValue paramValue = args[i] == null ? null : EngineUtils.getODataValue(client, containerHandler.getFactory().getMetadata(), new EdmV3Type(containerHandler.getFactory().getMetadata(), parAnnot.type()), args[i]); parameters.put(parAnnot.name(), paramValue); } } // 2. IMPORTANT: flush any pending change *before* invoke if this operation is side effecting if (annotation.isSideEffecting()) { new Container(client, containerHandler.getFactory()).flush(); } // 3. invoke final ODataInvokeResult result = client.getInvokeRequestFactory() .getInvokeRequest(target, containerHandler.getFactory().getMetadata(), funcImp, parameters) .execute().getBody(); // 3. process invoke result if (StringUtils.isBlank(annotation.returnType())) { return ClassUtils.returnVoid(); } final EdmType edmType = new EdmV3Type(containerHandler.getFactory().getMetadata(), annotation.returnType()); if (edmType.isEnumType()) { throw new UnsupportedOperationException("Usupported enum type " + edmType.getTypeExpression()); } if (edmType.isSimpleType() || edmType.isComplexType()) { return EngineUtils.getValueFromProperty(containerHandler.getFactory().getMetadata(), (ODataProperty) result, method.getGenericReturnType()); } if (edmType.isEntityType()) { if (edmType.isCollection()) { final ParameterizedType collType = (ParameterizedType) method.getReturnType() .getGenericInterfaces()[0]; final Class<?> collItemType = (Class<?>) collType.getActualTypeArguments()[0]; return getEntityCollection(collItemType, method.getReturnType(), null, (ODataEntitySet) result, target, false); } else { return getEntityProxy((ODataEntity) result, null, null, method.getReturnType(), false); } } throw new IllegalArgumentException("Could not process the functionImport information"); }
From source file:org.evergreen.web.utils.beanutils.PropertyUtilsBean.java
/** * Set the value of the specified indexed property of the specified * bean, with no type conversions. In addition to supporting the JavaBeans * specification, this method has been extended to support * <code>List</code> objects as well. * * @param bean Bean whose property is to be set * @param name Simple property name of the property value to be set * @param index Index of the property value to be set * @param value Value to which the indexed property element is to be set * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if <code>bean</code> or * <code>name</code> is null * @exception InvocationTargetException if the property accessor method * throws an exception//from ww w . j a v a2s .c o m * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setIndexedProperty(Object bean, String name, int index, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null || name.length() == 0) { if (bean.getClass().isArray()) { Array.set(bean, index, value); return; } else if (bean instanceof List) { ((List) bean).set(index, value); return; } } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException( "Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } ((DynaBean) bean).set(name, index, value); return; } // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException( "Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Call the indexed setter method if there is one if (descriptor instanceof IndexedPropertyDescriptor) { Method writeMethod = ((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod(); writeMethod = MethodUtils.getAccessibleMethod(bean.getClass(), writeMethod); if (writeMethod != null) { Object[] subscript = new Object[2]; subscript[0] = new Integer(index); subscript[1] = value; try { if (log.isTraceEnabled()) { String valueClassName = value == null ? "<null>" : value.getClass().getName(); log.trace("setSimpleProperty: Invoking method " + writeMethod + " with index=" + index + ", value=" + value + " (class " + valueClassName + ")"); } invokeMethod(writeMethod, bean, subscript); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof IndexOutOfBoundsException) { throw (IndexOutOfBoundsException) e.getTargetException(); } else { throw e; } } return; } } // Otherwise, the underlying property must be an array or a list Method readMethod = getReadMethod(bean.getClass(), descriptor); if (readMethod == null) { throw new NoSuchMethodException( "Property '" + name + "' has no getter method on bean class '" + bean.getClass() + "'"); } // Call the property getter to get the array or list Object array = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY); if (!array.getClass().isArray()) { if (array instanceof List) { // Modify the specified value in the List //((List) array).set(index, value); //? //((List) array).add(value); List list = (List) array; Type returnType = readMethod.getGenericReturnType(); Type acturalType = ((ParameterizedType) returnType).getActualTypeArguments()[0]; list.add(ConvertUtils.convert(value, (Class) acturalType)); } else if (array instanceof Set) { //?set?? //((Set) array).add(value); Set set = (Set) array; Type returnType = readMethod.getGenericReturnType(); Type acturalType = ((ParameterizedType) returnType).getActualTypeArguments()[0]; set.add(ConvertUtils.convert(value, (Class) acturalType)); } else { throw new IllegalArgumentException( "Property '" + name + "' is not indexed on bean class '" + bean.getClass() + "'"); } } else { // Modify the specified value in the array Array.set(array, index, value); } }
From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java
private EntityModel createWrapperEntity(String name, Method method, RegistryNodeModel registryNodeModel, boolean request, List<RelationshipModel> relationships, Map<String, EntityModel> models, Service service) {/*from w ww.j a va 2s. c om*/ EntityModel model = models.get(name); if (model != null) return model; String modelName = name.replaceAll("\\B([A-Z]+)\\B", " $1"); EntityModel entityModel = new EntityModel(); entityModel.setName(modelName); entityModel.setLookup(DiffUtils.lookup(registryNodeModel.getLookup(), modelName)); entityModel.setPath(registryNodeModel.getLookup()); entityModel.setAbstractEntity(false); entityModel.setTypeEntity(true); entityModel.setReverseEngineer(true); entityModel.setProtocol(EntityProtocol.HTTP); entityModel.setParent(registryNodeModel); models.put(name, entityModel); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); Type[] parameterTypes = method.getGenericParameterTypes(); List<FieldModel> fields = new ArrayList<FieldModel>(parameterTypes.length); for (int i = 0; i < parameterTypes.length; i++) { Annotation[] annotations = parameterAnnotations[i]; for (Annotation annotation : annotations) { if (WebParam.class.isInstance(annotation)) { WebParam param = (WebParam) annotation; if (param.mode() == INOUT || request && param.mode() == IN || !request && param.mode() == OUT) { analyzeField(param.name(), parameterTypes[i], TYPE, entityModel, null, models, relationships, fields); analyzeField(param.name(), parameterTypes[i], param.mode(), false, false, false, service); } break; } } } Type returnType = method.getGenericReturnType(); if (!request && void.class != returnType) { analyzeField(RETURN, returnType, TYPE, entityModel, null, models, relationships, fields); analyzeField(RETURN, returnType, null, false, false, true, service); } entityModel.setFields(fields); return entityModel; }
From source file:org.op4j.devutils.selected.ImplFile.java
public void computeMethodImplementations(final ImplType implType, final Class<?> interfaceClass) throws Exception { final List<Method> interfaceMethods = new ArrayList<Method>(); interfaceMethods.addAll(Arrays.asList(interfaceClass.getDeclaredMethods())); final Set<Type> extendedInterfaces = new HashSet<Type>( Arrays.asList(interfaceClass.getGenericInterfaces())); Type getReturnType = null;//from w w w. j a va 2s. c o m for (final Type extendedInterface : extendedInterfaces) { if (extendedInterface instanceof ParameterizedType) { final ParameterizedType pType = (ParameterizedType) extendedInterface; if (((Class<?>) pType.getRawType()).equals(UniqOperator.class)) { getReturnType = pType.getActualTypeArguments()[0]; } } } try { interfaceMethods.add(UniqOpOperator.class.getMethod("get")); } catch (NoSuchMethodException e) { // nothing to do } if (this.className.contains("Array")) { this.element = "T[]"; } else if (this.className.contains("List")) { this.element = "List<T>"; } else if (this.className.contains("Set")) { this.element = "Set<T>"; } else if (this.className.contains("Map")) { this.element = "Map<K,V>"; } else { this.element = "T"; } for (final Method interfaceMethod : interfaceMethods) { final String methodName = interfaceMethod.getName(); this.methodNames.add(methodName); final Type[] parameterTypes = interfaceMethod.getGenericParameterTypes(); if (methodName.startsWith("exec")) { this.currentLevelType = (new TypeRep( ((WildcardType) ((ParameterizedType) parameterTypes[0]).getActualTypeArguments()[0]) .getLowerBounds()[0])).getStringRep(); if (this.currentLevelType.endsWith("[]")) { this.currentLevelElement = this.currentLevelType.substring(0, this.currentLevelType.length() - 2); } else if (this.currentLevelType.startsWith("List<") && this.currentLevelType.endsWith(">")) { this.currentLevelElement = this.currentLevelType.substring(5, this.currentLevelType.length() - 1); } else if (this.currentLevelType.startsWith("Set<") && this.currentLevelType.endsWith(">")) { this.currentLevelElement = this.currentLevelType.substring(4, this.currentLevelType.length() - 1); } else if (this.currentLevelType.startsWith("Map<") && this.currentLevelType.endsWith(">")) { this.currentLevelElement = "Map.Entry<" + this.currentLevelType.substring(4, this.currentLevelType.length() - 1) + ">"; } else { this.currentLevelElement = "%%CURRENTELEMENTSHOULDNOTBEHERE%%"; } } final String returnTypeStr = (methodName.equals("get") ? (implType == ImplType.OP ? this.element : "Function<I," + this.element + ">") : (methodName.equals("getAsArrayOf") ? (implType == ImplType.OP ? this.element + "[]" : "Function<I," + this.element + "[]>") : (methodName.equals("getAsList") ? (implType == ImplType.OP ? "List<" + this.element + ">" : "Function<I,List<" + this.element + ">>") : new TypeRep(interfaceMethod.getGenericReturnType()).getStringRep() .replaceAll("ILevel", "Level")))); final StringBuilder parameterStrBuilder = new StringBuilder(); parameterStrBuilder.append("("); List<String> normalisedParamTypes = new ArrayList<String>(); List<String> normalisedRawParamTypes = new ArrayList<String>(); for (int j = 0; j < parameterTypes.length; j++) { normalisedParamTypes.add(getNormalisedParamType(parameterTypes[j], methodName, j)); normalisedRawParamTypes.add( StringUtils.substringBefore(getNormalisedParamType(parameterTypes[j], methodName, j), "<")); } String[] paramNamesForMethod = paramNames .get(methodName + "%" + StringUtils.join(normalisedRawParamTypes, ",")); if (paramNamesForMethod == null) { paramNamesForMethod = paramNames.get(methodName + "%" + parameterTypes.length); if (paramNamesForMethod == null) { paramNamesForMethod = paramNames.get(methodName); } } for (int j = 0; j < normalisedParamTypes.size(); j++) { if (j > 0) { parameterStrBuilder.append(", "); } parameterStrBuilder.append("final " + normalisedParamTypes.get(j) + " "); if (paramNamesForMethod == null) { throw new RuntimeException("No name for parameter " + j + " of method " + methodName + " in interface " + this.interfaceTypeRep.getStringRep()); } parameterStrBuilder.append(paramNamesForMethod[j]); } parameterStrBuilder.append(")"); final StringBuilder strBuilder = new StringBuilder(); strBuilder.append( " public " + returnTypeStr + " " + methodName + parameterStrBuilder.toString() + " {\n"); strBuilder.append(" return null;\n"); strBuilder.append(" }\n"); this.methodImplementations.add(strBuilder.toString()); } }
From source file:net.firejack.platform.core.store.AbstractStore.java
@SuppressWarnings("unchecked") protected Criterion parseAdvancedSearchRequest(List<SearchQuery> searchQueries, Map<String, String> aliases, boolean skipNotValidValues) { int index = 0; LinkedList<Criterion> criterions = new LinkedList<Criterion>(); for (SearchQuery searchQuery : searchQueries) { Criterion criterion;/* w w w . ja va 2s .co m*/ String field = searchQuery.getField(); if (field == null) { criterions.add(Restrictions.sqlRestriction("1 = 1")); } else { String[] fieldNames = field.split("\\."); if (fieldNames.length == 1) { String fieldName = fieldNames[0]; PropertyDescriptor propertyDescriptor = ClassUtils.getPropertyDescriptor(getClazz(), fieldName); if (propertyDescriptor != null) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null) { Class<?> returnType = readMethod.getReturnType(); try { criterion = getRestrictions(searchQuery, returnType); criterions.add(criterion); } catch (IllegalArgumentException e) { if (!skipNotValidValues) { throw new BusinessFunctionException( "The field '" + fieldName + "' has type '" + returnType.getName() + "', but value '" + searchQuery.getValue() + "' is incorrect"); } } } else { throw new BusinessFunctionException("The field '" + fieldName + "' has not read method in class '" + getClazz().getName() + "'"); } } else { throw new BusinessFunctionException("The field '" + fieldName + "' does not exist in class '" + getClazz().getName() + "'"); } } else { Class<E> aClass = getClazz(); String indexedFieldName = null; for (int i = 0; i < fieldNames.length; i++) { String fieldName = fieldNames[i]; PropertyDescriptor propertyDescriptor = ClassUtils.getPropertyDescriptor(aClass, fieldName); if (propertyDescriptor != null) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null) { Class<?> returnType = readMethod.getReturnType(); if (Collection.class.isAssignableFrom(returnType)) { returnType = (Class<?>) ((ParameterizedTypeImpl) readMethod .getGenericReturnType()).getActualTypeArguments()[0]; } if (AbstractModel.class.isAssignableFrom(returnType)) { aClass = (Class) returnType; String alias = i == 0 ? fieldName : indexedFieldName + "." + fieldName; indexedFieldName = aliases.get(alias); if (indexedFieldName == null) { indexedFieldName = fieldName + index++; aliases.put(alias, indexedFieldName); } } else { if (i == (fieldNames.length - 1)) { String queryFieldName = indexedFieldName + "." + fieldName; try { criterion = getRestrictions(new SearchQuery(queryFieldName, searchQuery.getOperation(), searchQuery.getValue()), returnType); criterions.add(criterion); } catch (IllegalArgumentException e) { if (!skipNotValidValues) { throw new BusinessFunctionException("The field '" + fieldName + "' has type '" + returnType.getName() + "', but value '" + searchQuery.getValue() + "' is incorrect"); } } } else { throw new BusinessFunctionException("Field name: '" + fieldName + "' is not correct in query: '" + field + "'"); } } } else { throw new BusinessFunctionException("The field '" + fieldName + "' has not read method in class '" + aClass + "'"); } } else { throw new BusinessFunctionException( "The field '" + fieldName + "' does not exist in class '" + aClass + "'"); } } } } } Criterion andCriterion = null; for (Criterion criterion : criterions) { andCriterion = criterions.getFirst() == criterion ? criterion : Restrictions.and(andCriterion, criterion); } return andCriterion; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private INakedObject deproxyNakedObject(boolean root, Set<PropertyDescriptor> collections, Set<PropertyDescriptor> lazys, Set<PropertyDescriptor> eagers, Set<LinkFileInfo> linkedFiles, INakedObject no, Set<PropertyDescriptor> idPds, Map<String, Map<Object, Object>> oldIdByNewId, EntityManager em, Map<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>> deproxyContext) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException, ClassNotFoundException, PersistenceException { String name = getClassName(no); if (isProxy(no, name)) no = clone(no, name);/* ww w. ja v a2s.c om*/ Map<com.hiperf.common.ui.shared.util.Id, INakedObject> map = deproxyContext.get(name); if (map == null) { map = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>(); deproxyContext.put(name, map); } com.hiperf.common.ui.shared.util.Id noId = getId(no, idsByClassName.get(name)); if (map.containsKey(noId)) return no; map.put(noId, no); if (root && linkedFiles != null && !linkedFiles.isEmpty()) { for (LinkFileInfo a : linkedFiles) { Object fileId = a.getLocalFileIdGetter().invoke(no, new Object[0]); if (fileId != null) a.getLocalFileNameSetter().invoke(no, getFileName(a.getFileClassName(), a.getFileNameField(), fileId, getEntityManager())); } } if (collections != null) { for (PropertyDescriptor pd : collections) { Method readMethod = pd.getReadMethod(); Method writeMethod = pd.getWriteMethod(); Object o = readMethod.invoke(no, new Object[0]); if (o != null) { if (root) { Collection orig = (Collection) o; boolean processed = false; Type type = readMethod.getGenericReturnType(); Class classInCollection = null; if (type instanceof ParameterizedType) { classInCollection = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; } if (classInCollection != null) { if (Number.class.isAssignableFrom(classInCollection) || String.class.equals(classInCollection) || Boolean.class.equals(classInCollection)) { Collection targetColl; int size = orig.size(); if (List.class.isAssignableFrom(readMethod.getReturnType())) { targetColl = new ArrayList(size); } else { targetColl = new HashSet(size); } if (size > 0) targetColl.addAll(orig); writeMethod.invoke(no, targetColl); processed = true; } } if (!processed) { //deproxyCollection(no, readMethod, writeMethod, orig, oldIdByNewId, em, deproxyContext); com.hiperf.common.ui.shared.util.Id id = getId(no, idPds); CollectionInfo ci = null; if (!id.isLocal()) { String className = getClassName(no); String attName = pd.getName(); ci = getCollectionInfo(em, id, className, attName); } if (List.class.isAssignableFrom(readMethod.getReturnType())) { if (ci != null) writeMethod.invoke(no, new LazyList<INakedObject>(ci.getSize(), ci.getDescription())); else writeMethod.invoke(no, new LazyList<INakedObject>()); } else { if (ci != null) writeMethod.invoke(no, new LazySet<INakedObject>(ci.getSize(), ci.getDescription())); else writeMethod.invoke(no, new LazySet<INakedObject>()); } } } else { if (List.class.isAssignableFrom(readMethod.getReturnType())) { writeMethod.invoke(no, new LazyList<INakedObject>()); } else { writeMethod.invoke(no, new LazySet<INakedObject>()); } } } } } if (lazys != null) { for (PropertyDescriptor pd : lazys) { Method readMethod = pd.getReadMethod(); Object o = readMethod.invoke(no, new Object[0]); if (o != null) { Class<?> targetClass = pd.getPropertyType(); if (root) { String targetClassName = targetClass.getName(); if (isProxy(o, targetClassName)) { o = deproxyObject(targetClass, o); } Set<PropertyDescriptor> ids = idsByClassName.get(targetClassName); o = deproxyNakedObject(root, collectionsByClassName.get(targetClassName), lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName), linkedFilesByClassName.get(targetClassName), (INakedObject) o, ids, oldIdByNewId, em, deproxyContext); pd.getWriteMethod().invoke(no, o); } else { Object lazyObj = newLazyObject(targetClass); pd.getWriteMethod().invoke(no, lazyObj); } } } } if (eagers != null) { for (PropertyDescriptor pd : eagers) { String targetClassName = pd.getPropertyType().getName(); Method readMethod = pd.getReadMethod(); Object o = readMethod.invoke(no, new Object[0]); if (o != null) { Set<PropertyDescriptor> ids = idsByClassName.get(targetClassName); deproxyNakedObject(root, collectionsByClassName.get(targetClassName), lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName), linkedFilesByClassName.get(targetClassName), (INakedObject) o, ids, oldIdByNewId, em, deproxyContext); } } } if (oldIdByNewId != null && idPds != null) { Map<Object, Object> map2 = oldIdByNewId.get(no.getClass().getName()); if (map2 != null && !map2.isEmpty()) { for (PropertyDescriptor pd : idPds) { Object id = pd.getReadMethod().invoke(no, StorageService.emptyArg); Object oldId = map2.get(id); if (oldId != null) { pd.getWriteMethod().invoke(no, new Object[] { oldId }); } } } } try { em.remove(no); } catch (Exception e) { } return no; }
From source file:play.modules.swagger.PlayReader.java
private Operation parseMethod(Class<?> cls, Method method, Route route) { Operation operation = new Operation(); ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId = method.getName(); operation.operationId(operationId);/*from ww w .jav a2s . c o m*/ String responseContainer = null; Type responseType = null; Map<String, Property> defaultResponseHeaders = new HashMap<>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!"".equals(apiOperation.nickname())) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (apiOperation.response() != null && !isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!"".equals(apiOperation.responseContainer())) { responseContainer = apiOperation.responseContainer(); } if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { securities.forEach(operation::security); } } if (apiOperation.consumes() != null && !apiOperation.consumes().isEmpty()) { operation.consumes(Arrays.asList(toArray(apiOperation.consumes()))); } if (apiOperation.produces() != null && !apiOperation.produces().isEmpty()) { operation.produces(Arrays.asList(toArray(apiOperation.produces()))); } } if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration responseType = method.getGenericReturnType(); } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = apiOperation == null ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModels(responseType); } } operation.operationId(operationId); if (responseAnnotation != null) { for (ApiResponse apiResponse : responseAnnotation.value()) { Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders()); Response response = new Response().description(apiResponse.message()).headers(responseHeaders); if (apiResponse.code() == 0) { operation.defaultResponse(response); } else { operation.response(apiResponse.code(), response); } if (StringUtils.isNotEmpty(apiResponse.reference())) { response.schema(new RefProperty(apiResponse.reference())); } else if (!isVoid(apiResponse.response())) { responseType = apiResponse.response(); final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property)); appendModels(responseType); } } } } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } List<Parameter> parameters = getParameters(cls, method, route); parameters.forEach(operation::parameter); if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.defaultResponse(response); } return operation; }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private void deproxyCollection(INakedObject no, Method readMethod, Method writeMethod, Collection originalColl, Map<String, Map<Object, Object>> oldIdByNewId, EntityManager em, Map<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>> deproxyContext) throws InstantiationException, IllegalAccessException, IntrospectionException, InvocationTargetException, ClassNotFoundException, PersistenceException { if (!(originalColl instanceof ILazy)) { Collection targetColl;//from www .j a v a 2 s. c om if (List.class.isAssignableFrom(readMethod.getReturnType())) { targetColl = new ArrayList(originalColl.size()); } else { targetColl = new HashSet(originalColl.size()); } Type type = readMethod.getGenericReturnType(); Class classInCollection = null; if (type instanceof ParameterizedType) { classInCollection = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; } if (classInCollection != null) { if (Number.class.isAssignableFrom(classInCollection) || String.class.equals(classInCollection) || Boolean.class.equals(classInCollection)) { targetColl.addAll((Collection) readMethod.invoke(no, new Object[0])); } else { for (Object obj : originalColl) { String targetClassName = classInCollection.getName(); if (isProxy(obj, targetClassName)) { obj = deproxyObject(classInCollection, obj); } Set<PropertyDescriptor> idPds = idsByClassName.get(targetClassName); targetColl.add(deproxyNakedObject(false, collectionsByClassName.get(targetClassName), lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName), linkedFilesByClassName.get(targetClassName), (INakedObject) obj, idPds, oldIdByNewId, em, deproxyContext)); } } writeMethod.invoke(no, targetColl); } } }
From source file:plugins.PlayReader.java
private Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters) { Operation operation = new Operation(); ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId = method.getName(); String responseContainer = null; Type responseType = null;//from www .j av a 2 s . c o m Map<String, Property> defaultResponseHeaders = new HashMap<String, Property>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!"".equals(apiOperation.nickname())) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (apiOperation.response() != null && !isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!"".equals(apiOperation.responseContainer())) { responseContainer = apiOperation.responseContainer(); } if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) { operation.security(sec); } } } if (apiOperation.consumes() != null && !apiOperation.consumes().isEmpty()) { operation.consumes(apiOperation.consumes()); } if (apiOperation.produces() != null && !apiOperation.produces().isEmpty()) { operation.produces(apiOperation.produces()); } } if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration Logger.debug("picking up response class from method " + method); responseType = method.getGenericReturnType(); } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = apiOperation == null ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModels(responseType); } } operation.operationId(operationId); if (apiOperation != null && apiOperation.consumes() != null && apiOperation.consumes().isEmpty()) { final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(mediaType); } } } if (apiOperation != null && apiOperation.produces() != null && apiOperation.produces().isEmpty()) { final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : ReaderUtils.splitContentValues(produces.value())) { operation.produces(mediaType); } } } List<ApiResponse> apiResponses = new ArrayList<ApiResponse>(); if (responseAnnotation != null) { for (ApiResponse apiResponse : responseAnnotation.value()) { Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders()); Response response = new Response().description(apiResponse.message()).headers(responseHeaders); if (apiResponse.code() == 0) { operation.defaultResponse(response); } else { operation.response(apiResponse.code(), response); } if (StringUtils.isNotEmpty(apiResponse.reference())) { response.schema(new RefProperty(apiResponse.reference())); } else if (!isVoid(apiResponse.response())) { responseType = apiResponse.response(); final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property)); appendModels(responseType); } } } } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters for (Parameter globalParameter : globalParameters) { operation.parameter(globalParameter); } Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i])); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.defaultResponse(response); } return operation; }
From source file:io.swagger.jaxrs.Reader.java
private Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters) { Operation operation = new Operation(); ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId = method.getName(); String responseContainer = null; Type responseType = null;/* w w w . j a v a 2s. c o m*/ Map<String, Property> defaultResponseHeaders = new HashMap<String, Property>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!"".equals(apiOperation.nickname())) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (apiOperation.response() != null && !isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!"".equals(apiOperation.responseContainer())) { responseContainer = apiOperation.responseContainer(); } if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) { operation.security(sec); } } } if (apiOperation.consumes() != null && !apiOperation.consumes().isEmpty()) { operation.consumes(apiOperation.consumes()); } if (apiOperation.produces() != null && !apiOperation.produces().isEmpty()) { operation.produces(apiOperation.produces()); } } if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseType = method.getGenericReturnType(); } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = apiOperation == null ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModels(responseType); } } operation.operationId(operationId); if (apiOperation != null && apiOperation.consumes() != null && apiOperation.consumes().isEmpty()) { final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(mediaType); } } } if (apiOperation != null && apiOperation.produces() != null && apiOperation.produces().isEmpty()) { final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : ReaderUtils.splitContentValues(produces.value())) { operation.produces(mediaType); } } } List<ApiResponse> apiResponses = new ArrayList<ApiResponse>(); if (responseAnnotation != null) { apiResponses.addAll(Arrays.asList(responseAnnotation.value())); } Class<?>[] exceptionTypes = method.getExceptionTypes(); for (Class<?> exceptionType : exceptionTypes) { ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class); if (exceptionResponses != null) { apiResponses.addAll(Arrays.asList(exceptionResponses.value())); } } for (ApiResponse apiResponse : apiResponses) { Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders()); Response response = new Response().description(apiResponse.message()).headers(responseHeaders); if (apiResponse.code() == 0) { operation.defaultResponse(response); } else { operation.response(apiResponse.code(), response); } if (StringUtils.isNotEmpty(apiResponse.reference())) { response.schema(new RefProperty(apiResponse.reference())); } else if (!isVoid(apiResponse.response())) { responseType = apiResponse.response(); final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property)); appendModels(responseType); } } } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters for (Parameter globalParameter : globalParameters) { operation.parameter(globalParameter); } Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i])); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.defaultResponse(response); } return operation; }