Search in sources :

Example 56 with StringWriter

use of java.io.StringWriter in project bigbluebutton by bigbluebutton.

the class StackTraceUtil method getStackTrace.

public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
}
Also used : StringWriter(java.io.StringWriter) PrintWriter(java.io.PrintWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 57 with StringWriter

use of java.io.StringWriter in project jvm-tools by aragozin.

the class FlameCheck method check.

@Test
public void check() throws IOException {
    FlameGraphGenerator fg = new FlameGraphGenerator();
    StackTraceReader r = read();
    if (!r.isLoaded()) {
        r.loadNext();
    }
    while (r.isLoaded()) {
        fg.feed(r.getStackTrace());
        r.loadNext();
    }
    StringWriter sw = new StringWriter();
    fg.renderSVG("Flame Graph", 1200, sw);
    FileWriter fw = new FileWriter(new File("target/flame.svg"));
    fw.append(sw.getBuffer());
    fw.close();
}
Also used : StringWriter(java.io.StringWriter) FileWriter(java.io.FileWriter) StackTraceReader(org.gridkit.jvmtool.stacktrace.StackTraceReader) File(java.io.File) FlameGraphGenerator(org.gridkit.jvmtool.stacktrace.analytics.flame.FlameGraphGenerator) Test(org.junit.Test)

Example 58 with StringWriter

use of java.io.StringWriter in project solo by b3log.

the class CommentProcessor method addArticleComment.

/**
     * Adds a comment to an article.
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "oId": generatedCommentId,
     *     "sc": "COMMENT_ARTICLE_SUCC",
     *     "commentDate": "", // yyyy/MM/dd HH:mm:ss
     *     "commentSharpURL": "",
     *     "commentThumbnailURL": "",
     *     "commentOriginalCommentName": "", // if exists this key, the comment is an reply
     *     "commentContent": "" // HTML
     * }
     * </pre>
     * </p>
     *
     * @param context the specified context, including a request json object, for example,
     *                "captcha": "",
     *                "oId": articleId,
     *                "commentName": "",
     *                "commentEmail": "",
     *                "commentURL": "",
     *                "commentContent": "",
     *                "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
     * @throws ServletException servlet exception
     * @throws IOException      io exception
     */
@RequestProcessing(value = "/add-article-comment.do", method = HTTPRequestMethod.POST)
public void addArticleComment(final HTTPRequestContext context) throws ServletException, IOException {
    final HttpServletRequest httpServletRequest = context.getRequest();
    final HttpServletResponse httpServletResponse = context.getResponse();
    final JSONObject requestJSONObject = Requests.parseRequestJSONObject(httpServletRequest, httpServletResponse);
    requestJSONObject.put(Common.TYPE, Article.ARTICLE);
    fillCommenter(requestJSONObject, httpServletRequest, httpServletResponse);
    final JSONObject jsonObject = commentMgmtService.checkAddCommentRequest(requestJSONObject);
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    renderer.setJSONObject(jsonObject);
    if (!jsonObject.optBoolean(Keys.STATUS_CODE)) {
        LOGGER.log(Level.WARN, "Can't add comment[msg={0}]", jsonObject.optString(Keys.MSG));
        return;
    }
    final HttpSession session = httpServletRequest.getSession(false);
    if (null == session) {
        jsonObject.put(Keys.STATUS_CODE, false);
        jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
        return;
    }
    final String storedCaptcha = (String) session.getAttribute(CaptchaProcessor.CAPTCHA);
    session.removeAttribute(CaptchaProcessor.CAPTCHA);
    if (!userQueryService.isLoggedIn(httpServletRequest, httpServletResponse)) {
        final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA);
        if (null == storedCaptcha || !storedCaptcha.equals(captcha)) {
            jsonObject.put(Keys.STATUS_CODE, false);
            jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
            return;
        }
    }
    try {
        final JSONObject addResult = commentMgmtService.addArticleComment(requestJSONObject);
        final Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(Comment.COMMENT, addResult);
        final JSONObject article = addResult.optJSONObject(Article.ARTICLE);
        article.put(Common.COMMENTABLE, addResult.opt(Common.COMMENTABLE));
        article.put(Common.PERMALINK, addResult.opt(Common.PERMALINK));
        dataModel.put(Article.ARTICLE, article);
        // https://github.com/b3log/solo/issues/12246
        try {
            final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
            final Template template = Templates.MAIN_CFG.getTemplate("common-comment.ftl");
            final JSONObject preference = preferenceQueryService.getPreference();
            Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), skinDirName, dataModel);
            Keys.fillServer(dataModel);
            final StringWriter stringWriter = new StringWriter();
            template.process(dataModel, stringWriter);
            stringWriter.close();
            addResult.put("cmtTpl", stringWriter.toString());
        } catch (final Exception e) {
        // 1.9.0 向后兼容
        }
        addResult.put(Keys.STATUS_CODE, true);
        renderer.setJSONObject(addResult);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Can not add comment on article", e);
        jsonObject.put(Keys.STATUS_CODE, false);
        jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(org.json.JSONObject) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONObject(org.json.JSONObject) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Template(freemarker.template.Template) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 59 with StringWriter

use of java.io.StringWriter in project CoreNLP by stanfordnlp.

the class SemanticGraphUtils method semgrexFromGraphHelper.

/**
   * Recursive call to generate the Semgrex pattern based off of this SemanticGraph.
   * nodeValuesTranformation is a function that converts a vertex (IndexedWord) to the value. For an example, see {@code semgrexFromGraph}
   * function implementations.
   */
protected static String semgrexFromGraphHelper(IndexedWord vertice, SemanticGraph sg, Set<IndexedWord> tabu, Set<SemanticGraphEdge> seenEdges, boolean useWordAsLabel, boolean nameEdges, Collection<IndexedWord> wildcardNodes, Map<IndexedWord, String> nodeNameMap, boolean orderedNodes, Function<IndexedWord, String> nodeValuesTransformation) {
    StringWriter buf = new StringWriter();
    // be labeled, but this may change later.
    if (wildcardNodes != null && wildcardNodes.contains(vertice)) {
        buf.append("{}");
    } else {
        String vertexStr = nodeValuesTransformation.apply(vertice);
        if (vertexStr != null && !vertexStr.isEmpty()) {
            buf.append(vertexStr);
        }
    //      buf.append("{");
    //      int i = 0;
    //      for(String corekey: useNodeCoreAnnotations){
    //        AnnotationLookup.KeyLookup lookup = AnnotationLookup.getCoreKey(corekey);
    //        assert lookup != null : "Invalid key " + corekey;
    //        if(i > 0)
    //          buf.append("; ");
    //        String value = vertice.containsKey(lookup.coreKey) ? vertice.get(lookup.coreKey).toString() : "null";
    //        buf.append(corekey+":"+nodeValuesTransformation.apply(value));
    //        i++;
    //      }
    //      if (useTag) {
    //
    //        buf.append("tag:"); buf.append(vertice.tag());
    //        if (useWord)
    //          buf.append(";");
    //      }
    //      if (useWord) {
    //        buf.append("word:"); buf.append(wordTransformation.apply(vertice.word()));
    //      }
    //      buf.append("}");
    }
    if (nodeNameMap != null) {
        buf.append("=");
        buf.append(nodeNameMap.get(vertice));
        buf.append(" ");
    } else if (useWordAsLabel) {
        buf.append("=");
        buf.append(sanitizeForSemgrexName(vertice.word()));
        buf.append(" ");
    }
    tabu.add(vertice);
    Iterable<SemanticGraphEdge> edgeIter = null;
    if (!orderedNodes) {
        edgeIter = sg.outgoingEdgeIterable(vertice);
    } else {
        edgeIter = CollectionUtils.sorted(sg.outgoingEdgeList(vertice), (arg0, arg1) -> (arg0.getRelation().toString().compareTo(arg1.getRelation().toString())));
    }
    // If we will proceed down that node, add parens if it will continue recursing down.
    for (SemanticGraphEdge edge : edgeIter) {
        seenEdges.add(edge);
        IndexedWord tgtVert = edge.getDependent();
        boolean applyParens = sg.outDegree(tgtVert) > 0 && !tabu.contains(tgtVert);
        buf.append(" >");
        buf.append(edge.getRelation().toString());
        if (nameEdges) {
            buf.append("=E");
            buf.write(String.valueOf(seenEdges.size()));
        }
        buf.append(" ");
        if (applyParens)
            buf.append("(");
        if (tabu.contains(tgtVert)) {
            buf.append("{tag:");
            buf.append(tgtVert.tag());
            buf.append("}");
            if (useWordAsLabel) {
                buf.append("=");
                buf.append(tgtVert.word());
                buf.append(" ");
            }
        } else {
            buf.append(semgrexFromGraphHelper(tgtVert, sg, tabu, seenEdges, useWordAsLabel, nameEdges, wildcardNodes, nodeNameMap, orderedNodes, nodeValuesTransformation));
            if (applyParens)
                buf.append(")");
        }
    }
    return buf.toString();
}
Also used : EnglishGrammaticalRelations(edu.stanford.nlp.trees.EnglishGrammaticalRelations) java.util(java.util) CoreAnnotations(edu.stanford.nlp.ling.CoreAnnotations) GrammaticalRelation(edu.stanford.nlp.trees.GrammaticalRelation) Redwood(edu.stanford.nlp.util.logging.Redwood) StringWriter(java.io.StringWriter) Morphology(edu.stanford.nlp.process.Morphology) Tree(edu.stanford.nlp.trees.Tree) Function(java.util.function.Function) MapList(edu.stanford.nlp.util.MapList) Pair(edu.stanford.nlp.util.Pair) Pattern(java.util.regex.Pattern) LabeledWord(edu.stanford.nlp.ling.LabeledWord) CollectionUtils(edu.stanford.nlp.util.CollectionUtils) Generics(edu.stanford.nlp.util.Generics) AnnotationLookup(edu.stanford.nlp.ling.AnnotationLookup) IndexedWord(edu.stanford.nlp.ling.IndexedWord) StringWriter(java.io.StringWriter) IndexedWord(edu.stanford.nlp.ling.IndexedWord)

Example 60 with StringWriter

use of java.io.StringWriter in project CoreNLP by stanfordnlp.

the class AddDep method cheapWordToString.

// Simple mapping of all the stuff we care about (until IndexedFeatureLabel --> CoreLabel map pain is fixed)
/**
   * This converts the node into a simple string based representation.
   * NOTE: this is extremely brittle, and presumes values do not contain delimiters
   */
public static String cheapWordToString(IndexedWord node) {
    StringWriter buf = new StringWriter();
    buf.write("{");
    buf.write(WORD_KEY);
    buf.write(TUPLE_DELIMITER);
    buf.write(nullShield(node.word()));
    buf.write(ATOM_DELIMITER);
    buf.write(LEMMA_KEY);
    buf.write(TUPLE_DELIMITER);
    buf.write(nullShield(node.lemma()));
    buf.write(ATOM_DELIMITER);
    buf.write(POS_KEY);
    buf.write(TUPLE_DELIMITER);
    buf.write(nullShield(node.tag()));
    buf.write(ATOM_DELIMITER);
    buf.write(VALUE_KEY);
    buf.write(TUPLE_DELIMITER);
    buf.write(nullShield(node.value()));
    buf.write(ATOM_DELIMITER);
    buf.write(CURRENT_KEY);
    buf.write(TUPLE_DELIMITER);
    buf.write(nullShield(node.originalText()));
    buf.write("}");
    return buf.toString();
}
Also used : StringWriter(java.io.StringWriter)

Aggregations

StringWriter (java.io.StringWriter)3563 PrintWriter (java.io.PrintWriter)1197 Test (org.junit.Test)686 IOException (java.io.IOException)563 StringReader (java.io.StringReader)258 Writer (java.io.Writer)239 StreamResult (javax.xml.transform.stream.StreamResult)239 File (java.io.File)207 HashMap (java.util.HashMap)154 Transformer (javax.xml.transform.Transformer)154 InputStreamReader (java.io.InputStreamReader)152 InputStream (java.io.InputStream)137 Map (java.util.Map)125 ArrayList (java.util.ArrayList)122 DOMSource (javax.xml.transform.dom.DOMSource)122 BufferedReader (java.io.BufferedReader)106 ByteArrayInputStream (java.io.ByteArrayInputStream)99 Reader (java.io.Reader)85 Marshaller (javax.xml.bind.Marshaller)82 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)81