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:com.acentera.utils.ProjectsHelpers.java

public static JSONObject getServersByProjectAndUserAccess(Long projectId, User user) {

    JSONObject res = new JSONObject();
    JSONArray jsoServersArray = new JSONArray();
    res.put("servers", jsoServersArray);
    try {// w w  w .j a v a2 s .com
        //TODO: Take the one that match the selected api tags only (ie: have access to)
        Set<ProjectProviders> lstProviders = ProjectImpl.getCloudProviders(projectId);

        Iterator<ProjectProviders> itrProviders = lstProviders.iterator();

        Logger.debug("GOT PROVIDER : " + lstProviders);

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

        Project p = ProjectImpl.getProject(projectId, user);
        Set<ProjectDevices> deviceSet = DeviceImpl.getDevices(projectId);

        HashMap<String, ProjectDevices> devicesToReturn = new HashMap<String, ProjectDevices>();
        Set<Long> processedDevices = new HashSet<Long>();

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

            //TODO: Refactor to support more Cloud Providers....
            try {
                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;
                            }
                        }

                        ProjectDevices deviceInProjectMapping = null;
                        Iterator<ProjectDevices> itrDevices = deviceSet.iterator();
                        while (itrDevices.hasNext() && deviceInProjectMapping == null) {
                            ProjectDevices pd = itrDevices.next();
                            //Try to find a device that matches the current one we are looking at..
                            if (((pd.getExternalId().compareTo(String.valueOf(droplet.getId())) == 0) && (pd
                                    .getProviders().getType().compareToIgnoreCase(prov.getType()) == 0))) {
                                deviceInProjectMapping = pd;
                            }
                        }

                        if (deviceInProjectMapping == null) {
                            //Device does not exists...
                            //Lets create a Generic GUID and also save the mapping...

                            //First create a Device
                            //Currently the framework doesn't automatically import data..
                            /*
                            Device dev = new Device();
                            dev.setProject(p);
                            dev.setPartner_id(user.getProject_id());
                            dev.setGUID(Utils.getUniqueGUID());
                            dev.setSalt(Utils.getRandomSalt());
                                    
                            ProjectDevices projectDevice = new ProjectDevices();
                            projectDevice.setDevice(dev);
                            projectDevice.setProject(p);
                            projectDevice.setExternalId( String.valueOf(droplet.getId()));
                            projectDevice.setProviders(prov);
                                    
                            DAO.save(dev);
                            DAO.save(projectDevice);
                            deviceInProjectMapping = projectDevice;
                            */
                        }

                        Logger.debug("deviceInProjectMapping");
                        if (deviceInProjectMapping != null) {
                            JSONObject jsoDroplet = JSONObject.fromObject(ow.writeValueAsString(droplet));

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

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

                            if (dsize != null) {
                                jsoDroplet.put("size", dsize);
                            }
                            ////jsoDroplet.put("acenteraid", deviceInProjectMapping.getDevice().getId());
                            jsoDroplet.put("acenteraid", deviceInProjectMapping.getId());

                            Logger.debug("deviceInProjectMapping acenteraid " + deviceInProjectMapping.getId());
                            jsoDroplet.put("external_id", droplet.getId());
                            jsoDroplet.put("id", deviceInProjectMapping.getId());
                            jsoDroplet.put("type", deviceInProjectMapping.getType());
                            deviceInProjectMapping.getDevice().setDropletInfo(jsoDroplet);

                            devicesToReturn.put(droplet.getId() + "_" + prov.getId(), deviceInProjectMapping);
                        }

                    }

                } else {
                    //nothing
                }

                //CHeck if all the api returned all the values... (what about api that we deleted??)
                Iterator<ProjectDevices> itrDevices = deviceSet.iterator();
                Logger.debug("GOT ProjectDevices  ??? ");
                while (itrDevices.hasNext()) {
                    ProjectDevices pd = itrDevices.next();
                    Logger.debug("GOT ProjectDevices : " + pd);
                    String key = pd.getExternalId() + "_" + pd.getProviders().getId();
                    if (!(devicesToReturn.containsKey(key))) {
                        //Device not found lets add

                        //We must get the JSONValue...
                        devicesToReturn.put(key, pd);
                    }
                }

                //At this point deviceTOReturn contains all of the entries...

                Logger.debug("deviceTOReturn ProjectDevices  ??? ");
                Iterator<Map.Entry<String, ProjectDevices>> itrResponse = devicesToReturn.entrySet().iterator();
                while (itrResponse.hasNext()) {
                    Map.Entry<String, ProjectDevices> item = itrResponse.next();
                    Logger.debug("deviceTOReturn ProjectDevices  : " + item.getValue());
                    Logger.debug("deviceTOReturn ProjectDevices  Device : " + item.getValue().getDevice());
                    Logger.debug("deviceTOReturn ProjectDevices  Device getDropletInfo : "
                            + item.getValue().getDevice().getDropletInfo());
                    if (item.getValue().getDevice().getDropletInfo().has("id")) {
                        if (!(processedDevices.contains(item.getValue().getDevice().getId()))) {
                            processedDevices.add(item.getValue().getDevice().getId());
                            jsoServersArray.add(item.getValue().getDevice().getDropletInfo());
                        }
                    }
                }

                Logger.debug("deviceInProjectMapping REGURNING OF : " + jsoServersArray);
                res.put("servers", jsoServersArray);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        //res.put("servers",jsoServersArray);

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

    return res;
}

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

/**
 * Generate the body of selected item./*from   ww w  .j  a  v  a  2s .c  om*/
 * @param pollId
 * @param callback
 * @param request
 * @param response
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@RequestMapping(value = "/api/jsonp/{type}/embedded", method = RequestMethod.GET)
public void typeJavascriptJSONP(
        // :TODO: Change parameter name pollId to id.
        @RequestParam(value = "id", required = true) Long pollId, @PathVariable final String type,
        @RequestParam(value = "callback", required = true) String callback, HttpServletRequest request,
        HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
    PrintWriter out = response.getWriter();
    String text = "";
    final int max_results = 1;
    final TypeSearchResult typeItem = TypeSearchResult.getTypeSearchResult(type);
    final JavascriptEmbebedBody embebedBody = new JavascriptEmbebedBody();
    final ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    @SuppressWarnings("rawtypes")
    final Map model = new HashMap();
    logPrint("typeItem::==" + typeItem);
    try {
        final String domain = WidgetUtil.getDomain(request, true);
        final String logo = EnMePlaceHolderConfigurer.getProperty("application.logo.icon");
        model.put("logo_enme", domain + "/resources/" + logo);
        model.put("domain", domain);
        model.put("typeItem", typeItem == null ? "" : typeItem.toString().toLowerCase());
        model.put("itemId", pollId);
        model.put("domain_config", domain);
        response.setContentType("text/javascript; charset=UTF-8");
        if (TypeSearchResult.TWEETPOLL.equals(typeItem)) {
            // generate tweetpoll body
            // generate tweetpoll body
            final TweetPoll tweetPoll = getTweetPollService().getTweetPollById(pollId);
            model.put("tp", tweetPoll);
            model.put("editorOwner", tweetPoll.getEditorOwner());
            model.put("votes", tweetPoll.getLikeVote());
            model.put("hits", tweetPoll.getHits());
            model.put("date_published", EnMeUtils.formatDate(tweetPoll.getCreateDate(), "HH:mm - d MMMM yyyy"));
            model.put("owner_picture",
                    domain + "/picture/profile/" + tweetPoll.getEditorOwner().getUsername() + "/thumbnail");
            model.put("owner_profile_url", domain + "/profile/" + tweetPoll.getEditorOwner().getUsername());
            StringBuffer buffer = new StringBuffer();
            String q = tweetPoll.getQuestion().getQuestion();
            final List<TweetPollSwitch> answers = getTweetPollService().getTweetPollSwitch(tweetPoll);
            final Set<HashTag> hashTags = tweetPoll.getHashTags();
            buffer.append(EnMeUtils.generateBodyTweetPollasHtml(domain, tweetPoll, q, answers, hashTags));
            model.put("body_text", buffer.toString());
            model.put("url_tpoll", domain + "/tweetpoll/" + tweetPoll.getTweetPollId() + "/"
                    + tweetPoll.getQuestion().getSlugQuestion());
            text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    HTML_TEMPLATES + "/tweetpoll_form.vm", "utf-8", model);
            final String string = new String(text.getBytes("UTF-8"));
            embebedBody.setBody(string);
        } else if (TypeSearchResult.TWEETPOLLRESULT.equals(typeItem)) {
            final TweetPoll tpoll = getTweetPollService().getTweetPollById(pollId);
            final TweetPollDetailBean tpollDetail = getTweetPollService().getTweetPollDetailInfo(pollId);
            model.put("owner_picture",
                    domain + "/picture/profile/" + tpoll.getEditorOwner().getUsername() + "/thumbnail");
            model.put("editorOwner", tpoll.getEditorOwner());
            model.put("question", tpoll.getQuestion());
            model.put("url", EnMeUtils.createTweetPollUrlAccess(domain, tpoll));
            model.put("answersList", tpollDetail.getResults());
            model.put("date_published", EnMeUtils.formatDate(tpoll.getCreateDate(), "HH:mm - d MMMM yyyy"));
            text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    HTML_TEMPLATES + "/tweetpoll_votes.vm", "utf-8", model);
            embebedBody.setAditionalInfo(tpollDetail.getResults());
            final String string = new String(text.getBytes("UTF-8"));
            embebedBody.setBody(string);
        } else if (TypeSearchResult.POLL.equals(typeItem)) {
            // generate poll body
            final Poll poll = getPollService().getPollById(pollId);
            // ENCUESTAME-664 temporally disabled
            if (poll.getIsPasswordProtected() != null && poll.getIsPasswordProtected()) {
                throw new EnMeException("password protected not embeddable");
            }
            final PollDetailBean detailBean = getPollService().getPollDetailInfo(poll.getPollId());
            model.put("owner_picture",
                    domain + "/picture/profile/" + poll.getEditorOwner().getUsername() + "/thumbnail");
            model.put("editorOwner", poll.getEditorOwner());
            model.put("title", poll.getQuestion().getQuestion());
            model.put("date_published", EnMeUtils.formatDate(poll.getCreateDate(), "HH:mm - d MMMM yyyy"));
            model.put("poll", poll);
            model.put("action", WidgetUtil.getDomain(request) + "/poll/vote/post");
            model.put("detailBean", detailBean);
            model.put("vote_title", "Vote");
            text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, HTML_TEMPLATES + "/poll_form.vm",
                    "utf-8", model);
            final String string = new String(text.getBytes("UTF-8"));
            embebedBody.setBody(string);
        } else if (TypeSearchResult.POLLRESULT.equals(typeItem)) {
            // generate poll body
            final Poll poll = getPollService().getPollById(pollId);
            final PollDetailBean detailBean = getPollService().getPollDetailInfo(poll.getPollId());
            model.put("owner_picture",
                    domain + "/picture/profile/" + poll.getEditorOwner().getUsername() + "/thumbnail");
            model.put("editorOwner", poll.getEditorOwner());
            model.put("question", poll.getQuestion());
            model.put("url", EnMeUtils.createUrlPollAccess(domain, poll));
            model.put("answersList", detailBean.getResults());
            model.put("date_published", EnMeUtils.formatDate(poll.getCreateDate(), "HH:mm - d MMMM yyyy"));
            text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    HTML_TEMPLATES + "/tweetpoll_votes.vm", "utf-8", model);
            embebedBody.setAditionalInfo(detailBean.getResults());
            final String string = new String(text.getBytes("UTF-8"));
            embebedBody.setBody(string);
        } else if (TypeSearchResult.HASHTAG.equals(typeItem)) {
            // generate hashtag body
            model.put("hellow", "world");
            text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, HTML_TEMPLATES + "/hashtag.vm",
                    "utf-8", model);
            final String string = new String(text.getBytes("UTF-8"));
            embebedBody.setBody(string);
        } else if (TypeSearchResult.PROFILE.equals(typeItem)) {
            final UserAccount user = getSecurityService().getUserbyId(pollId);
            model.put("owner_picture", domain + "/picture/profile/" + user.getUsername() + "/thumbnail");
            model.put("editorOwner", user);
            model.put("profile", user.getUsername());
            model.put("owner_profile_url", domain + "/profile/" + user.getUsername());
            model.put("picture",
                    getPictureService().getProfilePicture(user.getUsername(), PictureType.DEFAULT));
            model.put("total_tweets", getFrontService().getTotalItemsPublishedByType(user, Boolean.TRUE,
                    TypeSearchResult.TWEETPOLL));
            model.put("total_poll",
                    getFrontService().getTotalItemsPublishedByType(user, Boolean.TRUE, TypeSearchResult.POLL));
            model.put("total_survey", getFrontService().getTotalItemsPublishedByType(user, Boolean.TRUE,
                    TypeSearchResult.SURVEY));
            final List<HomeBean> lastPublication = getFrontService().getLastItemsPublishedFromUserAccount(
                    user.getUsername(), max_results, Boolean.FALSE, request);
            if (lastPublication.size() >= 1) {
                model.put("last_publication", lastPublication.get(0));
            }
            text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, HTML_TEMPLATES + "/profile.vm",
                    "utf-8", model);
            final String string = new String(text.getBytes("UTF-8"));
            embebedBody.setBody(string);
        } else {
            createWrongBody(model, embebedBody);
        }
        final String json = ow.writeValueAsString(embebedBody);
        out.print(callback + "(" + json + ")");
    } catch (Exception e) {
        //e.printStackTrace();
        log.error(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");
        }
    }
}