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

The following are Jave code examples for showing how to use append() of the java.io.Writer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Reer   File: XmlTransformer.java   Source Code and License Vote up 6 votes
private void doWriteTo(Writer writer, String encoding) {
    writeXmlDeclaration(writer, encoding);

    try {
        if (node != null) {
            printNode(node, writer);
        } else if (element != null) {
            printDomNode(element, writer);
        } else if (builder != null) {
            writer.append(TextUtil.toPlatformLineSeparators(stripXmlDeclaration(builder)));
        } else {
            writer.append(TextUtil.toPlatformLineSeparators(stripXmlDeclaration(stringValue)));
        }
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 2
Project: monarch   File: PluckStacks.java   Source Code and License Vote up 6 votes
public void writeTo(Writer w) throws IOException {
  if (DEBUG) {
    w.append("stack.name='" + getThreadName() + "' runnable=" + this.runnable + " lines="
        + lines.size());
    w.append("\n");
  }
  boolean first = true;
  for (String line : lines) {
    w.append(line);
    w.append("\n");
    if (first) {
      first = false;
      if (breadcrumbs != null) {
        for (String bline : breadcrumbs) {
          w.append(bline).append("\n");
        }
      }
    }
  }
}
 
Example 3
Project: rlc-analyser   File: RLCDataExporter.java   Source Code and License Vote up 6 votes
public static void writeLine(final Writer w, final List<String> values, char separators, final char customQuote) throws IOException {

			boolean first = true;

			//default customQuote is empty

			if (separators == ' ') {
				separators = DEFAULT_SEPARATOR;
			}

			final StringBuilder sb = new StringBuilder();
			for (final String value : values) {
				if (!first) {
					sb.append(separators);
				}
				if (customQuote == ' ') {
					sb.append(followCVSformat(value));
				} else {
					sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
				}

				first = false;
			}
			sb.append("\n");
			w.append(sb.toString());
		}
 
Example 4
Project: r8   File: MemberNaming.java   Source Code and License Vote up 6 votes
public void write(Writer writer, int collapsedRange, boolean indent) throws IOException {
  if (indent) {
    writer.append("    ");
  }
  if (collapsedRange == DO_NOT_COLLAPSE) {
    writer.append(inlinedRange.toString());
  } else {
    writer.append(Range.toCollapsedString(collapsedRange));
  }
  writer.append(":");
  signature.write(writer);
  if (originalRange != null) {
    writer.append(':')
        .append(originalRange.toString());
  }
  writer.append(" -> ")
      .append(renamedSignature.name);
  writer.append("\n");
}
 
Example 5
Project: emojava   File: Generator.java   Source Code and License Vote up 6 votes
private static void writeCsvRow(final Writer fw, final String... values) throws IOException {
    for (int i = 0; i < values.length; i++) {
        if (i != 0) {
            fw.append(",");
        }
        String value = values[i];
        if (value.contains("\n") || value.contains("\r")) {
            throw new IllegalStateException("CSV value should not contain newline (limited implementation).");
        }
        if (value.contains(",") || value.contains("\"")) {
            value = '"' + value.replace("\"", "\"\"") + '"';
        }
        fw.append(value);
    }
    fw.append("\r\n");
}
 
Example 6
Project: keywordEntityApiRankService   File: CSVWriter.java   Source Code and License Vote up 6 votes
public static void writeLine(Writer w, List<String> values, String separators, char customQuote)
		throws IOException {

	boolean first = true;

	if (separators == " ") {
		separators = DEFAULT_SEPARATOR;
	}

	StringBuilder sb = new StringBuilder();
	for (String value : values) {
		if (!first) {
			sb.append(separators);
		}
		if (customQuote == ' ') {
			sb.append(followCVSformat(value));
		} else {
			sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
		}

		first = false;
	}
	sb.append("\n");
	w.append(sb.toString());

}
 
Example 7
Project: OperatieBRP   File: AttributeChild.java   Source Code and License Vote up 6 votes
/**
 * Schrijf dit attribuut.
 *
 * @param value waarde
 * @param writer writer om XML mee te schrijven
 * @throws EncodeException bij encodeer foute
 */
@Override
public void encode(final Context context, final T value, final Writer writer) throws EncodeException {
    LOGGER.debug("encode(value={})", value);
    if (value == null) {
        return;
    }

    try {
        writer.append(" ");
        writer.append(getName());
        writer.append("=\"");
        writer.append(converter.encode(context, value));
        writer.append("\"");
    } catch (final IOException e) {
        throw new EncodeException(context.getElementStack(), e);
    }
}
 
Example 8
Project: vertx-sfdc-platformevents   File: JsonExperiments.java   Source Code and License Vote up 6 votes
private void test1() throws IOException {
	// final JsonObject scope = this.getScope();
	final JsonObject x = this.getScope();
	// Map<String, Object> scope = x.getMap();

	final Map<String, Object> scope = this.mappifyJsonObject(x);
	// Map<String, Object> scope = new HashMap<>();
	// scope.put("YesNo", true);
	// scope.put("answer", 42);
	final Mustache m = this.getTemplate();
	final Writer w = this.getWriter();
	w.append(x.encodePrettily());
	m.execute(w, scope);
	w.close();

}
 
Example 9
Project: googles-monorepo-demo   File: AppendableWriterTest.java   Source Code and License Vote up 5 votes
public void testAppendMethods() throws IOException {
  StringBuilder builder = new StringBuilder();
  Writer writer = new AppendableWriter(builder);

  writer.append("Hello,");
  writer.append(' ');
  writer.append("The World Wide Web", 4, 9);
  writer.append("!");

  assertEquals("Hello, World!", builder.toString());
}
 
Example 10
Project: r8   File: ClassNaming.java   Source Code and License Vote up 5 votes
void write(Writer writer, boolean collapseRanges) throws IOException {
  writer.append(originalName);
  writer.append(" -> ");
  writer.append(renamedName);
  writer.append(":\n");
  for (MemberNaming member : members.values()) {
    member.write(writer, collapseRanges, true);
  }
}
 
Example 11
Project: openrouteservice   File: FileUtility.java   Source Code and License Vote up 5 votes
public static void writeFile(String fileName, String encoding, String content) throws IOException
{
	Writer out = new BufferedWriter(new OutputStreamWriter(
			new FileOutputStream(fileName), encoding));
	out.append(content);
	out.flush();
	out.close();
}
 
Example 12
Project: elasticsearch_my   File: Joda.java   Source Code and License Vote up 5 votes
@Override
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
    if (hasMilliSecondPrecision) {
        out.append(String.valueOf(getDateTimeMillis(partial)));
    } else {
        out.append(String.valueOf(getDateTimeMillis(partial) / 1000));
    }
}
 
Example 13
Project: elastic-db-tools-for-java   File: CsvUtils.java   Source Code and License Vote up 5 votes
/**
 * Write a single line to CSV File.
 *
 * @param w
 *            Writer to write to
 * @param values
 *            List of values to write
 * @param separators
 *            List of separators
 * @param customQuote
 *            Custom quotation symbol
 * @throws IOException
 *             Exception thrown by writer
 */
public static void writeLine(Writer w,
        List<String> values,
        char separators,
        char customQuote) throws IOException {
    boolean first = true;

    // default customQuote is empty
    if (separators == ' ') {
        separators = DEFAULT_SEPARATOR;
    }

    StringBuilder sb = new StringBuilder();
    for (String value : values) {
        if (!first) {
            sb.append(separators);
        }
        if (customQuote == ' ') {
            sb.append(followCsvFormat(value));
        }
        else {
            sb.append(customQuote).append(followCsvFormat(value)).append(customQuote);
        }

        first = false;
    }
    sb.append("\n");
    w.append(sb.toString());
}
 
Example 14
Project: Hotspot-master-devp   File: XmlElement.java   Source Code and License Vote up 5 votes
private void addAttributes(Writer sb) throws IOException {
    if (attributes != null) {
        for (Map.Entry<String, Object> item : attributes.entrySet()) {
            sb.append(SPACE).append(item.getKey()).append(EQUEL).append(
                    QUOT);
            addText(sb, (String)item.getValue());
            sb.append(QUOT);
        }
    }
}
 
Example 15
Project: Elasticsearch   File: Joda.java   Source Code and License Vote up 5 votes
@Override
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
    if (hasMilliSecondPrecision) {
        out.append(String.valueOf(getDateTimeMillis(partial)));
    } else {
        out.append(String.valueOf(getDateTimeMillis(partial) / 1000));
    }
}
 
Example 16
Project: plugin-bt-jira   File: CsvWithCustomFieldsStreamingOutput.java   Source Code and License Vote up 4 votes
/**
 * Write all custom field values attached to given issue and custom field. Multi-valued custom fields use ',' as
 * separator.
 */
private void writeCustomFieldData(final int issue, final CustomFieldEditor customField, final Writer writer, final Format df) throws IOException {
	final int customFieldId = customField.getId();

	// Write the custom field data
	boolean first = true;
	moveToIssueAndCustomField(issue, customFieldId);
	boolean stringData = false;
	while (issueAndCustomFieldsCursor < customFieldValues.size() && customFieldValues.get(issueAndCustomFieldsCursor).getIssue() == issue
			&& customFieldValues.get(issueAndCustomFieldsCursor).getCustomField() == customFieldId) {
		// Custom field value has been found
		final CustomFieldValue customFieldValue = customFieldValues.get(issueAndCustomFieldsCursor);
		if (!first) {
			// Multi-valued custom field, append the value
			writer.append(',');
		}
		final Object value = customField.getEditor().getValue(customField, customFieldValue);
		if (value == null) {
			// Broken reference has been found, report it
			writer.append("#INVALID");
			log.warn("Broken reference for project '{}'[{}], issue [{}], custom field '{}'[{}], value '{}'",
					slaComputations.getProject().getName(), slaComputations.getJira(), issue, customField.getName(), customField.getId(),
					customFieldValue.getStringValue());
		} else if (value instanceof Date) {
			// Simple date, no escape
			writer.append(df.format(value));
		} else if (value instanceof Number) {
			// Simple number, no escape
			writer.append(StringUtils.removeEnd(value.toString().replace('.', ','), ",0"));
		} else {
			if (!stringData) {
				// Add the cell protection
				writer.append('\"');
				stringData = true;
			}
			// Write the value escaping the protection chars
			writer.append(value.toString().replace("\"", "\"\"").replace(';', ','));
		}
		issueAndCustomFieldsCursor++;
		first = false;
	}

	// Close the cell protection
	if (stringData) {
		writer.append('\"');
	}
}
 
Example 17
Project: r8   File: MemberNaming.java   Source Code and License Vote up 4 votes
@Override
void write(Writer writer) throws IOException {
  writer.append(type);
  writer.append(' ');
  writer.append(name);
}
 
Example 18
Project: csap-core   File: SourceControlManager.java   Source Code and License Vote up 4 votes
public void pullGitUpdate (	String scmUserid, String encodedPass, File sourceLocation,
							Writer outputWriter )
		throws Exception {

	String message = "\n\n *** Updating existing branch on git repository: "
			+ sourceLocation.getAbsolutePath()
			+ "\n Optional: use service clean to delete build location to force a new clone on new branch to be created.";

	logger.info( "{}", message );
	outputWriter.append( "\n" + message );
	outputWriter.flush();

	FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
	repositoryBuilder.findGitDir( sourceLocation );
	File gitLocation = repositoryBuilder.getGitDir();
	ObjectId oldHead = null;
	try (Repository repository = repositoryBuilder.setWorkTree( gitLocation ).build()) {
		oldHead = repository.resolve( "HEAD^{tree}" );
	}
	try (Git git = Git.open( gitLocation )) {

		// FetchCommand fetchCommand = git.fetch();
		PullCommand pullCommand = git.pull();

		if ( scmUserid.length() > 0 ) {
			pullCommand.setCredentialsProvider(
				new UsernamePasswordCredentialsProvider(
					scmUserid,
					encryptor.decrypt( encodedPass ) ) );
		}
		pullCommand.setProgressMonitor( gitMonitor( outputWriter ) );

		PullResult result = pullCommand.call();
		logger.info( "merge results: {}", result.getMergeResult() );
		outputWriter.append( "\n" + result.getMergeResult() + "\n\n Updated files:" );
		outputWriter.flush();

		printGitModifications( gitLocation, outputWriter, repositoryBuilder, oldHead, git );
		// ResetCommand command = git.reset() ;
		// command.setP
		// command.setMode( ResetType.HARD ).call() ;
	}

	// catch (Exception e) {
	// logger.error( "Failed to complete pull and diff of repository: {}",
	// csapApp.getCsapFilteredStackTrace( e ) );
	// isSuccessful = false;
	// }

	logger.info( "git sync complete" );
	outputWriter.append( "\n\n ================= git sync complete =============\n\n" );
	outputWriter.flush();
	return;
}
 
Example 19
Project: csap-core   File: SourceControlManager.java   Source Code and License Vote up 4 votes
private void printGitModifications ( File gitLocation, Writer outputWriter, FileRepositoryBuilder builder, ObjectId oldHead, Git git ) {
	if ( oldHead == null ) {
		logger.warn( "unable to determine git pull delta" );
	} else {
		try (Repository repository = builder.setWorkTree( gitLocation ).build()) {
			// The {tree} will return the underlying tree-id instead of
			// the
			// commit-id itself!
			// For a description of what the carets do see e.g.
			// http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde
			// This means we are selecting the parent of the parent of
			// the
			// parent of the parent of current HEAD and
			// take the tree-ish of it
			// ObjectId oldHead = repository.resolve( "HEAD^^^^{tree}"
			// );
			ObjectId head = repository.resolve( "HEAD^{tree}" );

			// System.out.println( "Printing diff between tree: " +
			// oldHead + " and " + head );

			// prepare the two iterators to compute the diff between
			try (ObjectReader reader = repository.newObjectReader()) {
				CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
				oldTreeIter.reset( reader, oldHead );
				CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
				newTreeIter.reset( reader, head );

				// finally get the list of changed files
				List<DiffEntry> diffs = git.diff()
					.setNewTree( newTreeIter )
					.setOldTree( oldTreeIter )
					.call();
				for ( DiffEntry entry : diffs ) {
					outputWriter.append( "\n *** " + entry );
					// System.out.println( "Entry: " + entry );
				}

			}
		} catch (Exception e) {
			logger.warn( "Unable to determine git delta: {}",
				CSAP.getCsapFilteredStackTrace( e ) );
		}
	}
}
 
Example 20
Project: NoMoreOversleeps   File: WebTemplate.java   Source Code and License Vote up 4 votes
public static final void renderTemplate(String template, HttpServletResponse response, Object model, Writer writer) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, TemplateException, IOException
{
	StringWriter writer_ = new StringWriter();
	PARSER.getTemplate(template).process(model, writer_);
	writer.append(writer_.toString());
}