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:it.uniroma2.sag.kelp.examples.main.SerializationExample.java

public static void main(String[] args) {
    try {//from w w  w. j a  va 2 s . c  o  m
        // Read a dataset into a trainingSet variable
        SimpleDataset trainingSet = new SimpleDataset();
        trainingSet.populate("src/main/resources/iris_dataset/iris_train.klp");

        SimpleDataset testSet = new SimpleDataset();
        testSet.populate("src/main/resources/iris_dataset/iris_test.klp");

        // print some statistics
        System.out.println("Training set statistics");
        System.out.print("Examples number ");
        System.out.println(trainingSet.getNumberOfExamples());

        List<Label> classes = trainingSet.getClassificationLabels();

        for (Label l : classes) {
            System.out.println(
                    "Training Label " + l.toString() + " " + trainingSet.getNumberOfPositiveExamples(l));
            System.out.println(
                    "Training Label " + l.toString() + " " + trainingSet.getNumberOfNegativeExamples(l));

            System.out.println("Test Label " + l.toString() + " " + testSet.getNumberOfPositiveExamples(l));
            System.out.println("Test Label " + l.toString() + " " + testSet.getNumberOfNegativeExamples(l));
        }

        // Kernel for the first representation (0-index)
        Kernel linear = new LinearKernel("0");
        // Normalize the linear kernel
        NormalizationKernel normalizedKernel = new NormalizationKernel(linear);
        // instantiate an svmsolver
        BinaryCSvmClassification svmSolver = new BinaryCSvmClassification();
        svmSolver.setKernel(normalizedKernel);
        svmSolver.setCp(2);
        svmSolver.setCn(1);

        OneVsAllLearning ovaLearner = new OneVsAllLearning();
        ovaLearner.setBaseAlgorithm(svmSolver);
        ovaLearner.setLabels(classes);

        // One can serialize the learning algorihtm
        ObjectSerializer serializer = new JacksonSerializerWrapper();
        String algoDescr = serializer.writeValueAsString(ovaLearner);
        System.out.println(algoDescr);

        // If the learning algorithm is specifified in the Json syntax
        // it is possible to load it in this way:
        ObjectMapper mapper = new ObjectMapper();
        ovaLearner = (OneVsAllLearning) mapper.readValue(algoDescr, OneVsAllLearning.class);
        // the ovaLearner object is the one loaded from the Json description
        // refer to the api documentation to read a learning algorithm from a file

        // learn and get the prediction function
        ovaLearner.learn(trainingSet);
        Classifier f = ovaLearner.getPredictionFunction();

        // it is possible also to serialize a classification function
        // that includes the model (e.g. the support vectors).
        String classificationFunctionDescr = serializer.writeValueAsString(f);
        System.out.println(classificationFunctionDescr);

        // and obiovously a classification function can be loaded in memory from
        // its json representation
        f = (Classifier) mapper.readValue(classificationFunctionDescr, Classifier.class);

        // classify examples and compute some statistics
        int correct = 0;
        for (Example e : testSet.getExamples()) {
            ClassificationOutput p = f.predict(testSet.getNextExample());
            //            System.out.println(p.getPredictedClasses());
            if (e.isExampleOf(p.getPredictedClasses().get(0))) {
                correct++;
            }
        }

        System.out.println("Accuracy: " + ((float) correct / (float) testSet.getNumberOfExamples()));
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:es.upv.grc.grcbox.server.GrcBoxServerApplication.java

/**
 * Launches the application with an HTTP server.
 * /*from   w  ww  .  j a v a 2s.c o m*/
 * @param args
 *            The arguments.
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    //Load Config File
    LOG.info("Working Directory = " + System.getProperty("user.dir"));
    File file = new File("./config.json");
    ObjectMapper mapper = new ObjectMapper();
    config = mapper.readValue(file, GrcBoxConfig.class);
    if (!Collections.disjoint(config.getInnerInterfaces(), config.getOuterInterfaces())) {
        System.err.print("InnerInterfaces and Outerinterfaces has elements in common. Aborting execution.");
        System.exit(-1);
    }

    LinkedList<String> innerInterfaces = config.getInnerInterfaces();
    RulesDB.setInnerInterfaces(innerInterfaces);
    RulesDB.initialize();
    for (String string : innerInterfaces) {
        startServer(string);
    }
}

From source file:de.oth.keycloak.InitKeycloakServer.java

public static void main(String[] args) {
    CheckParams checkParams = CheckParams.create(args, System.out, InitKeycloakServer.class.getName());
    if (checkParams == null) {
        System.exit(1);//w w w  .ja  v a2 s  . c o m
    }
    try {
        String server = checkParams.getServer();
        String realm = checkParams.getRealm();
        String user = checkParams.getUser();
        String pwd = checkParams.getPwd();
        String clientStr = checkParams.getClient();
        String secret = checkParams.getSecret();
        String initFileStr = checkParams.getInitFile();
        File initFile = new File(initFileStr);
        if (!initFile.isFile()) {
            URL url = InitKeycloakServer.class.getClassLoader().getResource(initFileStr);
            if (url != null) {
                initFile = new File(url.getFile());
                if (!initFile.isFile()) {
                    log.error("init file does not exist: " + initFile);
                    System.exit(1);
                }
            } else {
                log.error("init file does not exist: " + initFile);
                System.exit(1);
            }
        }
        Keycloak keycloak = (secret == null) ? Keycloak.getInstance(server, realm, user, pwd, clientStr)
                : Keycloak.getInstance(server, realm, user, pwd, clientStr, secret);

        ObjectMapper mapper = new ObjectMapper();
        RealmsConfig realmsConfig = mapper.readValue(initFile, RealmsConfig.class);

        if (realmsConfig != null) {
            List<RealmConfig> realmList = realmsConfig.getRealms();
            if (realmList == null || realmList.isEmpty()) {
                log.error("no realms config found 1");
                return;
            }
            for (RealmConfig realmConf : realmList) {
                addRealm(keycloak, realmConf);
            }
        } else {
            log.error("no realms config found 2");
        }
    } catch (Exception e) {
        log.error(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:edu.sdsc.scigraph.owlapi.loader.BatchOwlLoader.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from w w w  .  j  a v  a2  s.  com
    try {
        cmd = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BatchOwlLoader.class.getSimpleName(), getOptions());
        System.exit(-1);
    }

    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    OwlLoadConfiguration config = mapper.readValue(new File(cmd.getOptionValue('c').trim()),
            OwlLoadConfiguration.class);
    load(config);
    // TODO: Is Guice causing this to hang? #44
    System.exit(0);
}

From source file:test.jackson.JacksonNsgiRegister.java

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

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    RegisterContextRequest rcr = objectMapper.readValue(ngsiRcr, RegisterContextRequest.class);

    System.out.println(objectMapper.writeValueAsString(rcr));

    LinkedHashMap association = (LinkedHashMap) rcr.getContextRegistration().get(0).getContextMetadata().get(0)
            .getValue();//  w w w.  ja  v  a2s . c  om
    Association assocObject = objectMapper.convertValue(association, Association.class);
    System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(1).getContextMetadata().get(0);

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}

From source file:com.chiralBehaviors.autoconfigure.debug.TemplateDebugger.java

public static void main(String[] argv) throws JsonParseException, JsonMappingException, IOException {
    if (argv.length == 0) {
        System.out.println("Usage: TemplateDebugger <scenario file>+");
        System.exit(1);//  w  w w . j a  v  a  2 s. c o m
    }
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    for (String fileName : argv) {
        FileInputStream yaml = new FileInputStream(fileName);
        TemplateDebugger debugger = mapper.readValue(yaml, TemplateDebugger.class);
        System.out.println("======================================");
        System.out.println(String.format("Rendered output of %s", yaml));
        System.out.println("======================================");
        System.out.println();
        System.out.println(debugger.render());
        System.out.println();
        System.out.println("======================================");
        System.out.println();
        System.out.println();
    }
}

From source file:com.tsavo.trade.TradeBot.java

public static void main(String[] args)
        throws InterruptedException, EngineException, AudioException, EngineStateError, PropertyVetoException,
        KeyManagementException, NoSuchAlgorithmException, ExchangeException, NotAvailableFromExchangeException,
        NotYetImplementedForExchangeException, IOException {
    //initSSL(); // Setup the SSL certificate to interact with mtgox over
    // secure http.

    //System.setProperty("org.joda.money.CurrencyUnitDataProvider", "org.joda.money.CryptsyCurrencyUnitDataProvider");
    Portfolio portfolio = new Portfolio();
    File dest = new File("portfolio.json");
    if (dest.exists()) {
        InputStream file;/*from   w w  w  .  j  av  a  2s  .c  o m*/
        try {
            file = new FileInputStream(dest);
            InputStream buffer = new BufferedInputStream(file);
            // ObjectInput input;
            // input = new ObjectInputStream(buffer);
            ObjectMapper mapper = new ObjectMapper();
            portfolio = mapper.readValue(buffer, Portfolio.class);
            file.close();
            // input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Finder finder = new Finder(portfolio);
    System.out.println("System initialized successfully. Looking for opportunities...");
    while (true) {
        finder.run();
        Thread.sleep(10000);
    }
}

From source file:uk.ac.surrey.ee.iot.fiware.ngsi9.semantic.SemanticConverter.java

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

    SemanticConverter ri = new SemanticConverter();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    RegisterContextRequest rcr = new RegisterContextRequest();
    try {/* w ww. j  a v  a 2  s .  c om*/
        rcr = objectMapper.readValue(ri.NGSI_FILE, RegisterContextRequest.class);
    } catch (Exception e) {

    }
    ri.createJenaModel(rcr);

    //        //hMap.put("class", "OnDeviceResource"); 
    ////        hMap.put("class", new String[]{"ResourceService"});
    //        hMap.put("class", new String[]{"VirtualEntity"});
    ////        hMap.put("hasID", new String[]{"Resource_1"});
    //        hMap.put("hasID", new String[]{"VirtualEntity_1"});
    //        hMap.put("hasAttributeType", new String[]{"http://purl.oclc.org/NET/ssnx/qu/quantity#temperature"});     
    ////        hMap.put("isHostedOn", "PloggBoard_49_BA_01_light");
    ////        hMap.put("hasType", "Sensor");
    ////        hMap.put("hasName", "lightsensor49_BA_01");
    ////        hMap.put("isExposedThroughService", "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#49_BA_01_light_sensingService");
    ////        hMap.put("hasTag", "light sensor 49,1st,BA,office");
    //        hMap.put("hasLatitude", new String[]{"51.243455"});
    ////        hMap.put("hasGlobalLocation", "http://www.geonames.org/2647793/");
    ////        hMap.put("hasResourceID", "Resource_53_BA_power_sensor");
    ////        hMap.put("hasLocalLocation", "http://www.surrey.ac.uk/ccsr/ontologies/LocationModel.owl#U49");
    //        hMap.put("hasAltitude", new String[]{""});
    //        hMap.put("hasLongitude", new String[]{"-0.588088"});
    ////        hMap.put("hasTimeOffset", "20");
    //
    //        //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#";
    //        //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/VirtualEntityModel.owl#";
    //        //ri.ONT_FILE = "web/IoTA-Models/VirtualEntityModel.owl";
    //        ri.createJenaModel(hMap);
}

From source file:test.jackson.JacksonNsgiDiscover.java

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

    ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    DiscoveryContextAvailabilityRequest dcar = objectMapper.readValue(ngsiRcr,
            DiscoveryContextAvailabilityRequest.class);

    //        System.out.println(objectMapper.writeValueAsString(dcar));
    System.out.println(dcar.getRestriction().getOperationScope().get(1).getScopeValue());

    LinkedHashMap shapeHMap = (LinkedHashMap) dcar.getRestriction().getOperationScope().get(1).getScopeValue();
    //        Association assocObject =  objectMapper.convertValue(shapeHMap, Association.class);
    //        System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    Shape shape = objectMapper.convertValue(shapeHMap, Shape.class);
    System.out.println("Deserialized Class: " + shape.getClass().getSimpleName());
    System.out.println("VALUE: " + shape.getPolygon().getVertices().get(2).getLatitude());
    System.out.println("VALUE: " + shape.getCircle());
    if (!(shape.getCircle() == null))
        System.out.println("This is null");

    Polygon polygon = shape.getPolygon();
    int vertexSize = polygon.getVertices().size();
    Coordinate[] coords = new Coordinate[vertexSize];

    final ArrayList<Coordinate> points = new ArrayList<>();
    for (int i = 0; i < vertexSize; i++) {
        Vertex vertex = polygon.getVertices().get(i);
        points.add(new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude())));
        coords[i] = new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude()));
    }//w  w w  .  j  av  a2 s  .c  o m
    points.add(new Coordinate(Double.valueOf(polygon.getVertices().get(0).getLatitude()),
            Double.valueOf(polygon.getVertices().get(0).getLongitude())));

    final GeometryFactory gf = new GeometryFactory();

    final Coordinate target = new Coordinate(49, -0.6);
    final Point point = gf.createPoint(target);

    Geometry shapeGm = gf.createPolygon(
            new LinearRing(new CoordinateArraySequence(points.toArray(new Coordinate[points.size()])), gf),
            null);
    //    Geometry shapeGm = gf.createPolygon(coords);    
    System.out.println(point.within(shapeGm));

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}

From source file:jeplus.data.RVX.java

/**
 * Tester/*from   w w  w . j  a v  a 2s  .  c  om*/
 * @param args 
 * @throws java.io.IOException 
 */
public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
    RVX rvx = mapper.readValue(new File("my.rvx"), RVX.class);
    mapper.writeValue(new File("user-modified.json"), rvx);
    System.exit(0);
}