use of com.fasterxml.jackson.core.type.TypeReference in project nzbhydra2 by theotherp.
the class BaseConfigTest method applicationPropertiesShouldHaveTheSameKeysAsConfigClasses.
@Test
public void applicationPropertiesShouldHaveTheSameKeysAsConfigClasses() throws Exception {
ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
jsonMapper.registerModule(new Jdk8Module());
String jsonFromBaseConfig = jsonMapper.writeValueAsString(new BaseConfig());
ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());
yamlMapper.registerModule(new Jdk8Module());
BufferedReader reader = new BufferedReader(new InputStreamReader(BaseConfig.class.getResource("/config/application.yml").openStream()));
String applicationYmlContent = reader.lines().collect(Collectors.joining("\n"));
BaseConfig fromApplicationYml = yamlMapper.readValue(applicationYmlContent, BaseConfig.class);
String jsonFromApplicationProperties = jsonMapper.writeValueAsString(fromApplicationYml);
if (COMPARE_CONFIG_VALUES) {
assertEquals("JSON generated from application.yml and base config should be the same", jsonFromApplicationProperties, jsonFromBaseConfig);
}
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
};
HashMap<String, Object> mapFromApplicationYml = yamlMapper.readValue(applicationYmlContent, typeRef);
HashMap<String, Object> mapFromBaseConfig = jsonMapper.readValue(jsonFromBaseConfig, typeRef);
compare(mapFromApplicationYml, mapFromBaseConfig);
}
use of com.fasterxml.jackson.core.type.TypeReference in project nzbhydra2 by theotherp.
the class SearchingResultsUiTest method prepareFiveResultsFromTwoIndexers.
protected void prepareFiveResultsFromTwoIndexers() throws Exception {
replaceConfig(getClass().getResource("twoIndexers.json"));
mockWebServer.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
int mockServerPort = mockWebServer.getPort();
String mockServerBaseUrl = "http://127.0.0.1:" + mockServerPort + "/";
if (request.getRequestUrl().queryParameter("apikey") != null && request.getRequestUrl().queryParameter("apikey").equals("apikey1")) {
NewznabXmlItem result1 = RssItemBuilder.builder("indexer1-result1").pubDate(Instant.now().minus(1, ChronoUnit.DAYS)).link(mockServerBaseUrl + "nzblink1").hasNfo(false).grabs(1).size(mbToBytes(1)).newznabAttributes(new ArrayList<>(Arrays.asList(new NewznabAttribute("category", "5000")))).category("TV").build();
NewznabXmlItem result2 = RssItemBuilder.builder("indexer1-result2").pubDate(Instant.now().minus(2, ChronoUnit.DAYS)).link(mockServerBaseUrl + "nzblink2").hasNfo(true).grabs(2).size(mbToBytes(2)).newznabAttributes(new ArrayList<>(Arrays.asList(new NewznabAttribute("category", "5040")))).category("TV SD").build();
NewznabXmlItem result3 = RssItemBuilder.builder("indexer1-result3").pubDate(Instant.now().minus(3, ChronoUnit.DAYS)).link(mockServerBaseUrl + "nzblink3").comments("comments").grabs(3).size(mbToBytes(3)).newznabAttributes(new ArrayList<>(Arrays.asList(new NewznabAttribute("category", "5030")))).category("TV HD").build();
NewznabXmlRoot rssRoot = NewznabMockBuilder.getRssRoot(Arrays.asList(result1, result2, result3), 0, 3);
return new MockResponse().setBody(rssRoot.toXmlString()).setHeader("Content-Type", "application/xml; charset=utf-8");
} else if (request.getRequestUrl().queryParameter("apikey") != null && request.getRequestUrl().queryParameter("apikey").equals("apikey2")) {
NewznabXmlItem result5 = RssItemBuilder.builder("indexer2-result2").pubDate(Instant.now().minus(5, ChronoUnit.DAYS)).link(mockServerBaseUrl + "nzblink5").grabs(5).size(mbToBytes(5)).newznabAttributes(new ArrayList<>(Arrays.asList(new NewznabAttribute("category", "2040")))).category("Movies HD").build();
NewznabXmlItem result4 = RssItemBuilder.builder("indexer2-result1").pubDate(Instant.now().minus(4, ChronoUnit.DAYS)).link(mockServerBaseUrl + "nzblink4").grabs(4).size(mbToBytes(4)).newznabAttributes(new ArrayList<>(Arrays.asList(new NewznabAttribute("category", "2000")))).category("Movies").build();
NewznabXmlRoot rssRoot = NewznabMockBuilder.getRssRoot(Arrays.asList(result4, result5), 0, 2);
return new MockResponse().setBody(rssRoot.toXmlString()).setHeader("Content-Type", "application/xml; charset=utf-8");
} else if (request.getPath().endsWith("nzbzip")) {
System.out.println("Returning NZB ZIP response");
String body = request.getBody().readString(Charset.defaultCharset());
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Long> ids = objectMapper.readValue(body, new TypeReference<List<Long>>() {
});
FileZipResponse response = new FileZipResponse(true, "bla", null, ids, Collections.emptyList());
return new MockResponse().setBody(objectMapper.writeValueAsString(response)).setHeader("Content-Type", "application/xml; charset=utf-8");
} catch (IOException e) {
}
throw new RuntimeException("Unable to handle nzbzip");
} else if (request.getPath().contains("nzblink")) {
System.out.println("Returning NZB");
return new MockResponse().setBody("nzb").setHeader("Content-Type", "application/x-nzb; charset=utf-8");
} else {
throw new RuntimeException("Unexpected api key " + request.getRequestUrl().queryParameter("apikey"));
}
}
});
}
use of com.fasterxml.jackson.core.type.TypeReference in project light-portal by networknt.
the class ServerInfoRetriever method retrieve.
/**
* @param host the protocol, host and port
* @param path the path of the server info endpoint
* @param token the JWT token to access the server info endpoint
* @return a map that represent the server info or error status
* @throws ClientException client exception
*/
public static Map<String, Object> retrieve(String host, String path, String token) throws ClientException {
Map<String, Object> map;
final Http2Client client = Http2Client.getInstance();
final CountDownLatch latch = new CountDownLatch(1);
final ClientConnection connection;
try {
connection = client.connect(new URI(host), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
} catch (Exception e) {
throw new ClientException(e);
}
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
try {
ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(path);
request.getRequestHeaders().put(Headers.AUTHORIZATION, "Bearer " + token);
connection.sendRequest(request, client.createClientCallback(reference, latch));
latch.await();
// int statusCode = reference.get().getResponseCode();
String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
// regardless there is an error, convert the body to map anyway and the caller will process the
// result accordingly.
map = Config.getInstance().getMapper().readValue(body, new TypeReference<HashMap<String, Object>>() {
});
} catch (Exception e) {
logger.error("Exception: ", e);
throw new ClientException(e);
} finally {
IoUtils.safeClose(connection);
}
return map;
}
use of com.fasterxml.jackson.core.type.TypeReference in project java-sdk by optimizely.
the class ProjectConfigJacksonDeserializer method deserialize.
@Override
public ProjectConfig deserialize(JsonParser parser, DeserializationContext context) throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Audience.class, new AudienceJacksonDeserializer());
module.addDeserializer(Group.class, new GroupJacksonDeserializer());
mapper.registerModule(module);
JsonNode node = parser.getCodec().readTree(parser);
String accountId = node.get("accountId").textValue();
String projectId = node.get("projectId").textValue();
String revision = node.get("revision").textValue();
String version = node.get("version").textValue();
int datafileVersion = Integer.parseInt(version);
List<Group> groups = mapper.readValue(node.get("groups").toString(), new TypeReference<List<Group>>() {
});
List<Experiment> experiments = mapper.readValue(node.get("experiments").toString(), new TypeReference<List<Experiment>>() {
});
List<Attribute> attributes;
attributes = mapper.readValue(node.get("attributes").toString(), new TypeReference<List<Attribute>>() {
});
List<EventType> events = mapper.readValue(node.get("events").toString(), new TypeReference<List<EventType>>() {
});
List<Audience> audiences = mapper.readValue(node.get("audiences").toString(), new TypeReference<List<Audience>>() {
});
boolean anonymizeIP = false;
List<LiveVariable> liveVariables = null;
if (datafileVersion >= Integer.parseInt(ProjectConfig.Version.V3.toString())) {
liveVariables = mapper.readValue(node.get("variables").toString(), new TypeReference<List<LiveVariable>>() {
});
anonymizeIP = node.get("anonymizeIP").asBoolean();
}
List<FeatureFlag> featureFlags = null;
List<Rollout> rollouts = null;
if (datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString())) {
featureFlags = mapper.readValue(node.get("featureFlags").toString(), new TypeReference<List<FeatureFlag>>() {
});
rollouts = mapper.readValue(node.get("rollouts").toString(), new TypeReference<List<Rollout>>() {
});
}
return new ProjectConfig(accountId, anonymizeIP, projectId, revision, version, attributes, audiences, events, experiments, featureFlags, groups, liveVariables, rollouts);
}
use of com.fasterxml.jackson.core.type.TypeReference in project dcos-commons by mesosphere.
the class MarathonConstraintParser method splitConstraints.
/**
* Splits the provided marathon constraint statement into elements. Doesn't do any validation
* on the element contents.
*/
@VisibleForTesting
static List<List<String>> splitConstraints(String marathonConstraints) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// Meanwhile the marathon web interface uses a format like: 'a:b:c,d:e'
try {
// First try: ["a", "b", "c"]
// This format technically isn't present in the Marathon docs, but we're being lenient here.
List<String> row = mapper.readValue(marathonConstraints, new TypeReference<List<String>>() {
});
LOGGER.debug("Flat list '{}' => single row: '{}'", marathonConstraints, row);
return Arrays.asList(row);
} catch (IOException | ClassCastException e1) {
try {
// Then try: [["a", "b", "c"], ["d", "e"]]
List<List<String>> rows = mapper.readValue(marathonConstraints, new TypeReference<List<List<String>>>() {
});
LOGGER.debug("Nested list '{}' => {} rows: '{}'", marathonConstraints, rows.size(), rows);
return rows;
} catch (IOException | ClassCastException e2) {
// May throw ClassCastException as well as IOException
// Finally try: a:b:c,d:e
// Note: We use Guava's Splitter rather than String.split(regex) in order to correctly
// handle empty trailing fields like 'a:b:' => ['a', 'b', ''] (shouldn't come up but just in case).
List<List<String>> rows = new ArrayList<>();
// Allow backslash-escaping of commas or colons within regexes:
for (String rowStr : escapedSplit(marathonConstraints, ',')) {
rows.add(Lists.newArrayList(escapedSplit(rowStr, ':')));
}
LOGGER.debug("Comma/colon-separated '{}' => {} rows: '{}'", marathonConstraints, rows.size(), rows);
return rows;
}
}
}
Aggregations