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

The following are Jave code examples for showing how to use append() 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: jdk8u-jdk   File: FunctionGenerator.java   View Source Code Vote up 6 votes
private static String createLocalNew(final Class<? extends Invoke> type, final Function fxn) {
    final String identifier = makeInstanceName(fxn);
    StringWriter out = new StringWriter();

    out.append(String.format("%3$s[] argCoders = new %3$s[%1$d + %2$s.length];\n", fxn.args.size(), VARARGS_NAME, Coder.class.getCanonicalName()));

    for(int i = 0; i < fxn.args.size(); i++)
        out.append(String.format("argCoders[%1$d] = %2$s;\n", i, fxn.args.get(0).type.getJType().getCoderDescriptor().getCoderInstanceName()));

    if(fxn.variadic){
        out.append(String.format("for(int i = %1$d; i < (%1$d + %2$s.length); i++)\n", fxn.args.size(), VARARGS_NAME));
        out.append(String.format("\targCoders[i] = %1$s.getCoderAtRuntime(%2$s[i - %3$s]);\n", Coder.class.getCanonicalName(), VARARGS_NAME, fxn.args.size()));
    }

    out.append("final " + type.getCanonicalName() + " " + identifier + " = new " + type.getCanonicalName() + "(" + firstArg(fxn) + ", \"" + fxn.name + "\", "
            + fxn.returnValue.type.getJType().getCoderDescriptor().getCoderInstanceName() + ", argCoders);");

    return out.toString();
}
 
Example 2
Project: neoscada   File: DebianPackageWriter.java   View Source Code Vote up 6 votes
protected ContentProvider createChecksumContent () throws IOException
{
    if ( this.checkSums.isEmpty () )
    {
        return ContentProvider.NULL_CONTENT;
    }

    final StringWriter sw = new StringWriter ();

    for ( final Map.Entry<String, String> entry : this.checkSums.entrySet () )
    {
        final String filename = entry.getKey ().substring ( 2 ); // without the leading dot and slash

        sw.append ( entry.getValue () );
        sw.append ( "  " );
        sw.append ( filename );
        sw.append ( '\n' );
    }

    sw.close ();

    return new StaticContentProvider ( sw.toString () );
}
 
Example 3
Project: myfaces-trinidad   File: ChartRenderer.java   View Source Code Vote up 6 votes
protected void _outputSVGDocumentCreate(
  FacesContext context,
  StringWriter sw,
  UIComponent  component,
  FacesBean    bean
  ) throws IOException
{
  sw.append("ApacheChart.createSVG(\"");
  String clientId = component.getClientId(context);
  sw.append(clientId);
  sw.append("\",\"svgChart");
  sw.append(clientId);
  sw.append("\",\"");
  String templateURL = getTemplateSource(component, bean);
  templateURL = context.getExternalContext().encodeResourceURL(templateURL);
  sw.append(templateURL);
  sw.append("\",\"width:100%; height:100%;\"");
  sw.append(",null);\n");
}
 
Example 4
Project: aos-MediaLib   File: XmlDb.java   View Source Code Vote up 6 votes
private static void escapeAndAppendString(final String string, final StringWriter writer) {
    final int N = string.length();
    final char NE = (char)ESCAPE_TABLE.length;
    final String[] escapes = ESCAPE_TABLE;
    int lastPos = 0;
    int pos;
    for (pos=0; pos<N; pos++) {
        char c = string.charAt(pos);
        if (c >= NE) continue;
        String escape = escapes[c];
        if (escape == null) continue;
        if (lastPos < pos) writer.append(string, lastPos, pos);
        lastPos = pos + 1;
        writer.append(escape);
    }
    if (lastPos < pos) writer.append(string, lastPos, pos);
}
 
Example 5
Project: incubator-netbeans   File: MakeJNLP.java   View Source Code Vote up 5 votes
private void generateVersionXMLFiles() throws IOException {
    FileSet fs = new FileSet();
    fs.setIncludes("**/*.jar");
    for (File directory : jarDirectories) {
        fs.setDir(directory);
        DirectoryScanner scan = fs.getDirectoryScanner(getProject());
        StringWriter writeVersionXML = new StringWriter();
        writeVersionXML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        writeVersionXML.append("<jnlp-versions>\n");
        for (String jarName : scan.getIncludedFiles()) {
            File jar = new File(scan.getBasedir(), jarName);
            JarFile jarFile = new JarFile(jar);
            String version = getJarVersion(jarFile);
            if (version != null) {
                writeVersionXML.append("    <resource>\n        <pattern>\n            <name>");
                writeVersionXML.append(jar.getName());
                writeVersionXML.append("</name>\n            <version-id>");
                writeVersionXML.append(version);
                writeVersionXML.append("</version-id>\n        </pattern>\n        <file>");
                writeVersionXML.append(jar.getName());
                writeVersionXML.append("</file>\n    </resource>\n");
            } else {
                writeVersionXML.append("    <!-- No version found for ");
                writeVersionXML.append(jar.getName());
                writeVersionXML.append(" -->\n");
            }
        }
        writeVersionXML.append("</jnlp-versions>\n");
        writeVersionXML.close();

        File versionXML = new File(directory, "version.xml");
        FileWriter w = new FileWriter(versionXML);
        w.write(writeVersionXML.toString());
        w.close();
    }
}
 
Example 6
Project: bitsy   File: Record.java   View Source Code Vote up 5 votes
public static void generateEdgeLine(StringWriter sw, ObjectMapper mapper, EdgeBean eBean) throws JsonGenerationException, JsonMappingException, IOException {
    sw.getBuffer().setLength(0);
    
    sw.append('E'); // Record type
    sw.append('=');
    
    mapper.writeValue(sw, eBean);
    
    sw.append('#');
    
    int hashCode = sw.toString().hashCode(); 
    sw.append(toHex(hashCode));
    sw.append('\n');
}
 
Example 7
Project: jdk8u-jdk   File: NTypePrinter.java   View Source Code Vote up 5 votes
protected String printStruct(NStruct nt, char open, char close){
    StringWriter sw = new StringWriter();
    sw.append(open);
    sw.append(nt.name);
    if(nt.fields.size() > 0){
        sw.append('=');
        for(NField f : nt.fields){
            if(f.name != null && f.name.length() > 0)
                sw.append("\"" + f.name + "\"");
            sw.append(print(f.type));
        }
    }
    sw.append(close);
    return sw.toString();
}
 
Example 8
Project: springboot-shiro-cas-mybatis   File: InternalConfigStateController.java   View Source Code Vote up 5 votes
/**
 * Handle request.
 *
 * @param request the request
 * @param response the response
 * @return the model and view
 * @throws Exception the exception
 */
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(
        final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {

    final Map<String, Object> list = getBeans(this.applicationContext);
    LOGGER.debug("Found [{}] beans to report", list.size());

    final JsonSerializer<Object> serializer = new BeanObjectJsonSerializer();
    final StringBuilder builder = new StringBuilder();
    builder.append('[');

    final Set<Map.Entry<String, Object>> entries = list.entrySet();
    final Iterator<Map.Entry<String, Object>> it = entries.iterator();

    while (it.hasNext()) {
        final Map.Entry<String, Object> entry = it.next();
        final Object obj = entry.getValue();

        final StringWriter writer = new StringWriter();
        writer.append('{');
        writer.append('\"' + entry.getKey() + "\":");
        serializer.toJson(writer, obj);
        writer.append('}');
        builder.append(writer);

        if (it.hasNext()) {
            builder.append(',');
        }
    }
    builder.append(']');
    final ModelAndView mv = new ModelAndView(VIEW_CONFIG);
    final String jsonData = StringEscapeUtils.escapeJson(builder.toString());

    mv.addObject("jsonData", jsonData);
    mv.addObject("properties", casProperties.entrySet());
    return mv;
}
 
Example 9
Project: vrap   File: IncludeResolver.java   View Source Code Vote up 5 votes
private StringWriter preprocess(final Path filePath, final String currentIndent) throws IOException {
    final StringWriter stringWriter = new StringWriter();

    for (final String line : Files.readAllLines(filePath)) {
        final Matcher matcher = INCLUDE_TAG_PATTERN.matcher(line);

        if (line.startsWith("extends:")) {
            stringWriter.append(line).append("?include").append("\n");
            continue;
        }
        if (!line.startsWith("#%RAML 1.0 DataType")) {
            if (matcher.matches()) {
                final String indent = matcher.group(1) + "  ";
                final Path includePath = filePath.getParent().resolve(matcher.group(3));
                stringWriter.append(currentIndent).append(matcher.group(1)).append(matcher.group(2));
                if (!includePath.getFileName().toString().endsWith(".raml")) {
                    stringWriter.append(" |");
                }
                stringWriter.append("\n");
                final StringWriter includeWriter = preprocess(includePath, currentIndent + indent);
                stringWriter.append(includeWriter.toString()).append("\n");
            } else {
                stringWriter.append(currentIndent).append(line).append("\n");
            }
        }
    }
    return stringWriter;
}
 
Example 10
Project: myfaces-trinidad   File: ChartRenderer.java   View Source Code Vote up 5 votes
/**
 * Encodes a Color in JavaScript Object Notation.
 *
 * @param sw           the StringWriter
 * @param color        the color value
 */
static private void _writeJSColor(
  StringWriter sw,
  Color        color
  ) throws IOException
{
  sw.append("\"RGB(");
  sw.append(String.valueOf(color.getRed()));
  sw.append(",");
  sw.append(String.valueOf(color.getGreen()));
  sw.append(",");
  sw.append(String.valueOf(color.getBlue()));
  sw.append(")\"");
}
 
Example 11
Project: confplanner   File: SolverAction.java   View Source Code Vote up 5 votes
public String describeBest() {
    Solver<ConferenceData> solver = this.solver;
    if (solver == null) {
        return "";
    }
    ConferenceData currentBest = solver.getBestSolution();
    if (currentBest == prevBest) {
        return prevBestDescr;
    }
    prevBest = currentBest;
    currentBest.sort();

    StringWriter sw = new StringWriter();

    ScoreDirector<ConferenceData> scorer = solver.getScoreDirectorFactory().buildScoreDirector();
    scorer.setWorkingSolution(currentBest);
    Collection<ConstraintMatchTotal> totals = scorer.getConstraintMatchTotals();
    Map<Object, Indictment> map = scorer.getIndictmentMap();

    sw.append("<html><body style='font-family:monospace'>");
    for (ConstraintMatchTotal total : totals) {
        sw.append(String.valueOf(total.getScoreTotal())).append("\t").append(total.getConstraintName()).append("<br>");
    }
    sw.append("<br>");
    currentBest.print(sw, map);
    sw.append("</body></html>");
    prevBestDescr = sw.toString();
    return prevBestDescr;
}
 
Example 12
Project: microMathematics   File: TestScript.java   View Source Code Vote up 5 votes
public void publishHtmlReport(StringWriter writer)
{
    final int failedNumber = getTestCaseNumber(NumberType.FAILED);
    writer.append("\n\n<h1>" + scriptContent + "</h1>\n");
    writer.append("<p><b>Name</b>: " + scriptName + "</p>\n");
    writer.append("<p><b>Number of test cases</b>: " + getTestCaseNumber(NumberType.TOTAL) + "</p>\n");
    writer.append("<table border = \"1\" cellspacing=\"0\" cellpadding=\"5\">\n");
    String title = "    <tr>";
    for (String t : TestCase.PARAMETERS)
    {
        title += "<td><b>" + t + "</b></td>";
    }
    title += "</tr>\n";
    writer.append(title);
    for (TestCase tc : testCases)
    {
        tc.publishHtmlReport(writer);
    }
    writer.append("</table>\n");
    String status = "<p><b>Status</b>: ";
    if (failedNumber == 0)
    {
        status += "<font color=\"green\">PASSED</font>";
    }
    else
    {
        status += "<font color=\"red\">FAILED</font>";
    }
    status += " (passed: " + getTestCaseNumber(NumberType.PASSED) + ", failed: " + failedNumber + ")</p>\n";
    writer.append(status);
}
 
Example 13
Project: jdk8u-jdk   File: Coder.java   View Source Code Vote up 5 votes
private static String objCEncoding(final Coder[] elementCoders) {
    StringWriter str = new StringWriter();
    str.append("{?=");
    for(Coder c : elementCoders)
        str.append(c.getObjCEncoding());
    str.append("}");
    return str.toString();
}
 
Example 14
Project: myfaces-trinidad   File: ChartRenderer.java   View Source Code Vote up 5 votes
/**
 * Encodes a float in JavaScript Object Notation.
 *
 * @param sw           the StringWriter
 * @param value         the float value
 */
static private void _writeJSDouble(
  StringWriter sw,
  Double       value
  ) throws IOException
{
  sw.append(String.valueOf(value));
}
 
Example 15
Project: myfaces-trinidad   File: ChartRenderer.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
static private void _writeJSObject(
  StringWriter sw,
  Object       attrValue
  ) throws IOException
{
  if (attrValue == null)
  {
    sw.append("null");
  }
  else
  {
    if (attrValue instanceof String)
    {
      _writeJSString(sw, ((String)attrValue));
      return;
    }
    Class valueClass = attrValue.getClass();
    if (Boolean.class == valueClass)
    {
      _writeJSBoolean(sw, (Boolean)attrValue);
    }
    else if (Integer.class == valueClass)
    {
      _writeJSInt(sw, (Integer)attrValue);
    }
    else if (Double.class == valueClass)
    {
      _writeJSDouble(sw, (Double)attrValue);
    }
    else if (Color.class == valueClass)
    {
      _writeJSColor(sw, ((Color)attrValue));
    }
    else if (Collection.class.isAssignableFrom(valueClass))
    {
      _writeJSCollection(sw, ((Collection)attrValue));
    }
  }
}
 
Example 16
Project: calcite-avatica   File: Spaces.java   View Source Code Vote up 4 votes
/** Appends {@code n} spaces to a {@link StringWriter}. */
public static StringWriter append(StringWriter pw, int n) {
  pw.append(MAX, 0, n);
  return pw;
}
 
Example 17
Project: urdriver   File: URScriptExtendedInvocationHandler.java   View Source Code Vote up 4 votes
@Override
protected String buildURCommand(Method method) {
		if (commandCache.get(method) != null) {
			return commandCache.get(method);
		}
		StringWriter call = new StringWriter();
		call.append(method.getName());
		call.append("(");
		
		Annotation[][] parameterAnnotations = method.getParameterAnnotations();
		Annotation[] annotationOfParameter;
		boolean innerFunctionExists = false;
		for (int i = 0; i < method.getParameterTypes().length; i++) {
			innerFunctionExists = false;
			// resolve annotation for call string
			annotationOfParameter = parameterAnnotations[i];
			for (Annotation a : annotationOfParameter) {
				// resolve the @Named annotation
				if (a instanceof Named) {
					call.append(((Named) a).value());
				}
				// resolve @InnerFunction
				if(a instanceof InnerFunction) {
					Method m = null;
					try {
						m = ((InnerFunction) a).clazz().getDeclaredMethod(((InnerFunction) a).method(), ((InnerFunction) a).arguments());
					} catch (NoSuchMethodException | SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					String subCommand = buildURCommand(m);
					call.append(subCommand);
					innerFunctionExists = true;
				}
			}
			if(!innerFunctionExists)
				call.append("?" + i);
			if (i + 1 < method.getParameterTypes().length) {
				call.append(",");
			}
		}
		call.append(")");

		// add to cache
		commandCache.put(method, call.toString());
		return call.toString();

	}
 
Example 18
Project: jdk8u-jdk   File: StructTest.java   View Source Code Vote up 4 votes
private String byteToHexString(Byte b){
    StringWriter sw = new StringWriter();
    sw.append(halfByteToHex(b & 0xF));
    sw.append(halfByteToHex((b & 0xF0) >> 4));
    return sw.toString();
}
 
Example 19
Project: jdk8u-jdk   File: Subclassing.java   View Source Code Vote up 4 votes
boolean registerUserClass(final Class<? extends ID> clazz, final Class<? extends NSClass> clazzClazz) {
    final String nativeClassName = clazz.getSimpleName();
    // Is it already registered?
    if(0 != NSClass.getNativeClassByName(nativeClassName))
        return false;

    if(clazz.isAnonymousClass())
        throw new RuntimeException("JObjC cannot register anonymous classes.");

    // Verify superclass
    long superClass = NSClass.getNativeClassByName(clazz.getSuperclass().getSimpleName());
    if(0 == superClass)
        throw new RuntimeException(clazz.getSuperclass() + ", the superclass of " + clazz + ", must be a registered class.");

    runtime.registerPackage(clazz.getPackage().getName());

    // Create class
    long classPtr = Subclassing.allocateClassPair(superClass, nativeClassName);
    if(classPtr == 0) throw new RuntimeException("objc_allocateClassPair returned 0.");

    // Add ivar to hold jobject
    boolean addedI = Subclassing.addIVarForJObj(classPtr);
    if(!addedI) throw new RuntimeException("class_addIvar returned false.");

    // Verify constructor
    try {
        clazz.getConstructor(ID.CTOR_ARGS);
    } catch (Exception e) {
        throw new RuntimeException("Could not access required constructor: " + ID.CTOR_ARGS, e);
    }

    // Patch alloc to create corresponding jobject on invoke
    patchAlloc(classPtr);

    // Add methods
    Set<String> takenSelNames = new HashSet<String>();
    for(Method method : clazz.getDeclaredMethods()){
        // No overloading
        String selName = SEL.selectorName(method.getName(), method.getParameterTypes().length > 0);
        if(takenSelNames.contains(selName))
            throw new RuntimeException("Obj-C does not allow method overloading. The Objective-C selector '"
                    + selName + "' appears more than once in class " + clazz.getCanonicalName() + " / " + nativeClassName + ".");

        method.setAccessible(true);

        // Divine CIF
        Coder returnCoder = Coder.getCoderAtRuntimeForType(method.getReturnType());
        Class[] paramTypes = method.getParameterTypes();
        Coder[] argCoders = new Coder[paramTypes.length];
        for(int i = 0; i < paramTypes.length; i++)
            argCoders[i] = Coder.getCoderAtRuntimeForType(paramTypes[i]);

        CIF cif = new MsgSend(runtime, selName, returnCoder, argCoders).funCall.cif;

        // .. and objc encoding
        StringWriter encType = new StringWriter();
        encType.append(returnCoder.getObjCEncoding());
        encType.append("@:");
        for(int i = 0; i < argCoders.length; i++)
            encType.append(argCoders[i].getObjCEncoding());

        // Add it!
        boolean addedM = Subclassing.addMethod(classPtr, selName, method, cif, cif.cif.bufferPtr, encType.toString());
        if(!addedM) throw new RuntimeException("Failed to add method.");
        takenSelNames.add(selName);
    }

    // Seal it
    Subclassing.registerClassPair(classPtr);
    registeredUserSubclasses.add(classPtr);

    return true;
}
 
Example 20
Project: netto_rpc   File: RpcTcpClient.java   View Source Code Vote up 4 votes
@Override
protected Object invokeMethod(Method method, Object[] args) throws Throwable {
	// ServiceRequest req = new ServiceRequest();
	// req.setMethodName(method.getName());
	// req.setServiceName(this.getServiceName());
	// if (args != null)
	// req.setArgs(Arrays.asList(args));

	Socket socket = null;
	try {
		ObjectMapper mapper = JsonMapperUtil.getJsonMapper();
		socket = this.pool.getResource();
		socket.setSoTimeout(this.getTimeout());
		OutputStream os = socket.getOutputStream();
		String requestBody = mapper.writeValueAsString(args);
		byte[] byteBody = requestBody.getBytes("UTF-8");
		StringWriter headerWriter = new StringWriter(128);
		headerWriter.append(Constants.SERVICE_HEADER).append(":").append(this.getServiceName()).append("\r\n");
		headerWriter.append(Constants.METHOD_HEADER).append(":").append(method.getName()).append("\r\n");
		if (args != null) {
			headerWriter.append(Constants.ARGSLEN_HEADER).append(":").append(args.length + "");
		} else {
			headerWriter.append(Constants.ARGSLEN_HEADER).append(":0");
		}

		if (this.doSignature) {
			headerWriter.append("\r\n");
			String signature = this.createSignature(requestBody);
			headerWriter.append(NettoFrame.SIGNATURE_HEADER).append(":").append(signature);
		}

		byte[] headerContentBytes = headerWriter.toString().getBytes("UTF-8");

		String header = String.format("%s:%d/%d/%d", NettoFrame.NETTO_HEADER_START, 2, headerContentBytes.length,
				byteBody.length);
		byte[] headerBytes = new byte[NettoFrame.HEADER_LENGTH];

		Arrays.fill(headerBytes, (byte) ' ');
		System.arraycopy(header.getBytes("utf-8"), 0, headerBytes, 0, header.length());
		os.write(headerBytes);
		os.write(headerContentBytes);
		os.flush();
		os.write(byteBody);

		os.flush();

		InputStream is = socket.getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		String body = br.readLine();

		ServiceResponse<?> res = mapper.readValue(body, mapper.getTypeFactory().constructParametricType(
				ServiceResponse.class, mapper.getTypeFactory().constructType(method.getGenericReturnType())));
		if (res.getSuccess()) {
			return res.getRetObject();// mapper.readValue(res.getBody(),
										// mapper.getTypeFactory().constructType(method.getGenericReturnType()));
		} else {
			throw new Exception(String.valueOf(res.getErrorMessage()));
		}

	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		if (e instanceof SocketException) {
			socket.close();
			this.pool.invalidate(socket);
		}
		throw e;
	} finally {
		this.pool.release(socket);
	}
}