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.opencb.opencga.app.cli.main.OpenCGAMainOld.java

private StringBuilder createOutput(OptionsParser.CommonOptions commonOptions, List list, StringBuilder sb)
        throws JsonProcessingException {
    if (sb == null) {
        sb = new StringBuilder();
    }/*from  w  w  w  .  ja  v  a  2  s  .  c om*/
    String idSeparator = null;
    switch (commonOptions.outputFormat) {
    case IDS:
        idSeparator = idSeparator == null ? "\n" : idSeparator;
    case ID_CSV:
        idSeparator = idSeparator == null ? "," : idSeparator;
    case ID_LIST:
        idSeparator = idSeparator == null ? "," : idSeparator; {
        if (!list.isEmpty()) {
            try {
                Iterator iterator = list.iterator();

                Object next = iterator.next();
                if (next instanceof QueryResult) {
                    createOutput(commonOptions, (QueryResult) next, sb);
                } else {
                    sb.append(getId(next));
                }
                while (iterator.hasNext()) {
                    next = iterator.next();
                    if (next instanceof QueryResult) {
                        sb.append(idSeparator);
                        createOutput(commonOptions, (QueryResult) next, sb);
                    } else {
                        sb.append(idSeparator).append(getId(next));
                    }
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        break;
    }
    case NAME_ID_MAP: {
        if (!list.isEmpty()) {
            try {
                Iterator iterator = list.iterator();
                Object object = iterator.next();
                if (object instanceof QueryResult) {
                    createOutput(commonOptions, (QueryResult) object, sb);
                } else {
                    sb.append(getName(object)).append(":").append(getId(object));
                }
                while (iterator.hasNext()) {
                    object = iterator.next();
                    if (object instanceof QueryResult) {
                        sb.append(",");
                        createOutput(commonOptions, (QueryResult) object, sb);
                    } else {
                        sb.append(",").append(getName(object)).append(":").append(getId(object));
                    }
                }
            } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        break;
    }
    case RAW:
        if (list != null) {
            for (Object o : list) {
                sb.append(String.valueOf(o));
            }
        }
        break;
    default:
        logger.warn("Unsupported output format \"{}\" for that query", commonOptions.outputFormat);
    case PRETTY_JSON:
    case PLAIN_JSON:
        JsonFactory factory = new JsonFactory();
        ObjectMapper objectMapper = new ObjectMapper(factory);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //                objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
        ObjectWriter objectWriter = commonOptions.outputFormat == OptionsParser.OutputFormat.PRETTY_JSON
                ? objectMapper.writerWithDefaultPrettyPrinter()
                : objectMapper.writer();

        if (list != null && !list.isEmpty()) {
            Iterator iterator = list.iterator();
            sb.append(objectWriter.writeValueAsString(iterator.next()));
            while (iterator.hasNext()) {
                sb.append("\n").append(objectWriter.writeValueAsString(iterator.next()));
            }
        }
        break;
    }
    return sb;
}

From source file:controllers.core.RoadmapController.java

/**
 * Display the planning (gantt) of the current roadmap.
 * /*from   w  w w.j  a va 2s . co m*/
 * the list of portfolio entries depends of the current filter configuration
 * 
 * the gantt view is construct as:<br/>
 * -for each portfolio entry we get its life cycle process and its last
 * planned dates (there is one date by milestone)<br/>
 * -for each phase of the life cycle process, we get its start milestone and
 * we find the corresponding planned date (that is the start date) from the
 * last planned dates. We do the same for the end milestone<br/>
 * -we display one interval (bar) by phase according to the computed start
 * and end dates (see just above)
 */
public Result viewPlanning() {

    try {

        // get the filter config
        String uid = getUserSessionManagerPlugin().getUserSessionId(ctx());
        FilterConfig<PortfolioEntryListView> filterConfig = this.getTableProvider()
                .get().portfolioEntry.filterConfig.getCurrent(uid, request());

        OrderBy<PortfolioEntry> orderBy = filterConfig.getSortExpression();
        ExpressionList<PortfolioEntry> expressionList = PortfolioEntryDynamicHelper
                .getPortfolioEntriesViewAllowedAsQuery(filterConfig.getSearchExpression(), orderBy,
                        getSecurityService());

        // initiate the source items (gantt)
        List<SourceItem> items = new ArrayList<SourceItem>();

        // compute the items (for each portfolio entry)
        for (PortfolioEntry portfolioEntry : expressionList.findList()) {

            // get the active life cycle process instance
            LifeCycleInstance processInstance = portfolioEntry.activeLifeCycleInstance;

            // get the roadmap phases of a process
            List<LifeCyclePhase> lifeCyclePhases = LifeCycleMilestoneDao
                    .getLCPhaseRoadmapAsListByLCProcess(processInstance.lifeCycleProcess.id);

            if (lifeCyclePhases != null && !lifeCyclePhases.isEmpty()) {

                // get the last planned milestone instances
                List<PlannedLifeCycleMilestoneInstance> lastPlannedMilestoneInstances = LifeCyclePlanningDao
                        .getPlannedLCMilestoneInstanceLastAsListByPE(portfolioEntry.id);

                if (lastPlannedMilestoneInstances != null && lastPlannedMilestoneInstances.size() > 0) {

                    // transform the list of last planned milestone
                    // instances to
                    // a map
                    Map<Long, PlannedLifeCycleMilestoneInstance> lastPlannedMilestoneInstancesAsMap = new HashMap<>();
                    for (PlannedLifeCycleMilestoneInstance plannedMilestoneInstance : lastPlannedMilestoneInstances) {
                        lastPlannedMilestoneInstancesAsMap.put(plannedMilestoneInstance.lifeCycleMilestone.id,
                                plannedMilestoneInstance);
                    }

                    /*
                     * compute the common components for all phases
                     */

                    // get the CSS class
                    String cssClass = GANTT_DEFAULT_CSS_CLASS;
                    PortfolioEntryReport report = portfolioEntry.lastPortfolioEntryReport;
                    if (report != null && report.portfolioEntryReportStatusType != null) {
                        cssClass = report.portfolioEntryReportStatusType.cssClass;
                    }

                    // create the source data value (used when clicking on a
                    // phase)
                    SourceDataValue sourceDataValue = new SourceDataValue(
                            controllers.core.routes.PortfolioEntryController.overview(portfolioEntry.id).url(),
                            portfolioEntry.getName(), portfolioEntry.getDescription(),
                            views.html.modelsparts.display_actor.render(portfolioEntry.manager).body(),
                            views.html.framework_views.parts.formats.display_list_of_values
                                    .render(portfolioEntry.portfolios, "display").body());

                    boolean isFirstLoop = true;

                    for (LifeCyclePhase phase : lifeCyclePhases) {

                        if (lastPlannedMilestoneInstancesAsMap.containsKey(phase.startLifeCycleMilestone.id)
                                && lastPlannedMilestoneInstancesAsMap
                                        .containsKey(phase.endLifeCycleMilestone.id)) {

                            // get the from date
                            Date from = LifeCyclePlanningDao.getPlannedLCMilestoneInstanceAsPassedDate(
                                    lastPlannedMilestoneInstancesAsMap
                                            .get(phase.startLifeCycleMilestone.id).id);

                            // get the to date
                            Date to = LifeCyclePlanningDao.getPlannedLCMilestoneInstanceAsPassedDate(
                                    lastPlannedMilestoneInstancesAsMap.get(phase.endLifeCycleMilestone.id).id);

                            if (from != null && to != null) {

                                to = JqueryGantt.cleanToDate(from, to);

                                // add gap for the from date
                                if (phase.gapDaysStart != null && phase.gapDaysStart.intValue() > 0) {
                                    Calendar c = Calendar.getInstance();
                                    c.setTime(from);
                                    c.add(Calendar.DATE, phase.gapDaysStart);
                                    from = c.getTime();
                                }

                                // remove gap for the to date
                                if (phase.gapDaysEnd != null && phase.gapDaysEnd.intValue() > 0) {
                                    Calendar c = Calendar.getInstance();
                                    c.setTime(to);
                                    c.add(Calendar.DATE, -1 * phase.gapDaysEnd);
                                    to = c.getTime();
                                }

                                String name = "";
                                if (isFirstLoop) {
                                    if (portfolioEntry.getGovernanceId() != null) {
                                        name += portfolioEntry.getGovernanceId() + " - ";
                                    }
                                    name += portfolioEntry.getName();
                                }

                                SourceItem item = new SourceItem(name, "");

                                item.values.add(new SourceValue(from, to, "", phase.getName(), cssClass,
                                        sourceDataValue));

                                items.add(item);

                                isFirstLoop = false;

                            }

                        }

                    }

                }

            }
        }

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

        return ok(views.html.core.roadmap.roadmap_view_planning.render(source));

    } catch (Exception e) {
        return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(),
                getI18nMessagesPlugin());
    }
}

From source file:controllers.core.RoadmapController.java

/**
 * The capacity forecast table./*from  w w w . jav  a 2  s  .c  o m*/
 */
@Restrict({ @Group(IMafConstants.ROADMAP_SIMULATOR_PERMISSION) })
public Result simulatorCapacityForecast() {

    try {

        Integer percentage = getPreferenceManagerPlugin()
                .getPreferenceValueAsInteger(IMafConstants.ROADMAP_CAPACITY_SIMULATOR_WARNING_LIMIT_PREFERENCE);
        int warningLimitPercent = percentage.intValue();

        List<String> ids = FilterConfig.getIdsFromRequest(request());

        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String idsAsJson = ow.writeValueAsString(ids);

        /**
         * Bind the form: if the previous page is the roadmap, then we fill
         * the form with default values, else we use the submitted ones.
         */
        Form<CapacityForecastForm> capacityForecastForm = null;
        Form<CapacityForecastForm> boundForm = capacityForecastFormTemplate.bindFromRequest();
        if (boundForm.data().get("year") == null) {
            capacityForecastForm = capacityForecastFormTemplate
                    .fill(new CapacityForecastForm(idsAsJson, Calendar.getInstance().get(Calendar.YEAR)));
        } else {
            capacityForecastForm = boundForm;
        }
        CapacityForecastForm capacityForecastFormData = capacityForecastForm.get();

        /**
         * Compute the period according to the selected year.
         */
        Calendar yearStartDay = Calendar.getInstance();
        yearStartDay.set(Calendar.YEAR, capacityForecastFormData.year.intValue());
        yearStartDay.set(Calendar.MONTH, 0);
        yearStartDay.set(Calendar.DAY_OF_MONTH, 1);
        yearStartDay.set(Calendar.HOUR_OF_DAY, 0);
        yearStartDay.set(Calendar.MINUTE, 0);
        yearStartDay.set(Calendar.SECOND, 0);
        yearStartDay.set(Calendar.MILLISECOND, 0);

        Calendar yearEndDay = Calendar.getInstance();
        yearEndDay.set(Calendar.YEAR, capacityForecastFormData.year.intValue());
        yearEndDay.set(Calendar.MONTH, 11);
        yearEndDay.set(Calendar.DAY_OF_MONTH, 31);
        yearEndDay.set(Calendar.HOUR_OF_DAY, 23);
        yearEndDay.set(Calendar.MINUTE, 59);
        yearEndDay.set(Calendar.SECOND, 59);
        yearEndDay.set(Calendar.MILLISECOND, 999);

        /**
         * Get the PE allocations.
         */
        List<PortfolioEntryResourcePlanAllocatedOrgUnit> allocatedOrgUnits = new ArrayList<>();
        List<PortfolioEntryResourcePlanAllocatedCompetency> allocatedCompetencies = new ArrayList<>();
        List<PortfolioEntryResourcePlanAllocatedActor> allocatedActors = new ArrayList<>();
        for (String idString : ids) {

            Long id = Long.valueOf(idString);

            // Org unit: all allocated org units of the selected PE
            allocatedOrgUnits.addAll(PortfolioEntryResourcePlanDAO.getPEResourcePlanAllocatedOrgUnitAsListByPE(
                    id, yearStartDay.getTime(), yearEndDay.getTime(), capacityForecastFormData.onlyConfirmed,
                    null));

            // Competencies: all allocated competencies of the selected PE
            allocatedCompetencies.addAll(PortfolioEntryResourcePlanDAO.getPEPlanAllocatedCompetencyAsListByPE(
                    id, yearStartDay.getTime(), yearEndDay.getTime(), capacityForecastFormData.onlyConfirmed,
                    null));

            // Actor: all allocated actors of the selected PE
            allocatedActors.addAll(
                    PortfolioEntryResourcePlanDAO.getPEPlanAllocatedActorAsListByPE(id, yearStartDay.getTime(),
                            yearEndDay.getTime(), capacityForecastFormData.onlyConfirmed, null, null));

        }

        /**
         * Compute the capacities for the org unit and actor allocations and
         * group them by org unit.
         */

        Map<Long, OrgUnitCapacity> orgUnitCapacities = new HashMap<>();

        // Org unit: the org unit is simply the one of the allocated org
        // unit.
        for (PortfolioEntryResourcePlanAllocatedOrgUnit allocatedOrgUnit : allocatedOrgUnits) {

            OrgUnitCapacity orgUnitCapacity = null;
            if (orgUnitCapacities.containsKey(allocatedOrgUnit.orgUnit.id)) {
                orgUnitCapacity = orgUnitCapacities.get(allocatedOrgUnit.orgUnit.id);
            } else {
                orgUnitCapacity = new OrgUnitCapacity(warningLimitPercent, allocatedOrgUnit.orgUnit);
                orgUnitCapacities.put(allocatedOrgUnit.orgUnit.id, orgUnitCapacity);
            }

            computeCapacity(allocatedOrgUnit.startDate, allocatedOrgUnit.endDate,
                    getAllocatedDays(allocatedOrgUnit.days, allocatedOrgUnit.forecastDays),
                    capacityForecastFormData.year, orgUnitCapacity);
        }

        // Actor: the org unit is the one of the actor of the allocated
        // actor.
        for (PortfolioEntryResourcePlanAllocatedActor allocatedActor : allocatedActors) {

            if (allocatedActor.actor.orgUnit != null) {

                OrgUnitCapacity orgUnitCapacity = null;
                if (orgUnitCapacities.containsKey(allocatedActor.actor.orgUnit.id)) {
                    orgUnitCapacity = orgUnitCapacities.get(allocatedActor.actor.orgUnit.id);
                } else {
                    orgUnitCapacity = new OrgUnitCapacity(warningLimitPercent, allocatedActor.actor.orgUnit);
                    orgUnitCapacities.put(allocatedActor.actor.orgUnit.id, orgUnitCapacity);
                }

                computeCapacity(allocatedActor.startDate, allocatedActor.endDate,
                        getAllocatedDays(allocatedActor.days, allocatedActor.forecastDays),
                        capacityForecastFormData.year, orgUnitCapacity);

            }
        }

        /**
         * Compute the capacities for the competencies and actor allocations
         * and group them by competency.
         */

        Map<Long, CompetencyCapacity> competencyCapacities = new HashMap<>();

        // Competency: the competency is simply the one of the allocated
        // comptency.
        for (PortfolioEntryResourcePlanAllocatedCompetency allocatedCompetency : allocatedCompetencies) {

            CompetencyCapacity competencyCapacity = null;
            if (competencyCapacities.containsKey(allocatedCompetency.competency.id)) {
                competencyCapacity = competencyCapacities.get(allocatedCompetency.competency.id);
            } else {
                competencyCapacity = new CompetencyCapacity(warningLimitPercent,
                        allocatedCompetency.competency);
                competencyCapacities.put(allocatedCompetency.competency.id, competencyCapacity);
            }

            computeCapacity(allocatedCompetency.startDate, allocatedCompetency.endDate,
                    allocatedCompetency.days, capacityForecastFormData.year, competencyCapacity);
        }

        // Actor: the competency is the one of the actor of the allocated
        // actor.
        for (PortfolioEntryResourcePlanAllocatedActor allocatedActor : allocatedActors) {

            if (allocatedActor.actor.defaultCompetency != null) {

                CompetencyCapacity competencyCapacity = null;
                if (competencyCapacities.containsKey(allocatedActor.actor.defaultCompetency.id)) {
                    competencyCapacity = competencyCapacities.get(allocatedActor.actor.defaultCompetency.id);
                } else {
                    competencyCapacity = new CompetencyCapacity(warningLimitPercent,
                            allocatedActor.actor.defaultCompetency);
                    competencyCapacities.put(allocatedActor.actor.defaultCompetency.id, competencyCapacity);
                }

                computeCapacity(allocatedActor.startDate, allocatedActor.endDate,
                        getAllocatedDays(allocatedActor.days, allocatedActor.forecastDays),
                        capacityForecastFormData.year, competencyCapacity);

            }
        }

        /**
         * Get and compute the activity capacities and the actor available
         * capacities.
         */

        for (Entry<Long, OrgUnitCapacity> entry : orgUnitCapacities.entrySet()) {

            OrgUnitCapacity orgUnitCapacity = entry.getValue();

            // Get the activity allocations.
            List<TimesheetActivityAllocatedActor> allocatedActivities = TimesheetDao
                    .getTimesheetActivityAllocatedActorAsListByOrgUnitAndPeriod(orgUnitCapacity.getOrgUnit().id,
                            yearStartDay.getTime(), yearEndDay.getTime());

            // Compute the activity allocations.
            for (TimesheetActivityAllocatedActor allocatedActivity : allocatedActivities) {
                computeCapacity(allocatedActivity.startDate, allocatedActivity.endDate, allocatedActivity.days,
                        capacityForecastFormData.year, orgUnitCapacity);
            }

            // Get the available actor capacities.
            List<ActorCapacity> actorCapacities = ActorDao.getActorCapacityAsListByOrgUnitAndYear(
                    orgUnitCapacity.getOrgUnit().id, capacityForecastFormData.year);

            // Compute the available actor capacities.
            for (ActorCapacity actorCapacity : actorCapacities) {
                orgUnitCapacity.addAvailable(actorCapacity.month.intValue() - 1, actorCapacity.value);
            }
        }

        for (Entry<Long, CompetencyCapacity> entry : competencyCapacities.entrySet()) {

            CompetencyCapacity competencyCapacity = entry.getValue();

            // Get the activity allocations.
            List<TimesheetActivityAllocatedActor> allocatedActivities = TimesheetDao
                    .getTimesheetActivityAllocatedActorAsListByCompetencyAndPeriod(
                            competencyCapacity.getCompetency().id, yearStartDay.getTime(),
                            yearEndDay.getTime());

            // Compute the activity allocations.
            for (TimesheetActivityAllocatedActor allocatedActivity : allocatedActivities) {
                computeCapacity(allocatedActivity.startDate, allocatedActivity.endDate, allocatedActivity.days,
                        capacityForecastFormData.year, competencyCapacity);
            }

            // Get the available actor capacities.
            List<ActorCapacity> actorCapacities = ActorDao.getActorCapacityAsListByCompetencyAndYear(
                    competencyCapacity.getCompetency().id, capacityForecastFormData.year);

            // Compute the available actor capacities.
            for (ActorCapacity actorCapacity : actorCapacities) {
                competencyCapacity.addAvailable(actorCapacity.month.intValue() - 1, actorCapacity.value);
            }
        }

        return ok(views.html.core.roadmap.roadmap_capacity_forecast.render(capacityForecastForm,
                new ArrayList<OrgUnitCapacity>(orgUnitCapacities.values()),
                new ArrayList<CompetencyCapacity>(competencyCapacities.values())));

    } catch (Exception e) {
        return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(),
                getI18nMessagesPlugin());
    }

}

From source file:org.loklak.api.server.push.GeoJsonPushServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RemoteAccess.Post 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 2 s  .c  o 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.hasValue(source_type_str)) {
        DAO.log("invalid or missing source_type value : " + source_type_str);
        source_type_str = SourceType.IMPORT.name();
    }
    SourceType sourceType = SourceType.valueOf(source_type_str);

    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 List<Map<String, Object>> features;
    byte[] jsonText;
    try {
        jsonText = ClientConnection.download(url);
        Map<String, Object> map = DAO.jsonMapper.readValue(jsonText, DAO.jsonTypeRef);
        Object features_obj = map.get("features");
        features = features_obj instanceof List<?> ? (List<Map<String, Object>>) features_obj : null;
    } 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;
        }
    }

    List<Map<String, Object>> rawMessages = new ArrayList<>();
    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    PushReport nodePushReport = new PushReport();
    for (Map<String, Object> feature : features) {
        Object properties_obj = feature.get("properties");
        @SuppressWarnings("unchecked")
        Map<String, Object> properties = properties_obj instanceof Map<?, ?>
                ? (Map<String, Object>) properties_obj
                : null;
        Object geometry_obj = feature.get("geometry");
        @SuppressWarnings("unchecked")
        Map<String, Object> geometry = geometry_obj instanceof Map<?, ?> ? (Map<String, Object>) geometry_obj
                : null;

        if (properties == null) {
            properties = new HashMap<>();
        }
        if (geometry == null) {
            geometry = new HashMap<>();
        }

        Map<String, Object> message = new HashMap<>();

        // add mapped properties
        Map<String, Object> mappedProperties = convertMapRulesProperties(mapRules, properties);
        message.putAll(mappedProperties);

        if (!"".equals(sourceType)) {
            message.put("source_type", sourceType.name());
        } else {
            message.put("source_type", SourceType.IMPORT);
        }
        message.put("provider_type", MessageEntry.ProviderType.GEOJSON.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.add(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);
}

From source file:controllers.core.PortfolioEntryPlanningController.java

/**
 * Display the planning packages of a portfolio entry with a gantt view.
 * // w  ww. ja v a2  s .c  o m
 * @param id
 *            the portfolio entry id
 */
@With(CheckPortfolioEntryExists.class)
@Dynamic(IMafConstants.PORTFOLIO_ENTRY_DETAILS_DYNAMIC_PERMISSION)
public Result packages(Long id) {

    // get the portfolioEntry
    PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(id);

    try {

        // get the filter config
        String uid = getUserSessionManagerPlugin().getUserSessionId(ctx());
        FilterConfig<PortfolioEntryPlanningPackageListView> filterConfig = this.getTableProvider()
                .get().portfolioEntryPlanningPackage.filterConfig.getCurrent(uid, request());

        // get the table
        Pair<Table<PortfolioEntryPlanningPackageListView>, Pagination<PortfolioEntryPlanningPackage>> t = getPackagesTable(
                id, filterConfig, getMessagesPlugin());

        // get the available groups
        List<PortfolioEntryPlanningPackageGroup> groups = PortfolioEntryPlanningPackageDao
                .getPEPlanningPackageGroupActiveNonEmptyAsList();

        // get the syndicated reports
        List<DataSyndicationAgreementLink> agreementLinks = new ArrayList<>();
        DataSyndicationAgreementItem agreementItem = null;
        if (portfolioEntry.isSyndicated && getDataSyndicationService().isActive()) {
            try {
                agreementItem = getDataSyndicationService().getAgreementItemByDataTypeAndDescriptor(
                        PortfolioEntry.class.getName(), "PLANNING_PACKAGE");
                if (agreementItem != null) {
                    agreementLinks = getDataSyndicationService().getAgreementLinksOfItemAndSlaveObject(
                            agreementItem, PortfolioEntry.class.getName(), id);
                }
            } catch (Exception e) {
                Logger.error("impossible to get the syndicated planning package data", e);
            }
        }

        // construct the gantt

        ExpressionList<PortfolioEntryPlanningPackage> expressionList = filterConfig.updateWithSearchExpression(
                PortfolioEntryPlanningPackageDao.getPEPlanningPackageAsExprByPE(id));
        filterConfig.updateWithSortExpression(expressionList);

        // initiate the sortable collection
        SortableCollection<DateSortableObject> sortableCollection = new SortableCollection<>();

        for (PortfolioEntryPlanningPackage planningPackage : expressionList.findList()) {

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

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

            if (to != null) {

                SourceItem item = new SourceItem(planningPackage.name, "");

                String cssClass = null;

                if (from != null) {

                    to = JqueryGantt.cleanToDate(from, to);
                    cssClass = planningPackage.portfolioEntryPlanningPackageType.cssClass;

                } else {

                    from = to;
                    cssClass = "diamond diamond-" + planningPackage.portfolioEntryPlanningPackageType.cssClass;

                }

                item.values.add(new SourceValue(from, to, "", "", cssClass, null));

                sortableCollection.addObject(new DateSortableObject(from, item));

            }

        }

        List<SourceItem> items = new ArrayList<SourceItem>();
        for (ISortableObject sortableObject : sortableCollection.getSorted()) {
            SourceItem item = (SourceItem) sortableObject.getObject();
            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.portfolioentryplanning.packages.render(portfolioEntry, t.getLeft(),
                t.getRight(), filterConfig, groups, ganttSource, agreementLinks, agreementItem));

    } catch (Exception e) {

        return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(), getMessagesPlugin());

    }

}

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

public static JSONObject getServerByProject(Long projectId, Long acenteraId) {

    //SecurityUtils.getSubject()
    SecurityController.checkPermission(projectId);

    try {// w  ww  .j  a  va  2  s.  c  o m
        ProjectDevices projectDevice = ProjectImpl.getProjectServer(projectId, acenteraId);

        if (!(SecurityController.isTagPermitted(projectId, projectDevice))) {
            return null;
        }

        ProjectProviders prov = projectDevice.getProviders();

        JSONObject res = new JSONObject();
        JSONArray jsoServersArray = new JSONArray();

        List<DropletImage> lstDropletImages = null;
        List<Region> lstRegions = null;
        List<DropletSize> lstSize = null;

        //TODO: Refactor to support more Cloud Providers....
        try {
            DigitalOcean apiClient = new DigitalOceanClient(prov.getApikey(), prov.getSecretkey());

            Droplet droplet = apiClient.getDropletInfo(Integer.valueOf(projectDevice.getExternalId()));

            if (droplet != null) {
                JSONObject jso = new JSONObject();

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

                if (lstDropletImages == null) {
                    lstDropletImages = apiClient.getAvailableImages();
                }
                if (lstRegions == null) {
                    lstRegions = apiClient.getAvailableRegions();
                }

                if (lstSize == null) {
                    lstSize = apiClient.getAvailableSizes();
                }

                DropletImage dimage = null;
                Iterator<DropletImage> itrImages = lstDropletImages.iterator();
                while (dimage == null && itrImages.hasNext()) {
                    DropletImage img = itrImages.next();
                    if (img.getId().intValue() == droplet.getImageId().intValue()) {
                        dimage = img;
                    }
                }

                Region dregion = null;
                Iterator<Region> itrRegions = lstRegions.iterator();
                while (dregion == null && itrRegions.hasNext()) {
                    Region region = itrRegions.next();
                    if (region.getId().intValue() == droplet.getRegionId().intValue()) {
                        dregion = region;
                    }
                }

                DropletSize dsize = null;
                Iterator<DropletSize> itrSize = lstSize.iterator();
                while (dsize == null && itrSize.hasNext()) {
                    DropletSize size = itrSize.next();
                    Logger.debug("COMPARE SIZE OF : " + size.getId() + " VS " + droplet.getSizeId());
                    if (size.getId().intValue() == droplet.getSizeId().intValue()) {
                        Logger.debug(
                                "COMPARE SIZE OF : " + size.getId() + " VS " + droplet.getSizeId() + " FOUND");
                        dsize = size;
                    }
                }

                JSONObject jsoDropletImage = JSONObject.fromObject(ow.writeValueAsString(droplet));

                if (dimage != null) {
                    jsoDropletImage.put("image_distibution", dimage.getDistribution());
                    jsoDropletImage.put("image_name", dimage.getName());
                }

                if (dregion != null) {
                    jsoDropletImage.put("region_slug", dregion.getSlug());
                    jsoDropletImage.put("region_name", dregion.getName());
                }

                if (dsize != null) {
                    jsoDropletImage.put("size", dsize);
                }

                jsoDropletImage.put("external_id", droplet.getId());
                jsoDropletImage.put("type", projectDevice.getType());
                jsoDropletImage.put("id", projectDevice.getId());
                jsoDropletImage.put("provider", prov.getId());

                Set<ProjectProvidersRegions> lstRegionsProvider = prov.getRegions();
                Iterator<ProjectProvidersRegions> itrRegionsProviders = lstRegionsProvider.iterator();
                ProjectProvidersRegions selectedRegion = null;
                while (itrRegionsProviders.hasNext() && selectedRegion == null) {
                    ProjectProvidersRegions ppr = itrRegionsProviders.next();
                    if (ppr.getExtId() != null) {
                        if (ppr.getExtId().intValue() == droplet.getRegionId().intValue()) {
                            selectedRegion = ppr;
                        }
                    }
                }
                if (selectedRegion != null) {
                    jsoDropletImage.put("provider_region", selectedRegion.getProjectRegions().getId());
                }

                //droplet.getRegionId()

                //TODO: Can we edit ?
                if (SecurityController.isPermitted(projectId, PermisionTagConstants.SERVER,
                        projectDevice.getDevice().getId(), PermissionActionConstats.EDIT)) {
                    jsoDropletImage.put("canEdit", 1);
                }

                res.put("server", jsoDropletImage);
            }

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

        }

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

    return null;
}

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

public String getUserWithRolesAsJson(UserProjects uproject, User currentUser) {

    //TODO: Does currentUser have access to read this user information for this project ?

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

    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  va 2  s .  com
        Set<ProjectTags> projectTags = new HashSet<ProjectTags>();
        projectTags = ProjectImpl.getProjectTags(uproject);

        //jsoProject.put("user", lstUsers);
        JSONArray jsoProjectUserArray = new JSONArray();
        JSONArray jsoUserArray = new JSONArray();
        Project p = uproject.getProject();

        JSONArray jsoProjectIdArray = new JSONArray();
        jsoProjectIdArray.add(p.getId());

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

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

        //Get the User Roles infos
        JSONArray jsRolesArray = new JSONArray();
        Set<ProjectTags> roles = ProjectImpl.getUserProjectRoles(uproject);
        Iterator<ProjectTags> itrRoles = roles.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);

        jso.put("users", jsoUserArray);

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

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

            Set<ProjectProviders> userAccessProviders = new HashSet<ProjectProviders>();
            Iterator<ProjectProviders> itrProjectProviders = lstProviders.iterator();
            while (itrProjectProviders.hasNext()) {
                ProjectProviders pr = itrProjectProviders.next();
                if (SecurityController.isPermitted(p, pr)) {
                    userAccessProviders.add(pr);
                }
            }

            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);
        }

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

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

    return jso.toString();
}

From source file:controllers.core.PortfolioEntryPlanningController.java

/**
 * Display global gantt chart of the initiative.
 * /*from   w  w  w  . j  ava2  s.  c om*/
 * Life cycle phases of the process (with is_roadmap_phase = false)<br/>
 * Life cycle milestones (diamond)<br/>
 * Planning packages<br/>
 * Iterations<br/>
 * 
 * Configuration:<br/>
 * -Display phases<br/>
 * -Display milestones<br/>
 * -Display packages<br/>
 * -Display iterations<br/>
 * 
 * 
 * @param id
 *            the portfolio entry id
 */
@With(CheckPortfolioEntryExists.class)
@Dynamic(IMafConstants.PORTFOLIO_ENTRY_DETAILS_DYNAMIC_PERMISSION)
public Result overview(Long id) {

    // load the overview configuration from the user preference
    OverviewConfiguration conf = OverviewConfiguration.load(this.getPreferenceManagerPlugin());

    // prepare the overview configuration form
    Form<OverviewConfiguration> overviewConfigurationForm = overviewConfigurationFormTemplate.fill(conf);

    // get the portfolioEntry
    PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(id);

    // get the active life cycle process instance
    LifeCycleInstance processInstance = portfolioEntry.activeLifeCycleInstance;

    // get the last planned milestone instances
    List<PlannedLifeCycleMilestoneInstance> lastPlannedMilestoneInstances = LifeCyclePlanningDao
            .getPlannedLCMilestoneInstanceLastAsListByPE(portfolioEntry.id);

    // initiate the sortable collection
    SortableCollection<ComplexSortableObject> sortableCollection = new SortableCollection<>();

    /** Life cycle phases of the process (with is_roadmap_phase = false) **/

    if (conf.phases) {

        // get the all phases of a process
        List<LifeCyclePhase> lifeCyclePhases = LifeCycleMilestoneDao
                .getLCPhaseAsListByLCProcess(processInstance.lifeCycleProcess.id);

        if (lifeCyclePhases != null && !lifeCyclePhases.isEmpty() && lastPlannedMilestoneInstances != null
                && lastPlannedMilestoneInstances.size() > 0) {

            // get the CSS class
            String cssClass = "success";

            // create the source data value
            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.PortfolioEntryGovernanceController.index(portfolioEntry.id).url(),
                    null, null, null, null);

            // transform the list of last planned milestone instances to a
            // map
            Map<Long, PlannedLifeCycleMilestoneInstance> lastPlannedMilestoneInstancesAsMap = new HashMap<Long, PlannedLifeCycleMilestoneInstance>();
            for (PlannedLifeCycleMilestoneInstance plannedMilestoneInstance : lastPlannedMilestoneInstances) {
                lastPlannedMilestoneInstancesAsMap.put(plannedMilestoneInstance.lifeCycleMilestone.id,
                        plannedMilestoneInstance);
            }

            for (LifeCyclePhase phase : lifeCyclePhases) {

                if (lastPlannedMilestoneInstancesAsMap.containsKey(phase.startLifeCycleMilestone.id)
                        && lastPlannedMilestoneInstancesAsMap.containsKey(phase.endLifeCycleMilestone.id)) {

                    // get the from date
                    Date from = LifeCyclePlanningDao.getPlannedLCMilestoneInstanceAsPassedDate(
                            lastPlannedMilestoneInstancesAsMap.get(phase.startLifeCycleMilestone.id).id);

                    // get the to date
                    Date to = LifeCyclePlanningDao.getPlannedLCMilestoneInstanceAsPassedDate(
                            lastPlannedMilestoneInstancesAsMap.get(phase.endLifeCycleMilestone.id).id);

                    if (from != null && to != null) {

                        to = JqueryGantt.cleanToDate(from, to);

                        // add gap for the from date
                        if (phase.gapDaysStart != null && phase.gapDaysStart.intValue() > 0) {
                            Calendar c = Calendar.getInstance();
                            c.setTime(from);
                            c.add(Calendar.DATE, phase.gapDaysStart);
                            from = c.getTime();
                        }

                        // remove gap for the to date
                        if (phase.gapDaysEnd != null && phase.gapDaysEnd.intValue() > 0) {
                            Calendar c = Calendar.getInstance();
                            c.setTime(to);
                            c.add(Calendar.DATE, -1 * phase.gapDaysEnd);
                            to = c.getTime();
                        }

                        SourceItem item = new SourceItem(phase.getName(), null);

                        item.values.add(new SourceValue(from, to, "", phase.getName(), cssClass, dataValue));

                        sortableCollection.addObject(new ComplexSortableObject(from, 1,
                                phase.order != null ? phase.order : 0, item));

                    }

                }

            }

        }

    }

    /** Life cycle milestones (diamond) **/

    if (conf.milestones && lastPlannedMilestoneInstances != null && lastPlannedMilestoneInstances.size() > 0) {

        // get the CSS class
        String cssClass = "diamond diamond-danger";

        for (PlannedLifeCycleMilestoneInstance plannedMilestoneInstance : lastPlannedMilestoneInstances) {

            // create the source data value
            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.PortfolioEntryGovernanceController
                            .viewMilestone(portfolioEntry.id, plannedMilestoneInstance.lifeCycleMilestone.id)
                            .url(),
                    null, null, null, null);

            // get the from date
            Date from = LifeCyclePlanningDao
                    .getPlannedLCMilestoneInstanceAsPassedDate(plannedMilestoneInstance.id);

            // get the to date
            Date to = from;

            if (from != null) {

                SourceItem item = new SourceItem(plannedMilestoneInstance.lifeCycleMilestone.getShortName(),
                        null);

                item.values.add(new SourceValue(from, to, "", "", cssClass, dataValue));

                sortableCollection.addObject(new ComplexSortableObject(from, 2, 0, item));

            }

        }

    }

    /** Planning packages **/

    if (conf.packages) {

        for (PortfolioEntryPlanningPackage planningPackage : PortfolioEntryPlanningPackageDao
                .getPEPlanningPackageAsListByPE(portfolioEntry.id)) {

            // create the source data value
            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.PortfolioEntryPlanningController
                            .viewPackage(portfolioEntry.id, planningPackage.id).url(),
                    null, null, null, null);

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

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

            if (to != null) {

                String cssClass = null;

                if (from != null) {

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

                } else {

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

                }

                SourceItem item = new SourceItem(planningPackage.name, null);

                item.values.add(new SourceValue(from, to, "", planningPackage.name, cssClass, dataValue));

                sortableCollection.addObject(new ComplexSortableObject(from, 5, 0, item));

            }

        }

    }

    /** Iterations **/

    if (conf.iterations) {

        for (Iteration iteration : IterationDAO.getIterationAllAsListByPE(portfolioEntry.id)) {

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.PortfolioEntryDeliveryController
                            .viewIteration(portfolioEntry.id, iteration.id).url(),
                    null, null, null, null);

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

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

            if (to != null) {

                String cssClass = null;

                if (from != null) {

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

                } else {

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

                }

                SourceItem item = new SourceItem(iteration.name, null);

                item.values.add(new SourceValue(from, to, "", iteration.name, cssClass, dataValue));

                sortableCollection.addObject(new ComplexSortableObject(from, 4, 0, item));

            }

        }

    }

    /** construct the gantt **/

    List<SourceItem> items = new ArrayList<SourceItem>();
    for (ISortableObject sortableObject : sortableCollection.getSorted()) {
        Logger.debug(sortableObject.getSortableAttributesAsString());
        SourceItem item = (SourceItem) sortableObject.getObject();
        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.portfolioentryplanning.overview.render(portfolioEntry, ganttSource,
            overviewConfigurationForm));

}

From source file:org.encuestame.mvc.page.jsonp.EmbebedJsonServices.java

/**
 * Generate the body of selected item./*from ww w.  jav  a2 s  .  c  om*/
 * @param itemId
 * @param callback
 * @param request
 * @param response
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@RequestMapping(value = "/api/jsonp/generate/code/{type}/embedded", method = RequestMethod.GET)
public void embedded(@RequestParam(value = "id", required = true) Long itemId, @PathVariable final String type,
        @RequestParam(value = "callback", required = true) String callback,
        @RequestParam(value = "embedded_type", required = false) String embedded, HttpServletRequest request,
        HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
    PrintWriter out = response.getWriter();
    String text = "";
    final JavascriptEmbebedBody embebedBody = new JavascriptEmbebedBody();
    final Map model = new HashMap();
    final ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    try {
        @SuppressWarnings("rawtypes")
        final String domain = WidgetUtil.getRelativeDomain(request);
        final TypeSearchResult typeItem = TypeSearchResult.getTypeSearchResult(type);
        if (typeItem != null) {
            final EmbeddedType embeddedType = EnumerationUtils.getEnumFromString(EmbeddedType.class, embedded);
            response.setContentType("text/javascript; charset=UTF-8");
            model.put("domain", domain);
            model.put("embedded_type", embeddedType.toString().toLowerCase());
            model.put("typeItem", typeItem.toString().toLowerCase());
            model.put("itemId", itemId);
            model.put("class_type", TypeSearchResult.getCSSClass(typeItem));
            model.put("domain_config", WidgetUtil.getDomain(request, true));
            if (TypeSearchResult.TWEETPOLL.equals(typeItem)) {
                final TweetPoll tp = getTweetPollService().getTweetPollById(itemId);
                model.put("url", EnMeUtils.createTweetPollUrlAccess(domain, tp));
            } else if (TypeSearchResult.POLL.equals(typeItem)) {
                final Poll poll = getPollService().getPollById(itemId);
                model.put("url", EnMeUtils.createUrlPollAccess(domain, poll));
            } else if (TypeSearchResult.TWEETPOLLRESULT.equals(typeItem)) {
                final TweetPoll tp = getTweetPollService().getTweetPollById(itemId);
                model.put("url", EnMeUtils.createTweetPollUrlAccess(domain, tp));
            } else if (TypeSearchResult.POLLRESULT.equals(typeItem)) {
                final Poll poll = getPollService().getPollById(itemId);
                model.put("url", EnMeUtils.createUrlPollAccess(domain, poll));
            } else if (TypeSearchResult.HASHTAG.equals(typeItem)) {
                //FUTURE:
                model.put("url", "");
            } else if (TypeSearchResult.PROFILE.equals(typeItem)) {
                //FUTURE: should be username instead ID
                final UserAccount user = getSecurityService().getUserbyId(itemId);
                model.put("url", domain + "/profile/" + user.getUsername());
            }
            text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    CODE_TEMPLATES + embeddedType.toString().toLowerCase() + "_code.vm", "utf-8", model);
            String string = new String(text.getBytes("UTF-8"));
            embebedBody.setBody(string);
            final String json = ow.writeValueAsString(embebedBody);
            out.print(callback + "(" + json + ")");
        } else {
            createWrongBody(model, embebedBody);
            final String json = ow.writeValueAsString(embebedBody);
            out.print(callback + "(" + json + ")");
        }
    } catch (Exception e) {
        try {
            createWrongBody(model, embebedBody);
            final String json = ow.writeValueAsString(embebedBody);
            out.print(callback + "(" + json + ")");
        } catch (Exception ex) {
            ex.printStackTrace();
            log.fatal("creating wrong body has failed");
        }
    }
}

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

public static JSONObject getServerByProjectAndUserAccess(Long projectId, String providerName, Long serverId) {

    //SecurityUtils.getSubject()

    try {/*from  w w w  .j a  v a 2 s.co m*/

        Set<ProjectProviders> lstProviders = ProjectImpl.getCloudProviders(projectId);

        Iterator<ProjectProviders> itrProviders = lstProviders.iterator();
        JSONObject res = new JSONObject();
        JSONArray jsoServersArray = new JSONArray();

        List<DropletImage> lstDropletImages = null;
        List<Region> lstRegions = null;
        List<DropletSize> lstSize = null;

        while (itrProviders.hasNext()) {
            ProjectProviders prov = itrProviders.next();

            //TODO: Refactor to support more Cloud Providers....
            try {
                Logger.debug("API KEY : " + prov.getApikey() + " and secret : " + prov.getSecretkey());
                DigitalOcean apiClient = new DigitalOceanClient(prov.getApikey(), prov.getSecretkey());

                List<Droplet> lstDroplets = apiClient.getAvailableDroplets();

                if (lstDroplets != null) {
                    JSONObject jso = new JSONObject();

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

                    //jsoServersArray.add(ow.writeValueAsString(lstDroplets));
                    for (int i = 0; i < lstDroplets.size(); i++) {
                        Droplet droplet = lstDroplets.get(i);

                        if (lstDropletImages == null) {
                            lstDropletImages = apiClient.getAvailableImages();
                        }
                        if (lstRegions == null) {
                            lstRegions = apiClient.getAvailableRegions();
                        }

                        if (lstSize == null) {
                            lstSize = apiClient.getAvailableSizes();
                        }

                        DropletImage dimage = null;
                        Iterator<DropletImage> itrImages = lstDropletImages.iterator();
                        while (dimage == null && itrImages.hasNext()) {
                            DropletImage img = itrImages.next();
                            if (img.getId().intValue() == droplet.getImageId().intValue()) {
                                dimage = img;
                            }
                        }

                        Region dregion = null;
                        Iterator<Region> itrRegions = lstRegions.iterator();
                        while (dregion == null && itrRegions.hasNext()) {
                            Region region = itrRegions.next();
                            if (region.getId().intValue() == droplet.getRegionId().intValue()) {
                                dregion = region;
                            }
                        }

                        DropletSize dsize = null;
                        Iterator<DropletSize> itrSize = lstSize.iterator();
                        while (dsize == null && itrSize.hasNext()) {
                            DropletSize size = itrSize.next();
                            Logger.debug("COMPARE SIZE OF : " + size.getId() + " VS " + droplet.getSizeId());
                            if (size.getId().intValue() == droplet.getSizeId().intValue()) {
                                Logger.debug("COMPARE SIZE OF : " + size.getId() + " VS " + droplet.getSizeId()
                                        + " FOUND");
                                dsize = size;
                            }
                        }

                        JSONObject jsoDropletImage = JSONObject.fromObject(ow.writeValueAsString(droplet));

                        if (dimage != null) {
                            jsoDropletImage.put("image_distibution", dimage.getDistribution());
                            jsoDropletImage.put("image_name", dimage.getName());
                        }

                        if (dregion != null) {
                            jsoDropletImage.put("region_slug", dregion.getSlug());
                            jsoDropletImage.put("region_name", dregion.getName());
                        }

                        if (dsize != null) {
                            jsoDropletImage.put("size", dsize);
                        }
                        jsoServersArray.add(jsoDropletImage);
                    }

                } else {
                    //nothing
                }

                res.put("servers", jsoServersArray);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        //res.put("servers",jsoServersArray);
        return res;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}