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   Source Code and License 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   Source Code and License 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: continuous-performance-evaluation   File: RealtimeCargoTrackingService.java   Source Code and License 7 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 4
Project: OperatieBRP   File: AttributeChild.java   Source Code and License 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 5
Project: Backmemed   File: UserList.java   Source Code and License 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 6
Project: openjdk-jdk10   File: XMLKit.java   Source Code and License 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 7
Project: tbschedule-wed   File: ScheduleStrategyDataManager4ZK.java   Source Code and License 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 8
Project: de.flapdoodle.solid   File: CoreFiltersTest.java   Source Code and License 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 9
Project: de.flapdoodle.solid   File: LogicTest.java   Source Code and License 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 10
Project: alfresco-repository   File: XMLTransferManifestWriter.java   Source Code and License 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 11
Project: andbg   File: DexAnnotator.java   Source Code and License 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 12
Project: elasticsearch_my   File: CustomMustacheFactory.java   Source Code and License 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 13
Project: s-store   File: VoltTableUtil.java   Source Code and License 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 14
Project: incubator-netbeans   File: CompilationUnitTest.java   Source Code and License 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 15
Project: incubator-netbeans   File: SerialDataConvertor.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: openjdk-jdk10   File: PathFileObject.java   Source Code and License 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER)
public Writer openWriter() throws IOException {
    fileManager.updateLastUsedTime();
    fileManager.flushCache(this);
    ensureParentDirectoriesExist();
    return new OutputStreamWriter(Files.newOutputStream(path), fileManager.getEncodingName());
}
 
Example 42
Project: de.flapdoodle.solid   File: CoreTagsTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = RuntimePebbleException.class)
public void testCacheWithNoName() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{% cache %}{% if foobar %}true{% else %}false{% endif %}{% endcache %}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();
    context.put("foobar", true);

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("true", writer.toString());
}
 
Example 43
Project: de.flapdoodle.solid   File: LogicTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testContainsOperator() throws PebbleException, IOException {
    
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{% if names contains 'John' %}yes{% else %}no{% endif %}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();
    context.put("names", Arrays.asList("Bob", "Maria", "John"));

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("yes", writer.toString());
}
 
Example 44
Project: de.flapdoodle.solid   File: GetAttributeTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testBeanMethodWithArgument() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(true).build();

    PebbleTemplate template = pebble.getTemplate("hello {{ object.name('Steve') }}");
    Map<String, Object> context = new HashMap<>();
    context.put("object", new BeanWithMethodsThatHaveArguments());

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("hello Steve", writer.toString());
}
 
Example 45
Project: otus_java_2017_04   File: TemplateProcessor.java   Source Code and License 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 46
Project: XSnow   File: GsonRequestBodyConverter.java   Source Code and License 5 votes vote down vote up
@Override
public RequestBody convert(@NonNull T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    adapter.write(jsonWriter, value);
    jsonWriter.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
 
Example 47
Project: Banmanager   File: JSONObject.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 48
Project: outlook-message-parser   File: JEditorPaneRTF2HTMLConverter.java   Source Code and License 5 votes vote down vote up
public String rtf2html(final String rtf) {
	final JEditorPane p = new JEditorPane();
	p.setContentType("text/rtf");
	final EditorKit kitRtf = p.getEditorKitForContentType("text/rtf");
	try {
		kitRtf.read(new StringReader(rtf), p.getDocument(), 0);
		final Writer writer = new StringWriter();
		final EditorKit editorKitForContentType = p.getEditorKitForContentType("text/html");
		editorKitForContentType.write(writer, p.getDocument(), 0, p.getDocument().getLength());
		return writer.toString();
	} catch (IOException | BadLocationException e) {
		throw new RTF2HTMLException("Could not convert RTF to HTML.", e);
	}
}
 
Example 49
Project: dev-courses   File: InOutUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @see #copy(java.io.Reader, java.io.Writer, long, int)
 */
public static long copy(
        final Reader reader,
        final Writer writer) throws IOException {
    return copy(reader, writer,
            DEFAULT_COPY_AMOUNT,
            DEFAULT_COPY_BUFFER_SIZE);
}
 
Example 50
Project: de.flapdoodle.solid   File: GetAttributeTest.java   Source Code and License 5 votes vote down vote up
@Test()
public void testPrimitiveAttribute() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    PebbleTemplate template = pebble.getTemplate("hello {{ object.name }}");
    Map<String, Object> context = new HashMap<>();
    context.put("object", new SimpleObject8());

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("hello true", writer.toString());
}
 
Example 51
Project: openjdk-jdk10   File: DumbEscapeHandler.java   Source Code and License 5 votes vote down vote up
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
    int limit = start+length;
    for (int i = start; i < limit; i++) {
        switch (ch[i]) {
        case '&':
            out.write("&amp;");
            break;
        case '<':
            out.write("&lt;");
            break;
        case '>':
            out.write("&gt;");
            break;
        case '\"':
            if (isAttVal) {
                out.write("&quot;");
            } else {
                out.write('\"');
            }
            break;
        default:
            if (ch[i] > '\u007f') {
                out.write("&#");
                out.write(Integer.toString(ch[i]));
                out.write(';');
            } else {
                out.write(ch[i]);
            }
        }
    }
}
 
Example 52
Project: incubator-netbeans   File: EditableManifest.java   Source Code and License 5 votes vote down vote up
public void write(Writer w) throws IOException {
    // translating all newlines to correct format,
    // see SingleModulePropertiesTest#testThatManifestFormattingIsNotMessedUp_61248
    String output = NEWLINE.matcher(text).replaceAll(RET);
    w.write(output);
    newline(w);
}
 
Example 53
Project: Smart_City   File: CityItemRoutes.java   Source Code and License 5 votes vote down vote up
protected void initInsertItemRoute() throws IOException {
    get(new FreemarkerBasedRoute("/insert", "insert_item.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            template.process(null, writer);
        }
    });

    post(new Route("insert_item") {
        @Override
        public Object handle(Request rqst, Response rspns) {
            CityItem.Builder builder = new CityItem.Builder();
            builder.type(Integer.parseInt(rqst.queryParams("type")));
            // TODO add description to frontend
            builder.longitude(Double.parseDouble(rqst.queryParams("longitude")));
            builder.latitude(Double.parseDouble(rqst.queryParams("latitude")));
            builder.description(" ");

            String id = CityItemDAO.insertCityItem(builder.build());

            if (id.equals("-1")) {
                JSONObject jsonResp = new JSONObject();
                jsonResp.put("success", false);
                return jsonResp;
            }

            JSONObject jsonDataResponse = new JSONObject();
            jsonDataResponse.put("generate_link", "/download_qr?id=" + id);
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("success", true);
            jsonResponse.put("data", jsonDataResponse);

            return jsonResponse.toString();
        }
    });
}
 
Example 54
Project: myfaces-trinidad   File: RenderKitTestCase.java   Source Code and License 5 votes vote down vote up
private String _processTests(String golden, String baseResults) throws IOException
    {
      Writer out = new StringWriter(golden == null ? 1000 : golden.length());

      try
      {
        out.write("<results>");
        out.write(baseResults);
/*
        out.write("<results>\n");
        
        // surround content in a CDATA block to make it more likely to be valid XML
        out.write("<![CDATA[\n");
        
        try
        {
          out.write(baseResults);
        }
        finally
        {
          out.write("\n]]>");         
        }
*/
        Iterator<TestScript.Test> tests = _script.getTests().iterator();
        while (tests.hasNext())
        {
          TestScript.Test test = tests.next();

          _processTest(test, out, baseResults);
        }

        out.write("\n</results>\n");
      }
      finally
      {
        out.close();
      }

      return out.toString();
    }
 
Example 55
Project: guava-mock   File: AppendableWriter.java   Source Code and License 4 votes vote down vote up
@Override
public Writer append(@Nullable CharSequence charSeq, int start, int end) throws IOException {
  checkNotClosed();
  target.append(charSeq, start, end);
  return this;
}
 
Example 56
Project: aws-sdk-java-v2   File: JacksonUtils.java   Source Code and License 4 votes vote down vote up
public static JsonGenerator jsonGeneratorOf(Writer writer) throws IOException {
    return new JsonFactory().createGenerator(writer);
}
 
Example 57
Project: OpenJSharp   File: XMLWriter.java   Source Code and License 4 votes vote down vote up
/**
 * Returns underlying <code>Writer</code>
 */
protected Writer getWriter() {
    return writer;
}
 
Example 58
Project: Moenagade   File: WriterOutputStream.java   Source Code and License 4 votes vote down vote up
public WriterOutputStream(Writer writer, String encoding)
{
    _writer=writer;
    _encoding=encoding;
}
 
Example 59
Project: Reinickendorf_SER316   File: AltHTMLWriter.java   Source Code and License 4 votes vote down vote up
public AltHTMLWriter(Writer w, HTMLDocument doc, String enc) {
    this(w, doc, 0, doc.getLength(), enc, false);
}
 
Example 60
Project: rapidminer   File: Linear.java   Source Code and License 4 votes vote down vote up
/**
 * Writes the model to the modelOutput. It uses {@link java.util.Locale#ENGLISH} for number
 * formatting.
 *
 * <p>
 * <b>Note: The modelOutput is closed after reading or in case of an exception.</b>
 * </p>
 */
public static void saveModel(Writer modelOutput, Model model) throws IOException {
	int nr_feature = model.nr_feature;
	int w_size = nr_feature;
	if (model.bias >= 0) {
		w_size++;
	}

	int nr_w = model.nr_class;
	if (model.nr_class == 2 && model.solverType != SolverType.MCSVM_CS) {
		nr_w = 1;
	}

	Formatter formatter = new Formatter(modelOutput, DEFAULT_LOCALE);
	try {
		printf(formatter, "solver_type %s\n", model.solverType.name());
		printf(formatter, "nr_class %d\n", model.nr_class);

		if (model.label != null) {
			printf(formatter, "label");
			for (int i = 0; i < model.nr_class; i++) {
				printf(formatter, " %d", model.label[i]);
			}
			printf(formatter, "\n");
		}

		printf(formatter, "nr_feature %d\n", nr_feature);
		printf(formatter, "bias %.16g\n", model.bias);

		printf(formatter, "w\n");
		for (int i = 0; i < w_size; i++) {
			for (int j = 0; j < nr_w; j++) {
				double value = model.w[i * nr_w + j];

				/** this optimization is the reason for {@link Model#equals(double[], double[])} */
				if (value == 0.0) {
					printf(formatter, "%d ", 0);
				} else {
					printf(formatter, "%.16g ", value);
				}
			}
			printf(formatter, "\n");
		}

		formatter.flush();
		IOException ioException = formatter.ioException();
		if (ioException != null) {
			throw ioException;
		}
	} finally {
		formatter.close();
	}
}