Example usage for com.fasterxml.jackson.databind ObjectWriter writeValueAsString

List of usage examples for com.fasterxml.jackson.databind ObjectWriter writeValueAsString

Introduction

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

Prototype

@SuppressWarnings("resource")
public String writeValueAsString(Object value) throws JsonProcessingException 

Source Link

Document

Method that can be used to serialize any Java value as a String.

Usage

From source file:org.tsugi.lti2.LTI2Servlet.java

protected void getToolConsumerProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) {/*from  w  w w  . j  a  v a  2 s.c  om*/
    // Map<String,Object> deploy = ltiService.getDeployForConsumerKeyDao(profile_id);
    Map<String, Object> deploy = null;

    ToolConsumer consumer = buildToolConsumerProfile(request, deploy, profile_id);

    ObjectMapper mapper = new ObjectMapper();
    try {
        // http://stackoverflow.com/questions/6176881/how-do-i-make-jackson-pretty-print-the-json-content-it-generates
        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
        // ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above: 
        // ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
        // System.out.println(mapper.writeValueAsString(consumer));
        response.setContentType(APPLICATION_JSON);
        PrintWriter out = response.getWriter();
        out.println(writer.writeValueAsString(consumer));
        // System.out.println(writer.writeValueAsString(consumer));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:controllers.core.OrgUnitController.java

/**
 * Display the gantt of actors' allocations of the org unit.
 * /*w  ww  .  j  av  a2 s.  c  o  m*/
 * @param id
 *            the org unit id
 */
@With(CheckOrgUnitExists.class)
@Dynamic(IMafConstants.ORG_UNIT_VIEW_DYNAMIC_PERMISSION)
public Result allocation(Long id) {

    // get the org unit
    OrgUnit orgUnit = OrgUnitDao.getOrgUnitById(id);

    // prepare the data (to order them)
    SortableCollection<DateSortableObject> sortableCollection = new SortableCollection<>();
    for (PortfolioEntryResourcePlanAllocatedActor allocatedActor : PortfolioEntryResourcePlanDAO
            .getPEPlanAllocatedActorAsListByOrgUnitAndActive(id, true)) {
        if (allocatedActor.endDate != null) {
            sortableCollection.addObject(new DateSortableObject(allocatedActor.endDate, allocatedActor));
        }
    }
    for (TimesheetActivityAllocatedActor allocatedActivity : TimesheetDao
            .getTimesheetActivityAllocatedActorAsListByOrgUnit(id, true)) {
        if (allocatedActivity.endDate != null) {
            sortableCollection.addObject(new DateSortableObject(allocatedActivity.endDate, allocatedActivity));
        }
    }

    // construct the gantt

    List<SourceItem> items = new ArrayList<SourceItem>();

    for (DateSortableObject dateSortableObject : sortableCollection.getSorted()) {

        if (dateSortableObject.getObject() instanceof PortfolioEntryResourcePlanAllocatedActor) {

            PortfolioEntryResourcePlanAllocatedActor allocatedActor = (PortfolioEntryResourcePlanAllocatedActor) dateSortableObject
                    .getObject();

            // get the from date
            Date from = allocatedActor.startDate;

            // get the to date
            Date to = allocatedActor.endDate;

            // get the portfolio entry
            Long portfolioEntryId = allocatedActor.portfolioEntryResourcePlan.lifeCycleInstancePlannings
                    .get(0).lifeCycleInstance.portfolioEntry.id;
            PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(portfolioEntryId);

            String packageName = allocatedActor.portfolioEntryPlanningPackage != null
                    ? allocatedActor.portfolioEntryPlanningPackage.getName() + " / "
                    : "";

            SourceItem item = new SourceItem(allocatedActor.actor.getNameHumanReadable(),
                    portfolioEntry.getName());

            String cssClass = null;

            if (from != null) {

                to = JqueryGantt.cleanToDate(from, to);
                cssClass = "";

            } else {

                from = to;
                cssClass = "diamond diamond-";

            }

            if (allocatedActor.isConfirmed) {
                cssClass += "success";
            } else {
                cssClass += "warning";
            }

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.PortfolioEntryPlanningController.resources(portfolioEntry.id).url(),
                    null, null, null, null);

            item.values.add(new SourceValue(from, to, "",
                    packageName + views.html.framework_views.parts.formats.display_number
                            .render(allocatedActor.days, null, false).body(),
                    cssClass, dataValue));

            items.add(item);

        }

        if (dateSortableObject.getObject() instanceof TimesheetActivityAllocatedActor) {

            TimesheetActivityAllocatedActor allocatedActivity = (TimesheetActivityAllocatedActor) dateSortableObject
                    .getObject();

            // get the from date
            Date from = allocatedActivity.startDate;

            // get the to date
            Date to = allocatedActivity.endDate;

            SourceItem item = new SourceItem(allocatedActivity.actor.getNameHumanReadable(),
                    allocatedActivity.timesheetActivity.getName());

            String cssClass = null;

            if (from != null) {

                to = JqueryGantt.cleanToDate(from, to);
                cssClass = "";

            } else {

                from = to;
                cssClass = "diamond diamond-";

            }

            cssClass += "info";

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.ActorController
                            .allocationDetails(allocatedActivity.actor.id, 0, 0, false).url(),
                    null, null, null, null);

            item.values
                    .add(new SourceValue(from, to, "", views.html.framework_views.parts.formats.display_number
                            .render(allocatedActivity.days, null, false).body(), cssClass, dataValue));

            items.add(item);
        }

    }

    String ganttSource = "";
    try {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        ganttSource = ow.writeValueAsString(items);
    } catch (JsonProcessingException e) {
        Logger.error(e.getMessage());
    }

    return ok(views.html.core.orgunit.org_unit_allocation.render(orgUnit, ganttSource));

}

From source file:controllers.core.ActorController.java

/**
 * Display the gantt of allocations of the actor.
 * // w  w  w .j  a va  2 s.  c o m
 * @param id
 *            the actor id
 */
@With(CheckActorExists.class)
@Dynamic(IMafConstants.ACTOR_VIEW_DYNAMIC_PERMISSION)
public Result allocation(Long id) {

    // get the actor
    Actor actor = ActorDao.getActorById(id);

    // prepare the data (to order them)
    SortableCollection<DateSortableObject> sortableCollection = new SortableCollection<>();
    for (PortfolioEntryResourcePlanAllocatedActor allocatedActor : PortfolioEntryResourcePlanDAO
            .getPEPlanAllocatedActorAsListByActorAndActive(id, true)) {
        if (allocatedActor.endDate != null) {
            sortableCollection.addObject(new DateSortableObject(allocatedActor.endDate, allocatedActor));
        }
    }
    for (TimesheetActivityAllocatedActor allocatedActivity : TimesheetDao
            .getTimesheetActivityAllocatedActorAsListByActor(id, true)) {
        if (allocatedActivity.endDate != null) {
            sortableCollection.addObject(new DateSortableObject(allocatedActivity.endDate, allocatedActivity));
        }
    }

    // construct the gantt

    List<SourceItem> items = new ArrayList<SourceItem>();

    for (DateSortableObject dateSortableObject : sortableCollection.getSorted()) {

        if (dateSortableObject.getObject() instanceof PortfolioEntryResourcePlanAllocatedActor) {

            PortfolioEntryResourcePlanAllocatedActor allocatedActor = (PortfolioEntryResourcePlanAllocatedActor) dateSortableObject
                    .getObject();

            // get the from date
            Date from = allocatedActor.startDate;

            // get the to date
            Date to = allocatedActor.endDate;

            // get the portfolio entry
            Long portfolioEntryId = allocatedActor.portfolioEntryResourcePlan.lifeCycleInstancePlannings
                    .get(0).lifeCycleInstance.portfolioEntry.id;
            PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(portfolioEntryId);

            String packageName = allocatedActor.portfolioEntryPlanningPackage != null
                    ? allocatedActor.portfolioEntryPlanningPackage.getName()
                    : "";

            SourceItem item = new SourceItem(portfolioEntry.getName(), packageName);

            String cssClass = null;

            if (from != null) {

                to = JqueryGantt.cleanToDate(from, to);
                cssClass = "";

            } else {

                from = to;
                cssClass = "diamond diamond-";

            }

            if (allocatedActor.isConfirmed) {
                cssClass += "success";
            } else {
                cssClass += "warning";
            }

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.PortfolioEntryPlanningController.resources(portfolioEntry.id).url(),
                    null, null, null, null);

            item.values
                    .add(new SourceValue(from, to, "", views.html.framework_views.parts.formats.display_number
                            .render(allocatedActor.days, null, false).body(), cssClass, dataValue));

            items.add(item);

        }

        if (dateSortableObject.getObject() instanceof TimesheetActivityAllocatedActor) {

            TimesheetActivityAllocatedActor allocatedActivity = (TimesheetActivityAllocatedActor) dateSortableObject
                    .getObject();

            // get the from date
            Date from = allocatedActivity.startDate;

            // get the to date
            Date to = allocatedActivity.endDate;

            SourceItem item = new SourceItem(allocatedActivity.timesheetActivity.getName(), "");

            String cssClass = null;

            if (from != null) {

                to = JqueryGantt.cleanToDate(from, to);
                cssClass = "";

            } else {

                from = to;
                cssClass = "diamond diamond-";

            }

            cssClass += "info";

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.ActorController.allocationDetails(actor.id, 0, 0, false).url(),
                    null, null, null, null);

            item.values
                    .add(new SourceValue(from, to, "", views.html.framework_views.parts.formats.display_number
                            .render(allocatedActivity.days, null, false).body(), cssClass, dataValue));

            items.add(item);
        }

    }

    String ganttSource = "";
    try {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        ganttSource = ow.writeValueAsString(items);
    } catch (JsonProcessingException e) {
        Logger.error(e.getMessage());
    }

    return ok(views.html.core.actor.actor_allocation.render(actor, ganttSource));
}

From source file:com.orange.ngsi2.model.SubscriptionTest.java

@Test
public void serializationSubscriptionTest() throws JsonProcessingException, MalformedURLException {
    ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter());

    SubjectEntity subjectEntity = new SubjectEntity();
    subjectEntity.setId(Optional.of("Bcn_Welt"));
    subjectEntity.setType(Optional.of("Room"));
    Condition condition = new Condition();
    condition.setAttributes(Collections.singletonList("temperature"));
    condition.setExpression("q", "temperature>40");
    SubjectSubscription subjectSubscription = new SubjectSubscription(Collections.singletonList(subjectEntity),
            condition);//from   ww  w.j  av a  2 s .co  m
    List<String> attributes = new ArrayList<>();
    attributes.add("temperature");
    attributes.add("humidity");
    Notification notification = new Notification(attributes, new URL("http://localhost:1234"));
    notification.setThrottling(Optional.of(new Long(5)));
    notification.setTimesSent(12);
    notification.setLastNotification(Instant.parse("2015-10-05T16:00:00.10Z"));
    notification.setHeader("X-MyHeader", "foo");
    notification.setQuery("authToken", "bar");
    notification.setAttrsFormat(Optional.of(Notification.Format.keyValues));
    String json = writer.writeValueAsString(new Subscription("abcdefg", subjectSubscription, notification,
            Instant.parse("2016-04-05T14:00:00.20Z"), Subscription.Status.active));

    assertEquals(jsonString, json);
}

From source file:org.opencb.cellbase.app.cli.VariantAnnotationCommandExecutor.java

private boolean runAnnotation() throws Exception {

    // Build indexes for custom files and/or population frequencies file
    getIndexes();/*  w w w  .  j a v  a2 s  .c o  m*/

    if (variantAnnotationCommandOptions.variant != null && !variantAnnotationCommandOptions.variant.isEmpty()) {
        List<Variant> variants = Variant.parseVariants(variantAnnotationCommandOptions.variant);
        if (local) {
            DBAdaptorFactory dbAdaptorFactory = new MongoDBAdaptorFactory(configuration);
            VariantAnnotationCalculator variantAnnotationCalculator = new VariantAnnotationCalculator(
                    this.species, this.assembly, dbAdaptorFactory);
            List<QueryResult<VariantAnnotation>> annotationByVariantList = variantAnnotationCalculator
                    .getAnnotationByVariantList(variants, queryOptions);

            ObjectMapper jsonObjectMapper = new ObjectMapper();
            jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            jsonObjectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
            ObjectWriter objectWriter = jsonObjectMapper.writer();

            Path outPath = Paths.get(variantAnnotationCommandOptions.output);
            FileUtils.checkDirectory(outPath.getParent());
            BufferedWriter bufferedWriter = FileUtils.newBufferedWriter(outPath);
            for (QueryResult queryResult : annotationByVariantList) {
                bufferedWriter.write(objectWriter.writeValueAsString(queryResult.getResult()));
                bufferedWriter.newLine();
            }
            bufferedWriter.close();
        }
        return true;
    }

    // If a variant file is provided then we annotate it. Lines in the input file can be computationally
    // expensive to parse, i.e.: multisample vcf with thousands of samples. A specific task is created to enable
    // parallel parsing of these lines
    if (input != null) {
        DataReader dataReader = new StringDataReader(input);
        List<ParallelTaskRunner.TaskWithException<String, Variant, Exception>> variantAnnotatorTaskList = getStringTaskList();
        DataWriter dataWriter = getDataWriter(output.toString());

        ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numThreads, batchSize, QUEUE_CAPACITY,
                false);
        ParallelTaskRunner<String, Variant> runner = new ParallelTaskRunner<>(dataReader,
                variantAnnotatorTaskList, dataWriter, config);
        runner.run();
        // For internal use only - will only be run when -Dpopulation-frequencies is activated
        writeRemainingPopFrequencies();
    } else {
        // This will annotate the CellBase Variation collection
        if (cellBaseAnnotation) {
            // TODO: enable this query in the parseQuery method within VariantMongoDBAdaptor
            //                    Query query = new Query("$match",
            //                            new Document("annotation.consequenceTypes", new Document("$exists", 0)));
            //                    Query query = new Query();
            QueryOptions options = new QueryOptions("include", "chromosome,start,reference,alternate,type");
            List<ParallelTaskRunner.TaskWithException<Variant, Variant, Exception>> variantAnnotatorTaskList = getVariantTaskList();
            ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numThreads, batchSize,
                    QUEUE_CAPACITY, false);

            for (String chromosome : chromosomeList) {
                logger.info("Annotating chromosome {}", chromosome);
                Query query = new Query("chromosome", chromosome);
                DataReader dataReader = new VariationDataReader(dbAdaptorFactory.getVariationDBAdaptor(species),
                        query, options);
                DataWriter dataWriter = getDataWriter(
                        output.toString() + "/" + VARIATION_ANNOTATION_FILE_PREFIX + chromosome + ".json.gz");
                ParallelTaskRunner<Variant, Variant> runner = new ParallelTaskRunner<Variant, Variant>(
                        dataReader, variantAnnotatorTaskList, dataWriter, config);
                runner.run();
            }
        }
    }

    if (customFiles != null || populationFrequenciesFile != null) {
        closeIndexes();
    }

    logger.info("Variant annotation finished.");
    return false;
}

From source file:models.db.acentera.impl.ProjectImpl.java

public static JSONObject getProjectUserDetails(Long projectId, Long userId, User u) throws Exception {
    Logger.debug("getProjectUserDetails B1 ");
    Session s = (Session) HibernateSessionFactory.getSession();
    Criteria criteria = s.createCriteria(UserProjects.class);

    JSONArray jsoProjectUserArray = new JSONArray();
    JSONArray jsoUserArray = new JSONArray();
    JSONArray jsoProjectIdArray = new JSONArray();
    jsoProjectIdArray.add(projectId);/*from  w  w w. j a  v a 2 s .com*/

    Set<User> proessedUsers = new HashSet<User>();

    //Get informations about the current User if its in this project...
    //User theUser = UserImpl.getUserById(userId);

    //Verry Bad but we couldn't get the user / project mapping to work properly in restrictions...
    Logger.debug("getProjectUserDetails B2  ");
    List<UserProjects> lstUp = (List<UserProjects>) criteria
            .add(Restrictions.and(Restrictions.eq("project.id", projectId))).list();
    Logger.debug("getProjectUserDetails B2a  " + lstUp);

    UserProjects up = null;
    Iterator<UserProjects> itrUp = lstUp.iterator();
    while (itrUp.hasNext() && up == null) {
        UserProjects tmpUp = itrUp.next();
        if (tmpUp.getUser().getId().longValue() == userId) {
            up = tmpUp;
        }
    }

    Logger.debug("getProjectUserDetails Bb " + up);

    if (up == null) {
        Logger.debug("Returning null 2...");
        return null;
    }

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    ObjectWriter ow = mapper.writer();

    User projectUser = up.getUser();

    jsoProjectUserArray.add(projectUser.getId());
    JSONObject jsoUser = JSONObject.fromObject(mapper.writeValueAsString(projectUser));
    jsoUser.put("project", jsoProjectIdArray);
    jsoUser.put("project_id", projectId);

    //get current user Tag only..
    //Other tags will be gathered if end-user click on them..
    List<ProjectUserTags> tags = ProjectImpl.getUserProjectTags(up);
    JSONArray jsoTagsArr = new JSONArray();
    for (int i = 0; i < tags.size(); i++) {
        jsoTagsArr.add(JSONObject.fromObject(mapper.writeValueAsString(tags.get(i))));
    }

    //jsoUser.put("tags", mapper.writeValueAsString(userProject.getTags()));
    jsoUser.put("tags", jsoTagsArr);

    //Get the current user roles for this project...
    JSONArray jsRolesArray = new JSONArray();
    Set<ProjectTags> userRoles = ProjectImpl.getUserProjectRoles(up);
    Iterator<ProjectTags> itrRoles = userRoles.iterator();
    while (itrRoles.hasNext()) {
        ProjectTags userProjectRole = itrRoles.next();
        JSONObject role = JSONObject.fromObject(ow.writeValueAsString(userProjectRole));
        jsRolesArray.add(role);
    }
    jsoUser.put("roles", jsRolesArray);

    jsoUserArray.add(jsoUser);

    proessedUsers.add(projectUser);

    JSONObject jso = new JSONObject();
    jso.put("users", jsoUserArray);
    //jsoProject.put("users", jsoProjectUserArray);

    return jso;
}

From source file:com.vmware.xenon.swagger.SwaggerAssembler.java

private void completion(Map<Long, Operation> ops, Map<Long, Throwable> errors) {
    try {//w w w. j a  va2 s.co  m
        Map<String, Operation> sortedOps = new TreeMap<>();
        for (Map.Entry<Long, Operation> e : ops.entrySet()) {
            // ignore failed ops
            if (errors != null && errors.containsKey(e.getKey())) {
                continue;
            }

            String uri = UriUtils.getParentPath(e.getValue().getUri().getPath());

            sortedOps.put(uri, e.getValue());
        }

        // Add operations in sorted order
        for (Map.Entry<String, Operation> e : sortedOps.entrySet()) {
            this.addOperation(e.getKey(), e.getValue());
        }

        this.swagger.setDefinitions(this.modelRegistry.getDefinitions());

        ObjectWriter writer;
        String accept = this.get.getRequestHeader(Operation.ACCEPT_HEADER);
        if (accept != null && (accept.contains(CONTENT_TYPE_YML) || accept.contains(CONTENT_TYPE_YAML))) {
            this.get.addResponseHeader(Operation.CONTENT_TYPE_HEADER, Operation.MEDIA_TYPE_TEXT_YAML);
            writer = Yaml.pretty();
        } else {
            this.get.addResponseHeader(Operation.CONTENT_TYPE_HEADER, Operation.MEDIA_TYPE_APPLICATION_JSON);
            writer = Json.pretty();
        }

        if (this.postprocessor != null) {
            this.postprocessor.accept(this.swagger);
        }

        this.get.setBody(writer.writeValueAsString(this.swagger));
        this.get.complete();
    } catch (Exception e) {
        this.get.fail(e);
    }
}

From source file:com.acentera.utils.ProjectsHelpers.java

public String getUserProjectWithRolesAsJson(Project p, User u) {

    SecurityController.getSubject().checkPermission("project:" + p.getId() + ":view");

    //String projectAsJson = g.toJson(p);
    JSONObject jso = new JSONObject();

    UserProjects uproject = ProjectImpl.getUserProject(p.getId(), u);

    List<UserProjects> lstUsers = ProjectImpl.getUsersForProject(p);

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    ObjectWriter ow = mapper.writer();

    try {// w  w w.j a  v  a 2  s.c  o  m
        jso.put("project", ow.writeValueAsString(p));
        JSONObject jsoProject = jso.getJSONObject("project");
        jsoProject.put("invitetoken", uproject.getInviteToken());

        //Get the current user roles for this project...
        JSONArray jsRolesArray = new JSONArray();
        Set<ProjectTags> roles = ProjectImpl.getUserProjectRoles(uproject);
        Logger.debug("GOR ROLES : " + roles);
        Iterator<ProjectTags> itrRoles = roles.iterator();
        while (itrRoles.hasNext()) {
            ProjectTags userProjectRole = itrRoles.next();
            JSONObject role = JSONObject.fromObject(ow.writeValueAsString(userProjectRole));
            jsRolesArray.add(role);
            jsoProject.put(userProjectRole.getName(), 1);
        }

        //jsoProject.put("user", lstUsers);
        JSONArray jsoProjectUserArray = new JSONArray();
        JSONArray jsoUserArray = new JSONArray();
        Iterator<UserProjects> up = lstUsers.iterator();
        JSONArray jsoProjectIdArray = new JSONArray();
        jsoProjectIdArray.add(p.getId());

        Set<User> proessedUsers = new HashSet<User>();

        Logger.debug("ALL USERS : " + lstUsers);

        Set<ProjectTags> projectTags = new HashSet<ProjectTags>();
        projectTags = ProjectImpl.getProjectTags(uproject);

        if (SecurityController.getSubject().isPermitted("project:" + p.getId() + ":user:view")) {
            while (up.hasNext()) {
                UserProjects userProject = up.next();
                if (SecurityController.getSubject()
                        .isPermitted("project:" + p.getId() + ":user:view:" + userProject.getId())) {

                    //TOOD: If user can view this user otherwise continue.. (we must make sure project.users : [ ID's match only the one we can view ]

                    User projectUser = userProject.getUser();
                    Logger.debug("WILL INSERT.. " + projectUser.getEmail());

                    jsoProjectUserArray.add(projectUser.getId());
                    JSONObject jsoUser = JSONObject.fromObject(mapper.writeValueAsString(projectUser));

                    if (!proessedUsers.contains(projectUser)) {

                        //jsoUser.put("projects", jsoProjectIdArray);
                        jsoUser.put("project_id", p.getId());

                        //get current user Tag only..
                        //Other tags will be gathered if end-user click on them..
                        if (projectUser.equals(u)) {
                            List<ProjectUserTags> tags = ProjectImpl.getUserProjectTags(uproject);
                            JSONArray jsoTagsArr = new JSONArray();
                            for (int i = 0; i < tags.size(); i++) {
                                jsoTagsArr.add(JSONObject.fromObject(mapper.writeValueAsString(tags.get(i))));
                            }

                            //jsoUser.put("tags", mapper.writeValueAsString(userProject.getTags()));
                            jsoUser.put("tags", jsoTagsArr);
                        }

                        //jsoUser.put("tags", mapper.writeValueAsString(userProject.getTags()));

                    }
                    jsoUserArray.add(jsoUser);
                    proessedUsers.add(projectUser);
                }
            }
        }

        jso.put("users", jsoUserArray);
        jsoProject.put("users", jsoProjectUserArray);

        jso.put("tags", mapper.writeValueAsString(projectTags));

        Set<ProjectQuota> s = p.getQuotas();
        if ((s != null) && (s.size() > 0)) {
            jso.put("quotas", mapper.writeValueAsString(s));
        }

        Set<ProjectRegions> projectRegionsSet = new HashSet<ProjectRegions>();
        Set<ProjectProviders> lstProviders = p.getProviders();
        if ((lstProviders != null) && (lstProviders.size() > 0)) {

            Iterator<ProjectProviders> itrProjectProviders = lstProviders.iterator();
            Set<ProjectProviders> userAccessProviders = new HashSet<ProjectProviders>();
            while (itrProjectProviders.hasNext()) {
                ProjectProviders pr = itrProjectProviders.next();

                if (SecurityController.isTagPermitted(p.getId(), pr)) {
                    userAccessProviders.add(pr);
                    try {
                        if (pr.getRegions() != null) {
                            Iterator<ProjectProvidersRegions> itrRegions = pr.getRegions().iterator();
                            while (itrRegions.hasNext()) {
                                ProjectProvidersRegions ppr = itrRegions.next();
                                projectRegionsSet.add(ppr.getProjectRegions());
                            }
                        }
                    } catch (Exception ee) {

                    }
                }
            }

            jso.put("regions", mapper.writeValueAsString(projectRegionsSet));

            jso.put("providers", mapper.writeValueAsString(userAccessProviders));

            Set<ProjectSshKey> lstKeys = p.getSshKeys();
            if ((lstKeys != null) && (lstKeys.size() > 0)) {
                Iterator<ProjectSshKey> itrKeys = lstKeys.iterator();
                JSONArray jsoKeys = new JSONArray();
                while (itrKeys.hasNext()) {
                    ProjectSshKey sshKey = itrKeys.next();

                    if (SecurityController.isPermitted(p, sshKey)) {
                        jsoKeys.add(mapper.writeValueAsString(sshKey));
                    }

                }
                jso.put("sshkeys", jsoKeys);
            }

        }

        jsoProject.put("roles", jsRolesArray);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return jso.toString();
}

From source file:com.neatresults.mgnltweaks.json.JsonBuilder.java

/**
 * Executes configured chain of operations and produces the json output.
 *///from w  w  w  .j a v  a2s  .c  om
public String print() {

    ObjectWriter ow = mapper.writer();
    if (!inline) {
        ow = ow.withDefaultPrettyPrinter();
    }

    if (wrapForI18n) {
        node = new I18nNodeWrapper(node);
    }
    try {
        // total depth is that of starting node + set total by user
        totalDepth += node.getDepth();
        String json;
        if (childrenOnly) {
            Collection<EntryableContentMap> childNodes = new LinkedList<EntryableContentMap>();
            NodeIterator nodes = this.node.getNodes();
            asNodeStream(nodes).filter(this::isSearchInNodeType).map(this::cloneWith)
                    .forEach(builder -> childNodes.add(new EntryableContentMap(builder)));
            json = ow.writeValueAsString(childNodes);
        } else if (!allowOnlyNodeTypes.equals(".*")) {
            Collection<EntryableContentMap> childNodes = new LinkedList<EntryableContentMap>();
            NodeIterator nodes = this.node.getNodes();
            asNodeStream(nodes).filter(this::isSearchInNodeType)
                    .forEach(new PredicateSplitterConsumer<Node>(this::isOfAllowedDepthAndType,
                            allowedNode -> childNodes.add(new EntryableContentMap(this.cloneWith(allowedNode))),
                            allowedParent -> childNodes
                                    .addAll(this.getAllowedChildNodesContentMapsOf(allowedParent, 1))));
            json = ow.writeValueAsString(childNodes);

        } else {
            EntryableContentMap map = new EntryableContentMap(this);
            List<String> garbage = map.entrySet().stream()
                    .filter(entry -> entry.getValue() instanceof EntryableContentMap)
                    .filter(entry -> ((EntryableContentMap) entry.getValue()).entrySet().isEmpty())
                    .map(entry -> entry.getKey()).collect(Collectors.toList());
            garbage.stream().forEach(key -> map.remove(key));
            json = ow.writeValueAsString(map);
        }

        if (StringUtils.isNotEmpty(preexisingJson)) {
            String trimmedJson = preexisingJson.trim();
            if (trimmedJson.endsWith("}")) {
                json = "[" + preexisingJson + "," + json + "]";
            } else if (trimmedJson.endsWith("]")) {
                json = StringUtils.substringBeforeLast(preexisingJson, "]")
                        + (trimmedJson.equals("[]") ? "" : ",") + json + "]";
            }
        }
        if (escapeBackslash) {
            json = ESCAPES.matcher(json).replaceAll("\\\\\\\\");
        }
        return json;
    } catch (JsonProcessingException | RepositoryException e) {
        log.debug("Failed to generate JSON string", e);
    }

    return "{ }";
}

From source file:org.loklak.api.iot.GeoJsonPushServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);
    String remoteHash = Integer.toHexString(Math.abs(post.getClientHost().hashCode()));

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;/*  w w w .  j a  va  2s.  co  m*/
    }

    String url = post.get("url", "");
    String map_type = post.get("map_type", "");
    String source_type_str = post.get("source_type", "");
    if ("".equals(source_type_str) || !SourceType.isValid(source_type_str)) {
        DAO.log("invalid or missing source_type value : " + source_type_str);
        source_type_str = SourceType.GEOJSON.toString();
    }
    SourceType sourceType = SourceType.GEOJSON;

    if (url == null || url.length() == 0) {
        response.sendError(400, "your request does not contain an url to your data object");
        return;
    }
    String screen_name = post.get("screen_name", "");
    if (screen_name == null || screen_name.length() == 0) {
        response.sendError(400, "your request does not contain required screen_name parameter");
        return;
    }
    // parse json retrieved from url
    final JSONArray features;
    byte[] jsonText;
    try {
        jsonText = ClientConnection.download(url);
        JSONObject map = new JSONObject(new String(jsonText, StandardCharsets.UTF_8));
        features = map.getJSONArray("features");
    } catch (Exception e) {
        response.sendError(400, "error reading json file from url");
        return;
    }
    if (features == null) {
        response.sendError(400, "geojson format error : member 'features' missing.");
        return;
    }

    // parse maptype
    Map<String, List<String>> mapRules = new HashMap<>();
    if (!"".equals(map_type)) {
        try {
            String[] mapRulesArray = map_type.split(",");
            for (String rule : mapRulesArray) {
                String[] splitted = rule.split(":", 2);
                if (splitted.length != 2) {
                    throw new Exception("Invalid format");
                }
                List<String> valuesList = mapRules.get(splitted[0]);
                if (valuesList == null) {
                    valuesList = new ArrayList<>();
                    mapRules.put(splitted[0], valuesList);
                }
                valuesList.add(splitted[1]);
            }
        } catch (Exception e) {
            response.sendError(400, "error parsing map_type : " + map_type + ". Please check its format");
            return;
        }
    }

    JSONArray rawMessages = new JSONArray();
    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    PushReport nodePushReport = new PushReport();
    for (Object feature_obj : features) {
        JSONObject feature = (JSONObject) feature_obj;
        JSONObject properties = feature.has("properties") ? (JSONObject) feature.get("properties")
                : new JSONObject();
        JSONObject geometry = feature.has("geometry") ? (JSONObject) feature.get("geometry") : new JSONObject();
        JSONObject message = new JSONObject(true);

        // add mapped properties
        JSONObject mappedProperties = convertMapRulesProperties(mapRules, properties);
        message.putAll(mappedProperties);

        if (!"".equals(sourceType)) {
            message.put("source_type", sourceType);
        } else {
            message.put("source_type", SourceType.GEOJSON);
        }
        message.put("provider_type", ProviderType.IMPORT.name());
        message.put("provider_hash", remoteHash);
        message.put("location_point", geometry.get("coordinates"));
        message.put("location_mark", geometry.get("coordinates"));
        message.put("location_source", LocationSource.USER.name());
        message.put("place_context", PlaceContext.FROM.name());

        if (message.get("text") == null) {
            message.put("text", "");
        }
        // append rich-text attachment
        String jsonToText = ow.writeValueAsString(properties);
        message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText);

        if (properties.get("mtime") == null) {
            String existed = PushServletHelper.checkMessageExistence(message);
            // message known
            if (existed != null) {
                nodePushReport.incrementKnownCount(existed);
                continue;
            }
            // updated message -> save with new mtime value
            message.put("mtime", Long.toString(System.currentTimeMillis()));
        }

        try {
            message.put("id_str", PushServletHelper.computeMessageId(message, sourceType));
        } catch (Exception e) {
            DAO.log("Problem computing id : " + e.getMessage());
            nodePushReport.incrementErrorCount();
        }

        rawMessages.put(message);
    }

    PushReport report = PushServletHelper.saveMessagesAndImportProfile(rawMessages, Arrays.hashCode(jsonText),
            post, sourceType, screen_name);

    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), report);
    post.setResponse(response, "application/javascript");
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + report.getRecordCount() + ", new = "
            + report.getNewCount() + ", known = " + report.getKnownCount() + ", error = "
            + report.getErrorCount() + ", from host hash " + remoteHash);
}