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

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

Introduction

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

Prototype

@Deprecated
public JsonParser createJsonParser(String content) throws IOException, JsonParseException 

Source Link

Document

Method for constructing parser for parsing contents of given String.

Usage

From source file:org.helm.notation2.wsadapter.NucleotideWSLoader.java

/**
 * Loads the nucleotide store using the URL configured in {@code MonomerStoreConfiguration}.
 * //from   w w w  . j  a v  a2  s .c o  m
 * @return Map containing nucleotides
 * 
 * @throws IOException
 * @throws URISyntaxException
 */
public Map<String, String> loadNucleotideStore() throws IOException, URISyntaxException {

    Map<String, String> nucleotides = new HashMap<String, String>();
    LOG.debug("Loading nucleotide store by Webservice Loader");
    LOG.debug(MonomerStoreConfiguration.getInstance().toString());
    CloseableHttpResponse response = null;
    try {
        response = WSAdapterUtils
                .getResource(MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesFullURL());
        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();

        JsonParser jsonParser = jsonf.createJsonParser(instream);
        nucleotides = deserializeNucleotideStore(jsonParser);
        LOG.debug(nucleotides.size() + " nucleotides loaded");

        EntityUtils.consume(response.getEntity());

    } catch (ClientProtocolException e) {

        /* read file */
        JsonFactory jsonf = new JsonFactory();
        InputStream instream = new FileInputStream(
                new File(MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesFullURL()));

        JsonParser jsonParser = jsonf.createJsonParser(instream);
        nucleotides = deserializeNucleotideStore(jsonParser);
        LOG.debug(nucleotides.size() + " nucleotides loaded");

    } finally {

        if (response != null) {
            response.close();
        }
    }

    return nucleotides;
}

From source file:com.chenchengzhi.windtalkers.server.WindMessageFactory.java

@Override
public Message parse(HttpRequest httpRequest) {
    WindTalkerID talkerID = pathResolve(httpRequest);
    if (talkerID == null) {
        throw Issue.of(StatusCode.NOT_FOUND, WindMessageFactory.class.getCanonicalName(), "parse",
                "Talker not found!");
    }/*w w  w .  j  a v  a2s  .co m*/

    Message request = new Message(talkerID);

    ChannelBuffer buffer = httpRequest.getContent();
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getJsonFactory();
    byte[] rawRequestBytes = buffer.array();
    String content = new String(rawRequestBytes, Charsets.UTF_8);

    try {
        JsonNode body = mapper.readTree(factory.createJsonParser(content));
        request.setRequestBody(body);
    } catch (JsonProcessingException jpe) {
        throw Issue.of(StatusCode.BAD_REQUEST, WindMessageFactory.class.getCanonicalName(), "parse",
                "JsonProcessingException");
    } catch (IOException ioe) {
        throw Issue.of(StatusCode.BAD_REQUEST, WindMessageFactory.class.getCanonicalName(), "parse",
                "IOException");
    }

    return request;
}

From source file:org.apache.lucene.server.handlers.BulkAddDocumentsHandler.java

@Override
public String handleStreamed(Reader reader, Map<String, List<String>> params) throws Exception {

    JsonFactory jfactory = new JsonFactory();

    JsonParser parser = jfactory.createJsonParser(reader);

    if (parser.nextToken() != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("expected JSON object");
    }/*w  w w  .  ja v a  2  s .c  o  m*/
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (!parser.getText().equals("indexName")) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (parser.nextToken() != JsonToken.VALUE_STRING) {
        throw new IllegalArgumentException("indexName should be string");
    }

    IndexState indexState = globalState.get(parser.getText());
    indexState.verifyStarted(null);
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected documents next");
    }
    if (!parser.getText().equals("documents")) {
        throw new IllegalArgumentException("expected documents after indexName");
    }

    ShardState shardState = indexState.getShard(0);

    if (parser.nextToken() != JsonToken.START_ARRAY) {
        throw new IllegalArgumentException("documents should be a list");
    }

    int count = 0;
    IndexingContext ctx = new IndexingContext();

    AddDocumentHandler addDocHandler = (AddDocumentHandler) globalState.getHandler("addDocument");

    // Parse as many doc blocks as there are:
    while (true) {

        List<Document> children = null;
        Document parent = null;

        JsonToken token = parser.nextToken();
        if (token == JsonToken.END_ARRAY) {
            break;
        }
        if (token != JsonToken.START_OBJECT) {
            throw new IllegalArgumentException("expected object");
        }

        // Parse parent + children for this one doc block:
        while (true) {
            token = parser.nextToken();
            if (token == JsonToken.END_OBJECT) {
                // Done with parent + child in this block
                break;
            }
            if (token != JsonToken.FIELD_NAME) {
                throw new IllegalArgumentException("missing field name: " + token);
            }
            String f = parser.getText();
            if (f.equals("children")) {
                token = parser.nextToken();
                if (token != JsonToken.START_ARRAY) {
                    throw new IllegalArgumentException("expected array for children");
                }

                children = new ArrayList<Document>();

                // Parse each child:
                while (true) {
                    Document doc = addDocHandler.parseDocument(indexState, parser);
                    if (doc == null) {
                        break;
                    }
                    children.add(doc);
                }
            } else if (f.equals("parent")) {
                parent = addDocHandler.parseDocument(indexState, parser);
            } else {
                throw new IllegalArgumentException("unrecognized field name \"" + f + "\"");
            }
        }

        if (parent == null) {
            throw new IllegalArgumentException("missing parent");
        }
        if (children == null) {
            throw new IllegalArgumentException("missing children");
        }

        // Parent is last:
        children.add(parent);

        globalState.submitIndexingTask(shardState.getAddDocumentsJob(count, null, children, ctx));
        count++;
    }

    // nocommit this is ... lameish:
    while (true) {
        if (ctx.addCount.get() == count) {
            break;
        }
        Thread.sleep(1);
    }

    Throwable t = ctx.getError();
    if (t != null) {
        IOUtils.reThrow(t);
    }

    JSONObject o = new JSONObject();
    o.put("indexGen", shardState.writer.getMaxCompletedSequenceNumber());
    o.put("indexedDocumentBlockCount", count);
    return o.toString();
}

From source file:net.floodlightcontroller.configuration.ConfigurationManager.java

/**
 * Reads a configuration file and calls the corresponding configuration 
 * listeners./*  w w w .jav  a2  s.  c o m*/
 * 
 * @param file An optional configuration file name.
 */
private void readJsonFromFile(String fileName) {
    String configFile = (fileName != null) ? fileName : this.fileName;
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    JsonParser jp = null;

    try {
        jp = f.createJsonParser(new File(configFile));
        JsonNode root = mapper.readTree(jp);
        // Check if the file is empty.
        if (root == null)
            return;
        Iterator<Entry<String, JsonNode>> iter = root.fields();
        // For every configuration sub-node.
        while (iter.hasNext()) {
            Entry<String, JsonNode> entry = iter.next();
            String fieldName = entry.getKey();
            JsonNode child = entry.getValue();
            if (configurationListener.containsKey(fieldName)) {
                configurationListener.get(fieldName).putJsonConfig(child);
            } else {
                if (logger.isWarnEnabled()) {
                    logger.warn("No configuration listener found for " + fieldName);
                }
            }
        }
    } catch (FileNotFoundException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("Configuration file {} not found.", configFile);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.lucene.server.handlers.BulkUpdateDocumentHandler.java

@Override
public String handleStreamed(Reader reader, Map<String, List<String>> params) throws Exception {
    JsonFactory jfactory = new JsonFactory();

    JsonParser parser = jfactory.createJsonParser(reader);

    if (parser.nextToken() != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("expected JSON object");
    }/*from   w ww.  ja  va2  s.  c  o  m*/
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (!parser.getText().equals("indexName")) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (parser.nextToken() != JsonToken.VALUE_STRING) {
        throw new IllegalArgumentException("indexName should be string");
    }

    IndexState indexState = globalState.get(parser.getText());
    indexState.verifyStarted(null);

    ShardState shardState = indexState.getShard(0);

    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected documents next");
    }
    if (!parser.getText().equals("documents")) {
        throw new IllegalArgumentException("expected documents after indexName");
    }
    if (parser.nextToken() != JsonToken.START_ARRAY) {
        throw new IllegalArgumentException("documents should be a list");
    }

    IndexingContext ctx = new IndexingContext();

    AddDocumentHandler addDocHandler = (AddDocumentHandler) globalState.getHandler("addDocument");

    // Parse any number of documents to update:
    int count = 0;

    while (true) {
        JsonToken token = parser.nextToken();
        if (token == JsonToken.END_ARRAY) {
            break;
        }
        if (token != JsonToken.START_OBJECT) {
            throw new IllegalArgumentException("missing object");
        }

        // Parse term: and fields:
        Term updateTerm = null;

        final Document doc = new Document();

        while (true) {
            token = parser.nextToken();
            if (token == JsonToken.END_OBJECT) {
                break;
            }
            if (token != JsonToken.FIELD_NAME) {
                throw new IllegalArgumentException("missing field name");
            }
            String f = parser.getText();
            if (f.equals("term")) {
                if (parser.nextToken() != JsonToken.START_OBJECT) {
                    throw new IllegalArgumentException("missing object");
                }

                // TODO: allow field to be specified only once, then
                // only text per document

                String field = null, term = null;

                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    String f2 = parser.getText();
                    if (f2.equals("field")) {
                        if (parser.nextToken() != JsonToken.VALUE_STRING) {
                            throw new IllegalArgumentException("missing string value");
                        }
                        field = parser.getText();
                        // Ensure field is valid:
                        indexState.getField(field);
                    } else if (f2.equals("term")) {
                        if (parser.nextToken() != JsonToken.VALUE_STRING) {
                            throw new IllegalArgumentException("missing string value");
                        }
                        term = parser.getText();
                    } else {
                        throw new IllegalArgumentException("unexpected field " + f);
                    }
                }
                updateTerm = new Term(field, term);
            } else if (f.equals("fields")) {
                addDocHandler.parseFields(indexState, doc, parser);
            } else {
                boolean handled = false;
                for (AddDocumentHandler.PostHandle postHandle : addDocHandler.postHandlers) {
                    if (postHandle.invoke(indexState, f, parser, doc)) {
                        handled = true;
                        break;
                    }
                }
                if (!handled) {
                    throw new IllegalArgumentException("unrecognized field " + parser.getText());
                }
            }
        }

        if (updateTerm == null) {
            throw new IllegalArgumentException("missing term");
        }

        // TODO: this is dup'd code ... share better w/ AddDocHandler
        globalState.submitIndexingTask(shardState.getAddDocumentJob(count, updateTerm, doc, ctx));
        count++;
    }

    // nocommit this is ... lameish:
    while (true) {
        if (ctx.addCount.get() == count) {
            break;
        }
        Thread.sleep(1);
    }

    JSONObject o = new JSONObject();
    o.put("indexGen", shardState.writer.getMaxCompletedSequenceNumber());
    o.put("indexedDocumentCount", count);
    return o.toString();
}

From source file:com.baasbox.service.sociallogin.SocialLoginService.java

public boolean validationRequest(String token) throws BaasBoxSocialTokenValidationException {
    String url = getValidationURL(token);
    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    HttpGet method = new HttpGet(url);

    BasicResponseHandler brh = new BasicResponseHandler();

    String body;//from   w w  w. ja  va 2 s .co  m
    try {
        body = client.execute(method, brh);

        if (StringUtils.isEmpty(body)) {
            return false;
        } else {
            ObjectMapper mapper = new ObjectMapper();
            JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
            JsonParser jp = factory.createJsonParser(body);
            JsonNode jn = mapper.readTree(jp);
            return validate(jn);
        }
    } catch (IOException e) {
        throw new BaasBoxSocialTokenValidationException(
                "There was an error in the token validation process:" + ExceptionUtils.getMessage(e));
    }

}

From source file:mil.nga.giat.data.elasticsearch.FilterToElastic2.java

protected void visitLiteralGeometry(Literal expression) throws IOException {
    super.visitLiteralGeometry(expression);

    final GeometryJSON gjson = new GeometryJSON();
    final String geoJson = gjson.toString(currentGeometry);
    final JsonFactory factory = new JsonFactory();
    JsonParser parser = factory.createJsonParser(geoJson);
    final JsonXContentParser xParser = new JsonXContentParser(parser);
    xParser.nextToken();//from w w w. java 2  s.  c om
    currentShapeBuilder = ShapeBuilder.parse(xParser);
}

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

public Snippet(String json) {
    try {//ww w.ja  v  a  2 s  . c om
        Reader reader = new StringReader(json);
        JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory 
        JsonParser jsonParser = jsonFactory.createJsonParser(reader);
        jsonParser.nextToken();
        this.read(jsonParser);
    } catch (IOException e) {
        LOG.error(e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.lucene.server.handlers.BulkUpdateDocumentsHandler.java

@Override
public String handleStreamed(Reader reader, Map<String, List<String>> params) throws Exception {

    JsonFactory jfactory = new JsonFactory();

    JsonParser parser = jfactory.createJsonParser(reader);

    if (parser.nextToken() != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("expected JSON object");
    }/*from   w ww  .  ja v  a 2s.  c o  m*/
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (!parser.getText().equals("indexName")) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (parser.nextToken() != JsonToken.VALUE_STRING) {
        throw new IllegalArgumentException("indexName should be string");
    }

    IndexState indexState = globalState.get(parser.getText());
    indexState.verifyStarted(null);
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected documents next");
    }
    if (!parser.getText().equals("documents")) {
        throw new IllegalArgumentException("expected documents after indexName");
    }

    if (parser.nextToken() != JsonToken.START_ARRAY) {
        throw new IllegalArgumentException("documents should be a list");
    }
    ShardState shardState = indexState.getShard(0);

    int count = 0;
    IndexingContext ctx = new IndexingContext();

    AddDocumentHandler addDocHandler = (AddDocumentHandler) globalState.getHandler("addDocument");

    // Parse as many doc blocks as there are:
    while (true) {

        List<Document> children = null;
        Document parent = null;
        Term updateTerm = null;

        JsonToken token = parser.nextToken();
        if (token == JsonToken.END_ARRAY) {
            break;
        }
        if (token != JsonToken.START_OBJECT) {
            throw new IllegalArgumentException("expected object");
        }

        // Parse term + parent + children for this one doc block:
        while (true) {
            token = parser.nextToken();
            if (token == JsonToken.END_OBJECT) {
                // Done with parent + child in this block
                break;
            }
            if (token != JsonToken.FIELD_NAME) {
                throw new IllegalArgumentException("missing field name: " + token);
            }
            String f = parser.getText();
            if (f.equals("term")) {
                if (parser.nextToken() != JsonToken.START_OBJECT) {
                    throw new IllegalArgumentException("missing object");
                }

                // TODO: allow field to be specified only once, then
                // only text per document

                String field = null, term = null;

                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    String f2 = parser.getText();
                    if (f2.equals("field")) {
                        if (parser.nextToken() != JsonToken.VALUE_STRING) {
                            throw new IllegalArgumentException("missing string value");
                        }
                        field = parser.getText();
                        // Ensure field is valid:
                        indexState.getField(field);
                    } else if (f2.equals("term")) {
                        if (parser.nextToken() != JsonToken.VALUE_STRING) {
                            throw new IllegalArgumentException("missing string value");
                        }
                        term = parser.getText();
                    } else {
                        throw new IllegalArgumentException("unexpected field " + f);
                    }
                }
                updateTerm = new Term(field, term);
            } else if (f.equals("children")) {
                token = parser.nextToken();
                if (token != JsonToken.START_ARRAY) {
                    throw new IllegalArgumentException("expected array for children");
                }

                children = new ArrayList<Document>();

                // Parse each child:
                while (true) {
                    Document doc = addDocHandler.parseDocument(indexState, parser);
                    if (doc == null) {
                        break;
                    }
                    children.add(doc);
                }
            } else if (f.equals("parent")) {
                parent = addDocHandler.parseDocument(indexState, parser);
            } else {
                throw new IllegalArgumentException("unrecognized field name \"" + f + "\"");
            }
        }

        if (parent == null) {
            throw new IllegalArgumentException("missing parent");
        }
        if (children == null) {
            throw new IllegalArgumentException("missing children");
        }

        // Parent is last:
        children.add(parent);

        globalState.submitIndexingTask(shardState.getAddDocumentsJob(count, updateTerm, children, ctx));
        count++;
    }

    // nocommit this is ... lameish:
    while (true) {
        if (ctx.addCount.get() == count) {
            break;
        }
        Thread.sleep(1);
    }

    Throwable t = ctx.getError();
    if (t != null) {
        IOUtils.reThrow(t);
    }

    JSONObject o = new JSONObject();
    o.put("indexGen", shardState.writer.getMaxCompletedSequenceNumber());
    o.put("indexedDocumentBlockCount", count);

    return o.toString();
}

From source file:DAO.BestellingDAOJson.java

@Override
public List<ArtikelBestelling> readArtikelBestelling(Bestelling bestelling) throws SQLException {
    //create.put("artikellijst", list);
    //create.put("bestelling_id", bestelling.getBestelling_id());
    //create.put("klant_id", bestelling.getKlant_id());       
    List<ArtikelBestelling> artikelBestellingen = new ArrayList<>();
    ArtikelBestelling artikelBestelling;
    ArtikelPOJO artikelpojo;/* w  ww.jav a 2  s  .  c o  m*/
    HashMap<Integer, Bestelling> catalogus = new HashMap<>();
    //catalogus = bestelling;
    try (FileReader read = new FileReader("C:\\Users\\maurice\\Desktop\\Workshoptest.json");) {

        catalogus = gson.fromJson(read, artikelType);

        //je hoeft de arraylist Artikelbestelling niet in een hashmap te stoppen (waarvan de integer dan zou corresponderen
        // met de bestelling ID) omdat de bestelling ID standaard al in het bestelling object opgeslagen wordt..
        // dus je kunt met een hasNext for each loop alle elementen van catalogus doorlopen en met een if statement bekijken of
        // het overeenkomt. Ik bedenk me net dat de key telkens uniek hoort te zijn, je zou dus niet meerdere keren dezelfde klantID
        // als key kunnen opgeven... Je zult een unieke key moeten maken van zowel de klantID plus het bestellingID erachter geplakt.
        // en een "_" ertussen. Zo kun je ook zeer gemakkelijk de juist bestelling vinden.
        catalogus = gson.fromJson(read, artikelType);
        bestelling = catalogus.get(bestelling.getKlant_id());
    } catch (IOException ex) {
        logger.error("read input/output " + ex);
    }

    JSONParser jsonParser = new JSONParser();
    String jsonFilePath = "C:\\Users\\maurice\\Desktop\\Workshoptest.json";
    try {
        JsonFactory jfactory = new JsonFactory();
        JsonParser jParser = jfactory
                .createJsonParser(new File("C:\\Users\\maurice\\Desktop\\Workshoptest.json"));
        //ObjectMapper mapper = new ObjectMapper();
        //ObjectNode node = (ObjectNode) mapper.readTree(jParser);
        //node.get(jsonFilePath)
    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    return artikelBestellingen;
}