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

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

Introduction

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

Prototype

public JsonFactory() 

Source Link

Document

Default constructor used to create factory instances.

Usage

From source file:com.loopj.android.http.sample.Http401AuthSample.java

@Override
public ResponseHandlerInterface getResponseHandler() {
    return new BaseJsonHttpResponseHandler<SampleJSON>() {

        @Override//from   w  ww. j av a2  s  .com
        public void onStart() {
            clearOutputs();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SampleJSON response) {
            debugHeaders(LOG_TAG, headers);
            debugStatusCode(LOG_TAG, statusCode);
            if (response != null) {
                debugResponse(LOG_TAG, rawJsonResponse);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData,
                SampleJSON errorResponse) {
            debugHeaders(LOG_TAG, headers);
            debugStatusCode(LOG_TAG, statusCode);
            debugThrowable(LOG_TAG, throwable);

            // Ask the user for credentials if required by the server.
            if (statusCode == 401) {
                String realm = "Protected Page";
                String authType = null;

                // Cycle through the headers and look for the WWW-Authenticate header.
                for (Header header : headers) {
                    String headerName = header.getName();
                    if (HEADER_WWW_AUTHENTICATE.equalsIgnoreCase(headerName)) {
                        String headerValue = header.getValue().trim();
                        String headerValueLowerCase = headerValue.toLowerCase(Locale.US);

                        // Get the type of auth requested.
                        int charPos = headerValueLowerCase.indexOf(' ');
                        if (0 < charPos) {
                            authType = headerValueLowerCase.substring(0, charPos);

                            // The second part should begin with a "realm=" prefix.
                            if (headerValueLowerCase.substring(1 + charPos).startsWith(HEADER_REALM_PREFIX)) {
                                // The new realm value, including any possible wrapping quotation.
                                realm = headerValue.substring(1 + charPos + HEADER_REALM_PREFIX.length());

                                // If realm starts with a quote, remove surrounding quotes.
                                if (realm.charAt(0) == '"' || realm.charAt(0) == '\'') {
                                    realm = realm.substring(1, realm.length() - 1);
                                }
                            }
                        }
                    }
                }

                // We will support basic auth in this sample.
                if (authType != null && HEADER_BASIC.equals(authType)) {
                    // Show a dialog for the user and request user/pass.
                    Log.d(LOG_TAG, HEADER_REALM_PREFIX + realm);

                    // Present the dialog.
                    postRunnable(new DialogRunnable(realm));
                }
            }
        }

        @Override
        protected SampleJSON parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
            return new ObjectMapper().readValues(new JsonFactory().createParser(rawJsonData), SampleJSON.class)
                    .next();
        }
    };
}

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  . j a  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:org.lobid.lodmill.JsonDecoder.java

private JsonToken handleJsonp(final String jsonp) throws IOException, JsonParseException {
    JsonToken currentToken;/*  w w  w .j a va 2  s.  com*/
    final String callbackString = jsonp.substring(0, jsonp.indexOf(JsonDecoder.JSON_START_CHAR) - 1);
    final String json = jsonp.substring(jsonp.indexOf(JsonDecoder.JSON_START_CHAR), jsonp.length() - 1);
    this.jsonParser = new JsonFactory().createParser(json);
    LOG.debug("key=" + JsonDecoder.JSON_CALLBACK + " value=" + callbackString);
    getReceiver().startRecord("");
    STARTED = true;
    JSONP = true;
    getReceiver().literal(JsonDecoder.JSON_CALLBACK, callbackString);
    LOG.debug("Json=" + json);
    currentToken = this.jsonParser.nextToken();
    return currentToken;
}

From source file:org.springframework.social.betaseries.api.impl.BetaSerieErrorHandler.java

/**
 * Extract error details from response./*from   w ww  .  ja v  a 2  s.  c  om*/
 * 
 * @param response
 *            the response
 * @return the map
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@SuppressWarnings("unchecked")
private Map<String, Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    String json = readFully(response.getBody());

    System.out.println(json);

    if (logger.isDebugEnabled()) {
        logger.debug("Error from BetaSeries: " + json);
    }

    try {
        Map<String, Object> responseMap = mapper.<Map<String, Object>>readValue(json,
                new TypeReference<Map<String, Object>>() {
                });

        // all beta series response contain a json errors object, even if
        // there are no error,
        // only checking if the object contain an "errors" key is not enough
        // to consider an error occur
        if (responseMap.containsKey("errors")) {
            Object errorMap = responseMap.get("errors");
            Map<String, Object> errors = new HashMap<String, Object>();

            if (errorMap instanceof List) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) errorMap;
                if (list.size() > 0) {
                    errors = list.get(0);
                }
            } else if (errorMap instanceof Map) {
                errors = (Map<String, Object>) errorMap;
            }

            // checking if the errors Map size is not empty its the best
            // way to make sure an error occur
            if (errors != null) {
                return errors;
            }
        }
    } catch (JsonParseException e) {
        return null;
    }

    return null;
}

From source file:hu.fnf.devel.wishbox.ui.MainPage.java

private Container getItemContiner() {
    IndexedContainer container = new IndexedContainer();
    container.addContainerProperty("First", String.class, "1st");
    container.addContainerProperty("Second", String.class, "2nd");
    //        WebClient client = WebClient.create("http://195.228.45.136:8181/cxf/test");
    //        client = client.accept("application/json")
    //                .type("application/json")
    //                .path("/say/list");
    //        TestResp testResp = client.get(TestResp.class);

    if (getSession().getAttribute("state") == null) {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        getSession().setAttribute("user", user);

        URI uri = null;/*  w w w  . jav  a  2s  . c  om*/
        try {
            uri = new URI(("http://jenna.fnf.hu/gateway/persistence/user/" + user.getUserId()));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        String plainCreds = "API_KEY:API_PASS";

        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Creds);
        HttpEntity<String> request = new HttpEntity<String>(headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, request, String.class);

        JsonFactory factory = new JsonFactory();

        ObjectMapper m = new ObjectMapper(factory);
        JsonNode rootNode = null;
        try {
            rootNode = m.readTree(response.getBody());
        } catch (IOException e) {
            e.printStackTrace();
        }

        Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
        while (fieldsIterator.hasNext()) {

            Map.Entry<String, JsonNode> field = fieldsIterator.next();
            if (!field.getKey().startsWith("_")) {
                getSession().setAttribute(field.getKey(), field.getValue().asText());
            } else {

            }
            System.out.println("Key: " + field.getKey() + ":\t" + field.getValue());
        }
        getSession().setAttribute("state", "loaded");
    }
    com.vaadin.data.Item item = container.addItem(((User) getSession().getAttribute("user")).getNickname());
    item.getItemProperty("First").setValue(getSession().getAttribute("firstName").toString());
    item.getItemProperty("Second").setValue(getSession().getAttribute("lastName").toString());

    return container;
}

From source file:com.pressassociation.pr.filter.json.jackson.JacksonMatcherFilter.java

private void processFirstPass(Node parentNode, Object pojo, SerializerProvider provider, PropertyWriter writer,
        JsonGenerator generator) throws Exception {
    State state = this.state.get();
    Leaf leaf = Leaf.copyOf(state.propertyPath);

    // if this property _can_ contribute towards the path leading to a matching leaf then we have to check
    boolean matches = matcher.matches(leaf);
    if (matches || matcher.matchesParent(leaf)) {
        if (parentNode.isRoot()) {
            // make sure we don't actually write anything to the output, only replace if we are the root node, it will
            // be passed to other nodes as needed via recursive calls
            generator = new JsonFactory().createGenerator(CharStreams.nullWriter());
        }/*from   w ww. j  a  v  a 2 s .  c  o m*/

        // prepare a node for this property so child branches can add to it as needed
        state.currentNode = new Node(parentNode, writer.getName());
        writer.serializeAsField(pojo, generator, provider);

        // check the results of processing the children
        if (state.currentNode.isEmpty()) {
            // either we don't have any children or none of them are matching leaves.
            // in any case
            if (matches) {
                // it turns out we match anyway so add this node
                parentNode.addChild(state.currentNode);
            }
        } else {
            // child leafs match so we need to include this node as a parent of them
            parentNode.addChild(state.currentNode);
        }
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java

License:asdf

@Test
public void itAppliesConsistentHashingToRequestsForCoverageZone() throws Exception {
    CloseableHttpResponse response = null;

    try {/*w ww  .  ja va 2  s .c om*/
        String requestPath = URLEncoder.encode("/some/path/thing", "UTF-8");
        HttpGet httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/cache/coveragezone?ip=" + ipAddressInCoverageZone
                        + "&deliveryServiceId=" + deliveryServiceId + "&requestPath=" + requestPath);

        response = closeableHttpClient.execute(httpGet);

        assertThat("Expected to find " + ipAddressInCoverageZone
                + " in coverage zone using delivery service id " + deliveryServiceId,
                response.getStatusLine().getStatusCode(), equalTo(200));

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));

        String cacheId = cacheNode.get("id").asText();
        assertThat(cacheId, not(equalTo("")));

        response.close();

        response = closeableHttpClient.execute(httpGet);
        cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(cacheNode.get("id").asText(), equalTo(cacheId));

        response.close();

        requestPath = URLEncoder.encode("/another/different/path", "UTF-8");
        httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/cache/coveragezone?ip=" + ipAddressInCoverageZone
                        + "&deliveryServiceId=" + deliveryServiceId + "&requestPath=" + requestPath);

        response = closeableHttpClient.execute(httpGet);
        cacheNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(cacheNode.get("id").asText(), not(equalTo(cacheId)));
        assertThat(cacheNode.get("id").asText(), not(equalTo("")));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:de.odysseus.staxon.json.stream.jackson.JacksonStreamSourceTest.java

@Test
public void testString() throws IOException {
    StringReader reader = new StringReader("[\"\",\"abc\",\"\\b\\f\\n\\r\\t\",\"\\\"\",\"\\\\\",\"\\u001F\"]");
    JacksonStreamSource source = new JacksonStreamSource(new JsonFactory().createParser(reader));

    Assert.assertEquals(JsonStreamToken.START_ARRAY, source.peek());
    source.startArray();// w w  w .  j a  v a2s .co  m

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    Assert.assertEquals("", source.value().text);

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    Assert.assertEquals("abc", source.value().text);

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    Assert.assertEquals("\b\f\n\r\t", source.value().text);

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    Assert.assertEquals("\"", source.value().text);

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    Assert.assertEquals("\\", source.value().text);

    Assert.assertEquals(JsonStreamToken.VALUE, source.peek());
    Assert.assertEquals("\u001F", source.value().text);

    Assert.assertEquals(JsonStreamToken.END_ARRAY, source.peek());
    source.endArray();

    Assert.assertEquals(JsonStreamToken.NONE, source.peek());
    source.close();
}

From source file:msearch.io.MSFilmlisteLesen.java

private boolean filmlisteJsonEinlesen(File vonDatei, ListeFilme listeFilme) {
    boolean ret = false;
    BZip2CompressorInputStream bZip2CompressorInputStream;
    JsonFactory jsonF = new JsonFactory();
    JsonParser jp = null;/*from  w  w w.  j av  a 2 s. c  o  m*/
    JsonToken jsonToken;
    String sender = "", thema = "";
    try {
        // ##########################################################
        // und jetzt die Liste einlesen, URL kann es jetzt schon nicht mehr sein!
        if (!vonDatei.exists()) {
            MSLog.fehlerMeldung(702030698, MSLog.FEHLER_ART_PROG, "MSearchIoXmlFilmlisteLesen.filmlisteLesen",
                    "Datei existiert nicht: " + vonDatei.getName());
            return false;
        }
        if (vonDatei.getName().endsWith(MSConst.FORMAT_XZ)) {
            XZInputStream xZInputStream = new XZInputStream(new FileInputStream(vonDatei));
            jp = jsonF.createParser(new InputStreamReader(xZInputStream, MSConst.KODIERUNG_UTF));
        } else if (vonDatei.getName().endsWith(MSConst.FORMAT_BZ2)) {
            bZip2CompressorInputStream = new BZip2CompressorInputStream(new FileInputStream(vonDatei));
            jp = jsonF.createParser(new InputStreamReader(bZip2CompressorInputStream, MSConst.KODIERUNG_UTF));
        } else if (vonDatei.getName().endsWith(MSConst.FORMAT_ZIP)) {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(vonDatei));
            zipInputStream.getNextEntry();
            jp = jsonF.createParser(new InputStreamReader(zipInputStream, MSConst.KODIERUNG_UTF));
        } else {
            jp = jsonF.createParser(vonDatei); // geht so am schnellsten
        }
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }
        while ((jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                for (int k = 0; k < ListeFilme.MAX_ELEM; ++k) {
                    listeFilme.metaDaten[k] = jp.nextTextValue();
                }
                break;
            }
        }
        while ((jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                // sind nur die Feldbeschreibungen, brauch mer nicht
                jp.nextToken();
                break;
            }
        }
        while ((jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                DatenFilm datenFilm = new DatenFilm();
                for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                    datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] = jp.nextTextValue();
                    /// fr die Entwicklungszeit
                    if (datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] == null) {
                        datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] = "";
                    }
                }
                if (datenFilm.arr[DatenFilm.FILM_SENDER_NR].equals("")) {
                    datenFilm.arr[DatenFilm.FILM_SENDER_NR] = sender;
                } else {
                    sender = datenFilm.arr[DatenFilm.FILM_SENDER_NR];
                }
                if (datenFilm.arr[DatenFilm.FILM_THEMA_NR].equals("")) {
                    datenFilm.arr[DatenFilm.FILM_THEMA_NR] = thema;
                } else {
                    thema = datenFilm.arr[DatenFilm.FILM_THEMA_NR];
                }
                listeFilme.importFilmliste(datenFilm);
            }
        }
        jp.close();
        ret = true;
    } catch (Exception ex) {
        MSLog.fehlerMeldung(468956200, MSLog.FEHLER_ART_PROG, "MSearchIoXmlFilmlisteLesen.filmlisteLesen", ex,
                "von: " + vonDatei.getName());
    }
    return ret;
}

From source file:com.parworks.androidlibrary.ar.ARSites.java

private List<AugmentedData> getAugmentedImageGroupResult(final List<String> sites, String imageId) {
    Log.d("PARWORKS ANDROID LIBRARY", "getAugmentedImageGroupResult");
    Map<String, String> params = new HashMap<String, String>();
    params.put("imgId", imageId);
    HttpUtils httpUtils = new HttpUtils(mApiKey, mTime, mSignature);
    HttpResponse serverResponse = httpUtils.doGetWithSiteArray(
            HttpUtils.PARWORKS_API_BASE_URL + HttpUtils.AUGMENT_IMAGE_GROUP_RESULT_PATH, sites, params);
    HttpUtils.handleStatusCode(serverResponse.getStatusLine().getStatusCode());
    List<AugmentImageResultResponse> augmentedImageResults = new ArrayList<AugmentImageResultResponse>();
    try {/*from  w w  w  . ja va  2 s .  com*/
        JsonFactory f = new JsonFactory();
        JsonParser jp = f.createJsonParser(ARResponseUtils.convertHttpResponseToString(serverResponse));
        // advance stream to START_ARRAY first:
        jp.nextToken();
        // and then each time, advance to opening START_OBJECT
        while (jp.nextToken() == JsonToken.START_OBJECT) {
            Log.d(TAG, "Parsing json token");
            ARResponseHandler responseHandler = new ARResponseHandlerImpl();
            AugmentImageResultResponse augmentImageResult = responseHandler.handleResponse(jp,
                    AugmentImageResultResponse.class);
            augmentedImageResults.add(augmentImageResult);
        }
    } catch (Exception e) {
        throw new ARException("Failed to parse json.", e);
    }

    List<AugmentedData> allAugmentedData = new ArrayList<AugmentedData>();
    for (AugmentImageResultResponse response : augmentedImageResults) {
        allAugmentedData.add(convertAugmentResultResponse(imageId, response));
    }
    return allAugmentedData;
}