Best Testsigma code snippet using com.testsigma.automator.webservices.WebserviceUtil.execute
Source:WebserviceUtil.java
...46 private static final String HTTPS = "https";47 private HttpClient httpclient;48 private static int CONNECTION_TIMEOUT = 10 * 60 * 1000;49 private static int SOCKET_TIMEOUT = 10 * 60 * 1000;50 public void execute(TestCaseStepEntity testcaseStep, TestCaseStepResult result, Map<String, String> envSettings, TestCaseResult testCaseResult) throws TestsigmaTestdataNotFoundException {51 log.debug("Executing Rest step:" + testcaseStep);52 RestfulStepEntity entity = new ObjectMapper().convertValue(testcaseStep.getAdditionalData()53 .get(TestCaseStepEntity.REST_DETAILS_KEY), RestfulStepEntity.class);54 result.setResult(ResultConstant.SUCCESS);55 WebserviceResponse resObj = new WebserviceResponse();56 try {57 log.debug("Updating Rest step variables for RestStepEntity:" + entity);58 new RestAPIRunTimeDataProcessor(entity,result).processRestAPIStep();59 initializeHttpClient(entity);60 Map<String, String> headers = fetchHeadersFromRestStep(entity);61 setAuthorizationHeaders(entity, headers);62 setDefaultHeaders(entity, headers);63 entity.setUrl(entity.getUrl().replace("\\", "/"));64 HttpResponse<String> response = executeRestCall(entity.getUrl(),65 RequestMethod.valueOf(entity.getMethod().toUpperCase()), headers, getEntity(entity, envSettings, headers));66 log.debug("Rest Url - " + entity.getUrl() + " Method " + entity.getMethod().toUpperCase()67 + " Headers - " + new ObjectMapperService().convertToJson(headers) + " PayLoad - " + entity.getPayload());68 result.getMetadata().setReqEntity(entity);69 log.debug("Method - " + entity.getMethod().toUpperCase() + "response - " + new ObjectMapperService().convertToJson(response));70 ((Map<String, Object>) (testcaseStep.getAdditionalData().get(TestCaseStepEntity.REST_DETAILS_KEY))).put("url", entity.getUrl());71 resObj.setStatus(response.getStatusCode());72 if (entity.getStoreMetadata()) {73 resObj.setContent(response.getResponseText());74 resObj.setHeaders(response.getHeadersMap());75 }76 result.getMetadata().setRestResult(resObj);77 new RestApiResponseValidator(entity, result, response).validateResponse();78 new RestAPIRunTimeDataProcessor(entity,result).storeResponseData(response,envSettings);79 } catch (Exception e) {80 log.error("Error while executing Rest Step:"+testcaseStep, e);81 if (e instanceof AutomatorException) {82 result.setResult(ResultConstant.FAILURE);83 result.setMessage(e.getMessage());84 } else {85 String genericExceptionMessage = getExceptionSpecificMessage(e, result);86 result.setResult(ResultConstant.FAILURE);87 result.setMessage(genericExceptionMessage);88 }89 }90 result.getMetadata().setRestResult(resObj);91 log.debug("Test Step Result :: " + new ObjectMapperService().convertToJson(result));92 }93 private String getExceptionSpecificMessage(Exception exception, TestCaseStepResult testCaseStepResult) {94 String resultMessage;95 if(testCaseStepResult.getMessage() != null){//If specific Message is already set, we show the same in result96 return testCaseStepResult.getMessage();97 }98 if (exception instanceof PathNotFoundException) {99 resultMessage = AutomatorMessages.MSG_INVALID_PATH;100 } else if (exception instanceof ClientProtocolException) {101 if (exception.getCause() instanceof CircularRedirectException) {102 resultMessage = exception.getCause().getLocalizedMessage();103 } else {104 resultMessage = exception.getLocalizedMessage();105 }106 } else if (exception.getCause() instanceof ProtocolException) {107 resultMessage = AutomatorMessages.MSG_REST_INVALID_URL;108 } else if (exception instanceof UnknownHostException) {109 resultMessage = AutomatorMessages.MSG_INVALID_URL;110 } else {111 resultMessage = exception.getLocalizedMessage();112 }113 return resultMessage;114 }115 private Map<String, String> fetchHeadersFromRestStep(RestfulStepEntity restfulStepEntity) {116 Map<String, String> headers = new HashMap<>();117 if (StringUtils.isNotBlank(restfulStepEntity.getRequestHeaders())) {118 headers = new ObjectMapperService().parseJson(restfulStepEntity.getRequestHeaders(), new TypeReference<>() {119 });120 }121 return headers;122 }123 private void initializeHttpClient(RestfulStepEntity restfulStepEntity) {124 RequestConfig config = RequestConfig.custom()125 .setConnectTimeout(CONNECTION_TIMEOUT)126 .setSocketTimeout(SOCKET_TIMEOUT).build();127 if (restfulStepEntity.getFollowRedirects()) {128 httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();129 } else {130 httpclient = HttpClients.custom().setDefaultRequestConfig(config).disableRedirectHandling().build();131 }132 }133 private void setAuthorizationHeaders(RestfulStepEntity entity, Map<String, String> headers) {134 log.debug("Set Authorization headers for entity:" + entity);135 log.debug("Set Authorization headers ,headers:" + headers);136 if (entity.getAuthorizationType() != null) {137 headers = (headers != null) ? headers : new HashMap<>();138 Map<String, String> info = new ObjectMapperService().parseJson(entity.getAuthorizationValue(),139 new TypeReference<>() {140 });141 if (AuthorizationTypes.BASIC == entity.getAuthorizationType()) {142 headers.put(HttpHeaders.AUTHORIZATION,143 com.testsigma.automator.http.HttpClient.BASIC_AUTHORIZATION + " " +144 encodedCredentials(info.get("username") + ":" + info.get("password")));145 } else if (entity.getAuthorizationType() == AuthorizationTypes.BEARER) {146 headers.put("Authorization", "Bearer " + info.get("Bearertoken"));147 }148 }149 }150 private String encodedCredentials(String input) {151 String authHeader = "";152 try {153 byte[] encodedAuth = Base64.encodeBase64(input.getBytes(StandardCharsets.ISO_8859_1));154 if (encodedAuth != null) {155 authHeader = new String(encodedAuth);156 }157 } catch (Exception ignore) {158 }159 return authHeader;160 }161 private void setDefaultHeaders(RestfulStepEntity entity, Map<String, String> headers) {162 log.debug("Setting default headers for entity:" + entity);163 log.debug("Set default headers, headers:" + headers);164 try {165 headers = (headers != null) ? headers : new HashMap<String, String>();166 if (headers.get("Host") == null) {167 URL url = new URL(entity.getUrl());168 headers.put("Host", url.getHost());169 }170 if (headers.get("Content-Type") == null) {171 headers.put("Content-Type", "application/json");172 }173 } catch (Exception e) {174 log.error("error while setting default headers");175 }176 }177 private HttpEntity getEntity(RestfulStepEntity entity, Map<String, String> envSettings, Map<String, String> headers) throws Exception {178 MultipartEntityBuilder builder = MultipartEntityBuilder.create();179 if (entity.getIsMultipart() != null && entity.getIsMultipart()) {180 removeContentTypeHeader(headers);181 Map<String, Object> payload = new ObjectMapperService().parseJson(entity.getPayload(), new TypeReference<>() {182 });183 for (Map.Entry<String, Object> data : payload.entrySet()) {184 removeContentTypeHeader(headers);185 boolean isFileUrl = data.getValue() != null && (data.getValue().toString().startsWith("http")186 || data.getValue().toString().startsWith("https"));187 if (isFileUrl) {188 String filePath = downloadFile(data.getValue().toString(), envSettings);189 String[] fileNames = filePath.split(File.separator);190 builder.addBinaryBody(data.getKey(), new File(filePath), ContentType.DEFAULT_BINARY, fileNames[fileNames.length - 1]);191 } else {192 builder.addPart(data.getKey(), new StringBody(new ObjectMapperService().convertToJson(data.getValue()), ContentType.APPLICATION_JSON));193 }194 }195 return builder.build();196 } else if (entity.getPayload() != null) {197 return new StringEntity(entity.getPayload());198 }199 return null;200 }201 public void removeContentTypeHeader(Map<String, String> headers) {202 String contenttype = null;203 for (Map.Entry<String, String> entry : headers.entrySet()) {204 if (entry.getKey().equalsIgnoreCase("content-type")) {205 contenttype = entry.getKey();206 break;207 }208 }209 if (contenttype != null) {210 headers.remove(contenttype);211 }212 }213 public HttpResponse<String> executeRestCall(String url, RequestMethod method, Map<String, String> headers,214 HttpEntity input) throws IOException {215 HttpResponse<String> returnResponse;216 log.debug(String.format("Executing Rest API call with below props\n method::%s\n, headers::%s\n HttpEntity::%s", method,217 headers, input));218 try {219 HttpUriRequest request = null;220 switch (method) {221 case GET:222 request = new HttpGet(url);223 setHeaders(request, headers);224 break;225 case POST:226 request = new HttpPost(url);227 if (input != null)228 ((HttpPost) request).setEntity(input);229 setHeaders(request, headers);230 break;231 case PUT:232 request = new HttpPut(url);233 if (input != null)234 ((HttpPut) request).setEntity(input);235 setHeaders(request, headers);236 break;237 case PATCH:238 request = new HttpPatch(url);239 if (input != null)240 ((HttpPatch) request).setEntity(input);241 setHeaders(request, headers);242 break;243 case DELETE:244 request = new HttpDelete(url);245 setHeaders(request, headers);246 break;247 case OPTIONS:248 request = new HttpOptions(url);249 setHeaders(request, headers);250 break;251 case TRACE:252 request = new HttpTrace(url);253 setHeaders(request, headers);254 break;255 case HEAD:256 request = new HttpHead(url);257 setHeaders(request, headers);258 break;259 default:260 break;261 }262 log.debug("***Executing REST API Call***");263 org.apache.http.HttpResponse response = httpclient.execute(request);264 log.debug("URL : " + url);265 log.debug("Response Status Code : " + response.getStatusLine().getStatusCode());266 returnResponse = new HttpResponse<>(response, new TypeReference<>() {267 });268 return returnResponse;269 } catch (Exception e) {270 throw e;271 } finally {272 HttpClientUtils.closeQuietly(httpclient);273 }274 }275 private void setHeaders(HttpUriRequest request, Map<String, String> headers) {276 if (headers != null) {277 for (String key : headers.keySet()) {...
Source:RestTestcaseStepRunner.java
...9 public RestTestcaseStepRunner(WorkspaceType workspaceType, Platform os) {10 super(workspaceType, os);11 }12 @Override13 protected void execute(Map<String, String> envSetting, TestCaseStepResult result, TestCaseStepEntity testcaseStep,14 TestCaseResult testCaseResult) throws AutomatorException {15 log.info("Executing REST step, step:" + testcaseStep);16 if (breakOrContinueLoopStep(testcaseStep, result)) {17 log.info("Its a break or continue step, not executing REST API call");18 return;19 }20 new WebserviceUtil().execute(testcaseStep, result, envSetting, testCaseResult);21 }22 private boolean breakOrContinueLoopStep(TestCaseStepEntity testcaseStep, TestCaseStepResult result) {23 log.info("Validating for Break or Continue step");24 TestStepType stepType = testcaseStep.getType();25 if (stepType != null && (stepType == TestStepType.BREAK_LOOP || stepType == TestStepType.CONTINUE_LOOP)) {26 result.setResult(ResultConstant.SUCCESS);27 return true;28 }29 return false;30 }31 @Override32 protected void onStepFailure(ExecutionLabType exeType, WorkspaceType workspaceType, TestPlanRunSettingEntity settings)33 throws AutomatorException {34 }...
execute
Using AI Code Generation
1import com.testsigma.automator.webservices.WebserviceUtil;2import com.testsigma.automator.webservices.WebserviceUtil.Response;3import com.testsigma.automator.webservices.WebserviceUtil.Request;4import com.testsigma.automator.webservices.WebserviceUtil.RequestMethod;5import com.testsigma.automator.webservices.WebserviceUtil.AuthenticationType;6import java.util.Map;7import java.util.HashMap;8import java.util.List;9import java.util.ArrayList;10import java.util.Iterator;11import java.util.Set;12import java.util.HashSet;13public class 2 {14 public static void main(String[] args) {15 WebserviceUtil webserviceUtil = new WebserviceUtil();16 Request request = new Request();17 request.setMethod(RequestMethod.GET);18 request.setAuthenticationType(AuthenticationType.NONE);19 request.setHeaders(new HashMap<String, String>());20 request.setParams(new HashMap<String, String>());21 Response response = webserviceUtil.execute(request);22 System.out.println("Response Code: "+response.getCode());23 System.out.println("Response Status: "+response.getStatus());24 System.out.println("Response Headers: "+response.getHeaders());25 System.out.println("Response Body: "+response.getBody());26 }27}28import com.testsigma.automator.webservices.WebserviceUtil;29import com.testsigma.automator.webservices.WebserviceUtil.Response;30import com.testsigma.automator.webservices.WebserviceUtil.Request;31import com.testsigma.automator.webservices.WebserviceUtil.RequestMethod;32import com.testsigma.automator.webservices.WebserviceUtil.AuthenticationType;33import java.util.Map;34import java.util.HashMap;35import java.util.List;36import java.util.ArrayList;37import java.util.Iterator;38import java.util.Set;39import java.util.HashSet;40public class 3 {41 public static void main(String[] args) {42 WebserviceUtil webserviceUtil = new WebserviceUtil();43 Request request = new Request();44 request.setMethod(RequestMethod.GET);45 request.setAuthenticationType(AuthenticationType.NONE);46 request.setHeaders(new HashMap<String, String>());47 request.setParams(new HashMap<String, String>());
execute
Using AI Code Generation
1import com.testsigma.automator.webservices.WebserviceUtil;2import com.testsigma.automator.webservices.WebServiceResponse;3import com.testsigma.automator.webservices.WebServiceRequest;4import com.testsigma.automator.webservices.WebServiceRequestBuilder;5import com.testsigma.automator.webservices.WebServiceRequestBuilder.Method;6import com.testsigma.automator.webservices.WebServiceRequestBuilder.Protocol;7public class 2 {8public static void main(String[] args) {9WebServiceRequest request = new WebServiceRequestBuilder()10.setProtocol(Protocol.HTTP)11.setMethod(Method.GET)12.build();13WebServiceResponse response = WebserviceUtil.execute(request);14System.out.println(response.getResponse());15}16}
execute
Using AI Code Generation
1import com.testsigma.automator.webservices.WebserviceUtil;2public class 2 {3 public static void main(String[] args) throws Exception {4 + "</soap:Envelope>";5 String result = WebserviceUtil.execute(url, xml, soapAction);6 System.out.println(result);7 }8}
execute
Using AI Code Generation
1import com.testsigma.automator.webservices.*;2import java.util.HashMap;3import java.util.Map;4public class 2{5public static void main(String[] args) {6</soapenv:Envelope>";7Map<String, String> headers = new HashMap<String, String>();8headers.put("Content-Type", "text/xml; charset=utf-8");9String result = WebserviceUtil.execute(url, body, headers);10System.out.println(result);11}12}13The following example shows how to use the 3rd method of WebserviceUtil.execute() method:14import com.testsigma.automator.webservices.*;15import java.util.HashMap;16import java.util.Map
execute
Using AI Code Generation
1package com.testsigma.automator.webservices;2import java.io.IOException;3import java.util.HashMap;4import java.util.Map;5import org.apache.http.client.ClientProtocolException;6import org.apache.http.entity.StringEntity;7import org.json.JSONArray;8import org.json.JSONObject;9import com.testsigma.automator.webservices.WebserviceUtil;10public class WebserviceUtilExample {11public static void main(String[] args) throws ClientProtocolException, IOException {12Map<String, String> headers = new HashMap<String, String>();13headers.put("Content-Type", "application/json");14headers.put("Accept", "application/json");15Map<String, String> queryParameters = new HashMap<String, String>();16queryParameters.put("param1", "value1");17queryParameters.put("param2", "value2");18StringEntity entity = new StringEntity("sample body");19System.out.println(response);20}21}22package com.testsigma.automator.webservices;23import java.io.IOException;24import java.util.HashMap;25import java.util.Map;26import org.apache.http.client.ClientProtocolException;27import org.apache.http.entity.StringEntity;28import org.json.JSONArray;29import org.json.JSONObject;30import com.testsigma.automator.webservices.WebserviceUtil;31public class WebserviceUtilExample {32public static void main(String[] args) throws ClientProtocolException, IOException {33Map<String, String> headers = new HashMap<String, String>();34headers.put("Content-Type", "application/json");35headers.put("Accept", "application/json");
execute
Using AI Code Generation
1import com.testsigma.automator.webservices.WebserviceUtil;2import com.testsigma.automator.webservices.WsResponse;3import com.testsigma.automator.webservices.WsRequest;4import com.testsigma.automator.webservices.WsRequestBuilder;5import com.testsigma.automator.webservices.WsResponse;6import com.testsigma.automator.webservices.WsResponseBuilder;7import com.testsigma.automator.webservices.WsResponse;8import com.testsigma.automator.webservices.WsResponse;9import com.testsigma.automator.webservic
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!!