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:org.springframework.social.mixcloud.api.impl.MixcloudErrorHandler.java

@SuppressWarnings("rawtypes")
private SocialException extractExceptionFromResponse(ClientHttpResponse response) throws IOException {

    ObjectMapper mapper = new ObjectMapper(new JsonFactory());

    try {//from w  ww  .j  a v a2  s .  com
        String json = readFully(response.getBody());
        Map<String, String> responseMap = mapper.<Map<String, String>>readValue(json,
                new TypeReference<Map<String, Object>>() {
                });
        if (responseMap.containsKey("error")) {
            Object error = responseMap.get("error");
            if (error instanceof String) {
                return new UncategorizedApiException("mixcloud", responseMap.get("error"),
                        new RuntimeException(responseMap.get("error")));
            } else if (error instanceof Map) {
                Map errorMap = (Map) error;
                String type = (String) ((Map) error).get("type");
                if ("OAuthException".equals(type)) {
                    return new InvalidAuthorizationException("mixcloud", (String) errorMap.get("message"));
                }
                if ("ResourceNotFoundException".equals(type)) {
                    return new ResourceNotFoundException("mixcloud", (String) errorMap.get("message"));
                }
                return new UncategorizedApiException("mixcloud", responseMap.get("error"),
                        new RuntimeException(responseMap.get("error")));
            } else {
                return null;
            }
        } else {
            return null;
        }
    } catch (JsonParseException e) {
        return null;
    }
}

From source file:com.joliciel.jochre.search.highlight.HighlightManagerImpl.java

@Override
public void findSnippets(Highlighter highlighter, Set<Integer> docIds, Set<String> fields, Writer out) {
    try {//from w w w  .  j  av a2s . c  o m
        Map<Integer, Set<HighlightTerm>> termMap = highlighter.highlight(docIds, fields);
        Map<Integer, List<Snippet>> snippetMap = this.findSnippets(docIds, fields, termMap,
                this.getSnippetCount(), this.getSnippetSize());

        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator jsonGen = jsonFactory.createGenerator(out);

        jsonGen.writeStartObject();

        for (int docId : docIds) {
            Document doc = indexSearcher.doc(docId);
            jsonGen.writeObjectFieldStart(doc.get("id"));
            jsonGen.writeStringField("path", doc.get("path"));
            jsonGen.writeNumberField("docId", docId);

            jsonGen.writeArrayFieldStart("snippets");
            for (Snippet snippet : snippetMap.get(docId)) {
                snippet.toJson(jsonGen, df);
            }
            jsonGen.writeEndArray();

            if (includeText) {
                jsonGen.writeArrayFieldStart("snippetText");
                for (Snippet snippet : snippetMap.get(docId)) {
                    jsonGen.writeStartObject();
                    jsonGen.writeStringField("snippet", this.displaySnippet(docId, snippet));
                    jsonGen.writeEndObject();
                }
                jsonGen.writeEndArray();
            }

            if (includeGraphics) {
                jsonGen.writeArrayFieldStart("snippetGraphics");
                for (Snippet snippet : snippetMap.get(docId)) {
                    jsonGen.writeStartObject();
                    ImageSnippet imageSnippet = this.getImageSnippet(snippet);
                    jsonGen.writeNumberField("left", imageSnippet.getRectangle().getLeft());
                    jsonGen.writeNumberField("top", imageSnippet.getRectangle().getTop());
                    jsonGen.writeNumberField("right", imageSnippet.getRectangle().getRight());
                    jsonGen.writeNumberField("bottom", imageSnippet.getRectangle().getBottom());

                    jsonGen.writeArrayFieldStart("highlights");
                    for (Rectangle highlight : imageSnippet.getHighlights()) {
                        jsonGen.writeStartObject();
                        jsonGen.writeNumberField("left", highlight.getLeft());
                        jsonGen.writeNumberField("top", highlight.getTop());
                        jsonGen.writeNumberField("right", highlight.getRight());
                        jsonGen.writeNumberField("bottom", highlight.getBottom());
                        jsonGen.writeEndObject();
                    }
                    jsonGen.writeEndArray();
                    jsonGen.writeEndObject();
                }
                jsonGen.writeEndArray();
            }
            jsonGen.writeEndObject();
        } // next doc

        jsonGen.writeEndObject();
        jsonGen.flush();
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:org.springframework.social.cloudplaylists.api.impl.CloudPlaylistsErrorHandler.java

@SuppressWarnings("rawtypes")
private Map extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {

    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    try {//from  w  ww .j a va  2  s  .  c  o m
        String json = readFully(response.getBody());
        HashMap errorDetails = mapper.readValue(json, HashMap.class);
        return errorDetails;
    } catch (JsonParseException e) {
        return null;
    }
}

From source file:com.ryan.ryanreader.jsonwrap.JsonValue.java

/**
 * Begins parsing a JSON stream into a tree structure. The JsonValue object
 * created contains the value at the root of the tree.
 * //from  w ww.  j  a v  a 2  s .c  o m
 * This constructor will block until the first JSON token is received. To
 * continue building the tree, the "build" method (inherited from
 * JsonBuffered) must be called in another thread.
 * 
 * @param source
 *         The source of incoming JSON data.
 * @throws java.io.IOException
 */
public JsonValue(final File source) throws IOException {
    this(new JsonFactory().createParser(source));
}

From source file:org.kiji.rest.representations.KijiRestEntityId.java

/**
 * Create a list of KijiRestEntityIds from a string input, which can be a json array of valid
 * entity id strings and/or valid hbase row keys.
 * This method is used for entity ids specified from the URL.
 *
 * @param entityIdListString string of a json array of rows identifiers.
 * @param layout of the table in which the entity id belongs.
 *        If null, then long components may not be recognized.
 * @return a properly constructed list of KijiRestEntityIds.
 * @throws IOException if KijiRestEntityId list can not be properly constructed.
 *//*from   w ww.  j a v  a2  s  .c  om*/
public static List<KijiRestEntityId> createListFromUrl(final String entityIdListString,
        final KijiTableLayout layout) throws IOException {
    final JsonParser parser = new JsonFactory().createJsonParser(entityIdListString)
            .enable(Feature.ALLOW_COMMENTS).enable(Feature.ALLOW_SINGLE_QUOTES)
            .enable(Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    final JsonNode jsonNode = BASIC_MAPPER.readTree(parser);

    List<KijiRestEntityId> kijiRestEntityIds = Lists.newArrayList();

    if (jsonNode.isArray()) {
        for (JsonNode node : jsonNode) {
            if (node.isTextual()) {
                kijiRestEntityIds.add(createFromUrl(node.textValue(), layout));
            } else {
                kijiRestEntityIds.add(createFromUrl(node.toString(), layout));
            }
        }
    } else {
        throw new IOException("The entity id list string is not a valid json array.");
    }

    return kijiRestEntityIds;
}

From source file:de.qaware.cloud.deployer.kubernetes.test.BaseKubernetesResourceTest.java

protected void testDeleteOptions(UrlPattern instancePattern) throws JsonProcessingException {
    String jsonDeleteOptions = new ObjectMapper(new JsonFactory()).writeValueAsString(new DeleteOptions(0));
    instanceRule.verify(deleteRequestedFor(instancePattern).withRequestBody(equalTo(jsonDeleteOptions)));
}

From source file:org.springframework.social.wechat.api.impl.WechatErrorHandler.java

private Map<String, String> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    String json = readFully(response.getBody());

    logger.debug("Error from Wechat: " + json);

    try {//from   w  w  w  .j  a  va 2  s .  c o  m
        Map<String, String> responseMap = mapper.<Map<String, String>>readValue(json,
                new TypeReference<Map<String, String>>() {
                });
        Map<String, String> errorMap = Collections.<String, String>emptyMap();
        errorMap.put(ERROR_CODE, responseMap.get(ERROR_CODE));
        errorMap.put(ERROR_MESSAGE, responseMap.get(ERROR_MESSAGE));
        return errorMap;

    } catch (JsonParseException e) {
        return null;
    }
}

From source file:com.world.watch.worldwatchcron.util.WWCron.java

public long extractLatestTimeStamp(String newsJson) {
    long maxTS = 0;
    JsonFactory factory = new JsonFactory();
    try {/*  w  ww.  ja va 2 s  .  c o m*/
        JsonParser parser = factory.createParser(newsJson);
        while (!parser.isClosed()) {
            JsonToken token = parser.nextToken();
            if (token == null) {
                break;
            }
            String fieldName = parser.getCurrentName();
            if (fieldName != null && fieldName.equals("date")) {
                parser.nextToken();
                long date = Long.parseLong(parser.getText());
                if (maxTS < date) {
                    maxTS = date;
                }
            }
        }
    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //logger.error("File not found ", e);
    }
    return maxTS;
}

From source file:org.apache.hadoop.gateway.services.registry.impl.DefaultServiceRegistryService.java

private HashMap<String, HashMap<String, RegEntry>> getMapFromJsonString(String json) {
    Registry map = null;/*from w w w  .  j  av  a  2  s  .c  o m*/
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    TypeReference<Registry> typeRef = new TypeReference<Registry>() {
    };
    try {
        map = mapper.readValue(json, typeRef);
    } catch (JsonParseException e) {
        LOG.failedToGetMapFromJsonString(json, e);
    } catch (JsonMappingException e) {
        LOG.failedToGetMapFromJsonString(json, e);
    } catch (IOException e) {
        LOG.failedToGetMapFromJsonString(json, e);
    }
    return map;
}

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

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

        @Override//from w  ww . j  av  a2 s.  co m
        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);
            if (errorResponse != null) {
                debugResponse(LOG_TAG, rawJsonData);
            }
        }

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