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.freelectron.leobel.testlwa.models.AlertsFileDataStore.java

@Override
public synchronized void writeToDisk(final List<Alert> alerts, final ResultListener listener) {
    sExecutor.execute(new Runnable() {
        @Override/*from   ww  w . jav  a  2s.  c  o  m*/
        public void run() {
            ObjectWriter writer = ObjectMapperFactory.getObjectWriter();
            PrintWriter out = null;
            try {
                out = new PrintWriter(ALARM_FILE);
                out.print(writer.writeValueAsString(alerts));
                out.flush();
                listener.onSuccess();
            } catch (IOException e) {
                Log.d("Failed to write to disk", e.getMessage(), e);
                listener.onFailure();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    });
}

From source file:org.usd.edu.btl.cli.ConvertBets.java

public void toSeq(String inputS, String output) {
    ObjectMapper mapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);

    //mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //ignore the extra BETS fields
    BETSV1 betsTool;//ww  w.  ja  va  2 s  .  co m

    try {
        //map input json files to iplant class
        betsTool = mapper.readValue(input, BETSV1.class);

        //convert bets to BioExtract
        SeqV1 bExtOutput = BETSConverter.toSeq(betsTool); //pass the iplant tool spec, convert to bets

        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();

        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            ObjectWriter bExtWriter = mapper.writer().withDefaultPrettyPrinter();
            String bExtJson = bExtWriter.writeValueAsString(bExtOutput); //write Json as String

            System.err.println("=== BETS TO SEQ JSON === \n");
            System.out.println(bExtJson);
        } else {
            //write to files
            ow.writeValue(new File(output), bExtOutput);
            System.err.println(output + " has been created successfully");
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

From source file:com.unboundid.scim2.common.messages.ListResponse.java

/**
 * Create a new List Response.//from   ww  w  .ja v  a2s .  com
 *
 * @param totalResults The total number of results returned.
 * @param resources A multi-valued list of complex objects containing the
 *                  requested resources
 * @param startIndex The 1-based index of hte first result in the current
 *                   set of list results
 * @param itemsPerPage The number of resources returned in a list response
 *                     page.
 */
public ListResponse(final int totalResults, final List<T> resources, final Integer startIndex,
        final Integer itemsPerPage) {
    this.totalResults = totalResults;
    this.startIndex = startIndex;
    this.itemsPerPage = itemsPerPage;

    final ObjectReader reader = JsonUtils.getObjectReader();
    final ObjectWriter writer = JsonUtils.getObjectWriter();
    try {
        final String rawResources = writer.writeValueAsString(resources);
        this.resources = reader.forType(new TypeReference<List<T>>() {
        }).readValue(rawResources);
    } catch (final IOException ie) {
        throw new IllegalArgumentException("Resources exception", ie);
    }
}

From source file:com.blockwithme.lessobjects.schema.StructSchema.java

/** Instantiates a new struct envelope from Struct object. */
@SuppressWarnings("null")
public StructSchema(final Struct theStruct) {
    checkNotNull(theStruct);/*from   w w w. j a va  2s  .  co  m*/
    final StructInfo structInfo = theStruct.structInfo();
    if (structInfo != null) {
        createdBy = structInfo.createdBy();
        createdOn = structInfo.createdOn();
        schemaVersion = structInfo.schemaVersion();
    } else {
        createdBy = DEFAULT_CREATED_BY;
        createdOn = new Date();
        schemaVersion = DEFAULT_SCHEMA_VERSION;
    }
    jsonVersion = JSON_VERSION;
    struct = theStruct;
    binding = new StructBinding(struct);
    try {
        final ObjectMapper mapper = mapper();
        final ObjectWriter writer = mapper.writerWithView(JSONViews.SignatureView.class);
        final String signatureStr = writer.writeValueAsString(binding);
        final ObjectWriter writer2 = mapper.writerWithView(JSONViews.CompleteView.class);
        final String fullString = writer2.writeValueAsString(binding);
        signature = MurmurHash.hash64(signatureStr);
        fullHash = MurmurHash.hash64(fullString);
    } catch (final JsonProcessingException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:fr.treeptik.cloudunit.ports.PortsControllerTestIT.java

private String getString(PortResource portResource, ObjectMapper mapper) throws JsonProcessingException {
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
    return ow.writeValueAsString(portResource);
}

From source file:edu.ucsd.crbs.cws.App.java

License:asdf

public static void getWorkspaceFileAsJson(OptionSet optionSet) throws Exception {
    WorkspaceFileRestDAOImpl workspaceFileDAO = new WorkspaceFileRestDAOImpl();
    workspaceFileDAO.setRestURL((String) optionSet.valueOf(URL_ARG));
    User u = getUserFromOptionSet(optionSet);
    workspaceFileDAO.setUser(u);/*from  w w w  . ja v a2 s . c om*/
    Long workspaceFileId = (Long) optionSet.valueOf(GET_WORKSPACE_FILE_ARG);

    if (workspaceFileId == -1) {
        List<WorkspaceFile> wsfList = workspaceFileDAO.getWorkspaceFiles(null, null, null, null, null);
        ObjectMapper om = new ObjectMapper();
        ObjectWriter ow = om.writerWithDefaultPrettyPrinter();
        if (wsfList != null) {
            for (WorkspaceFile wsf : wsfList) {
                System.out.println(ow.writeValueAsString(wsf));
            }
        }
        return;
    }
    WorkspaceFile wsf = workspaceFileDAO.getWorkspaceFileById(workspaceFileId.toString(), u);
    if (wsf != null) {
        ObjectMapper om = new ObjectMapper();
        ObjectWriter ow = om.writerWithDefaultPrettyPrinter();
        System.out.println(ow.writeValueAsString(wsf));
    } else {
        System.err.println("Unable to retreive WorkspaceFile with id: "
                + ((Long) optionSet.valueOf(GET_WORKSPACE_FILE_ARG)).toString());
        System.exit(1);
    }
    return;

}

From source file:edu.ucsd.crbs.cws.App.java

License:asdf

/**
 * Prints out examples of {@link Workflow}, {@link WorkspaceFile}, {@link Job}, {@link WorkspaceFile}
 * objects in pretty JSON format//from w w w.j a v  a2  s.c  om
 * @throws Exception 
 */
public static void renderExampleWorkflowsAndTasksAsJson() throws Exception {

    ObjectMapper om = new ObjectMapper();
    ObjectWriter ow = om.writerWithDefaultPrettyPrinter();

    System.out.println("Json for Empty Workflow");
    System.out.println("-----------------------");
    System.out.println(ow.writeValueAsString(getWorkflowWithNoParameters()));
    System.out.flush();
    System.out.println("-----------------------\n\n");

    System.out.println("Json for Workflow with Parameters");
    System.out.println("-----------------------");

    System.out.println(ow.writeValueAsString(getWorkflowWithParameters()));
    System.out.flush();
    System.out.println("-----------------------\n\n");

    System.out.println("Json for Job with 2 parameters and workflow");
    System.out.println("-----------------------");
    System.out.println(ow.writeValueAsString(getJobWithParametersAndWorkflow()));
    System.out.flush();
    System.out.println("-----------------------\n\n");

    System.out.println("Json for WorkspaceFile");
    System.out.println("-----------------------");
    System.out.println(ow.writeValueAsString(getWorkspaceFile()));
    System.out.flush();

    System.out.println("Json for User");
    System.out.println("-----------------------");
    System.out.println(ow.writeValueAsString(getUser()));
    System.out.flush();

    System.out.println("Json for Event");
    System.out.println("-----------------------");
    System.out.println(ow.writeValueAsString(getEvent()));
    System.out.flush();

}

From source file:ws.util.AbstractJSONCoder.java

@Override
public String encode(T pojo) throws EncodeException {
    StringBuilder log = new StringBuilder().append(type).append("| [coder] encoding..").append(pojo);
    String json = null;/*from  w ww.j a v  a2  s.co  m*/
    try {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        // Jackson jr ??@JsonManagedReference, @JsonBackReference????
        //                  json = JSON.std.asString(pojo);
        json = ow.writeValueAsString(pojo);
        log.append(" DONE.");
    } catch (IOException e) {
        log.append(" **NG**.");
        logger.log(Level.SEVERE, e.toString());
        e.printStackTrace();
        throw new EncodeException(json, e.getMessage());
    } catch (Exception e) {
        log.append(" **NG**.");
        logger.log(Level.SEVERE, e.toString());
        e.printStackTrace();
        throw new EncodeException(json, e.getMessage());
    } finally {
        logger.log(Level.INFO, log.toString());
    }
    //            logger.log(Level.INFO, new StringBuilder()
    //                  .append("[coder] done: ")
    //                  .append(json)
    //                  .toString());
    return json;
}

From source file:edu.ucsd.crbs.cws.App.java

License:asdf

public static void addNewWorkspaceFile(OptionSet optionSet, boolean uploadFile, final String theArg)
        throws Exception {
    String postURL = null;//  w  ww. j  a v  a2  s . c  o  m
    if (optionSet.has(URL_ARG)) {
        postURL = (String) optionSet.valueOf(URL_ARG);
        failIfOptionSetMissingLoginOrToken(optionSet, "--" + theArg + " and --" + URL_ARG + " flag");
    }

    File file = (File) optionSet.valueOf(theArg);
    WorkspaceFile wsp = new WorkspaceFile();
    wsp.setName(file.getName());
    wsp.setSize(file.length());
    wsp.setDir(file.isDirectory());
    if (optionSet.has(OWNER_ARG)) {
        wsp.setOwner((String) optionSet.valueOf(OWNER_ARG));
    }
    if (optionSet.has(PATH_ARG)) {
        wsp.setPath((String) optionSet.valueOf(PATH_ARG));
    }
    if (optionSet.has(JOB_ID_ARG)) {
        wsp.setSourceJobId((Long) optionSet.valueOf(JOB_ID_ARG));
    }
    if (optionSet.has(MD5_ARG)) {
        wsp.setMd5((String) optionSet.valueOf(MD5_ARG));
    }
    if (optionSet.has(DESCRIPTION_ARG)) {
        wsp.setDescription((String) optionSet.valueOf(DESCRIPTION_ARG));
    }
    if (optionSet.has(TYPE_ARG)) {
        wsp.setType((String) optionSet.valueOf(TYPE_ARG));
    }

    if (optionSet.has(NAME_ARG)) {
        wsp.setName((String) optionSet.valueOf(NAME_ARG));
    }

    if (optionSet.has(SIZE_ARG)) {
        wsp.setSize((Long) optionSet.valueOf(SIZE_ARG));
    }

    if (optionSet.has(WORKSPACE_FILE_FAILED_ARG)) {
        wsp.setFailed((Boolean) optionSet.valueOf(WORKSPACE_FILE_FAILED_ARG));
    }

    ObjectMapper om = new ObjectMapper();
    ObjectWriter ow = om.writerWithDefaultPrettyPrinter();
    if (postURL == null) {
        System.out.println("\n--- JSON Representation of WorkspaceFile ---");
        System.out.println(ow.writeValueAsString(wsp));
        System.out.flush();
        System.out.println("---------------------------------------");
        System.exit(0);
    }
    User u = getUserFromOptionSet(optionSet);
    WorkspaceFileRestDAOImpl workspaceFileDAO = new WorkspaceFileRestDAOImpl();
    workspaceFileDAO.setRestURL(postURL);
    workspaceFileDAO.setUser(u);

    WorkspaceFile workspaceFileRes = workspaceFileDAO.insert(wsp, uploadFile);
    System.out.println("WorkspaceFile id: " + workspaceFileRes.getId());

    if (uploadFile == false) {
        return;
    }

    if (workspaceFileRes.getUploadURL() == null) {
        throw new Exception("No upload url found for workflow!!!" + ow.writeValueAsString(workspaceFileRes));
    }
    uploadWorkspaceFile(workspaceFileRes, file);
}

From source file:jc.mongodb.JacksonDBObjectSerializerTest.java

@Test
public void toDBObject() throws Exception {
    DBObject obj;/*from w w  w. ja  va 2 s.c om*/
    TestBean bean;
    ObjectWriter mapper = new ObjectMapper().writer().without(SerializationFeature.WRITE_NULL_MAP_VALUES);

    bean = new TestBean("testbean");
    bean.setCount(123);

    obj = serializer.toDBObject(bean, true, false);
    assertEquals("{\"field\":{\"count\":123,\"beans\":[],\"name\":\"testbean\"}}",
            mapper.writeValueAsString(obj.toMap()));

    obj = serializer.toDBObject(bean, true, true);
    assertEquals("{\"field\":{\"$ne\":{\"count\":123,\"beans\":[],\"name\":\"testbean\"}}}",
            mapper.writeValueAsString(obj.toMap()));

    obj = serializer.toDBObject(bean, false, false);
    assertEquals("{\"field\":{\"count\":123,\"beans\":[],\"name\":\"testbean\"}}",
            mapper.writeValueAsString(obj.toMap()));

    obj = serializer.toDBObject(bean, false, true);
    assertEquals("{\"field\":{\"count\":123,\"beans\":[],\"name\":\"testbean\"}}",
            mapper.writeValueAsString(obj.toMap()));
}