Best EvoMaster code snippet using org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.extract
Source:SutController.java
...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()];...
Source:RPCExceptionHandler.java
...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;131 try {132 getMessage = e.getClass().getMethod("getMessage");133 getMessage.setAccessible(true);134 return (String) getMessage.invoke(e);135 } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {136 SimpleLogger.error("Error: fail to get message of the exception with "+ex.getMessage());137 return null;138 }139 }140 private static Object getExceptionCause(Object e) {141 Method getCause = null;142 try {143 getCause = e.getClass().getMethod("getCause");144 getCause.setAccessible(true);145 Object exp = getCause.invoke(e);146 if (exp != null) return exp;147 getCause = e.getClass().getMethod("getUndeclaredThrowable");148 getCause.setAccessible(true);149 return getCause.invoke(e);150 } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {151 SimpleLogger.error("Error: fail to get message of the exception with "+ex.getMessage());152 return null;153 }154 }155 private static boolean isRootThriftException(Object e) throws ClassNotFoundException {156 return Class.forName(THRIFT_EXCEPTION_ROOT).isInstance(e);157 }158 private static boolean isInstanceOf(Object e, String name) throws ClassNotFoundException {159 return Class.forName(name).isInstance(e);160 }161 /**162 * Note that now we only support categorize exception for thrift163 * @param e is the exception instance164 * @return a category165 * @throws ClassNotFoundException could not find the TException of the thrift166 */167 private static RPCExceptionCategory extract(Object e) throws ClassNotFoundException {168 if (isInstanceOf(e, "org.apache.thrift.TApplicationException"))169 return RPCExceptionCategory.APPLICATION;170 if (isInstanceOf(e, "org.apache.thrift.protocol.TProtocolException"))171 return RPCExceptionCategory.PROTOCOL;172 if (isInstanceOf(e, "org.apache.thrift.transport.TTransportException"))173 return RPCExceptionCategory.TRANSPORT;174 return RPCExceptionCategory.OTHERS;175 }176 private static RPCExceptionType getExceptionType(RPCExceptionCategory category, int intValue){177 for (RPCExceptionType type: RPCExceptionType.values()){178 if (type.intValue == intValue && type.category == category) return type;179 }180 return null;181 }...
extract
Using AI Code Generation
1import org.evomaster.client.java.controller.problem.rpc.RPCException;2import org.evomaster.client.java.controller.problem.rpc.RPCExceptionType;3import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;4public class 3 {5 public static void main(String[] args) {6 try {7 RPCException rpcException = new RPCException("message", RPCExceptionType.INVALID_REQUEST);8 RPCExceptionHandler.extract(rpcException);9 } catch (Exception e) {10 System.out.println("Exception caught: " + e);11 }12 }13}14import org.evomaster.client.java.controller.problem.rpc.RPCException;15import org.evomaster.client.java.controller.problem.rpc.RPCExceptionType;16import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;17public class 4 {18 public static void main(String[] args) {19 try {20 RPCException rpcException = new RPCException("message", RPCExceptionType.INVALID_REQUEST);21 RPCExceptionHandler.extract(rpcException);22 } catch (Exception e) {23 System.out.println("Exception caught: " + e);24 }25 }26}27import org.evomaster.client.java.controller.problem.rpc.RPCException;28import org.evomaster.client.java.controller.problem.rpc.RPCExceptionType;29import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;30public class 5 {31 public static void main(String[] args) {32 try {33 RPCException rpcException = new RPCException("message", RPCExceptionType.INVALID_REQUEST);34 RPCExceptionHandler.extract(rpcException);35 } catch (Exception e) {36 System.out.println("Exception caught: " + e);37 }38 }39}40import org.evomaster.client.java.controller.problem.rpc.RPCException;41import org.evomaster.client.java.controller.problem.rpc.RPCExceptionType;42import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;43public class 6 {44 public static void main(String[] args) {45 try {46 RPCException rpcException = new RPCException("message", RPCExceptionType.INVALID_REQUEST
extract
Using AI Code Generation
1import org.evomaster.client.java.controller.problem.rpc.RPCException;2import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;3public class 3 {4 public static void main(String[] args) {5 try {6 throw new RPCException("RPCException");7 } catch (RPCException e) {8 RPCExceptionHandler.extract(e);9 }10 }11}12import org.evomaster.client.java.controller.problem.rpc.RPCException;13import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;14public class 4 {15 public static void main(String[] args) {16 try {17 throw new RPCException("RPCException");18 } catch (RPCException e) {19 RPCExceptionHandler.extract(e);20 }21 }22}23import org.evomaster.client.java.controller.problem.rpc.RPCException;24import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;25public class 5 {26 public static void main(String[] args) {27 try {28 throw new RPCException("RPCException");29 } catch (RPCException e) {30 RPCExceptionHandler.extract(e);31 }32 }33}34import org.evomaster.client.java.controller.problem.rpc.RPCException;35import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;36public class 6 {37 public static void main(String[] args) {38 try {39 throw new RPCException("RPCException");40 } catch (RPCException e) {41 RPCExceptionHandler.extract(e);42 }43 }44}45import org.evomaster.client.java.controller.problem.rpc.RPCException;46import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;47public class 7 {48 public static void main(String[] args) {49 try {50 throw new RPCException("RPCException");51 } catch (RPCException e) {52 RPCExceptionHandler.extract(e);53 }54 }55}
extract
Using AI Code Generation
1import org.evomaster.client.java.controller.api.dto.SutInfoDto;2import org.evomaster.client.java.controller.problem.rpc.RPCException;3import org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler;4import org.evomaster.client.java.controller.problem.rpc.RPCResult;5import org.evomaster.client.java.controller.problem.rpc.RPCStatement;6import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseExecutionDto;7import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;8import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseRowDto;9import org.evomaster.client.java.controller.api.dto.database.operations.DeleteTableDto;10import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;11import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseStructureDto;12import org.evomaster.client.java.controller.api.dto.database.operations.SchemaDto;13import org.evomaster.client.java.controller.api.dto.database.operations.TableDto;14import org.evomaster.client.java.controller.api.dto.database.operations.ColumnDto;15import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseType;16import org.evomaster.client.java.controller.api.dto.database.operations.DeleteRowDto;17import org.evomaster.client.java.controller.api.dto.database.operations.SqlCallDto;18import org.evomaster.client.java.controller.api.dto.database.operations.SqlQueryDto;19import org.evomaster.client.java.controller.api.dto.database.operations.UpdateTableDto;20import org.evomaster.client.java.controller.api.dto.database.operations.UpdateRowDto;21import org.evomaster.client.java.controller.api.dto.database.operations.constraint.*;22import org.evomaster.client.java.controller.api.dto.database.operations.TableIndexDto;23import org.evomaster.client.java.controller.api.dto.database.operations.TableForeignKeyDto;24import org.evomaster.client.java.controller.api.dto.database.operations.TableUniqueDto;25import org.evomaster.client.java.controller.api.dto.database.operations.TableCheckDto;26import org.evomaster.client.java.controller.api.dto.database.operations.TableTriggerDto;27import org.evomaster.client.java.controller.api.dto.database.operations.TableColumnDto;28import org.evomaster.client.java.controller.api.dto.database.operations.TableColumnIndexDto;29import org.evomaster.client.java.controller.api.dto.database.operations.TableColumnForeignKeyDto;30import org.evomaster.client.java.controller.api.dto.database.operations.TableColumnUniqueDto;31import org.evomaster.client.java.controller.api.dto.database.operations.TableColumnCheckDto;32import org.evomaster.client
extract
Using AI Code Generation
1package org.evomaster.client.java.controller.problem.rpc;2import java.util.List;3public class RPCException extends RuntimeException {4 private final String rpcName;5 private final List<String> parameters;6 public RPCException(String rpcName, List<String> parameters, Throwable cause) {7 super(cause);8 this.rpcName = rpcName;9 this.parameters = parameters;10 }11 public String getRpcName() {12 return rpcName;13 }14 public List<String> getParameters() {15 return parameters;16 }17}18package org.evomaster.client.java.controller.problem.rpc;19import java.util.List;20public class RPCExceptionHandler {21 public static String handle(RPCException exception) {22 StringBuilder sb = new StringBuilder();23 sb.append("Failed to execute RPC call: ");24 sb.append(exception.getRpcName());25 sb.append(" with parameters: ");26 sb.append(exception.getParameters());27 sb.append(" due to: ");28 sb.append(exception.getCause().getMessage());29 return sb.toString();30 }31}32package org.evomaster.client.java.controller.problem.rpc;33import java.util.List;34public class RPCException extends RuntimeException {35 private final String rpcName;36 private final List<String> parameters;37 public RPCException(String rpcName, List<String> parameters, Throwable cause) {38 super(cause);39 this.rpcName = rpcName;40 this.parameters = parameters;41 }42 public String getRpcName() {43 return rpcName;44 }45 public List<String> getParameters() {46 return parameters;47 }48}49package org.evomaster.client.java.controller.problem.rpc;50import java.util.List;51public class RPCExceptionHandler {52 public static String handle(RPCException exception) {53 StringBuilder sb = new StringBuilder();54 sb.append("Failed to execute RPC call: ");55 sb.append(exception.getRpcName());56 sb.append(" with parameters: ");57 sb.append(exception.getParameters());58 sb.append(" due to: ");59 sb.append(exception.getCause().getMessage());60 return sb.toString();61 }62}
extract
Using AI Code Generation
1class 3 {2 public static void main(String[] args) {3 try{4 org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.extract(new org.evomaster.client.java.controller.problem.rpc.RPCException("RPCException", 0, "RPCException"));5 }catch (org.evomaster.client.java.controller.problem.rpc.RPCException e){6 e.printStackTrace();7 }8 }9}10class 4 {11 public static void main(String[] args) {12 try{13 org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.extract(new org.evomaster.client.java.controller.problem.rpc.RPCException("RPCException", 0, "RPCException"));14 }catch (org.evomaster.client.java.controller.problem.rpc.RPCException e){15 e.printStackTrace();16 }17 }18}19class 5 {20 public static void main(String[] args) {21 try{22 org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.extract(new org.evomaster.client.java.controller.problem.rpc.RPCException("RPCException", 0, "RPCException"));23 }catch (org.evomaster.client.java.controller.problem.rpc.RPCException e){24 e.printStackTrace();25 }26 }27}28class 6 {29 public static void main(String[] args) {30 try{31 org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.extract(new org.evomaster.client.java.controller.problem.rpc.RPCException("RPCException", 0, "RPCException"));32 }catch (org.evomaster.client.java.controller.problem.rpc.RPCException e){33 e.printStackTrace();34 }35 }36}37class 7 {38 public static void main(String[] args) {39 try{40 org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler.extract(new org.evomaster.client.java.controller.problem.rpc.RPCException("RPCException", 0, "RPCException"));41 }catch
extract
Using AI Code Generation
1public class 3 {2 public static void main(String[] args) {3 String response = "HTTP/1.1 500 Internal Server Error\\r\\nContent-Type: application/json\\r\\nContent-Length: 45\\r\\nDate: Tue, 07 Apr 2020 11:37:34 GMT\\r\\n\\r\\n{\"status\":500,\"error\":\"Internal Server Error\"}";4 Exception e = RPCExceptionHandler.extractException(response);5 System.out.println(e.getMessage());6 }7}8public class 4 {9 public static void main(String[] args) {10 String response = "HTTP/1.1 500 Internal Server Error\\r\\nContent-Type: application/json\\r\\nContent-Length: 45\\r\\nDate: Tue, 07 Apr 2020 11:37:34 GMT\\r\\n\\r\\n{\"status\":500,\"error\":\"Internal Server Error\"}";11 RestCallResult result = RestCallResult.extractResult(response);12 System.out.println(result.getException().getMessage());13 }14}15public class 5 {16 public static void main(String[] args) {17 String response = "HTTP/1.1 500 Internal Server Error\\r\\nContent-Type: application/json\\r\\nContent-Length: 45\\r\\nDate: Tue, 07 Apr 2020 11:37:34 GMT\\r\\n\\r\\n{\"status\":500,\"error\":\"Internal Server Error\"}";18 RestCallResult result = RestCallResult.extractResult(response);19 System.out.println(result.getBody());20 }21}22public class 6 {23 public static void main(String
extract
Using AI Code Generation
1public class 3 {2 public static void main(String[] args) {3 String path = "C:\\Users\\user\\Desktop\\output.txt";4 String className = "org.evomaster.client.java.controller.problem.rpc.RPCExceptionHandler";5 String methodName = "extract";6 String argClass = "org.evomaster.client.java.controller.problem.rpc.RPCException";7 String argName = "e";8 String resultClass = "java.lang.String";9 String resultName = "message";10 String exceptionClass = "org.evomaster.client.java.controller.problem.rpc.RPCException";11 String exceptionName = "e";12 String exceptionMessageClass = "java.lang.String";13 String exceptionMessageName = "message";14 String exceptionStackTraceClass = "java.lang.StackTraceElement[]";15 String exceptionStackTraceName = "stackTrace";16 String exceptionStackTraceElementClass = "java.lang.StackTraceElement";17 String exceptionStackTraceElementClassName = "className";18 String exceptionStackTraceElementFileName = "fileName";19 String exceptionStackTraceElementMethodName = "methodName";
extract
Using AI Code Generation
1String exception = RPCExceptionHandler.extractException(response);2if(exception != null) {3 throw new Exception(exception);4}5T returnValue = (T) RPCExceptionHandler.extractReturnValue(response);6return returnValue;7String exception = RPCExceptionHandler.extractException(response);8if(exception != null) {9 throw new Exception(exception);10}11T returnValue = (T) RPCExceptionHandler.extractReturnValue(response);12return returnValue;13String exception = RPCExceptionHandler.extractException(response);14if(exception != null) {15 throw new Exception(exception);16}17T returnValue = (T) RPCExceptionHandler.extractReturnValue(response);18return returnValue;19String exception = RPCExceptionHandler.extractException(response);20if(exception != null) {21 throw new Exception(exception);22}23T returnValue = (T) RPCExceptionHandler.extractReturnValue(response);24return returnValue;25String exception = RPCExceptionHandler.extractException(response);26if(exception != null) {27 throw new Exception(exception);28}29T returnValue = (T) RPCExceptionHandler.extractReturnValue(response);30return returnValue;31String exception = RPCExceptionHandler.extractException(response);32if(exception != null)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!