Example usage for com.fasterxml.jackson.databind ObjectMapper getFactory

List of usage examples for com.fasterxml.jackson.databind ObjectMapper getFactory

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper getFactory.

Prototype

@Override
public JsonFactory getFactory() 

Source Link

Document

Method that can be used to get hold of JsonFactory that this mapper uses if it needs to construct JsonParser s and/or JsonGenerator s.

Usage

From source file:org.apache.taverna.scufl2.api.configurations.Configuration.java

protected JsonNode parseJson(String jsonString) {
    ObjectMapper mapper = new ObjectMapper();
    try {/*from ww  w  .j  a va2  s  .co  m*/
        JsonParser parser = mapper.getFactory().createParser(jsonString);
        return parser.readValueAs(JsonNode.class);
    } catch (IOException e) {
        throw new IllegalArgumentException("Not valid JSON string", e);
    }
}

From source file:com.streamsets.datacollector.execution.store.FilePipelineStateStore.java

@Override
public List<PipelineState> getHistory(String pipelineName, String rev, boolean fromBeginning)
        throws PipelineStoreException {
    if (!pipelineDirExists(pipelineName, rev) || !pipelineStateHistoryFileExists(pipelineName, rev)) {
        return Collections.emptyList();
    }/*from w  ww  .jav  a 2  s. c  o m*/
    try (Reader reader = new FileReader(getPipelineStateHistoryFile(pipelineName, rev))) {
        ObjectMapper objectMapper = ObjectMapperFactory.get();
        JsonParser jsonParser = objectMapper.getFactory().createParser(reader);
        MappingIterator<PipelineStateJson> pipelineStateMappingIterator = objectMapper.readValues(jsonParser,
                PipelineStateJson.class);
        List<PipelineStateJson> pipelineStateJsons = pipelineStateMappingIterator.readAll();
        Collections.reverse(pipelineStateJsons);
        if (fromBeginning) {
            return BeanHelper.unwrapPipelineStatesNewAPI(pipelineStateJsons);
        } else {
            int toIndex = pipelineStateJsons.size() > 100 ? 100 : pipelineStateJsons.size();
            return BeanHelper.unwrapPipelineStatesNewAPI(pipelineStateJsons.subList(0, toIndex));
        }
    } catch (IOException e) {
        throw new PipelineStoreException(ContainerError.CONTAINER_0115, pipelineName, rev, e.toString(), e);
    }
}

From source file:com.wealdtech.jackson.ObjectMapperFactory.java

/**
 * Build an objectmapper from a given configuration.
 *
 * @param configuration//from   w w w  . ja v  a2s  .c  o m
 *          the objectmapper configuration
 * @return an objectmapper
 */
public ObjectMapper build(final ObjectMapperConfiguration configuration) {
    final ObjectMapper mapper = new ObjectMapper(configuration.getFactory().orNull());
    for (Module module : configuration.getModules()) {
        mapper.registerModule(module);
    }
    for (Map.Entry<JsonParser.Feature, Boolean> entry : configuration.getParserFeatures().entrySet()) {
        mapper.getFactory().configure(entry.getKey(), entry.getValue());
    }
    mapper.setInjectableValues(configuration.getInjectableValues());
    if (configuration.getPropertyNamingStrategy().isPresent()) {
        mapper.setPropertyNamingStrategy(configuration.getPropertyNamingStrategy().get());
    }
    if (configuration.getSerializationInclusion().isPresent()) {
        mapper.setSerializationInclusion(configuration.getSerializationInclusion().get());
    }

    return mapper;
}

From source file:com.anrisoftware.simplerest.oanda.rest.AbstractInstrumentHistory.java

private JsonParser createParser(ObjectMapper mapper, HttpEntity entity)
        throws IOException, JsonParseException, JsonMappingException {
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(entity.getContent());
    return parser;
}

From source file:org.apache.unomi.web.EventsCollectorServlet.java

private void doEvent(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Date timestamp = new Date();
    if (request.getParameter("timestamp") != null) {
        timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
    }/*from   w  ww.  j  a  va  2  s  . c o  m*/

    //        logger.debug(HttpUtils.dumpRequestInfo(request));

    HttpUtils.setupCORSHeaders(request, response);

    String sessionId = request.getParameter("sessionId");
    if (sessionId == null) {
        logger.error(
                "No sessionId found in incoming request, aborting processing. See debug level for more information");
        if (logger.isDebugEnabled()) {
            logger.debug("Request dump:" + HttpUtils.dumpRequestInfo(request));
        }
        return;
    }

    Session session = profileService.loadSession(sessionId, timestamp);
    if (session == null) {
        logger.error("No session found for sessionId={}, aborting request !", sessionId);
        return;
    }

    String profileIdCookieName = "context-profile-id";

    Profile sessionProfile = session.getProfile();
    Profile profile = null;
    if (sessionProfile.getItemId() != null) {
        // Reload up-to-date profile
        profile = profileService.load(sessionProfile.getItemId());
        if (profile == null || profile instanceof Persona) {
            logger.error("No valid profile found or persona found for profileId={}, aborting request !",
                    session.getProfileId());
            return;
        }
    } else {
        // Session uses anonymous profile, try to find profile from cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (profileIdCookieName.equals(cookie.getName())) {
                profile = profileService.load(cookie.getValue());
            }
        }
        if (profile == null) {
            logger.error("No valid profile found or persona found for profileId={}, aborting request !",
                    session.getProfileId());
            return;
        }
    }

    String payload = HttpUtils.getPayload(request);
    if (payload == null) {
        logger.error("No event payload found for request, aborting !");
        return;
    }

    ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
    JsonFactory factory = mapper.getFactory();
    EventsCollectorRequest events = null;
    try {
        events = mapper.readValue(factory.createParser(payload), EventsCollectorRequest.class);
    } catch (Exception e) {
        logger.error("Cannot read payload " + payload, e);
        return;
    }
    if (events == null || events.getEvents() == null) {
        logger.error("No events found in payload");
        return;
    }

    String thirdPartyId = eventService.authenticateThirdPartyServer(
            ((HttpServletRequest) request).getHeader("X-Unomi-Peer"), request.getRemoteAddr());

    int changes = 0;

    List<String> filteredEventTypes = privacyService.getFilteredEventTypes(profile.getItemId());

    for (Event event : events.getEvents()) {
        if (event.getEventType() != null) {
            Event eventToSend = new Event(event.getEventType(), session, profile, event.getScope(),
                    event.getSource(), event.getTarget(), event.getProperties(), timestamp);
            if (sessionProfile.isAnonymousProfile()) {
                // Do not keep track of profile in event
                eventToSend.setProfileId(null);
            }

            if (!eventService.isEventAllowed(event, thirdPartyId)) {
                logger.debug("Event is not allowed : {}", event.getEventType());
                continue;
            }
            if (filteredEventTypes != null && filteredEventTypes.contains(event.getEventType())) {
                logger.debug("Profile is filtering event type {}", event.getEventType());
                continue;
            }

            eventToSend.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
            eventToSend.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
            logger.debug("Received event " + event.getEventType() + " for profile=" + sessionProfile.getItemId()
                    + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp="
                    + timestamp);
            int eventChanged = eventService.send(eventToSend);
            //if the event execution changes the profile
            if ((eventChanged & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) {
                profile = eventToSend.getProfile();
            }
            changes |= eventChanged;
        }
    }

    if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) {
        profileService.save(profile);
    }
    if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED) {
        profileService.saveSession(session);
    }

    PrintWriter responseWriter = response.getWriter();
    responseWriter.append("{\"updated\":" + changes + "}");
    responseWriter.flush();
}

From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java

@Test
public void writeJSONViaLowerlevelLibs() throws IOException {
    final StringWriter writer = new StringWriter();

    final ObjectMapper mapper = new ObjectMapper();

    final JsonGenerator jgen = mapper.getFactory().createGenerator(writer);

    jgen.writeStartObject();

    jgen.writeStringField("odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");

    jgen.writeStringField("Name@odata.type", "Edm.String");
    jgen.writeStringField("Name", "A name");

    jgen.writeStringField("CustomerId@odata.type", "Edm.Int32");
    jgen.writeNumberField("CustomerId", 0);

    jgen.writeArrayFieldStart("BackupContactInfo");

    jgen.writeStartObject();/*from  w w  w .j a  v a  2s . co m*/

    jgen.writeArrayFieldStart("AlternativeNames");
    jgen.writeString("myname");
    jgen.writeEndArray();

    jgen.writeArrayFieldStart("EmailBag");
    jgen.writeString("myname@mydomain.com");
    jgen.writeEndArray();

    jgen.writeObjectFieldStart("ContactAlias");
    jgen.writeStringField("odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    jgen.writeArrayFieldStart("AlternativeNames");
    jgen.writeString("myAlternativeName");
    jgen.writeEndArray();
    jgen.writeEndObject();

    jgen.writeEndObject();

    jgen.writeEndArray();

    jgen.writeEndObject();

    jgen.flush();

    assertFalse(writer.toString().isEmpty());
}

From source file:com.modelsolv.kaboom.serializer.SerializerTest.java

private JsonNode parseJson(String json) {
    try {//from w  ww .j  a  v  a 2s  .c  o m
        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(json);
        return mapper.readTree(jp);
    } catch (Exception e) {
        throw new RuntimeException("Failed to parse JSON returned from serializer.", e);
    }
}

From source file:no.ssb.jsonstat.v2.deser.DatasetDeserializerTest.java

@Test
public void testDimensionOrder() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    mapper.registerModule(new JsonStatModule());

    URL resource = getResource(getClass(), "dimOrder.json");

    JsonParser jsonParser = mapper.getFactory().createParser(resource.openStream());
    jsonParser.nextValue();//from w  w  w. j ava2s.  com

    DatasetBuildable deserialize = ds.deserialize(jsonParser, mapper.getDeserializationContext());

    assertThat(deserialize.build().getDimension().keySet()).containsExactly("A", "B", "C");

}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public Registration requestRegistrationAS() throws IOException {
    String clientName = "opPostmanTestRS"; // CLIENT_NAME_PREFIX +
    // System.currentTimeMillis();
    String clientCredentials = "client_credentials";
    String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\""
            + clientCredentials + "\"], \"id_token_signed_response_alg\":\"" + "HS256" + "\"}";

    // Registration
    URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AS);

    HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection();
    httpConRegistration.setDoOutput(true);
    httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConRegistration.setRequestProperty("Content-Type", "application/json");
    httpConRegistration.setRequestProperty("Accept", "application/json");
    httpConRegistration.setRequestMethod("POST");

    OutputStream outRegistration = httpConRegistration.getOutputStream();
    outRegistration.write(requestBodyRegistration.getBytes());
    outRegistration.close();/*ww w  .j  av  a 2s.  c  o m*/

    int responseCodeRegistration = httpConRegistration.getResponseCode();
    log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration);

    if (responseCodeRegistration == 201) {
        // everything ok
        InputStream isR = httpConRegistration.getInputStream();
        byte[] bisR = getBytesFromInputStream(isR);
        String jsonResponseRegistration = new String(bisR);
        log.info(jsonResponseRegistration);

        // extract the value of client_id (this value is called <c_id>in
        // the following) and the value of client_secret (called
        // <c_secret> in the following) from the JSON response

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisR);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode c_id = actualObj.get("client_id");
        JsonNode c_secret = actualObj.get("client_secret");

        if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null
                || c_secret.getNodeType() != JsonNodeType.STRING) {
            log.error("client_id: " + c_id);
            log.error("client_secret: " + c_secret);
        } else {
            // ok so far
            // Store <c_id> and <c_secret> for use during the token
            // acquisition
            log.info("client_id: " + c_id);
            log.info("client_secret: " + c_secret);

            return new Registration(c_id.textValue(), c_secret.textValue());
        }

    } else {
        // error
        InputStream error = httpConRegistration.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }
    httpConRegistration.disconnect();

    return null;
}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public Registration requestRegistrationAM() throws IOException {

    Registration registration = null;/* w ww .  j  av a  2 s  .  co  m*/

    String clientName = CLIENT_NAME_PREFIX + System.currentTimeMillis();
    String clientCredentials = "client_credentials";
    String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\""
            + clientCredentials + "\"]}";

    // Registration
    URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AM);

    HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection();
    httpConRegistration.setDoOutput(true);
    httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConRegistration.setRequestProperty("Content-Type", "application/json");
    httpConRegistration.setRequestProperty("Accept", "application/json");
    httpConRegistration.setRequestMethod("POST");

    OutputStream outRegistration = httpConRegistration.getOutputStream();
    outRegistration.write(requestBodyRegistration.getBytes());
    outRegistration.close();

    int responseCodeRegistration = httpConRegistration.getResponseCode();
    log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration);

    if (responseCodeRegistration == 201) {
        // everything ok
        InputStream isR = httpConRegistration.getInputStream();
        byte[] bisR = getBytesFromInputStream(isR);
        String jsonResponseRegistration = new String(bisR);
        log.info(jsonResponseRegistration);

        // extract the value of client_id (this value is called <c_id>in
        // the following) and the value of client_secret (called
        // <c_secret> in the following) from the JSON response

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisR);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode c_id = actualObj.get("client_id");
        JsonNode c_secret = actualObj.get("client_secret");

        if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null
                || c_secret.getNodeType() != JsonNodeType.STRING) {
            log.error("client_id: " + c_id);
            log.error("client_secret: " + c_secret);
        } else {
            // ok so far
            // Store <c_id> and <c_secret> for use during the token
            // acquisition
            log.info("client_id: " + c_id);
            log.info("client_secret: " + c_secret);

            registration = new Registration(c_id.textValue(), c_secret.textValue());
        }

    } else {
        // error
        InputStream error = httpConRegistration.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }
    httpConRegistration.disconnect();

    return registration;
}