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.orange.ngsi2.model.EntityTypeTest.java

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

    EntityType entityType = new EntityType();
    Map<String, AttributeType> attrs = new HashMap<>();
    AttributeType tempAttribute = new AttributeType("urn:phenomenum:temperature");
    attrs.put("temperature", tempAttribute);
    AttributeType humidityAttribute = new AttributeType("percentage");
    attrs.put("humidity", humidityAttribute);
    AttributeType pressureAttribute = new AttributeType("null");
    attrs.put("pressure", pressureAttribute);
    entityType.setAttrs(attrs);//from   ww  w .ja  v a  2 s .  c  o m
    entityType.setCount(7);
    String json = writer.writeValueAsString(entityType);

    assertEquals(jsonString, json);
}

From source file:puma.central.pdp.CentralPUMAPDP.java

@Override
public String getMetrics() {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    try {//from  w  w w  .  j  a v  a2s .  c  o m
        return writer.writeValueAsString(TimerFactory.getInstance().getMetricRegistry());
    } catch (JsonProcessingException e) {
        logger.log(Level.WARNING, "Exception on JSON encoding of metrics", e);
        return "";
    }
}

From source file:com.vsct.dt.strowgr.admin.repository.consul.ConsulRepository.java

private String encodeJson(Map<String, Integer> portsByEntrypoint) throws IOException {
    ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
    return ow.writeValueAsString(portsByEntrypoint);
}

From source file:controllers.core.MilestoneApprovalController.java

/**
 * Display the milestones' planning.//from w ww . jav  a 2  s  .c  om
 */
@Restrict({ @Group(IMafConstants.MILESTONE_OVERVIEW_PERMISSION) })
public Result overview() {

    List<LifeCycleMilestoneInstance> milestoneInstances = LifeCycleMilestoneDao
            .getLCMilestoneInstancePublicPEAsList();

    List<MilestoneInstanceEvent> events = new ArrayList<MilestoneInstanceEvent>();
    for (LifeCycleMilestoneInstance milestoneInstance : milestoneInstances) {
        events.add(new MilestoneInstanceEvent(milestoneInstance));
    }

    String source = "";
    try {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        source = ow.writeValueAsString(events);
        source = source.replaceAll("\"statusClass\"", "\"class\"");
    } catch (JsonProcessingException e) {
        return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(),
                getI18nMessagesPlugin());
    }

    return ok(views.html.core.milestoneapproval.overview.render(source));
}

From source file:us.colloquy.index.IndexHandler.java

@Test
public void loadDiariesIndex() {
    Properties properties = loadProperties();

    List<DiaryEntry> diaryEntries = new ArrayList<>();

    List<DocumentPointer> documentPointers = new ArrayList<>();

    //  getURIForAllDiaries(documentPointers, System.getProperty("user.home") + "/Documents/Tolstoy/openDiaries");
    ///*from   ww  w. j a v a2 s  . c  om*/
    String strPathToDiaries = "samples/diaries";

    //find all volumes with diaries
    Path pathToDiaries = FileSystems.getDefault().getPath(strPathToDiaries);

    List<Path> listOfDiaryVolumes = new ArrayList<>();

    int maxDepth = 1;

    try (Stream<Path> stream = Files.find(pathToDiaries, maxDepth, (path, attr) -> {
        return String.valueOf(path).contains("dnevnik");
    })) {
        stream.forEach(listOfDiaryVolumes::add);

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

    int diaryCounter = 0;

    File entries_debug = new File("entries_debug.txt");

    entries_debug.delete();

    try (FileWriter fw = new FileWriter("entries_debug.txt", true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter outDebug = new PrintWriter(bw)) {
        outDebug.println("start file");
        //more code

        for (Path path : listOfDiaryVolumes) {
            documentPointers.clear();

            getURIForAllDiaries(documentPointers, path);

            diaryEntries.clear();

            for (DocumentPointer pointer : documentPointers) {
                List<DiaryEntry> diaryEntriesInPointer = new ArrayList<>();

                DiaryParser.parseDiaries(pointer, diaryCounter++, diaryEntriesInPointer, outDebug); //test case "temp/OEBPS/Text/0001_1006_2002.xhtml"

                //find if anything is wrong in a pointer

                for (DiaryEntry diaryEntry : diaryEntriesInPointer) {
                    if (diaryEntry.getDate() == null || diaryEntry.getEntry().length() < 20) {
                        System.out.println(" Missing entry:  --------------- " + pointer.getUri()
                                + " ---------------------------------");
                        System.out.println(diaryEntry.toString());

                    }
                }

                diaryEntries.addAll(diaryEntriesInPointer);
            }

            System.out.println("Total number of diaries in " + path.getFileName() + ": " + diaryEntries.size());

            //code below to set ids and check a few letters
            int i = 0;

            for (DiaryEntry diaryEntry : diaryEntries) {
                i++;

                String id = "D-" + path.getFileName().toString().replaceAll(".*_", "") + "-" + i;

                diaryEntry.setId(id);
            }

            System.out.println("Total number of diaries in volume: " + diaryEntries.size());

            //export json files

            try {
                ObjectWriter ow = new com.fasterxml.jackson.databind.ObjectMapper().writer()
                        .withDefaultPrettyPrinter();

                String json = ow.writeValueAsString(diaryEntries);

                System.out.println("-------------------- Start exporting diaries in Volume "
                        + path.getFileName() + " ------------- ");

                //   String origin = diaryEntries.get(0).getSource();

                String fileName = "parsed/diaries/" + path.getFileName() + ".json";

                try (Writer out = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"))) {
                    out.write(json);

                }

                System.out.println("-------------------- End of export in Volume " + path.getFileName()
                        + " ------------- ");

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

            if (properties.getProperty("upload_to_elastic").equalsIgnoreCase("true")) {

                ElasticLoader.uploadDiariesToElasticServer(properties, diaryEntries);
            }
        }

        outDebug.println("end file");
        //more code
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }

}

From source file:com.basistech.rosette.apimodel.ModelTest.java

@Test
public void packageTest() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException,
        InstantiationException, IOException {
    Reflections reflections = new Reflections(this.getClass().getPackage().getName(),
            new SubTypesScanner(false));

    Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);
    for (Object clazz : allClasses) {
        String className = ((Class) clazz).getName();
        if (className.contains("com.basistech.rosette.dm")) {
            continue;
        }//  w ww.  j a v  a2s .c  om
        if (className.contains("Adm")) {
            continue; // these are too hard.
        }
        if (className.endsWith(".ModelTest")) {
            continue;
        }
        if (className.endsWith(".NonNullTest")) {
            continue;
        }
        if (className.endsWith("Mixin")) {
            continue;
        }

        if (className.endsWith("Builder")) {
            continue;
        }
        if (className.contains(".batch.")) {
            // there are polymorphism issues in here for this test strategy.
            continue;
        }

        Class c = Class.forName(className);
        if (Modifier.isAbstract(c.getModifiers())) {
            continue;
        }
        Constructor[] ctors = c.getDeclaredConstructors();
        if (ctors.length == 0) {
            continue;
        }
        Constructor ctor = ctors[0];
        if (ctor.getParameterTypes().length == 0) {
            continue; // don't want empty constructor
        }
        Object o1;
        if (Modifier.isPublic(ctor.getModifiers())) {

            boolean oldInputStreams = inputStreams;
            try {
                if (className.endsWith("ConstantsResponse")) {
                    inputStreams = false; // special case due to Object in there.
                }
                o1 = createObject(ctor);
            } finally {
                inputStreams = oldInputStreams;
            }

            // serialize
            // for a request, we might need a view
            ObjectWriter writer = mapper.writerWithView(Object.class);
            if (o1 instanceof DocumentRequest) {
                DocumentRequest r = (DocumentRequest) o1;
                if (r.getRawContent() instanceof String) {
                    writer = mapper.writerWithView(DocumentRequestMixin.Views.Content.class);
                }
            }
            String json = writer.writeValueAsString(o1);
            // deserialize
            Object o2 = mapper.readValue(json, (Class<? extends Object>) clazz);
            // verify
            assertEquals(o1, o2);
        }
    }
}

From source file:org.springside.examples.showcase.demos.utilities.json.JsonDemo.java

/**
 * ??POJO???????Jackson?View?./* ww w  .jav a 2 s. c o  m*/
 */
@Test
public void multiViewBean() throws IOException {
    MultiViewBean multiViewBean = new MultiViewBean();
    multiViewBean.setName("Foo");
    multiViewBean.setAge(16);
    multiViewBean.setOtherValue("others");

    // public view
    ObjectWriter publicWriter = mapper.getMapper().writerWithView(Views.Public.class);
    assertThat(publicWriter.writeValueAsString(multiViewBean))
            .isEqualTo("{\"name\":\"Foo\",\"otherValue\":\"others\"}");

    // internal view
    ObjectWriter internalWriter = mapper.getMapper().writerWithView(Views.Internal.class);
    assertThat(internalWriter.writeValueAsString(multiViewBean))
            .isEqualTo("{\"age\":16,\"otherValue\":\"others\"}");

}

From source file:us.colloquy.sandbox.TestExtractor.java

@Test
public void useJsoup() {

    String homeDir = System.getProperty("user.home");

    System.out.println(homeDir);//from ww  w . j  a va2s .  c  o  m

    //JSOUP API allows to extract all  elements of letters in files

    // File input = new File("samples/OEBPS/Text/0001_1006_2001.xhtml");

    File input = new File("samples/pisma-1904/OEBPS/Text/single_doc.html");

    try {
        Document doc = Jsoup.parse(input, "UTF-8");

        List<Letter> letters = new ArrayList<>(); //our model contains only a subset of fields

        String previousYear = "";

        for (Element element : doc.getElementsByClass("section")) {
            Letter letter = new Letter();

            StringBuilder content = new StringBuilder();

            for (Element child : element.children()) {

                for (Attribute att : child.attributes()) {
                    System.out.println(att.getKey() + " " + att.getValue());
                }

                if ("center".equalsIgnoreCase(child.className())) {
                    String toWhom = child.getElementsByTag("strong").text();

                    if (StringUtils.isEmpty(toWhom)) {
                        toWhom = child.text();
                        // System.out.println(toWhom);
                    }

                    String[] toWhomArray = toWhom.split("(\\s\\s)|(,)");

                    for (String to : toWhomArray) {
                        RussianDate.parseToWhom(letter, to); //here we need to recognize a russian name and store that but for now we store the content
                    }

                    //check if there is anything else here and find date and place - it will be replaced if exists below

                    String entireText = child.text();

                    String tail = entireText.replace(toWhom, "");

                    if (StringUtils.isNotEmpty(tail)) {
                        RussianDate.parseDateAndPlace(letter, tail, previousYear); //a parser that figures out date and place if they are present
                    }

                    // System.out.println("two whom\t " +  child.getElementsByTag("strong").text() );

                } else if ("Data".equalsIgnoreCase(child.className())) {

                    if (child.getElementsByTag("em") != null
                            && StringUtils.isNotEmpty(child.getElementsByTag("em").text())) {
                        RussianDate.parseDateAndPlace(letter, child.getElementsByTag("em").text(),
                                previousYear); //most often date and place are enclosed in em tag

                        if (letter.getDate() != null) {
                            LocalDate localDate = letter.getDate().toInstant().atZone(ZoneId.systemDefault())
                                    .toLocalDate();
                            int year = localDate.getYear();
                            previousYear = year + "";
                        }
                    }

                    // System.out.println("when and where\t " + child.getElementsByTag("em").text());

                } else if ("petit".equalsIgnoreCase(child.className())
                        || "Textpetit_otstup".equalsIgnoreCase(child.className())) {
                    letter.getNotes().add(child.text());

                } else {
                    //System.out.println(child.text() );

                    Elements elements = child.getElementsByTag("sup");

                    for (Element e : elements) {
                        String value = e.text();

                        e.replaceWith(new TextNode("[" + value + "]", null));
                    }

                    for (Element el : child.getAllElements()) {
                        // System.out.println(el.tagName());
                        if ("sup".equalsIgnoreCase(el.tagName())) {
                            content.append(" [" + el.text() + "] ");
                        } else {
                            content.append(el.text());
                        }

                    }

                    content.append("\n");

                }

                //                  System.out.println(child.tag() + "\n" );
                //                  System.out.println(child.outerHtml() + "\n" + child.text());
            }

            letter.setContent(content.toString());
            letters.add(letter);
        }

        ObjectWriter ow = new com.fasterxml.jackson.databind.ObjectMapper().writer().withDefaultPrettyPrinter();

        for (Letter letter : letters) {
            //                if (letter.getDate() == null)
            //                {

            //                        if (StringUtils.isNotEmpty(person.getLastName()))
            //                        {
            String json = ow.writeValueAsString(letter);

            System.out.println(json);
            //                        }

            //}

        }

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

}

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

@SuppressWarnings("unchecked")
@Override//from   w ww  . jav a  2 s.com
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;
    }

    String url = post.get("url", "");
    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;
    }

    Map<String, Object> map;
    byte[] jsonText;
    try {
        jsonText = ClientConnection.download(url);
        map = DAO.jsonMapper.readValue(jsonText, DAO.jsonTypeRef);
    } catch (Exception e) {
        response.sendError(400, "error reading json file from url");
        return;
    }

    // validation phase
    ProcessingReport report = this.validator.validate(new String(jsonText));
    if (!report.isSuccess()) {
        response.sendError(400,
                "json does not conform to schema : " + this.getValidatorSchema().name() + "\n" + report);
        return;
    }

    // conversion phase
    Object extractResults = extractMessages(map);
    List<Map<String, Object>> messages;
    if (extractResults instanceof List) {
        messages = (List<Map<String, Object>>) extractResults;
    } else if (extractResults instanceof Map) {
        messages = new ArrayList<>();
        messages.add((Map<String, Object>) extractResults);
    } else {
        throw new IOException("extractMessages must return either a List or a Map. Get "
                + (extractResults == null ? "null" : extractResults.getClass().getCanonicalName())
                + " instead");
    }
    List<Map<String, Object>> convertedMessages = this.converter.convert(messages);

    PushReport nodePushReport = new PushReport();
    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    // custom treatment for each message
    for (int i = 0; i < messages.size(); i++) {
        Map<String, Object> message = convertedMessages.get(i);
        message.put("source_type", this.getSourceType().name());
        message.put("location_source", LocationSource.USER.name());
        message.put("place_context", PlaceContext.ABOUT.name());
        if (message.get("text") == null) {
            message.put("text", "");
        }

        // append rich-text attachment
        String jsonToText = ow.writeValueAsString(messages.get(i));
        message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText);
        customProcessing(message);

        if (message.get("mtime") == null) {
            String existed = PushServletHelper.checkMessageExistence(message);
            // message known
            if (existed != null) {
                messages.remove(i);
                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, getSourceType()));
        } catch (Exception e) {
            DAO.log("Problem computing id : " + e.getMessage());
        }
    }
    try {
        PushReport savingReport = PushServletHelper.saveMessagesAndImportProfile(convertedMessages,
                Arrays.hashCode(jsonText), post, getSourceType(), screen_name);
        nodePushReport.combine(savingReport);
    } catch (IOException e) {
        response.sendError(404, e.getMessage());
        return;
    }
    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), nodePushReport);

    post.setResponse(response, "application/javascript");
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + nodePushReport.getRecordCount() + ", new = "
            + nodePushReport.getNewCount() + ", known = " + nodePushReport.getKnownCount() + ", error = "
            + nodePushReport.getErrorCount() + ", from host hash " + remoteHash);
}

From source file:org.loklak.api.iot.AbstractPushServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query 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;/*from   w  w w . j  av  a2s. c  om*/
    }

    String url = post.get("url", "");
    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;
    }

    JSONObject map;
    String jsonString = "";
    try {
        jsonString = new String(ClientConnection.download(url), StandardCharsets.UTF_8);
        map = new JSONObject(jsonString);
    } catch (Exception e) {
        response.sendError(400, "error reading json file from url");
        return;
    }

    // validation phase
    ProcessingReport report = this.validator.validate(jsonString);
    if (!report.isSuccess()) {
        response.sendError(400,
                "json does not conform to schema : " + this.getValidatorSchema().name() + "\n" + report);
        return;
    }

    // conversion phase
    Object extractResults = extractMessages(map);
    JSONArray messages;
    if (extractResults instanceof JSONArray) {
        messages = (JSONArray) extractResults;
    } else if (extractResults instanceof JSONObject) {
        messages = new JSONArray();
        messages.put((JSONObject) extractResults);
    } else {
        throw new IOException("extractMessages must return either a List or a Map. Get "
                + (extractResults == null ? "null" : extractResults.getClass().getCanonicalName())
                + " instead");
    }
    JSONArray convertedMessages = this.converter.convert(messages);

    PushReport nodePushReport = new PushReport();
    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    // custom treatment for each message
    for (int i = 0; i < messages.length(); i++) {
        JSONObject message = (JSONObject) convertedMessages.get(i);
        message.put("source_type", this.getSourceType().toString());
        message.put("location_source", LocationSource.USER.name());
        message.put("place_context", PlaceContext.ABOUT.name());
        if (message.get("text") == null) {
            message.put("text", "");
        }

        // append rich-text attachment
        String jsonToText = ow.writeValueAsString(messages.get(i));
        message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText);
        customProcessing(message);

        if (message.get("mtime") == null) {
            String existed = PushServletHelper.checkMessageExistence(message);
            // message known
            if (existed != null) {
                messages.remove(i);
                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, getSourceType()));
        } catch (Exception e) {
            DAO.log("Problem computing id : " + e.getMessage());
        }
    }
    try {
        PushReport savingReport = PushServletHelper.saveMessagesAndImportProfile(convertedMessages,
                jsonString.hashCode(), post, getSourceType(), screen_name);
        nodePushReport.combine(savingReport);
    } catch (IOException e) {
        response.sendError(404, e.getMessage());
        return;
    }
    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), nodePushReport);

    post.setResponse(response, "application/javascript");
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + nodePushReport.getRecordCount() + ", new = "
            + nodePushReport.getNewCount() + ", known = " + nodePushReport.getKnownCount() + ", error = "
            + nodePushReport.getErrorCount() + ", from host hash " + remoteHash);
}