How to use Object method of org.evomaster.client.java.controller.problem.rpc.schema.params.ObjectParam class

Best EvoMaster code snippet using org.evomaster.client.java.controller.problem.rpc.schema.params.ObjectParam.Object

Source:RPCEndpointsBuilder.java Github

copy

Full Screen

1package org.evomaster.client.java.controller.problem.rpc;2import com.fasterxml.jackson.core.JsonProcessingException;3import com.fasterxml.jackson.databind.JsonNode;4import com.fasterxml.jackson.databind.ObjectMapper;5import org.evomaster.client.java.controller.api.dto.AuthenticationDto;6import org.evomaster.client.java.controller.api.dto.CustomizedRequestValueDto;7import org.evomaster.client.java.controller.api.dto.JsonAuthRPCEndpointDto;8import org.evomaster.client.java.controller.problem.rpc.schema.LocalAuthSetupSchema;9import org.evomaster.client.java.controller.problem.rpc.schema.params.*;10import org.evomaster.client.java.controller.problem.rpc.schema.types.*;11import org.evomaster.client.java.controller.api.dto.problem.rpc.RPCType;12import org.evomaster.client.java.controller.problem.rpc.schema.EndpointSchema;13import org.evomaster.client.java.controller.problem.rpc.schema.InterfaceSchema;14import org.evomaster.client.java.utils.SimpleLogger;15import java.lang.annotation.Annotation;16import java.lang.reflect.*;17import java.math.BigDecimal;18import java.math.BigInteger;19import java.nio.ByteBuffer;20import java.util.*;21import java.util.stream.Collectors;22/**23 * created by manzhang on 2021/11/424 */25public class RPCEndpointsBuilder {26 private final static ObjectMapper objectMapper = new ObjectMapper();27 private final static String OBJECT_FLAG = "OBJECT";28 private static String getObjectTypeNameWithFlag(Class<?> clazz, String name) {29 if (isNotCustomizedObject(clazz)) return name;30 return OBJECT_FLAG + ":" + name;31 }32 private static boolean isNotCustomizedObject(Class<?> clazz){33 return PrimitiveOrWrapperType.isPrimitiveOrTypes(clazz) || clazz == String.class ||34 clazz == ByteBuffer.class || clazz.isEnum() || clazz.isArray() ||35 List.class.isAssignableFrom(clazz) || Set.class.isAssignableFrom(clazz);36 }37 /**38 * validate CustomizedRequestValueDto, eg,39 * 1) for any CustomizedRequestValueDto, keyValuePairs and keyValues could not be specified or null at the same time40 * 2) for keyValuePairs, if annotationOnEndpoint or specificEndpointName or specificRequestTypeName are specified, they should have consistent keys41 * 3) keyValues with respect to any specific annotationOnEndpoint or specificEndpointName or specificRequestTypeName should be specified only one time42 * @param customizedRequestValueDtos are customized info to be checked43 */44 public static void validateCustomizedValueInRequests(List<CustomizedRequestValueDto> customizedRequestValueDtos){45 if (customizedRequestValueDtos == null || customizedRequestValueDtos.isEmpty()) return;46 customizedRequestValueDtos.forEach(s->{47 if (s.keyValues != null && s.combinedKeyValuePairs != null)48 throw new IllegalArgumentException("Driver Config Error: keyValues and keyValuePairs should not be specified at the same time");49 if (s.keyValues == null && s.combinedKeyValuePairs == null)50 throw new IllegalArgumentException("Driver Config Error: one of keyValues and keyValuePairs must be specified, could not be null at the same time");51 });52 validateKeyValuePairs(customizedRequestValueDtos);53 validateKeyValues(customizedRequestValueDtos);54 }55 /**56 * validate specified notNullAnnotations57 * @param notNullAnnotations are specified customized annotation representing if any field of RPC dto is required58 */59 public static void validateCustomizedNotNullAnnotationForRPCDto(List<CustomizedNotNullAnnotationForRPCDto> notNullAnnotations){60 if (notNullAnnotations == null || notNullAnnotations.isEmpty()) return;61 notNullAnnotations.forEach(s->{62 if (s.annotationType == null)63 throw new IllegalArgumentException("Driver Config Error: annotationType should not be null");64 if ((s.annotationMethod == null) ^ (s.equalsTo == null))65 throw new IllegalArgumentException("Driver Config Error: annotationMethod and equalsTo should be specified at the same time");66 });67 }68 private static void validateKeyValues(List<CustomizedRequestValueDto> customizedRequestValueDtos){69 List<String> handled = new ArrayList<>();70 customizedRequestValueDtos.stream().filter(s-> s.keyValues !=null).forEach(s->{71 if (s.keyValues.key == null)72 throw new IllegalArgumentException("Driver Config Error: key must be specified when customizing keyValues");73 if (s.keyValues.values.isEmpty()){74 throw new IllegalArgumentException("Driver Config Error: at least one values is needed for customizing keyValues with the key "+s.keyValues.key);75 }76 String key = "key:"+s.keyValues.key+""+getKeyForCustomizedRequestValueDto(s);77 if (handled.contains(key))78 throw new IllegalArgumentException("Driver Config Error: "+key+" should be specified only once");79 handled.add(key);80 });81 }82 private static void validateKeyValuePairs(List<CustomizedRequestValueDto> customizedRequestValueDtos){83 Map<String, List<CustomizedRequestValueDto>> group = new HashMap<>();84 customizedRequestValueDtos.stream().filter(s-> s.combinedKeyValuePairs !=null && !s.combinedKeyValuePairs.isEmpty()).forEach(s->{85 String key = getKeyForCustomizedRequestValueDto(s);86 if (key.length() != 0){87 if (!group.containsKey(key))88 group.put(key, new ArrayList<>());89 group.get(key).add(s);90 }91 });92 group.forEach((key, g) -> {93 if (g.size() > 1) {94 List<String> keys = g.get(0).combinedKeyValuePairs.stream().map(a -> a.fieldKey).collect(Collectors.toList());95 g.forEach(a -> {96 List<String> akeys = a.combinedKeyValuePairs.stream().map(k -> k.fieldKey).collect(Collectors.toList());97 if (akeys.size() != keys.size() || !akeys.containsAll(keys)) {98 throw new IllegalArgumentException("Driver Config Error: keys for same " + key + " must be specified with same keys");99 }100 });101 }102 });103 }104 private static String getKeyForCustomizedRequestValueDto(CustomizedRequestValueDto s){105 String key = "";106 if (s.annotationOnEndpoint != null)107 key += " annotationOnEndpoint_"+s.annotationOnEndpoint;108 if (s.specificEndpointName != null)109 key += " specificEndpointName_"+s.specificEndpointName;110 if (s.specificRequestTypeName != null)111 key += " specificRequestTypeName_"+s.specificRequestTypeName;112 return key;113 }114 /**115 * @param interfaceName the name of interface116 * @param rpcType is the type of RPC, e.g., gRPC, Thrift117 * @param client is the corresponding client to maniplute the interface118 * @param skipEndpointsByName specifies a list of names of endpoints to be skipped during testing119 * @param skipEndpointsByAnnotation specifies a list of annotations applied on endpoints that could be skipped during testing120 * @param involveEndpointsByName specifies a list of names of endpoints to be involved during testing121 * @param involveEndpointsByAnnotation specifies a list of annotations applied on endpoints that are involved during testing122 * @param authenticationDtoList specifies a list of authentication info123 * @param customizedRequestValueDtos specifies a list of candidate values in requests124 * @return an interface schema for evomaster to access125 */126 public static InterfaceSchema build(String interfaceName, RPCType rpcType, Object client,127 List<String> skipEndpointsByName, List<String> skipEndpointsByAnnotation,128 List<String> involveEndpointsByName, List<String> involveEndpointsByAnnotation,129 List<AuthenticationDto> authenticationDtoList,130 List<CustomizedRequestValueDto> customizedRequestValueDtos,131 List<CustomizedNotNullAnnotationForRPCDto> notNullAnnotations) {132 List<EndpointSchema> endpoints = new ArrayList<>();133 List<EndpointSchema> endpointsForAuth = new ArrayList<>();134 List<String> skippedEndpoints = new ArrayList<>();135 Map<Integer, EndpointSchema> authEndpoints = new HashMap<>();136 try {137 Class<?> interfaze = Class.forName(interfaceName);138 InterfaceSchema schema = new InterfaceSchema(interfaceName, endpoints, getClientClass(client) , rpcType, skippedEndpoints, authEndpoints, endpointsForAuth);139 for (Method m : interfaze.getDeclaredMethods()) {140 if (filterMethod(m, skipEndpointsByName, skipEndpointsByAnnotation, involveEndpointsByName, involveEndpointsByAnnotation)){141 try{142 EndpointSchema endpointSchema = build(schema, m, rpcType, authenticationDtoList, customizedRequestValueDtos, notNullAnnotations);143 endpoints.add(endpointSchema);144 }catch (RuntimeException exception){145 /*146 TODO might send such log to core in order to better identify problems which is not handled yet147 */148 SimpleLogger.error("EM Driver Error: fail to handle the endpoint schema "+m.getName()+" with the error msg:"+exception.getMessage());149 }150 } else {151 skippedEndpoints.add(m.getName());152 }153 List<AuthenticationDto> auths = getAuthEndpointInInterface(authenticationDtoList, interfaceName, m);154 if (auths != null && !auths.isEmpty()){155 try{156 // handle endpoint which is for auth setup157 EndpointSchema authEndpoint = build(schema, m, rpcType, null, customizedRequestValueDtos,notNullAnnotations);158 endpointsForAuth.add(authEndpoint);159 for (AuthenticationDto auth: auths){160 EndpointSchema copy = authEndpoint.copyStructure();161 if (auth.jsonAuthEndpoint == null){162 throw new IllegalArgumentException("Driver Config Error: now we only support auth info specified with JsonAuthRPCEndpointDto");163 }164 int index = authenticationDtoList.indexOf(auth);165 // set value based on specified info166 if (copy.getRequestParams().size() != auth.jsonAuthEndpoint.jsonPayloads.size())167 throw new IllegalArgumentException("Driver Config Error: mismatched size of jsonPayloads ("+auth.jsonAuthEndpoint.classNames.size()+") with real endpoint ("+authEndpoint.getRequestParams().size()+").");168 setAuthEndpoint(copy, auth.jsonAuthEndpoint);169 authEndpoints.put(index, copy);170 }171 }catch (RuntimeException exception){172 SimpleLogger.error("EM Driver Error: fail to handle the authEndpoint schema "+m.getName()+" with the error msg:"+exception.getMessage());173 }174 }175 }176 return schema;177 } catch (ClassNotFoundException e) {178 throw new RuntimeException("cannot find the interface with the name (" + interfaceName + ") and the error message is " + e.getMessage());179 }180 }181 /**182 * build the local auth setup183 * @param authenticationDtoList a list of auth info specified by user184 * @return a map of such local auth setup185 * key - index at a list of auth info specified by user186 * value - local endpoint187 */188 public static Map<Integer, LocalAuthSetupSchema> buildLocalAuthSetup(List<AuthenticationDto> authenticationDtoList){189 if (authenticationDtoList==null || authenticationDtoList.isEmpty()) return null;190 Map<Integer, LocalAuthSetupSchema> map = new HashMap<>();191 for (AuthenticationDto dto : authenticationDtoList){192 if (dto.localAuthSetup != null){193 int index = authenticationDtoList.indexOf(dto);194 LocalAuthSetupSchema local = new LocalAuthSetupSchema();195 local.getRequestParams().get(0).setValueBasedOnInstance(dto.localAuthSetup.authenticationInfo);196 map.put(index, local);197 }198 }199 return map;200 }201 private static void setAuthEndpoint(EndpointSchema authEndpoint, JsonAuthRPCEndpointDto jsonAuthEndpoint) throws ClassNotFoundException{202 if (jsonAuthEndpoint.classNames != null && jsonAuthEndpoint.classNames.size() != jsonAuthEndpoint.jsonPayloads.size())203 throw new IllegalArgumentException("Driver Config Error: to specify inputs for auth endpoint, classNames and jsonPayloads should have same size");204 for (int i = 0; i < authEndpoint.getRequestParams().size(); i++){205 NamedTypedValue inputParam = authEndpoint.getRequestParams().get(i);206 String jsonString = jsonAuthEndpoint.jsonPayloads.get(i);207 if (jsonAuthEndpoint.classNames == null){208 setNamedValueBasedOnJsonString(inputParam,jsonString, i);209 }else{210 Class<?> clazz = Class.forName(jsonAuthEndpoint.classNames.get(i));211 try {212 Object value = objectMapper.readValue(jsonString, clazz);213 inputParam.setValueBasedOnInstance(value);214 } catch (JsonProcessingException e) {215 SimpleLogger.uniqueWarn("Driver Config Error: a jsonPayload at ("+i+") cannot be read as the object "+jsonAuthEndpoint.classNames.get(i));216 setNamedValueBasedOnJsonString(inputParam,jsonString, i);217 }218 }219 }220 }221 private static void setNamedValueBasedOnJsonString(NamedTypedValue inputParam, String jsonString, int index){222 if (inputParam instanceof StringParam || inputParam instanceof PrimitiveOrWrapperParam || inputParam instanceof ByteBufferParam){223 setNamedValueBasedOnCandidates(inputParam, jsonString);224 } else if (inputParam instanceof ObjectParam){225 try {226 JsonNode node = objectMapper.readTree(jsonString);227 List<NamedTypedValue> fields = new ArrayList<>();228 for (NamedTypedValue f: ((ObjectParam) inputParam).getType().getFields()){229 NamedTypedValue v = f.copyStructureWithProperties();230 if (node.has(v.getName())){231 setNamedValueBasedOnCandidates(f, node.textValue());232 fields.add(v);233 }else {234 SimpleLogger.uniqueWarn("Driver Config Error: cannot find field with the name "+v.getName()+" in the specified json");235 }236 }237 inputParam.setValue(fields);238 } catch (JsonProcessingException ex) {239 SimpleLogger.uniqueWarn("Driver Config Error: a jsonPayload at ("+index+") cannot be read as a JSON object with error:" +ex.getMessage());240 }241 }242 }243 private static List<AuthenticationDto> getAuthEndpointInInterface(List<AuthenticationDto> authenticationDtos, String interfaceName, Method method){244 if (authenticationDtos == null) return null;245 for (AuthenticationDto dto : authenticationDtos){246 if (dto.localAuthSetup == null && (dto.jsonAuthEndpoint == null || dto.jsonAuthEndpoint.endpointName == null || dto.jsonAuthEndpoint.interfaceName == null)){247 SimpleLogger.uniqueWarn("Driver Config Error: To specify auth for RPC, either localAuthSetup or jsonAuthEndpoint should be specified." +248 "For JsonAuthRPCEndpointDto, endpointName and interfaceName cannot be null");249 }250 }251 return authenticationDtos.stream().filter(a-> a.jsonAuthEndpoint != null252 && a.jsonAuthEndpoint.endpointName.equals(method.getName())253 && a.jsonAuthEndpoint.interfaceName.equals(interfaceName)).collect(Collectors.toList());254 }255 private static boolean filterMethod(Method endpoint,256 List<String> skipEndpointsByName, List<String> skipEndpointsByAnnotation,257 List<String> involveEndpointsByName, List<String> involveEndpointsByAnnotation){258 if (skipEndpointsByName != null && involveEndpointsByName != null)259 throw new IllegalArgumentException("Driver Config Error: skipEndpointsByName and involveEndpointsByName should not be specified at same time.");260 if (skipEndpointsByAnnotation != null && involveEndpointsByAnnotation != null)261 throw new IllegalArgumentException("Driver Config Error: skipEndpointsByAnnotation and involveEndpointsByAnnotation should not be specified at same time.");262 if (skipEndpointsByName != null || skipEndpointsByAnnotation != null)263 return !anyMatchByNameAndAnnotation(endpoint, skipEndpointsByName, skipEndpointsByAnnotation);264 if (involveEndpointsByName != null || involveEndpointsByAnnotation != null)265 return anyMatchByNameAndAnnotation(endpoint, involveEndpointsByName, involveEndpointsByAnnotation);266 return true;267 }268 private static boolean anyMatchByNameAndAnnotation(Method endpoint, List<String> names, List<String> annotations){269 boolean anyMatch = false;270 if (annotations != null){271 for (Annotation annotation : endpoint.getAnnotations()){272 anyMatch = anyMatch || annotations.contains(annotation.annotationType().getName());273 }274 }275 if (names != null)276 anyMatch = anyMatch || names.contains(endpoint.getName());277 return anyMatch;278 }279 private static String getClientClass(Object client){280 if (client == null) return null;281 String clazzType = client.getClass().getName();282 // handle com.sun.proxy283 if (!clazzType.startsWith("com.sun.proxy.")){284 return clazzType;285 }286 Class<?>[] clazz = client.getClass().getInterfaces();287 if (clazz.length == 0){288 SimpleLogger.error("Error: the client is not related to any interface");289 return null;290 }291 if (clazz.length > 1)292 SimpleLogger.error("ERROR: the client has more than one interfaces");293 return clazz[0].getName();294 }295 private static EndpointSchema build(InterfaceSchema schema, Method method, RPCType rpcType, List<AuthenticationDto> authenticationDtoList,296 List<CustomizedRequestValueDto> customizedRequestValueDtos,297 List<CustomizedNotNullAnnotationForRPCDto> notNullAnnotations) {298 List<NamedTypedValue> requestParams = new ArrayList<>();299 List<AuthenticationDto> authAnnotationDtos = getSpecificRelatedAuth(authenticationDtoList, method);300 List<Integer> authKeys = null;301 if (authAnnotationDtos != null)302 authKeys = authAnnotationDtos.stream().map(s-> authenticationDtoList.indexOf(s)).collect(Collectors.toList());303 Set<String> relatedCustomization = new HashSet<>();304 for (Parameter p : method.getParameters()) {305 requestParams.add(buildInputParameter(schema, p, rpcType, getRelatedCustomization(customizedRequestValueDtos, method), relatedCustomization, notNullAnnotations));306 }307 NamedTypedValue response = null;308 if (!method.getReturnType().equals(Void.TYPE)) {309 Map<TypeVariable, Type> genericTypeMap = new HashMap<>();310 response = build(schema, method.getReturnType(), method.getGenericReturnType(), "return", rpcType, new ArrayList<>(), null, null, null, null, null, genericTypeMap);311 }312 List<NamedTypedValue> exceptions = null;313 if (method.getExceptionTypes().length > 0){314 exceptions = new ArrayList<>();315 for (int i = 0; i < method.getExceptionTypes().length; i++){316 NamedTypedValue exception = build(schema, method.getExceptionTypes()[i],317 method.getGenericExceptionTypes()[i], "exception_"+i, rpcType, new ArrayList<>(), null, null, null, null, null, null);318 exceptions.add(exception);319 }320 }321 return new EndpointSchema(method.getName(),322 schema.getName(), schema.getClientInfo(), requestParams, response, exceptions,323 authAnnotationDtos!= null && !authAnnotationDtos.isEmpty(), authKeys, relatedCustomization);324 }325 private static List<AuthenticationDto> getSpecificRelatedAuth(List<AuthenticationDto> authenticationDtoList, Method method){326 if (authenticationDtoList == null) return null;327 List<String> annotations = Arrays.stream(method.getAnnotations()).map(s-> s.annotationType().getName()).collect(Collectors.toList());328 return authenticationDtoList.stream().filter(s->329 (s.localAuthSetup != null && s.localAuthSetup.annotationOnEndpoint != null && annotations.contains(s.localAuthSetup.annotationOnEndpoint)) ||330 (s.jsonAuthEndpoint != null && s.jsonAuthEndpoint.annotationOnEndpoint != null && annotations.contains(s.jsonAuthEndpoint.annotationOnEndpoint))331 ).collect(Collectors.toList());332 }333 private static Map<Integer, CustomizedRequestValueDto> getRelatedCustomization(List<CustomizedRequestValueDto> customizedRequestValueDtos, Method method){334 if (customizedRequestValueDtos == null) return null;335 List<String> annotations = Arrays.stream(method.getAnnotations()).map(s-> s.annotationType().getName()).collect(Collectors.toList());336 List<CustomizedRequestValueDto> list = customizedRequestValueDtos.stream().filter(337 s-> (s.annotationOnEndpoint == null || annotations.contains(s.annotationOnEndpoint)) &&338 (s.specificEndpointName == null || s.specificEndpointName.contains(method.getName()))339 ).collect(Collectors.toList());340 if (list.isEmpty()) return null;341 Map<Integer, CustomizedRequestValueDto> map = new HashMap<>();342 list.forEach(s->map.put(customizedRequestValueDtos.indexOf(s), s));343 return map;344 }345 private static NamedTypedValue buildInputParameter(InterfaceSchema schema, Parameter parameter, RPCType type,346 Map<Integer,CustomizedRequestValueDto> customizationDtos, Set<String> relatedCustomization,347 List<CustomizedNotNullAnnotationForRPCDto> notNullAnnotations) {348 String name = parameter.getName();349 Class<?> clazz = parameter.getType();350 List<String> depth = new ArrayList<>();351 Map<TypeVariable, Type> genericTypeMap = new HashMap<>();352 NamedTypedValue namedTypedValue = build(schema, clazz, parameter.getParameterizedType(), name, type, depth, customizationDtos, relatedCustomization, null, notNullAnnotations, null, genericTypeMap);353 for (Annotation annotation: parameter.getAnnotations()){354 handleConstraint(namedTypedValue, annotation, notNullAnnotations);355 }356 return namedTypedValue;357 }358 private static NamedTypedValue build(InterfaceSchema schema, Class<?> clazz, Type genericType, String name, RPCType rpcType, List<String> depth,359 Map<Integer, CustomizedRequestValueDto> customizationDtos, Set<String> relatedCustomization, AccessibleSchema accessibleSchema,360 List<CustomizedNotNullAnnotationForRPCDto> notNullAnnotations, Class<?> originalType, Map<TypeVariable, Type> genericTypeMap) {361 handleGenericSuperclass(clazz, genericTypeMap);362 List<String> genericTypes = handleGenericType(clazz, genericType, genericTypeMap);363 String clazzWithGenericTypes = CodeJavaGenerator.handleClassNameWithGeneric(clazz.getName(), genericTypes);364 depth.add(getObjectTypeNameWithFlag(clazz, clazzWithGenericTypes));365 NamedTypedValue namedValue = null;366 try{367 if (PrimitiveOrWrapperType.isPrimitiveOrTypes(clazz)) {368 namedValue = PrimitiveOrWrapperParam.build(name, clazz, accessibleSchema);369 } else if (clazz == String.class) {370 StringType stringType = new StringType();371 namedValue = new StringParam(name, stringType, accessibleSchema);372 } else if (clazz == BigDecimal.class){373 BigDecimalType bigDecimalType = new BigDecimalType();374 namedValue = new BigDecimalParam(name, bigDecimalType, accessibleSchema);375 } else if (clazz == BigInteger.class){376 BigIntegerType bigIntegerType = new BigIntegerType();377 namedValue = new BigIntegerParam(name, bigIntegerType, accessibleSchema);378 } else if (clazz.isEnum()) {379 String [] items = Arrays.stream(clazz.getEnumConstants()).map(e-> getNameEnumConstant(e)).toArray(String[]::new);380 EnumType enumType = new EnumType(clazz.getSimpleName(), clazz.getName(), items, clazz);381 EnumParam param = new EnumParam(name, enumType, accessibleSchema);382 //register this type in the schema383 schema.registerType(enumType.copy(), param.copyStructureWithProperties());384 namedValue = param;385 } else if (clazz.isArray()){386 Type type = null;387 Class<?> templateClazz = null;388 if (genericType instanceof GenericArrayType){389 type = ((GenericArrayType)genericType).getGenericComponentType();390 templateClazz = getTemplateClass(type, genericTypeMap);391 }else {392 templateClazz = clazz.getComponentType();393 }394 NamedTypedValue template = build(schema, templateClazz, type,"template", rpcType, depth, customizationDtos, relatedCustomization, null, notNullAnnotations, null, genericTypeMap);395 template.setNullable(false);396 CollectionType ctype = new CollectionType(clazz.getSimpleName(),clazz.getName(), template, clazz);397 ctype.depth = getDepthLevel(clazz, depth, clazzWithGenericTypes);398 namedValue = new ArrayParam(name, ctype, accessibleSchema);399 } else if (clazz == ByteBuffer.class){400 // handle binary of thrift401 namedValue = new ByteBufferParam(name, accessibleSchema);402 } else if (List.class.isAssignableFrom(clazz) || Set.class.isAssignableFrom(clazz)){403 if (genericType == null)404 throw new RuntimeException("genericType should not be null for List and Set class");405 Type type = ((ParameterizedType) genericType).getActualTypeArguments()[0];406 Class<?> templateClazz = getTemplateClass(type, genericTypeMap);407 NamedTypedValue template = build(schema, templateClazz, type,"template", rpcType, depth, customizationDtos, relatedCustomization, null, notNullAnnotations, null, genericTypeMap);408 template.setNullable(false);409 CollectionType ctype = new CollectionType(clazz.getSimpleName(),clazz.getName(), template, clazz);410 ctype.depth = getDepthLevel(clazz, depth, clazzWithGenericTypes);411 if (List.class.isAssignableFrom(clazz))412 namedValue = new ListParam(name, ctype, accessibleSchema);413 else414 namedValue = new SetParam(name, ctype, accessibleSchema);415 } else if (Map.class.isAssignableFrom(clazz)){416 if (genericType == null)417 throw new RuntimeException("genericType should not be null for List and Set class");418 Type keyType = ((ParameterizedType) genericType).getActualTypeArguments()[0];419 Type valueType = ((ParameterizedType) genericType).getActualTypeArguments()[1];420 Class<?> keyTemplateClazz = getTemplateClass(keyType, genericTypeMap);421 NamedTypedValue keyTemplate = build(schema, keyTemplateClazz, keyType,"keyTemplate", rpcType, depth, customizationDtos, relatedCustomization, null, notNullAnnotations, null, genericTypeMap);422 keyTemplate.setNullable(false);423 Class<?> valueTemplateClazz = getTemplateClass(valueType, genericTypeMap);424 NamedTypedValue valueTemplate = build(schema, valueTemplateClazz, valueType,"valueTemplate", rpcType, depth, customizationDtos, relatedCustomization, null, notNullAnnotations, null, genericTypeMap);425 MapType mtype = new MapType(clazz.getSimpleName(), clazz.getName(), new PairParam(new PairType(keyTemplate, valueTemplate), null), clazz);426 mtype.depth = getDepthLevel(clazz, depth, clazzWithGenericTypes);427 namedValue = new MapParam(name, mtype, accessibleSchema);428 } else if (Date.class.isAssignableFrom(clazz)){429 if (clazz == Date.class)430 namedValue = new DateParam(name, accessibleSchema);431 else432 throw new RuntimeException("NOT support "+clazz.getName()+" date type in java yet");433 } else if (Exception.class.isAssignableFrom(clazz) && clazz.getName().startsWith("java")){434 // note that here we only extract class name and message435 StringParam msgField = new StringParam("message", new AccessibleSchema(false, null, "getMessage"));436 ObjectType exceptionType = new ObjectType(clazz.getSimpleName(), clazz.getName(), Collections.singletonList(msgField), clazz, genericTypes);437 namedValue = new ObjectParam(name, exceptionType, accessibleSchema);438 } else {439 if (clazz.getName().startsWith("java")){440 throw new RuntimeException("NOT handle "+clazz.getName()+" class in java yet");441 }442 long cycleSize = depth.stream().filter(s-> s.equals(getObjectTypeNameWithFlag(clazz, clazzWithGenericTypes))).count();443 if (cycleSize == 1){444 List<NamedTypedValue> fields = new ArrayList<>();445 Map<Integer, CustomizedRequestValueDto> objRelatedCustomizationDtos = getCustomizationBasedOnSpecifiedType(customizationDtos, clazz.getName());446 // field list447 List<Field> fieldList = new ArrayList<>();448 getAllFields(clazz, fieldList, rpcType);449 for(Field f: fieldList){450 // skip final field451 if (Modifier.isFinal(f.getModifiers()))452 continue;453 if (doSkipReflection(f.getName()))454 continue;455 AccessibleSchema faccessSchema = null;456 //check accessible457 if (Modifier.isPublic(f.getModifiers())){458 faccessSchema = new AccessibleSchema();459 } else{460 // find getter and setter461 faccessSchema = new AccessibleSchema(false, findGetterOrSetter(clazz, f, false), findGetterOrSetter(clazz, f, true));462 if (faccessSchema.getterMethodName == null || faccessSchema.setterMethodName == null){463 SimpleLogger.warn("Error: skip the field "+f.getName()+" since its setter/getter is not found");464 continue;465 }466 }467 Class<?> fType = f.getType();468 Class<?> foriginalType = null;469 Type fGType = f.getGenericType();470 if (f.getGenericType() instanceof TypeVariable){471 foriginalType = f.getType();472 Type actualType = getActualType(genericTypeMap, (TypeVariable) f.getGenericType());473 if (actualType instanceof Class){474 fType = (Class<?>) actualType;475 fGType = fType;476 }else if (actualType instanceof ParameterizedType){477 fGType = actualType;478 if (((ParameterizedType) actualType).getRawType() instanceof Class<?>)479 fType = (Class<?>) ((ParameterizedType) actualType).getRawType();480 else481 throw new RuntimeException("Error: Fail to handle actual type of a generic type");482 }483 }484 NamedTypedValue field = build(schema, fType, fGType,f.getName(), rpcType, depth, objRelatedCustomizationDtos, relatedCustomization, faccessSchema, notNullAnnotations, foriginalType, genericTypeMap);485 for (Annotation annotation : f.getAnnotations()){486 handleConstraint(field, annotation, notNullAnnotations);487 }488 fields.add(field);489 }490 handleNativeRPCConstraints(clazz, fields, rpcType);491 ObjectType otype = new ObjectType(clazz.getSimpleName(), clazz.getName(), fields, clazz, genericTypes);492 otype.setOriginalType(originalType);493 otype.depth = getDepthLevel(clazz, depth, clazzWithGenericTypes);494 ObjectParam oparam = new ObjectParam(name, otype, accessibleSchema);495 schema.registerType(otype.copy(), oparam);496 namedValue = oparam;497 }else {498 CycleObjectType otype = new CycleObjectType(clazz.getSimpleName(), clazz.getName(), clazz, genericTypes);499 otype.depth = getDepthLevel(clazz, depth, clazzWithGenericTypes);500 ObjectParam oparam = new ObjectParam(name, otype, accessibleSchema);501 schema.registerType(otype.copy(), oparam);502 namedValue = oparam;503 }504 }505 }catch (ClassCastException e){506 throw new RuntimeException(String.format("fail to perform reflection on param/field: %s; class: %s; genericType: %s; class of genericType: %s; depth: %s; error info:%s",507 name, clazz.getName(), genericType==null?"null":genericType.getTypeName(), genericType==null?"null":genericType.getClass().getName(), String.join(",", depth), e.getMessage()));508 }509 namedValue.getType().setOriginalType(originalType);510 if (customizationDtos!=null){511 handleNamedValueWithCustomizedDto(namedValue, customizationDtos, relatedCustomization);512 }513 return namedValue;514 }515 private static String getNameEnumConstant(Object object) {516 try {517 Method name = object.getClass().getMethod("name");518 name.setAccessible(true);519 return (String) name.invoke(object);520 } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {521 SimpleLogger.warn("Driver Error: fail to extract name for enum constant", e);522 return object.toString();523 }524 }525 private static void handleGenericSuperclass(Class clazz, Map<TypeVariable, Type> map){526 if (isNotCustomizedObject(clazz)) return;527 if (clazz.getGenericSuperclass() == null || !(clazz.getGenericSuperclass() instanceof ParameterizedType)) return;528 Type[] actualTypes = ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments();529 if (((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments().length == 0) return;530 TypeVariable[] typeVariables = clazz.getSuperclass().getTypeParameters();531 if (typeVariables.length != actualTypes.length){532 throw new RuntimeException("Error: fail to handle generic types in Dto");533 }534 for (int i = 0; i < typeVariables.length; i++){535 map.put(typeVariables[i], actualTypes[i]);536 }537 handleGenericSuperclass(clazz.getSuperclass(), map);538 }539 private static List<String> handleGenericType(Class<?> clazz, Type genericType, Map<TypeVariable, Type> map){540 if (isNotCustomizedObject(clazz)) return null;541 if (!(genericType instanceof ParameterizedType)) return null;542 List<String> genericTypes = new ArrayList<>();543 Type[] actualTypes = ((ParameterizedType) genericType).getActualTypeArguments();544 TypeVariable[] typeVariables = clazz.getTypeParameters();545 if (typeVariables.length != actualTypes.length){546 throw new RuntimeException("Error: fail to handle generic types in Dto");547 }548 for (int i = 0; i < typeVariables.length; i++){549 Type a = actualTypes[i];550 if (a instanceof TypeVariable)551 a = getActualType(map, (TypeVariable) a);552 if (a != null)553 genericTypes.add(a.getTypeName());554 map.put(typeVariables[i], actualTypes[i]);555 }556 return genericTypes;557 }558 private static Type getActualType(Map<TypeVariable, Type> map, TypeVariable typeVariable){559 Type t = map.get(typeVariable);560 if (t == null) return null;561 if (t instanceof TypeVariable)562 return getActualType(map, (TypeVariable) t);563 return t;564 }565 private static void getAllFields(Class<?> clazz, List<Field> fieldList, RPCType type){566 if (type == RPCType.THRIFT && isNativeThriftDto(clazz)){567 getFieldForNativeThriftDto(clazz, fieldList);568 return;569 }570 fieldList.addAll(0, Arrays.asList(clazz.getDeclaredFields()));571 if (!Exception.class.isAssignableFrom(clazz) && clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class)572 getAllFields(clazz.getSuperclass(), fieldList, type);573 }574 private static Map<Integer, CustomizedRequestValueDto> getCustomizationBasedOnSpecifiedType(Map<Integer, CustomizedRequestValueDto> customizationDtos, String objTypeName){575 if (customizationDtos == null) return null;576 return customizationDtos.entrySet().stream().filter(s-> s.getValue().specificRequestTypeName == null ||577 s.getValue().specificRequestTypeName.equals(objTypeName)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));578 }579 private static String findGetterOrSetter(Class<?> clazz, Field field, boolean findGetter){580 List<Method> found;581 if (findGetter){582 found = Arrays.stream(clazz.getMethods()).filter(m->583 Modifier.isPublic(m.getModifiers()) &&584// (m.getName().equalsIgnoreCase("get"+field.getName()) || m.getName().equalsIgnoreCase("is"+field.getName())) &&585 isGetter(field.getName(), m.getName(), field.getType().getTypeName()) &&586 m.getParameterCount() == 0587 ).collect(Collectors.toList());588 }else {589 found = Arrays.stream(clazz.getMethods()).filter(m->590 Modifier.isPublic(m.getModifiers()) &&591// m.getName().equalsIgnoreCase("set"+field.getName()) &&592 isSetter(field.getName(), m.getName(), field.getType().getTypeName()) &&593 m.getParameterCount() == 1 &&594 (m.getParameterTypes()[0].equals(field.getType()) || m.getParameterTypes()[0].equals(PrimitiveOrWrapperParam.getPrimitiveOrWrapper(field.getType())))595 ).collect(Collectors.toList());596 }597 if (found.size() == 1)598 return found.get(0).getName();599 String msg = "RPC extract schema Error: cannot access field property, there exist "+found.size()+" methods to access the field "+ field.getName() + " for the class "+ clazz.getName();600 if (found.size() > 1){601 /*602 instead of throwing the exception,603 provide a warning and use the first one604 */605 SimpleLogger.uniqueWarn(msg);606 return found.get(0).getName();607 }608 SimpleLogger.uniqueWarn(msg);609 return null;610 }611 private static boolean isSetter(String fieldName, String methodName, String type){612 boolean isBoolean = type.equals(Boolean.class.getName()) || type.equals(boolean.class.getName());613 String fieldText = fieldName;614 if (isBoolean && fieldText.startsWith("is") && fieldText.length() > 2)615 fieldText = fieldText.substring(2);616 String gsMethod = "set";617 return methodName.equalsIgnoreCase(gsMethod+fieldText) || methodName.equalsIgnoreCase(gsMethod+fieldName);618 }619 private static boolean isGetter(String fieldName, String methodName, String type){620 boolean isBoolean = type.equals(Boolean.class.getName()) || type.equals(boolean.class.getName());621 return methodName.equalsIgnoreCase("get"+fieldName) || (isBoolean && (methodName.equalsIgnoreCase(fieldName) || methodName.equalsIgnoreCase("is"+fieldName)));622 }623 private static void handleNamedValueWithCustomizedDto(NamedTypedValue namedTypedValue, Map<Integer, CustomizedRequestValueDto> customizationDtos, Set<String> relatedCustomization){624 List<String> candidateReferences = new ArrayList<>();625 List<NamedTypedValue> candidates = new ArrayList<>();626 customizationDtos.forEach((i, dto)->{627 if (dto.combinedKeyValuePairs != null628 // && (dto.specificRequestTypeName == null || dto.specificRequestTypeName.equals(namedTypedValue.getType().getFullTypeName()))629 ){630 dto.combinedKeyValuePairs.forEach(p->{631 if (p.fieldKey.equals(namedTypedValue.getName())){632 NamedTypedValue copy = namedTypedValue.copyStructureWithProperties();633 boolean ok = setNamedValueBasedOnCandidates(copy, p.fieldValue);634 if (ok){635 if (!candidateReferences.contains(""+i)){636 relatedCustomization.add(""+i);637 candidateReferences.add(""+i);638 candidates.add(copy);639 } else640 throw new IllegalArgumentException("Error: there should not exist same key with the name "+p.fieldKey+"in a combinedKeyValuePairs");641 }642 }643 });644 }645 });646 if (!candidates.isEmpty()){647 namedTypedValue.setCandidateReferences(candidateReferences);648 namedTypedValue.setCandidates(candidates);649 return;650 }651 // check for keyValues652 List<CustomizedRequestValueDto> ikey = customizationDtos.values().stream().filter(s-> s.keyValues!= null && s.keyValues.key.equals(namedTypedValue.getName())653 //&& (s.specificRequestTypeName== null || s.specificRequestTypeName.equals(namedTypedValue.getType().getFullTypeName()))654 ).collect(Collectors.toList());655 if (ikey.size() == 1){656 setCandidatesForNamedValue(namedTypedValue, ikey.get(0));657 } else if (ikey.size() > 1){658 throw new IllegalStateException("Error: more than one Dto for independent key with "+getKeyForCustomizedRequestValueDto(ikey.get(0)));659 }660 }661 private static void setCandidatesForNamedValue(NamedTypedValue namedTypedValue, CustomizedRequestValueDto customizedRequestValueDto){662 boolean handled = true;663 List<NamedTypedValue> candidates = new ArrayList<>();664 if (namedTypedValue instanceof PrimitiveOrWrapperParam || namedTypedValue instanceof StringParam || namedTypedValue instanceof ByteBufferParam){665 for (String v: customizedRequestValueDto.keyValues.values){666 NamedTypedValue copy= namedTypedValue.copyStructureWithProperties();667 handled = handled && setNamedValueBasedOnCandidates(copy, v);668 candidates.add(copy);669 }670 }else {671 SimpleLogger.uniqueWarn("Error: Do not support configuring pre-defined values for the type "+namedTypedValue.getType().getFullTypeName());672 return;673 }674 if (handled){675 namedTypedValue.setCandidates(candidates);676 }677 }678 private static boolean setNamedValueBasedOnCandidates(NamedTypedValue copy, String value){679 try {680 if (copy instanceof PrimitiveOrWrapperParam){681 ((PrimitiveOrWrapperParam) copy).setValueBasedOnStringValue(value);682 }else if (copy instanceof StringParam)683 copy.setValue(value);684 else if (copy instanceof ByteBufferParam)685 copy.setValue(value.getBytes());686 }catch (RuntimeException exception){687 SimpleLogger.uniqueWarn("Error: fail to generate candidates with string value "+value+" for "+copy.getName() +" with type "+copy.getType().getFullTypeName());688 return false;689 }690 return true;691 }692 private static void handleConstraint(NamedTypedValue namedTypedValue, Annotation annotation, List<CustomizedNotNullAnnotationForRPCDto> notNullAnnotations){693 if (annotation.annotationType().getName().startsWith("javax.validation.constraints")){694 JavaXConstraintHandler.handleParam(namedTypedValue, annotation);695 } else if (notNullAnnotations != null && !notNullAnnotations.isEmpty()){696 boolean isRequired = notNullAnnotations.stream().anyMatch(a-> isRequired(annotation, a));697 namedTypedValue.setNullable(!isRequired);698 }699 // remove the log for the moment, might need it later700// else {701// SimpleLogger.info("annotation with "+ annotation.annotationType().getName()+" is not handled");702// }703 }704 private static boolean isRequired(Annotation annotation, CustomizedNotNullAnnotationForRPCDto notNullAnnotations){705 if (annotation.annotationType().getName().equals(notNullAnnotations.annotationType)){706 if (notNullAnnotations.annotationMethod != null && notNullAnnotations.equalsTo !=null){707 try {708 return annotation.annotationType().getDeclaredMethod(notNullAnnotations.annotationMethod).invoke(annotation).equals(notNullAnnotations.equalsTo);709 } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {710 SimpleLogger.uniqueWarn("Error: fail to invoke the specified method in the annotation with the error msg:"+e.getMessage());711 return false;712 }713 }714 return true;715 }716 return false;717 }718 private static Class<?> getTemplateClass(Type type, Map<TypeVariable, Type> genericTypeMap){719 Type actualType = type;720 if (type instanceof TypeVariable)721 actualType = getActualType(genericTypeMap, (TypeVariable) type);722 if (actualType instanceof ParameterizedType){723 return (Class<?>) ((ParameterizedType)actualType).getRawType();724 }else if (actualType instanceof Class)725 return (Class<?>) actualType;726 throw new RuntimeException("unhanded type:"+ type);727 }728 /**729 * there might exist some additional info generated by eg instrumentation730 * then we need to skip reflection on such info with the specified name731 * @param name is a name of object to check732 * @return whether to skip the object733 */734 private static boolean doSkipReflection(String name){735 return name.equals("$jacocoData");736 }737 private static boolean isMetaMap(Field field){738 boolean result = field.getName().equals("metaDataMap")739 && Map.class.isAssignableFrom(field.getType());740 if (!result) return result;741 Type genericType = field.getGenericType();742 Type valueType = ((ParameterizedType) genericType).getActualTypeArguments()[1];743 return valueType.getTypeName().equals("org.apache.thrift.meta_data.FieldMetaData");744 }745 private final static String NATIVE_THRIFT_DTO_INTERFACE = "org.apache.thrift.TBase";746 private final static String NATIVE_THRIFT_FIELD_SCHEMA = "metaDataMap";747 private static boolean isNativeThriftDto(Class<?> clazz){748 return clazz.getInterfaces().length > 0 && Arrays.stream(clazz.getInterfaces()).anyMatch(i-> i.getName().equals(NATIVE_THRIFT_DTO_INTERFACE));749 }750 private static void getFieldForNativeThriftDto(Class<?> clazz, List<Field> fields){751 try {752 Field metaMap_field = clazz.getDeclaredField(NATIVE_THRIFT_FIELD_SCHEMA);753 if (isMetaMap(metaMap_field)){754 Object metaMap = metaMap_field.get(null);755 if (metaMap instanceof Map){756 for (Object f : ((Map)metaMap).values()){757 Field fname = f.getClass().getDeclaredField("fieldName");758 fname.setAccessible(true);759 String name = (String) fname.get(f);760 fields.add(clazz.getDeclaredField(name));761 }762 }763 }764 } catch (NoSuchFieldException | IllegalAccessException e) {765 SimpleLogger.uniqueWarn("Error: fail to get the metaDataMap field in native dto");766 }767 }768 private static void handleNativeRPCConstraints(Class<?> clazz, List<NamedTypedValue> fields, RPCType type){769 if (type == RPCType.THRIFT && isNativeThriftDto(clazz)){770 try {771 Field metaMap_field = clazz.getDeclaredField(NATIVE_THRIFT_FIELD_SCHEMA);772 if (isMetaMap(metaMap_field))773 handleMetaMap(metaMap_field, fields);774 } catch (NoSuchFieldException e) {775 SimpleLogger.uniqueWarn("Error: fail to get the metaDataMap field in native dto");776 }777 }778 }779 private static void handleMetaMap(Field metaMap_field, List<NamedTypedValue> fields){780 Object metaMap = null;781 try {782 metaMap = metaMap_field.get(null);783 if (metaMap instanceof Map){784 for (Object f : ((Map)metaMap).values()){785 Field fname = f.getClass().getDeclaredField("fieldName");786 fname.setAccessible(true);787 String name = (String) fname.get(f);788 NamedTypedValue field = findFieldByName(name, fields);789 if (field!=null){790 Field frequiredType = f.getClass().getDeclaredField("requirementType");791 frequiredType.setAccessible(true);792 byte required = (byte)frequiredType.get(f);793 if (required == 1)794 field.setNullable(false);795 // TODO for handling default796 }else {797 SimpleLogger.uniqueWarn("Error: fail to find field in list but exist in metaMap, and the field name is "+ name);798 }799 }800 }801 } catch (IllegalAccessException | NoSuchFieldException e) {802 SimpleLogger.uniqueWarn("Error: fail to set isNull based on metaMap of Thrift struct "+e.getMessage());803 }804 }805 private static NamedTypedValue findFieldByName(String name, List<NamedTypedValue> fields){806 for (NamedTypedValue f: fields){807 if (f.getName().equals(name)) return f;808 }809 return null;810 }811 private static int getDepthLevel(Class clazz, List<String> depth, String clazzFullNameWithGeneric){812 String tag = getObjectTypeNameWithFlag(clazz, clazzFullNameWithGeneric);813 int start = Math.max(0, depth.lastIndexOf(tag));814 return depth.subList(start, depth.size()).stream().filter(s-> !s.equals(tag) && s.startsWith(OBJECT_FLAG)).collect(Collectors.toSet()).size();815 }816}...

Full Screen

Full Screen

Source:ObjectParam.java Github

copy

Full Screen

2import com.fasterxml.jackson.core.JsonProcessingException;3import org.evomaster.client.java.controller.api.dto.problem.rpc.ParamDto;4import org.evomaster.client.java.controller.problem.rpc.CodeJavaGenerator;5import org.evomaster.client.java.controller.problem.rpc.schema.types.AccessibleSchema;6import org.evomaster.client.java.controller.problem.rpc.schema.types.ObjectType;7import org.evomaster.client.java.controller.problem.rpc.schema.types.PrimitiveOrWrapperType;8import org.evomaster.client.java.controller.problem.rpc.schema.types.TypeSchema;9import org.evomaster.client.java.utils.SimpleLogger;10import java.lang.reflect.Field;11import java.lang.reflect.InvocationTargetException;12import java.lang.reflect.Method;13import java.lang.reflect.Type;14import java.util.ArrayList;15import java.util.List;16import java.util.Map;17import java.util.stream.Collectors;18/**19 * object param20 */21public class ObjectParam extends NamedTypedValue<ObjectType, List<NamedTypedValue>> {22 public ObjectParam(String name, ObjectType type, AccessibleSchema accessibleSchema) {23 super(name, type, accessibleSchema);24 }25 @Override26 public Object newInstance() throws ClassNotFoundException {27 if (getValue() == null) return null;28 String clazzName = getType().getFullTypeName();29 Class<?> clazz = Class.forName(clazzName);30 try {31 Object instance = clazz.newInstance();32 for (NamedTypedValue v: getValue()){33 if (v.accessibleSchema == null || v.accessibleSchema.isAccessible){34 Field f = clazz.getField(v.getName());35 f.setAccessible(true);36 Object vins = v.newInstance();37 if (vins != null)38 f.set(instance, vins);39 } else if(v.accessibleSchema.setterMethodName != null){40 Method m = getSetter(clazz, v.accessibleSchema.setterMethodName, v.getType(), v.getType().getClazz(), 0);41 //clazz.getMethod(v.accessibleSchema.setterMethodName, v.getType().getClazz());42 m.invoke(instance, v.newInstance());43 }44 }45 return instance;46 } catch (InstantiationException e) {47 throw new RuntimeException("fail to construct the class:"+clazzName+" with error msg:"+e.getMessage());48 } catch (IllegalAccessException e) {49 throw new RuntimeException("fail to access the class:"+clazzName+" with error msg:"+e.getMessage());50 } catch (NoSuchFieldException e) {51 throw new RuntimeException("fail to access the field:"+clazzName+" with error msg:"+e.getMessage());52 } catch (NoSuchMethodException e) {53 throw new RuntimeException("fail to access the method:"+clazzName+" with error msg:"+e.getMessage());54 } catch (InvocationTargetException e) {55 throw new RuntimeException("fail to invoke the setter method:"+clazzName+" with error msg:"+e.getMessage());56 }57 }58 private Method getSetter(Class<?> clazz, String setterName, TypeSchema type, Class<?> typeClass, int attemptTimes) throws NoSuchMethodException {59 try {60 Method m = clazz.getMethod(setterName, type.getClazz());61 return m;62 } catch (NoSuchMethodException e) {63 if (type instanceof PrimitiveOrWrapperType && attemptTimes == 0){64 Type p = PrimitiveOrWrapperParam.getPrimitiveOrWrapper(type.getClazz());65 if (p instanceof Class){66 return getSetter(clazz, setterName, type, (Class)p, 1);67 }68 }69 throw e;70 }71 }72 @Override73 public ObjectParam copyStructure() {74 return new ObjectParam(getName(), getType(), accessibleSchema);75 }76 @Override77 public ParamDto getDto() {78 ParamDto dto = super.getDto();79 if (getValue() != null){80 dto.innerContent = getValue().stream().map(NamedTypedValue::getDto).collect(Collectors.toList());81 dto.stringValue = NOT_NULL_MARK_OBJ_DATE;82 } else83 dto.innerContent = getType().getFields().stream().map(NamedTypedValue::getDto).collect(Collectors.toList());84 return dto;85 }86 @Override87 public void setValueBasedOnDto(ParamDto dto) {88 if (dto.innerContent!=null && !dto.innerContent.isEmpty()){89 List<NamedTypedValue> fields = getType().getFields();90 List<NamedTypedValue> values = new ArrayList<>();91 for (ParamDto p: dto.innerContent){92 NamedTypedValue f = fields.stream().filter(s-> s.sameParam(p)).findFirst().get().copyStructureWithProperties();93 f.setValueBasedOnDto(p);94 values.add(f);95 }96 setValue(values);97 }98 }99 @Override100 protected void setValueBasedOnValidInstance(Object instance) {101 List<NamedTypedValue> values = new ArrayList<>();102 List<NamedTypedValue> fields = getType().getFields();103 Class<?> clazz;104 try {105 clazz = Class.forName(getType().getFullTypeName());106 } catch (ClassNotFoundException e) {107 throw new RuntimeException("ERROR: fail to get class with the name"+getType().getFullTypeName()+" Msg:"+e.getMessage());108 }109 for (NamedTypedValue f: fields){110 NamedTypedValue copy = f.copyStructureWithProperties();111 try {112 if (f.accessibleSchema == null || f.accessibleSchema.isAccessible){113 Field fi = clazz.getField(f.getName());114 fi.setAccessible(true);115 Object fiv = fi.get(instance);116 copy.setValueBasedOnInstance(fiv);117 } else if(f.accessibleSchema.getterMethodName != null){118 Method m = clazz.getMethod(f.accessibleSchema.getterMethodName);119 copy.setValueBasedOnInstance(m.invoke(instance));120 }121 } catch (NoSuchFieldException | IllegalAccessException e) {122 throw new RuntimeException("ERROR: fail to get value of the field with the name ("+ f.getName()+ ") and error Msg:"+e.getMessage());123 } catch (NoSuchMethodException | InvocationTargetException e) {124 throw new RuntimeException("ERROR: fail to get/invoke getter method for the field with the name ("+ f.getName()+ ") and error Msg:"+e.getMessage());125 }126 values.add(copy);127 }128 setValue(values);129 }130 @Override131 public void setValueBasedOnInstanceOrJson(Object json) throws JsonProcessingException {132 List<NamedTypedValue> values = new ArrayList<>();133 List<NamedTypedValue> fields = getType().getFields();134 if (isValidInstance(json)){135 setValueBasedOnInstance(json);136 }else {137 /*138 in jackson, object would be extracted as a map139 */140 assert json instanceof Map;141 for (NamedTypedValue f: fields){142 NamedTypedValue copy = f.copyStructureWithProperties();143 Object fiv = ((Map)json).get(f.getName());144 copy.setValueBasedOnInstanceOrJson(fiv);145 values.add(copy);146 }147 setValue(values);148 }149 }150 @Override151 public List<String> newInstanceWithJava(boolean isDeclaration, boolean doesIncludeName, String variableName, int indent) {152 String typeName = getType().getTypeNameForInstance();153 String varName = variableName;154 List<String> codes = new ArrayList<>();155 boolean isNull = (getValue() == null);156 String var = CodeJavaGenerator.oneLineInstance(isDeclaration, doesIncludeName, typeName, varName, null);157 CodeJavaGenerator.addCode(codes, var, indent);158 if (isNull) return codes;159 CodeJavaGenerator.addCode(codes, "{", indent);160 // new obj161 CodeJavaGenerator.addCode(codes, CodeJavaGenerator.setInstanceObject(typeName, varName), indent+1);162 for (NamedTypedValue f : getValue()){163 if (f.accessibleSchema == null || f.accessibleSchema.isAccessible){164 String fName = varName+"."+f.getName();165 codes.addAll(f.newInstanceWithJava(false, true, fName, indent+1));166 }else{167 String fName = varName;168 boolean fdeclar = false;169 if (f instanceof ObjectParam || f instanceof MapParam || f instanceof CollectionParam || f instanceof DateParam || f instanceof BigDecimalParam || f instanceof BigIntegerParam){170 fName = varName+"_"+f.getName();171 fdeclar = true;172 }173 codes.addAll(f.newInstanceWithJava(fdeclar, true, fName, indent+1));174 if (f instanceof ObjectParam || f instanceof MapParam || f instanceof CollectionParam || f instanceof DateParam || f instanceof BigDecimalParam || f instanceof BigIntegerParam){175 CodeJavaGenerator.addCode(codes, CodeJavaGenerator.methodInvocation(varName, f.accessibleSchema.setterMethodName, fName)+CodeJavaGenerator.appendLast(),indent+1);176 }177 }178 }179 CodeJavaGenerator.addCode(codes, "}", indent);180 return codes;181 }182 @Override183 public List<String> newAssertionWithJava(int indent, String responseVarName, int maxAssertionForDataInCollection) {184 List<String> codes = new ArrayList<>();185 if (getValue() == null){186 CodeJavaGenerator.addCode(codes, CodeJavaGenerator.junitAssertNull(responseVarName), indent);187 return codes;188 }189 for (NamedTypedValue f : getValue()){190 String fName = null;191 if (f.accessibleSchema == null || f.accessibleSchema.isAccessible)192 fName = responseVarName+"."+f.getName();193 else{194 if (f.accessibleSchema.getterMethodName == null){195 String msg = "Error: Object("+getType().getFullTypeName()+") has private field "+f.getName()+", but there is no getter method";196 SimpleLogger.uniqueWarn(msg);197 CodeJavaGenerator.addComment(codes, msg, indent);198 }else{199 fName = responseVarName+"."+f.accessibleSchema.getterMethodName+"()";200 }201 }202 if (fName != null)203 codes.addAll(f.newAssertionWithJava(indent, fName, maxAssertionForDataInCollection));204 }205 return codes;206 }207 @Override208 public String getValueAsJavaString() {209 return null;...

Full Screen

Full Screen

Object

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.api.dto.SutInfoDto;2import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;3import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;4import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;5import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;6import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;7import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto;8import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexType;9import org.evomaster.client.java.controller.api.dto.database.schema.TableType;10import org.evomaster.client.java.controller.api.dto.database.schema.ViewDto;11import org.evomaster.client.java.controller.api.dto.database.schema.ViewType;12import org.evomaster.client.java.controller.api.dto.problem.ProblemInfoDto;13import org.evomaster.client.java.controller.api.dto.problem.RestResourceDto;14import org.evomaster.client.java.controller.api.dto.problem.RestResourceNodeDto;15import org.evomaster.client.java.controller.api.dto.problem.RestResourceSampleDto;16import org.evomaster.client.java.controller.api.dto.problem.RestSpecDto;17import org.evomaster.client.java.controller.api.dto.problem.TestResultsDto;18import org.evomaster.client.java.controller.api.dto.problem.TestSuiteInfoDto;19import org.evomaster.client.java.controller.api.dto.problem.TestSuiteSplitDto;20import org.evomaster.client.java.controller.api.dto.problem.TestingInfoDto;21import org.evomaster.client.java.controller.api.dto.problem.TestingTargetInfoDto;22import org.evomaster.client.java.controller.api.dto.problem.rest.*;23import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationDto;24import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2Dto;25import org.evomaster.client.java.controller.api.dto.sut.auth.UserPasswordDto;26import org.evomaster.client.java.controller.api.dto.sut.auth.UserTokenDto;27import org.evomaster.client.java.controller.api.dto.sut.auth.UserTokenDto.TokenLocation;28import org.evomaster.client.java.controller.api.dto.sut.auth.UserTokenDto.TokenType;29import org.evomaster.client.java.controller.api.dto.sut.system.SystemPortDto;30import org.evomaster.client.java.controller.api.dto.sut.system.SystemPortDto.PortType;31import org.evomaster.client.java.controller.api.dto.sut.system.System

Full Screen

Full Screen

Object

Using AI Code Generation

copy

Full Screen

1public class ObjectParam extends Param {2 public ObjectParam(String name, Object value) {3 super(name, value);4 }5 public ObjectParam(String name, Object value, boolean isHeader) {6 super(name, value, isHeader);7 }8 public ObjectParam(String name, Object value, boolean isHeader, boolean isCookie) {9 super(name, value, isHeader, isCookie);10 }11 public ObjectParam(String name, Object value, boolean isHeader, boolean isCookie, boolean isQuery) {12 super(name, value, isHeader, isCookie, isQuery);13 }14 public ObjectParam(String name, Object value, boolean isHeader, boolean isCookie, boolean isQuery, boolean isPath) {15 super(name, value, isHeader, isCookie, isQuery, isPath);16 }17 public ObjectParam(String name, Object value, boolean isHeader, boolean isCookie, boolean isQuery, boolean isPath, boolean isFormData) {18 super(name, value, isHeader, isCookie, isQuery, isPath, isFormData);19 }20 public ObjectParam(String name, Object value, boolean isHeader, boolean isCookie, boolean isQuery, boolean isPath, boolean isFormData, boolean isBody) {21 super(name, value, isHeader, isCookie, isQuery, isPath, isFormData, isBody);22 }23 public ObjectParam(String name, Object value, boolean isHeader, boolean isCookie, boolean isQuery, boolean isPath, boolean isFormData, boolean isBody, boolean isJson) {24 super(name, value, isHeader, isCookie, isQuery, isPath, isFormData, isBody, isJson);25 }26 public ObjectParam(String name, Object value, boolean isHeader, boolean isCookie, boolean isQuery, boolean isPath, boolean isFormData, boolean isBody, boolean isJson, boolean isXml) {27 super(name, value, isHeader, isCookie, isQuery, isPath, isFormData, isBody, isJson, isXml);28 }29 public ObjectParam copy() {30 return new ObjectParam(name, value, isHeader, isCookie, isQuery, isPath, isFormData, isBody, isJson, isXml);31 }32 public String toString() {33 return "ObjectParam{" +

Full Screen

Full Screen

Object

Using AI Code Generation

copy

Full Screen

1public class 2 extends org.evomaster.client.java.controller.problem.rpc.schema.params.ObjectParam {2 public 2() {3 super(null);4 }5 public 2(java.lang.Object value) {6 super(value);7 }8 public java.lang.Object getValue() {9 return (java.lang.Object) super.getValue();10 }11 public void setValue(java.lang.Object value) {12 super.setValue(value);13 }14 public java.lang.Object getValue(java.lang.Class<?> returnType) {15 return (java.lang.Object) super.getValue(returnType);16 }17 public java.lang.Object getValue(java.lang.Class<?> returnType, java.util.List<java.lang.String> path) {18 return (java.lang.Object) super.getValue(returnType, path);19 }20 public java.lang.Object getValue(java.lang.Class<?> returnType, java.util.List<java.lang.String> path, java.util.List<org.evomaster.client.java.controller.problem.rpc.schema.params.Param> params) {21 return (java.lang.Object) super.getValue(returnType, path, params);22 }23 public java.lang.Object getValue(java.lang.Class<?> returnType, java.util.List<java.lang.String> path, java.util.List<org.evomaster.client.java.controller.problem.rpc.schema.params.Param> params, org.evomaster.client.java.controller.problem.rpc.schema.RpcCall rpcCall) {24 return (java.lang.Object) super.getValue(returnType, path, params, rpcCall);25 }26 public java.lang.String getClassName() {27 return "java.lang.Object";28 }29 public java.lang.String getClassName(java.util.List<java.lang.String> path) {30 return "java.lang.Object";31 }32 public java.lang.String getClassName(java.util.List<java.lang.String> path, java.util.List<org.evomaster.client.java.controller.problem.rpc.schema.params.Param> params) {33 return "java.lang.Object";34 }35 public java.lang.String getClassName(java.util.List<java.lang.String> path, java.util.List<org.evomaster.client.java.controller.problem.rpc.schema.params.Param> params, org.evomaster.client.java.controller.problem.rpc.schema.RpcCall rpcCall) {36 return "java.lang.Object";37 }38 public java.lang.String getClassName(java.util.List<java.lang.String> path, java.util.List<org.evomaster.client.java.controller.problem.rpc.schema.params.Param> params, org.evomaster.client.java.controller.problem.rpc.schema.RpcCall rpcCall, java.lang.String parent

Full Screen

Full Screen

Object

Using AI Code Generation

copy

Full Screen

1public class ObjectParam {2 private String type;3 private String value;4 private String id;5 public ObjectParam() {6 }7 public ObjectParam(String type, String value, String id) {8 this.type = type;9 this.value = value;10 this.id = id;11 }12 public String getType() {13 return type;14 }15 public void setType(String type) {16 this.type = type;17 }18 public String getValue() {19 return value;20 }21 public void setValue(String value) {22 this.value = value;23 }24 public String getId() {25 return id;26 }27 public void setId(String id) {28 this.id = id;29 }30 public boolean equals(Object o) {31 if (this == o) return true;32 if (!(o instanceof ObjectParam)) return false;33 ObjectParam that = (ObjectParam) o;34 return Objects.equals(getType(), that.getType()) &&35 Objects.equals(getValue(), that.getValue()) &&36 Objects.equals(getId(), that.getId());37 }38 public int hashCode() {39 return Objects.hash(getType(), getValue(), getId());40 }41 public String toString() {42 return "ObjectParam{" +43 '}';44 }45}46public class ObjectParam {47 private String type;48 private String value;49 private String id;50 public ObjectParam() {51 }52 public ObjectParam(String type, String value, String id) {53 this.type = type;54 this.value = value;55 this.id = id;56 }57 public String getType() {58 return type;59 }60 public void setType(String type) {61 this.type = type;62 }63 public String getValue() {64 return value;65 }66 public void setValue(String value) {67 this.value = value;68 }69 public String getId() {70 return id;71 }72 public void setId(String id) {73 this.id = id;74 }75 public boolean equals(Object o) {76 if (this == o) return true;77 if (!(o instanceof ObjectParam

Full Screen

Full Screen

Object

Using AI Code Generation

copy

Full Screen

1public class 2 {2 public static void main(String[] args) {3 ObjectParam param = new ObjectParam();4 param.setParamName("paramName");5 param.setParamType("paramType");6 param.setParamValue("paramValue");7 param.setParamSchema("paramSchema");8 param.setParamRequired(true);9 param.setParamAllowEmptyValue(true);10 param.setParamAllowReserved(true);11 param.setParamDeprecated(true);12 param.setParamAllowEmptyValue(true);13 param.setParamAllowReserved(true);14 param.setParamDeprecated(true);15 param.setParamExample("paramExample");16 param.setParamExplode(true);17 param.setParamStyle("paramStyle");18 param.setParamAllowEmptyValue(true);19 param.setParamAllowReserved(true);20 param.setParamDeprecated(true);21 param.setParamExample("paramExample");22 param.setParamExplode(true);23 param.setParamStyle("paramStyle");24 param.setParamAllowEmptyValue(true);25 param.setParamAllowReserved(true);26 param.setParamDeprecated(true);27 param.setParamExample("paramExample");28 param.setParamExplode(true);29 param.setParamStyle("paramStyle");30 param.setParamAllowEmptyValue(true);31 param.setParamAllowReserved(true);32 param.setParamDeprecated(true);33 param.setParamExample("paramExample");34 param.setParamExplode(true);35 param.setParamStyle("paramStyle");36 param.setParamAllowEmptyValue(true);37 param.setParamAllowReserved(true);38 param.setParamDeprecated(true);39 param.setParamExample("paramExample");40 param.setParamExplode(true);41 param.setParamStyle("paramStyle");42 param.setParamAllowEmptyValue(true);43 param.setParamAllowReserved(true);44 param.setParamDeprecated(true);45 param.setParamExample("paramExample");46 param.setParamExplode(true);47 param.setParamStyle("paramStyle");48 param.setParamAllowEmptyValue(true);49 param.setParamAllowReserved(true);50 param.setParamDeprecated(true);51 param.setParamExample("paramExample");52 param.setParamExplode(true);53 param.setParamStyle("paramStyle");54 param.setParamAllowEmptyValue(true);55 param.setParamAllowReserved(true);56 param.setParamDeprecated(true);57 param.setParamExample("paramExample");58 param.setParamExplode(true);59 param.setParamStyle("paramStyle");

Full Screen

Full Screen

Object

Using AI Code Generation

copy

Full Screen

1public class 2 {2 public static void main(String[] args) {3 ObjectParam objectParam = new ObjectParam();4 objectParam.setParam(new Object());5 objectParam.setParam(null);6 objectParam.setParam(new Object());7 }8}9public class 3 {10 public static void main(String[] args) {11 ObjectParam objectParam = new ObjectParam();12 objectParam.setParam(new Object());13 objectParam.setParam(null);14 objectParam.setParam(new Object());15 }16}17public class 4 {18 public static void main(String[] args) {19 ObjectParam objectParam = new ObjectParam();20 objectParam.setParam(new Object());21 objectParam.setParam(null);22 objectParam.setParam(new Object());23 }24}25public class 5 {26 public static void main(String[] args) {27 ObjectParam objectParam = new ObjectParam();28 objectParam.setParam(new Object());29 objectParam.setParam(null);30 objectParam.setParam(new Object());31 }32}33public class 6 {34 public static void main(String[] args) {35 ObjectParam objectParam = new ObjectParam();36 objectParam.setParam(new Object());37 objectParam.setParam(null);38 objectParam.setParam(new Object());39 }40}41public class 7 {42 public static void main(String[] args) {43 ObjectParam objectParam = new ObjectParam();44 objectParam.setParam(new Object());45 objectParam.setParam(null);46 objectParam.setParam(new Object());47 }48}49public class 8 {50 public static void main(String[] args) {

Full Screen

Full Screen

Object

Using AI Code Generation

copy

Full Screen

1public class 2 {2 public static void main(String[] args) {3 ObjectParam objectParam0 = new ObjectParam();4 objectParam0.setClassName("ClassName");5 objectParam0.setFields(new ArrayList<Param>());6 objectParam0.setClassName("ClassName");7 objectParam0.setFields(new ArrayList<Param>());8 System.out.println(objectParam0.toString());9 }10}11public class 3 {12 public static void main(String[] args) {13 ObjectParam objectParam0 = new ObjectParam();14 objectParam0.setClassName("ClassName");15 objectParam0.setFields(new ArrayList<Param>());16 objectParam0.setClassName("ClassName");17 objectParam0.setFields(new ArrayList<Param>());18 System.out.println(objectParam0.toString());19 }20}21public class 4 {22 public static void main(String[] args) {23 ObjectParam objectParam0 = new ObjectParam();24 objectParam0.setClassName("ClassName");25 objectParam0.setFields(new ArrayList<Param>());26 objectParam0.setClassName("ClassName");27 objectParam0.setFields(new ArrayList<Param>());28 System.out.println(objectParam0.toString());29 }30}31public class 5 {32 public static void main(String[] args) {33 ObjectParam objectParam0 = new ObjectParam();34 objectParam0.setClassName("ClassName");35 objectParam0.setFields(new ArrayList<Param>());36 objectParam0.setClassName("ClassName");37 objectParam0.setFields(new ArrayList<Param>());38 System.out.println(objectParam0.toString());39 }40}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run EvoMaster automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful