Java Code Examples for java.io.StringWriter.toString()

The following are Jave code examples for showing how to use toString() of the java.io.StringWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: rapidminer   File: AnnotationsDecorator.java   View Source Code Vote up 6 votes
/**
 * Calculates the preferred height of the editor pane with the given fixed width.
 *
 * @param width
 *            the width of the pane
 * @return the preferred height given the current editor pane content or {@code -1} if there was
 *         a problem. Value will never exceed {@link WorkflowAnnotation#MAX_HEIGHT}
 */
private int getContentHeightOfEditor(final int width) {
	HTMLDocument document = (HTMLDocument) editPane.getDocument();
	StringWriter writer = new StringWriter();
	try {
		editPane.getEditorKit().write(writer, document, 0, document.getLength());
	} catch (IndexOutOfBoundsException | IOException | BadLocationException e1) {
		// should not happen
		return -1;
	}
	String comment = writer.toString();
	comment = AnnotationDrawUtils.removeStyleFromComment(comment);

	int maxHeight = model.getSelected() instanceof ProcessAnnotation ? ProcessAnnotation.MAX_HEIGHT
			: OperatorAnnotation.MAX_HEIGHT;
	return Math.min(
			AnnotationDrawUtils.getContentHeight(
					AnnotationDrawUtils.createStyledCommentString(comment, model.getSelected().getStyle()), width),
					maxHeight);
}
 
Example 2
Project: myfaces-trinidad   File: ChartBean.java   View Source Code Vote up 6 votes
private String _getEventIntsAsString(int[] intArray)
{
  if(intArray!=null)
  {
    StringWriter sw = new StringWriter();
    for(int i=0; i<intArray.length; ++i)
    {
      if(i!=0)
        sw.append(',');
      sw.append(String.valueOf(intArray[i]));
    }
    return sw.toString();
  }
  else
    return null;
}
 
Example 3
Project: gemoc-studio   File: ErrorAwareMessagingSystem.java   View Source Code Vote up 6 votes
@Override
public void log(Kind msgKind, String message, String messageGroup,
		Throwable throwable) {
	StringWriter sw = new StringWriter();
	if(throwable != null){
		throwable.printStackTrace(new PrintWriter(sw));
	}
	String stackTrace = sw.toString();
	System.out.println(getKindString(msgKind)+" [" +messageGroup + "] " + message + " "+getCallerString()+"\n"+ stackTrace);
	switch (msgKind) {
	case UserERROR:
		errorTrace.add(getKindString(msgKind) + " [" +messageGroup + "] " + message + " "  + " "+getCallerString());
		break;
	case DevERROR:
		errorTrace.add(getKindString(msgKind) + " [" +messageGroup + "] " + message + " "  + " "+getCallerString());
		break;
	default:
		break;
	}
}
 
Example 4
Project: ctsms   File: InputModel.java   View Source Code Vote up 6 votes
public String getInkValueWithSelections() throws JSONException, UnsupportedEncodingException {
	JSONArray inkValueJson;
	String inkValue = getInkValue();
	if (inkValue != null && inkValue.length() > 0) {
		inkValueJson = new JSONArray(inkValue);
	} else {
		inkValueJson = new JSONArray();
	}
	StringBuilder selectionSetValueIds = new StringBuilder();
	HashMap<String, String> selectionSetValueIdToStrokesIdMap = getSelectionSetValueIdToStrokesIdMap();
	Iterator<String> it = getSelectionValueIds().iterator();
	while (it.hasNext()) {
		if (selectionSetValueIds.length() > 0) {
			selectionSetValueIds.append(WebUtil.ID_SEPARATOR_STRING);
		}
		String selectionSetValueId = it.next();
		if (selectionSetValueIdToStrokesIdMap.containsKey(selectionSetValueId)) {
			selectionSetValueIds.append(selectionSetValueIdToStrokesIdMap.get(selectionSetValueId));
		}
	}
	inkValueJson.put(selectionSetValueIds.toString());
	StringWriter output = new StringWriter();
	inkValueJson.write(output);
	return output.toString();
}
 
Example 5
Project: GifImageLoader   File: Util.java   View Source Code Vote up 5 votes
static String readFully(Reader reader) throws IOException {
	try {
		StringWriter writer = new StringWriter();
		char[] buffer = new char[1024];
		int count;
		while ((count = reader.read(buffer)) != -1) {
			writer.write(buffer, 0, count);
		}
		return writer.toString();
	} finally {
		reader.close();
	}
}
 
Example 6
Project: paraflow   File: ParaFlowException.java   View Source Code Vote up 5 votes
private String getStackTraceMessage()
{
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    super.printStackTrace(pw);

    return sw.toString();
}
 
Example 7
Project: GitHub   File: JsonMapper.java   View Source Code Vote up 5 votes
/**
 * Serialize a list of objects to a JSON String.
 *
 * @param map The map of objects to serialize.
 */
public String serialize(Map<String, T> map) throws IOException {
    StringWriter sw = new StringWriter();
    JsonGenerator jsonGenerator = LoganSquare.JSON_FACTORY.createGenerator(sw);
    serialize(map, jsonGenerator);
    jsonGenerator.close();
    return sw.toString();
}
 
Example 8
Project: jetfuel   File: HttpClient.java   View Source Code Vote up 5 votes
public String downloadString() {
	try {
		StringWriter writer = new StringWriter();
		for (int i = this.responseStream.read(); i >= 0; i = this.responseStream.read())
			writer.write(i);

		String ret = writer.toString();

		writer.close();
		return ret;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 9
Project: OpenJSharp   File: JMods.java   View Source Code Vote up 5 votes
@Override
public String toString() {
    StringWriter s = new StringWriter();
    JFormatter f = new JFormatter(new PrintWriter(s));
    this.generate(f);
    return s.toString();
}
 
Example 10
Project: CoffeeMaker   File: VelocityUtil.java   View Source Code Vote up 5 votes
public static String parse(String templateFileName, AbstractFileWrapper data) {

        // 初始化模板引擎
        VelocityEngine engine = new VelocityEngine();
        engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
        engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        Properties props = new Properties();

        URL resource = VelocityUtil.class.getClassLoader().getResource(".");
        Objects.requireNonNull(resource);

        // 设置模板目录
        String basePath = resource.getPath() + Const.TEMPLATE_LOCATION_DIR;
        props.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,  basePath);
        //设置velocity的编码
        props.setProperty(Velocity.ENCODING_DEFAULT, StandardCharsets.UTF_8.name());
        props.setProperty(Velocity.INPUT_ENCODING,   StandardCharsets.UTF_8.name());
        props.setProperty(Velocity.OUTPUT_ENCODING,  StandardCharsets.UTF_8.name());
        engine.init(props);

        Template template = engine.getTemplate(templateFileName);
        // 设置变量
        VelocityContext ctx = new VelocityContext();

        ctx.put("data", data);

        StringWriter writer = new StringWriter();
        template.merge(ctx, writer);

        return writer.toString();


    }
 
Example 11
Project: KUtils-master   File: KLog.java   View Source Code Vote up 5 votes
private static void printStackTrace() {

        if (!IS_SHOW_LOG) {
            return;
        }

        Throwable tr = new Throwable();
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        tr.printStackTrace(pw);
        pw.flush();
        String message = sw.toString();

        String traceString[] = message.split("\\n\\t");
        StringBuilder sb = new StringBuilder();
        sb.append("\n");
        for (String trace : traceString) {
            if (trace.contains("at com.socks.library.KLog")) {
                continue;
            }
            sb.append(trace).append("\n");
        }
        String[] contents = wrapperContent(STACK_TRACE_INDEX_4, null, sb.toString());
        String tag = contents[0];
        String msg = contents[1];
        String headString = contents[2];
        BaseLog.printDefault(D, tag, headString + msg);
    }
 
Example 12
Project: neoscada   File: ParserDriverProcessor.java   View Source Code Vote up 5 votes
private String makeXml ( final Component component ) throws IOException
{
    final XMIResourceImpl xmi = new XMIResourceImpl ();
    xmi.getContents ().add ( EcoreUtil.copy ( component ) );

    final StringWriter writer = new StringWriter ();
    xmi.save ( writer, null );
    return writer.toString ();
}
 
Example 13
Project: bazel-tools   File: Main.java   View Source Code Vote up 5 votes
private static String createLockContents(final Options options) throws IOException {
  final StringWriter stringWriter = new StringWriter();
  try (final Stream<Path> jvmFiles = Files.walk(options.jvmDirectory());
      final PrintWriter out = new PrintWriter(stringWriter)) {
    out.println("version\t1");
    Stream.concat(Stream.of(options.inputFile(), options.outputFile()), jvmFiles)
        .sorted()
        .forEachOrdered(file -> describeFile(options.workspaceDirectory(), file, out));
  }
  return stringWriter.toString();
}
 
Example 14
Project: 5zig-TIMV-Plugin   File: JSONArray.java   View Source Code Vote up 5 votes
public static String toJSONString(double[] array){
	final StringWriter writer = new StringWriter();
	
	try {
		writeJSONString(array, writer);
		return writer.toString();
	} catch(IOException e){
		// This should never happen for a StringWriter
		throw new RuntimeException(e);
	}
}
 
Example 15
Project: Pogamut3   File: SposhLogicController.java   View Source Code Vote up 4 votes
private String getStackTrace(Exception ex) {
    StringWriter sw = new StringWriter();
    ex.printStackTrace(new PrintWriter(sw));
    return sw.toString();
}
 
Example 16
Project: smart-cache   File: Utils.java   View Source Code Vote up 4 votes
public static String getStackTrace(Throwable ex) {
    StringWriter buf = new StringWriter();
    ex.printStackTrace(new PrintWriter(buf));

    return buf.toString();
}
 
Example 17
Project: cas-5.1.0   File: ClickatellSmsSender.java   View Source Code Vote up 4 votes
@Override
public boolean send(final String from, final String to, final String message) {
    try {
        final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization", this.token);
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);

        final Map<String, Object> map = new HashMap<>();
        map.put("content", message);
        map.put("to", Arrays.asList(to));
        map.put("from", from);

        final StringWriter stringify = new StringWriter();
        mapper.writeValue(stringify, map);

        final HttpEntity<String> request = new HttpEntity<>(stringify.toString(), headers);
        final ResponseEntity<Map> response = restTemplate.postForEntity(new URI(this.serverUrl), request, Map.class);
        if (response.hasBody()) {
            final List<Map> messages = (List<Map>) response.getBody().get("messages");

            final String error = (String) response.getBody().get("error");
            if (StringUtils.isNotBlank(error)) {
                LOGGER.error(error);
                return false;
            }

            final List<String> errors = messages.stream()
                    .filter(m -> m.containsKey("accepted") && !Boolean.valueOf(m.get("accepted").toString()) && m.containsKey("error"))
                    .map(m -> (String) m.get("error"))
                    .collect(Collectors.toList());
            if (errors.isEmpty()) {
                return true;
            }
            errors.forEach(LOGGER::error);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return false;
}
 
Example 18
Project: tscfg-docgen   File: FreemarkerDocGenerator.java   View Source Code Vote up 4 votes
@Override
public String generateDoc(Configuration config) throws Exception {
  StringWriter writer = new StringWriter();
  loadTemplate().process(config, writer);
  return writer.toString();
}
 
Example 19
Project: dlface   File: Entities.java   View Source Code Vote up 3 votes
/**
 * <p>
 * Escapes the characters in a <code>String</code>.
 * </p>
 * <p/>
 * <p>
 * For example, if you have called addEntity(&quot;foo&quot;, 0xA1), escape(&quot;\u00A1&quot;) will return
 * &quot;&amp;foo;&quot;
 * </p>
 *
 * @param str The <code>String</code> to escape.
 * @return A new escaped <code>String</code>.
 */
public String escape(String str) {
    StringWriter stringWriter = createStringWriter(str);
    try {
        this.escape(stringWriter, str);
    } catch (IOException e) {
        // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) do not
        // throw IOExceptions.
        throw new RuntimeException(e);
    }
    return stringWriter.toString();
}
 
Example 20
Project: BrainBridge   File: LoggerUtil.java   View Source Code Vote up 2 votes
/**
 * Gets the stack trace of a given exception as {@link String} instead of
 * printing it to the error console.
 * 
 * @param e
 *            The exception to get the stack trace of
 * @return The stack trace of the given exception
 */
public static final String getStackTrace(final Exception e) {
	final StringWriter target = new StringWriter();
	e.printStackTrace(new PrintWriter(target));
	return target.toString();
}