Java 类java.io.StringWriter 实例源码

项目:cas-server-4.2.1    文件:CouchbaseServiceRegistryDao.java   
@Override
public RegisteredService save(final RegisteredService service) {
    logger.debug("Saving service {}", service);

    if (service.getId() == AbstractRegisteredService.INITIAL_IDENTIFIER_VALUE) {
        ((AbstractRegisteredService) service).setId(service.hashCode());
    }

    final StringWriter stringWriter = new StringWriter();
    registeredServiceJsonSerializer.toJson(stringWriter, service);

    couchbase.bucket().upsert(
            RawJsonDocument.create(
                    String.valueOf(service.getId()),
                    0, stringWriter.toString()));
    return service;
}
项目:elastic-db-tools-for-java    文件:StoreOperationRequestBuilder.java   
/**
 * Print the created XML to verify. Usage: return printLogAndReturn(new JAXBElement(rootElementName, StoreOperationInput.class, input));
 *
 * @return JAXBElement - same object which came as input.
 */
private static JAXBElement printLogAndReturn(JAXBElement jaxbElement) {
    try {
        // Create a String writer object which will be
        // used to write jaxbElment XML to string
        StringWriter writer = new StringWriter();

        // create JAXBContext which will be used to update writer
        JAXBContext context = JAXBContext.newInstance(StoreOperationInput.class);

        // marshall or convert jaxbElement containing student to xml format
        context.createMarshaller().marshal(jaxbElement, writer);

        // print XML string representation of Student object
        System.out.println(writer.toString());
    }
    catch (JAXBException e) {
        e.printStackTrace();
    }
    return jaxbElement;
}
项目:Aurora    文件:CharacterHandler.java   
/**
 * xml 格式化
 *
 * @param xml
 * @return
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
项目:GitHub    文件:SerializeWriterTest_17.java   
public void test_writer_1() throws Exception {
    StringWriter strOut = new StringWriter();
    SerializeWriter out = new SerializeWriter(strOut, 6);
    out.config(SerializerFeature.QuoteFieldNames, true);

    try {
        JSONSerializer serializer = new JSONSerializer(out);

        VO vo = new VO();
        vo.setValue(123456789);
        serializer.write(vo);
    } finally {
        out.close();
    }
    Assert.assertEquals("{\"value\":123456789}", strOut.toString());
}
项目:hadoop    文件:RLESparseResourceAllocation.java   
/**
 * Returns the JSON string representation of the current resources allocated
 * over time
 * 
 * @return the JSON string representation of the current resources allocated
 *         over time
 */
public String toMemJSONString() {
  StringWriter json = new StringWriter();
  JsonWriter jsonWriter = new JsonWriter(json);
  readLock.lock();
  try {
    jsonWriter.beginObject();
    // jsonWriter.name("timestamp").value("resource");
    for (Map.Entry<Long, Resource> r : cumulativeCapacity.entrySet()) {
      jsonWriter.name(r.getKey().toString()).value(r.getValue().toString());
    }
    jsonWriter.endObject();
    jsonWriter.close();
    return json.toString();
  } catch (IOException e) {
    // This should not happen
    return "";
  } finally {
    readLock.unlock();
  }
}
项目:uavstack    文件:ClobSeriliazer.java   
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    try {
        if (object == null) {
            serializer.writeNull();
            return;
        }

        Clob clob = (Clob) object;
        Reader reader = clob.getCharacterStream();

        StringWriter writer = new StringWriter();
        char[] buf = new char[1024];
        int len = 0;
        while ((len = reader.read(buf)) != -1) {
            writer.write(buf, 0, len);
        }
        reader.close();

        String text = writer.toString();
        serializer.write(text);
    } catch (SQLException e) {
        throw new IOException("write clob error", e);
    }
}
项目:hippo-groovy-updater    文件:TestUpdaterTransforming.java   
@Test
public void generateHippoEcmExtensions() throws URISyntaxException, IOException, JAXBException {
    URI resourceURI = getClass().getResource("").toURI();
    File root = new File(resourceURI);
    List<ScriptClass> scriptClasses = ScriptClassFactory.getScriptClasses(root);
    Node node = XmlGenerator.getEcmExtensionNode(root, new File(root, "target"), scriptClasses, "my-updater-prefix-");

    StringWriter writer = new StringWriter();

    getMarshaller().marshal(node, writer);
    final String xml = writer.toString();
    URL testfileResultUrl = getClass().getResource("resulting-hippoecm-extension.xml");
    File resultFile = new File(testfileResultUrl.toURI());

    String expectedContent = FileUtils.fileRead(resultFile);
    assertEquals(expectedContent, xml);
}
项目:incubator-netbeans    文件:ErrorPanel.java   
private void btnStackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStackActionPerformed
    StringWriter sw = new StringWriter();
    exception.printStackTrace(new PrintWriter(sw));
    JPanel pnl = new JPanel();
    pnl.setLayout(new BorderLayout());
    pnl.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
    JTextArea ta = new JTextArea();
    ta.setText(sw.toString());
    ta.setEditable(false);
    JScrollPane pane = new JScrollPane(ta);
    pnl.add(pane);
    pnl.setMaximumSize(new Dimension(600, 300));
    pnl.setPreferredSize(new Dimension(600, 300));
    NotifyDescriptor.Message nd = new NotifyDescriptor.Message(pnl);
    DialogDisplayer.getDefault().notify(nd);

}
项目:raven    文件:JaxbUtils.java   
public static String obj2xml(Object o, Class<?> clazz) throws JAXBException {

    if(null == o){
        throw new InvalidParameterException();
    }
    JAXBContext context = JAXBContext.newInstance(clazz);

    Marshaller marshaller = context.createMarshaller();

    // 
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    // 是否去掉头部信息
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

    StringWriter writer = new StringWriter();
    marshaller.marshal(o, writer);
    return writer.toString();
}
项目:OpenJSharp    文件:UnixPrintJob.java   
private void handleProcessFailure(final Process failedProcess,
        final String[] execCmd, final int result) throws IOException {
    try (StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw)) {
        pw.append("error=").append(Integer.toString(result));
        pw.append(" running:");
        for (String arg: execCmd) {
            pw.append(" '").append(arg).append("'");
        }
        try (InputStream is = failedProcess.getErrorStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr)) {
            while (br.ready()) {
                pw.println();
                pw.append("\t\t").append(br.readLine());
            }
        } finally {
            pw.flush();
            throw new IOException(sw.toString());
        }
    }
}
项目:openjdk-jdk10    文件:XMLSignatureInputDebugger.java   
/**
 * Method getHTMLRepresentation
 *
 * @return The HTML Representation.
 * @throws XMLSignatureException
 */
public String getHTMLRepresentation() throws XMLSignatureException {
    if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) {
        return HTMLPrefix + "<blink>no node set, sorry</blink>" + HTMLSuffix;
    }

    // get only a single node as anchor to fetch the owner document
    Node n = this.xpathNodeSet.iterator().next();

    this.doc = XMLUtils.getOwnerDocument(n);

    try {
        this.writer = new StringWriter();

        this.canonicalizeXPathNodeSet(this.doc);
        this.writer.close();

        return this.writer.toString();
    } catch (IOException ex) {
        throw new XMLSignatureException("empty", ex);
    } finally {
        this.xpathNodeSet = null;
        this.doc = null;
        this.writer = null;
    }
}
项目:retroxlibs    文件:RetroBoxDialog.java   
public static void showException(final Activity activity, Exception e, SimpleCallback callback) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    Throwable cause = e.getCause();
    if (cause!=null) {
        cause.printStackTrace(pw);
    } else {
        e.printStackTrace(pw);
    }

    final TextView text = (TextView)activity.findViewById(R.id.txtDialogAction);
    text.setTextSize(12);

    String msg =  e.toString() + "\n" + e.getMessage() + "\n" + sw.toString();
    showAlert(activity, "Error", msg, callback);
}
项目:java-debug    文件:CompileUtils.java   
public static void compileFiles(File projectRoot, List<String> javaFiles) {
    DiagnosticCollector diagnosticCollector = new DiagnosticCollector();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.ENGLISH, Charset.forName("utf-8"));
    Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(javaFiles.toArray(new String[0]));
    File outputFolder = new File(projectRoot, "bin");
    if (!outputFolder.exists()) {
        outputFolder.mkdir();
    }
    String[] options = new String[] { "-d", outputFolder.getAbsolutePath() , "-g", "-proc:none"};
    final StringWriter output = new StringWriter();
    CompilationTask task = compiler.getTask(output, fileManager, diagnosticCollector, Arrays.asList(options), null, javaFileObjects);
    boolean result = task.call();
    if (!result) {
        throw new IllegalArgumentException(
            "Compilation failed:\n" + output);
    }
    List list = diagnosticCollector.getDiagnostics();
    for (Object object : list) {
        Diagnostic d = (Diagnostic) object;
        System.out.println(d.getMessage(Locale.ENGLISH));
    }
}
项目:JavaRushTasks    文件:Solution.java   
public static StringWriter getAllDataFromInputStream(InputStream is) throws IOException {
    StringWriter writer = new StringWriter();

    try {
        while (is.available() > 0) {
            byte[] buf = new byte[1024];
            int len = is.read(buf);
            String s = new String(buf, 0, len);
            writer.append(s);
        }
    } catch (Exception e) {
        return new StringWriter();
    }

    return writer;
}
项目:ralasafe    文件:UserCategory.java   
public UserCategoryTestResult test(User user, Map context,
        QueryManager queryManager) {
    UserCategoryTestResult result = new UserCategoryTestResult();
    Interpreter interpreter = new Interpreter();
    String script = toScript();
    try {
        eval(interpreter, user, context, queryManager);
        Boolean contain = (Boolean) interpreter
                .get(SystemConstant.DOES_USER_CATEGORY_CONTAIN);
        Map variableMap = (Map) interpreter
                .get(SystemConstant.VARIABLE_MAP);
        result.setValid(contain.booleanValue());
        result.setFailed(false);
        result.setScript(script);
        result.setVariableMap(variableMap);
    } catch (EvalError e) {
        result.setFailed(true);
        StringWriter sw=new StringWriter();
        PrintWriter pw=new PrintWriter( sw );
        e.printStackTrace( pw );
        result.setErrorMessage( sw.toString() );
        //result.setErrorMessage(StringUtil.getEvalError(e.getMessage()));
        result.setScript(script);
    }
    return result;
}
项目:Android-DFU-App    文件:UARTActivity.java   
/**
 * Saves the given configuration in the database.
 */
private void saveConfiguration() {
    final UartConfiguration configuration = mConfiguration;
    try {
        final Format format = new Format(new HyphenStyle());
        final Strategy strategy = new VisitorStrategy(new CommentVisitor());
        final Serializer serializer = new Persister(strategy, format);
        final StringWriter writer = new StringWriter();
        serializer.write(configuration, writer);
        final String xml = writer.toString();

        mDatabaseHelper.updateConfiguration(configuration.getName(), xml);
        mWearableSynchronizer.onConfigurationAddedOrEdited(mPreferences.getLong(PREFS_CONFIGURATION, 0), configuration);
    } catch (final Exception e) {
        Log.e(TAG, "Error while creating a new configuration", e);
    }
}
项目:openjdk-jdk10    文件:XSLTFunctionsTest.java   
/**
 * @bug 8165116
 * Verifies that redirect works properly when extension function is enabled
 *
 * @param xml the XML source
 * @param xsl the stylesheet that redirect output to a file
 * @param output the output file
 * @param redirect the redirect file
 * @throws Exception if the test fails
 **/
@Test(dataProvider = "redirect")
public void testRedirect(String xml, String xsl, String output, String redirect) throws Exception {

    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(ORACLE_ENABLE_EXTENSION_FUNCTION, true);
    Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));

    //Transform the xml
    tryRunWithTmpPermission(
            () -> t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter())),
            new FilePermission(output, "write"), new FilePermission(redirect, "write"));

    // Verifies that the output is redirected successfully
    String userDir = getSystemProperty("user.dir");
    Path pathOutput = Paths.get(userDir, output);
    Path pathRedirect = Paths.get(userDir, redirect);
    Assert.assertTrue(Files.exists(pathOutput));
    Assert.assertTrue(Files.exists(pathRedirect));
    System.out.println("Output to " + pathOutput + " successful.");
    System.out.println("Redirect to " + pathRedirect + " successful.");
    Files.deleteIfExists(pathOutput);
    Files.deleteIfExists(pathRedirect);
}
项目:fluentxml4j    文件:FluentXmlSerializerIntegrationTest.java   
@Test
public void serializeCustomizedToWriter()
{
    StringWriter wr = new StringWriter();

    serialize(documentTestRule.asDocument())
            .withSerializer(new SerializerConfigurerAdapter()
            {
                @Override
                protected void configure(Transformer transformer)
                {
                    super.configure(transformer);
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                }
            })
            .to(wr);

    String serializedXml = wr.getBuffer().toString();
    assertThat(serializedXml, is("<foo:test xmlns:foo=\"bar\"/>\n"));
}
项目:server-utility    文件:JaxbXMLUtil.java   
/**
 * JavaBean转换成xml,默认编码UTF-8
 *
 * @param obj 待转换对象
 * @return 转换后的xml
 */
public static String convertToXml(Object obj) {
    String result = null;
    try {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, CharsetConstant.UTF_8);

        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        result = writer.toString();
    } catch (Exception e) {
        logger.error(ExceptionUtil.parseException(e));
    }

    return result;
}
项目:incubator-netbeans    文件:ErrorManagerDelegatesToLoggingTest.java   
public void testThatWeNotifyAnException() throws Exception {
    Throwable t = new NullPointerException("npe");
    Throwable v = new ClassNotFoundException("cnf", t);

    Throwable a = new IOException();
    ErrorManager.getDefault().annotate(a, v);
    ErrorManager.getDefault().notify(a);

    assertEquals("Last throwable is a", a, MyHandler.lastThrowable);
    assertNotNull("And it has a cause", MyHandler.lastThrowable.getCause());

    StringWriter w = new StringWriter();
    MyHandler.lastThrowable.getCause().printStackTrace(new PrintWriter(w));
    String msg = w.toString();

    if (msg.indexOf("npe") == -1) fail("there should be npe: " + msg);
    if (msg.indexOf("cnf") == -1) fail("there should be cnf: " + msg);

}
项目:marathonv5    文件:ObjectMapNamingStrategy.java   
public void init() {
    runtimeLogger = RuntimeLogger.getRuntimeLogger();
    omapService = getObjectMapService();
    try {
        omapService.load();
        runtimeLogger.info(MODULE, "Loaded object map omapService");
    } catch (IOException e) {
        StringWriter w = new StringWriter();
        e.printStackTrace(new PrintWriter(w));
        runtimeLogger.error(MODULE, "Error in creating naming strategy:" + e.getMessage(), w.toString());
        FXUIUtils.showMessageDialog(null, "Error in creating naming strategy:" + e.getMessage(), "Error in NamingStrategy",
                Alert.AlertType.ERROR);
        e.printStackTrace();
        System.exit(1);
    }
}
项目:xsharing-services-router    文件:UraSerializerWrapperTest.java   
@Test
public void testSerialize() throws Exception {
    String expected = "{\"version\":null,\"status\":0,\"routeInstructions\":null,\"routeGeometry\":[[50.753,5.712],[50.653,6.012]]}";
    GeoCoordinates[] coords = new GeoCoordinates[2];
    coords[0] = new GeoCoordinates(50.753, 5.712);
    coords[1] = new GeoCoordinates(50.653, 6.012);
    PathData pathData = new PathData.Builder().withRouteGeometry(coords).build();

    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixInAnnotations(PathData.class, UraPathDataMixIn.class);
    Writer stringWriter = new StringWriter();
    try {
        mapper.writeValue(stringWriter, pathData);
        String json = stringWriter.toString();
        assertNotNull(json);
        assertEquals(json, expected);
    } catch (Exception e) {
        fail();
    }
}
项目:Open-DM    文件:AbstractArcCli.java   
public String helpScreen() {
    StringBuffer usage = new StringBuffer();
    HelpFormatter formatter = new HelpFormatter();

    if (cliOrder != null && cliOrder.size() > 0) {
        formatter.setOptionComparator(new OptionComparator());
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    formatter.printHelp(pw,
                        HCPMoverProperties.CLI_WIDTH.getAsInt(),
                        getHelpUsageLine(),
                        null /* header */,
                        getOptions(),
                        HelpFormatter.DEFAULT_LEFT_PAD /* leftPad */,
                        HelpFormatter.DEFAULT_DESC_PAD /* descPad */,
                        null /* footer */,
                        false /* autoUsage */
    );

    usage.append(getHelpHeader());
    usage.append(sw.toString());
    usage.append(getHelpFooter());
    return usage.toString();
}
项目:de.flapdoodle.solid    文件:EscaperExtensionTest.java   
@Test()
public void testPrintBigDecimal() throws PebbleException, IOException {

    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(true).build();

    String source = "{{ num }}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();
    BigDecimal num = new BigDecimal("1234E+4");
    context.put("num", num);

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals(num.toPlainString(), writer.toString());
    assertNotEquals(num.toString(), writer.toString());
}
项目:alfresco-repository    文件:ValueDataTypeValidatorImplTest.java   
@Test
public void testValueContentDataType() throws Exception
{
    // d:content tests
    {
        final String contentDataType = "d:content";
        validate_invalid("somePrefix:", "some very long text"); // invalid QName prefixed data type
        validate_invalid("unknownPrefix" + System.currentTimeMillis() + ":content", "some text"); // prefix is not mapped to a namespace URI

        validate_valid(contentDataType, null); // no validation
        validate_valid(contentDataType, ""); // no validation
        ByteArrayInputStream is = new ByteArrayInputStream("very long text".getBytes("UTF-8"));
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        validate_valid(contentDataType,  writer.toString()); // valid value
    }
}
项目:de.flapdoodle.solid    文件:CoreTagsTest.java   
@Test
public void testForWithArray() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{% for user in users %}{{ user }}{% endfor %}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();

    String[] users = new String[3];
    users[0] = "User 1";
    users[1] = "User 2";
    users[2] = "User 3";
    context.put("users", users);

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("User 1User 2User 3", writer.toString());
}
项目:jarn    文件:YarnState.java   
/**
 * Replaces any {{ }} wrapped variable placeholders in a {@link String} with
 * the current value in this {@link YarnState}
 * 
 * @param text
 *            The {@link String} to replace variable placeholders in
 * @return The {@link String} with variable values inserted
 */
public String applyVariables(String text) {
    if (!mustacheCache.containsKey(text)) {
        mustacheCache.put(text, mustacheFactory.compile(new StringReader(text), text));
    }
    Mustache mustache = mustacheCache.get(text);

    StringWriter result = new StringWriter();
    mustache.execute(result, variablesMustache);
    return result.toString();
}
项目:openjdk-jdk10    文件:Bug6490380.java   
@Test
public void test() {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        URL input = Bug6490380.class.getResource("Bug4693341.xml");
        StreamSource source = new StreamSource(input.openStream(), input.toString());
        StringWriter sw = new StringWriter();
        transformer.transform(source, new StreamResult(sw));
        String s = sw.toString();
        Assert.assertEquals(s.indexOf("!DOCTYPE"), s.lastIndexOf("!DOCTYPE"));
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
项目:googles-monorepo-demo    文件:FreshValueGeneratorTest.java   
@AndroidIncompatible // problem with equality of Type objects?
public void testFreshInstance() {
  assertFreshInstances(
      String.class, CharSequence.class,
      Appendable.class, StringBuffer.class, StringBuilder.class,
      Pattern.class, MatchResult.class,
      Number.class, int.class, Integer.class,
      long.class, Long.class,
      short.class, Short.class,
      byte.class, Byte.class,
      boolean.class, Boolean.class,
      char.class, Character.class,
      int[].class, Object[].class,
      UnsignedInteger.class, UnsignedLong.class,
      BigInteger.class, BigDecimal.class,
      Throwable.class, Error.class, Exception.class, RuntimeException.class,
      Charset.class, Locale.class, Currency.class,
      List.class, Map.Entry.class,
      Object.class,
      Equivalence.class, Predicate.class, Function.class,
      Comparable.class, Comparator.class, Ordering.class,
      Class.class, Type.class, TypeToken.class,
      TimeUnit.class, Ticker.class,
      Joiner.class, Splitter.class, CharMatcher.class,
      InputStream.class, ByteArrayInputStream.class,
      Reader.class, Readable.class, StringReader.class,
      OutputStream.class, ByteArrayOutputStream.class,
      Writer.class, StringWriter.class, File.class,
      Buffer.class, ByteBuffer.class, CharBuffer.class,
      ShortBuffer.class, IntBuffer.class, LongBuffer.class,
      FloatBuffer.class, DoubleBuffer.class,
      String[].class, Object[].class, int[].class);
}
项目:https-github.com-hyb1996-NoRootScriptDroid    文件:CrashHandler.java   
public static String throwableToString(Throwable throwable) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    throwable.printStackTrace();
    throwable.printStackTrace(pw);
    return sw.toString();
}
项目:GitHub    文件:OnPreSerializeProcessor.java   
@Override
public void findAndParseObjects(RoundEnvironment env, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements, Types types) {
    for (Element element : env.getElementsAnnotatedWith(OnPreJsonSerialize.class)) {
        try {
            processOnPreJsonSerializeMethodAnnotation(element, jsonObjectMap, elements);
        } catch (Exception e) {
            StringWriter stackTrace = new StringWriter();
            e.printStackTrace(new PrintWriter(stackTrace));

            error(element, "Unable to generate injector for %s. Stack trace incoming:\n%s", OnPreJsonSerialize.class, stackTrace.toString());
        }
    }
}
项目:jetfuel    文件:StringAdapter.java   
/**
 * Converts an input stream to a string.
 * 
 * @param is
 * @return
 */
public String convertStream(InputStream is) {
    try {
        StringWriter writer = new StringWriter();
        for (int i = is.read(); i >= 0; i = is.read())
            writer.write(i);
        is.close();
        return writer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:dracoon-dropzone    文件:Crypto.java   
private static String getStringFromPublicKey(PublicKey pubKey) throws InvalidKeyPairException {
    try {
        StringWriter writer = new StringWriter();
        JcaPEMWriter pemWriter = new JcaPEMWriter(writer);
        pemWriter.writeObject(pubKey);
        pemWriter.close();
        return writer.toString();
    } catch (IOException e) {
        throw new InvalidKeyPairException("Could not encode public key. PEM encoding failed.",
                e);
    }
}
项目:ARCLib    文件:IndexStore.java   
/**
 * Converts XML node to String.
 *
 * @param node
 * @return
 * @throws TransformerException
 */
default String nodeToString(Node node)
        throws TransformerException {
    StringWriter buf = new StringWriter();
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    xform.transform(new DOMSource(node), new StreamResult(buf));
    return (buf.toString());
}
项目:Pet-Supply-Store    文件:AbstractUIServlet.java   
private void serveNotFoundException(HttpServletRequest request, HttpServletResponse response, Exception e)
        throws ServletException, IOException {
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    String exceptionAsString = sw.toString();
    response.setStatus(404);
    request.setAttribute("CategoryList", new ArrayList<Category>());
    request.setAttribute("storeIcon", "");
    request.setAttribute("errorImage", "");
    request.setAttribute("title", "Pet Supply Store Timeout");
    request.setAttribute("messagetitle", "404: Not Found Exception: " + e.getMessage());
    request.setAttribute("messageparagraph", exceptionAsString);
    request.setAttribute("login", false);
    request.getRequestDispatcher("WEB-INF/pages/error.jsp").forward(request, response);
}
项目:apache-tomcat-7.0.73-with-comment    文件:HTMLManagerServlet.java   
/**
 * Deploy an application for the specified path from the specified
 * web application archive.
 *
 * @param config URL of the context configuration file to be deployed
 * @param cn Name of the application to be deployed
 * @param war URL of the web application archive to be deployed
 * @return message String
 */
protected String deployInternal(String config, ContextName cn, String war,
        StringManager smClient) {

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    super.deploy(printWriter, config, cn, war, false, smClient);

    return stringWriter.toString();
}
项目:de.flapdoodle.solid    文件:LogicTest.java   
@Test
public void testContainsOperatorWithNot() throws PebbleException, IOException {

    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{% if not (names contains 'Cobra') %}yes{% else %}no{% endif %}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();
    context.put("names", Arrays.asList("Bob", "Maria", "John"));

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("yes", writer.toString());
}
项目:letv    文件:CrashHandler.java   
private String saveCrashInfo(Throwable ex) {
    Writer info = new StringWriter();
    PrintWriter printWriter = new PrintWriter(info);
    ex.printStackTrace(printWriter);
    for (Throwable cause = ex.getCause(); cause != null; cause = cause.getCause()) {
        cause.printStackTrace(printWriter);
    }
    String result = info.toString() + "\t" + ex.getMessage();
    printWriter.close();
    return result;
}
项目:EatDubbo    文件:StringEscapeUtils.java   
/**
 * <p>Worker method for the {@link #escapeJavaScript(String)} method.</p>
 * 
 * @param str String to escape values in, may be null
 * @param escapeSingleQuotes escapes single quotes if <code>true</code>
 * @return the escaped string
 */
private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes) {
    if (str == null) {
        return null;
    }
    try {
        StringWriter writer = new StringWriter(str.length() * 2);
        escapeJavaStyleString(writer, str, escapeSingleQuotes);
        return writer.toString();
    } catch (IOException ioe) {
        // this should never ever happen while writing to a StringWriter
        ioe.printStackTrace();
        return null;
    }
}
项目:lams    文件:NestableDelegate.java   
/**
 * Captures the stack trace associated with the specified
 * <code>Throwable</code> object, decomposing it into a list of
 * stack frames.
 *
 * @param t The <code>Throwable</code>.
 * @return  An array of strings describing each stack frame.
 * @since 2.0
 */
protected String[] getStackFrames(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);

    // Avoid infinite loop between decompose() and printStackTrace().
    if (t instanceof Nestable) {
        ((Nestable) t).printPartialStackTrace(pw);
    } else {
        t.printStackTrace(pw);
    }
    return ExceptionUtils.getStackFrames(sw.getBuffer().toString());
}