Example usage for com.fasterxml.jackson.databind ObjectMapper writer

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writer

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writer.

Prototype

public ObjectWriter writer() 

Source Link

Document

Convenience method for constructing ObjectWriter with default settings.

Usage

From source file:org.geppetto.frontend.GeppettoServletController.java

/**
 * Get simulation watch lists//from w w w  .  j  av a 2  s  .  c  o m
 * 
 * @throws JsonProcessingException
 */
public void getWatchLists(String requestID, GeppettoMessageInbound visitor) throws JsonProcessingException {
    List<WatchList> watchLists = visitor.getSimulationService().getWatchLists();

    // serialize watch-lists
    ObjectMapper mapper = new ObjectMapper();
    String serializedLists = mapper.writer().writeValueAsString(watchLists);

    // message the client with results
    this.messageClient(requestID, visitor, OUTBOUND_MESSAGE_TYPES.GET_WATCH_LISTS, serializedLists);
}

From source file:org.geppetto.frontend.GeppettoServletController.java

/**
 * Request list of watchable variables for the simulation
 * /*from ww w .  j  av  a  2 s.co  m*/
 * @throws JsonProcessingException
 */
public void listWatchableVariables(String requestID, GeppettoMessageInbound visitor)
        throws JsonProcessingException {
    // get watchable variables for the entire simulation
    VariableList vars = visitor.getSimulationService().listWatchableVariables();

    // serialize
    ObjectMapper mapper = new ObjectMapper();
    String serializedVars = mapper.writer().writeValueAsString(vars);

    // message the client with results
    this.messageClient(requestID, visitor, OUTBOUND_MESSAGE_TYPES.LIST_WATCH_VARS, serializedVars);
}

From source file:org.geppetto.frontend.GeppettoServletController.java

/**
 * Request list of forceable variables for the simulation
 * /*from   w w w  .j a  v  a  2 s .  c  o  m*/
 * @throws JsonProcessingException
 */
public void listForceableVariables(String requestID, GeppettoMessageInbound visitor)
        throws JsonProcessingException {
    // get forceable variables for the entire simulation
    VariableList vars = visitor.getSimulationService().listForceableVariables();

    // serialize
    ObjectMapper mapper = new ObjectMapper();
    String serializedVars = mapper.writer().writeValueAsString(vars);

    // message the client with results
    this.messageClient(requestID, visitor, OUTBOUND_MESSAGE_TYPES.LIST_FORCE_VARS, serializedVars);
}

From source file:org.geppetto.frontend.GeppettoServletController.java

/**
 * instructs simulation to start sending watched variables value to the
 * client/*from   w ww  . j av a2  s. c  o m*/
 * 
 * @param requestID
 * @throws JsonProcessingException
 */
public void startWatch(String requestID, GeppettoMessageInbound visitor) throws JsonProcessingException {
    visitor.getSimulationService().startWatch();

    List<WatchList> watchLists = visitor.getSimulationService().getWatchLists();

    // serialize watch-lists
    ObjectMapper mapper = new ObjectMapper();
    String serializedLists = mapper.writer().writeValueAsString(watchLists);

    // message the client the watch lists were started
    messageClient(requestID, visitor, OUTBOUND_MESSAGE_TYPES.START_WATCH, serializedLists);
}

From source file:org.geppetto.frontend.GeppettoServletController.java

/**
 * Adds watch lists with variables to be watched
 * /*  w ww . j a  v a2  s.c om*/
 * @throws GeppettoExecutionException
 * @throws JsonProcessingException
 * @throws GeppettoInitializationException
 */
public void addWatchLists(String requestID, String jsonLists, GeppettoMessageInbound visitor)
        throws GeppettoExecutionException, GeppettoInitializationException {
    List<WatchList> lists = null;

    lists = fromJSON(new TypeReference<List<WatchList>>() {
    }, jsonLists);
    visitor.getSimulationService().addWatchLists(lists);

    // serialize watch-lists
    ObjectMapper mapper = new ObjectMapper();
    String serializedLists;
    try {
        serializedLists = mapper.writer().writeValueAsString(lists);
    } catch (JsonProcessingException e) {
        throw new GeppettoExecutionException(e);
    }

    // message the client the watch lists were added
    messageClient(requestID, visitor, OUTBOUND_MESSAGE_TYPES.SET_WATCH_LISTS, serializedLists);

}

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 {//from   ww w .  j a v a2 s  .co m
        //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:com.basistech.rosette.dm.json.plain.JsonTest.java

@Test
public void versionCheckPasses() throws Exception {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper());
    ObjectWriter objectWriter = mapper.writer();
    objectWriter.writeValue(writer, referenceTextOldEntities);
    mapper.readValue(writer.toString(), AnnotatedText.class);
}

From source file:com.basistech.rosette.dm.json.plain.JsonTest.java

@Test
public void versionInjected() throws Exception {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper());
    ObjectWriter objectWriter = mapper.writer();
    objectWriter.writeValue(writer, referenceTextOldEntities);
    // to tell that the version is there, we read as a tree
    JsonNode tree = mapper.readTree(writer.toString());
    String version = tree.get("version").asText();
    assertEquals("1.1.0", version);
}

From source file:com.chiralBehaviors.autoconfigure.AutoConfigure.java

private void saveRestartState() {
    RestartState state = new RestartState();
    ServiceReference reference = discovery.getReference(serviceRegistration.get());
    if (reference == null) {
        logger.info("Not saving restart state as no service was registered");
        return;//from ww  w .ja  va 2 s  .  c  o m
    }
    state.serviceURL = reference.getUrl().getServiceURL();
    state.serviceProperties = reference.getProperties();
    logger.info(String.format("Saving restart state to file: %s, url: %s, properties: %s",
            new File(config.restartStateFile).getAbsolutePath(), state.serviceURL, state.serviceProperties));
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writer().writeValue(new File(config.restartStateFile), state);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to save restart state", e);
    }
}

From source file:com.basistech.rosette.dm.json.plain.JsonTest.java

@Test
public void dataPlainString() throws Exception {
    CharSequence fancyCharSequence = new CharSequence() {
        private final String data = "Hello Polly";

        public String getExtraneousInfo() {
            return "What is this doing here?";
        }/*from   w w  w  . j  a  va 2s .c o m*/

        @Override
        public int length() {
            return data.length();
        }

        @Override
        public char charAt(int index) {
            return data.charAt(index);
        }

        @Override
        public CharSequence subSequence(int start, int end) {
            return data.substring(start, end);
        }

        @Override
        public String toString() {
            return data;
        }
    };

    AnnotatedText.Builder builder = new AnnotatedText.Builder();
    builder.data(fancyCharSequence);
    AnnotatedText text = builder.build();
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper());
    ObjectWriter objectWriter = mapper.writer();
    objectWriter.writeValue(writer, text);
    assertFalse(writer.toString().contains("What is this doing here"));
    assertTrue(writer.toString().contains("Hello Polly"));
}