java.io.Writer Java Examples

The following examples show how to use java.io.Writer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavapTask.java    From openjdk-8 with GNU General Public License v2.0 8 votes vote down vote up
private static PrintWriter getPrintWriterForWriter(Writer w) {
    if (w == null)
        return getPrintWriterForStream(null);
    else if (w instanceof PrintWriter)
        return (PrintWriter) w;
    else
        return new PrintWriter(w, true);
}
 
Example #2
Source File: AtoZListFormatter.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private void addRows(Writer writer, List listLeft, List listRight)
		throws IOException
{
	Iterator leftIt = listLeft != null ? listLeft.iterator()
			: new EmptyIterator();
	Iterator rightIt = listRight != null ? listRight.iterator()
			: new EmptyIterator();

	while (leftIt.hasNext() || rightIt.hasNext())
	{
		String leftName = (String) (leftIt != null && leftIt.hasNext() ? leftIt
				.next()
				: null);
		String rightName = (String) (rightIt != null && rightIt.hasNext() ? rightIt
				.next()
				: null);
		insertRow(writer, leftName, rightName, false);
	}
}
 
Example #3
Source File: ClobTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Transfer data from a source Reader to a destination Writer.
 *
 * @param source source data
 * @param dest destination to write to
 * @param tz buffer size in number of characters. Must be 1 or greater.
 * @return Number of characters read from the source data. This should equal the
 *      number of characters written to the destination.
 */
private int transferData(Reader source, Writer dest, int tz)
        throws IOException {
    if (tz < 1) {
        throw new IllegalArgumentException(
            "Buffer size must be 1 or greater: " + tz);
    }
    BufferedReader in = new BufferedReader(source);
    BufferedWriter out = new BufferedWriter(dest, tz);
    char[] bridge = new char[tz];
    int total = 0;
    int read;
    while ((read = in.read(bridge, 0, tz)) != -1) {
        out.write(bridge, 0, read);
        total += read;
    }
    in.close();
    // Don't close the stream, in case it will be written to again.
    out.flush();
    return total;
}
 
Example #4
Source File: BaseStartElement.java    From woodstox with Apache License 2.0 6 votes vote down vote up
@Override
public void writeAsEncodedUnicode(Writer w)
    throws XMLStreamException
{
    try {
        w.write('<');
        String prefix = mName.getPrefix();
        if (prefix != null && prefix.length() > 0) {
            w.write(prefix);
            w.write(':');
        }
        w.write(mName.getLocalPart());

        // Base class can output namespaces and attributes:
        outputNsAndAttr(w);

        w.write('>');
    } catch (IOException ie) {
        throw new WstxIOException(ie);
    }
}
 
Example #5
Source File: OracleLobHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setClobAsCharacterStream(
		PreparedStatement ps, int paramIndex, final Reader characterStream, int contentLength)
	throws SQLException {

	if (characterStream != null) {
		Clob clob = (Clob) createLob(ps, true, new LobCallback() {
			@Override
			public void populateLob(Object lob) throws Exception {
				Method methodToInvoke = lob.getClass().getMethod("getCharacterOutputStream", (Class[]) null);
				Writer writer = (Writer) methodToInvoke.invoke(lob, (Object[]) null);
				FileCopyUtils.copy(characterStream, writer);
			}
		});
		ps.setClob(paramIndex, clob);
		if (logger.isDebugEnabled()) {
			logger.debug("Set character stream for Oracle CLOB with length " + clob.length());
		}
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
		logger.debug("Set Oracle CLOB to null");
	}
}
 
Example #6
Source File: CejshBuilder.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
File writeProperties(File packageFolder, int articleCount) throws IOException, FileNotFoundException {
    File propertiesFile = new File(packageFolder, IMPORT_PROPERTIES_FILENAME);
    Properties properties = new Properties();
    gcalendar.setTimeInMillis(System.currentTimeMillis());
    String importDate = DatatypeConverter.printDateTime(gcalendar);
    properties.setProperty(PROP_IMPORT_INFODATE, importDate);
    properties.setProperty(PROP_IMPORT_OBJECTS, String.valueOf(articleCount));
    properties.setProperty(PROP_IMPORT_CONTENT_FILES, "0");
    properties.setProperty(PROP_IMPORT_BWMETA_FILES, "1");
    Writer propsWriter = new NoCommentsWriter(new OutputStreamWriter(new FileOutputStream(propertiesFile), Charsets.UTF_8));
    try {
        properties.store(propsWriter, null);
        return propertiesFile;
    } finally {
        propsWriter.close();
    }
}
 
Example #7
Source File: ToStream.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 *   Report an element type declaration.
 *
 *   <p>The content model will consist of the string "EMPTY", the
 *   string "ANY", or a parenthesised group, optionally followed
 *   by an occurrence indicator.  The model will be normalized so
 *   that all whitespace is removed,and will include the enclosing
 *   parentheses.</p>
 *
 *   @param name The element type name.
 *   @param model The content model as a normalized string.
 *   @exception SAXException The application may raise an exception.
 */
public void elementDecl(String name, String model) throws SAXException
{
    // Do not inline external DTD
    if (m_inExternalDTD)
        return;
    try
    {
        final java.io.Writer writer = m_writer;
        DTDprolog();

        writer.write("<!ELEMENT ");
        writer.write(name);
        writer.write(' ');
        writer.write(model);
        writer.write('>');
        writer.write(m_lineSep, 0, m_lineSepLen);
    }
    catch (IOException e)
    {
        throw new SAXException(e);
    }

}
 
Example #8
Source File: GenerateElementsIndex.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void generateSimpleElementDescriptors(Writer out, Collection<String> tagNames, String type) throws IOException {
    out.write("\n//" + type + " elements:\n//-----------------------\n\n");
    for(String tagName : tagNames) {
        out.write(ElementDescriptor.elementName2EnumName(tagName));
        out.write("(\n");
        out.write("\tHtmlTagType." + type + ",\n");
        out.write("\tnew Link(\"");
        out.write(tagName);
        out.write("\", null),\n");
        out.write("\tnull,\n");
        out.write("\tEnumSet.of(ContentType.FLOW, ContentType.PHRASING, ContentType.EMBEDDED),\n");
        out.write("\tEnumSet.noneOf(FormAssociatedElementsCategory.class),\n");
        out.write("\tEnumSet.noneOf(ContentType.class),\n");
        out.write("\tnew String[]{},\n");
        out.write("\tEnumSet.noneOf(ContentType.class),\n");
        out.write("\tnew String[]{},\n");
        out.write("\tEnumSet.noneOf(Attribute.class),\n");
        out.write("\tnull\n");
        out.write("),\n");
    }
}
 
Example #9
Source File: MetricsListTest.java    From prometheus-hystrix with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteNiceMetricsOutput() throws IOException {
    // given
    HystrixPrometheusMetricsPublisher.builder().shouldExportDeprecatedMetrics(false).buildAndRegister();
    TestHystrixCommand command = new TestHystrixCommand("any");

    // when
    command.execute();

    // then
    Writer writer = new FileWriter("target/sample.txt");
    try {
        TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
        writer.flush();
    } finally {
        writer.close();
    }
}
 
Example #10
Source File: JsonEscape.java    From unbescape with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 *   Perform a JSON <strong>unescape</strong> operation on a <tt>char[]</tt> input.
 * </p>
 * <p>
 *   No additional configuration arguments are required. Unescape operations
 *   will always perform <em>complete</em> JSON unescape of SECs and u-based escapes.
 * </p>
 * <p>
 *   This method is <strong>thread-safe</strong>.
 * </p>
 *
 * @param text the <tt>char[]</tt> to be unescaped.
 * @param offset the position in <tt>text</tt> at which the unescape operation should start.
 * @param len the number of characters in <tt>text</tt> that should be unescaped.
 * @param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
 *               be written at all to this writer if input is <tt>null</tt>.
 * @throws IOException if an input/output exception occurs
 */
public static void unescapeJson(final char[] text, final int offset, final int len, final Writer writer)
                                throws IOException {

    if (writer == null) {
        throw new IllegalArgumentException("Argument 'writer' cannot be null");
    }

    final int textLen = (text == null? 0 : text.length);

    if (offset < 0 || offset > textLen) {
        throw new IllegalArgumentException(
                "Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
    }

    if (len < 0 || (offset + len) > textLen) {
        throw new IllegalArgumentException(
                "Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
    }

    JsonEscapeUtil.unescape(text, offset, len, writer);

}
 
Example #11
Source File: RandomDNA.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Creates a random reference and writes it in FASTA format into a {@link Writer}.
 * @param out the output writer.
 * @param dict the dictionary indicating the number of contigs and their lengths.
 * @param basesPerLine number of base to print in each line of the output FASTA file.
 *
 * @throws IOException if such an exception was thrown while accessing and writing into the temporal file.
 * @throws IllegalArgumentException if {@code dict} is {@code null}, or {@code out } is {@code null}
 *    or {@code basesPerLine} is 0 or negative.
 */
public void nextFasta(final Writer out, final SAMSequenceDictionary dict, final int basesPerLine)
        throws IOException {
    Utils.nonNull(out);
    Utils.nonNull(dict);
    ParamUtils.isPositive(basesPerLine, "number of base per line must be strictly positive: " + basesPerLine);
    final byte[] buffer = new byte[basesPerLine];
    final String lineSeparator = System.lineSeparator();
    for (final SAMSequenceRecord sequence : dict.getSequences()) {
        int pendingBases = sequence.getSequenceLength();
        out.append(">").append(sequence.getSequenceName()).append(lineSeparator);
        while (pendingBases > 0) {
            final int lineLength = pendingBases < basesPerLine ? pendingBases : basesPerLine;
            nextBases(buffer, 0, lineLength);
            out.append(new String(buffer, 0, lineLength)).append(lineSeparator);
            pendingBases -= lineLength;
        }
    }
}
 
Example #12
Source File: HTMLMaker.java    From neoprofiler with Apache License 2.0 5 votes vote down vote up
public void html(DBProfile profile, Writer writer) throws IOException {
	VelocityEngine ve = new VelocityEngine();
       
	ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); 
	ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
	
	ve.init();
       
	Template t = null;
	
	if(ve.resourceExists("/template.html"))
		t = ve.getTemplate("/template.html");
	else {
		try { 
			t = ve.getTemplate("src/main/resources/template.html");				
		} catch(Exception exc) { 
			System.err.println("The application could not find a needed HTML template.");
			System.err.println("This is an unusual problem; please report it as an issue, and provide details of your configuration.");
			throw new RuntimeException("Could not find HTML template as resource.");
		}
	}
	
       VelocityContext context = new VelocityContext();

       StringWriter markdownContent = new StringWriter();
       
       // Write markdown content....
       new MarkdownMaker().markdown(profile, markdownContent);
       
       context.put("title", profile.getName());
       context.put("markdown", markdownContent.getBuffer().toString());
       context.put("links", generateGraph(profile)); 
       //context.put("d3graph", d3graph.toString());

       // Dump the contents of the template merged with the context.  That's it!
       t.merge(context, writer);
}
 
Example #13
Source File: Formatter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Reformat a block of code.
* @param doc document to work with
* @param startOffset offset at which the formatting starts
* @param endOffset offset at which the formatting ends
* @return length of the reformatted code
*/
public int reformat(BaseDocument doc, int startOffset, int endOffset)
throws BadLocationException {
    LegacyFormattersProvider.pushFormattingContextDocument(doc);
    try {
        try {
            CharArrayWriter cw = new CharArrayWriter();
            Writer w = createWriter(doc, startOffset, cw);
            String originalString = doc.getText(startOffset, endOffset - startOffset);
            w.write(originalString);
            w.close();
            String out = new String(cw.toCharArray());
            if(!out.equals(originalString)){
                doc.remove(startOffset, endOffset - startOffset);
                doc.insertString(startOffset, out, null);
                return out.length();
            }else{
                //nothing changed
                return 0;
            }
        } catch (IOException e) {
            Utilities.annotateLoggable(e);
            return 0;
        }
    } finally {
        LegacyFormattersProvider.popFormattingContextDocument(doc);
    }
}
 
Example #14
Source File: SxmpWriter.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
static private void writeErrorElement(Writer out, Response response) throws IOException {
    out.write("  <error code=\"");
    out.write(response.getErrorCode().toString());
    out.write("\" message=\"");
    out.write(StringUtil.escapeXml(response.getErrorMessage()));
    out.write("\"/>\n");
}
 
Example #15
Source File: AbstractValidationFormatterWriterTest.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testTwtsMissingSide() throws Exception {
    Writer writer = new StringWriter();
    TableFormatterConfig config = new TableFormatterConfig(Locale.getDefault(), ';', "inv", true, true);
    try (ValidationWriter twtsWriter = getTwtsValidationFormatterCsvWriter(config, writer, true, false)) {
        twtsWriter.write(twtId, Float.NaN, Float.NaN, Float.NaN, rho, rhoPreviousStep, rhoNextStep, tapPosition,
                         lowTapPosition, highTapPosition, twtTargetV, null, Float.NaN, false, false, true);
        assertEquals(getTwtsMissingSideContent(), writer.toString().trim());
    }
}
 
Example #16
Source File: GridJrxmlResult.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void execute( ActionInvocation invocation )
    throws Exception
{
    // ---------------------------------------------------------------------
    // Get grid
    // ---------------------------------------------------------------------

    Grid _grid = (Grid) invocation.getStack().findValue( "grid" );
    
    grid = _grid != null ? _grid : grid; 

    Map<Object, Object> _params = (Map<Object, Object>) invocation.getStack().findValue( "params" );

    params = _params != null ? _params : params;
    
    // ---------------------------------------------------------------------
    // Configure response
    // ---------------------------------------------------------------------

    HttpServletResponse response = ServletActionContext.getResponse();
    
    Writer writer = response.getWriter();

    String filename = CodecUtils.filenameEncode( StringUtils.defaultIfEmpty( grid.getTitle(), DEFAULT_FILENAME ) ) + ".jrxml";
    
    ContextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_XML, true, filename, true );
    
    // ---------------------------------------------------------------------
    // Write jrxml based on Velocity template
    // ---------------------------------------------------------------------

    GridUtils.toJrxml( grid, params, writer );
}
 
Example #17
Source File: XMLStreamWriterImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void setOutputUsingWriter(Writer writer)
   throws IOException
{
    fWriter = writer;

    if (writer instanceof OutputStreamWriter) {
        String charset = ((OutputStreamWriter) writer).getEncoding();
        if (charset != null && !charset.equalsIgnoreCase("utf-8")) {
            fEncoder = Charset.forName(charset).newEncoder();
        }
    }
}
 
Example #18
Source File: IOUtils.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
/**
 * write.
 *
 * @param reader     Reader.
 * @param writer     Writer.
 * @param bufferSize buffer size.
 * @return count.
 * @throws IOException
 */
public static long write(Reader reader, Writer writer, int bufferSize) throws IOException {
    int read;
    long total = 0;
    char[] buf = new char[BUFFER_SIZE];
    while ((read = reader.read(buf)) != -1) {
        writer.write(buf, 0, read);
        total += read;
    }
    return total;
}
 
Example #19
Source File: IssMasterSerializer.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void doSerialize(Object obj, Writer writer, XmlRpcSerializer serializer)
        throws XmlRpcException, IOException {
    SerializerHelper helper = new SerializerHelper(serializer);

    IssMaster master = (IssMaster) obj;
    helper.add("id", master.getId());
    helper.add("label", master.getLabel());
    helper.add("caCert", master.getCaCert());
    helper.add("isCurrentMaster", master.isDefaultMaster());
    helper.writeTo(writer);
}
 
Example #20
Source File: ToStream.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Report an attribute type declaration.
 *
 * <p>Only the effective (first) declaration for an attribute will
 * be reported.  The type will be one of the strings "CDATA",
 * "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY",
 * "ENTITIES", or "NOTATION", or a parenthesized token group with
 * the separator "|" and all whitespace removed.</p>
 *
 * @param eName The name of the associated element.
 * @param aName The name of the attribute.
 * @param type A string representing the attribute type.
 * @param valueDefault A string representing the attribute default
 *        ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if
 *        none of these applies.
 * @param value A string representing the attribute's default value,
 *        or null if there is none.
 * @exception SAXException The application may raise an exception.
 */
public void attributeDecl(
    String eName,
    String aName,
    String type,
    String valueDefault,
    String value)
    throws SAXException
{
    // Do not inline external DTD
    if (m_inExternalDTD)
        return;
    try
    {
        final java.io.Writer writer = m_writer;
        DTDprolog();

        writer.write("<!ATTLIST ");
        writer.write(eName);
        writer.write(' ');

        writer.write(aName);
        writer.write(' ');
        writer.write(type);
        if (valueDefault != null)
        {
            writer.write(' ');
            writer.write(valueDefault);
        }

        //writer.write(" ");
        //writer.write(value);
        writer.write('>');
        writer.write(m_lineSep, 0, m_lineSepLen);
    }
    catch (IOException e)
    {
        throw new SAXException(e);
    }
}
 
Example #21
Source File: XmlUtil.java    From revapi with Apache License 2.0 5 votes vote down vote up
static void toIndentedString(PlexusConfiguration xml, int indentationSize, int currentDepth, Writer wrt)
        throws IOException {

    indent(indentationSize, currentDepth, wrt);

    boolean hasChildren = xml.getChildCount() > 0;
    boolean hasContent = xml.getValue() != null && !xml.getValue().isEmpty();
    wrt.write('<');
    wrt.write(xml.getName());
    if (!hasChildren && !hasContent) {
        wrt.write("/>");
    } else {
        wrt.write('>');
        if (hasChildren) {
            wrt.write('\n');
            for (PlexusConfiguration c : xml.getChildren()) {
                toIndentedString(c, indentationSize, currentDepth + 1, wrt);
                wrt.append('\n');
            }

            if (!hasContent) {
                indent(indentationSize, currentDepth, wrt);
            }
        }

        if (hasContent) {
            escaped(wrt, xml.getValue());
        }

        wrt.write("</");
        wrt.write(xml.getName());
        wrt.write('>');
    }
}
 
Example #22
Source File: WSDLUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void writeWSDL(Definition def, Writer outputWriter)
    throws WSDLException, IOException {
    WSDLCorbaFactory wsdlfactory = new WSDLCorbaFactoryImpl();
    WSDLWriter writer = wsdlfactory.newWSDLWriter();
    writer.writeWSDL(def, outputWriter);

    outputWriter.flush();
    outputWriter.close();
}
 
Example #23
Source File: FDFField.java    From PdfBox-Android with Apache License 2.0 5 votes vote down vote up
/**
 * This will write this element as an XML document.
 *
 * @param output The stream to write the xml to.
 *
 * @throws IOException If there is an error writing the XML.
 */
public void writeXML( Writer output ) throws IOException
{
    output.write("<field name=\"" + getPartialFieldName() + "\">\n");
    Object value = getValue();
    if( value != null )
    {
        if(value instanceof COSString)
        {
            output.write("<value>" + escapeXML(((COSString) value).getString()) + "</value>\n");
        }
        else if(value instanceof COSStream)
        {
            output.write("<value>" + escapeXML(((COSStream) value).getString()) + "</value>\n");
        }
    }
    String rt = getRichText();
    if( rt != null )
    {
        output.write("<value-richtext>" + escapeXML(rt) + "</value-richtext>\n");
    }
    List<FDFField> kids = getKids();
    if( kids != null )
    {
        for (FDFField kid : kids)
        {
            kid.writeXML(output);
        }
    }
    output.write( "</field>\n");
}
 
Example #24
Source File: Taxonomy.java    From rtg-tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Writes the current taxonomy to the given <code>writer</code> as a tab separated value file.
 * @param writer where to write to
 * @throws IOException if an error occurs while writing.
 */
public void write(Writer writer) throws IOException {
  final LineWriter lw = new LineWriter(writer);

  lw.writeln(VERSION_HEADER);
  lw.writeln("#taxID" + TAB + "parentID" + TAB + "rank" + TAB + "name");

  final TaxonNode root = getRoot();
  if (root != null) {
    for (final TaxonNode node : root.depthFirstTraversal()) {
      lw.writeln(node.getId() + TAB + node.getParentId() + TAB + node.getRank() + TAB + node.getName());
    }
  }
}
 
Example #25
Source File: GeneratorsValidation.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
public boolean checkGenerators(String id, double p, double q, double v, double targetP, double targetQ, double targetV,
                                      boolean voltageRegulatorOn, double minP, double maxP, double minQ, double maxQ, boolean connected,
                                      boolean mainComponent, ValidationConfig config, Writer writer) {
    Objects.requireNonNull(id);
    Objects.requireNonNull(config);
    Objects.requireNonNull(writer);

    try (ValidationWriter generatorsWriter = ValidationUtils.createValidationWriter(id, config, writer, ValidationType.GENERATORS)) {
        return checkGenerators(id, p, q, v, targetP, targetQ, targetV, voltageRegulatorOn, minP, maxP, minQ, maxQ, connected, mainComponent, config,
                generatorsWriter, new BalanceTypeGuesser());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #26
Source File: AtoZListFormatter.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private void insertRow(Writer writer, String left, String right, boolean odd)
		throws IOException
{
	writer.write("<tr><td>");
	if (left != null)
	{
		writer.write(left);
	}
	writer.write("</td><td> </td><td>");
	if (right != null)
	{
		writer.write(right);
	}
	writer.write("</td></tr>");
}
 
Example #27
Source File: SetupTemplateUtils.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static void createPom(Map<String, String> context, File pomFile) throws MojoExecutionException {
    try {

        Template temp = cfg.getTemplate("templates/pom-template.ftl");
        Writer out = new FileWriter(pomFile);
        temp.process(context, out);
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to generate pom.xml", e);
    }
}
 
Example #28
Source File: ElementOption.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void write(Writer writer) throws IOException {
    writer.write('<');
    writer.write(name);
    writer.write('>');
    if (option != null) {
        option.write(writer);
    } else {
        writer.write(StringUtil.xmlEncode(value));
    }
    writer.write("</");
    writer.write(name);
    writer.write('>');
}
 
Example #29
Source File: TajoAdmin.java    From tajo with Apache License 2.0 5 votes vote down vote up
private void processDesc(Writer writer) throws ParseException, IOException,
    ServiceException, SQLException {

  List<BriefQueryInfo> queryList = tajoClient.getRunningQueryList();
  SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
  int id = 1;
  for (BriefQueryInfo queryInfo : queryList) {
      String queryId = String.format("q_%s_%04d",
                                     queryInfo.getQueryId().getId(),
                                     queryInfo.getQueryId().getSeq());

      writer.write("Id: " + id);
      writer.write("\n");
      id++;
      writer.write("Query Id: " + queryId);
      writer.write("\n");
      writer.write("Started Time: " + df.format(queryInfo.getStartTime()));
      writer.write("\n");

      writer.write("Query State: " + queryInfo.getState().name());
      writer.write("\n");
      long end = queryInfo.getFinishTime();
      long start = queryInfo.getStartTime();
      String executionTime = decimalF.format((end-start) / 1000) + " sec";
      if (TajoClientUtil.isQueryComplete(queryInfo.getState())) {
        writer.write("Finished Time: " + df.format(queryInfo.getFinishTime()));
        writer.write("\n");
      }
      writer.write("Execution Time: " + executionTime);
      writer.write("\n");
      writer.write("Query Progress: " + queryInfo.getProgress());
      writer.write("\n");
      writer.write("Query Statement:");
      writer.write("\n");
      writer.write(queryInfo.getQuery());
      writer.write("\n");
      writer.write("\n");
  }
}
 
Example #30
Source File: Processor.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element e : roundEnv.getElementsAnnotatedWith(Gen.class)) {
        Gen gen = e.getAnnotation(Gen.class);
        try {
            JavaFileObject source = processingEnv.getFiler().createSourceFile(gen.fileName());

            try (Writer out = source.openWriter()) {
                out.write(gen.content());
            }
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    TypeElement generated = processingEnv.getElementUtils().getTypeElement("Generated");

    if (generated != null) {
        Check check = ElementFilter.methodsIn(generated.getEnclosedElements()).get(0).getAnnotation(Check.class);

        checkCorrectException(check::classValue, "java.lang.Class<java.lang.String>");
        checkCorrectException(check::intConstValue, "boolean");
        checkCorrectException(check::enumValue, "java.lang.String");
        checkCorrectException(check::incorrectAnnotationValue, "java.lang.Deprecated");
        checkCorrectException(check::incorrectArrayValue, "<any>");
        checkCorrectException(check::incorrectClassValue, "<any>");

        seenGenerated = true;
    }

    if (roundEnv.processingOver() && !seenGenerated) {
        Assert.error("Did not see the generated class!");
    }

    return true;
}