下面列出了java.io.Writer#write ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static private void writeReduceActionClasses(Grammar grammar, Writer out) throws IOException
{
for (int i = 0; i < grammar.rules.length; i++)
{
Production rule = grammar.rules[i];
if (rule.code == null)
continue;
out.write("\n\t/**");
out.write("\n\t * ");
out.write(rule.toString());
out.write("\n\t */");
out.write("\n\tfinal class Action");
out.write(String.valueOf(rule.id));
out.write(" extends Action {\n");
out.write("\t\t\t\tpublic Symbol reduce(Symbol[] _symbols, int offset) {\n");
writeReduceActionCode(rule, out);
out.write("\t\t\t\t}");
out.write("\n\t}\n");
}
}
/**
* {@inheritDoc}
*/
@Override
public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
int max = longest;
if (index + longest > input.length()) {
max = input.length() - index;
}
// descend so as to get a greedy algorithm
for (int i = max; i >= shortest; i--) {
final CharSequence subSeq = input.subSequence(index, index + i);
final CharSequence result = lookupMap.get(subSeq.toString());
if (result != null) {
out.write(result.toString());
return i;
}
}
return 0;
}
private void writeCertArray(Writer writer, Certificate[] certificates) throws IOException {
if (certificates == null) {
writer.write("-1\n");
return;
}
try {
writer.write(Integer.toString(certificates.length) + '\n');
for (Certificate certificate : certificates) {
byte[] bytes = certificate.getEncoded();
String line = Base64.encode(bytes);
writer.write(line + '\n');
}
} catch (CertificateEncodingException e) {
throw new IOException(e.getMessage());
}
}
public Writer appendTo(Writer writer) throws IOException
{
writer.write("{table}\n"); //$NON-NLS-1$
writer.write(Messages.getString("ApiDoc.14")); //$NON-NLS-1$
Iterator iterator = apiDocs.entrySet().iterator();
while (iterator.hasNext())
{
Map.Entry entry = (Map.Entry) iterator.next();
writer.write((String) entry.getKey());
ApiConverter converter = (ApiConverter) entry.getValue();
writer.write("|"); //$NON-NLS-1$
writer.write(converter.getBaseUrl());
writer.write("|"); //$NON-NLS-1$
writer.write(converter.getName());
writer.write("\n"); //$NON-NLS-1$
}
writer.write("{table}"); //$NON-NLS-1$
return writer;
}
/**
* write the read
*
* @param readBlock
* @param w
* @return number of reads written
* @throws java.io.IOException
*/
private static void write(IReadBlock readBlock, Writer w) throws IOException {
String header = readBlock.getReadHeader();
if (header != null) {
if (!header.startsWith(">"))
w.write(">");
w.write(header);
if (!header.endsWith("\n"))
w.write("\n");
} else
w.write(">null\n");
String sequence = readBlock.getReadSequence();
if (sequence != null) {
if (sequence.endsWith("\n\n")) {
w.write(sequence.substring(0, sequence.length() - 1));
} else {
w.write(sequence);
if (!sequence.endsWith("\n"))
w.write("\n");
}
} else
w.write("null\n");
}
/**
* export the tree
*
* @param viewer
* @param writer
* @param showInternalLabels
* @param showUnassignedLabels
* @param simplify
* @return number of nodes written
* @throws IOException
*/
public static int apply(ViewerBase viewer, Writer writer, boolean showInternalLabels, boolean showUnassignedLabels, boolean simplify) throws IOException {
final PhyloTree tree = viewer.getTree();
Node root = tree.getRoot();
if (root == null)
return 0;
NodeSet toUse = null;
if (viewer.getSelectedNodes().size() > 0) {
toUse = new NodeSet(tree);
visitNodesToUseRec(viewer, root, toUse);
while (!viewer.getSelected(root)) {
Node w = null;
for (Edge e = root.getFirstOutEdge(); e != null; e = root.getNextOutEdge(e)) {
if (toUse.contains(e.getTarget())) {
if (w == null)
w = e.getTarget();
else {
w = null;
break;
}
}
}
if (w != null) // there is exactly one node below the current root that should be used, move to it
root = w;
else
break;
}
}
final int countNodes = writeAsTreeRec(viewer, toUse, root, writer, showInternalLabels, showUnassignedLabels, simplify, 0);
writer.write(";\n");
return countNodes;
}
public static void json(Object obj, Writer writer, boolean writeClass) throws IOException
{
if( obj == null )
writer.write(NULL);
else
json(obj, new JSONWriter(writer), writeClass);
}
public void write(Object obj, boolean showType, Writer output) throws IOException
{
StringBuilder builder = (StringBuilder) obj;
output.write("\"value\":\"");
output.write(builder.toString());
output.write('"');
}
static final Writer writeValue(Writer writer, Object value,
int indentFactor, int indent) throws JSONException, IOException {
if (value == null || value.equals(null)) {
writer.write("null");
} else if (value instanceof JSONObject) {
((JSONObject) value).write(writer, indentFactor, indent);
} else if (value instanceof JSONArray) {
((JSONArray) value).write(writer, indentFactor, indent);
} else if (value instanceof Map) {
new JSONObject((Map<String, Object>) value).write(writer, indentFactor, indent);
} else if (value instanceof Collection) {
new JSONArray((Collection<Object>) value).write(writer, indentFactor,
indent);
} else if (value.getClass().isArray()) {
new JSONArray(value).write(writer, indentFactor, indent);
} else if (value instanceof Number) {
writer.write(numberToString((Number) value));
} else if (value instanceof Boolean) {
writer.write(value.toString());
} else if (value instanceof JSONString) {
Object o;
try {
o = ((JSONString) value).toJSONString();
} catch (Exception e) {
throw new JSONException(e);
}
writer.write(o != null ? o.toString() : quote(value.toString()));
} else {
quote(value.toString(), writer);
}
return writer;
}
/**
* Output getConnection method
*
* @param def definition
* @param out Writer
* @param indent space number
* @throws IOException ioException
*/
private void writeGetConnection(Definition def, Writer out, int indent) throws IOException
{
String connInterface = def.getMcfDefs().get(0).getConnInterfaceClass();
String cfInterface = def.getMcfDefs().get(0).getCfInterfaceClass();
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * GetConnection\n");
writeWithIndent(out, indent, " * @return " + connInterface);
writeEol(out);
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "private " + connInterface + " getConnection() throws Exception");
writeLeftCurlyBracket(out, indent);
writeWithIndent(out, indent + 1, "InitialContext context = new InitialContext();\n");
writeIndent(out, indent + 1);
out.write(cfInterface + " factory = (" + cfInterface +
")context.lookup(JNDI_NAME);\n");
writeIndent(out, indent + 1);
out.write(connInterface + " conn = factory.getConnection();\n");
writeWithIndent(out, indent + 1, "if (conn == null)");
writeLeftCurlyBracket(out, indent + 1);
writeIndent(out, indent + 2);
out.write("throw new RuntimeException(\"No connection\");");
writeRightCurlyBracket(out, indent + 1);
writeWithIndent(out, indent + 1, "return conn;");
writeRightCurlyBracket(out, indent);
}
@Override
public void write(Writer writer, Prerequisite prereq) throws PersistenceLayerException
{
checkValidOperator(prereq, operatorsHandled());
try
{
if (prereq.getOperator().equals(PrerequisiteOperator.LT))
{
writer.write('!');
}
writer.write("PRESKILLSIT:");
writer.write(prereq.isOverrideQualify() ? "Q:" : "");
writer.write("1,");
String cat = prereq.getCategoryName();
writer.write("SKILL=");
writer.write(cat);
writer.write(',');
writer.write(prereq.getKey());
if (prereq.getSubKey() != null)
{
writer.write(" (");
writer.write(prereq.getSubKey());
writer.write(')');
}
writer.write("=");
writer.write(prereq.getOperand());
}
catch (IOException e)
{
throw new PersistenceLayerException(e);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setStatus(HttpServletResponse.SC_OK);
String user = req.getRemoteUser();
String principal = (req.getUserPrincipal() != null) ? req.getUserPrincipal().getName() : null;
Writer writer = resp.getWriter();
writer.write(MessageFormat.format("You are: user[{0}] principal[{1}]\n", user, principal));
}
/**
* Output Reference method
*
* @param def definition
* @param out Writer
* @param indent space number
* @throws IOException ioException
*/
private void writeReference(Definition def, Writer out, int indent) throws IOException
{
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Get the Reference instance.\n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @return Reference instance\n");
writeWithIndent(out, indent, " * @exception NamingException Thrown if a reference can't be obtained\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "@Override\n");
writeWithIndent(out, indent, "public Reference getReference() throws NamingException");
writeLeftCurlyBracket(out, indent);
writeLogging(def, out, indent + 1, "trace", "getReference");
writeIndent(out, indent + 1);
out.write("return reference;");
writeRightCurlyBracket(out, indent);
writeEol(out);
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Set the Reference instance.\n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @param reference A Reference instance\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "@Override\n");
writeWithIndent(out, indent, "public void setReference(Reference reference)");
writeLeftCurlyBracket(out, indent);
writeLogging(def, out, indent + 1, "trace", "setReference", "reference");
writeIndent(out, indent + 1);
out.write("this.reference = reference;");
writeRightCurlyBracket(out, indent);
writeEol(out);
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @return The writer.
* @throws JSONException
*/
Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
int length = this.length();
writer.write('[');
if (length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, indent);
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
@RequestMapping("/{root}")
public void handle(@PathVariable("root") int root, @MatrixVariable(required=false, defaultValue="7") int q,
Writer writer) throws IOException {
assertEquals("Invalid path variable value", 42, root);
writer.write("test-" + root + "-" + q);
}
public void execute(Writer writer, MacroParameter params)
throws IllegalArgumentException, IOException
{
SpecializedRenderContext context = (SpecializedRenderContext) params
.getContext();
String useids = params.get("useids", 0); //$NON-NLS-1$
String siteId = context.getSiteId();
Collection groups = null;
Site site;
try
{
site = SiteService.getSite(siteId);
}
catch (IdUnusedException e)
{
throw new IllegalArgumentException(Messages.getString("SectionsMacro.5")+ siteId + " : "+e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
//Site can't be null because the not found would have thrown an exception
groups = site.getGroups();
for (Iterator is = groups.iterator(); is.hasNext();)
{
Group group = (Group) is.next();
String pageName = ""; //$NON-NLS-1$
if ("true".equals(useids)) //$NON-NLS-1$
{
pageName = group.getId() + "/Home"; //$NON-NLS-1$
}
else
{
pageName = group.getReference() + "/"; //$NON-NLS-1$
pageName += "section/" + group.getTitle() + "/Home"; //$NON-NLS-1$ //$NON-NLS-2$
}
writer.write("\n"); //$NON-NLS-1$
writer.write("* [ Section: "); //$NON-NLS-1$
writer.write(group.getTitle());
writer.write("|"); //$NON-NLS-1$
writer.write(pageName);
writer.write("]"); //$NON-NLS-1$
}
writer.write("\n"); //$NON-NLS-1$
return;
}
/**
* {@inheritDoc}
*/
@Override
public boolean write(Writer out, boolean atNewline) throws IOException {
out.write(rawHtmlContent);
return rawHtmlContent.endsWith(DocletConstants.NL);
}
/**
* This method handle byte order mark for charset that do not write it.
*
* @param charset charset (UTF 16 or 32 based)
* @param os output stream where to write BOM
* @throws java.io.IOException
*/
private void writeByteOrderMark(Charset charset, OutputStream os) throws IOException {
if (!UTF_16_CHARSETS.contains(charset.name()) && !UTF_32_CHARSETS.contains(charset.name())) {
return;
}
/*
* We need to use writer because encode methods in Charset don't work.
*/
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out, charset);
try {
writer.write('\uFFFD'); // NOI18N
} catch (IOException ex) {
LOGGER.log(Level.INFO, null, ex);
return;
} finally {
writer.close();
}
byte[] buffer = out.toByteArray();
if ((UTF_16_CHARSETS.contains(charset.name()) && buffer.length > 2) || (UTF_32_CHARSETS.contains(charset.name()) && buffer.length > 4)) {
// charset writes BOM
return;
}
if (UTF_16_CHARSETS.contains(charset.name())) {
if (buffer.length < 2) {
// don't know what to do
return;
}
if (buffer[0] == (byte) 0xFF && buffer[1] == (byte) 0xFD) {
// big endian
os.write(0xFE);
os.write(0xFF);
} else if (buffer[0] == (byte) 0xFD && buffer[1] == (byte) 0xFF) {
// little endian
os.write(0xFF);
os.write(0xFE);
}
} else if (UTF_32_CHARSETS.contains(charset.name())) {
if (buffer.length < 4) {
// don't know what to do
return;
}
if (buffer[0] == (byte) 0xFF && buffer[1] == (byte) 0xFD && buffer[2] == (byte) 0x00 && buffer[3] == (byte) 0x00) {
// big endian
os.write(0x00);
os.write(0x00);
os.write(0xFE);
os.write(0xFF);
} else if (buffer[0] == (byte) 0x00 && buffer[1] == (byte) 0x00 && buffer[2] == (byte) 0xFD && buffer[3] == (byte) 0xFF) {
// little endian
os.write(0xFF);
os.write(0xFE);
os.write(0x00);
os.write(0x00);
}
}
}
/**
* Copy chars from a large (over 2GB) <code>Reader</code> to a <code>Writer</code>.
* <p/>
* This method uses the provided buffer, so there is no need to use a
* <code>BufferedReader</code>.
* <p/>
*
* @param input the <code>Reader</code> to read from
* @param output the <code>Writer</code> to write to
* @param buffer the buffer to be used for the copy
* @return the number of characters copied
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 2.2
*/
public static long copyLarge(Reader input, Writer output, char[] buffer) throws IOException {
long count = 0;
int n;
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
/**
* Dumps the list and all its contents into a string. The list will be terminated by brackets,
* elements separated by komma, space. Elements itself will be dumped by recursive calls to the
* element specific method of the same name.
*
* @param stream is a stream opened and ready for writing. This can also be a string stream for
* efficient output.
* @exception IOException if something fishy happens to the stream.
*/
public void toString(Writer stream) throws IOException {
stream.write("[ ");
for (Iterator i = this.m_scalarList.iterator(); i.hasNext(); ) {
((Scalar) i.next()).toString(stream);
if (i.hasNext()) stream.write(", ");
}
stream.write(" ]");
}