List of usage examples for java.lang.reflect Type equals
public boolean equals(Object obj)
From source file:io.swagger.client.ApiClient.java
/** * Deserialize response body to Java object, according to the return type and * the Content-Type response header./*w w w .j a v a 2 s . c o m*/ * * @param <T> Type * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ @SuppressWarnings("unchecked") public <T> T deserialize(Response response, Type returnType) throws ApiException, IOException { if (response == null || returnType == null) { return null; } if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). try { return (T) response.body().bytes(); } catch (IOException e) { throw new ApiException(e); } } else if (returnType.equals(File.class)) { // Handle file downloading. return (T) downloadFileFromResponse(response); } String respBody; try { if (response.body() != null) respBody = response.body().string(); else respBody = null; } catch (IOException e) { throw new ApiException(e); } if (respBody == null || "".equals(respBody)) { return null; } String contentType = response.headers().get("Content-Type"); if (contentType == null) { // ensuring a default content type contentType = "application/json"; } else if (contentType.equals("application/xml")) { if (XML.toJSONObject(respBody).has("TaskList")) { JSONObject rootElement = (JSONObject) XML.toJSONObject(respBody).get("TaskList"); return this.json.deserialize( ((JSONArray) ((JSONObject) rootElement.get("Tasks")).get("Tasks")).toString(), returnType); } } if (isJsonMime(contentType)) { if (new JSONObject(respBody).has("Tasks")) { return json.deserialize(new JSONObject(respBody).get("Tasks").toString(), returnType); } else { return json.deserialize(respBody, returnType); } } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. return (T) respBody; } else { throw new ApiException("Content type \"" + contentType + "\" is not supported for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); } }
From source file:io.sinistral.proteus.server.tools.swagger.Reader.java
@SuppressWarnings("deprecation") private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod, List<Parameter> globalParameters, List<ApiResponse> classApiResponses, List<String> pathParamNames) { Operation operation = new Operation(); if (annotatedMethod != null) { method = annotatedMethod.getAnnotated(); }//from w ww . j av a 2s.c om ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId; // check if it's an inherited or implemented method. boolean methodInSuperType = false; if (!cls.isInterface()) { methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null; } if (!methodInSuperType) { for (Class<?> implementedInterface : cls.getInterfaces()) { methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null; if (methodInSuperType) { break; } } } if (!methodInSuperType) { operationId = method.getName(); } else { operationId = this.getOperationId(method.getName()); } String responseContainer = null; Type responseType = null; Map<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (operationId == null) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (!isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } if (!apiOperation.consumes().isEmpty()) { String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() }); for (String consume : consumesAr) { operation.consumes(consume); } } if (!apiOperation.produces().isEmpty()) { String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() }); for (String produce : producesAr) { operation.produces(produce); } } } /* * @TODO * Use apiOperation response class instead of unwrapping ServerResponse's inner type */ 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 (responseType != null) { final JavaType javaType = TypeFactory.defaultInstance().constructType(responseType); if (!isVoid(javaType)) { final Class<?> responseCls = javaType.getRawClass(); if (responseCls != null) { if (responseCls.isAssignableFrom(ServerResponse.class)) { responseType = javaType.containedType(0); } else if (responseCls.isAssignableFrom(CompletableFuture.class)) { Class<?> futureCls = javaType.containedType(0).getRawClass(); if (futureCls.isAssignableFrom(ServerResponse.class)) { final JavaType futureType = TypeFactory.defaultInstance() .constructType(javaType.containedType(0)); responseType = futureType.containedType(0); } else { responseType = javaType.containedType(0); } } } } } 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 (operation.getConsumes() == null || operation.getConsumes().isEmpty()) { final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(mediaType); } } } if (operation.getProduces() == null || operation.getProduces().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<>(); 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) { addResponse(operation, apiResponse); } // merge class level @ApiResponse for (ApiResponse apiResponse : classApiResponses) { String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code()); if (operation.getResponses() != null && operation.getResponses().containsKey(key)) { continue; } addResponse(operation, apiResponse); } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters for (Parameter globalParameter : globalParameters) { LOGGER.debug("globalParameters TYPE: " + globalParameter); operation.parameter(globalParameter); } Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method); java.lang.reflect.Parameter[] methodParameters = method.getParameters(); if (annotatedMethod == null) { Type[] genericParameterTypes = method.getGenericParameterTypes(); for (int i = 0; i < genericParameterTypes.length; i++) { Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); if (type.getTypeName().contains("Optional") || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) { if (type instanceof com.fasterxml.jackson.databind.type.SimpleType) { com.fasterxml.jackson.databind.type.SimpleType simpleType = (com.fasterxml.jackson.databind.type.SimpleType) type; type = simpleType.containedType(0); } } if (type.equals(ServerRequest.class) || type.equals(HttpServerExchange.class) || type.equals(HttpHandler.class) || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) { continue; } List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]), methodParameters[i], pathParamNames); for (Parameter parameter : parameters) { operation.parameter(parameter); } } } else { for (int i = 0; i < annotatedMethod.getParameterCount(); i++) { AnnotatedParameter param = annotatedMethod.getParameter(i); if (param.getParameterType().equals(ServerRequest.class) || param.getParameterType().equals(HttpServerExchange.class) || param.getParameterType().equals(HttpHandler.class) || param.getParameterType().getTypeName().contains("ServerResponse")) { continue; } Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]), methodParameters[i], pathParamNames); for (Parameter parameter : parameters) { operation.parameter(parameter); } } } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.response(200, response); } processOperationDecorator(operation, method); return operation; }
From source file:org.evosuite.testcase.TestCodeVisitor.java
private String getParameterString(Type[] parameterTypes, List<VariableReference> parameters, boolean isGenericMethod, boolean isOverloaded, int startPos) { String parameterString = ""; for (int i = startPos; i < parameters.size(); i++) { if (i > startPos) { parameterString += ", "; }/* w w w .j a v a 2 s. co m*/ Type declaredParamType = parameterTypes[i]; Type actualParamType = parameters.get(i).getType(); String name = getVariableName(parameters.get(i)); Class<?> rawParamClass = declaredParamType instanceof WildcardType ? Object.class : GenericTypeReflector.erase(declaredParamType); if (rawParamClass.isPrimitive() && name.equals("null")) { parameterString += getPrimitiveNullCast(rawParamClass); } else if (isGenericMethod && !(declaredParamType instanceof WildcardType)) { if (!declaredParamType.equals(actualParamType) || name.equals("null")) { parameterString += "(" + getTypeName(declaredParamType) + ") "; if (name.contains("(short")) name = name.replace("(short)", ""); if (name.contains("(byte")) name = name.replace("(byte)", ""); } } else if (name.equals("null")) { parameterString += "(" + getTypeName(declaredParamType) + ") "; } else if (!GenericClass.isAssignable(declaredParamType, actualParamType)) { if (TypeUtils.isArrayType(declaredParamType) && TypeUtils.isArrayType(actualParamType)) { Class<?> componentClass = GenericTypeReflector.erase(declaredParamType).getComponentType(); if (componentClass.equals(Object.class)) { GenericClass genericComponentClass = new GenericClass(componentClass); if (genericComponentClass.hasWildcardOrTypeVariables()) { // If we are assigning a generic array, then we don't need to cast } else { // If we are assigning a non-generic array, then we do need to cast parameterString += "(" + getTypeName(declaredParamType) + ") "; } } else { //if (!GenericClass.isAssignable(GenericTypeReflector.getArrayComponentType(declaredParamType), GenericTypeReflector.getArrayComponentType(actualParamType))) { parameterString += "(" + getTypeName(declaredParamType) + ") "; } } else if (!(actualParamType instanceof ParameterizedType)) { parameterString += "(" + getTypeName(declaredParamType) + ") "; } if (name.contains("(short")) name = name.replace("(short)", ""); if (name.contains("(byte")) name = name.replace("(byte)", ""); //} } else { // We have to cast between wrappers and primitives in case there // are overloaded signatures. This could be optimized by checking // if there actually is a problem of overloaded signatures GenericClass parameterClass = new GenericClass(declaredParamType); if (parameterClass.isWrapperType() && parameters.get(i).isPrimitive()) { parameterString += "(" + getTypeName(declaredParamType) + ") "; } else if (parameterClass.isPrimitive() && parameters.get(i).isWrapperType()) { parameterString += "(" + getTypeName(declaredParamType) + ") "; } else if (isOverloaded) { // If there is an overloaded method, we need to cast to make sure we use the right version if (!declaredParamType.equals(actualParamType)) { parameterString += "(" + getTypeName(declaredParamType) + ") "; } } } parameterString += name; } return parameterString; }
From source file:org.evosuite.utils.generic.GenericUtils.java
public static Type replaceTypeVariable(Type targetType, TypeVariable<?> variable, Type variableType) { if (targetType instanceof Class<?>) return targetType; else if (targetType instanceof GenericArrayType) { GenericArrayType gType = (GenericArrayType) targetType; Type componentType = replaceTypeVariable(gType.getGenericComponentType(), variable, variableType); return GenericArrayTypeImpl.createArrayType(componentType); } else if (targetType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) targetType; Type ownerType = null;//from w w w . java 2 s .c o m if (pType.getOwnerType() != null) { ownerType = replaceTypeVariable(pType.getOwnerType(), variable, variableType); } Type[] originalParameterTypes = pType.getActualTypeArguments(); Type[] parameterTypes = new Type[originalParameterTypes.length]; for (int i = 0; i < originalParameterTypes.length; i++) { parameterTypes[i] = replaceTypeVariable(originalParameterTypes[i], variable, variableType); } /* if (variableType instanceof ParameterizedType) { ParameterizedType parameterizedVars = (ParameterizedType) variableType; Map<TypeVariable<?>, Type> subTypes = TypeUtils.getTypeArguments(parameterizedVars); for (Entry<TypeVariable<?>, Type> subTypeEntry : subTypes.entrySet()) { if (pType.getOwnerType() != null) { ownerType = replaceTypeVariable(pType.getOwnerType(), subTypeEntry.getKey(), subTypeEntry.getValue()); } for (int i = 0; i < originalParameterTypes.length; i++) { parameterTypes[i] = replaceTypeVariable(originalParameterTypes[i], subTypeEntry.getKey(), subTypeEntry.getValue()); } } } */ return new ParameterizedTypeImpl((Class<?>) pType.getRawType(), parameterTypes, ownerType); } else if (targetType instanceof WildcardType) { WildcardType wType = (WildcardType) targetType; Type[] originalUpperBounds = wType.getUpperBounds(); Type[] originalLowerBounds = wType.getLowerBounds(); Type[] upperBounds = new Type[originalUpperBounds.length]; Type[] lowerBounds = new Type[originalLowerBounds.length]; for (int i = 0; i < originalUpperBounds.length; i++) { upperBounds[i] = replaceTypeVariable(originalUpperBounds[i], variable, variableType); } for (int i = 0; i < originalLowerBounds.length; i++) { lowerBounds[i] = replaceTypeVariable(originalLowerBounds[i], variable, variableType); } return new WildcardTypeImpl(upperBounds, lowerBounds); } else if (targetType instanceof TypeVariable<?>) { if (targetType.equals(variable)) { //logger.debug("Do equal: " + variable + "/" + targetType); return variableType; } else { //logger.debug("Do not equal: " + variable + "/" + targetType); //logger.debug("Do not equal: " + variable.getGenericDeclaration() + "/" // + ((TypeVariable<?>) targetType).getGenericDeclaration()); return targetType; } } else { //logger.debug("Unknown type of class " + targetType.getClass() + ": " // + targetType); return targetType; } }
From source file:org.evosuite.testcase.TestFactory.java
/** * Create a new variable or reuse and existing one * * @param test/*from www . j av a 2 s. c om*/ * @param parameterType * @param position * @param recursionDepth * @param exclude * @return * @throws ConstructionFailedException */ private VariableReference createOrReuseVariable(TestCase test, Type parameterType, int position, int recursionDepth, VariableReference exclude, boolean allowNull, boolean excludeCalleeGenerators, boolean canUseMocks) throws ConstructionFailedException { if (Properties.SEED_TYPES && parameterType.equals(Object.class)) { return createOrReuseObjectVariable(test, position, recursionDepth, exclude, allowNull, canUseMocks); } double reuse = Randomness.nextDouble(); List<VariableReference> objects = getCandidatesForReuse(test, parameterType, position, exclude, allowNull, canUseMocks); GenericClass clazz = new GenericClass(parameterType); boolean isPrimitiveOrSimilar = clazz.isPrimitive() || clazz.isWrapperType() || clazz.isEnum() || clazz.isClass() || clazz.isString(); if (isPrimitiveOrSimilar && !objects.isEmpty() && reuse <= Properties.PRIMITIVE_REUSE_PROBABILITY) { logger.debug(" Looking for existing object of type {}", parameterType); VariableReference reference = Randomness.choice(objects); return reference; } else if (!isPrimitiveOrSimilar && !objects.isEmpty() && (reuse <= Properties.OBJECT_REUSE_PROBABILITY)) { if (logger.isDebugEnabled()) { logger.debug(" Choosing from {} existing objects: {}", objects.size(), Arrays.toString(objects.toArray())); } VariableReference reference = Randomness.choice(objects); logger.debug(" Using existing object of type {}: {}", parameterType, reference); return reference; } //if chosen to not re-use existing variable, try create a new one VariableReference created = createVariable(test, parameterType, position, recursionDepth, exclude, allowNull, excludeCalleeGenerators, canUseMocks, true); if (created != null) { return created; } //could not create, so go back in trying to re-use an existing variable if (objects.isEmpty()) { if (allowNull) { return createNull(test, parameterType, position, recursionDepth); } else { throw new ConstructionFailedException("No objects and generators for type " + parameterType); } } if (logger.isDebugEnabled()) { logger.debug(" Choosing from {} existing objects: {}", objects.size(), Arrays.toString(objects.toArray())); } VariableReference reference = Randomness.choice(objects); assert canUseMocks || !(test.getStatement(reference.getStPosition()) instanceof FunctionalMockStatement); logger.debug(" Using existing object of type {}: {}", parameterType, reference); return reference; }
From source file:org.kitodo.services.data.ProcessService.java
/** * Returns the batches of the desired type for a process. * * @param type/*from w ww . j av a 2 s . c o m*/ * of batches to return * @return all batches of the desired type */ public List<Batch> getBatchesByType(Process process, Type type) { List<Batch> batches = getBatchesInitialized(process); if (type != null) { List<Batch> result = new ArrayList<>(batches); Iterator<Batch> indicator = result.iterator(); while (indicator.hasNext()) { if (!type.equals(indicator.next().getType())) { indicator.remove(); } } return result; } return batches; }
From source file:org.evosuite.testcase.ImportsTestCodeVisitor.java
private void collectFromParameters(Type[] parameterTypes, List<VariableReference> parameters, boolean isGenericMethod, boolean isOverloaded, int startPos) { for (int i = startPos; i < parameters.size(); i++) { Type declaredParamType = parameterTypes[i]; Type actualParamType = parameters.get(i).getType(); getClassName(declaredParamType); getClassName(parameters.get(i)); Class<?> rawParamClass = declaredParamType instanceof WildcardType ? Object.class : GenericTypeReflector.erase(declaredParamType); if (rawParamClass.isPrimitive()) { getClassName(rawParamClass); getClassName(ClassUtils.primitiveToWrapper(rawParamClass)); } else if (isGenericMethod && !(declaredParamType instanceof WildcardType)) { } else if (!GenericClass.isAssignable(declaredParamType, actualParamType)) { if (TypeUtils.isArrayType(declaredParamType) && TypeUtils.isArrayType(actualParamType)) { Class<?> componentClass = GenericTypeReflector.erase(declaredParamType).getComponentType(); if (componentClass.equals(Object.class)) { GenericClass genericComponentClass = new GenericClass(componentClass); if (genericComponentClass.hasWildcardOrTypeVariables()) { // If we are assigning a generic array, then we don't need to cast } else { // If we are assigning a non-generic array, then we do need to cast getClassName(declaredParamType); }/*w ww .ja v a 2 s . c o m*/ } else { //if (!GenericClass.isAssignable(GenericTypeReflector.getArrayComponentType(declaredParamType), GenericTypeReflector.getArrayComponentType(actualParamType))) { getClassName(declaredParamType); } } else if (!(actualParamType instanceof ParameterizedType)) { getClassName(declaredParamType); } } else { // We have to cast between wrappers and primitives in case there // are overloaded signatures. This could be optimized by checking // if there actually is a problem of overloaded signatures GenericClass parameterClass = new GenericClass(declaredParamType); if (parameterClass.isWrapperType() && parameters.get(i).isPrimitive()) { getClassName(declaredParamType); } else if (parameterClass.isPrimitive() && parameters.get(i).isWrapperType()) { getClassName(declaredParamType); } else if (isOverloaded) { // If there is an overloaded method, we need to cast to make sure we use the right version if (!declaredParamType.equals(actualParamType)) { getClassName(declaredParamType); } } } } }
From source file:com.clark.func.Functions.java
/** * <p>//from w ww . j av a2 s . c o m * Checks if the subject type may be implicitly cast to the target * parameterized type following the Java generics rules. * </p> * * @param type * the subject type to be assigned to the target type * @param toParameterizedType * the target parameterized type * @return true if <code>type</code> is assignable to <code>toType</code>. */ private static boolean isAssignable(Type type, ParameterizedType toParameterizedType, Map<TypeVariable<?>, Type> typeVarAssigns) { if (type == null) { return true; } // only a null type can be assigned to null type which // would have cause the previous to return true if (toParameterizedType == null) { return false; } // all types are assignable to themselves if (toParameterizedType.equals(type)) { return true; } // get the target type's raw type Class<?> toClass = getRawType(toParameterizedType); // get the subject type's type arguments including owner type arguments // and supertype arguments up to and including the target class. Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(type, toClass, null); // null means the two types are not compatible if (fromTypeVarAssigns == null) { return false; } // compatible types, but there's no type arguments. this is equivalent // to comparing Map< ?, ? > to Map, and raw types are always assignable // to parameterized types. if (fromTypeVarAssigns.isEmpty()) { return true; } // get the target type's type arguments including owner type arguments Map<TypeVariable<?>, Type> toTypeVarAssigns = getTypeArguments(toParameterizedType, toClass, typeVarAssigns); // now to check each type argument for (Map.Entry<TypeVariable<?>, Type> entry : toTypeVarAssigns.entrySet()) { Type toTypeArg = entry.getValue(); Type fromTypeArg = fromTypeVarAssigns.get(entry.getKey()); // parameters must either be absent from the subject type, within // the bounds of the wildcard type, or be an exact match to the // parameters of the target type. if (fromTypeArg != null && !toTypeArg.equals(fromTypeArg) && !(toTypeArg instanceof WildcardType && isAssignable(fromTypeArg, toTypeArg, typeVarAssigns))) { return false; } } return true; }