org.junit.jupiter.api.TestFactory#java.io.Writer源码实例Demo

下面列出了org.junit.jupiter.api.TestFactory#java.io.Writer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-8   文件: JavapTask.java
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);
}
 
源代码2 项目: unbescape   文件: JsonEscape.java
/**
 * <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);

}
 
源代码3 项目: sakai   文件: AtoZListFormatter.java
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);
	}
}
 
源代码4 项目: woodstox   文件: BaseStartElement.java
@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);
    }
}
 
源代码5 项目: netbeans   文件: GenerateElementsIndex.java
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");
    }
}
 
源代码6 项目: gatk   文件: RandomDNA.java
/**
 * 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;
        }
    }
}
 
源代码7 项目: lams   文件: OracleLobHandler.java
@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");
	}
}
 
源代码8 项目: spliceengine   文件: ClobTest.java
/**
 * 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;
}
 
源代码9 项目: proarc   文件: CejshBuilder.java
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();
    }
}
 
源代码10 项目: prometheus-hystrix   文件: MetricsListTest.java
@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();
    }
}
 
源代码11 项目: jdk8u60   文件: ToStream.java
/**
 *   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);
    }

}
 
源代码12 项目: groovy   文件: EncodingGroovyMethods.java
/**
 * Produces a Writable that writes the hex encoding of the byte[]. Calling
 * toString() on this Writable returns the hex encoding as a String. The hex
 * encoding includes two characters for each byte and all letters are lower case.
 *
 * @param data byte array to be encoded
 * @return object which will write the hex encoding of the byte array
 * @see Integer#toHexString(int)
 */
public static Writable encodeHex(final byte[] data) {
    return new Writable() {
        public Writer writeTo(Writer out) throws IOException {
            for (byte datum : data) {
                // convert byte into unsigned hex string
                String hexString = Integer.toHexString(datum & 0xFF);

                // add leading zero if the length of the string is one
                if (hexString.length() < 2) {
                    out.write("0");
                }

                // write hex string to writer
                out.write(hexString);
            }
            return out;
        }

        public String toString() {
            Writer buffer = new StringBuilderWriter();

            try {
                writeTo(buffer);
            } catch (IOException e) {
                throw new StringWriterIOException(e);
            }

            return buffer.toString();
        }
    };
}
 
源代码13 项目: annotation-tools   文件: IndexFileWriter.java
private IndexFileWriter(AScene scene,
        Writer out) throws DefException {
    this.scene = scene;
    pw = new PrintWriter(out);
    write();
    pw.flush();
}
 
源代码14 项目: dubbo-2.6.5   文件: IOUtils.java
/**
 * 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;
}
 
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void omitFields() throws Exception {
	Map omittedFieldsMap = Collections.singletonMap(Flight.class, "flightNumber");
	marshaller.setOmittedFields(omittedFieldsMap);
	Writer writer = new StringWriter();
	marshaller.marshal(flight, new StreamResult(writer));
	assertXpathNotExists("/flight/flightNumber", writer.toString());
}
 
源代码16 项目: jdk8u60   文件: IndentingWriter.java
/**
 * Create a new IndentingWriter that writes indented text to the
 * given Writer and uses the supplied indent step.
 */
public IndentingWriter(Writer out, int step) {
    this(out);

    if (indentStep < 0)
        throw new IllegalArgumentException("negative indent step");

    indentStep = step;
}
 
源代码17 项目: hottub   文件: EncodingInfo.java
/**
 * Returns a writer for this encoding based on
 * an output stream.
 *
 * @return A suitable writer
 * @exception UnsupportedEncodingException There is no convertor
 *  to support this encoding
 */
public Writer getWriter(OutputStream output)
    throws UnsupportedEncodingException {
    // this should always be true!
    if (javaName != null)
        return new OutputStreamWriter(output, javaName);
    javaName = EncodingMap.getIANA2JavaMapping(ianaName);
    if(javaName == null)
        // use UTF-8 as preferred encoding
        return new OutputStreamWriter(output, "UTF8");
    return new OutputStreamWriter(output, javaName);
}
 
源代码18 项目: access2csv   文件: Driver.java
static int export(Database db, String tableName, Writer csv, boolean withHeader) throws IOException{
	Table table = db.getTable(tableName);
	String[] buffer = new String[table.getColumnCount()];
	CSVWriter writer = new CSVWriter(new BufferedWriter(csv));
	int rows = 0;
	try{
		if (withHeader) {
			int x = 0;
			for(Column col : table.getColumns()){
				buffer[x++] = col.getName();
			}
			writer.writeNext(buffer);
		}

		for(Row row : table){
			int i = 0;
			for (Object object : row.values()) {
				buffer[i++] = object == null ? null : object.toString();
			}
			writer.writeNext(buffer);
			rows++;
		}
	}finally{
		writer.close();
	}
	return rows;
}
 
源代码19 项目: live-chat-engine   文件: MockHttpServletResponse.java
@Override
public PrintWriter getWriter() throws UnsupportedEncodingException {
	if (!this.writerAccessAllowed) {
		throw new IllegalStateException("Writer access not allowed");
	}
	if (this.writer == null) {
		Writer targetWriter = (this.characterEncoding != null ?
				new OutputStreamWriter(this.content, this.characterEncoding) : new OutputStreamWriter(this.content));
		this.writer = new ResponsePrintWriter(targetWriter);
	}
	return this.writer;
}
 
源代码20 项目: gemfirexd-oss   文件: JSONObject.java
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) value).write(writer, indentFactor, indent);
    } else if (value instanceof Collection) {
        new JSONArray((Collection) 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;
}
 
源代码21 项目: J2ME-Loader   文件: TwoColumnOutput.java
/**
 * Appends a newline to the given buffer via the given writer, but
 * only if it isn't empty and doesn't already end with one.
 *
 * @param buf {@code non-null;} the buffer in question
 * @param out {@code non-null;} the writer to use
 */
private static void appendNewlineIfNecessary(StringBuffer buf,
                                             Writer out)
        throws IOException {
    int len = buf.length();

    if ((len != 0) && (buf.charAt(len - 1) != '\n')) {
        out.write('\n');
    }
}
 
源代码22 项目: cloudhopper-commons   文件: SxmpWriter.java
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");
}
 
源代码23 项目: cxf   文件: WSDLUtils.java
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();
}
 
源代码24 项目: PdfBox-Android   文件: FDFField.java
/**
 * 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");
}
 
源代码25 项目: powsybl-core   文件: GeneratorsValidation.java
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);
    }
}
 
源代码26 项目: sakai   文件: AtoZListFormatter.java
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>");
}
 
源代码27 项目: vertx-maven-plugin   文件: SetupTemplateUtils.java
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);
    }
}
 
源代码28 项目: tajo   文件: TajoAdmin.java
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");
  }
}
 
源代码29 项目: openjdk-jdk8u   文件: Processor.java
@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;
}
 
源代码30 项目: davmail   文件: ElementOption.java
/**
 * @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('>');
}