Java Code Examples for java.io.Writer

The following are top voted examples for showing how to use java.io.Writer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: PDF2RDF   File: TitleExtractor.java   View source code 9 votes vote down vote up
private boolean process() throws IOException {
    boolean toReturn = false;
    PDFTextStripper stripper = new TitleExtractor();
    PDDocument document = null;

    try {
        document = PDDocument.load(new File(this.getFileNamePathWithExtension()));

        //((TitleExtractor) stripper).setFileNamePathWithExtension(this.getFileNamePathWithExtension());
        stripper.setSortByPosition(true);
        stripper.setStartPage(0);
        stripper.setEndPage(1);

        Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
        stripper.writeText(document, dummy);
        
        setTitle(((TitleExtractor) stripper).getTitle());

        toReturn = true;
    } finally {
        if (document != null) {
            document.close();
        }
    }
    return toReturn;
}
 
Example 2
Project: OpenJSharp   File: JNIWriter.java   View source code 7 votes vote down vote up
/** Emit a class file for a given class.
 *  @param c      The class from which a class file is generated.
 */
public FileObject write(ClassSymbol c)
    throws IOException
{
    String className = c.flatName().toString();
    FileObject outFile
        = fileManager.getFileForOutput(StandardLocation.NATIVE_HEADER_OUTPUT,
            "", className.replaceAll("[.$]", "_") + ".h", null);
    Writer out = outFile.openWriter();
    try {
        write(out, c);
        if (verbose)
            log.printVerbose("wrote.file", outFile);
        out.close();
        out = null;
    } finally {
        if (out != null) {
            // if we are propogating an exception, delete the file
            out.close();
            outFile.delete();
            outFile = null;
        }
    }
    return outFile; // may be null if write failed
}
 
Example 3
Project: OperatieBRP   File: AttributeChild.java   View source code 6 votes vote down vote up
/**
 * 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 4
Project: Backmemed   File: UserList.java   View source code 6 votes vote down vote up
public void writeChanges() throws IOException
{
    Collection<V> collection = this.values.values();
    String s = this.gson.toJson((Object)collection);
    BufferedWriter bufferedwriter = null;

    try
    {
        bufferedwriter = Files.newWriter(this.saveFile, Charsets.UTF_8);
        bufferedwriter.write(s);
    }
    finally
    {
        IOUtils.closeQuietly((Writer)bufferedwriter);
    }
}
 
Example 5
Project: openjdk-jdk10   File: XMLKit.java   View source code 6 votes vote down vote up
public static void writeCData(String val, Writer w) throws IOException {
    String begCData = "<![CDATA[";
    String endCData = "]]>";
    w.write(begCData);
    for (int vpos = 0, split;; vpos = split) {
        split = val.indexOf(endCData, vpos);
        if (split < 0) {
            w.write(val, vpos, val.length() - vpos);
            w.write(endCData);
            return;
        }
        split += 2; // bisect the "]]>" goo
        w.write(val, vpos, split - vpos);
        w.write(endCData);
        w.write(begCData);
    }
}
 
Example 6
Project: tbschedule-wed   File: ScheduleStrategyDataManager4ZK.java   View source code 6 votes vote down vote up
/**
 * 导入配置信息【目前支持baseTaskType和strategy数据】
 * 
 * @param config
 * @param writer
 * @param isUpdate
 * @throws Exception
 */
public void importConfig(String config, Writer writer, boolean isUpdate)
		throws Exception {
	ConfigNode configNode = gson.fromJson(config, ConfigNode.class);
	if (configNode != null) {
		String path = configNode.getRootPath() + "/"
				+ configNode.getConfigType();
		ZKTools.createPath(getZooKeeper(), path, CreateMode.PERSISTENT, zkManager.getAcl());
		String y_node = path + "/" + configNode.getName();
		if (getZooKeeper().exists(y_node, false) == null) {
			writer.append("<font color=\"red\">成功导入新配置信息\n</font>");
			getZooKeeper().create(y_node, configNode.getValue().getBytes(),
					zkManager.getAcl(), CreateMode.PERSISTENT);
		} else if (isUpdate) {
			writer.append("<font color=\"red\">该配置信息已经存在,并且强制更新了\n</font>");
			getZooKeeper().setData(y_node,
					configNode.getValue().getBytes(), -1);
		} else {
			writer.append("<font color=\"red\">该配置信息已经存在,如果需要更新,请配置强制更新\n</font>");
		}
	}
	writer.append(configNode.toString());
}
 
Example 7
Project: de.flapdoodle.solid   File: CoreFiltersTest.java   View source code 6 votes vote down vote up
@Test
public void testDate() throws ParseException, PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false)
            .defaultLocale(Locale.ENGLISH).build();

    String source = "{{ realDate | date('MM/dd/yyyy') }}{{ realDate | date(format) }}{{ stringDate | date('yyyy/MMMM/d','yyyy-MMMM-d') }}";

    PebbleTemplate template = pebble.getTemplate(source);
    Map<String, Object> context = new HashMap<>();
    DateFormat format = new SimpleDateFormat("yyyy-MMMM-d", Locale.ENGLISH);
    Date realDate = format.parse("2012-July-01");
    context.put("realDate", realDate);
    context.put("stringDate", format.format(realDate));
    context.put("format", "yyyy-MMMM-d");

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("07/01/20122012-July-12012/July/1", writer.toString());
}
 
Example 8
Project: de.flapdoodle.solid   File: LogicTest.java   View source code 6 votes vote down vote up
/**
 * Tests if the macro output SafeString concatenation is working.
 */
@Test
public void testMacroSafeStringConcatenation() throws PebbleException, IOException {

    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{% macro macro1() %}Bob{% endmacro %}\n"
                  + "{% macro macro2() %}Maria{% endmacro %}\n"
                  + "{% macro macro3() %}John{% endmacro %}\n"
                  + "{{ (macro1() + macro2() + macro3()) | lower }}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("bobmariajohn", writer.toString());

}
 
Example 9
Project: alfresco-repository   File: XMLTransferManifestWriter.java   View source code 6 votes vote down vote up
/**
 * Start the transfer manifest
 */
public void startTransferManifest(Writer writer) throws SAXException
{
    format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding("UTF-8");

    this.writer = new XMLWriter(writer, format);
    this.writer.startDocument();

    this.writer.startPrefixMapping(PREFIX, TransferModel.TRANSFER_MODEL_1_0_URI);
    this.writer.startPrefixMapping("cm", NamespaceService.CONTENT_MODEL_1_0_URI);

    // Start Transfer Manifest // uri, name, prefix
    this.writer.startElement(TransferModel.TRANSFER_MODEL_1_0_URI,
                ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, PREFIX + ":"
                            + ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, EMPTY_ATTRIBUTES);
}
 
Example 10
Project: andbg   File: DexAnnotator.java   View source code 6 votes vote down vote up
public void writeAnnotations(Writer out) throws IOException {
    List<MapItem> mapItems = dexFile.getMapItems();
    // sort the map items based on the order defined by sectionAnnotationOrder
    Ordering<MapItem> ordering = Ordering.from(new Comparator<MapItem>() {
        @Override public int compare(MapItem o1, MapItem o2) {
            return Ints.compare(sectionAnnotationOrder.get(o1.getType()), sectionAnnotationOrder.get(o2.getType()));
        }
    });

    mapItems = ordering.immutableSortedCopy(mapItems);

    try {
        for (MapItem mapItem: mapItems) {
            SectionAnnotator annotator = annotators.get(mapItem.getType());
            annotator.annotateSection(this);
        }
    } finally {
        dexFile.writeAnnotations(out, this);
    }
}
 
Example 11
Project: elasticsearch_my   File: CustomMustacheFactory.java   View source code 6 votes vote down vote up
@Override
public Writer run(Writer writer, List<Object> scopes) {
    if (getCodes() != null) {
        for (Code code : getCodes()) {
            try (StringWriter capture = new StringWriter()) {
                code.execute(capture, scopes);

                String s = capture.toString();
                if (s != null) {
                    encoder.encode(s, writer);
                }
            } catch (IOException e) {
                throw new MustacheException("Exception while parsing mustache function at line " + tc.line(), e);
            }
        }
    }
    return writer;
}
 
Example 12
Project: s-store   File: VoltTableUtil.java   View source code 6 votes vote down vote up
/**
 * Dump out a VoltTable as a CSV to the given writer
 * If the header flag is set to true, then the output will include 
 * the column names in the first row
 * @param out
 * @param vt
 * @param write_header
 */
public static void csv(Writer out, VoltTable vt, boolean header) {
    CSVWriter writer = new CSVWriter(out);
    
    if (header) {
        String cols[] = new String[vt.getColumnCount()];
        for (int i = 0; i < cols.length; i++) {
            cols[i] = vt.getColumnName(i);
        } // FOR
        writer.writeNext(cols);
    }
    vt.resetRowPosition();
    while (vt.advanceRow()) {
        String row[] = vt.getRowStringArray();
        assert(row != null);
        assert(row.length == vt.getColumnCount());
        writer.writeNext(row);
    } // WHILE
}
 
Example 13
Project: incubator-netbeans   File: CompilationUnitTest.java   View source code 6 votes vote down vote up
private void setupJavaTemplates() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package zoo;\n" +
        "\n" +
        "public class A {\n" +
        "}\n"
    );

    FileObject emptyJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Empty.java");
    emptyJava.setAttribute("template", Boolean.TRUE);
    classJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Class.java");
    classJava.setAttribute("template", Boolean.TRUE);
    classJava.setAttribute("verbatim-create-from-template", Boolean.TRUE);
    template = "/*\r\ninitial\r\ncomment\r\n*/\r\npackage zoo;\r\npublic class Template {\r\n    public Template() {}\r\n}\r\n";
    Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
    w.write(template);
    w.close();
}
 
Example 14
Project: continuous-performance-evaluation   File: RealtimeCargoTrackingService.java   View source code 6 votes vote down vote up
public void onCargoInspected(@Observes @CargoInspected Cargo cargo) {
    Writer writer = new StringWriter();

    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator
                .writeStartObject()
                .write("trackingId", cargo.getTrackingId().getIdString())
                .write("origin", cargo.getOrigin().getName())
                .write("destination", cargo.getRouteSpecification().getDestination().getName())
                .write("lastKnownLocation", cargo.getDelivery().getLastKnownLocation().getName())
                .write("transportStatus", cargo.getDelivery().getTransportStatus().toString())
                .writeEnd();
    }

    String jsonValue = writer.toString();

    for (Session session : sessions) {
        try {
            session.getBasicRemote().sendText(jsonValue);
        } catch (IOException ex) {
            logger.log(Level.WARNING, "Unable to publish WebSocket message", ex);
        }
    }

}
 
Example 15
Project: incubator-netbeans   File: SerialDataConvertor.java   View source code 6 votes vote down vote up
/** store the setting object even if was not changed */
private void writeDown() throws IOException {
    Object inst = instance.get();
    if (inst == null) return ;
    
    ByteArrayOutputStream b = new ByteArrayOutputStream(1024);
    Writer w = new OutputStreamWriter(b, "UTF-8"); // NOI18N
    try {
        isWriting = true;
        Convertor conv = getConvertor();
        if (conv != null) {
            conv.write(w, inst);
        } else {
            write(w, inst);
        }
    } finally {
        w.close();
        isWriting = false;
    }
    isChanged = false;

    buf = b;
    file.getFileSystem().runAtomicAction(this);
    buf = null;
    if (!isChanged) firePropertyChange(PROP_SAVE);
}
 
Example 16
Project: incubator-netbeans   File: XMLStorage.java   View source code 6 votes vote down vote up
static void save (final FileObject fo, final String content) {
    requestProcessor.post (new Runnable () {
        public void run () {
            try {
                FileLock lock = fo.lock ();
                try {
                    OutputStream os = fo.getOutputStream (lock);
                    Writer writer = new OutputStreamWriter (os, "UTF-8"); // NOI18N
                    try {
                        writer.write (content);
                    } finally {
                        writer.close ();
                    } 
                } finally {
                    lock.releaseLock ();
                }
            } catch (IOException ex) {
                ErrorManager.getDefault ().notify (ex);
            }
        }
    });
}
 
Example 17
Project: incubator-netbeans   File: FileBackedClobTest.java   View source code 6 votes vote down vote up
@Test
public void testSetCharacterStream() throws Exception {
    FileBackedClob b;
    char[] test1 = "test".toCharArray();
    char[] test2 = "test0123456789".toCharArray();
    char[] firstPartReference = new char[testCase2.length - test1.length - 4];
    char[] secondPartReference = new char[4];
    System.arraycopy(testCase2, 0, firstPartReference, 0, testCase2.length - test1.length - 4);
    System.arraycopy(testCase2, testCase2.length - 4 - 1, secondPartReference, 0, 4);
    b = new FileBackedClob(new CharArrayReader(testCase2));
    Writer os = b.setCharacterStream(testCase2.length - test1.length - 4 + 1);
    os.write(test1);
    os.close();
    assertEquals(new String(firstPartReference), b.getSubString(1, testCase2.length - test1.length - 4));
    assertEquals(new String(secondPartReference), b.getSubString(testCase2.length - 4, 4));
    assertEquals(new String(test1), b.getSubString(testCase2.length - 4 - test1.length + 1, test1.length));
    assertEquals(b.length(), 1024);
    os = b.setCharacterStream(testCase2.length - test1.length - 4 + 1);
    os.write(test2);
    os.close();
    assertEquals(new String(firstPartReference), b.getSubString(1, testCase2.length - test1.length - 4));
    assertEquals(b.length(), 1024 - test1.length - 4 + test2.length);
    assertEquals(new String(test2), b.getSubString(b.length() - test2.length + 1, test2.length));
    b.free();
}
 
Example 18
Project: n4js   File: AbstractTranspiler.java   View source code 5 votes vote down vote up
/**
 * Transpile the given resource to the given writers.
 *
 * @param resource
 *            the resource to transpile.
 * @param options
 *            the {@link GeneratorOption generator options} to use during generation.
 * @param outCode
 *            the writer where the generated output code should be sent.
 * @param optSourceMapInfo
 *            meta-info including the writer to create source-maps. If absent do not create source-maps.
 */
public void transpile(N4JSResource resource, GeneratorOption[] options, Writer outCode,
		Optional<SourceMapInfo> optSourceMapInfo) {

	// step 1: create initial transpiler state (i.e. create intermediate model, etc.)
	final TranspilerState state = prepare(resource, options);

	// step 2: execute all transformations on the transpiler state
	transform(state);

	// step 3: pretty-print the intermediate model + emit source maps (optional)
	final Optional<String> optPreamble = getPreamble();
	prettyPrint(state, outCode, optPreamble, optSourceMapInfo);
}
 
Example 19
Project: de.flapdoodle.solid   File: LogicTest.java   View source code 5 votes vote down vote up
@Test
public void testBinaryOperators() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{{ 8 + 5 * 4 - (6 + 10 / 2)  + 44 }}-{{ 10%3 }}";
    PebbleTemplate template = pebble.getTemplate(source);

    Writer writer = new StringWriter();
    template.evaluate(writer);
    assertEquals("61-1", writer.toString());
}
 
Example 20
Project: trellis   File: HtmlSerializer.java   View source code 5 votes vote down vote up
/**
 * Send the content to an output stream.
 *
 * @param out the output stream
 * @param triples the triples
 * @param subject the subject
 */
public void write(final OutputStream out, final Stream<? extends Triple> triples, final IRI subject) {
    final Writer writer = new OutputStreamWriter(out, UTF_8);
    try {
        template
            .execute(writer, new HtmlData(namespaceService, subject, triples.collect(toList()), properties))
            .flush();
    } catch (final IOException ex) {
        throw new UncheckedIOException(ex);
    }
}
 
Example 21
Project: de.flapdoodle.solid   File: ParsingOdditiesTest.java   View source code 5 votes vote down vote up
@Test
public void testExpressionInArguments() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    PebbleTemplate template = pebble
            .getTemplate("{{ input(1 + 1) }}{% macro input(value) %}{{value}}{% endmacro %}");

    Writer writer = new StringWriter();
    template.evaluate(writer);
    assertEquals("2", writer.toString());
}
 
Example 22
Project: de.flapdoodle.solid   File: RawFilterTest.java   View source code 5 votes vote down vote up
@Test
public void testRawFilterWithJsonObject() throws PebbleException, IOException {
	PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();
    PebbleTemplate template = pebble.getTemplate("{{ text | raw }}");
    Map<String, Object> context = new HashMap<>();
    context.put("text", new JsonObject());
    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals(JsonObject.JSON_VALUE, writer.toString());
}
 
Example 23
Project: stroom-stats   File: XMLUtil.java   View source code 5 votes vote down vote up
public static String prettyPrintXML(final String xml) {
    final Reader reader = new StringReader(xml);
    final Writer writer = new StringWriter(1000);

    prettyPrintXML(reader, writer);

    return writer.toString();
}
 
Example 24
Project: OpenJSharp   File: SimpleDocFileFactory.java   View source code 5 votes vote down vote up
/**
 * Open an writer for the file, using the encoding (if any) given in the
 * doclet configuration.
 * The file must have been created with a location of
 * {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} and a corresponding relative path.
 */
public Writer openWriter() throws IOException, UnsupportedEncodingException {
    if (location != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
        throw new IllegalStateException();

    createDirectoryForFile(file);
    FileOutputStream fos = new FileOutputStream(file);
    if (configuration.docencoding == null) {
        return new BufferedWriter(new OutputStreamWriter(fos));
    } else {
        return new BufferedWriter(new OutputStreamWriter(fos, configuration.docencoding));
    }
}
 
Example 25
Project: lams   File: Dom4JDriver.java   View source code 5 votes vote down vote up
@Override
public HierarchicalStreamWriter createWriter(final Writer out) {
    final HierarchicalStreamWriter[] writer = new HierarchicalStreamWriter[1];
    final FilterWriter filter = new FilterWriter(out) {
        @Override
        public void close() {
            writer[0].close();
        }
    };
    writer[0] = new Dom4JXmlWriter(new XMLWriter(filter, outputFormat), getNameCoder());
    return writer[0];
}
 
Example 26
Project: powsybl-core   File: AbstractValidationFormatterWriterTest.java   View source code 5 votes vote down vote up
protected void testFlows(String flowsContent, boolean verbose) throws IOException {
    Writer writer = new StringWriter();
    TableFormatterConfig config = new TableFormatterConfig(Locale.getDefault(), ';', "inv", true, true);
    try (ValidationWriter flowsWriter = getFlowsValidationFormatterCsvWriter(config, writer, verbose)) {
        flowsWriter.write(branchId, p1, p1Calc, q1, q1Calc, p2, p2Calc, q2, q2Calc, r, x, g1, g2, b1, b2, rho1, rho2,
                          alpha1, alpha2, u1, u2, theta1, theta2, z, y, ksi, connected1, connected2, mainComponent1,
                          mainComponent2, validated);
        assertEquals(flowsContent, writer.toString().trim());
    }
}
 
Example 27
Project: HuskyCrates-Sponge   File: JSONWriter.java   View source code 5 votes vote down vote up
/**
 * Make a fresh JSONWriter. It can be used to build one JSON text.
 */
public JSONWriter(Writer w) {
    this.comma = false;
    this.mode = 'i';
    this.stack = new JSONObject[maxdepth];
    this.top = 0;
    this.writer = w;
}
 
Example 28
Project: qpp-conversion-tool   File: ConversionFileWriterWrapper.java   View source code 5 votes vote down vote up
/**
 * Write out the QPP to a file.
 *
 * @param jsonWrapper The QPP to write
 * @param outFile The location to write.
 */
private void writeOutQpp(JsonWrapper jsonWrapper, Path outFile) {
	try (Writer writer = Files.newBufferedWriter(outFile)) {
		writer.write(jsonWrapper.toString());
		writer.flush();
	} catch (IOException exception) {
		DEV_LOG.error("Could not write out QPP JSON to file", exception);
	}
}
 
Example 29
Project: OpenDA   File: NetcdfUtils.java   View source code 5 votes vote down vote up
/**
 * Converts the data in the given netcdf file to text format and returns this as a String.
 * This can be used e.g. in unit tests to compare the data in human readable text format instead of in binary format.
 *
 * @param netcdfFile netcdf file
 * @param variableNames semicolon delimited list of variables of which the data should be printed.
 *                      If this is null or empty, then all variables are printed.
 * @return String with cdl representation of the data.
 * @throws IOException
 */
public static String netcdfFileToString(File netcdfFile, String variableNames) throws IOException {
	boolean printAllVariables = false;
	if (variableNames == null || variableNames.isEmpty()) {
		printAllVariables = true;
		variableNames = null;
	}

	Writer writer = new StringWriter();
	NCdumpW.print(netcdfFile.getAbsolutePath(), writer, printAllVariables, false, false, true, variableNames, null);
	return writer.toString();
}
 
Example 30
Project: de.flapdoodle.solid   File: InheritanceTest.java   View source code 5 votes vote down vote up
@Test
public void testMultiLevelInheritance() throws PebbleException, IOException {
	PebbleEngine pebble = new PebbleEngine.Builder().strictVariables(false).build();
	PebbleTemplate template = pebble.getTemplate("templates/template.child.peb");

	Writer writer = new StringWriter();
	template.evaluate(writer);
	assertEquals("GRANDFATHER TEXT ABOVE HEAD" + LINE_SEPARATOR + LINE_SEPARATOR + "\tCHILD HEAD" + LINE_SEPARATOR
			+ LINE_SEPARATOR + "GRANDFATHER TEXT BELOW HEAD AND ABOVE FOOT" + LINE_SEPARATOR + LINE_SEPARATOR + "\tGRANDFATHER FOOT" + LINE_SEPARATOR + LINE_SEPARATOR
			+ "GRANDFATHER TEXT BELOW FOOT", writer.toString());
}
 
Example 31
Project: OpenJSharp   File: ToStream.java   View source code 5 votes vote down vote up
/**
 * Handle one of the default entities, return false if it
 * is not a default entity.
 *
 * @param ch character to be escaped.
 * @param i index into character array.
 * @param chars non-null reference to character array.
 * @param len length of chars.
 * @param fromTextNode true if the characters being processed
 * are from a text node, false if they are from an attribute value
 * @param escLF true if the linefeed should be escaped.
 *
 * @return i+1 if the character was written, else i.
 *
 * @throws java.io.IOException
 */
protected int accumDefaultEntity(
    java.io.Writer writer,
    char ch,
    int i,
    char[] chars,
    int len,
    boolean fromTextNode,
    boolean escLF)
    throws IOException
{

    if (!escLF && CharInfo.S_LINEFEED == ch)
    {
        writer.write(m_lineSep, 0, m_lineSepLen);
    }
    else
    {
        // if this is text node character and a special one of those,
        // or if this is a character from attribute value and a special one of those
        if ((fromTextNode && m_charInfo.isSpecialTextChar(ch)) || (!fromTextNode && m_charInfo.isSpecialAttrChar(ch)))
        {
            String outputStringForChar = m_charInfo.getOutputStringForChar(ch);

            if (null != outputStringForChar)
            {
                writer.write(outputStringForChar);
            }
            else
                return i;
        }
        else
            return i;
    }

    return i + 1;

}
 
Example 32
Project: guava-mock   File: CharStreamsTest.java   View source code 5 votes vote down vote up
public void testNullWriter() throws Exception {
  // create a null writer
  Writer nullWriter = CharStreams.nullWriter();
  // write to the writer
  nullWriter.write('n');
  String test = "Test string for NullWriter";
  nullWriter.write(test);
  nullWriter.write(test, 2, 10);
  // nothing really to assert?
  assertSame(CharStreams.nullWriter(), CharStreams.nullWriter());
}
 
Example 33
Project: mustache-showcase   File: NavActiveLambda.java   View source code 5 votes vote down vote up
@Override
public void execute(Template.Fragment frag, Writer out) throws IOException {
    String body = frag.execute();
    if (body.equals(((Map) frag.context()).get(NavNameLambda.NAME))) {
        out.write(ACTIVE_CLASS_NAME);
    }
}
 
Example 34
Project: googles-monorepo-demo   File: CharStreamsTest.java   View source code 5 votes vote down vote up
public void testAsWriter() {
  // Should wrap Appendable in a new object
  Appendable plainAppendable = new StringBuilder();
  Writer result = CharStreams.asWriter(plainAppendable);
  assertNotSame(plainAppendable, result);
  assertNotNull(result);

  // A Writer should not be wrapped
  Appendable secretlyAWriter = new StringWriter();
  result = CharStreams.asWriter(secretlyAWriter);
  assertSame(secretlyAWriter, result);
}
 
Example 35
Project: otus_java_2017_06   File: TemplateProcessor.java   View source code 5 votes vote down vote up
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 36
Project: openjdk-jdk10   File: ElementStructureTest.java   View source code 5 votes vote down vote up
void realClasses(String location, Predicate<String> acceptor, Writer output, String version) throws Exception {
    Path classes = Paths.get(location);
    Map<String, JavaFileObject> className2File = new HashMap<>();
    Map<JavaFileObject, String> file2ClassName = new HashMap<>();

    try (BufferedReader descIn = Files.newBufferedReader(classes)) {
        String classFileData;

        while ((classFileData = descIn.readLine()) != null) {
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            for (int i = 0; i < classFileData.length(); i += 2) {
                data.write(Integer.parseInt(classFileData.substring(i, i + 2), 16));
            }
            JavaFileObject file = new ByteArrayJavaFileObject(data.toByteArray());
            try (InputStream in = new ByteArrayInputStream(data.toByteArray())) {
                String name = ClassFile.read(in).getName().replace("/", ".");
                className2File.put(name, file);
                file2ClassName.put(file, name);
            } catch (IOException | ConstantPoolException ex) {
                throw new IllegalStateException(ex);
            }
        }
    }

    try (JavaFileManager fm = new TestFileManager(className2File, file2ClassName)) {
        JavacTaskImpl task = (JavacTaskImpl) ToolProvider.getSystemJavaCompiler().getTask(null, fm, null, Arrays.asList("-source", version), null, Arrays.asList(new ToolBox.JavaSource("Test", "")));
        task.parse();

        PACK: for (String pack : packages(fm)) {
            PackageElement packEl = task.getElements().getPackageElement(pack);
            assert packEl != null;
            new ExhaustiveElementScanner(task, output, acceptor).visit(packEl);
        }
    }
}
 
Example 37
Project: GitHub   File: Output.java   View source code 5 votes vote down vote up
private void writeLinesFrom(Iterable<String> services) throws IOException {
  new CharSink() {
    @Override
    public Writer openStream() throws IOException {
      return getFiler()
          .createResource(StandardLocation.CLASS_OUTPUT, key.packageName, key.relativeName)
          .openWriter();
    }
  }.writeLines(services, "\n");
}
 
Example 38
Project: tac-kbp-eal   File: GoldArgumentCountsInspector.java   View source code 5 votes vote down vote up
static void writeTsv(ImmutableMultiset<String> data, File file) throws IOException {
  try (Writer out = Files.asCharSink(file, Charsets.UTF_8).openBufferedStream()) {
    for (Entry<String> e : Multisets.copyHighestCountFirst(data).entrySet()) {
      out.write(e.getElement() + "\t" + e.getCount() + "\n");
    }
  }
}
 
Example 39
Project: hadoop   File: TestEncryptedShuffle.java   View source code 5 votes vote down vote up
private void encryptedShuffleWithCerts(boolean useClientCerts)
  throws Exception {
  try {
    Configuration conf = new Configuration();
    String keystoresDir = new File(BASEDIR).getAbsolutePath();
    String sslConfsDir =
      KeyStoreTestUtil.getClasspathDir(TestEncryptedShuffle.class);
    KeyStoreTestUtil.setupSSLConfig(keystoresDir, sslConfsDir, conf,
                                    useClientCerts);
    conf.setBoolean(MRConfig.SHUFFLE_SSL_ENABLED_KEY, true);
    startCluster(conf);
    FileSystem fs = FileSystem.get(getJobConf());
    Path inputDir = new Path("input");
    fs.mkdirs(inputDir);
    Writer writer =
      new OutputStreamWriter(fs.create(new Path(inputDir, "data.txt")));
    writer.write("hello");
    writer.close();

    Path outputDir = new Path("output", "output");

    JobConf jobConf = new JobConf(getJobConf());
    jobConf.setInt("mapred.map.tasks", 1);
    jobConf.setInt("mapred.map.max.attempts", 1);
    jobConf.setInt("mapred.reduce.max.attempts", 1);
    jobConf.set("mapred.input.dir", inputDir.toString());
    jobConf.set("mapred.output.dir", outputDir.toString());
    JobClient jobClient = new JobClient(jobConf);
    RunningJob runJob = jobClient.submitJob(jobConf);
    runJob.waitForCompletion();
    Assert.assertTrue(runJob.isComplete());
    Assert.assertTrue(runJob.isSuccessful());
  } finally {
    stopCluster();
  }
}
 
Example 40
Project: openjdk-jdk10   File: EncodingInfo.java   View source code 5 votes vote down vote up
/**
 * 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);
}