use of com.fasterxml.jackson.core.type.TypeReference in project actor4j-core by relvaner.
the class PersistenceFeature method test.
@Test(timeout = 10000)
public void test() {
CountDownLatch testDone = new CountDownLatch(2);
ActorSystem system = new ActorSystem();
AtomicBoolean first = new AtomicBoolean(true);
UUID id = system.addActor(() -> new PersistentActor<MyState, MyEvent>("example") {
@Override
public void receive(ActorMessage<?> message) {
MyEvent event1 = new MyEvent("I am the first event!");
MyEvent event2 = new MyEvent("I am the second event!");
saveSnapshot(null, null, new MyState("I am a state!"));
persist((s) -> logger().debug(String.format("Event: %s", s)), (e) -> logger().error(String.format("Error: %s", e.getMessage())), event1, event2);
if (first.getAndSet(false))
tell(null, Actor.RESTART, self());
}
@Override
public void recover(String json) {
if (!Recovery.isError(json)) {
logger().debug(String.format("Recovery: %s", json));
Recovery<MyState, MyEvent> obj = Recovery.convertValue(json, new TypeReference<Recovery<MyState, MyEvent>>() {
});
logger().debug(String.format("Recovery: %s", obj.toString()));
if (first.get())
assertEquals("{\"state\":{}}", json);
else {
assertEquals("I am a state!", obj.state.title);
assertTrue(obj.events.size() == 2);
assertEquals("I am the first event!", obj.events.get(0).title);
assertEquals("I am the second event!", obj.events.get(1).title);
}
testDone.countDown();
} else
logger().error(String.format("Error: %s", Recovery.getErrorMsg(json)));
}
@Override
public UUID persistenceId() {
/* e.g. https://www.uuidgenerator.net/ */
return UUID.fromString("60f086af-27d3-44e9-8fd7-eb095c98daed");
}
});
// Drop database
MongoClient client = new MongoClient("localhost", 27017);
client.dropDatabase("actor4j-test");
client.close();
system.persistenceMode("localhost", 27017, "actor4j-test");
system.start();
system.sendWhenActive(new ActorMessage<Object>(null, 0, system.SYSTEM_ID, id));
try {
testDone.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
system.shutdownWithActors(true);
}
use of com.fasterxml.jackson.core.type.TypeReference in project syncope by apache.
the class SyncopeJWTSSOProvider method resolve.
@Transactional(readOnly = true)
@Override
public Pair<User, Set<SyncopeGrantedAuthority>> resolve(final JwtClaims jwtClaims) {
User user = userDAO.findByUsername(jwtClaims.getSubject());
Set<SyncopeGrantedAuthority> authorities = Collections.emptySet();
if (user != null) {
AccessToken accessToken = accessTokenDAO.find(jwtClaims.getTokenId());
if (accessToken.getAuthorities() != null) {
try {
authorities = POJOHelper.deserialize(ENCRYPTOR.decode(new String(accessToken.getAuthorities()), CipherAlgorithm.AES), new TypeReference<Set<SyncopeGrantedAuthority>>() {
});
} catch (Throwable t) {
LOG.error("Could not read stored authorities", t);
}
}
}
return Pair.of(user, authorities);
}
use of com.fasterxml.jackson.core.type.TypeReference in project light-4j by networknt.
the class BodyHandler method handleRequest.
/**
* Check the header starts with application/json and parse it into map or list
* based on the first character "{" or "[". Ignore other content type values.
*
* @param exchange HttpServerExchange
* @throws Exception Exception
*/
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
// parse the body to map or list if content type is application/json
String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
if (contentType != null && contentType.startsWith("application/json")) {
if (exchange.isInIoThread()) {
exchange.dispatch(this);
return;
}
exchange.startBlocking();
InputStream is = exchange.getInputStream();
if (is != null) {
try {
if (is.available() != -1) {
Object body;
String s = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
s = s.trim();
if (s.startsWith("{")) {
body = Config.getInstance().getMapper().readValue(s, new TypeReference<HashMap<String, Object>>() {
});
} else if (s.startsWith("[")) {
body = Config.getInstance().getMapper().readValue(s, new TypeReference<List<Object>>() {
});
} else {
// error here. The content type in head doesn't match the body.
Status status = new Status(CONTENT_TYPE_MISMATCH, contentType);
exchange.setStatusCode(status.getStatusCode());
exchange.getResponseSender().send(status.toString());
return;
}
exchange.putAttachment(REQUEST_BODY, body);
}
} catch (IOException e) {
logger.error("IOException: ", e);
Status status = new Status(CONTENT_TYPE_MISMATCH, contentType);
exchange.setStatusCode(status.getStatusCode());
exchange.getResponseSender().send(status.toString());
return;
}
}
}
next.handleRequest(exchange);
}
use of com.fasterxml.jackson.core.type.TypeReference in project tutorials by eugenp.
the class JacksonMapDeserializeUnitTest method whenObjectStringMapDeserialize_thenCorrect.
@Test
public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
};
map = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class);
Assert.assertEquals("Comedy", classWithMap.getMap().get(new MyPair("Abbott", "Costello")));
}
use of com.fasterxml.jackson.core.type.TypeReference in project nakadi by zalando.
the class EventStreamController method getStreamingStart.
@VisibleForTesting
List<NakadiCursor> getStreamingStart(final EventType eventType, final String cursorsStr) throws UnparseableCursorException, ServiceUnavailableException, InvalidCursorException, InternalNakadiException, NoSuchEventTypeException {
List<Cursor> cursors = null;
if (cursorsStr != null) {
try {
cursors = jsonMapper.readValue(cursorsStr, new TypeReference<ArrayList<Cursor>>() {
});
} catch (final IOException ex) {
throw new UnparseableCursorException("incorrect syntax of X-nakadi-cursors header", ex, cursorsStr);
}
// Unfortunately, In order to have consistent exception checking, one can not just call validator
for (final Cursor cursor : cursors) {
if (null == cursor.getPartition()) {
throw new InvalidCursorException(CursorError.NULL_PARTITION, cursor);
} else if (null == cursor.getOffset()) {
throw new InvalidCursorException(CursorError.NULL_OFFSET, cursor);
}
}
}
final Timeline latestTimeline = timelineService.getActiveTimeline(eventType);
if (null != cursors) {
if (cursors.isEmpty()) {
throw new InvalidCursorException(CursorError.INVALID_FORMAT);
}
final List<NakadiCursor> result = new ArrayList<>();
for (final Cursor c : cursors) {
result.add(cursorConverter.convert(eventType.getName(), c));
}
for (final NakadiCursor c : result) {
if (c.getTimeline().isDeleted()) {
throw new InvalidCursorException(CursorError.UNAVAILABLE, c);
}
}
final Map<Storage, List<NakadiCursor>> groupedCursors = result.stream().collect(Collectors.groupingBy(c -> c.getTimeline().getStorage()));
for (final Map.Entry<Storage, List<NakadiCursor>> entry : groupedCursors.entrySet()) {
timelineService.getTopicRepository(entry.getKey()).validateReadCursors(entry.getValue());
}
return result;
} else {
final TopicRepository latestTopicRepository = timelineService.getTopicRepository(latestTimeline);
// if no cursors provided - read from the newest available events
return latestTopicRepository.loadTopicStatistics(Collections.singletonList(latestTimeline)).stream().map(PartitionStatistics::getLast).collect(Collectors.toList());
}
}
Aggregations