Example usage for com.fasterxml.jackson.databind ObjectMapper readValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readValue

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public <T> T readValue(byte[] src, JavaType valueType)
            throws IOException, JsonParseException, JsonMappingException 

Source Link

Usage

From source file:luceneindexer.Main.java

/**
 * @param args the command line arguments
 *///from   w  w w  . j  a v a  2s .co  m
public static void main(String[] args) {
    // TODO code application logic here
    System.out.println("Hello world");
    //Open the file of JSON for reading
    FileOpener fOpener = new FileOpener("parks.json");

    //Create the object for writing
    LuceneWriter luceneWriter = new LuceneWriter("indexDir");

    //This is from Jackson which allows for binding the JSON to the Park.java class
    ObjectMapper objectMapper = new ObjectMapper();

    try {

        //first see if we can open a directory for writing
        if (luceneWriter.openIndex()) {
            //get a buffered reader handle to the file
            BufferedReader breader = new BufferedReader(fOpener.getFileForReading());
            String value = null;
            //loop through the file line by line and parse 
            while ((value = breader.readLine()) != null) {
                Park park = objectMapper.readValue(value, Park.class);

                //now submit each park to the lucene writer to add to the index
                luceneWriter.addPark(park);

            }

        } else {
            System.out.println("We had a problem opening the directory for writing");
        }

    } catch (Exception e) {
        System.out.println("Threw exception " + e.getClass() + " :: " + e.getMessage());
    } finally {
        //close out the index and release the lock on the file
        luceneWriter.finish();
    }

}

From source file:spatialluceneindexer.Main.java

/**
 * @param args the command line arguments
 *///  w ww. j  a v a 2 s . c om
public static void main(String[] args) {

    System.out.println("Starting to create the index");

    //Open the file of JSON for reading
    FileOpener fOpener = new FileOpener("parks.json");

    //Create the object for writing
    LuceneWriter luceneWriter = new LuceneWriter("indexDir");

    //This is from Jackson which allows for binding the JSON to the Park.java class
    ObjectMapper objectMapper = new ObjectMapper();

    try {

        //first see if we can open a directory for writing
        if (luceneWriter.openIndex()) {
            //get a buffered reader handle to the file
            BufferedReader breader = new BufferedReader(fOpener.getFileForReading());
            String value = null;
            //loop through the file line by line and parse 
            while ((value = breader.readLine()) != null) {
                Park park = objectMapper.readValue(value, Park.class);

                //now submit each park to the lucene writer to add to the index
                luceneWriter.addPark(park);

            }

        } else {
            System.out.println("We had a problem opening the directory for writing");
        }

    } catch (Exception e) {
        System.out.println("Threw exception " + e.getClass() + " :: " + e.getMessage());
    } finally {
        luceneWriter.finish();
    }

    System.out.println("Finished created the index");
}

From source file:MondrianService.java

public static void main(String[] arg) {
    System.out.println("Starting Mondrian Connector for Infoveave");
    Properties prop = new Properties();
    InputStream input = null;/*w w  w.  j a  v a 2 s.  c  o m*/
    int listenPort = 9998;
    int threads = 100;
    try {
        System.out.println("Staring from :" + getSettingsPath());
        input = new FileInputStream(getSettingsPath() + File.separator + "MondrianService.properties");
        prop.load(input);
        listenPort = Integer.parseInt(prop.getProperty("port"));
        threads = Integer.parseInt(prop.getProperty("maxThreads"));
        if (input != null) {
            input.close();
        }
        System.out.println("Found MondrianService.Properties");
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }

    port(listenPort);
    threadPool(threads);
    enableCORS("*", "*", "*");

    ObjectMapper mapper = new ObjectMapper();
    MondrianConnector connector = new MondrianConnector();
    get("/ping", (request, response) -> {
        response.type("application/json");
        return "\"Here\"";
    });

    post("/cubes", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetCubes(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/measures", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetMeasures(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/dimensions", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetDimensions(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/cleanCache", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.CleanCubeCache(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/executeQuery", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            String content = mapper.writeValueAsString(connector.ExecuteQuery2(queryObject));
            return content;
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });
}

From source file:com.sonatype.nexus.perftest.PerformanceTestRunner.java

public static void main(String[] args) throws Exception {
    final Nexus nexus = new Nexus();
    ObjectMapper mapper = new XmlMapper();
    mapper.setInjectableValues(new InjectableValues() {
        @Override/*from  w  w w  .  ja v  a  2  s.c  o  m*/
        public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty,
                Object beanInstance) {
            if (Nexus.class.getName().equals(valueId)) {
                return nexus;
            }
            return null;
        }
    });
    File src = new File(args[0]).getCanonicalFile();
    System.out.format("Using test configuration %s\n", src);
    PerformanceTest test = mapper.readValue(src, PerformanceTest.class);
    test.run();
    System.out.println("Exit");
    System.exit(0);
}

From source file:de.raion.xmppbot.XmppBot.java

/**
 * starting the xmppbot/*from   www . j a v  a 2  s  .  c  o  m*/
 * @param args arguments, arg[0] should link to the named configfile, otherwise
 *         Enbot will lookup for <code>xmppbot.json</code> in the workingdirectory
 * @throws Exception if an not expected Exception occure
 */
public static void main(String[] args) throws Exception {

    XmppBot bot = new XmppBot();

    File configFile = null;

    if (args.length == 0) {
        String fileName = bot.getContext().getString("xmppbot.configuration.filename", "xmppbot.json");
        configFile = new File(fileName);

    } else {
        configFile = new File(args[0]);
    }

    log.info(configFile.getAbsolutePath());

    ObjectMapper mapper = new ObjectMapper();
    BotConfiguration config = mapper.readValue(configFile, BotConfiguration.class);

    log.debug(config.toString());

    bot.init(config);
    TimeUnit.HOURS.sleep(1);

}

From source file:org.honeybee.coderally.Modelt.java

public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    InputStream assets = null;//from w  w  w . j a  va  2 s .c om
    TrackData data;

    try {
        assets = Tracks.class.getResourceAsStream("/tracks/space/track.json");
        data = mapper.readValue(assets, TrackData.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(assets);
    }
    Schumacher schewy = new Modelt.Schumacher();

    Walker walker = new Walker(data.checkpoints, schewy);
    schewy.buildMap(data.checkpoints);
    walker.showIt();

}

From source file:com.sonatype.nexus.perftest.PerformanceTestAsserter.java

public static void main(String[] args) throws Exception {

    final Nexus nexus = new Nexus();
    ObjectMapper mapper = new XmlMapper();

    mapper.setInjectableValues(new InjectableValues() {
        @Override/*from  www  . ja v  a2 s . c  o m*/
        public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty,
                Object beanInstance) {
            if (Nexus.class.getName().equals(valueId)) {
                return nexus;
            }
            return null;
        }
    });

    File src = new File(args[0]).getCanonicalFile();
    String name = src.getName().substring(0, src.getName().lastIndexOf("."));

    Collection<ClientSwarm> swarms = mapper.readValue(src, PerformanceTest.class).getSwarms();

    List<Metric> metrics = new ArrayList<>();
    for (ClientSwarm swarm : swarms) {
        metrics.add(swarm.getMetric());
    }

    System.out.println("Test " + name + " metrics:" + metrics);
    assertTest(name, metrics);
    System.out.println("Exit");
    System.exit(0);
}

From source file:com.linecorp.platform.channel.sample.Main.java

public static void main(String[] args) {

    BusinessConnect bc = new BusinessConnect();

    /**//www . ja  va2s  .c om
     * Prepare the required channel secret and access token
     */
    String channelSecret = System.getenv("CHANNEL_SECRET");
    String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN");
    if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null
            || channelAccessToken.isEmpty()) {
        System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined.");
        return;
    }

    port(Integer.valueOf(System.getenv("PORT")));
    staticFileLocation("/public");

    /**
     * Define the callback url path
     */
    post("/events", (request, response) -> {
        String requestBody = request.body();

        /**
         * Verify whether the channel signature is valid or not
         */
        String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE");
        if (channelSignature == null || channelSignature.isEmpty()) {
            response.status(400);
            return "Please provide valid channel signature and try again.";
        }
        if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) {
            response.status(401);
            return "Invalid channel signature.";
        }

        /**
         * Parse the http request body
         */
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        EventList events;
        try {
            events = objectMapper.readValue(requestBody, EventList.class);
        } catch (IOException e) {
            response.status(400);
            return "Invalid request body.";
        }

        ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken);

        /**
         * Process the incoming messages/operations one by one
         */
        List<String> toUsers;
        for (Event event : events.getResult()) {
            switch (event.getEventType()) {
            case Constants.EventType.MESSAGE:
                toUsers = new ArrayList<>();
                toUsers.add(event.getContent().getFrom());

                // @TODO: We strongly suggest you should modify this to process the incoming message/operation async
                bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient);
                break;
            case Constants.EventType.OPERATION:
                if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) {
                    String newFriend = event.getContent().getParams().get(0);
                    Profile profile = bc.getProfile(newFriend, apiHttpClient);
                    String displayName = profile == null ? "Unknown" : profile.getDisplayName();
                    toUsers = new ArrayList<>();
                    toUsers.add(newFriend);
                    bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient);
                    Connection connection = null;
                    connection = DatabaseUrl.extract().getConnection();
                    toUsers = bc.getFriends(newFriend, connection);
                    if (toUsers.size() > 0) {
                        bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!",
                                apiHttpClient);
                    }
                    bc.addFriend(newFriend, displayName, connection);
                    if (connection != null) {
                        connection.close();
                    }
                }
                break;
            default:
                // Unknown type?
            }
        }
        return "Events received successfully.";
    });

    get("/", (request, response) -> {
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("message", "Hello World!");
        return new ModelAndView(attributes, "index.ftl");
    }, new FreeMarkerEngine());
}

From source file:com.vethrfolnir.TestJsonAfterUnmarshal.java

public static void main(String[] args) throws Exception {
    ArrayList<TestThing> tsts = new ArrayList<>();

    for (int i = 0; i < 21; i++) {

        final int nr = i;
        tsts.add(new TestThing() {
            {/*from  w w w.  jav a2  s.  c o  m*/
                id = 1028 * nr + 256;
                name = "Name-" + nr;
            }
        });
    }

    ObjectMapper mp = new ObjectMapper();
    mp.setVisibilityChecker(mp.getDeserializationConfig().getDefaultVisibilityChecker()
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE));

    mp.configure(SerializationFeature.INDENT_OUTPUT, true);

    ByteArrayOutputStream br = new ByteArrayOutputStream();
    mp.writeValue(System.err, tsts);
    mp.writeValue(br, tsts);

    ByteArrayInputStream in = new ByteArrayInputStream(br.toByteArray());
    tsts = mp.readValue(in, new TypeReference<ArrayList<TestThing>>() {
    });

    System.err.println();
    System.out.println("Got: " + tsts);
}

From source file:com.amazonaws.services.iot.client.sample.shadowEcho.ShadowEchoSample.java

public static void main(String args[])
        throws IOException, AWSIotException, AWSIotTimeoutException, InterruptedException {
    CommandArguments arguments = CommandArguments.parse(args);
    initClient(arguments);//from   w w w  .  j  av a  2  s.co m

    String thingName = arguments.getNotNull("thingName", SampleUtil.getConfig("thingName"));
    AWSIotDevice device = new AWSIotDevice(thingName);

    awsIotClient.attach(device);
    awsIotClient.connect();

    // Delete existing document if any
    device.delete();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Thing thing = new Thing();

    while (true) {
        long desired = thing.state.desired.counter;
        thing.state.reported.counter = desired;
        thing.state.desired.counter = desired + 1;

        String jsonState = objectMapper.writeValueAsString(thing);

        try {
            // Send updated document to the shadow
            device.update(jsonState);
            System.out.println(System.currentTimeMillis() + ": >>> " + jsonState);
        } catch (AWSIotException e) {
            System.out.println(System.currentTimeMillis() + ": update failed for " + jsonState);
            continue;
        }

        try {
            // Retrieve updated document from the shadow
            String shadowState = device.get();
            System.out.println(System.currentTimeMillis() + ": <<< " + shadowState);

            thing = objectMapper.readValue(shadowState, Thing.class);
        } catch (AWSIotException e) {
            System.out.println(System.currentTimeMillis() + ": get failed for " + jsonState);
            continue;
        }

        Thread.sleep(1000);
    }

}