Example usage for com.fasterxml.jackson.databind MappingJsonFactory MappingJsonFactory

List of usage examples for com.fasterxml.jackson.databind MappingJsonFactory MappingJsonFactory

Introduction

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

Prototype

public MappingJsonFactory() 

Source Link

Usage

From source file:com.entertailion.android.shapeways.MainActivity.java

private void getMaterials() {
    Log.d(LOG_TAG, "getMaterials");
    try {//from   w w w .  j a v  a  2s  . c o m
        HttpResponse httpResponse = ((ShapewaysApplication) getApplicationContext()).getShapewaysClient()
                .getResponse(ShapewaysClient.API_URL_BASE + ShapewaysClient.MATERIALS_PATH);
        String response = EntityUtils.toString(httpResponse.getEntity());
        Log.i(LOG_TAG, "response=" + response);

        // http://wiki.fasterxml.com/JacksonInFiveMinutes
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = mapper.readValue(response, Map.class);
        Log.i(LOG_TAG, "map=" + map);

        // The response does not use array[] notation for the list of
        // materials.
        // So, have to manually parse the JSON to get the list data.
        MappingJsonFactory f = new MappingJsonFactory();
        JsonParser jp = f.createJsonParser(response);
        Materials materials = new Materials();
        materials.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        jp.nextToken(); // will return JsonToken.START_OBJECT (verify?)
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldname = jp.getCurrentName();
            Log.d(LOG_TAG, "fieldname=" + fieldname);
            jp.nextToken(); // move to value
            if ("materials".equals(fieldname)) { // contains an object
                // Material material = jp.readValueAs(Material.class);
                boolean end = false;
                do {
                    Material material = new Material();
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        String namefield = jp.getCurrentName();
                        Log.d(LOG_TAG, "namefield=" + namefield);
                        jp.nextToken(); // move to value
                        if ("materialId".equals(namefield)) {
                            material.setMaterialId(Integer.parseInt(jp.getText()));
                        } else if ("title".equals(namefield)) {
                            material.setTitle(jp.getText());
                        } else if ("supportsColorFiles".equals(namefield)) {
                            material.setSupportsColorFiles(Integer.parseInt(jp.getText()));
                        } else if ("printerId".equals(namefield)) {
                            material.setPrinterId(jp.getText());
                        } else if ("swatch".equals(namefield)) {
                            material.setSwatch(jp.getText());
                        } else {
                            Log.w(LOG_TAG, "Unrecognized material field: " + namefield);
                        }
                    }
                    materials.getMaterials().add(material);
                    JsonToken token = jp.nextToken();
                    Log.d(LOG_TAG, "token=" + token);
                    if (token == JsonToken.FIELD_NAME) {
                        try {
                            Integer.parseInt(jp.getCurrentName());
                            jp.nextToken();
                        } catch (Exception ex) {
                            end = true;
                        }
                    } else if (token == JsonToken.END_OBJECT) {
                        end = true;
                    }
                } while (!end);

            } else if ("result".equals(fieldname)) {
                if (jp.getText().equals(Result.success.name())) {
                    materials.setResult(Result.success);
                } else if (jp.getText().equals(Result.failure.name())) {
                    materials.setResult(Result.failure);
                }
            } else {
                Log.w(LOG_TAG, "Unrecognized materials field: " + fieldname);
            }
        }
        jp.close(); // ensure resources get cleaned up timely and properly

        Log.i(LOG_TAG, "materials=" + materials.getMaterials().size());
        Log.i(LOG_TAG, "material: id=" + materials.getMaterials().get(0).getMaterialId());
        Log.i(LOG_TAG, "material: title=" + materials.getMaterials().get(0).getTitle());
        Log.i(LOG_TAG, "material: swatch=" + materials.getMaterials().get(0).getSwatch());
    } catch (Exception e) {
        Log.e(LOG_TAG, "getMaterials", e);
    }
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

/**
 * read_config()//from  www  .  j  a  va  2 s.  c  o m
 * The copperegg_config.json file contains a specification for the metric groups and dashboards to be created / or updated.
 * Mandatory
 */
public void read_config(InputStream in) throws Exception {

    JsonFactory f = new MappingJsonFactory();
    JsonParser jp = f.createJsonParser(in);

    JsonToken current;

    current = jp.nextToken();
    if (current != JsonToken.START_OBJECT) {
        logger.warn("read_config: Error:  START_OBJECT not found : quiting.");
        return;
    }
    current = jp.nextToken();
    String fieldName = jp.getCurrentName();
    current = jp.nextToken();
    if (fieldName.equals("config")) {
        if (current != JsonToken.START_OBJECT) {
            logger.warn("read_config: Error:  START_OBJECT not found after config : quiting.");
            return;
        }
        current = jp.nextToken();
        String fieldName2 = jp.getCurrentName();
        if (fieldName2.equals("metric_groups")) {
            current = jp.nextToken();
            if (current != JsonToken.START_ARRAY) {
                logger.warn("read_config: Error:  START_ARRAY not found after metric_groups : quiting.");
                return;
            }

            current = jp.nextToken();
            while (current != JsonToken.END_ARRAY) {
                if (current != JsonToken.START_OBJECT) {
                    logger.warn(
                            "read_config: Error:  START_OBJECT not found after metric_groups START_ARRAY : quiting.");
                    return;
                }
                current = jp.nextToken();
                JsonNode node1 = jp.readValueAsTree();
                String node1string = write_tostring(node1);
                metricgroupMap.put(node1.get("name").asText(), node1string);
                current = jp.nextToken();
            }

            current = jp.nextToken();
            String fieldName3 = jp.getCurrentName();

            if (fieldName3.equals("dashboards")) {
                current = jp.nextToken();
                if (current != JsonToken.START_ARRAY) {
                    logger.warn("read_config: Error:  START_ARRAY not found after dashboards : quiting.");
                    return;
                }
                current = jp.nextToken();
                while (current != JsonToken.END_ARRAY) {
                    if (current != JsonToken.START_OBJECT) {
                        logger.warn(
                                "read_config: Error:  START_OBJECT not found after dashboards START_ARRAY : quiting.");
                        return;
                    }
                    current = jp.nextToken();
                    JsonNode node = jp.readValueAsTree();
                    String nodestring = write_tostring(node);
                    dashMap.put(node.get("name").asText(), nodestring);
                    current = jp.nextToken();

                }
                if (jp.nextToken() != JsonToken.END_OBJECT) {
                    logger.warn("read_config: Error:  END_OBJECT expected, not found (1): quiting.");
                    return;
                }
                if (jp.nextToken() != JsonToken.END_OBJECT) {
                    logger.warn("read_config: Error:  END_OBJECT expected, not found (2): quiting.");
                    return;
                }
            } else {
                logger.warn("read_config: Error:  Expected dashboards : quiting.");
                return;
            }
        } else {
            logger.warn("read_config: Error:  Expected metric_groups : quiting.");
            return;
        }
    }
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

public String groupFind(String findName, String findIndex, Integer ExpectInt) throws Exception {
    JsonFactory f = new MappingJsonFactory();
    JsonParser jp = f.createJsonParser(findIndex);

    int count = 0;
    int foundit = 0;
    String Result = null;/*from w  w  w.j a va2 s .  c om*/

    JsonToken current = jp.nextToken();
    if (current != JsonToken.START_ARRAY) {
        logger.warn("groupFind: Error: START_ARRAY expected, not found : quiting.");
        return (Result);
    }
    current = jp.nextToken();
    while (current != JsonToken.END_ARRAY) {
        if (current != JsonToken.START_OBJECT) {
            logger.warn("groupFind: Error: START_OBJECT expected, not found : quiting.");
            return (Result);
        }
        current = jp.nextToken();
        JsonNode node = jp.readValueAsTree();
        String tmpStr = node.get("name").asText().toString();
        if (findName.equals(node.get("name").asText().toString())) {
            if (ExpectInt != 0) {
                foundit = node.get("id").asInt();
                Result = String.valueOf(foundit);
            } else {
                Result = node.get("id").asText().toString();
            }
            break;
        }
        current = jp.nextToken();
        count = count + 1;
    }
    return (Result);
}

From source file:org.apache.arrow.vector.ipc.JsonFileReader.java

public JsonFileReader(File inputFile, BufferAllocator allocator) throws JsonParseException, IOException {
    super();/*w ww.  j  av a  2s.  c o m*/
    this.allocator = allocator;
    MappingJsonFactory jsonFactory = new MappingJsonFactory();
    this.parser = jsonFactory.createParser(inputFile);
    // Allow reading NaN for floating point values
    this.parser.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
}

From source file:org.apache.arrow.vector.ipc.JsonFileWriter.java

public JsonFileWriter(File outputFile, JSONWriteConfig config) throws IOException {
    MappingJsonFactory jsonFactory = new MappingJsonFactory();
    this.generator = jsonFactory.createGenerator(outputFile, JsonEncoding.UTF8);
    if (config.pretty) {
        DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
        prettyPrinter.indentArraysWith(NopIndenter.instance);
        this.generator.setPrettyPrinter(prettyPrinter);
    }/* w  ww. j  ava2s.  c  om*/
    // Allow writing of floating point NaN values not as strings
    this.generator.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, false);
}

From source file:org.sead.repositories.reference.RefRepository.java

private JsonNode getAggregation(String id, File indexFile, CountingInputStream cis, boolean withChildren,
        Long oreFileSize) throws JsonParseException, JsonMappingException, IOException {
    log.debug("Getting Aggregation");

    long curPos = 0;

    // Always need to generate these
    ArrayList<String> entries = new ArrayList<String>();
    ArrayList<Long> offsets = new ArrayList<Long>();

    FileInputStream fis = new FileInputStream(indexFile);
    JsonFactory f = new MappingJsonFactory();
    JsonParser jp = f.createParser(fis);

    JsonToken current;//from w  w  w .  ja  v a 2s.  co m
    log.debug("Reading Index file");
    current = jp.nextToken(); // Start object

    while ((current = jp.nextToken()) != null) {
        if (current.equals(JsonToken.FIELD_NAME)) {
            String fName = jp.getText();
            current = jp.nextToken(); // Get to start of
            // value
            long offset = jp.getLongValue();
            log.trace("Adding: " + fName + " : " + offset);
            entries.add(fName);
            offsets.add(offset);
        }
    }
    IOUtils.closeQuietly(fis);

    File descFile = getDescFile(id);
    InputStream is = new FileInputStream(descFile);
    ObjectNode resultNode = (ObjectNode) mapper.readTree(is);
    IOUtils.closeQuietly(is);

    log.trace(resultNode.toString());
    if ((resultNode.has("Has Part")) && withChildren) {

        resultNode = getChildren(resultNode, indexFile, cis, oreFileSize, curPos, entries, offsets);
    } else {
        resultNode.remove("aggregates");
    }
    log.debug("Aggregation retrieved");
    return resultNode;
}

From source file:org.sead.repositories.reference.RefRepository.java

private JsonNode getItem(String item, File indexFile, CountingInputStream cis, boolean withChildren,
        Long oreFileSize, long curOffset, ArrayList<String> entries, ArrayList<Long> offsets)
        throws JsonParseException, JsonMappingException, IOException {
    log.trace("Getting: " + item + " with starting offset: " + curOffset);

    long curPos = curOffset;

    if ((entries == null) || (offsets == null)) {
        entries = new ArrayList<String>();
        offsets = new ArrayList<Long>();

        FileInputStream fis = new FileInputStream(indexFile);
        JsonFactory f = new MappingJsonFactory();
        JsonParser jp = f.createParser(fis);

        JsonToken current;//from   w ww. java 2 s.  c o  m
        log.trace("Reading Index file");
        current = jp.nextToken(); // Start object

        while ((current = jp.nextToken()) != null) {
            if (current.equals(JsonToken.FIELD_NAME)) {
                String fName = jp.getText();
                current = jp.nextToken(); // Get to start of
                // value
                long offset = jp.getLongValue();
                log.trace("Adding: " + fName + " : " + offset);
                entries.add(fName);
                offsets.add(offset);
            }
        }
        try {
            fis.close();
        } catch (Exception e) {
            log.debug(e.getMessage());
        }

    }

    byte[] b = null;
    int bytesRead = 0;

    int index = entries.indexOf(item);
    if (index == -1) {
        log.warn(item + " not in index");
    }
    // getSizeEstimateFor(index)
    int estSize;
    if (index < offsets.size() - 1) {
        estSize = (int) (offsets.get(index + 1) - offsets.get(index));
    } else {
        estSize = (int) (oreFileSize - offsets.get(index));
    }
    curPos += skipTo(cis, curPos, offsets.get(index));
    log.trace("Current Pos updated to : " + curPos);
    b = new byte[estSize];
    bytesRead = cis.read(b);
    log.trace("Read " + bytesRead + " bytes");
    if (bytesRead == estSize) {
        log.trace("Read: " + new String(b));
        InputStream is = new ByteArrayInputStream(b);
        // mapper seems to be OK ignoring a last char such as a comma after
        // the object/tree
        ObjectNode resultNode = (ObjectNode) mapper.readTree(is);
        try {
            is.close();
        } catch (Exception e) {
            log.debug(e.getMessage());
        }

        curPos += bytesRead;
        log.trace("curPos: " + curPos + " : count: " + cis.getByteCount());

        log.trace(resultNode.toString());
        if ((resultNode.has("Has Part")) && withChildren) {
            resultNode = getChildren(resultNode, indexFile, cis, oreFileSize, curPos, entries, offsets);
        } else {
            resultNode.remove("aggregates");
        }
        /*
         * if (args[2] != null) { long offset2 = Long.parseLong(args[2]);
         * sbc.position(offset2); b.clear(); sbc.read(b);
         * 
         * InputStream is2 = new ByteArrayInputStream(b.array());
         * 
         * JsonNode node2 = mapper.readTree(is2);
         * System.out.println(node2.toString()); is2.close(); }
         */
        return resultNode;
    } else {
        return null;
    }

}

From source file:org.sead.repositories.reference.RefRepository.java

protected static void generateIndex(InputStream ro, File descFile, File indexFile)
        throws JsonParseException, IOException {

    log.debug("Generating desc and index files");
    JsonFactory f = new MappingJsonFactory(); // reading
    JsonParser jp = f.createParser(ro);/*w ww  .j  a va  2 s  .com*/

    JsonGenerator generator = new JsonFactory().createGenerator(descFile, JsonEncoding.UTF8);

    JsonToken current;

    current = jp.nextToken();

    report(jp, current);
    while ((current = jp.nextToken()) != null) {
        if (current.equals(JsonToken.FIELD_NAME)) {
            String fName = jp.getText();
            if (fName.equals("describes")) {
                log.trace("describes");
                while (((current = jp.nextToken()) != null)) {
                    if (jp.isExpectedStartObjectToken()) {
                        generator.setCodec(new ObjectMapper());
                        generator.useDefaultPrettyPrinter();

                        generator.writeStartObject();

                        while (((current = jp.nextToken()) != JsonToken.END_OBJECT)) {
                            if (current != JsonToken.FIELD_NAME) {
                                log.warn("Unexpected Token!");
                                report(jp, current);

                            } else {
                                report(jp, current);
                                String name = jp.getText();
                                current = jp.nextToken(); // Get to start of
                                // value
                                if (!name.equals("aggregates")) {
                                    log.trace("Writing: " + name);
                                    generator.writeFieldName(name);
                                    generator.writeTree(jp.readValueAsTree());
                                } else {
                                    report(jp, current);
                                    log.trace("Skipping?");
                                    if (current.isStructStart()) {
                                        indexChildren(indexFile, jp);
                                        // jp.skipChildren();
                                    } else {
                                        log.warn("Was Not Struct start!");
                                    }
                                    log.trace("Hit aggregates");

                                }
                            }
                        }

                        generator.writeEndObject();

                        generator.close();
                    }
                }
            }
        }
    }
}

From source file:portal.api.PortalClientIT.java

@Test
public void testPortalClientInstallServiceNotFoundAndFail() throws Exception {

    logger.info("Executing TEST = testPortalRSInstallServiceNotFound");
    List<Object> providers = new ArrayList<Object>();
    providers.add(new com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider());
    String uuid = UUID.fromString("55cab8b8-668b-4c75-99a9-39b24ed3d8be").toString();
    InstalledVxF is = prepareInstalledService(uuid);

    WebClient client = WebClient.create(endpointUrl + "/services/api/client/ivxfs/", providers);
    Response r = client.accept("application/json").type("application/json").post(is);
    assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());

    String portalAPIVersionListHeaders = (String) r.getHeaders().getFirst("X-Portal-API-Version");
    assertEquals("1.0.0", portalAPIVersionListHeaders);

    MappingJsonFactory factory = new MappingJsonFactory();
    JsonParser parser = factory.createJsonParser((InputStream) r.getEntity());
    InstalledVxF output = parser.readValueAs(InstalledVxF.class);
    logger.info("InstalledServiceoutput = " + output.getUuid() + ", status=" + output.getStatus());
    assertEquals(InstalledVxFStatus.INIT, output.getStatus());

    // wait for 2 seconds
    Thread.sleep(2000);//from w ww. j  av a2 s  . com
    // ask again about this task
    client = WebClient.create(endpointUrl + "/services/api/client/ivxfs/" + uuid);
    r = client.accept("application/json").type("application/json").get();

    factory = new MappingJsonFactory();
    parser = factory.createJsonParser((InputStream) r.getEntity());
    output = parser.readValueAs(InstalledVxF.class);

    assertEquals(uuid, output.getUuid());
    assertEquals(InstalledVxFStatus.FAILED, output.getStatus());
    assertEquals("(pending)", output.getName());
}

From source file:portal.api.PortalClientIT.java

@Test
public void testPortalClientInstallVxFAndGetStatus() throws Exception {

    logger.info("Executing TEST = testPortalRSInstallServiceAndGetStatus");

    List<Object> providers = new ArrayList<Object>();
    providers.add(new com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider());
    String uuid = UUID.fromString("77777777-668b-4c75-99a9-39b24ed3d8be").toString();

    // first delete an existing installation if exists

    WebClient client = WebClient.create(endpointUrl + "/services/api/client/ivxfs/" + uuid, providers);
    Response r = client.accept("application/json").type("application/json").delete();
    if (Response.Status.NOT_FOUND.getStatusCode() != r.getStatus()) {

        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        logger.info("VxF is already installed! We uninstall it first!");
        int guard = 0;
        InstalledVxF insvxf = null;/*ww w.java2 s . c  o  m*/
        do {

            // ask again about this task
            client = WebClient.create(endpointUrl + "/services/api/client/ivxfs/" + uuid);
            r = client.accept("application/json").type("application/json").get();

            MappingJsonFactory factory = new MappingJsonFactory();
            JsonParser parser = factory.createJsonParser((InputStream) r.getEntity());
            insvxf = parser.readValueAs(InstalledVxF.class);

            logger.info(
                    "Waiting for UNINSTALLED for test vxf UUID=" + uuid + " . Now is: " + insvxf.getStatus());
            Thread.sleep(2000);
            guard++;

        } while ((insvxf != null) && (insvxf.getStatus() != InstalledVxFStatus.UNINSTALLED)
                && (insvxf.getStatus() != InstalledVxFStatus.FAILED) && (guard <= 30));

        if (insvxf.getStatus() != InstalledVxFStatus.FAILED)
            assertEquals(InstalledVxFStatus.UNINSTALLED, insvxf.getStatus());

    }

    // now post a new installation
    client = WebClient.create(endpointUrl + "/services/api/client/ivxfs/", providers);
    InstalledVxF is = prepareInstalledService(uuid);
    r = client.accept("application/json").type("application/json").post(is);
    assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());

    int guard = 0;

    InstalledVxF insvxf = null;
    do {

        // ask again about this task
        client = WebClient.create(endpointUrl + "/services/api/client/ivxfs/" + uuid);
        r = client.accept("application/json").type("application/json").get();

        MappingJsonFactory factory = new MappingJsonFactory();
        JsonParser parser = factory.createJsonParser((InputStream) r.getEntity());
        insvxf = parser.readValueAs(InstalledVxF.class);

        logger.info("Waiting for STARTED for test vxf UUID=" + uuid + " . Now is: " + insvxf.getStatus());
        Thread.sleep(1000);
        guard++;

    } while ((insvxf != null) && (insvxf.getStatus() != InstalledVxFStatus.STARTED) && (guard <= 30));

    assertEquals(uuid, insvxf.getUuid());
    assertEquals(InstalledVxFStatus.STARTED, insvxf.getStatus());
    assertEquals("IntegrTestLocal example service", insvxf.getName());

}