Java Code Examples for org.boon.json.JsonFactory#create()

The following examples show how to use org.boon.json.JsonFactory#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClusterTest.java    From jdbc-cb with Apache License 2.0 6 votes vote down vote up
@Test
public void testBadInstance() throws Exception
{

    Cluster cluster = ((ProtocolImpl)((CBConnection) con).protocol).getCluster();

    String endpoint = "{\"cluster\":\"default\",\"name\":\"10.168.209.119\",\"queryEndpoint\":\"http://10.168.209.119:8093/query/service\"," +
            "\"adminEndpoint\":\"http://10.168.209.119:8093/admin\",\"options\":null}";

    ObjectMapper mapper = JsonFactory.create();
    Map <String,Object> instanceEndpoint = (Map)mapper.fromJson(endpoint);

    cluster.addEndPoint(instanceEndpoint);

    assertNotNull(con);
    Statement statement = con.createStatement();
    assertNotNull(statement);

    // there are only 4 endpoints we added 1 which is 5
    for (int i = 0; i++< 6;)
    {

        int inserted = statement.executeUpdate("INSERT INTO default  (KEY, VALUE) VALUES ( 'K" + i +"'," + i +")");
        assertEquals(1, inserted);
    }
}
 
Example 2
Source File: Bug199_2.java    From boon with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Builder builder = new Builder();
    MetadataImpl metadataImpl = builder.getMetadata();

    JsonSerializerFactory jsonSerializerFactory=new JsonSerializerFactory().usePropertyOnly();
    ObjectMapper mapper = JsonFactory.create(null, jsonSerializerFactory);
    String json = mapper.writeValueAsString(metadataImpl);
    System.out.println("=============" + json);


    File file = new File("metadata.json");
    FileWriter writer = new FileWriter(file);
    mapper.toJson(metadataImpl, writer);
    writer.close();
    Path path = Paths.get(file.toString());
    InputStream inputStream = Files.newInputStream(path);


    MetadataImpl object = JsonFactory.create().readValue(inputStream,
            MetadataImpl.class);
    inputStream.close();

    System.out.println("after deserialization"
            + mapper.writeValueAsString(object));

}
 
Example 3
Source File: TestSQLJson.java    From jdbc-cb with Apache License 2.0 5 votes vote down vote up
@Test
public void setSqlJson() throws Exception
{
    String json = "{\n" +
            "  \"emailAddress\": \"[email protected]\",\n" +
            "  \"type\": \"customer\",\n" +
            "  \"dateLastActive\": \"2014-05-06T15:52:14Z\",\n" +
            "  \"firstName\": \"Darrin\",\n" +
            "  \"phoneNumber\": \"497-854-2229 x000\",\n" +
            "  \"postalCode\": \"45603-9112\",\n" +
            "  \"lastName\": \"Ortiz\",\n" +
            "  \"ccInfo\": {\n" +
            "    \"cardNumber\": \"1234-2121-1221-1211\",\n" +
            "    \"cardType\": \"discover\",\n" +
            "    \"cardExpiry\": \"2012-11-12\"\n" +
            "  },\n" +
            "  \"dateAdded\": \"2013-06-10T15:52:14Z\",\n" +
            "  \"state\": \"IN\",\n" +
            "  \"customerId\": \"customer10\"\n" +
            "}";

    ObjectMapper mapper = JsonFactory.create();
    Map <String,Object> jsonObject = mapper.readValue(json, Map.class);

    String query = "insert into default (key,value) values (?,?)";

    SQLJSON sqljson = ((CBConnection)con).createSQLJSON();
    sqljson.setMap( jsonObject );
    try (PreparedStatement pstmt = con.prepareStatement(query))
    {
        pstmt.setString(1,"customer1");
        ((CBPreparedStatement)pstmt).setSQLJSON(2,sqljson);
        assertEquals(1,pstmt.executeUpdate());
    }
}
 
Example 4
Source File: Bug199.java    From boon with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {

    JsonSerializerFactory factory = new JsonSerializerFactory();
    factory.usePropertyOnly();
    ObjectMapper mapper = JsonFactory.create(null, factory);

    User user = new User();
    EnumMap<Gender,User> map = new EnumMap<Gender, User>(Gender.class);
    map.put(Gender.FEMALE, user);

    puts(map);
    puts(mapper.writeValueAsString( map));
}
 
Example 5
Source File: ProtocolImpl.java    From jdbc-cb with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public Cluster handleClusterResponse(CloseableHttpResponse response) throws IOException
{
    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    String string = EntityUtils.toString(entity);
    logger.trace ("Cluster response {}", string);
    ObjectMapper mapper = JsonFactory.create();

    // has to be an object here since we can get a 404 back which is a string
    Object jsonArray = mapper.fromJson(string);

    String message="";

    switch (status)
    {
        case 200:
            //noinspection unchecked
            rewriteURLs((List<Map>)jsonArray);
            return new Cluster((List)jsonArray, ssl);
        case 400:
            message = "Bad Request";
            break;
        case 401:
            message = "Unauthorized Request credentials are missing or invalid";
            break;
        case 403:
            message = "Forbidden Request: read only violation or client unauthorized to modify";
            break;
        case 404:
            message = "Not found: Check the URL";
            break;
        case 405:
            message = "Method not allowed: The REST method type in request is supported";
            break;
        case 409:
            message = "Conflict: attempt to create a keyspace or index that already exists";
            break;
        case 410:
            message = "Gone: The server is doing a graceful shutdown";
            break;
        case 500:
            message = "Internal server error: unforeseen problem processing the request";
            break;
        case 503:
            message = "Service Unavailable: there is an issue preventing the request from being serv serviced";
            break;
    }
    throw new ClientProtocolException(message +": " + status);

}
 
Example 6
Source File: ProtocolImpl.java    From jdbc-cb with Apache License 2.0 4 votes vote down vote up
public int [] executeBatch() throws SQLException
{
    try
    {
        Instance instance = getNextEndpoint();
        String url = instance.getEndpointURL(ssl);

        HttpPost httpPost = new HttpPost( url );
        httpPost.setHeader("Accept", "application/json");

        Map <String,Object> parameters = new HashMap<String,Object>();
        addOptions(parameters);
        for (String query:batchStatements)
        {
            parameters.put(STATEMENT, query);
        }

        CloseableHttpResponse response = httpClient.execute(httpPost);
        int status = response.getStatusLine().getStatusCode();

        if ( status >= 200 && status < 300 )
        {
            HttpEntity entity = response.getEntity();
            ObjectMapper mapper = JsonFactory.create();
            @SuppressWarnings("unchecked") Map <String,Object> jsonObject = (Map)mapper.fromJson(EntityUtils.toString(entity));

            String statusString = (String)jsonObject.get("status");

            if (statusString.equals("errors"))
            {
                List errors= (List)jsonObject.get("errors");
                Map error = (Map)errors.get(0);
                throw new SQLException((String)error.get("msg"));
            }
            else if (statusString.equals("success"))
            {
                Map  metrics = (Map)jsonObject.get("metrics");
                if ( metrics.containsKey("mutationCount") )
                {
                    updateCount = (int)metrics.get("mutationCount");
                    return new int [0];
                }
                if ( metrics.containsKey("resultCount") )
                {
                   // TODO FIX ME resultSet = new CBResultSet(jsonObject);
                    return new int [0];
                }
            }
            else if (statusString.equals("running"))
            {
                return new int [0];
            }
            else if (statusString.equals("completed"))
            {
                return new int [0];
            }
            else if (statusString.equals("stopped"))
            {
                return new int [0];
            }
            else if (statusString.equals("timeout"))
            {
                return new int [0];
            }
            else if (statusString.equals("fatal"))
            {
                return new int [0];
            }

            else
            {
                //logger.error("Unexpected status string {} for query {}", statusString, query);
                throw new SQLException("Unexpected status: " + statusString);
            }
        }

        else
        {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    }
    catch (Exception ex)
    {
        //logger.error ("Error executing update query {} {}", query, ex.getMessage());
        throw new SQLException("Error executing update",ex.getCause());
    }
    return new int [0];

}
 
Example 7
Source File: Bug312.java    From boon with Apache License 2.0 4 votes vote down vote up
@Test
public void testWithMapUsingFactory() {
    JsonParserFactory jsonParserFactory = new JsonParserFactory()
            .useFieldsFirst()
            .lax() //allow loose parsing of JSON like JSON Smart
            .setCharset( StandardCharsets.UTF_8 ) //Set the standard charset, defaults to UTF_8
            .setLazyChop( true ) //similar to chop but only does it after map.get
            ;

    JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory()
            .useFieldsFirst() //one of these
                    //.addPropertySerializer(  )  customize property output
                    //.addTypeSerializer(  )      customize type output
            .useJsonFormatForDates() //use json dates
                    //.addFilter(  )   add a property filter to exclude properties
            .includeEmpty().includeNulls().includeDefaultValues() //override defaults
            .handleComplexBackReference() //uses identity map to track complex back reference and avoid them
            .setHandleSimpleBackReference( true ) //looks for simple back reference for parent
            .setCacheInstances( true ) //turns on caching for immutable objects
            ;

    final ObjectMapper objectMapper = JsonFactory.create(jsonParserFactory, jsonSerializerFactory);


    MyClass myClass = new MyClass();
    final String json = objectMapper.toJson(myClass);

    puts(json);

    final MyClass myClass1 = objectMapper.readValue(json, MyClass.class);


    assertEquals("foo", myClass1.string);

    assertEquals(1, myClass1.integer);


    assertNull(myClass1.map);


}
 
Example 8
Source File: Bug297.java    From boon with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

            // create object
            MyObject myobject = new MyObject();
            // add a title and attributes
            myobject.setTitle("title with \" double qoutes");
            Map<String,Object> attributes = new HashMap<>();
            attributes.put("author", "author with \" double quotes");
            myobject.setAttrs(attributes);

            // create ObjectMapper
            ObjectMapper mapper = JsonFactory.create();

            // serialize myobject to json
            String myobjectJson = mapper.toJson(myobject);
            System.out.println(myobjectJson);
            // prints: {"title":"title with \" double qoutes","attrs":{"author":"author with \" double quotes"}}
            // parse myobjectJson to an object
            MyObject myobjectParsed = mapper.fromJson(myobjectJson, MyObject.class);

            final boolean equals = myobjectParsed.equals(myobject);

            System.out.println("equals " + equals + " " + myobjectParsed.title);

            System.out.println(myobjectParsed.title);

            System.out.println(myobjectParsed.getAttrs().get("author").getClass().getName());


            puts("\n", myobjectParsed, "\n", myobject);

            // serialize again my myobjectParsed to json
            myobjectJson = mapper.toJson(myobjectParsed);
            System.out.println(myobjectJson);
            // double quoted for attrs are not escaped
            // prints: {"title":"title with \" double qoutes","attrs":{"author":"author with " double quotes"}}


            MyObject myobjectParsed2 = mapper.fromJson(myobjectJson,MyObject.class);
            // Exception in thread "main" org.boon.json.JsonException: expecting current character to be ':' but got '}' with an int value of 125

        }
 
Example 9
Source File: Bug287.java    From boon with Apache License 2.0 4 votes vote down vote up
@Test
public void serializingClassFieldCausesSegFault() {

    SomeClass someClassInstance = new SomeClass(Bug287.class);

    ObjectMapper mapper = JsonFactory.create();

    final String json = mapper.toJson(someClassInstance);

    puts(json);

    SomeClass someClassInstance2 = mapper.readValue("{\"clazz\":\"org.boon.bugs.Bug287\"} ", SomeClass.class);

    ok = someClassInstance2.clazz.getName().equals("org.boon.bugs.Bug287");

}
 
Example 10
Source File: HowToParseJSONInJava.java    From boon with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception{

        Player kevin = new Player("Kevin", "Cricket", 32, 221,
                new int[]{33, 66, 78, 21, 9, 200});

        final ObjectMapper mapper = JsonFactory.create();


        final File file = File.createTempFile("json", "exmaple.json");
        mapper.writeValue(file, kevin);



        Player somePlayer = mapper.readValue(file, Player.class);

        puts("They are equal", somePlayer.equals(kevin));


    }
 
Example 11
Source File: BugReport165AndIssue169.java    From boon with Apache License 2.0 3 votes vote down vote up
@Test
public void test2() {

    Employee employee = new Employee();

    ObjectMapper mapper = JsonFactory.create();

    String json = mapper.toJson(employee);

    puts(json);

    employee.name = "Rick Hightower";

    json = mapper.toJson(employee);

    puts(json);

    employee.birthDate = System.currentTimeMillis() - 60 * 1000 * 24 * 7 * 52 * 29;


    json = mapper.toJson(employee);

    puts(json);

    Employee newEmployee = mapper.fromJson(json, Employee.class);

    puts("New Employee", newEmployee.birthDate, newEmployee.name);


    ok = newEmployee.name.equals("Rick Hightower") && newEmployee.birthDate > 0 || die();

}
 
Example 12
Source File: PartialDataTreeExample.java    From boon with Apache License 2.0 2 votes vote down vote up
public static void main (String... args) {
    File file = new File(".", "src/test/resources/teams.json");
    String path = file.getAbsolutePath().toString();
    puts ("PATH", path);
    puts ("CONTENTS of PATH", IO.read(path));

    /* Jackson style interface. */
    ObjectMapper mapper = JsonFactory.create();
    Object jsonObject = mapper.readValue(file, Object.class);
    puts ("JSON Object", jsonObject);


    /* Using Boon path. */
    puts ("teamInfo", atIndex(jsonObject, "teamInfo"));
    puts("Team Roster", atIndex(jsonObject, "teamInfo.teamRoster"));
    puts("Team Names", atIndex(jsonObject, "teamInfo.teamRoster.teamNames"));


    /* Using Boon style parser (fast). */
    JsonParserAndMapper boonMapper = new JsonParserFactory().create();
    jsonObject = boonMapper.parseFile(path);


    /* Using Boon path. */
    puts ("teamInfo", atIndex(jsonObject, "teamInfo"));
    puts("Team Roster", atIndex(jsonObject, "teamInfo.teamRoster"));
    puts("Team Names", atIndex(jsonObject, "teamInfo.teamRoster.teamNames"));



    /* Using Boon style (easy) 2 parser. */
    jsonObject = Boon.jsonResource(path);


    /* Using Boon path. */
    puts ("teamInfo", atIndex(jsonObject, "teamInfo"));
    puts("Team Roster", atIndex(jsonObject, "teamInfo.teamRoster"));
    puts("Team Names", atIndex(jsonObject, "teamInfo.teamRoster.teamNames"));

    //There is also a Groovy style and a GSON style.

    List<String> teamNames = (List<String>) atIndex(jsonObject, "teamInfo.teamRoster.teamNames");

    puts("Team Names", teamNames);

    Set<String> teamNameSet = set(teamNames);

    puts ("Converted to a set", teamNameSet);


    TeamInfo teamInfo = fromMap((Map<String, Object>) atIndex(jsonObject, "teamInfo"), TeamInfo.class);
    puts(teamInfo);


    TeamRoster teamRoster = fromMap((Map<String, Object>) atIndex(jsonObject, "teamInfo.teamRoster"), TeamRoster.class);
    puts(teamRoster);

}