Example usage for com.fasterxml.jackson.core JsonFactory createParser

List of usage examples for com.fasterxml.jackson.core JsonFactory createParser

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory createParser.

Prototype

public JsonParser createParser(String content) throws IOException, JsonParseException 

Source Link

Document

Method for constructing parser for parsing contents of given String.

Usage

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();//from   w  w w  .j a v  a2s.c om

    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:com.apteligent.ApteligentJavaClient.java

/**
 * @param appID appId (string, optional): The app to retrieve data about,
 * @param metricType The metric to retrieve
 * @param duration can only be 1440 (24 hours) or 43200 (1 month)
 * @return Error object//from  ww w  . ja  v a  2 s.co m
 */
public CrashSummary getErrorGraph(String appID, CrashSummary.MetricType metricType, int duration) {

    // { "params": {"duration": 43200, "graph": "crashes", "appId": "4f2cc6dfb09315234e000639"}}
    //String responseStr = "{\"data\": {\"start\": \"2014-11-13T00:00:00\", \"interval\": 86400, \"end\": \"2014-12-13T00:00:00\", \"series\": [{\"points\": [0, 3, 2, 0, 2, 3, 2, 3, 0, 6, 0, 0, 0, 1, 0, 0, 6, 2, 0, 1, 0, 0, 4, 1, 0, 0, 1, 2, 0, 0], \"name\": \"crashes\"}]}, \"params\": {\"duration\": 43200, \"graph\": \"crashes\", \"appId\": \"4f2cc6dfb09315234e000639\"}}";

    String params = "{ \"params\": " + "{\"duration\": " + duration + "," + " \"graph\": \""
            + metricType.toString() + "\"," + " \"appId\": \"" + appID + "\"}" + "}";

    System.out.println(params);
    CrashSummary crashSummary = null;
    try {
        HttpsURLConnection conn = sendPostRequest(API_ERROR_GRAPH, params);
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        TreeNode node = mapper.readTree(jp);
        crashSummary = mapper.treeToValue(node.get("data"), CrashSummary.class);
        if (crashSummary != null) {
            crashSummary.setParams(appID, metricType, duration);
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return crashSummary;
}

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

public Registration requestRegistrationAM() throws IOException {

    Registration registration = null;/*from www. j  a  v a 2  s. com*/

    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;
}

From source file:com.apteligent.ApteligentJavaClient.java

/*********************************************************************************************************************/

private Token auth(String email, String password) throws IOException {
    String urlParameters = "grant_type=password&username=" + email + "&password=" + password;

    URL obj = new URL(API_TOKEN);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);/*  ww  w  .j  av  a 2 s.c  om*/
    conn.setDoInput(true);

    //add request header
    String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes()));
    conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth));
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    conn.setRequestMethod("POST");

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    // read token
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(conn.getInputStream());
    ObjectMapper mapper = getObjectMapper();
    Token token = mapper.readValue(jp, Token.class);

    return token;
}

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 www  .  j  av  a2s.  com

    //        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.github.jonpeterson.jackson.module.interceptor.JsonInterceptingSerializer.java

@Override
public void serialize(T value, JsonGenerator generator, SerializerProvider provider) throws IOException {
    // serialize the value into a byte array buffer then parse it back out into a JsonNode tree
    // TODO: find a better way to convert the value into a tree
    JsonFactory factory = generator.getCodec().getFactory();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096);
    JsonGenerator bufferGenerator = factory.createGenerator(buffer);
    try {//w  w w.  j  a v a  2 s  .c  om
        delegate.serialize(value, bufferGenerator, provider);
    } finally {
        bufferGenerator.close();
    }
    JsonNode jsonNode = factory.createParser(buffer.toByteArray()).readValueAsTree();

    // execute interceptors on node
    for (JsonInterceptor interceptor : interceptors)
        jsonNode = interceptor.intercept(jsonNode, jsonNodeFactory);

    // write node
    generator.writeTree(jsonNode);
}

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

public String requestASToken(Registration registration, String[] adds) throws IOException {
    String asToken = null;/*  w  ww  . j a  va 2  s  . c  o m*/

    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    //
    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    // Request
    // POST /iam-services/0.1/oidc/am/token HTTP/1.1
    URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION);

    HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection();
    httpConTokenAcquisition.setDoOutput(true);
    httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpConTokenAcquisition.setRequestProperty("Accept", "application/json");
    // httpConTokenAcquisition.setRequestProperty("Authorization",
    // "Basic Base64(<c_id>:<c_secret>");
    String auth = registration.c_id + ":" + registration.c_secret;
    String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes()));
    httpConTokenAcquisition.setRequestProperty("Authorization", authb);
    httpConTokenAcquisition.setRequestMethod("POST");

    String requestBodyTokenAcquisition = "grant_type=client_credentials";
    if (adds == null || adds.length == 0) {
        // no additions
    } else {
        if (adds.length % 2 == 0) {
            for (int i = 0; i < (adds.length - 1); i += 2) {
                requestBodyTokenAcquisition += "&";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8");
                requestBodyTokenAcquisition += "=";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8");
            }
        } else {
            log.warn(
                    "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds));
        }
    }

    OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream();
    outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes());
    outTokenAcquisition.close();

    int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode();
    log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": "
            + responseCodeoutTokenAcquisition);

    if (responseCodeoutTokenAcquisition == 200) {
        // everything ok
        InputStream isTA = httpConTokenAcquisition.getInputStream();
        byte[] bisTA = getBytesFromInputStream(isTA);
        String jsonResponseTA = new String(bisTA);
        log.info(jsonResponseTA);

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

        JsonNode access_token = actualObj.get("access_token");
        if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) {
            log.error("access_token: " + access_token);
        } else {
            // ok so far
            // access_token provides a JWT structure
            // see Understanding JWT
            // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html

            log.info("access_token: " + access_token);
            // http://jwt.io/

            // TODO verify signature (e.g., use Jose4J)

            // Note: currently we assume signature is fine.. we just fetch
            // "as_token"
            String[] decAT = access_token.textValue().split("\\.");
            if (decAT == null || decAT.length != 3) {
                log.error("Cannot build JWT tripple structure for " + access_token);
            } else {
                assert (decAT.length == 3);
                // JWT structure
                // decAT[0]; // header
                // decAT[1]; // payload
                // decAT[2]; // signature
                String decAT1 = new String(Base64.getDecoder().decode(decAT[1]));
                JsonParser jpas = factory.createParser(decAT1);
                JsonNode payload = mapper.readTree(jpas);
                JsonNode as_token = payload.get("as_token");
                if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) {
                    log.error("as_token: " + as_token);
                } else {
                    log.info("as_token: " + as_token);
                    asToken = as_token.textValue();
                }
            }
        }

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

    httpConTokenAcquisition.disconnect();

    return asToken;
}

From source file:com.cedarsoft.serialization.jackson.AbstractJacksonSerializer.java

/**
 * This method creates the parser. This method may be overridden to create a FilteringJsonParser or something like that
 * @param jsonFactory the json factory/*w ww .j  a v  a  2s . c  o  m*/
 * @param in the input stream
 * @return the created json parser
 * @throws java.io.IOException if there is an io problem
 */
@Nonnull
protected JsonParser createJsonParser(@Nonnull JsonFactory jsonFactory, @Nonnull InputStream in)
        throws IOException {
    return jsonFactory.createParser(in);
}

From source file:com.arpnetworking.jackson.BuilderDeserializerTest.java

@Test
public void testWithoutNull() throws IOException {
    final TestFooBeanInterface expectedBean = TestFooBeanImpl.Builder.newInstance()
            .setFieldString(UUID.randomUUID().toString()).setFieldBoolean(Boolean.TRUE)
            .setFieldPrimitive(RANDOM_GENERATOR.nextInt()).setFieldBooleanPrimitive(false).build();

    final String jsonString = "{\"fieldString\":\"" + expectedBean.getFieldString() + "\""
            + ", \"fieldBoolean\":" + expectedBean.isFieldBoolean() + ", \"fieldPrimitive\":"
            + expectedBean.getFieldPrimitive() + ", \"fieldBooleanPrimitive\":"
            + expectedBean.isFieldBooleanPrimitive() + "}";

    final JsonFactory jsonFactory = new JsonFactory(new ObjectMapper());
    try (final JsonParser jsonParser = jsonFactory.createParser(jsonString)) {
        final JsonDeserializer<? extends TestFooBeanInterface> deserializer = BuilderDeserializer
                .of(TestFooBeanImpl.Builder.class);
        final TestFooBeanInterface actualBean = deserializer.deserialize(jsonParser, null);
        Assert.assertEquals(expectedBean, actualBean);
    }//from ww w.j a  v  a2 s.com
}

From source file:com.arpnetworking.jackson.BuilderDeserializerTest.java

@Test
public void testWithNull() throws IOException {
    final TestFooBeanInterface expectedBean = TestFooBeanImpl.Builder.newInstance()
            .setFieldString(UUID.randomUUID().toString()).setFieldBoolean(Boolean.TRUE)
            .setFieldPrimitive(RANDOM_GENERATOR.nextInt()).setFieldBooleanPrimitive(false).setFieldNull(null)
            .build();//from w  ww.jav  a 2  s .  c  o  m

    final String jsonString = "{\"fieldString\":\"" + expectedBean.getFieldString() + "\""
            + ", \"fieldBoolean\":" + expectedBean.isFieldBoolean() + ", \"fieldPrimitive\":"
            + expectedBean.getFieldPrimitive() + ", \"fieldBooleanPrimitive\":"
            + expectedBean.isFieldBooleanPrimitive() + ", \"fieldNull\":" + expectedBean.getFieldNull() + "}";

    final JsonFactory jsonFactory = new JsonFactory(new ObjectMapper());
    try (final JsonParser jsonParser = jsonFactory.createParser(jsonString)) {
        final JsonDeserializer<? extends TestFooBeanInterface> deserializer = BuilderDeserializer
                .of(TestFooBeanImpl.Builder.class);
        final TestFooBeanInterface actualBean = deserializer.deserialize(jsonParser, null);
        Assert.assertEquals(expectedBean, actualBean);
    }
}