Search in sources :

Example 46 with TypeReference

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);
}
Also used : ActorSystem(actor4j.core.ActorSystem) ActorSystem(actor4j.core.ActorSystem) ActorPersistenceObject(actor4j.core.persistence.ActorPersistenceObject) Actor(actor4j.core.actors.Actor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) UUID(java.util.UUID) Recovery(actor4j.core.persistence.Recovery) ActorLogger(actor4j.core.utils.ActorLogger) PersistentActor(actor4j.core.actors.PersistentActor) ActorMessage(actor4j.core.messages.ActorMessage) CountDownLatch(java.util.concurrent.CountDownLatch) MongoClient(com.mongodb.MongoClient) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Assert(org.junit.Assert) CountDownLatch(java.util.concurrent.CountDownLatch) Recovery(actor4j.core.persistence.Recovery) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MongoClient(com.mongodb.MongoClient) ActorPersistenceObject(actor4j.core.persistence.ActorPersistenceObject) TypeReference(com.fasterxml.jackson.core.type.TypeReference) UUID(java.util.UUID) Test(org.junit.Test)

Example 47 with TypeReference

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);
}
Also used : User(org.apache.syncope.core.persistence.api.entity.user.User) AccessToken(org.apache.syncope.core.persistence.api.entity.AccessToken) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Transactional(org.springframework.transaction.annotation.Transactional)

Example 48 with TypeReference

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);
}
Also used : Status(com.networknt.status.Status) Scanner(java.util.Scanner) InputStream(java.io.InputStream) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException)

Example 49 with TypeReference

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")));
}
Also used : MyPair(com.baeldung.jackson.entities.MyPair) HashMap(java.util.HashMap) ClassWithAMap(com.baeldung.jackson.entities.ClassWithAMap) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Test(org.junit.Test)

Example 50 with TypeReference

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());
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) FlowIdUtils(org.zalando.nakadi.util.FlowIdUtils) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) NakadiException(org.zalando.nakadi.exceptions.NakadiException) NoSuchEventTypeException(org.zalando.nakadi.exceptions.NoSuchEventTypeException) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) Problem(org.zalando.problem.Problem) Map(java.util.Map) Counter(com.codahale.metrics.Counter) TimelineService(org.zalando.nakadi.service.timeline.TimelineService) TypeReference(com.fasterxml.jackson.core.type.TypeReference) FeatureToggleService(org.zalando.nakadi.service.FeatureToggleService) EventTypeChangeListener(org.zalando.nakadi.service.EventTypeChangeListener) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) ConsumerLimitingService(org.zalando.nakadi.service.ConsumerLimitingService) TopicRepository(org.zalando.nakadi.repository.TopicRepository) ConnectionSlot(org.zalando.nakadi.service.ConnectionSlot) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) PartitionStatistics(org.zalando.nakadi.domain.PartitionStatistics) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) BlacklistService(org.zalando.nakadi.service.BlacklistService) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) Timeline(org.zalando.nakadi.domain.Timeline) ServiceTemporarilyUnavailableException(org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException) Optional(java.util.Optional) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) UnparseableCursorException(org.zalando.nakadi.exceptions.UnparseableCursorException) Client(org.zalando.nakadi.security.Client) Storage(org.zalando.nakadi.domain.Storage) ClosedConnectionsCrutch(org.zalando.nakadi.service.ClosedConnectionsCrutch) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cursor(org.zalando.nakadi.view.Cursor) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) Meter(com.codahale.metrics.Meter) HttpServletRequest(javax.servlet.http.HttpServletRequest) ImmutableList(com.google.common.collect.ImmutableList) EventStreamFactory(org.zalando.nakadi.service.EventStreamFactory) Qualifier(org.springframework.beans.factory.annotation.Qualifier) PRECONDITION_FAILED(javax.ws.rs.core.Response.Status.PRECONDITION_FAILED) Nullable(javax.annotation.Nullable) OutputStream(java.io.OutputStream) AccessDeniedException(org.zalando.nakadi.exceptions.runtime.AccessDeniedException) EventType(org.zalando.nakadi.domain.EventType) MetricRegistry(com.codahale.metrics.MetricRegistry) Logger(org.slf4j.Logger) INTERNAL_SERVER_ERROR(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) MetricUtils.metricNameFor(org.zalando.nakadi.metrics.MetricUtils.metricNameFor) IOException(java.io.IOException) FORBIDDEN(javax.ws.rs.core.Response.Status.FORBIDDEN) EventStream(org.zalando.nakadi.service.EventStream) AuthorizationValidator(org.zalando.nakadi.service.AuthorizationValidator) HttpStatus(org.springframework.http.HttpStatus) EventConsumer(org.zalando.nakadi.repository.EventConsumer) EventTypeRepository(org.zalando.nakadi.repository.EventTypeRepository) Closeable(java.io.Closeable) NoConnectionSlotsException(org.zalando.nakadi.exceptions.NoConnectionSlotsException) LIMIT_CONSUMERS_NUMBER(org.zalando.nakadi.service.FeatureToggleService.Feature.LIMIT_CONSUMERS_NUMBER) CursorError(org.zalando.nakadi.domain.CursorError) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MetricUtils(org.zalando.nakadi.metrics.MetricUtils) EventStreamConfig(org.zalando.nakadi.service.EventStreamConfig) InternalNakadiException(org.zalando.nakadi.exceptions.InternalNakadiException) Collections(java.util.Collections) CursorConverter(org.zalando.nakadi.service.CursorConverter) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) UnparseableCursorException(org.zalando.nakadi.exceptions.UnparseableCursorException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) Cursor(org.zalando.nakadi.view.Cursor) Timeline(org.zalando.nakadi.domain.Timeline) Storage(org.zalando.nakadi.domain.Storage) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) TypeReference(com.fasterxml.jackson.core.type.TypeReference) TopicRepository(org.zalando.nakadi.repository.TopicRepository) Map(java.util.Map) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

TypeReference (com.fasterxml.jackson.core.type.TypeReference)316 IOException (java.io.IOException)130 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)113 Test (org.junit.Test)95 ArrayList (java.util.ArrayList)74 Map (java.util.Map)74 List (java.util.List)60 HashMap (java.util.HashMap)58 File (java.io.File)34 TextPageLink (org.thingsboard.server.common.data.page.TextPageLink)27 Collectors (java.util.stream.Collectors)25 InputStream (java.io.InputStream)23 JsonNode (com.fasterxml.jackson.databind.JsonNode)19 ImmutableMap (com.google.common.collect.ImmutableMap)19 lombok.val (lombok.val)18 Matchers.containsString (org.hamcrest.Matchers.containsString)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)14 Collections (java.util.Collections)13 ISE (org.apache.druid.java.util.common.ISE)12 URL (java.net.URL)10