Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

In this page you can find the example usage for java.io Writer close.

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:com.streamsets.datacollector.util.TestConfiguration.java

@Test
public void testIncludes() throws Exception {
    File dir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(dir.mkdirs());//from   w  ww  . ja  va 2 s .c o m
    Configuration.setFileRefsBaseDir(dir);

    Writer writer = new FileWriter(new File(dir, "config.properties"));
    IOUtils.write("a=A\nconfig.includes=include1.properties , ", writer);
    writer.close();

    writer = new FileWriter(new File(dir, "include1.properties"));
    IOUtils.write("b=B\nconfig.includes=include2.properties , ", writer);
    writer.close();

    writer = new FileWriter(new File(dir, "include2.properties"));
    IOUtils.write("c=C\n", writer);
    writer.close();

    Configuration conf = new Configuration();
    Reader reader = new FileReader(new File(dir, "config.properties"));
    conf.load(reader);
    reader.close();

    Assert.assertEquals("A", conf.get("a", null));
    Assert.assertEquals("B", conf.get("b", null));
    Assert.assertEquals("C", conf.get("c", null));
    Assert.assertNull(conf.get(Configuration.CONFIG_INCLUDES, null));
}

From source file:com.kurento.kmf.test.base.GridBrowserMediaApiTest.java

private void createRemoteScript(Node node, String remotePort, String remoteScript, String remoteFolder,
        String remoteChromeDriver, String remoteSeleniumJar, Browser browser, int maxInstances)
        throws IOException {

    // Create script for Node
    Configuration cfg = new Configuration();

    Map<String, Object> data = new HashMap<String, Object>();
    data.put("remotePort", String.valueOf(remotePort));
    data.put("maxInstances", String.valueOf(maxInstances));
    data.put("hubIp", hubAddress);
    data.put("hubPort", String.valueOf(hubPort));
    data.put("remoteFolder", remoteFolder);
    data.put("remoteChromeDriver", remoteChromeDriver);
    data.put("remoteSeleniumJar", remoteSeleniumJar);
    data.put("pidFile", node.REMOTE_PID_FILE);
    data.put("browser", browser);

    cfg.setClassForTemplateLoading(GridBrowserMediaApiTest.class, "/templates/");

    try {//from ww  w  .  jav  a  2 s .  c  o  m
        Template template = cfg.getTemplate(LAUNCH_SH + ".ftl");
        Writer writer = new FileWriter(new File(LAUNCH_SH));
        template.process(data, writer);
        writer.flush();
        writer.close();

    } catch (Exception e) {
        throw new RuntimeException("Exception while creating file from template", e);
    }

    // Copy script to remote node
    node.getRemoteHost().scp(LAUNCH_SH, remoteScript);
    node.getRemoteHost().execAndWaitCommand("chmod", "+x", remoteScript);
    Shell.run("rm", LAUNCH_SH);
}

From source file:com.github.mavogel.ilias.printer.VelocityOutputPrinter.java

/**
 * Prints the header, content and output to the given print stream with a custom template.
 *
 * @param outputType   the desired output type. @see {@link OutputType}
 * @param templateName the name of the template
 * @param contextMap   the context for velocity
 * @throws Exception in case of a error, so the caller can handle it
 *///from  w  ww. jav  a 2s.  c  o m
private static void printWithCustomTemplate(final OutputType outputType, final String templateName,
        final Map<String, Object> contextMap) throws Exception {
    Velocity.init();
    Writer writer = null;
    try {
        final Template template = Velocity.getTemplate(templateName);
        final VelocityContext context = new VelocityContext();
        contextMap.forEach((k, v) -> context.put(k, v));
        writer = new BufferedWriter(createFileWriter(outputType, templateName));

        template.merge(context, writer);
        writer.flush();
    } catch (ResourceNotFoundException rnfe) {
        LOG.error("Couldn't find the template with name '" + templateName + "'");
        throw new Exception(rnfe.getMessage());
    } catch (ParseErrorException pee) {
        LOG.error("Syntax error: problem parsing the template ' " + templateName + "': " + pee.getMessage());
        throw new Exception(pee.getMessage());
    } catch (MethodInvocationException mie) {
        LOG.error(
                "An invoked method on the template '" + templateName + "' threw an error: " + mie.getMessage());
        throw new Exception(mie.getMessage());
    } catch (Exception e) {
        LOG.error("Error: " + e.getMessage());
        throw e;
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:experiment.ExperimentLogger.java

public void flushtoFile() throws FileNotFoundException, IOException {

    Writer output = new BufferedWriter(new FileWriter(file));
    try {// w w w.j a  va  2s.c  o  m
        //FileWriter always assumes default encoding is OK!
        output.write(content.toString());
    } finally {
        output.close();
    }

}

From source file:com.ewcms.publication.freemarker.generator.GeneratorBase.java

/**
 * ??//  ww  w.j a  v  a  2s. co  m
 * 
 * @param template   ?
 * @param parameters ?
 * @param rule       ??
 * @param writer     
 * @throws TemplateException
 * @throws IOException
 */
protected void write(Template template, Map<String, Object> parameters, UriRuleable rule, Writer writer)
        throws PublishException {

    setUriRuleParameters(rule, parameters);
    addUriRuleToProcessParameters(rule, parameters);

    try {
        template.process(parameters, writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        logger.error("Writer tempfile error {}", e.getMessage());
        throw new PublishException(e);
    } catch (TemplateException e) {
        logger.error("Freemarker proccess error {}", e.getMessage());
        throw new PublishException(e);
    }
}

From source file:de.minestar.contao2.manager.PlayerManager.java

@SuppressWarnings("unchecked")
/**//from  w  ww . java  2  s . c  om
 * Store all online player in a JSON file, so we can display it on the website
 */
private void saveJSON() {
    JSONObject json = new JSONObject();
    // FILL JSON FILE WITH DATA

    json.put("ConnectedUsers", Bukkit.getOnlinePlayers().length);
    json.put("ConnectedDefaultUsers",
            this.groupMap.get(ContaoGroup.DEFAULT).size() + this.groupMap.get(ContaoGroup.X).size());
    json.put("ConnectedProbeUsers", this.groupMap.get(ContaoGroup.PROBE).size());
    json.put("ConnectedFreeUsers", this.groupMap.get(ContaoGroup.FREE).size());
    json.put("ConnectedPayUsers", this.groupMap.get(ContaoGroup.PAY).size());
    json.put("ConnectedAdmins", this.groupMap.get(ContaoGroup.ADMIN).size());
    json.put("FreeUserSlots", Settings.getFreeSlots());
    json.put("MaxPublicSlots", Settings.getMaxSlots());
    json.put("TotalSlots", Bukkit.getMaxPlayers());

    // WRITE JSON FILE
    try {
        File f = new File(Settings.getJSONFilePath());
        if (!f.exists())
            f.createNewFile();
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF8"));
        writer.write(json.toJSONString());
        writer.flush();
        writer.close();
    } catch (Exception e) {
        ConsoleUtils.printException(e, Core.NAME, "Can't save the JSON file!");
    }
}

From source file:edu.nyu.cs.omnidroid.app.controller.external.actions.GMailService.java

/**
 * Send a GMail/*  w ww.ja v  a2 s  .co  m*/
 */
private void send() {
    //Toast.makeText(this, "GMail Service Started", Toast.LENGTH_LONG).show();

    SMTPClient client = new SMTPClient("UTF-8");
    client.setDefaultTimeout(60 * 1000);

    client.setRequireStartTLS(true); // requires STARTTLS
    client.setUseAuth(true); // use SMTP AUTH

    try {
        client.connect("smtp.gmail.com", 587);
        checkReply(client);
    } catch (IOException e) {
        //ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_INTERNET, 
        //   getString(R.string.gmail_failed_no_network));      
        return;
    }

    try {
        client.login("localhost", account.accountName, account.credential);
        checkReply(client);
    } catch (IOException e) {
        ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_IRRECOVERABLE,
                getString(R.string.gmail_failed_authentication_error));
        return;
    }

    try {
        client.setSender(account.accountName);
        checkReply(client);

        client.addRecipient(to);
        checkReply(client);

        Writer writer = client.sendMessageData();

        if (writer != null) {
            SimpleSMTPHeader header = new SimpleSMTPHeader(account.accountName, to, subject);
            writer.write(header.toString());
            writer.write(body);
            writer.close();
            client.completePendingCommand();
            checkReply(client);
        }

        client.logout();
        client.disconnect();

    } catch (IOException e) {
        ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_UNKNOWN,
                getString(R.string.gmail_failed_server_error));
        return;
    }
    ResultProcessor.process(this, intent, ResultProcessor.RESULT_SUCCESS, getString(R.string.gmail_sent));

}

From source file:de.kp.ames.web.core.rss.RssConsumer.java

/**
 * Get RSS feed in native representation
 * //from w w w  .jav a  2  s  . c o  m
 * @param method
 * @return
 */
public String getFeed(String method) {

    try {
        SyndFeed feed = execute(method);

        Writer writer = new StringWriter();

        SyndFeedOutput output = new SyndFeedOutput();
        output.output(feed, writer);

        String content = writer.toString();
        writer.close();

        return content;

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
    }

    return null;

}

From source file:experiment.ExperimentLogger.java

public void flushtoConfigFile() throws FileNotFoundException, IOException {

    Writer output = new BufferedWriter(new FileWriter(configFile));
    try {//from  w w w  .  ja  va 2 s . c om
        //FileWriter always assumes default encoding is OK!
        output.write(config.toString());
    } finally {
        output.close();
    }

}