How to use handle method of org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler class

Best EvoMaster code snippet using org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.handle

Source:SutController.java Github

copy

Full Screen

2import com.fasterxml.jackson.core.JsonProcessingException;3import com.fasterxml.jackson.databind.ObjectMapper;4import org.eclipse.jetty.server.AbstractNetworkConnector;5import org.eclipse.jetty.server.Server;6import org.eclipse.jetty.server.handler.ErrorHandler;7import org.eclipse.jetty.servlet.ServletContextHandler;8import org.eclipse.jetty.servlet.ServletHolder;9import org.evomaster.client.java.controller.CustomizationHandler;10import org.evomaster.client.java.controller.SutHandler;11import org.evomaster.client.java.controller.api.dto.*;12import org.evomaster.client.java.controller.api.dto.problem.rpc.SeededRPCActionDto;13import org.evomaster.client.java.controller.db.SqlScriptRunnerCached;14import org.evomaster.client.java.controller.internal.db.DbSpecification;15import org.evomaster.client.java.controller.api.dto.problem.rpc.RPCType;16import org.evomaster.client.java.controller.problem.rpc.CustomizedNotNullAnnotationForRPCDto;17import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;18import org.evomaster.client.java.controller.api.dto.problem.rpc.SeededRPCTestDto;19import org.evomaster.client.java.controller.problem.rpc.schema.EndpointSchema;20import org.evomaster.client.java.controller.problem.rpc.schema.InterfaceSchema;21import org.evomaster.client.java.controller.api.dto.problem.rpc.RPCActionDto;22import org.evomaster.client.java.controller.problem.rpc.schema.LocalAuthSetupSchema;23import org.evomaster.client.java.controller.problem.rpc.schema.params.*;24import org.evomaster.client.java.controller.api.dto.database.operations.InsertionResultsDto;25import org.evomaster.client.java.controller.db.DbCleaner;26import org.evomaster.client.java.controller.db.SqlScriptRunner;27import org.evomaster.client.java.controller.internal.db.SchemaExtractor;28import org.evomaster.client.java.controller.internal.db.SqlHandler;29import org.evomaster.client.java.controller.problem.ProblemInfo;30import org.evomaster.client.java.controller.problem.RPCProblem;31import org.evomaster.client.java.controller.problem.rpc.RPCEndpointsBuilder;32import org.evomaster.client.java.instrumentation.BootTimeObjectiveInfo;33import org.evomaster.client.java.instrumentation.staticstate.UnitsInfoRecorder;34import org.evomaster.client.java.utils.SimpleLogger;35import org.evomaster.client.java.controller.api.ControllerConstants;36import org.evomaster.client.java.controller.api.dto.database.execution.ExecutionDto;37import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;38import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;39import org.evomaster.client.java.instrumentation.AdditionalInfo;40import org.evomaster.client.java.instrumentation.TargetInfo;41import org.glassfish.jersey.jackson.JacksonFeature;42import org.glassfish.jersey.logging.LoggingFeature;43import org.glassfish.jersey.server.ResourceConfig;44import org.glassfish.jersey.servlet.ServletContainer;45import java.lang.reflect.InvocationTargetException;46import java.lang.reflect.Method;47import java.net.InetSocketAddress;48import java.sql.Connection;49import java.sql.SQLException;50import java.util.*;51import java.util.concurrent.ConcurrentHashMap;52import java.util.concurrent.CopyOnWriteArrayList;53import java.util.stream.Collectors;54/**55 * Abstract class used to connect to the EvoMaster process, and56 * that is responsible to start/stop/restart the tested application,57 * ie the system under test (SUT)58 */59public abstract class SutController implements SutHandler, CustomizationHandler {60 private int controllerPort = ControllerConstants.DEFAULT_CONTROLLER_PORT;61 private String controllerHost = ControllerConstants.DEFAULT_CONTROLLER_HOST;62 private final SqlHandler sqlHandler = new SqlHandler();63 private Server controllerServer;64 /**65 * If using a SQL Database, gather info about its schema66 */67 private DbSchemaDto schemaDto;68 /**69 * For each action in a test, keep track of the extra heuristics, if any70 */71 private final List<ExtraHeuristicsDto> extras = new CopyOnWriteArrayList<>();72 /**73 * track all tables accessed in a test74 */75 private final List<String> accessedTables = new CopyOnWriteArrayList<>();76 /**77 * a map of table to fk target tables78 */79 private final Map<String, List<String>> fkMap = new ConcurrentHashMap<>();80 /**81 * a map of table to a set of commands which are to insert data into the db82 */83 private final Map<String, List<String>> tableInitSqlMap = new ConcurrentHashMap<>();84 /**85 * a map of interface schemas for RPC service under test86 * - key is full name of the interface87 * - value is extracted interface schema88 */89 private final Map<String, InterfaceSchema> rpcInterfaceSchema = new LinkedHashMap <>();90 /**91 * a map of local auth setup schemas for RPC service under test92 * - key is the index of the auth info which is specified in the driver93 * - value is extracted local auth setup schema94 */95 private final Map<Integer, LocalAuthSetupSchema> localAuthSetupSchemaMap = new LinkedHashMap <>();96 /**97 * handle parsing RPCActionDto based on json string.98 * Note that it is only used for RPC99 */100 private ObjectMapper objectMapper;101 private int actionIndex = -1;102 /**103 * Start the controller as a RESTful server.104 * Use the setters of this class to change the default105 * port and host.106 * <br>107 * This method is blocking until the server is initialized.108 *109 * @return true if there was no problem in starting the controller110 */111 public final boolean startTheControllerServer() {112 //Jersey113 ResourceConfig config = new ResourceConfig();114 config.register(JacksonFeature.class);115 config.register(new EMController(this));116 config.register(LoggingFeature.class);117 //Jetty118 controllerServer = new Server(InetSocketAddress.createUnresolved(119 getControllerHost(), getControllerPort()));120 ErrorHandler errorHandler = new ErrorHandler();121 errorHandler.setShowStacks(true);122 controllerServer.setErrorHandler(errorHandler);123 ServletHolder servlet = new ServletHolder(new ServletContainer(config));124 ServletContextHandler context = new ServletContextHandler(controllerServer,125 ControllerConstants.BASE_PATH + "/*");126 context.addServlet(servlet, "/*");127 try {128 controllerServer.start();129 } catch (Exception e) {130 SimpleLogger.error("Failed to start Jetty: " + e.getMessage());131 controllerServer.destroy();132 }133 //just make sure we start from a clean state134 newSearch();135 SimpleLogger.info("Started controller server on: " + controllerServer.getURI());136 return true;137 }138 public final boolean stopTheControllerServer() {139 try {140 controllerServer.stop();141 return true;142 } catch (Exception e) {143 SimpleLogger.error("Failed to stop the controller server: " + e.toString());144 return false;145 }146 }147 /**148 * @return the actual port in use (eg, if it was an ephemeral 0)149 */150 public final int getControllerServerPort() {151 return ((AbstractNetworkConnector) controllerServer.getConnectors()[0]).getLocalPort();152 }153 public final int getControllerPort() {154 return controllerPort;155 }156 public final void setControllerPort(int controllerPort) {157 this.controllerPort = controllerPort;158 }159 public final String getControllerHost() {160 return controllerHost;161 }162 public final void setControllerHost(String controllerHost) {163 this.controllerHost = controllerHost;164 }165 @Override166 public InsertionResultsDto execInsertionsIntoDatabase(List<InsertionDto> insertions, InsertionResultsDto... previous) {167 Connection connection = getConnectionIfExist();168 if (connection == null) {169 throw new IllegalStateException("No connection to database");170 }171 try {172 return SqlScriptRunner.execInsert(connection, insertions, previous);173 } catch (SQLException e) {174 throw new RuntimeException(e);175 }176 }177 public int getActionIndex(){178 return actionIndex;179 }180 /**181 * Calculate heuristics based on intercepted SQL commands182 *183 * @param sql command as a string184 */185 @Deprecated186 public final void handleSql(String sql) {187 Objects.requireNonNull(sql);188 sqlHandler.handle(sql);189 }190 public final void enableComputeSqlHeuristicsOrExtractExecution(boolean enableSqlHeuristics, boolean enableSqlExecution){191 sqlHandler.setCalculateHeuristics(enableSqlHeuristics);192 sqlHandler.setExtractSqlExecution(enableSqlHeuristics || enableSqlExecution);193 }194 /**195 * This is needed only during test generation (not execution),196 * and it is automatically called by the EM controller after197 * the SUT is started.198 */199 public final void initSqlHandler() {200 sqlHandler.setConnection(getConnectionIfExist());201 sqlHandler.setSchema(getSqlDatabaseSchema());202 }203 /**204 * TODO further handle multiple connections205 * @return sql connection if there exists206 */207 public final Connection getConnectionIfExist(){208 return (getDbSpecifications() == null209 || getDbSpecifications().isEmpty())? null: getDbSpecifications().get(0).connection;210 }211 /**212 *213 * @return whether to employ smart db clean214 */215 public final boolean doEmploySmartDbClean(){216 return getDbSpecifications() != null217 && !getDbSpecifications().isEmpty() && getDbSpecifications().get(0).employSmartDbClean;218 }219 public final void resetExtraHeuristics() {220 sqlHandler.reset();221 }222 public final List<ExtraHeuristicsDto> getExtraHeuristics() {223 if (extras.size() == actionIndex) {224 extras.add(computeExtraHeuristics());225 }226 return new ArrayList<>(extras);227 }228 public final ExtraHeuristicsDto computeExtraHeuristics() {229 ExtraHeuristicsDto dto = new ExtraHeuristicsDto();230 if(sqlHandler.isCalculateHeuristics() || sqlHandler.isExtractSqlExecution()){231 /*232 TODO refactor, once we move SQL analysis into Core233 */234 List<AdditionalInfo> list = getAdditionalInfoList();235 if(!list.isEmpty()) {236 AdditionalInfo last = list.get(list.size() - 1);237 last.getSqlInfoData().stream().forEach(it -> {238// String sql = it.getCommand();239 try {240 sqlHandler.handle(it);241 } catch (Exception e){242 SimpleLogger.error("FAILED TO HANDLE SQL COMMAND: " + it.getCommand());243 assert false; //we should try to handle all cases in our tests244 }245 });246 }247 }248 if(sqlHandler.isCalculateHeuristics()) {249 sqlHandler.getDistances().stream()250 .map(p ->251 new HeuristicEntryDto(252 HeuristicEntryDto.Type.SQL,253 HeuristicEntryDto.Objective.MINIMIZE_TO_ZERO,254 p.sqlCommand,255 p.distance256 ))257 .forEach(h -> dto.heuristics.add(h));258 }259 if (sqlHandler.isCalculateHeuristics() || sqlHandler.isExtractSqlExecution()){260 ExecutionDto executionDto = sqlHandler.getExecutionDto();261 dto.databaseExecutionDto = executionDto;262 // set accessed table263 if (executionDto != null){264 accessedTables.addAll(executionDto.deletedData);265 accessedTables.addAll(executionDto.insertedData.keySet());266// accessedTables.addAll(executionDto.queriedData.keySet());267 accessedTables.addAll(executionDto.insertedData.keySet());268 accessedTables.addAll(executionDto.updatedData.keySet());269 }270 }271 return dto;272 }273 /**274 * perform smart db clean by cleaning the data in accessed table275 */276 public final void cleanAccessedTables(){277 if (getDbSpecifications() == null || getDbSpecifications().isEmpty()) return;278 if (getDbSpecifications().size() > 1)279 throw new RuntimeException("Error: DO NOT SUPPORT MULTIPLE SQL CONNECTION YET");280 DbSpecification emDbClean = getDbSpecifications().get(0);281 if (getConnectionIfExist() == null || !emDbClean.employSmartDbClean) return;282 try {283 setExecutingInitSql(true);284 // clean accessed tables285 Set<String> tableDataToInit = null;286 if (!accessedTables.isEmpty()){287 List<String> tablesToClean = new ArrayList<>();288 getTableToClean(accessedTables, tablesToClean);289 if (!tablesToClean.isEmpty()){290 if (emDbClean.schemaNames != null && !emDbClean.schemaNames.isEmpty()){291 emDbClean.schemaNames.forEach(sch-> DbCleaner.clearDatabase(getConnectionIfExist(), sch, null, tablesToClean, emDbClean.dbType));292 }else293 DbCleaner.clearDatabase(getConnectionIfExist(), null, null, tablesToClean, emDbClean.dbType);294 tableDataToInit = tablesToClean.stream().filter(a-> tableInitSqlMap.keySet().stream().anyMatch(t-> t.equalsIgnoreCase(a))).collect(Collectors.toSet());295 }296 }297 handleInitSql(tableDataToInit, emDbClean);298 }catch (SQLException e) {299 throw new RuntimeException("SQL Init Execution Error: fail to execute "+e);300 }finally {301 setExecutingInitSql(false);302 }303 }304 private void handleInitSql(Collection<String> tableDataToInit, DbSpecification spec) throws SQLException {305 // init db script306 boolean initAll = initSqlScriptAndGetInsertMap(getConnectionIfExist(), spec);307 if (!initAll && tableDataToInit!= null &&!tableDataToInit.isEmpty()){308 tableDataToInit.forEach(a->{309 tableInitSqlMap.keySet().stream().filter(t-> t.equalsIgnoreCase(a)).forEach(t->{310 tableInitSqlMap.get(t).forEach(c->{311 try {312 SqlScriptRunner.execCommand(getConnectionIfExist(), c);313 } catch (SQLException e) {314 throw new RuntimeException("SQL Init Execution Error: fail to execute "+ c + " with error "+e);315 }316 });317 });318 });319 }320 }321 /**322 * collect info about what table are manipulated by evo in order to generate data directly into it323 * @param tables a list of name of tables324 */325 public void addTableToInserted(List<String> tables){326 accessedTables.addAll(tables);327 }328 private void getTableToClean(List<String> accessedTables, List<String> tablesToClean){329 for (String t: accessedTables){330 if (!findInCollectionIgnoreCase(t, tablesToClean).isPresent()){331 if (findInMapIgnoreCase(t, fkMap).isPresent()){332 tablesToClean.add(t);333 List<String> fk = fkMap.entrySet().stream().filter(e->334 findInCollectionIgnoreCase(t, e.getValue()).isPresent()335 && !findInCollectionIgnoreCase(e.getKey(), tablesToClean).isPresent()).map(Map.Entry::getKey).collect(Collectors.toList());336 if (!fk.isEmpty())337 getTableToClean(fk, tablesToClean);338 }else {339 SimpleLogger.uniqueWarn("Cannot find the table "+t+" in ["+String.join(",", fkMap.keySet())+"]");340 }341 }342 }343 }344 private Optional<String> findInCollectionIgnoreCase(String name, Collection<String> list){345 return list.stream().filter(i-> i.equalsIgnoreCase(name)).findFirst();346 }347 private Optional<? extends Map.Entry<String, ?>> findInMapIgnoreCase(String name, Map<String, ?> list){348 return list.entrySet().stream().filter(x-> x.getKey().equalsIgnoreCase(name)).findFirst();349 }350 /**351 *352 * @param dbSpecification contains info of the db connection353 * @return whether the init script is executed354 */355 private boolean initSqlScriptAndGetInsertMap(Connection connection, DbSpecification dbSpecification) throws SQLException {356 if (dbSpecification.initSqlOnResourcePath == null357 && dbSpecification.initSqlScript == null) return false;358 // TODO to handle initSqlMap for multiple connections359 if (tableInitSqlMap.isEmpty()){360 List<String> all = new ArrayList<>();361 if (dbSpecification.initSqlOnResourcePath != null){362 all.addAll(SqlScriptRunnerCached.extractSqlScriptFromResourceFile(dbSpecification.initSqlOnResourcePath));363 }364 if (dbSpecification.initSqlScript != null){365 all.addAll(SqlScriptRunner.extractSql(dbSpecification.initSqlScript));366 }367 if (!all.isEmpty()){368 // collect insert sql commands map, key is table name, and value is a list sql insert commands369 tableInitSqlMap.putAll(SqlScriptRunner.extractSqlTableMap(all));370 // execute all commands371 SqlScriptRunner.runCommands(connection, all);372 return true;373 }374 }375 return false;376 }377 /**378 * Extra information about the SQL Database Schema, if any is present.379 * Note: this is extracted by querying the database itself.380 * So the database must be up and running.381 *382 * @return a DTO with the schema information383 * @see SutHandler#getDbSpecifications384 */385 public final DbSchemaDto getSqlDatabaseSchema() {386 if (schemaDto != null) {387 return schemaDto;388 }389 if (getDbSpecifications() == null || getDbSpecifications().isEmpty()) {390 return null;391 }392 try {393 schemaDto = SchemaExtractor.extract(getConnectionIfExist());394 Objects.requireNonNull(schemaDto);395 schemaDto.employSmartDbClean = doEmploySmartDbClean();396 } catch (Exception e) {397 SimpleLogger.error("Failed to extract the SQL Database Schema: " + e.getMessage());398 return null;399 }400 if (fkMap.isEmpty()){401 schemaDto.tables.forEach(t->{402 fkMap.putIfAbsent(t.name, new ArrayList<>());403 if (t.foreignKeys!=null && !t.foreignKeys.isEmpty()){404 t.foreignKeys.forEach(f->{405 fkMap.get(t.name).add(f.targetTable.toUpperCase());406 });407 }408 });409 }410 return schemaDto;411 }412 /**413 *414 * @return a map from the name of interface to extracted interface415 */416 public final Map<String, InterfaceSchema> getRPCSchema(){417 return rpcInterfaceSchema;418 }419 /**420 *421 * @return a map of auth local method422 */423 public Map<Integer, LocalAuthSetupSchema> getLocalAuthSetupSchemaMap() {424 return localAuthSetupSchemaMap;425 }426 /**427 * extract endpoints info of the RPC interface by reflection based on the specified service interface name428 */429 @Override430 public final void extractRPCSchema(){431 if (objectMapper == null)432 objectMapper = new ObjectMapper();433 if (!rpcInterfaceSchema.isEmpty())434 return;435 if (!(getProblemInfo() instanceof RPCProblem)){436 SimpleLogger.error("Problem ("+getProblemInfo().getClass().getSimpleName()+") is not RPC but request RPC schema.");437 return;438 }439 try {440 RPCEndpointsBuilder.validateCustomizedValueInRequests(getCustomizedValueInRequests());441 RPCEndpointsBuilder.validateCustomizedNotNullAnnotationForRPCDto(specifyCustomizedNotNullAnnotation());442 RPCProblem rpcp = (RPCProblem) getProblemInfo();443 for (String interfaceName: rpcp.getMapOfInterfaceAndClient()){444 InterfaceSchema schema = RPCEndpointsBuilder.build(interfaceName, rpcp.getType(), rpcp.getClient(interfaceName),445 rpcp.skipEndpointsByName!=null? rpcp.skipEndpointsByName.get(interfaceName):null,446 rpcp.skipEndpointsByAnnotation!=null?rpcp.skipEndpointsByAnnotation.get(interfaceName):null,447 rpcp.involveEndpointsByName!=null? rpcp.involveEndpointsByName.get(interfaceName):null,448 rpcp.involveEndpointsByAnnotation!=null? rpcp.involveEndpointsByAnnotation.get(interfaceName):null,449 getInfoForAuthentication(),450 getCustomizedValueInRequests(),451 specifyCustomizedNotNullAnnotation());452 rpcInterfaceSchema.put(interfaceName, schema);453 }454 localAuthSetupSchemaMap.clear();455 Map<Integer, LocalAuthSetupSchema> local = RPCEndpointsBuilder.buildLocalAuthSetup(getInfoForAuthentication());456 if (local!=null && !local.isEmpty())457 localAuthSetupSchemaMap.putAll(local);458 }catch (Exception e){459// SimpleLogger.error("Failed to extract the RPC Schema: " + e.getMessage());460 throw new RuntimeException("Failed to extract the RPC Schema: " + e.getMessage());461 }462 }463 /**464 * parse seeded tests for RPC465 * @return a list of tests, and each test is a list of RCPActionDto466 */467 public List<List<RPCActionDto>> handleSeededTests(){468 if (seedRPCTests() == null || seedRPCTests().isEmpty()) return null;469 if (rpcInterfaceSchema.isEmpty())470 throw new IllegalStateException("empty RPC interface: The RPC interface schemas are not extracted yet");471 List<List<RPCActionDto>> results = new ArrayList<>();472 for (SeededRPCTestDto dto: seedRPCTests()){473 if (dto.rpcFunctions != null && !dto.rpcFunctions.isEmpty()){474 List<RPCActionDto> test = new ArrayList<>();475 for (SeededRPCActionDto actionDto : dto.rpcFunctions){476 InterfaceSchema schema = rpcInterfaceSchema.get(actionDto.interfaceName);477 if (schema != null){478 EndpointSchema actionSchema = schema.getOneEndpointWithSeededDto(actionDto);479 if (actionSchema != null){480 EndpointSchema copy = actionSchema.copyStructure();481 for (int i = 0; i < copy.getRequestParams().size(); i++){482 // TODO need to check if generic type could be handled with jackson483 NamedTypedValue p = copy.getRequestParams().get(i);484 try {485 String stringValue = actionDto.inputParams.get(i);486// Object value = objectMapper.readValue(stringValue, p.getType().getClazz());487 p.setValueBasedOnInstanceOrJson(stringValue);488 } catch (JsonProcessingException e) {489 throw new IllegalStateException(490 String.format("Seeded Test Error: cannot parse the seeded test %s at the parameter %d with error msg: %s", actionDto, i, e.getMessage()));491 }492 }493 test.add(copy.getDto());494 }else {495 throw new IllegalStateException("Seeded Test Error: cannot find the action "+actionDto.functionName);496 }497 } else {498 throw new IllegalStateException("Seeded Test Error: cannot find the interface "+ actionDto.interfaceName);499 }500 }501 results.add(test);502 } else {503 SimpleLogger.warn("Seeded Test: empty RPC function calls for the test "+ dto.testName);504 }505 }506 return results;507 }508 /**509 * Either there is no connection, or, if there is, then it must have P6Spy configured.510 * But this might not apply to all kind controllers511 *512 * @return false if the verification failed513 */514 @Deprecated515 public final boolean verifySqlConnection(){516 return true;517// Connection connection = getConnection();518// if(connection == null519// //check does not make sense for External520// || !(this instanceof EmbeddedSutController)){521// return true;522// }523//524// /*525// bit hacky/brittle, but seems there is no easy way to check if a connection is526// using P6Spy.527// However, the name of driver's package would appear when doing a toString on it528// */529// String info = connection.toString();530//531// return info.contains("p6spy");532 }533 /**534 * Re-initialize all internal data to enable a completely new search phase535 * which should be independent from previous ones536 */537 public abstract void newSearch();538 /**539 * Re-initialize some internal data needed before running a new test540 */541 public final void newTest() {542 actionIndex = -1;543 resetExtraHeuristics();544 extras.clear();545 //clean all accessed table in a test546 accessedTables.clear();547 newTestSpecificHandler();548 // set executingAction state false for newTest549 setExecutingAction(false);550 }551 /**552 * As some heuristics are based on which action (eg HTTP call, or click of button)553 * in the test sequence is executed, and their order, we need to keep track of which554 * action does cover what.555 *556 * @param dto the DTO with the information about the action (eg its index in the test)557 */558 public final void newAction(ActionDto dto) {559 if (dto.index > extras.size()) {560 extras.add(computeExtraHeuristics());561 }562 this.actionIndex = dto.index;563 resetExtraHeuristics();564 newActionSpecificHandler(dto);565 }566 public final void executeHandleLocalAuthenticationSetup(RPCActionDto dto, ActionResponseDto responseDto){567 LocalAuthSetupSchema endpointSchema = new LocalAuthSetupSchema();568 endpointSchema.setValue(dto);569 handleLocalAuthenticationSetup(endpointSchema.getAuthenticationInfo());570 if (dto.responseVariable != null && dto.doGenerateTestScript){571 responseDto.testScript = endpointSchema.newInvocationWithJava(dto.responseVariable, dto.controllerVariable,dto.clientVariable);572 }573 }574 /**575 * execute a RPC request based on the specified dto576 * @param dto is the action DTO to be executed577 */578 public final void executeAction(RPCActionDto dto, ActionResponseDto responseDto) {579 EndpointSchema endpointSchema = getEndpointSchema(dto);580 if (dto.responseVariable != null && dto.doGenerateTestScript){581 try{582 responseDto.testScript = endpointSchema.newInvocationWithJava(dto.responseVariable, dto.controllerVariable,dto.clientVariable);583 }catch (Exception e){584 SimpleLogger.warn("Fail to generate test script"+e.getMessage());585 }586 if (responseDto.testScript ==null)587 SimpleLogger.warn("Null test script for action "+dto.actionName);588 }589 Object response;590 try {591 response = executeRPCEndpoint(dto, false);592 } catch (Exception e) {593 throw new RuntimeException("ERROR: target exception should be caught, but "+ e.getMessage());594 }595 //handle exception596 if (response instanceof Exception){597 try{598 RPCExceptionHandler.handle(response, responseDto, endpointSchema, getRPCType(dto));599 return;600 } catch (Exception e){601 SimpleLogger.error("ERROR: fail to handle exception instance to dto "+ e.getMessage());602 //throw new RuntimeException("ERROR: fail to handle exception instance to dto "+ e.getMessage());603 }604 }605 if (endpointSchema.getResponse() != null){606 if (response != null){607 try{608 // successful execution609 NamedTypedValue resSchema = endpointSchema.getResponse().copyStructureWithProperties();610 resSchema.setValueBasedOnInstance(response);611 responseDto.rpcResponse = resSchema.getDto();612 if (dto.doGenerateAssertions && dto.responseVariable != null)613 responseDto.assertionScript = resSchema.newAssertionWithJava(dto.responseVariable, dto.maxAssertionForDataInCollection);614 else615 responseDto.jsonResponse = objectMapper.writeValueAsString(response);616 } catch (Exception e){617 SimpleLogger.error("ERROR: fail to set successful response instance value to dto "+ e.getMessage());618 //throw new RuntimeException("ERROR: fail to set successful response instance value to dto "+ e.getMessage());619 }620 try {621 responseDto.customizedCallResultCode = categorizeBasedOnResponse(response);622 } catch (Exception e){623 SimpleLogger.error("ERROR: fail to categorize result with implemented categorizeBasedOnResponse "+ e.getMessage());624 //throw new RuntimeException("ERROR: fail to categorize result with implemented categorizeBasedOnResponse "+ e.getMessage());625 }626 }627 }628 }629 private Object executeRPCEndpoint(RPCActionDto dto, boolean throwTargetException) throws Exception {630 Object client = ((RPCProblem)getProblemInfo()).getClient(dto.interfaceId);631 EndpointSchema endpointSchema = getEndpointSchema(dto);632 return executeRPCEndpointCatchTargetException(client, endpointSchema, throwTargetException);633 }634 private Object executeRPCEndpointCatchTargetException(Object client, EndpointSchema endpoint, boolean throwTargetException) throws Exception {635 Object res;636 try {637 res = executeRPCEndpoint(client, endpoint);638 } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {639 throw new RuntimeException("EM RPC REQUEST EXECUTION ERROR: fail to process a RPC request with "+ e.getMessage());640 } catch (InvocationTargetException e) {641 if (throwTargetException)642 throw (Exception) e.getTargetException();643 else644 res = e.getTargetException();645 } catch (Exception e){646 SimpleLogger.error("ERROR: other exception exists "+ e.getMessage());647 if (throwTargetException) throw e;648 else res = e;649 }650 return res;651 }652 @Override653 public Object executeRPCEndpoint(String json) throws Exception{654 try {655 RPCActionDto dto = objectMapper.readValue(json, RPCActionDto.class);656 return executeRPCEndpoint(dto, true);657 } catch (JsonProcessingException e) {658 SimpleLogger.error("Failed to extract the json: " + e.getMessage());659 }660 return null;661 }662 /**663 * execute a RPC request with specified client664 * @param client is the client to execute the endpoint665 * @param endpoint is the endpoint to be executed666 */667 private final Object executeRPCEndpoint(Object client, EndpointSchema endpoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException {668 if (endpoint.getRequestParams().isEmpty()){669 Method method = client.getClass().getDeclaredMethod(endpoint.getName());670 return method.invoke(client);671 }672 Object[] params = new Object[endpoint.getRequestParams().size()];673 Class<?>[] types = new Class<?>[endpoint.getRequestParams().size()];674 try{675 for (int i = 0; i < params.length; i++){676 NamedTypedValue param = endpoint.getRequestParams().get(i);677 params[i] = param.newInstance();678 types[i] = param.getType().getClazz();679 }680 } catch (Exception e){681 throw new RuntimeException("ERROR: fail to instance value of input parameters based on dto/schema, msg error:"+e.getMessage());682 }683 Method method = client.getClass().getDeclaredMethod(endpoint.getName(), types);684 return method.invoke(client, params);685 }686 private EndpointSchema getEndpointSchema(RPCActionDto dto){687 InterfaceSchema interfaceSchema = rpcInterfaceSchema.get(dto.interfaceId);688 EndpointSchema endpointSchema = interfaceSchema.getOneEndpoint(dto).copyStructure();689 endpointSchema.setValue(dto);690 return endpointSchema;691 }692 private RPCType getRPCType(RPCActionDto dto){693 return rpcInterfaceSchema.get(dto.interfaceId).getRpcType();694 }695 public abstract void newTestSpecificHandler();696 public abstract void newActionSpecificHandler(ActionDto dto);697 /**698 * Check if bytecode instrumentation is on.699 *700 * @return true if the instrumentation is on701 */702 public abstract boolean isInstrumentationActivated();703 /**704 * <p>705 * Check if the system under test (SUT) is running and fully initialized706 * </p>707 *708 * <p>709 * How to implement this method depends on the library/framework used710 * to build the application.711 * In Spring applications, this can be done with something like:712 * {@code ctx != null && ctx.isRunning()}, where {@code ctx} is a field where713 * {@code ConfigurableApplicationContext} should be stored when starting714 * the application.715 * </p>716 * @return true if the SUT is running717 */718 public abstract boolean isSutRunning();719 /**720 * <p>721 * A "," separated list of package prefixes or class names.722 * For example, "com.foo.,com.bar.Bar".723 * This is used to specify for which classes we want to measure724 * code coverage.725 * </p>726 *727 * <p>728 * Note: be careful of using something as general as "com."729 * or "org.", as most likely ALL your third-party libraries730 * would be instrumented as well, which could have a severe731 * impact on performance.732 * </p>733 *734 * @return a String representing the packages to cover735 */736 public abstract String getPackagePrefixesToCover();737 /**738 * <p>739 * If the application uses some sort of authentication, these details740 * need to be provided here.741 * Even if EvoMaster can have access to the database, it would not be able742 * to recover hashed passwords.743 * </p>744 *745 * <p>746 * To test the application, there is the need to provide auth for at least 1 user747 * (and more if they have different authorization roles).748 * When EvoMaster generates test cases, it can decide to use the credential of749 * any user provided by this method.750 * </p>751 *752 * <p>753 * What type of info to provide here depends on the auth mechanism, e.g.,754 * Basic or cookie-based (using {@link CookieLoginDto}).755 * To simplify the creation of these DTOs with auth info, you can look756 * at {@link org.evomaster.client.java.controller.AuthUtils}.757 * </p>758 *759 * <p>760 * If the credential are stored in a database, be careful on how the761 * method {@code resetStateOfSUT} is implemented.762 * If you delete all data with {@link DbCleaner}, then you will need as well to763 * recreate the auth details.764 * This can be put in a script, executed then with {@link SqlScriptRunner}.765 * </p>766 *767 * @return a list of valid authentication credentials, or {@code null} if768 * * none is necessary769 */770 public abstract List<AuthenticationDto> getInfoForAuthentication();771 /**772 * <p>773 * If the system under test (SUT) uses a SQL database, we need to have a774 * configured connection to access it.775 * </p>776 *777 * <p>778 * This method is related to {@link SutHandler#resetStateOfSUT}.779 * When accessing a {@code Connection} object to reset the state of780 * the application, we suggest to save it to field (eg when starting the781 * application), and return such field here, e.g., {@code return connection;}.782 * This connection object will be used by EvoMaster to analyze the state of783 * the database to create better test cases.784 * </p>785 *786 * @return {@code null} if the SUT does not use any SQL database787 */788 @Deprecated789 public Connection getConnection(){790 throw new IllegalStateException("This deprecated method should never be called");791 }792 /**793 * If the system under test (SUT) uses a SQL database, we need to specify794 * the driver used to connect, eg. {@code org.h2.Driver}.795 * This is needed for when we intercept SQL commands with P6Spy796 *797 * @return {@code null} if the SUT does not use any SQL database798 * @deprecated this method is no longer needed799 */800 @Deprecated801 public String getDatabaseDriverName(){802 throw new IllegalStateException("This deprecated method should never be called");803 }804 public abstract List<TargetInfo> getTargetInfos(Collection<Integer> ids);805 /**806 * @return additional info for each action in the test.807 * The list is ordered based on the action index.808 */809 public abstract List<AdditionalInfo> getAdditionalInfoList();810 /**811 * <p>812 * Depending of which kind of SUT we are dealing with (eg, REST, GraphQL or SPA frontend),813 * there is different info that must be provided.814 * For example, in a RESTful API, you need to speficy where the OpenAPI/Swagger schema815 * is located.816 * </p>817 *818 * <p>819 * The interface {@link ProblemInfo} provides different implementations, like820 * {@code RestProblem}.821 * You will need to instantiate one of such classes, and return it here in this method.822 * </p>823 * @return an instance of object with all the needed data for the specific addressed problem824 */825 public abstract ProblemInfo getProblemInfo();826 /**827 * Test cases could be outputted in different language (e.g., Java and Kotlin),828 * using different testing libraries (e.g., JUnit 4 or 5).829 * Here, need to specify the default option.830 *831 * @return the format in which the test cases should be generated832 */833 public abstract SutInfoDto.OutputFormat getPreferredOutputFormat();834 public abstract UnitsInfoDto getUnitsInfoDto();835 public abstract void setKillSwitch(boolean b);836 public abstract void setExecutingInitSql(boolean executingInitSql);837 public abstract void setExecutingAction(boolean executingAction);838 public abstract BootTimeInfoDto getBootTimeInfoDto();839 protected BootTimeInfoDto getBootTimeInfoDto(BootTimeObjectiveInfo info){840 if (info == null)841 return null;842 BootTimeInfoDto infoDto = new BootTimeInfoDto();843 infoDto.targets = info.getObjectiveCoverageAtSutBootTime()844 .entrySet().stream().map(e-> new TargetInfoDto(){{845 descriptiveId = e.getKey();846 value = e.getValue();847 }}).collect(Collectors.toList());848 infoDto.externalServicesDto = info.getExternalServiceInfo().stream()849 .map(e -> new ExternalServiceInfoDto(e.getProtocol(), e.getHostname(), e.getRemotePort()))850 .collect(Collectors.toList());851 return infoDto;852 }853 public abstract String getExecutableFullPath();854 protected UnitsInfoDto getUnitsInfoDto(UnitsInfoRecorder recorder){855 if(recorder == null){856 return null;857 }858 UnitsInfoDto dto = new UnitsInfoDto();859 dto.numberOfBranches = recorder.getNumberOfBranches();860 dto.numberOfLines = recorder.getNumberOfLines();861 dto.numberOfReplacedMethodsInSut = recorder.getNumberOfReplacedMethodsInSut();862 dto.numberOfReplacedMethodsInThirdParty = recorder.getNumberOfReplacedMethodsInThirdParty();863 dto.numberOfTrackedMethods = recorder.getNumberOfTrackedMethods();864 dto.unitNames = recorder.getUnitNames();865 dto.parsedDtos = recorder.getParsedDtos();866 dto.numberOfInstrumentedNumberComparisons = recorder.getNumberOfInstrumentedNumberComparisons();867 return dto;868 }869 @Override870 public Object getRPCClient(String interfaceName) {871 if (!(getProblemInfo() instanceof RPCProblem))872 throw new RuntimeException("ERROR: the problem should be RPC but it is "+ getProblemInfo().getClass().getSimpleName());873 Object client = ((RPCProblem) getProblemInfo()).getClient(interfaceName);874 if (client == null)875 throw new RuntimeException("ERROR: cannot find any client with the name :"+ interfaceName);876 return client;877 }878 @Override879 public CustomizedCallResultCode categorizeBasedOnResponse(Object response) {880 return null;881 }882 @Override883 public List<CustomizedRequestValueDto> getCustomizedValueInRequests() {884 return null;885 }886 @Override887 public List<CustomizedNotNullAnnotationForRPCDto> specifyCustomizedNotNullAnnotation() {888 return null;889 }890 @Override891 public List<SeededRPCTestDto> seedRPCTests() {892 return null;893 }894 @Override895 public void resetDatabase(List<String> tablesToClean) {896 if (getDbSpecifications()!= null && !getDbSpecifications().isEmpty()){897 getDbSpecifications().forEach(spec->{898 if (spec==null || spec.connection == null || !spec.employSmartDbClean){899 return;900 }901 if (spec.schemaNames == null || spec.schemaNames.isEmpty())902 DbCleaner.clearDatabase(spec.connection, null, null, tablesToClean, spec.dbType);903 else904 spec.schemaNames.forEach(sp-> DbCleaner.clearDatabase(spec.connection, sp, null, tablesToClean, spec.dbType));905 try {906 handleInitSql(tablesToClean, spec);907 } catch (SQLException e) {908 throw new RuntimeException("Fail to execute the specified initSqlScript "+e);909 }910 });911 }912 }913}...

Full Screen

Full Screen

Source:RPCExceptionHandler.java Github

copy

Full Screen

...10import java.lang.reflect.InvocationTargetException;11import java.lang.reflect.Method;12import java.lang.reflect.UndeclaredThrowableException;13/**14 * handle RPC exception, for instance15 * - extract possible category eg, application, protocol, if possible16 * - extract exception info, eg, customized exception, message, or status code17 */18public class RPCExceptionHandler {19 private final static String THRIFT_EXCEPTION_ROOT= "org.apache.thrift.TException";20 /**21 *22 * @param e is an exception instance thrown after the endpoint invocation23 * @param dto represents the endpoint which was invoked24 * @param endpointSchema is the schema of the endpoint25 * @param type is the RPC type26 */27 public static void handle(Object e, ActionResponseDto dto, EndpointSchema endpointSchema, RPCType type){28 Object exceptionToHandle = e;29 boolean isCause = false;30 // handle undeclared throwable exception31 if (UndeclaredThrowableException.class.isAssignableFrom(e.getClass())){32 Object cause = getExceptionCause(e);33 if (cause != null){34 exceptionToHandle = cause;35 isCause = true;36 }37 }38 boolean handled = false;39 RPCExceptionInfoDto exceptionInfoDto = null;40 try {41 exceptionInfoDto = handleExceptionNameAndMessage(exceptionToHandle);42 handled = handleDefinedException(exceptionToHandle, endpointSchema, type, exceptionInfoDto);43 if (handled) {44 dto.exceptionInfoDto = exceptionInfoDto;45 dto.exceptionInfoDto.isCauseOfUndeclaredThrowable = isCause;46 return;47 }48 } catch (ClassNotFoundException ex) {49 dto.exceptionInfoDto = exceptionInfoDto;50 throw new RuntimeException("ERROR: fail to handle defined exception for "+type+" with error msg:"+ ex);51 }52 // handling defined exception for each RPC53 switch (type){54 case THRIFT: handled = handleThrift(exceptionToHandle, endpointSchema, exceptionInfoDto); break;55 case GENERAL: break; // do nothing56 default: throw new RuntimeException("ERROR: NOT SUPPORT exception handling for "+type);57 }58 if (!handled) {59 handleUnexpectedException(exceptionToHandle, exceptionInfoDto);60 }61 dto.exceptionInfoDto = exceptionInfoDto;62 dto.exceptionInfoDto.isCauseOfUndeclaredThrowable = isCause;63 }64 private static void handleUnexpectedException(Object e, RPCExceptionInfoDto dto){65 dto.type = RPCExceptionType.UNEXPECTED_EXCEPTION;66 }67 private static RPCExceptionInfoDto handleExceptionNameAndMessage(Object e){68 RPCExceptionInfoDto dto = new RPCExceptionInfoDto();69 if (Exception.class.isAssignableFrom(e.getClass())){70 dto.exceptionName = e.getClass().getName();71 dto.exceptionMessage = getExceptionMessage(e);72 }else73 SimpleLogger.error("ERROR: the exception is not java.lang.Exception "+e.getClass().getName());74 return dto;75 }76 /**77 * handle exceptions from thrift78 * https://javadoc.io/doc/org.apache.thrift/libthrift/latest/org/apache/thrift/TException.html79 * @param e is an exception thrown from the rpc call execution80 * @param endpointSchema is the schema of this endpoint81 * @return extracted exception dto82 */83 private static boolean handleThrift(Object e, EndpointSchema endpointSchema, RPCExceptionInfoDto dto) {84 boolean handled = false;85 try {86 if (!isRootThriftException(e)){87 //SimpleLogger.info("Exception e is not an instance of TException of Thrift, and it is "+ e.getClass().getName());88 return false;89 }90 handled = handleTException(e, dto);91 if (!handled){92 SimpleLogger.error("Fail to extract exception type info for an exception "+ e.getClass().getName());93 }94 } catch (ClassNotFoundException ex) {95 SimpleLogger.error("ERROR: in handling Thrift exception with error msg:"+ex.getMessage());96 //throw new IllegalStateException("ERROR: in handling Thrift exception with error msg:"+ex.getMessage());97 }98 return handled;99 }100 private static boolean handleDefinedException(Object e, EndpointSchema endpointSchema, RPCType rpcType, RPCExceptionInfoDto dto) throws ClassNotFoundException {101 if (endpointSchema.getExceptions() == null) return false;102 for (NamedTypedValue p : endpointSchema.getExceptions()){103 String type = p.getType().getFullTypeNameWithGenericType();104 // skip to handle root TException here105 if (rpcType == RPCType.THRIFT && type.equals(THRIFT_EXCEPTION_ROOT))106 continue;107 if (isInstanceOf(e, type)){108 p.setValueBasedOnInstance(e);109 dto.exceptionDto = p.getDto();110 dto.type = RPCExceptionType.CUSTOMIZED_EXCEPTION;111 return true;112 }113 }114 return false;115 }116 private static boolean handleTException(Object e, RPCExceptionInfoDto dto) {117 Method getType = null;118 try {119 getType = e.getClass().getDeclaredMethod("getType");120 getType.setAccessible(true);121 int type = (int) getType.invoke(e);122 dto.type = getExceptionType(extract(e), type);123 return true;124 } catch (NoSuchMethodException | ClassNotFoundException | InvocationTargetException | IllegalAccessException ex) {125 SimpleLogger.error("Fail to get type of TException with getType() "+ex.getMessage());126 }127 return false;128 }129 private static String getExceptionMessage(Object e) {130 Method getMessage = null;...

Full Screen

Full Screen

handle

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.api.dto.SutInfoDto;2import org.evomaster.client.java.controller.api.dto.TestResultsDto;3import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseExecutionDto;4import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseRowDto;5import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;6import org.evomaster.client.java.controller.api.dto.database.operations.QueryDto;7import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;8import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;9import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;10import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto;11import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexType;12import org.evomaster.client.java.controller.api.dto.database.schema.TableSchemaDto;13import org.evomaster.client.java.controller.api.dto.database.schema.TableType;14import org.evomaster.client.java.controller.api.dto.database.schema.ViewDto;15import org.evomaster.client.java.controller.api.dto.database.schema.ViewSchemaDto;16import org.evomaster.client.java.controller.api.dto.error.ErrorDto;17import org.evomaster.client.java.controller.api.dto.error.StackTraceDto;18import org.evomaster.client.java.controller.api.dto.error.StackTraceElementDto;19import org.evomaster.client.java.controller.api.dto.problem.ProblemInfoDto;20import org.evomaster.client.java.controller.api.dto.problem.RestProblemDto;21import org.evomaster.client.java.controller.api.dto.problem.RestResourceCallsDto;22import org.evomaster.client.java.controller.api.dto.problem.RestResourceDto;23import org.evomaster.client.java.controller.api.dto.problem.RestSpecDto;24import org.evomaster.client.java.controller.api.dto.problem.RestSpecMethodDto;25import org.evomaster.client.java.controller.api.dto.problem.RestSpecResponseDto;26import org.evomaster.client.java.controller.api.dto.problem.TestInfoDto;27import org.evomaster.client.java.controller.api.dto.problem.TestResultsStatusDto;28import org.evomaster.client.java.controller.api.dto.problem.TestRunResultDto;29import org.evomaster.client.java.controller.api.dto.problem.TestRunResultsDto;30import org.evomaster.client.java.controller.api.dto.sut.SutInfoDto;31import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationDto;32import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationInfoDto;33import

Full Screen

Full Screen

handle

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller.problem.rpc;2import org.evomaster.client.java.controller.problem.RestProblem;3import org.evomaster.client.java.controller.problem.RestProblemException;4import org.evomaster.client.java.controller.problem.RestProblemHandler;5import org.evomaster.client.java.controller.problem.RestProblemHandling;6import org.evomaster.client.java.controller.problem.RestProblemHandlingStatus;7import java.util.Arrays;8import java.util.List;9import static org.evomaster.client.java.controller.problem.RestProblemHandlingStatus.*;10public class RPCExceptionHandler implements RestProblemHandler {11 public List<RestProblemHandling> getRestProblemsHandled() {12 return Arrays.asList(13 new RestProblemHandling(RPCException.class, this::handle)14 );15 }16 private RestProblemHandlingStatus handle(RestProblem problem) {17 if (problem == null || problem.getException() == null) {18 return NOT_HANDLED;19 }20 if (problem.getException() instanceof RPCException) {21 RPCException e = (RPCException) problem.getException();22 throw new RPCException(e.getMessage(), e.getErrorCode(), e.getDetails());23 }24 return NOT_HANDLED;25 }26}27package org.evomaster.client.java.controller.problem.rpc;28import com.google.gson.JsonObject;29import org.evomaster.client.java.controller.problem.RestProblemException;30public class RPCException extends RestProblemException {31 private final int errorCode;32 private final JsonObject details;33 public RPCException(String message, int errorCode, JsonObject details) {34 super(message);35 this.errorCode = errorCode;36 this.details = details;37 }38 public int getErrorCode() {39 return errorCode;40 }41 public JsonObject getDetails() {42 return details;43 }44}45package org.evomaster.client.java.controller.problem.rpc;46import com.google.gson.JsonObject;47import org.evomaster.client.java.controller.problem.RestProblemException;48public class RPCException extends RestProblemException {49 private final int errorCode;50 private final JsonObject details;51 public RPCException(String message, int errorCode, JsonObject details) {52 super(message);

Full Screen

Full Screen

handle

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller.problem.rpc;2import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;3import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseResultDto;4import org.evomaster.client.java.controller.api.dto.database.operations.QueryDto;5import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;6import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;7import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;8import org.evomaster.client.java.controller.api.dto.problem.RestCallResultDto;9import org.evomaster.client.java.controller.api.dto.problem.RestCallResultsDto;10import org.evomaster.client.java.controller.api.dto.problem.RestIndividualDto;11import org.evomaster.client.java.controller.api.dto.problem.RestProblemDto;12import org.evomaster.client.java.controller.api.dto.problem.RestResourceCallsDto;13import org.evomaster.client.java.controller.api.dto.problem.TestResultsDto;14import org.evomaster.client.java.controller.api.dto.sut.SutInfoDto;15import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationDto;16import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationHeaderDto;17import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationResponseDto;18import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationTokenDto;19import org.evomaster.client.java.controller.api.dto.sut.auth.FormLoginDto;20import org.evomaster.client.java.controller.api.dto.sut.auth.FormLoginTokenDto;21import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2Dto;22import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2TokenDto;23import org.evomaster.client.java.controller.api.dto.sut.auth.SessionDto;24import org.evomaster.client.java.controller.api.dto.sut.auth.SessionTokenDto;25import org.evomaster.client.java.controller.api.dto.sut.auth.SimpleDto;26import org.evomaster.client.java.controller.api.dto.sut.auth.SimpleTokenDto;27import org.evomaster.client.java.controller.api.dto.sut.system.ExecutionDto;28import org.evomaster.client.java.controller.api.dto.sut.system.ExecutionResultDto;29import org.evomaster.client.java.controller.api.dto.sut.system.SystemInfoDto;30import org.evomaster.client.java.controller.api.dto.sut.system.SystemResourceDto;31import org.evomaster

Full Screen

Full Screen

handle

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;2import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;3import org.evomaster.client.java.controller.api.dto.database.operations.QueryDto;4import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;5import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;6import org.evomaster.client.java.controller.api.dto.database.schema.DbActionDto;7import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;8import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto;9import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexType;10import org.evomaster.client.java.controller.api.dto.database.schema.TableSchemaDto;11import org.evomaster.client.java.controller.api.dto.database.schema.TableType;12import org.evomaster.client.java.controller.api.dto.database.operations.DeleteDto;13import org.evomaster.client.java.controller.api.dto.database.operations.UpdateDto;14import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;15import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;16import org.evomaster.client.java.controller.api.dto.database.operations.QueryDto;17import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;18import org.evomaster.client.java.controller.api.dto.database.schema.TableType;19import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexType;20import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto;21import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;22import org.evomaster.client.java.controller.api.dto.database.schema.TableSchemaDto;23import org.evomaster.client.java.controller.api.dto.database.schema.DbActionDto;24import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;25import org.evomaster.client.java.controller.problem.rpc.RPCException;26import org.evomaster.client.java.controller.problem.rpc.RPCExceptionInfo;27import org.evomaster.client.java.controller.problem.rpc.RPCProblem;28import org.evomaster.client.java.controller.problem.rpc.RPCRequest;29import org.evomaster.client.java.controller.problem.rpc.RPCResponse;30import org.evomaster.client.java.controller.problem.rpc.RPCResult;31import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;32import org.evomaster.client.java.controller.problem.rpc.RPCExceptionInfo;33import org

Full Screen

Full Screen

handle

Using AI Code Generation

copy

Full Screen

1public class 3 {2public static void main(String[] args) {3RPCExceptionHandler handler = new RPCExceptionHandler();4try {5throw new Exception("test");6} catch (Exception e) {7handler.handle(e);8}9}10}11public class 4 {12public static void main(String[] args) {13RestExceptionHandler handler = new RestExceptionHandler();14try {15throw new Exception("test");16} catch (Exception e) {17handler.handle(e);18}19}20}21public class 5 {22public static void main(String[] args) {23RestIndividual individual = new RestIndividual();24try {25throw new Exception("test");26} catch (Exception e) {27individual.handle(e);28}29}30}31public class 6 {32public static void main(String[] args) {33RestIndividual individual = new RestIndividual();34try {35throw new Exception("test");36} catch (Exception e) {37individual.handle(e);38}39}40}41public class 7 {42public static void main(String[] args) {43RestIndividual individual = new RestIndividual();44try {45throw new Exception("test");46} catch (Exception e) {47individual.handle(e);48}49}50}51public class 8 {52public static void main(String[] args) {53RestIndividual individual = new RestIndividual();54try {55throw new Exception("test");56} catch (Exception e) {57individual.handle(e);58}59}60}61public class 9 {62public static void main(String[] args) {63RestIndividual individual = new RestIndividual();64try {65throw new Exception("test");66} catch (Exception e) {67individual.handle(e);68}69}70}

Full Screen

Full Screen

handle

Using AI Code Generation

copy

Full Screen

1public class 3 {2 public static void main(String[] args) {3 int port = 8080;4 String host = "localhost";5 String path = "/api/v1/3";6 String method = "POST";7 String body = "{\"a\":1,\"b\":2,\"c\":3}";8 String contentType = "application/json";9 String accept = "application/json";10 try {11 org.evomaster.client.java.controller.problem.rpc.RPCResult result = org.evomaster.client.java.controller.problem.rpc.RPCController.handle(url, path, method, body, contentType, accept);12 System.out.println(result.getBody());13 } catch (Exception e) {14 org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.handle(e);15 }16 }17}18public class 4 {19 public static void main(String[] args) {20 int port = 8080;21 String host = "localhost";22 String path = "/api/v1/4";23 String method = "POST";24 String body = "{\"a\":1,\"b\":2,\"c\":3}";25 String contentType = "application/json";26 String accept = "application/json";27 try {28 org.evomaster.client.java.controller.problem.rpc.RPCResult result = org.evomaster.client.java.controller.problem.rpc.RPCController.handle(url, path, method, body, contentType, accept);29 System.out.println(result.getBody());30 } catch (Exception e) {31 org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.handle(e);32 }33 }34}35public class 5 {36 public static void main(String[] args) {37 int port = 8080;38 String host = "localhost";39 String path = "/api/v1/5";40 String method = "POST";

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