Skip to content
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.intuit.tank.http.json;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import tools.jackson.databind.json.JsonMapper;

/**
* Global shared, threads-safe JsonMapper instance.
*/
public class GenericJsonHandler {
private static final Logger logger = LogManager.getLogger(GenericJsonHandler.class);
private static final JsonMapper jsonMapper = JsonMapper.builder().build();

/**
* Converts a JSON string to a Java object of a specified class.
* @param json
* @param clazz
* @return
*/
protected static <T> T fromJson(String json, Class<T> clazz) {
try {
return jsonMapper.readValue(json, clazz);
} catch (Exception ex) {
logger.warn("Unable to parse the response string as a JSON object: {}", json, ex);
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,12 @@
* #L%
*/

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
Expand All @@ -46,13 +45,13 @@ public JsonResponse(String resp) {

@Override
public void setResponseBody(String body) {
this.response = this.cleanString(body);
this.response = cleanString(body);
}

@Override
public void setResponseBody(byte[] byteArray) {
this.responseByteArray = byteArray;
this.response = this.cleanString(new String(byteArray));
this.response = cleanString(new String(byteArray));
}

@Override
Expand All @@ -78,25 +77,20 @@ public String getValue(String key) {
return "";
}
}

private String cleanString(String input) {
try {
return StringUtils.remove(input.trim(),"(\r\n)+");
} catch (Exception ex) {
return input;
}
return input == null ? null :
input.strip()
.replace("\r\n", "")
.replace("\r", "")
.replace("\n", "");
}

private void initialize() {
try {
if (!StringUtils.isEmpty(this.response)) {
this.jsonMap = new ObjectMapper().readValue(this.response, HashMap.class);
} else {
this.jsonMap = new HashMap();
}
} catch (IOException ex) {
logger.warn("Unable to parse the response string as a JSON object: " + this.response, ex);
}
Map map = StringUtils.isNotEmpty(response)
? GenericJsonHandler.fromJson(response, HashMap.class)
: null;
jsonMap = (map != null) ? map : Collections.emptyMap();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

import org.apache.commons.lang3.tuple.ImmutablePair;
Expand Down Expand Up @@ -93,7 +92,7 @@ public void testGetValue_1()
public void testJsonResponseBody() throws Exception{

JsonResponse fixture = new JsonResponse();
fixture.setResponseBody(readFile("src/test/resources/json-response.json"));
fixture.setResponseBody(Files.readString(Paths.get("src/test/resources/json-response.json")));

Stream<Pair<String, String>> keys = Stream.of(
new ImmutablePair<>("/data/data/returns/IRS1040/Return/ReturnData/PPPerson/SpouseFilerInfoPP/FieldAttributes/UUID", "de7f702f-e40b-4f16-8a7d-e4263f11421d"),
Expand All @@ -114,18 +113,4 @@ public void testJsonResponseBody() throws Exception{

keys.forEach(pair -> assertEquals(pair.getValue(), fixture.getValue(pair.getKey())));
}

private String readFile( String file ) throws IOException {

try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;

import com.fasterxml.jackson.core.JsonProcessingException;
import tools.jackson.core.JacksonException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.logging.log4j.LogManager;
Expand Down Expand Up @@ -111,7 +111,7 @@ public void startTest(final StandaloneAgentRequest request) {
currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.AVAILABLE);
try {
sendAvailability();
} catch (JsonProcessingException ex) {
} catch (JacksonException ex) {
throw new RuntimeException(ex);
}
}
Expand Down Expand Up @@ -152,7 +152,7 @@ private void startPinger() {
t.start();
}

private void sendAvailability() throws JsonProcessingException {
private void sendAvailability() throws JacksonException {
// create new availability as a copy of the original
AgentAvailability availability = new AgentAvailability(currentAvailability.getInstanceId(),
currentAvailability.getInstanceUrl(), currentAvailability.getCapacity(),
Expand Down
7 changes: 7 additions & 0 deletions agent/apiharness/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@
<version>${project.version}</version>
</dependency>

<!-- Workaround for JsonLayout in log4j2 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@
import java.net.http.HttpResponse;
import java.util.Date;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import tools.jackson.core.JacksonException;
import org.apache.http.HttpHeaders;
import org.apache.http.entity.ContentType;
import org.apache.logging.log4j.LogManager;
Expand All @@ -36,6 +34,7 @@
import com.intuit.tank.vm.agent.messages.WatsAgentStatusResponse;
import com.intuit.tank.vm.api.enumerated.JobStatus;
import com.intuit.tank.vm.api.enumerated.AgentCommand;
import tools.jackson.databind.json.JsonMapper;

public class APIMonitor implements Runnable {

Expand All @@ -44,7 +43,7 @@ public class APIMonitor implements Runnable {
*/
private static final int MIN_REPORT_TIME = 15000;
private static final Logger LOG = LogManager.getLogger(APIMonitor.class);
private static final ObjectWriter objectWriter = new ObjectMapper().writerFor(CloudVmStatus.class).withDefaultPrettyPrinter();
private static final JsonMapper jsonMapper = JsonMapper.builder().build();
private static boolean doMonitor = true;
private static final HttpClient client = HttpClient.newHttpClient();
private static CloudVmStatus status;
Expand Down Expand Up @@ -169,8 +168,8 @@ public synchronized static void setJobStatus(JobStatus jobStatus) {
}
}

protected static void setInstanceStatus(String instanceId, CloudVmStatus VmStatus) throws URISyntaxException, JsonProcessingException {
String json = objectWriter.writeValueAsString(VmStatus);
protected static void setInstanceStatus(String instanceId, CloudVmStatus VmStatus) throws URISyntaxException, JacksonException {
String json = jsonMapper.writeValueAsString(VmStatus);
String token = APITestHarness.getInstance().getTankConfig().getAgentConfig().getAgentToken();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(APITestHarness.getInstance().getTankConfig().getControllerBase() + "/v2/agent/instance/status/" + instanceId))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.concurrent.Semaphore;
import java.util.zip.GZIPInputStream;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.intuit.tank.http.TankHttpClient;
import com.intuit.tank.vm.api.enumerated.*;
import org.apache.commons.io.FileUtils;
Expand Down Expand Up @@ -66,6 +65,7 @@
import com.intuit.tank.vm.common.TankConstants;
import com.intuit.tank.vm.settings.TankConfig;
import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils;
import tools.jackson.databind.json.JsonMapper;

public class APITestHarness {
private static final Logger LOG = LogManager.getLogger(APITestHarness.class);
Expand Down Expand Up @@ -255,6 +255,7 @@ private static void usage() {
private void startHttp(String baseUrl, String token) {
isLocal = false;
HostInfo hostInfo = new HostInfo();
JsonMapper JSON_MAPPER = JsonMapper.builder().build();
CommandListener.startHttpServer(tankConfig.getAgentConfig().getAgentPort());
baseUrl = (baseUrl == null) ? AmazonUtil.getControllerBaseUrl() : baseUrl;
token = (token == null) ? AmazonUtil.getAgentToken() : token;
Expand Down Expand Up @@ -299,8 +300,7 @@ private void startHttp(String baseUrl, String token) {
LOG.info(LogUtil.getLogMessage("Sending AgentData to controller: " + data.toString()));
while (count < FIBONACCI.length) {
try {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writerFor(AgentData.class)
String json = JSON_MAPPER.writerFor(AgentData.class)
.withDefaultPrettyPrinter().writeValueAsString(data);
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(baseUrl + "/v2/agent/ready"))
Expand All @@ -310,10 +310,10 @@ private void startHttp(String baseUrl, String token) {
.POST(BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
startData = objectMapper.readerFor(AgentTestStartData.class).readValue(response.body());
startData = JSON_MAPPER.readerFor(AgentTestStartData.class).readValue(response.body());
break;
} catch (Exception e) {
LOG.error("Error sending ready: " + e, e);
LOG.error("Error sending ready: {}", e, e);
try {
Thread.sleep(FIBONACCI[count++] * 1000);
} catch ( InterruptedException ignored) {}
Expand Down Expand Up @@ -345,7 +345,7 @@ private void startHttp(String baseUrl, String token) {
thread.setDaemon(false);
thread.start();
} catch (Exception e) {
LOG.error("Error communicating with controller: " + e, e);
LOG.error("Error communicating with controller: {}", e, e);
System.exit(0);
}
}
Expand Down
Loading
Loading