Best Testsigma code snippet using com.testsigma.automator.service.ObjectMapperService
Source:WebserviceUtil.java  
...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;...Source:FunctionExecutor.java  
1package com.testsigma.automator.runners;2import com.testsigma.automator.constants.ErrorCodes;3import com.testsigma.automator.constants.AutomatorMessages;4import com.testsigma.automator.exceptions.TestsigmaInvalidParameterDataException;5import com.testsigma.automator.service.ObjectMapperService;6import java.util.ArrayList;7import java.util.List;8import java.util.Map;9public class FunctionExecutor {10  protected final ObjectMapperService objectMapperService;11  public FunctionExecutor() {12    this.objectMapperService = new ObjectMapperService();13  }14  private static Class<?> getClassFromName(final String className) {15    switch (className) {16      case "boolean":17        return boolean.class;18      case "byte":19        return byte.class;20      case "short":21        return short.class;22      case "int":23        return int.class;24      case "long":25        return long.class;26      case "float":...ObjectMapperService
Using AI Code Generation
1ObjectMapperService objectMapperService = new ObjectMapperService();2objectMapperService.setObjectMapper(objectMapper);3objectMapperService.setObjectMapper(objectMapper);4ObjectMapperService objectMapperService = new ObjectMapperService();5objectMapperService.setObjectMapper(objectMapper);6objectMapperService.setObjectMapper(objectMapper);7ObjectMapperService objectMapperService = new ObjectMapperService();8objectMapperService.setObjectMapper(objectMapper);9objectMapperService.setObjectMapper(objectMapper);10ObjectMapperService objectMapperService = new ObjectMapperService();11objectMapperService.setObjectMapper(objectMapper);12objectMapperService.setObjectMapper(objectMapper);13ObjectMapperService objectMapperService = new ObjectMapperService();14objectMapperService.setObjectMapper(objectMapper);15objectMapperService.setObjectMapper(objectMapper);16ObjectMapperService objectMapperService = new ObjectMapperService();17objectMapperService.setObjectMapper(objectMapper);18objectMapperService.setObjectMapper(objectMapper);ObjectMapperService
Using AI Code Generation
1import com.testsigma.automator.service.ObjectMapperService;2import com.testsigma.automator.service.ObjectMapperServiceException;3public class ObjectMapperServiceExample {4	public static void main(String[] args) {5		String jsonString = "{\"name\":\"John\", \"age\":30, \"car\":null}";6		try {7			User user = ObjectMapperService.getObjectFromJson(jsonString, User.class);8			System.out.println("User Name: " + user.getName());9			System.out.println("User Age: " + user.getAge());10			System.out.println("User Car: " + user.getCar());11		} catch (ObjectMapperServiceException e) {12			e.printStackTrace();13		}14	}15}16import com.testsigma.automator.service.ObjectMapperService;17import com.testsigma.automator.service.ObjectMapperServiceException;18public class ObjectMapperServiceExample {19	public static void main(String[] args) {20		User user = new User();21		user.setName("John");22		user.setAge(30);23		user.setCar(null);24		try {25			String jsonString = ObjectMapperService.getJsonFromObject(user);26			System.out.println("JSON String: " + jsonString);27		} catch (ObjectMapperServiceException e) {28			e.printStackTrace();29		}30	}31}32import com.testsigma.automator.service.ObjectMapperService;33import com.testsigma.automator.service.ObjectMapperServiceException;34public class ObjectMapperServiceExample {35	public static void main(String[] args) {36		try {37			User user = ObjectMapperService.getObjectFromJsonFile("user.json", User.class);38			System.out.println("User Name: " + user.getName());39			System.out.println("User Age: " + user.getAge());40			System.out.println("User Car: " + user.getCar());41		} catch (ObjectMapperServiceException e) {42			e.printStackTrace();43		}44	}45}46import com.testsigma.automator.service.ObjectMapperService;47import com.testsigma.automatorObjectMapperService
Using AI Code Generation
1import com.testsigma.automator.service.ObjectMapperService;2import java.io.File;3import java.io.IOException;4import java.util.ArrayList;5import java.util.List;6public class ObjectMapperServiceTest {7    public static void main(String[] args) throws IOException {8        ObjectMapperService objectMapperService = new ObjectMapperService();9        Person person = new Person();10        person.setAge(20);11        person.setName("Test Sigma");12        String jsonString = objectMapperService.convertObjectToJSONString(person);13        System.out.println("jsonString = " + jsonString);14        Person person1 = objectMapperService.convertJSONStringToObject(jsonString, Person.class);15        System.out.println("person1 = " + person1);16        objectMapperService.convertObjectToJSONFile(person, "person.json");17        Person person2 = objectMapperService.convertJSONFileToObject(new File("person.json"), Person.class);18        System.out.println("person2 = " + person2);19        objectMapperService.convertObjectToJSONFile(person, new File("person1.json"));20        Person person3 = objectMapperService.convertJSONFileToObject("person1.json", Person.class);21        System.out.println("person3 = " + person3);22        objectMapperService.convertObjectToJSONFile(person, new File("person2.json"));23        Person person4 = objectMapperService.convertJSONFileToObject(new File("person2.json"), Person.class);24        System.out.println("person4 = " + person4);25        objectMapperService.convertObjectToJSONFile(person, "person3.json");26        Person person5 = objectMapperService.convertJSONFileToObject("person3.json", Person.class);27        System.out.println("person5 = " + person5);28        List<Person> personList = new ArrayList<>();29        personList.add(person);30        personList.add(person1);31        personList.add(person2);32        personList.add(person3);33        personList.add(person4);ObjectMapperService
Using AI Code Generation
1import com.testsigma.automator.service.ObjectMapperService;2import com.testsigma.automator.util.Log;3import java.io.IOException;4import java.util.HashMap;5import java.util.Map;6import org.testng.annotations.Test;7public class TestObjectMapperService {8  public void testObjectMapperService() throws IOException {9    Map<String, Object> map = new HashMap<>();10    map.put("a", "b");11    map.put("c", "d");12    String json = ObjectMapperService.getJson(map);13    Log.info(json);14    Map<String, Object> map1 = ObjectMapperService.getMap(json);15    Log.info(map1);16  }17}18import com.testsigma.automator.service.ObjectMapperService;19import com.testsigma.automator.util.Log;20import java.io.IOException;21import java.util.HashMap;22import java.util.Map;23import org.testng.annotations.Test;24public class TestObjectMapperService {25  public void testObjectMapperService() throws IOException {26    Map<String, Object> map = new HashMap<>();27    map.put("a", "b");28    map.put("c", "d");29    String json = ObjectMapperService.getJson(map);30    Log.info(json);31    Map<String, Object> map1 = ObjectMapperService.getMap(json);32    Log.info(map1);33  }34}35import com.testsigma.automator.service.ObjectMapperService;36import com.testsigma.automator.util.Log;37import java.io.IOException;38import java.util.HashMap;39import java.util.Map;40import org.testng.annotations.Test;41public class TestObjectMapperService {42  public void testObjectMapperService() throws IOException {43    Map<String, Object> map = new HashMap<>();44    map.put("a", "b");45    map.put("c", "d");46    String json = ObjectMapperService.getJson(map);47    Log.info(json);48    Map<String, Object> map1 = ObjectMapperService.getMap(json);49    Log.info(map1);50  }51}ObjectMapperService
Using AI Code Generation
1ObjectMapperService mapperService = new ObjectMapperService();2String json = "{\"name\":\"John\", \"age\":30, \"car\":null}";3Person person = mapperService.convertJsonToObject(json, Person.class);4System.out.println(person.getName());5ObjectMapperService mapperService = new ObjectMapperService();6Person person = new Person("John", 30, null);7String json = mapperService.convertObjectToJson(person);8System.out.println(json);9ObjectMapperService mapperService = new ObjectMapperService();10Person person1 = new Person("John", 30, null);11Person person2 = new Person("Peter", 25, null);12List<Person> persons = new ArrayList<>();13persons.add(person1);14persons.add(person2);15String json = mapperService.convertListToJson(persons);16System.out.println(json);17ObjectMapperService mapperService = new ObjectMapperService();18String json = "[{\"name\":\"John\", \"age\":30, \"car\":null}, {\"name\":\"Peter\", \"age\":25, \"car\":null}]";19List<Person> persons = mapperService.convertJsonToList(json, Person.class);20System.out.println(persons.get(0).getName());21System.out.println(persons.get(1).getName());22ObjectMapperService mapperService = new ObjectMapperService();23String json = "{\"person1\":{\"name\":\"John\", \"age\":30, \"car\":null}, \"person2\":{\"name\":\"Peter\", \"age\":25, \"car\":null}}";24Map<String, Person> persons = mapperService.convertJsonToMap(json, Person.class);25System.out.println(persons.get("person1").getName());26System.out.println(persons.get("person2").getName());ObjectMapperService
Using AI Code Generation
1ObjectMapperService objectMapperService = new ObjectMapperService();2ObjectMapperService.MapToJavaObject(objectMapperService, json, javaObject);3ObjectMapperService objectMapperService = new ObjectMapperService();4ObjectMapperService.MapToJsonObject(objectMapperService, javaObject, json);5ObjectMapperService objectMapperService = new ObjectMapperService();6ObjectMapperService.Map(objectMapperService, json, javaObject);7ObjectMapperService objectMapperService = new ObjectMapperService();8ObjectMapperService.Map(objectMapperService, json, javaObject, javaObjectClass);9ObjectMapperService objectMapperService = new ObjectMapperService();10ObjectMapperService.Map(objectMapperService, json, javaObject, javaObjectClass, jsonType);11ObjectMapperService objectMapperService = new ObjectMapperService();12ObjectMapperService.Map(objectMapperService, json, javaObject, javaObjectClass, jsonType, javaType);13ObjectMapperService objectMapperService = new ObjectMapperService();14ObjectMapperService.Map(objectMapperService, json, javaObject, javaObjectClass, jsonType, javaType, javaCollectionType);15ObjectMapperService objectMapperService = new ObjectMapperService();16ObjectMapperService.Map(objectMapperService, json, javaObject, javaObjectClass, jsonType, javaType, javaCollectionType, javaMapType);17ObjectMapperService objectMapperService = new ObjectMapperService();18ObjectMapperService.Map(objectMapperService, json, javaObject, javaObjectClass,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!!
