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:eu.freme.broker.eservices.ELink.java

@RequestMapping(value = "/e-link/templates", method = RequestMethod.GET)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> getAllTemplates(
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        // @RequestParam(value = "outformat", required=false) String
        // outformat,
        // @RequestParam(value = "o", required=false) String o,
        @RequestParam Map<String, String> allParams) {
    try {/*from  ww w .  j  a va2s . co m*/
        NIFParameterSet nifParameters = this.normalizeNif(null, acceptHeader, contentTypeHeader, allParams,
                true);

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", nifParameters.getOutformat().contentType());

        List<Template> templates = templateDAO.findAllReadAccessible();
        if (nifParameters.getOutformat().equals(RDFConstants.RDFSerialization.JSON)) {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            String serialization = ow.writeValueAsString(templates);
            return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK);
        } else {
            Model mergedModel = ModelFactory.createDefaultModel();
            for (Template template : templates) {
                mergedModel.add(template.getRDF());
            }
            return new ResponseEntity<>(
                    rdfConversionService.serializeRDF(mergedModel, nifParameters.getOutformat()),
                    responseHeaders, HttpStatus.OK);
        }
    } catch (BadRequestException ex) {
        throw new BadRequestException(ex.getMessage());
    } catch (Exception ex) {
        Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex);
    }
    throw new InternalServerErrorException("Unknown problem. Please contact us.");
}

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

public static JSONObject getSshKeyAsJson(ProjectSshKey sshKey) throws JsonProcessingException {

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

    if (SecurityController.isPermitted(sshKey.getProjects(), sshKey)) {
        jso.put("sshkey", ow.writeValueAsString(sshKey));
    }/*w ww  . ja v a2  s .  c  om*/
    //jso.getJSONObject("sshkey").remove("tags");
    return jso;
}

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

public static String shutdownServer(Long projectId, Long serverId) throws Exception {

    ProjectProviders prov = ProjectImpl.getServerCloudProvider(projectId, serverId,
            SecurityController.getUser());
    ProjectDevices dev = ProjectImpl.getProjectServer(projectId, serverId);

    DigitalOcean apiClient = new DigitalOceanClient(prov.getApikey(), prov.getSecretkey());

    ProjectTasks task = new ProjectTasks();
    task.setName("Shutdown Server");
    task.setType("server");
    task.setProviderId(prov.getId());//  w ww .j  a  v a  2  s .c  om
    task.setProjects(prov.getProject());
    ProjectImpl.save(task);

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

    Response res = apiClient.powerOffDroplet(Integer.valueOf(dev.getExternalId()));
    Logger.debug("GOT RESPONSE OF : " + ow.writeValueAsString(res));

    task.setExtId(res.getEventId());

    ProjectImpl.update(task);

    JSONObject jsoTask = new JSONObject();
    jsoTask.put("task_id", task.getId());
    jsoTask.put("success", true);

    return jsoTask.toString();
}

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

public static String getProjectProvidersAsJson(ProjectProviders prov) {

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    ObjectWriter ow = mapper.writer();
    JSONObject jso = new JSONObject();
    try {// www .  java  2  s.  c  o  m
        Logger.debug("PROVIDER IS : " + prov.getId());
        jso.put("provider", ow.writeValueAsString(prov));
        return jso.toString();
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:eu.freme.broker.eservices.ELink.java

@RequestMapping(value = "/e-link/templates/{templateid}", method = RequestMethod.PUT)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> updateTemplateById(
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        // @RequestParam(value = "informat", required=false) String
        // informat,
        // @RequestParam(value = "f", required=false) String f,
        // @RequestParam(value = "outformat", required=false) String
        // outformat,
        // @RequestParam(value = "o", required=false) String o,
        @RequestParam(value = "owner", required = false) String ownerName,
        @PathVariable("templateid") long templateId, @RequestParam Map<String, String> allParams,
        @RequestBody String postBody) {

    try {/*ww w .j ava  2  s.  co m*/
        // NOTE: informat was defaulted to JSON before! Now it is TURTLE.
        // NOTE: outformat was defaulted to turtle, if acceptHeader=="*/*"
        // and informat==null, otherwise to JSON. Now it is TURTLE.
        NIFParameterSet nifParameters = this.normalizeNif(postBody, acceptHeader, contentTypeHeader, allParams,
                true);

        // validateTemplateID(templateId);
        // check read access
        Template template = templateDAO.findOneById(templateId);

        // Was the nif-input empty?
        if (nifParameters.getInput() != null) {
            if (nifParameters.getInformat().equals(RDFConstants.RDFSerialization.JSON)) {
                JSONObject jsonObj = new JSONObject(nifParameters.getInput());
                template.update(jsonObj);
            } else {
                Model model = rdfConversionService.unserializeRDF(nifParameters.getInput(),
                        nifParameters.getInformat());
                template.setTemplateWithModel(model);
            }
        }

        template = templateDAO.save(template);

        if (!Strings.isNullOrEmpty(ownerName)) {
            User owner = userDAO.getRepository().findOneByName(ownerName);
            if (owner == null)
                throw new BadRequestException(
                        "Can not change owner of the template. User \"" + ownerName + "\" does not exist.");
            template = templateDAO.updateOwner(template, owner);
        }

        String serialization;
        if (nifParameters.getOutformat().equals(RDFConstants.RDFSerialization.JSON)) {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            serialization = ow.writeValueAsString(template);
        } else {
            serialization = rdfConversionService.serializeRDF(template.getRDF(), nifParameters.getOutformat());
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        URI location = new URI("/e-link/templates/" + template.getId());
        responseHeaders.setLocation(location);
        responseHeaders.set("Content-Type", nifParameters.getOutformat().contentType());
        return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK);
    } catch (URISyntaxException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(ex.getMessage());
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.broker.exception.AccessDeniedException();
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (OwnedResourceNotFoundException ex) {
        logger.error(ex.getMessage(), ex);
        throw new TemplateNotFoundException("Template not found. " + ex.getMessage());
    } catch (org.json.JSONException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(
                "The JSON object is incorrectly formatted. Problem description: " + ex.getMessage());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
    throw new InternalServerErrorException("Unknown problem. Please contact us.");
}

From source file:eu.freme.broker.eservices.ELink.java

@RequestMapping(value = "/e-link/templates", method = RequestMethod.POST)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> createTemplate(
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        // @RequestParam(value = "informat", required=false) String
        // informat,
        // @RequestParam(value = "f", required=false) String f,
        // @RequestParam(value = "outformat", required=false) String
        // outformat,
        // @RequestParam(value = "o", required=false) String o,
        // Type was moved as endpoint-type field of the template.
        // @RequestParam(value = "visibility", required=false) String
        // visibility,
        // Type was moved as endpoint-type field of the template.
        // @RequestParam(value = "type", required=false) String type,
        @RequestParam Map<String, String> allParams, @RequestBody String postBody) {

    try {/*from ww w  .j av  a2 s  .  c o  m*/

        NIFParameterSet nifParameters = this.normalizeNif(postBody, acceptHeader, contentTypeHeader, allParams,
                false);

        // NOTE: informat was defaulted to JSON before! Now it is TURTLE.
        // NOTE: outformat was defaulted to turtle, if acceptHeader=="*/*"
        // and informat==null, otherwise to JSON. Now it is TURTLE.
        // NOTE: switched back to JSON since we use MySQL and RDF is no
        // longer supported, but JSON only.
        nifParameters.setInformat(RDFSerialization.JSON);
        nifParameters.setOutformat(RDFSerialization.JSON);

        Template template;
        if (nifParameters.getInformat().equals(RDFConstants.RDFSerialization.JSON)) {
            JSONObject jsonObj = new JSONObject(nifParameters.getInput());
            templateValidator.validateTemplateEndpoint(jsonObj.getString("endpoint"));

            // AccessDeniedException can be thrown, if current
            // authentication is the anonymousUser
            template = new Template(jsonObj);
        } else {
            throw new BadRequestException("Other formats then JSON are no longer supported for templates.");
            // Model model =
            // rdfConversionService.unserializeRDF(nifParameters.getInput(),
            // nifParameters.getInformat());
            // template = new Template(
            // OwnedResource.Visibility.getByString(visibility),
            // Template.Type.getByString(jsonObj.getString("endpoint-type")),
            // model);
            // templateValidator.validateTemplateEndpoint(template.getEndpoint());
        }

        template = templateDAO.save(template);

        String serialization;
        if (nifParameters.getOutformat().equals(RDFConstants.RDFSerialization.JSON)) {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            serialization = ow.writeValueAsString(template);
        } else {
            // Should never fail to.
            serialization = rdfConversionService.serializeRDF(template.getRDF(), nifParameters.getOutformat());
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        URI location = new URI("/e-link/templates/" + template.getId());
        responseHeaders.setLocation(location);
        responseHeaders.set("Content-Type", nifParameters.getOutformat().contentType());
        // String serialization =
        // rdfConversionService.serializeRDF(template.getRDF(),
        // nifParameters.getOutformat());
        return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK);
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.broker.exception.AccessDeniedException(ex.getMessage());
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (URISyntaxException | org.json.JSONException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(ex.getMessage());
    } catch (InvalidTemplateEndpointException ex) {
        logger.error(ex.getMessage(), ex);
        throw new InvalidTemplateEndpointException(ex.getMessage());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new InternalServerErrorException(ex.getMessage());
    }
}

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

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

    Registration registration = new Registration("abcde", new URL("http://localhost:1234"));
    registration.setDuration("PT1M");
    SubjectEntity subjectEntity = new SubjectEntity();
    subjectEntity.setType(Optional.of("Room"));
    SubjectRegistration subjectRegistration = new SubjectRegistration(Collections.singletonList(subjectEntity),
            Collections.singletonList("humidity"));
    registration.setSubject(subjectRegistration);
    String json = writer.writeValueAsString(registration);
    String jsonString = "{\n" + "  \"id\" : \"abcde\",\n" + "  \"subject\" : {\n" + "    \"entities\" : [ {\n"
            + "      \"type\" : \"Room\"\n" + "    } ],\n" + "    \"attributes\" : [ \"humidity\" ]\n"
            + "  },\n" + "  \"callback\" : \"http://localhost:1234\",\n" + "  \"duration\" : \"PT1M\"\n" + "}";
    assertEquals(jsonString, json);/*from  w w w  . ja  va  2 s.c o m*/
}

From source file:com.jwebmp.core.htmlbuilder.javascript.JavaScriptPart.java

/**
 * Returns the object presented as a JSON strong
 *
 * @param o//from w  ww. j av  a  2 s  . c om
 *       An object to represent
 *
 * @return the string
 */
public String objectAsString(Object o) {
    try {
        ObjectWriter writer = GuiceContext.get(JSONObjectWriter);
        return writer.writeValueAsString(o).replace("\r\n", "\n");
    } catch (JsonProcessingException ex) {
        JavaScriptPart.log.log(Level.FINER, "Unable to Serialize as JSON Json Processing Exception", ex);
        return "";
    } catch (Exception ex) {
        JavaScriptPart.log.log(Level.SEVERE, "Unable to Serialize as JSON", ex);
        return "";
    }
}

From source file:com.groupon.odo.controllers.PathController.java

/**
 * Handles update requests for specific paths
 *
 * @param model//from   w  ww .  j  a  v  a  2  s  .  c  o  m
 * @param pathIdentifier
 * @param profileIdentifier
 * @param clientUUID
 * @param responseEnabled
 * @param requestEnabled
 * @param addOverride
 * @param enabledMoveUp
 * @param enabledMoveDown
 * @param pathName
 * @param path
 * @param bodyFilter
 * @param customResponse
 * @param customRequest
 * @param resetResponse
 * @param resetRequest
 * @param contentType
 * @param repeatNumber
 * @param global
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/api/path/{pathIdentifier}", method = RequestMethod.POST)
public @ResponseBody String setPath(Model model, @PathVariable String pathIdentifier,
        @RequestParam(value = "profileIdentifier", required = false) String profileIdentifier,
        @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID,
        @RequestParam(required = false) Boolean responseEnabled,
        @RequestParam(required = false) Boolean requestEnabled,
        @RequestParam(value = "addOverride", required = false) Integer addOverride,
        @RequestParam(value = "enabledMoveUp", required = false) String enabledMoveUp,
        @RequestParam(value = "enabledMoveDown", required = false) String enabledMoveDown,
        @RequestParam(required = false) String pathName, @RequestParam(required = false) String path,
        @RequestParam(required = false) String bodyFilter,
        @RequestParam(required = false) String customResponse,
        @RequestParam(required = false) String customRequest,
        @RequestParam(required = false) Boolean resetResponse,
        @RequestParam(required = false) Boolean resetRequest,
        @RequestParam(required = false) String contentType,
        @RequestParam(required = false) Integer repeatNumber, @RequestParam(required = false) Boolean global,
        @RequestParam(required = false) Integer requestType,
        @RequestParam(value = "groups[]", required = false) Integer[] groups, HttpServletResponse response)
        throws Exception {
    String decodedProfileIdentifier = null;
    if (profileIdentifier != null)
        decodedProfileIdentifier = URLDecoder.decode(profileIdentifier, "UTF-8");
    Identifiers identifiers = ControllerUtils.convertProfileAndPathIdentifier(decodedProfileIdentifier,
            pathIdentifier);
    Integer pathId = identifiers.getPathId();

    // update the enabled value
    if (responseEnabled != null) {
        PathOverrideService.getInstance().setResponseEnabled(pathId, responseEnabled, clientUUID);
    }

    // update the enabled value
    if (requestEnabled != null) {
        PathOverrideService.getInstance().setRequestEnabled(pathId, requestEnabled, clientUUID);
    }

    // add an override
    if (addOverride != null) {
        OverrideService.getInstance().enableOverride(addOverride, pathId, clientUUID);
    }

    // move priority of an enabled override up
    if (enabledMoveUp != null) {
        // TODO make this handle ordinals correctly
        String[] parts = enabledMoveUp.split(",");
        OverrideService.getInstance().increasePriority(Integer.parseInt(parts[0]), pathId, clientUUID);
    }

    // move priority of an enabled override down
    if (enabledMoveDown != null) {
        // TODO make this handle ordinals correctly
        String[] parts = enabledMoveDown.split(",");
        OverrideService.getInstance().decreasePriority(Integer.parseInt(parts[0]), pathId, clientUUID);
    }

    // update the name of the path
    if (pathName != null) {
        // TODO: Update UI to display the appropriate error message for this
        if (pathName.equals("test")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return "Cannot update path.  \"test\" is a reserved path name.";
        }

        if (pathName.contains("/")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return "Cannot update path.  Path names cannot contain \"/\"";
        }

        PathOverrideService.getInstance().setName(pathId, pathName);
    }

    // update the actual path
    if (path != null) {
        // test regex parsing of the path
        try {
            Pattern.compile(path);
        } catch (PatternSyntaxException pse) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return "Cannot add path.  Path regular expression is not valid.";
        }

        PathOverrideService.getInstance().setPath(pathId, path);
    }

    // update the bodyFilter
    if (bodyFilter != null) {
        PathOverrideService.getInstance().setBodyFilter(pathId, bodyFilter);
    }

    // update the custom response
    if (customResponse != null) {
        PathOverrideService.getInstance().setCustomResponse(pathId, customResponse, clientUUID);
    }

    // update the custom request
    if (customRequest != null) {
        PathOverrideService.getInstance().setCustomRequest(pathId, customRequest, clientUUID);
    }

    // clears all response settings for the specified path
    if (resetResponse != null) {
        PathOverrideService.getInstance().clearResponseSettings(pathId, clientUUID);
    }

    // clears all request settings for the specified path
    if (resetRequest != null) {
        PathOverrideService.getInstance().clearRequestSettings(pathId, clientUUID);
    }

    // sets content type
    if (contentType != null) {
        PathOverrideService.getInstance().setContentType(pathId, contentType);
    }

    // sets global
    if (global != null) {
        PathOverrideService.getInstance().setGlobal(pathId, global);
    }

    // sets repeat number
    if (repeatNumber != null) {
        EditService.getInstance().updateRepeatNumber(repeatNumber, pathId, clientUUID);
    }

    // sets request type
    if (requestType != null) {
        PathOverrideService.getInstance().setRequestType(pathId, requestType);
    }

    // sets groups
    if (groups != null) {
        pathOverrideService.setGroupsForPath(groups, pathId);
    }

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter writer = objectMapper.writer();

    return writer.writeValueAsString(PathOverrideService.getInstance().getPath(pathId, clientUUID, null));
}

From source file:com.google.api.server.spi.tools.GetDiscoveryDocAction.java

/**
 * Generates a Java client library for an API.  Combines the steps of generating API
 * configuration, generating Discovery doc and generating client library into one.
 * @param classPath Class path to load service classes and their dependencies
 * @param outputDirPath Directory to write output files into
 * @param warPath Directory or file containing a WAR layout
 * @param serviceClassNames Array of service class names of the API
 * @param debug Whether or not to output intermediate output files
 * @param outputToDisk Whether or not to output discovery docs to disk
 *///from  w  ww. ja  va2  s .  co  m
public Map<String, String> getDiscoveryDoc(URL[] classPath, String outputDirPath, String warPath,
        List<String> serviceClassNames, boolean debug, boolean outputToDisk)
        throws ClassNotFoundException, IOException, ApiConfigException {
    File outputDir = new File(outputDirPath);
    if (!outputDir.isDirectory()) {
        throw new IllegalArgumentException(outputDirPath + " is not a directory");
    }

    ClassLoader classLoader = new URLClassLoader(classPath, getClass().getClassLoader());
    ApiConfig.Factory configFactory = new ApiConfig.Factory();
    TypeLoader typeLoader = new TypeLoader(classLoader);
    SchemaRepository schemaRepository = new SchemaRepository(typeLoader);
    ApiConfigValidator validator = new ApiConfigValidator(typeLoader, schemaRepository);
    DiscoveryGenerator discoveryGenerator = new DiscoveryGenerator(typeLoader);
    List<ApiConfig> apiConfigs = Lists.newArrayListWithCapacity(serviceClassNames.size());
    ImmutableListMultimap<ApiKey, ApiConfig> configsByKey = Multimaps.index(apiConfigs,
            new Function<ApiConfig, ApiKey>() {
                @Override
                public ApiKey apply(ApiConfig input) {
                    return input.getApiKey();
                }
            });
    for (ApiKey key : configsByKey.keys()) {
        validator.validate(configsByKey.get(key));
    }
    ApiConfigLoader configLoader = new ApiConfigLoader(configFactory, typeLoader,
            new ApiConfigAnnotationReader(typeLoader.getAnnotationTypes()));
    ServiceContext serviceContext = ServiceContext.create(AppEngineUtil.getApplicationId(warPath),
            ServiceContext.DEFAULT_API_NAME);
    for (Class<?> serviceClass : loadClasses(classLoader, serviceClassNames)) {
        apiConfigs.add(configLoader.loadConfiguration(serviceContext, serviceClass));
    }
    DiscoveryGenerator.Result result = discoveryGenerator.writeDiscovery(apiConfigs,
            new DiscoveryContext().setHostname(serviceContext.getAppHostName()), schemaRepository);
    ObjectWriter writer = ObjectMapperUtil.createStandardObjectMapper().writer(new EndpointsPrettyPrinter());
    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
    for (Map.Entry<ApiKey, RestDescription> entry : result.discoveryDocs().entrySet()) {
        ApiKey key = entry.getKey();
        String discoveryDocFilePath = outputDir + "/" + key.getName() + "-" + key.getVersion()
                + "-rest.discovery";
        String docString = writer.writeValueAsString(entry.getValue());
        if (outputToDisk) {
            Files.write(docString, new File(discoveryDocFilePath), UTF_8);
            System.out.println("API Discovery Document written to " + discoveryDocFilePath);
        }
        builder.put(discoveryDocFilePath, docString);
    }
    return builder.build();
}