Best Testsigma code snippet using com.testsigma.automator.constants.AutomatorMessages.protocol
Source:WebserviceUtil.java
1package com.testsigma.automator.webservices;2import com.fasterxml.jackson.core.type.TypeReference;3import com.fasterxml.jackson.databind.ObjectMapper;4import com.jayway.jsonpath.PathNotFoundException;5import com.testsigma.automator.constants.AuthorizationTypes;6import com.testsigma.automator.constants.AutomatorMessages;7import com.testsigma.automator.entity.*;8import com.testsigma.automator.exceptions.AutomatorException;9import com.testsigma.automator.exceptions.TestsigmaFileNotFoundException;10import com.testsigma.automator.exceptions.TestsigmaTestdataNotFoundException;11import com.testsigma.automator.http.HttpResponse;12import com.testsigma.automator.runners.EnvironmentRunner;13import com.testsigma.automator.service.ObjectMapperService;14import com.testsigma.automator.utilities.PathUtil;15import lombok.extern.log4j.Log4j2;16import org.apache.commons.codec.binary.Base64;17import org.apache.commons.io.FilenameUtils;18import org.apache.commons.lang3.StringUtils;19import org.apache.http.HttpEntity;20import org.apache.http.HttpHeaders;21import org.apache.http.ProtocolException;22import org.apache.http.client.CircularRedirectException;23import org.apache.http.client.ClientProtocolException;24import org.apache.http.client.HttpClient;25import org.apache.http.client.config.RequestConfig;26import org.apache.http.client.methods.*;27import org.apache.http.client.utils.HttpClientUtils;28import org.apache.http.entity.ContentType;29import org.apache.http.entity.StringEntity;30import org.apache.http.entity.mime.MultipartEntityBuilder;31import org.apache.http.entity.mime.content.StringBody;32import org.apache.http.impl.client.HttpClients;33import org.springframework.http.HttpStatus;34import org.springframework.web.bind.annotation.RequestMethod;35import java.io.File;36import java.io.IOException;37import java.net.URL;38import java.net.UnknownHostException;39import java.nio.charset.StandardCharsets;40import java.nio.file.Paths;41import java.util.HashMap;42import java.util.Map;43@Log4j244public class WebserviceUtil {45 private static final String HTTP = "http";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()) {278 request.addHeader(key, headers.get(key));279 }280 }281 }282 private String downloadFile(String fileUrl, Map<String, String> envSettings) throws Exception {283 try {284 if (fileUrl.startsWith(HTTP) || fileUrl.startsWith(HTTPS)) {285 String fileName = FilenameUtils.getName(new java.net.URL(fileUrl).getPath());286 String filePath = getDownloadFilePath(envSettings);287 com.testsigma.automator.http.HttpClient httpClient = EnvironmentRunner.getAssetsHttpClient();288 HttpResponse<String> response = httpClient.downloadFile(fileUrl, filePath + File.separator + fileName);289 if (response != null && response.getStatusCode() == HttpStatus.OK.value()) {290 return filePath + File.separator + fileName;291 } else {292 throw new TestsigmaFileNotFoundException(AutomatorMessages.getMessage(AutomatorMessages.EXCEPTION_DOWNLOAD_LOCAL_FILE, fileUrl));293 }294 } else {295 return fileUrl;296 }297 } catch (Exception e) {298 log.error(e.getMessage(), e);299 throw e;300 }301 }302 private String getDownloadFilePath(Map<String, String> envSettings) {303 String fullPath = Paths.get(PathUtil.getInstance().getUploadPath(), envSettings.get("envRunId"))304 .toFile().getAbsolutePath();305 File file = new File(fullPath);306 if (!file.exists()) {307 file.mkdirs();308 }309 return fullPath;310 }311}...
Source:AutomatorMessages.java
...29 public static final String EXCEPTION_INVALID_PARAMETER_FORMAT = "Invalid value ?1 entered for parameter ?2 while executing the Custom Test Data Function \"?3\"";30 public static final String EXCEPTION_INVALID_CLASS_NAME = "Unsupported class \"?1\" used to generate test data from custom function";31 public static final String EXCEPTION_METHOD_NOT_FOUND = "No implementation found for this template";32 public static final String EXCEPTION_INVALID_TESTDATA = "No data available for runtime test data variable ?1. Refer previous Test Steps in this Test Case or Test Steps in other Test Cases to know the variable names saved by using store(naturalText) action Test Steps. Go to https://testsigma.com/docs/test-data/types/runtime/ to know more about runtime test data.";33 public static final String MSG_INVALID_URL = "When the given API Endpoint is invalid: UnknownHostException:Message : \"The given API URL is not valid or the server is down.Please check whether the API URL is correct, starts with correct protocol (Http/Https) and also confirm the server is up and running\"";34 public static final String MSG_RESPONSE_EMPTY = "Property/Entity not found for given JSONPath expression : PathNotFoundException:Message : Property for the given JSONPath is not found in the Response.Please check the Response Body and provide correct JSONPath expression.";35 public static final String MSG_INVALID_PATH = "Property/Entity not found for given JSONPath expression : PathNotFoundException:Message : Property for the given JSONPath is not found in the Response.Please check the Response Body and provide correct JSONPath expression.";36 public static final String MSG_INVALID_RESPONSE = "The response from the given endpoint URL is not in JSON format. Unable to compare the response with the expected JSON data. You may check the complete Response Body in response section";37 public static final String MSG_REST_ERROR_STATUS = "Response status is not equal to the expected response";38 public static final String MSG_REST_ERROR_HEADERS = "Response headers doesn't match with the expected headers";39 public static final String MSG_REST_ERROR_CONTENT = "Response content doesn't match with the expected content";40 public static final String MSG_REST_ERROR_PATH = "Content for path ?1 doesn't match with the expected value";41 public static final String MSG_REST_ERROR_BODY_EMPTY = "No Test body provided to validate response";42 public static final String MSG_REST_SCHEMA_ERROR_EMPTY = "No schema provided to validate response";43 // Used in ActionConstants check for dependencies.44 public static final String KEYWORD_GO_TO = "Navigate to";45 public static final String KEYWORD_SCREENSHOT = "Take screenshot with URL";46 public static final String EXCEPTION_DOWNLOAD_LOCAL_FILE = "There is no file with URL ?1";47 final public static String INVALID_NUMBER_ARGUMENT = "Invalid integer provided to generate random test data string. Refer \"https://testsigma.com/docs/test-data/types/random/\" to know the valid integer range and learn more about random test data";...
protocol
Using AI Code Generation
1public class 2 {2 public static void main(String[] args) {3 System.out.println(AutomatorMessages.protocol());4 }5}6public class 3 {7 public static void main(String[] args) {8 System.out.println(AutomatorMessages.protocol());9 }10}
protocol
Using AI Code Generation
1import com.testsigma.automator.constants.AutomatorMessages;2import com.testsigma.automator.constants.AutomatorMessages;3class Test{4public static void main(String args[]){5System.out.println(AutomatorMessages.protocol("test"));6}7}8import com.testsigma.automator.constants.AutomatorMessages;9import com.testsigma.automator.constants.AutomatorMessages;10class Test{11public static void main(String args[]){12System.out.println(AutomatorMessages.protocol("test"));13}14}15import com.testsigma.automator.constants.AutomatorMessages;16import com.testsigma.automator.constants.AutomatorMessages;17class Test{18public static void main(String args[]){19System.out.println(AutomatorMessages.protocol("test"));20}21}22import com.testsigma.automator.constants.AutomatorMessages;23import com.testsigma.automator.constants.AutomatorMessages;24class Test{25public static void main(String args[]){26System.out.println(AutomatorMessages.protocol("test"));27}28}29import com.testsigma.automator.constants.AutomatorMessages;30import com.testsigma.automator.constants.AutomatorMessages;31class Test{32public static void main(String args[]){33System.out.println(AutomatorMessages.protocol("test"));34}35}36import com.testsigma.automator.constants.AutomatorMessages;37import com.testsigma.automator.constants.AutomatorMessages;38class Test{39public static void main(String args[]){40System.out.println(AutomatorMessages.protocol("test"));41}42}
protocol
Using AI Code Generation
1String msg = AutomatorMessages.protocol("protocol.msg");2System.out.println(msg);3String msg = AutomatorMessages.protocol("protocol.msg");4System.out.println(msg);5String msg = AutomatorMessages.protocol("protocol.msg");6System.out.println(msg);7String msg = AutomatorMessages.protocol("protocol.msg");8System.out.println(msg);9String msg = AutomatorMessages.protocol("protocol.msg");10System.out.println(msg);11String msg = AutomatorMessages.protocol("protocol.msg");12System.out.println(msg);13String msg = AutomatorMessages.protocol("protocol.msg");14System.out.println(msg);15String msg = AutomatorMessages.protocol("protocol.msg");16System.out.println(msg);17String msg = AutomatorMessages.protocol("protocol.msg");18System.out.println(msg);
protocol
Using AI Code Generation
1String fileName = "C:\\Users\\TestSigma\\Desktop\\test.txt";2String fileContent = AutomatorMessages.protocol("readFile", fileName);3System.out.println(fileContent);4String fileName = "C:\\Users\\TestSigma\\Desktop\\test.txt";5String fileContent = AutomatorMessages.protocol("readFile", fileName);6System.out.println(fileContent);7String fileName = "C:\\Users\\TestSigma\\Desktop\\test.txt";8String fileContent = AutomatorMessages.protocol("readFile", fileName);9System.out.println(fileContent);10String fileName = "C:\\Users\\TestSigma\\Desktop\\test.txt";11String fileContent = AutomatorMessages.protocol("readFile", fileName);12System.out.println(fileContent);13String fileName = "C:\\Users\\TestSigma\\Desktop\\test.txt";14String fileContent = AutomatorMessages.protocol("readFile", fileName);15System.out.println(fileContent);16String fileName = "C:\\Users\\TestSigma\\Desktop\\test.txt";17String fileContent = AutomatorMessages.protocol("readFile", fileName);18System.out.println(fileContent);
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!!