Example usage for com.fasterxml.jackson.databind JsonNode toString

List of usage examples for com.fasterxml.jackson.databind JsonNode toString

Introduction

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

Prototype

public abstract String toString();

Source Link

Usage

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

private void convertAndParseIfOrAny(String json) throws IOException {
    JsonNode rJSON = p.newNode();//from   www  .  j av  a 2s  .  c  om
    RDBMS r = new RDBMS();
    r.setDialect("oracle");
    r.setSQLMapping(new SQLMapping());
    r.getSQLMapping().setJoins(new ArrayList<Join>());
    r.getSQLMapping().getJoins().add(new Join());
    r.getSQLMapping().getJoins().get(0).setJoinTablesStatement("x");
    r.getSQLMapping().getJoins().get(0).setProjectionMappings(new ArrayList<ProjectionMapping>());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().add(new ProjectionMapping());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setColumn("c");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setField("f");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setSort("s");
    r.getSQLMapping().getJoins().get(0).setTables(new ArrayList<Table>());
    r.getSQLMapping().getJoins().get(0).getTables().add(new Table());
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setAlias("a");
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setName("n");
    r.getSQLMapping().setColumnToFieldMap(new ArrayList<ColumnToField>());
    r.getSQLMapping().getColumnToFieldMap().add(new ColumnToField());
    r.getSQLMapping().getColumnToFieldMap().get(0).setColumn("c");
    r.getSQLMapping().getColumnToFieldMap().get(0).setField("f");
    r.getSQLMapping().getColumnToFieldMap().get(0).setTable("t");
    Operation o = new Operation();
    ArrayList<Expression> expressionList = new ArrayList<Expression>();
    Conditional e4 = new Conditional();
    IfOr ifOr = new IfOr();
    IfFieldCheckValue anIf = new IfFieldCheckValue();
    anIf.setOp("eq");
    anIf.setField(new Path("abc"));
    anIf.setValue("123");
    IfFieldCheckValue anIf2 = new IfFieldCheckValue();
    anIf2.setOp("lt");
    anIf2.setField(new Path("abc"));
    anIf2.setValue("123");
    List asList = Arrays.asList(anIf, anIf2);
    ifOr.setConditions(((List<If>) asList));
    e4.setIf(ifOr);
    Then then = new Then();
    ArrayList<Expression> expressions2 = new ArrayList<Expression>();
    Statement e5 = new Statement();
    e5.setType("delete");
    e5.setSQL("DELETE FROM somewhere WHERE someColumn=someValue");
    expressions2.add(e5);
    then.setExpressions(expressions2);
    e4.setThen(then);
    expressionList.add(e4);
    o.setExpressionList(expressionList);
    r.setDelete(duplicate("delete", o));
    r.setFetch(duplicate("fetch", o));
    r.setInsert(duplicate("insert", o));
    r.setSave(duplicate("save", o));
    r.setUpdate(duplicate("update", o));
    cut.convert(p, rJSON, r);

    Object ro = cut.parse("rdbms", p, JsonUtils.json(json).get("rdbms"));
    JsonNode roJSON = p.newNode();
    cut.convert(p, roJSON, ro);
    assertEqualJson(roJSON.toString(), rJSON.toString());
}

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

private void convertAndParseIfAndAll(String json) throws IOException {
    JsonNode rJSON = p.newNode();/* w w  w  .j  a v  a2 s. c  o m*/
    RDBMS r = new RDBMS();
    r.setDialect("oracle");
    r.setSQLMapping(new SQLMapping());
    r.getSQLMapping().setJoins(new ArrayList<Join>());
    r.getSQLMapping().getJoins().add(new Join());
    r.getSQLMapping().getJoins().get(0).setJoinTablesStatement("x");
    r.getSQLMapping().getJoins().get(0).setProjectionMappings(new ArrayList<ProjectionMapping>());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().add(new ProjectionMapping());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setColumn("c");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setField("f");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setSort("s");
    r.getSQLMapping().getJoins().get(0).setTables(new ArrayList<Table>());
    r.getSQLMapping().getJoins().get(0).getTables().add(new Table());
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setAlias("a");
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setName("n");
    r.getSQLMapping().setColumnToFieldMap(new ArrayList<ColumnToField>());
    r.getSQLMapping().getColumnToFieldMap().add(new ColumnToField());
    r.getSQLMapping().getColumnToFieldMap().get(0).setColumn("c");
    r.getSQLMapping().getColumnToFieldMap().get(0).setField("f");
    r.getSQLMapping().getColumnToFieldMap().get(0).setTable("t");
    Operation o = new Operation();
    ArrayList<Expression> expressionList = new ArrayList<Expression>();
    Conditional e4 = new Conditional();
    IfAnd ifAnd = new IfAnd();
    IfFieldCheckValue anIf = new IfFieldCheckValue();
    anIf.setOp("eq");
    anIf.setField(new Path("abc"));
    anIf.setValue("123");
    IfFieldCheckValue anIf2 = new IfFieldCheckValue();
    anIf2.setOp("lt");
    anIf2.setField(new Path("abc"));
    anIf2.setValue("123");
    List asList = Arrays.asList(anIf, anIf2);
    ifAnd.setConditions(((List<If>) asList));
    e4.setIf(ifAnd);
    Then then = new Then();
    ArrayList<Expression> expressions2 = new ArrayList<Expression>();
    Statement e5 = new Statement();
    e5.setType("delete");
    e5.setSQL("DELETE FROM somewhere WHERE someColumn=someValue");
    expressions2.add(e5);
    then.setExpressions(expressions2);
    e4.setThen(then);
    expressionList.add(e4);
    o.setExpressionList(expressionList);
    r.setDelete(duplicate("delete", o));
    r.setFetch(duplicate("fetch", o));
    r.setInsert(duplicate("insert", o));
    r.setSave(duplicate("save", o));
    r.setUpdate(duplicate("update", o));
    cut.convert(p, rJSON, r);

    Object ro = cut.parse("rdbms", p, JsonUtils.json(json).get("rdbms"));
    JsonNode roJSON = p.newNode();
    cut.convert(p, roJSON, ro);
    assertEqualJson(roJSON.toString(), rJSON.toString());
}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static void setDatabaseProperties(String dbName, String propName, ObjectNode objNode)
        throws IOException {
    InputStream jsonstream = null;
    try {//from ww  w  .j  av a2  s . c o m
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet(
                "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
        HttpResponse response1 = client.execute(getrequest);
        jsonstream = response1.getEntity().getContent();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jnode = mapper.readTree(jsonstream);
        if (!jnode.isNull()) {

            if (!jnode.has(propName)) {
                ((ObjectNode) jnode).putArray(propName).addAll(objNode.withArray(propName));
                //                   System.out.println("when Node is null"+propName + objNode.toString());
            } else {
                if (!jnode.path(propName).isArray()) {
                    System.out.println("property is not array");
                    ((ObjectNode) jnode).putAll(objNode);
                } else {
                    JsonNode member = jnode.withArray(propName);
                    if (objNode.path(propName).isArray()) {
                        ((ArrayNode) member).addAll(objNode.withArray(propName));
                        //                     System.out.println("when Node is not null"+ propName + objNode.withArray(propName).toString());
                    }
                }
            }

            HttpPut put = new HttpPut(
                    "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
            put.addHeader("Content-type", "application/json");
            put.setEntity(new StringEntity(jnode.toString()));

            HttpResponse response2 = client.execute(put);
            HttpEntity respEntity = response2.getEntity();
            if (respEntity != null) {
                String content = EntityUtils.toString(respEntity);
                System.out.println(content);
            }
        } else {
            System.out.println("REST call for database properties returned NULL \n" + jnode.toString() + "\n"
                    + response1.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    } finally {
        if (jsonstream == null) {
        } else {
            jsonstream.close();
        }
    }
}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static void setDatabaseFieldProperties(String dbName, String field_name, String propName,
        ObjectNode objNode) throws IOException {
    InputStream jsonstream = null;
    try {/*from  w ww  .j  a va 2 s  . c  o  m*/
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet(
                "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
        HttpResponse response1 = client.execute(getrequest);
        jsonstream = response1.getEntity().getContent();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jnode = mapper.readTree(jsonstream);
        if (!jnode.isNull() && jnode.has("field")) {
            JsonNode fieldNode = jnode.withArray("field");
            Iterator<JsonNode> fnode = fieldNode.elements();
            while (fnode.hasNext()) {
                JsonNode fnchild = fnode.next();
                if ((fnchild.path("field-name").asText()).equals(field_name)) {
                    //                     System.out.println("Hurray" +fnchild.has(propName));
                    if (!fnchild.has(propName)) {
                        ((ObjectNode) fnchild).putArray(propName).addAll(objNode.withArray(propName));
                        //                     System.out.println("Adding child array include node" + jnode.toString());
                    } else {
                        JsonNode member = fnchild.withArray(propName);
                        ((ArrayNode) member).addAll(objNode.withArray(propName));
                    }

                }
            }

            HttpPut put = new HttpPut(
                    "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json");
            put.addHeader("Content-type", "application/json");
            put.setEntity(new StringEntity(jnode.toString()));

            HttpResponse response2 = client.execute(put);
            HttpEntity respEntity = response2.getEntity();
            if (respEntity != null) {
                String content = EntityUtils.toString(respEntity);
                System.out.println(content);
            }
        } else {
            System.out.println("REST call for database properties returned NULL \n" + jnode.toString() + "\n"
                    + response1.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    } finally {
        if (jsonstream == null) {
        } else {
            jsonstream.close();
        }
    }
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.TestIkanowV1SyncService_LibraryJars.java

@Test
public void test_puttingItAllTogether()
        throws JsonProcessingException, IOException, ParseException, InterruptedException, ExecutionException {

    @SuppressWarnings("unchecked")
    ICrudService<JsonNode> v1_share_db = this._service_context.getCoreManagementDbService()
            .getUnderlyingPlatformDriver(ICrudService.class, Optional.of("social.share")).get();

    v1_share_db.deleteDatastore().get();

    IManagementCrudService<SharedLibraryBean> library_db = this._service_context.getCoreManagementDbService()
            .getSharedLibraryStore();//  w w  w  .  j  a v a 2 s.  c  o m

    library_db.deleteDatastore().get();

    // Create 2 V1 sources

    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final JsonNode v1_share_1 = mapper
            .readTree(this.getClass().getResourceAsStream("test_v1_sync_sample_share.json"));
    final JsonNode v1_share_2 = mapper
            .readTree(this.getClass().getResourceAsStream("test_v1_sync_sample_share.json"));
    final JsonNode v1_share_3 = mapper
            .readTree(this.getClass().getResourceAsStream("test_v1_sync_sample_share.json"));

    ((ObjectNode) v1_share_2).set("_id", new TextNode("655d44e3347d336b3e8c4cbe"));
    ((ObjectNode) v1_share_2).set("title", new TextNode("/app/aleph2/library/misc/library2.jar"));

    ((ObjectNode) v1_share_3).set("_id", new TextNode("755d44e3347d336b3e8c4cbe"));
    ((ObjectNode) v1_share_3).set("title", new TextNode("/app/aleph2/library/misc/library3.jar"));

    //final SharedLibraryBean share1 = IkanowV1SyncService_LibraryJars.getLibraryBeanFromV1Share(v1_share_1);
    final SharedLibraryBean share2 = IkanowV1SyncService_LibraryJars.getLibraryBeanFromV1Share(v1_share_2);
    final SharedLibraryBean share3 = IkanowV1SyncService_LibraryJars.getLibraryBeanFromV1Share(v1_share_3);

    final DBCollection dbc = v1_share_db.getUnderlyingPlatformDriver(DBCollection.class, Optional.empty())
            .get();
    final DBObject v1_share_1_dbo = (DBObject) JSON.parse(v1_share_1.toString());
    v1_share_1_dbo.put("_id", new ObjectId(v1_share_1.get("_id").asText()));
    v1_share_1_dbo.removeField("binaryId");
    final DBObject v1_share_2_dbo = (DBObject) JSON.parse(v1_share_2.toString());
    v1_share_2_dbo.put("_id", new ObjectId(v1_share_2.get("_id").asText()));
    v1_share_2_dbo.put("modified", new Date());
    v1_share_2_dbo.removeField("binaryId");
    final DBObject v1_share_3_dbo = (DBObject) JSON.parse(v1_share_3.toString());
    v1_share_3_dbo.put("_id", new ObjectId(v1_share_3.get("_id").asText()));
    v1_share_3_dbo.removeField("binaryId");

    assertEquals(0L, (long) v1_share_db.countObjects().get());
    dbc.save(v1_share_1_dbo);
    dbc.save(v1_share_2_dbo);
    assertEquals(2L, (long) v1_share_db.countObjects().get());

    // Store the buckets

    assertEquals(0L, (long) library_db.countObjects().get());
    library_db.storeObjects(Arrays.asList(share2, share3)).get();
    assertEquals(2L, (long) library_db.countObjects().get());

    // OK now fire off an instance of the runner

    IkanowV1SyncService_LibraryJars s1 = new IkanowV1SyncService_LibraryJars(
            BeanTemplateUtils.clone(_service_config).with("v1_enabled", true).done(), _service_context);

    int old = IkanowV1SyncService_LibraryJars._num_leader_changes;
    s1.start();
    for (int i = 0; i < 20; ++i) {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }

        if ((old + 1) == IkanowV1SyncService_LibraryJars._num_leader_changes)
            break;
    }
    s1.stop();

    assertEquals(old + 1, IkanowV1SyncService_LibraryJars._num_leader_changes);

    // Now sleep a bit more to let the monitor have time to finish:
    Thread.sleep(3000L);

    // Check a few things have happened:

    // 1) share 1 was created

    assertTrue("share 1 should be created",
            library_db.getObjectById("v1_" + v1_share_1.get("_id").asText()).get().isPresent());

    // 2) share 2 should have been updated

    SharedLibraryBean updated_share_2 = library_db.getObjectById("v1_" + v1_share_2.get("_id").asText()).get()
            .get();
    assertTrue("share 2 should have been updated: ",
            updated_share_2.modified().getTime() > share2.modified().getTime());

    // 3) share 3 was deleted:

    assertFalse("share 3 should be deleted",
            library_db.getObjectById("v1_" + v1_share_3.get("_id").asText()).get().isPresent());
}

From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.TestElasticsearchCrudService.java

@Test
public void multiObjectRetrieve() throws InterruptedException, ExecutionException {

    final ElasticsearchCrudService<TestBean> service = getTestService("multiObjectRetrieve", TestBean.class);

    final List<TestBean> l = IntStream.rangeClosed(0, 9).boxed()
            .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i)
                    .with("test_string", "test_string" + i).with("test_long", (Long) (long) i).done().get())
            .collect(Collectors.toList());

    service.storeObjects(l).get();//  w  ww . ja v a  2s .com

    assertEquals(10, service.countObjects().get().intValue());

    service.optimizeQuery(Arrays.asList("test_string")).get(); // (The get() waits for completion)

    // 1) Simple retrieve, no fields specified - sort

    final QueryComponent<TestBean> query = CrudUtils.allOf(TestBean.class)
            .rangeAbove("test_string", "test_string4", true).withPresent("test_long")
            .orderBy(Tuples._2T("test_string", -1));

    try (Cursor<TestBean> cursor = service.getObjectsBySpec(query).get()) {

        assertEquals(5, cursor.count());

        final List<TestBean> objs = StreamSupport.stream(Optionals.ofNullable(cursor).spliterator(), false)
                .collect(Collectors.toList());

        assertEquals(5, objs.size());

        final JsonNode first_obj = BeanTemplateUtils.toJson(objs.get(0));

        assertEquals("{\"_id\":\"id9\",\"test_string\":\"test_string9\",\"test_long\":9}",
                first_obj.toString());
    } catch (Exception e) {
        //(fail on close, normally carry on - but here error out)
        fail("getObjectsBySpec errored on close");
    }

    // 2) Simple retrieve, field specified (exclusive) - sort and limit

    final QueryComponent<TestBean> query_2 = CrudUtils.allOf(TestBean.class)
            .rangeAbove("test_string", "test_string4", false).withPresent("test_long")
            .orderBy(Tuples._2T("test_long", 1)).limit(4);

    try (Cursor<TestBean> cursor = service.getObjectsBySpec(query_2, Arrays.asList("test_string"), false)
            .get()) {

        assertEquals(6, cursor.count()); // (count ignores limit)

        final List<TestBean> objs = StreamSupport.stream(Optionals.ofNullable(cursor).spliterator(), false)
                .collect(Collectors.toList());

        assertEquals(4, objs.size());

        final JsonNode first_obj = BeanTemplateUtils.toJson(objs.get(0));

        assertEquals("{\"_id\":\"id4\",\"test_long\":4}", first_obj.toString());
    } catch (Exception e) {
        //(fail on close, normally carry on - but here error out)
        fail("getObjectsBySpec errored on close");
    }

    // 3) Simple retrieve, no docs returned

    final QueryComponent<TestBean> query_3 = CrudUtils.allOf(TestBean.class)
            .rangeAbove("test_string", "test_string9", true).withPresent("test_long").limit(4);

    try (Cursor<TestBean> cursor = service.getObjectsBySpec(query_3, Arrays.asList("test_string"), false)
            .get()) {
        final List<TestBean> objs = StreamSupport.stream(Optionals.ofNullable(cursor).spliterator(), false)
                .collect(Collectors.toList());

        assertEquals(0, objs.size());
    } catch (Exception e) {
        //(fail on close, normally carry on - but here error out)
        fail("getObjectsBySpec errored on close");
    }

    // 4) Test on an index that doens't exists, check the same

    final ElasticsearchCrudService<TestBean> service2 = getTestService("multiObjectRetrieve_missing",
            TestBean.class, false, Optional.empty());

    final QueryComponent<TestBean> query_4 = CrudUtils.allOf(TestBean.class)
            .rangeAbove("test_string", "test_string9", true).withPresent("test_long").limit(4);

    try (Cursor<TestBean> cursor = service2.getObjectsBySpec(query_4, Arrays.asList("test_string"), false)
            .get()) {
        final List<TestBean> objs = StreamSupport.stream(Optionals.ofNullable(cursor).spliterator(), false)
                .collect(Collectors.toList());

        assertEquals(0, objs.size());
    } catch (Exception e) {
        //(fail on close, normally carry on - but here error out)
        fail("getObjectsBySpec errored on close");
    }
}

From source file:com.baasbox.service.user.UserService.java

public static ODocument signUp(String username, String password, Date signupDate, String role,
        JsonNode nonAppUserAttributes, JsonNode privateAttributes, JsonNode friendsAttributes,
        JsonNode appUsersAttributes, boolean generated)
        throws InvalidJsonException, UserAlreadyExistsException, EmailAlreadyUsedException {

    if (StringUtils.isEmpty(username))
        throw new IllegalArgumentException("username cannot be null or empty");
    if (StringUtils.isEmpty(password))
        throw new IllegalArgumentException("password cannot be null or empty");

    ODatabaseRecordTx db = DbHelper.getConnection();
    ODocument profile = null;/*from   ww  w  .ja v  a2  s  . c  o m*/
    UserDao dao = UserDao.getInstance();
    if (privateAttributes != null && privateAttributes.has("email")) {
        boolean checkEmail = dao
                .emailIsAlreadyUsed((String) privateAttributes.findValuesAsText("email").get(0));
        if (checkEmail)
            throw new EmailAlreadyUsedException("The email provided is already in use by another user");
    }
    try {
        //because we have to create an OUser record and a User Object, we need a transaction

        DbHelper.requestTransaction();

        if (role == null)
            profile = dao.create(username, password);
        else
            profile = dao.create(username, password, role);

        ORID userRid = ((ORID) profile.field("user")).getIdentity();
        ORole friendRole = RoleDao.createFriendRole(username);
        friendRole.getDocument().field(RoleService.FIELD_ASSIGNABLE, true);
        friendRole.getDocument().field(RoleService.FIELD_MODIFIABLE, false);
        friendRole.getDocument().field(RoleService.FIELD_INTERNAL, true);
        friendRole.getDocument().field(RoleService.FIELD_DESCRIPTION, "These are friends of " + username);

        /*    these attributes are visible by:
        *    Anonymous users
        *    Registered user
        *    Friends
        *    User
        */

        //anonymous
        {
            ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
            try {
                if (nonAppUserAttributes != null)
                    attrObj.fromJSON(nonAppUserAttributes.toString());
                else
                    attrObj.fromJSON("{}");
            } catch (OSerializationException e) {
                throw new InvalidJsonException(
                        dao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER + " is not a valid JSON object", e);
            }
            PermissionsHelper.grantRead(attrObj, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
            PermissionsHelper.grantRead(attrObj, RoleDao.getRole(DefaultRoles.ANONYMOUS_USER.toString()));
            PermissionsHelper.grantRead(attrObj, friendRole);
            PermissionsHelper.changeOwner(attrObj, userRid);
            profile.field(dao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER, attrObj);
            attrObj.save();
        }

        /*    these attributes are visible by:
         *    User
         */
        {
            ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
            try {
                if (privateAttributes != null)
                    attrObj.fromJSON(privateAttributes.toString());
                else
                    attrObj.fromJSON("{}");
            } catch (OSerializationException e) {
                throw new InvalidJsonException(
                        dao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER + " is not a valid JSON object", e);
            }
            profile.field(dao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER, attrObj);
            PermissionsHelper.changeOwner(attrObj, userRid);
            attrObj.save();
        }

        /*    these attributes are visible by:
         *    Friends
         *    User
         */
        {
            ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
            try {
                if (friendsAttributes != null)
                    attrObj.fromJSON(friendsAttributes.toString());
                else
                    attrObj.fromJSON("{}");
            } catch (OSerializationException e) {
                throw new InvalidJsonException(
                        dao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER + " is not a valid JSON object", e);
            }
            PermissionsHelper.grantRead(attrObj, friendRole);
            PermissionsHelper.changeOwner(attrObj, userRid);
            profile.field(dao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER, attrObj);
            attrObj.save();
        }

        /*    these attributes are visible by:
         *    Registered user
         *    Friends
         *    User
         */
        {
            ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
            try {
                if (appUsersAttributes != null)
                    attrObj.fromJSON(appUsersAttributes.toString());
                else
                    attrObj.fromJSON("{}");
            } catch (OSerializationException e) {
                throw new InvalidJsonException(
                        dao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER + " is not a valid JSON object", e);
            }
            attrObj.field("_social", new HashMap());
            PermissionsHelper.grantRead(attrObj, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
            PermissionsHelper.changeOwner(attrObj, userRid);
            profile.field(dao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER, attrObj);
            attrObj.save();
        }

        //system info
        {
            ODocument attrObj = new ODocument(dao.USER_ATTRIBUTES_CLASS);
            attrObj.field(dao.USER_LOGIN_INFO, new ArrayList());
            attrObj.field(dao.USER_SIGNUP_DATE, signupDate == null ? new Date() : signupDate);
            PermissionsHelper.changeOwner(attrObj, userRid);
            profile.field(dao.ATTRIBUTES_SYSTEM, attrObj);
        }

        profile.field(dao.USER_SIGNUP_DATE, signupDate == null ? new Date() : signupDate);
        //this is useful when you want to know if the username was automatically generated
        profile.field(UserDao.GENERATED_USERNAME, generated);

        PermissionsHelper.grantRead(profile, RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString()));
        PermissionsHelper.grantRead(profile, RoleDao.getRole(DefaultRoles.ANONYMOUS_USER.toString()));
        PermissionsHelper.changeOwner(profile, userRid);

        profile.save();
        DbHelper.commitTransaction();
    } catch (OSerializationException e) {
        DbHelper.rollbackTransaction();
        throw new InvalidJsonException(e);
    } catch (InvalidJsonException e) {
        DbHelper.rollbackTransaction();
        throw e;
    } catch (UserAlreadyExistsException e) {
        DbHelper.rollbackTransaction();
        throw e;
    } catch (Exception e) {
        DbHelper.rollbackTransaction();
        throw new RuntimeException(ExceptionUtils.getStackTrace(e));
    }
    return profile;
}

From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java

@Override
public Validation<BasicMessageBean, JsonNode> emitObject(final Optional<DataBucketBean> bucket,
        final AnalyticThreadJobBean job, final Either<JsonNode, Map<String, Object>> object,
        final Optional<AnnotationBean> annotations) {
    final DataBucketBean this_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get());

    if (annotations.isPresent()) {
        throw new RuntimeException(ErrorUtils.get(ErrorUtils.NOT_YET_IMPLEMENTED, "annotations"));
    }//from   w  w w . ja v a2  s  .  c o m
    final JsonNode obj_json = object.either(__ -> __,
            map -> (JsonNode) _mapper.convertValue(map, JsonNode.class));

    if (!this_bucket.full_name().equals(_mutable_state.bucket.get().full_name())) {
        return externalEmit(this_bucket, job, obj_json);
    }
    _mutable_state.has_unflushed_data = this._multi_writer.get().batchWrite(obj_json);

    final String topic = _distributed_services.generateTopicName(this_bucket.full_name(),
            ICoreDistributedServices.QUEUE_END_NAME);
    if (_distributed_services.doesTopicExist(topic)) {
        // (ie someone is listening in on our output data, so duplicate it for their benefit)
        _mutable_state.has_unflushed_data = true;
        _distributed_services.produce(topic, obj_json.toString());
    }
    //(else nothing to do)

    return Validation.success(obj_json);
}