Best EvoMaster code snippet using org.evomaster.client.java.controller.api.dto.WrappedResponseDto.withError
Source:EMController.java
...69 String connectionHeader = httpServletRequest.getHeader("Connection");70 if( connectionHeader == null71 || !connectionHeader.equalsIgnoreCase("keep-alive")){72 return Response.status(400).entity(WrappedResponseDto73 .withError("Requests should always contain a 'Connection: keep-alive'")).build();74 }75 assert trackRequestSource(httpServletRequest);76 if(! sutController.verifySqlConnection()){77 String msg = "SQL drivers are misconfigured. You must use a 'p6spy' wrapper when you " +78 "run the SUT. For example, a database connection URL like 'jdbc:h2:mem:testdb' " +79 "should be changed into 'jdbc:p6spy:h2:mem:testdb'. " +80 "See documentation on how to configure P6Spy.";81 SimpleLogger.error(msg);82 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();83 }84 SutInfoDto dto = new SutInfoDto();85 dto.isSutRunning = sutController.isSutRunning();86 dto.baseUrlOfSUT = baseUrlOfSUT;87 dto.infoForAuthentication = sutController.getInfoForAuthentication();88 dto.sqlSchemaDto = sutController.getSqlDatabaseSchema();89 dto.defaultOutputFormat = sutController.getPreferredOutputFormat();90 ProblemInfo info = sutController.getProblemInfo();91 if (info == null) {92 String msg = "Undefined problem type in the EM Controller";93 SimpleLogger.error(msg);94 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();95 } else if (info instanceof RestProblem) {96 RestProblem rp = (RestProblem) info;97 dto.restProblem = new RestProblemDto();98 dto.restProblem.swaggerJsonUrl = rp.getSwaggerJsonUrl();99 dto.restProblem.endpointsToSkip = rp.getEndpointsToSkip();100 } else {101 String msg = "Unrecognized problem type: " + info.getClass().getName();102 SimpleLogger.error(msg);103 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();104 }105 dto.unitsInfoDto = sutController.getUnitsInfoDto();106 if(dto.unitsInfoDto == null){107 String msg = "Failed to extract units info";108 SimpleLogger.error(msg);109 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();110 }111 return Response.status(200).entity(WrappedResponseDto.withData(dto)).build();112 }113 @Path(ControllerConstants.CONTROLLER_INFO)114 @GET115 public Response getControllerInfoDto(@Context HttpServletRequest httpServletRequest) {116 assert trackRequestSource(httpServletRequest);117 ControllerInfoDto dto = new ControllerInfoDto();118 dto.fullName = sutController.getClass().getName();119 dto.isInstrumentationOn = sutController.isInstrumentationActivated();120 return Response.status(200).entity(WrappedResponseDto.withData(dto)).build();121 }122 @Path(ControllerConstants.NEW_SEARCH)123 @POST124 public Response newSearch(@Context HttpServletRequest httpServletRequest) {125 assert trackRequestSource(httpServletRequest);126 sutController.newSearch();127 return Response.status(201).entity(WrappedResponseDto.withNoData()).build();128 }129 @Path(ControllerConstants.RUN_SUT_PATH)130 @PUT131 @Consumes(Formats.JSON_V1)132 public Response runSut(SutRunDto dto, @Context HttpServletRequest httpServletRequest) {133 assert trackRequestSource(httpServletRequest);134 try {135 if (dto.run == null) {136 String msg = "Invalid JSON: 'run' field is required";137 SimpleLogger.warn(msg);138 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();139 }140 boolean sqlHeuristics = dto.calculateSqlHeuristics != null && dto.calculateSqlHeuristics;141 boolean sqlExecution = dto.extractSqlExecutionInfo != null && dto.extractSqlExecutionInfo;142 sutController.enableComputeSqlHeuristicsOrExtractExecution(sqlHeuristics, sqlExecution);143 boolean doReset = dto.resetState != null && dto.resetState;144 synchronized (this) {145 if (!dto.run) {146 if (doReset) {147 String msg = "Invalid JSON: cannot reset state and stop service at same time";148 SimpleLogger.warn(msg);149 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();150 }151 //if on, we want to shut down the server152 if (sutController.isSutRunning()) {153 sutController.stopSut();154 baseUrlOfSUT = null;155 }156 } else {157 /*158 If SUT is not up and running, let's start it159 */160 if (!sutController.isSutRunning()) {161 baseUrlOfSUT = sutController.startSut();162 if (baseUrlOfSUT == null) {163 //there has been an internal failure in starting the SUT164 String msg = "Internal failure: cannot start SUT based on given configuration";165 SimpleLogger.warn(msg);166 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();167 }168 sutController.initSqlHandler();169 } else {170 //TODO as starting should be blocking, need to check171 //if initialized, and wait if not172 }173 /*174 regardless of where it was running or not, need to reset state.175 this is controlled by a boolean, although most likely we ll always176 want to do it177 */178 if (dto.resetState != null && dto.resetState) {179 sutController.resetStateOfSUT();180 sutController.newTest();181 }182 /*183 Note: here even if we start the SUT, the starting of a "New Search"184 cannot be done here, as in this endpoint we also deal with the reset185 of state. When we reset state for a new test run, we do not want to186 reset all the other data regarding the whole search187 */188 }189 }190 } catch (RuntimeException e) {191 /*192 FIXME: ideally, would not need to do a try/catch on each single endpoint,193 as could configure Jetty/Jackson to log all errors.194 But even after spending hours googling it, haven't managed to configure it195 */196 String msg = e.getMessage();197 SimpleLogger.error(msg, e);198 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();199 }200 return Response.status(204).entity(WrappedResponseDto.withNoData()).build();201 }202 @Path(ControllerConstants.TEST_RESULTS)203 @GET204 public Response getTestResults(205 @QueryParam("ids")206 @DefaultValue("")207 String idList,208 @Context HttpServletRequest httpServletRequest) {209 assert trackRequestSource(httpServletRequest);210 try {211 TestResultsDto dto = new TestResultsDto();212 Set<Integer> ids;213 try {214 ids = Arrays.stream(idList.split(","))215 .filter(s -> !s.trim().isEmpty())216 .map(Integer::parseInt)217 .collect(Collectors.toSet());218 } catch (NumberFormatException e) {219 String msg = "Invalid parameter 'ids': " + e.getMessage();220 SimpleLogger.warn(msg);221 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();222 }223 List<TargetInfo> targetInfos = sutController.getTargetInfos(ids);224 if (targetInfos == null) {225 String msg = "Failed to collect target information for " + ids.size() + " ids";226 SimpleLogger.error(msg);227 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();228 }229 targetInfos.forEach(t -> {230 TargetInfoDto info = new TargetInfoDto();231 info.id = t.mappedId;232 info.value = t.value;233 info.descriptiveId = t.descriptiveId;234 info.actionIndex = t.actionIndex;235 dto.targets.add(info);236 });237 List<AdditionalInfo> additionalInfos = sutController.getAdditionalInfoList();238 if (additionalInfos != null) {239 additionalInfos.forEach(a -> {240 AdditionalInfoDto info = new AdditionalInfoDto();241 info.queryParameters = new HashSet<>(a.getQueryParametersView());242 info.headers = new HashSet<>(a.getHeadersView());243 info.lastExecutedStatement = a.getLastExecutedStatement();244 info.stringSpecializations = new HashMap<>();245 for(Map.Entry<String, Set<StringSpecializationInfo>> entry :246 a.getStringSpecializationsView().entrySet()){247 assert ! entry.getValue().isEmpty();248 List<StringSpecializationInfoDto> list = entry.getValue().stream()249 .map(it -> new StringSpecializationInfoDto(250 it.getStringSpecialization().toString(),251 it.getValue(),252 it.getType().toString()))253 .collect(Collectors.toList());254 info.stringSpecializations.put(entry.getKey(), list);255 }256 dto.additionalInfoList.add(info);257 });258 } else {259 String msg = "Failed to collect additional info";260 SimpleLogger.error(msg);261 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();262 }263 dto.extraHeuristics = sutController.getExtraHeuristics();264 return Response.status(200).entity(WrappedResponseDto.withData(dto)).build();265 } catch (RuntimeException e) {266 /*267 FIXME: ideally, would not need to do a try/catch on each single endpoint,268 as could configure Jetty/Jackson to log all errors.269 But even after spending hours googling it, haven't managed to configure it270 */271 String msg = "Thrown exception: " + e.getMessage();272 SimpleLogger.error(msg, e);273 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();274 }275 }276 @Path(ControllerConstants.NEW_ACTION)277 @Consumes(MediaType.APPLICATION_JSON)278 @PUT279 public Response newAction(ActionDto dto, @Context HttpServletRequest httpServletRequest) {280 assert trackRequestSource(httpServletRequest);281 sutController.newAction(dto);282 return Response.status(204).entity(WrappedResponseDto.withNoData()).build();283 }284 @Path(ControllerConstants.DATABASE_COMMAND)285 @Consumes(Formats.JSON_V1)286 @POST287 public Response executeDatabaseCommand(DatabaseCommandDto dto, @Context HttpServletRequest httpServletRequest) {288 assert trackRequestSource(httpServletRequest);289 try {290 Connection connection = sutController.getConnection();291 if (connection == null) {292 String msg = "No active database connection";293 SimpleLogger.warn(msg);294 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();295 }296 if (dto.command == null && (dto.insertions == null || dto.insertions.isEmpty())) {297 String msg = "No input command";298 SimpleLogger.warn(msg);299 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();300 }301 if (dto.command != null && dto.insertions != null && !dto.insertions.isEmpty()) {302 String msg = "Only 1 command can be specified";303 SimpleLogger.warn(msg);304 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();305 }306 if (dto.insertions != null) {307 if (dto.insertions.stream().anyMatch(i -> i.targetTable == null || i.targetTable.isEmpty())) {308 String msg = "Insertion with no target table";309 SimpleLogger.warn(msg);310 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();311 }312 }313 QueryResult queryResult = null;314 Map<Long, Long> idMapping = null;315 try {316 if (dto.command != null) {317 queryResult = SqlScriptRunner.execCommand(connection, dto.command);318 } else {319 idMapping = SqlScriptRunner.execInsert(connection, dto.insertions);320 }321 } catch (Exception e) {322 String msg = "Failed to execute database command: " + e.getMessage();323 SimpleLogger.warn(msg);324 return Response.status(400).entity(WrappedResponseDto.withError(msg)).build();325 }326 if (queryResult != null) {327 return Response.status(200).entity(WrappedResponseDto.withData(queryResult.toDto())).build();328 } else if (idMapping != null) {329 return Response.status(200).entity(WrappedResponseDto.withData(idMapping)).build();330 } else {331 return Response.status(204).entity(WrappedResponseDto.withNoData()).build();332 }333 } catch (RuntimeException e) {334 /*335 FIXME: ideally, would not need to do a try/catch on each single endpoint,336 as could configure Jetty/Jackson to log all errors.337 But even after spending hours googling it, haven't managed to configure it338 */339 String msg = "Thrown exception: " + e.getMessage();340 SimpleLogger.error(msg, e);341 return Response.status(500).entity(WrappedResponseDto.withError(msg)).build();342 }343 }344}...
withError
Using AI Code Generation
1package org.evomaster.client.java.controller.api.dto;2import com.fasterxml.jackson.annotation.JsonInclude;3import com.fasterxml.jackson.annotation.JsonProperty;4import java.util.Objects;5public class WrappedResponseDto<T> {6 @JsonProperty("dto")7 private T dto;8 @JsonProperty("error")9 @JsonInclude(JsonInclude.Include.NON_NULL)10 private String error;11 public WrappedResponseDto() {12 }13 public WrappedResponseDto(T dto) {14 this.dto = dto;15 }16 public WrappedResponseDto(T dto, String error) {17 this.dto = dto;18 this.error = error;19 }20 public T getDto() {21 return dto;22 }23 public void setDto(T dto) {24 this.dto = dto;25 }26 public String getError() {27 return error;28 }29 public void setError(String error) {30 this.error = error;31 }32 public boolean hasError(){33 return error != null;34 }35 public boolean equals(Object o) {36 if (this == o) return true;37 if (o == null || getClass() != o.getClass()) return false;38 WrappedResponseDto<?> that = (WrappedResponseDto<?>) o;39 return Objects.equals(dto, that.dto) &&40 Objects.equals(error, that.error);41 }42 public int hashCode() {43 return Objects.hash(dto, error);44 }45 public String toString() {46 return "WrappedResponseDto{" +47 '}';48 }49}50package org.evomaster.client.java.controller.api.dto;51import com.fasterxml.jackson.annotation.JsonInclude;52import com.fasterxml.jackson.annotation.JsonProperty;53import java.util.Objects;54public class WrappedResponseDto<T> {55 @JsonProperty("dto")56 private T dto;57 @JsonProperty("error")58 @JsonInclude(JsonInclude.Include.NON_NULL)59 private String error;60 public WrappedResponseDto() {61 }62 public WrappedResponseDto(T dto) {63 this.dto = dto;64 }65 public WrappedResponseDto(T dto, String error) {66 this.dto = dto;67 this.error = error;68 }69 public T getDto() {
withError
Using AI Code Generation
1package org.evomaster.client.java.controller.api.dto;2import com.fasterxml.jackson.annotation.JsonCreator;3import com.fasterxml.jackson.annotation.JsonProperty;4public class WrappedResponseDto<T> {5 private final int statusCode;6 private final String body;7 private final T dto;8 private final String error;9 public WrappedResponseDto(@JsonProperty("statusCode") int statusCode,10 @JsonProperty("body") String body,11 @JsonProperty("dto") T dto,12 @JsonProperty("error") String error) {13 this.statusCode = statusCode;14 this.body = body;15 this.dto = dto;16 this.error = error;17 }18 public int getStatusCode() {19 return statusCode;20 }21 public String getBody() {22 return body;23 }24 public T getDto() {25 return dto;26 }27 public String getError() {28 return error;29 }30 public boolean isError() {31 return error != null;32 }33 public String withError() {34 if (!isError()) {35 throw new IllegalStateException("No error message");36 }37 return error;38 }39 public String toString() {40 return "WrappedResponseDto{" +41 '}';42 }43}44package org.evomaster.client.java.controller.api.dto;45import com.fasterxml.jackson.annotation.JsonCreator;46import com.fasterxml.jackson.annotation.JsonProperty;47public class WrappedResponseDto<T> {48 private final int statusCode;49 private final String body;50 private final T dto;51 private final String error;52 public WrappedResponseDto(@JsonProperty("statusCode") int statusCode,53 @JsonProperty("body") String body,54 @JsonProperty("dto") T dto,55 @JsonProperty("error") String error) {56 this.statusCode = statusCode;57 this.body = body;58 this.dto = dto;59 this.error = error;60 }61 public int getStatusCode() {62 return statusCode;
withError
Using AI Code Generation
1import org.evomaster.client.java.controller.api.dto.WrappedResponseDto;2import org.junit.jupiter.api.Test;3import org.springframework.boot.test.context.SpringBootTest;4import static io.restassured.RestAssured.get;5import static org.junit.jupiter.api.Assertions.*;6@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)7public class RestAssuredTest {8 public void testGetAllBooks() {9 WrappedResponseDto response = get("/api/book")10 .then()11 .extract()12 .as(WrappedResponseDto.class);13 assertTrue(response.withError().is2xxSuccessful());14 }15}16withError().is1xxInformational()17withError().is2xxSuccessful()18withError().is3xxRedirection()19withError().is4xxClientError()20withError().is5xxServerError()21withError().isInformational()22withError().isSuccessful()23withError().isRedirection()24withError().isClientError()25withError().isServerError()26withError().isError()27withError().is1xxInformational()28withError().is2xxSuccessful()29withError().is3xxRedirection()30withError().is4xxClientError()31withError().is5xxServerError()32withError().is1xxInformational()33withError().is2xxSuccessful()34withError().is3xxRedirection
withError
Using AI Code Generation
1import org.evomaster.client.java.controller.api.dto.WrappedResponseDto;2import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;3import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseRowDto;4import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;5import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;6import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;7import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;8import java.util.ArrayList;9import java.util.List;10public class ExampleEMTest {11 public void testEM(){12 ExampleEMController controller = new ExampleEMController();13 ExampleDto dto = new ExampleDto();14 String targetId = "1";15 String methodName = "example";16 Object[] input = new Object[]{dto};17 int expectedStatus = 200;
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!!