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:cv_vacature_bank.Jsonhandler.java

public void createFile(String type) {
    Writer writer = null;
    id++;//from  w w w. j a va 2 s.com

    try {
        writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(type + Integer.toString(id) + ".txt"), "utf-8"));

        for (JSONObject jo : objs) {
            writer.write(jo.toJSONString() + "\n\n");
        }
    } catch (IOException ex) {
        // report
    } finally {
        try {
            writer.close();
        } catch (Exception ex) {
        }
    }
}

From source file:net.metanotion.emailqueue.SmtpSender.java

@Override
public boolean send(final Connection conn, final MessageStruct msg) throws IOException {
    logger.trace("Set Sender " + msg.Sender);
    conn.client.setSender(msg.Sender);/*  w  ww  .j  a  v a2 s .c o  m*/
    logger.trace("Set Recipient " + msg.Recipient);
    conn.client.addRecipient(msg.Recipient);
    final Writer writer = conn.client.sendMessageData();
    final SimpleSMTPHeader header = new SimpleSMTPHeader(msg.Sender, msg.Recipient, msg.Subject);
    logger.trace("Write header");
    writer.write(header.toString());
    logger.trace("Write message");
    writer.write(msg.Message);
    logger.trace("Close");
    writer.close();
    logger.trace("Complete command");
    return conn.client.completePendingCommand();
}

From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java

@Test
public void testOutputStreamOpenAutocloseWrite() throws Exception {
    final FileObject fo = openFileObject("out.txt");
    final Writer writer = openWriter(fo);
    try {/*from  w  ww .ja  v a 2  s  .  c  o m*/
        Thread.sleep(SLEEP_TIME);
        writer.write("test");
    } finally {
        writer.close();
    }
    assertContentEquals(fo, "test");
    fo.close();
}

From source file:fr.jetoile.hadoopunit.integrationtest.IntegrationBootstrapTest.java

@Test
public void oozieShouldStart() throws Exception {
    LOGGER.info("OOZIE: Test Submit Workflow Start");

    org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
    conf.set("fs.default.name",
            "hdfs://127.0.0.1:" + configuration.getInt(HadoopUnitConfig.HDFS_NAMENODE_PORT_KEY));

    URI uri = URI.create("hdfs://127.0.0.1:" + configuration.getInt(HadoopUnitConfig.HDFS_NAMENODE_PORT_KEY));

    FileSystem hdfsFs = FileSystem.get(uri, conf);

    OozieClient oozieClient = new OozieClient("http://" + configuration.getString(OozieBootstrap.OOZIE_HOST)
            + ":" + configuration.getInt(OozieBootstrap.OOZIE_PORT) + "/oozie");

    Path appPath = new Path(hdfsFs.getHomeDirectory(), "testApp");
    hdfsFs.mkdirs(new Path(appPath, "lib"));
    Path workflow = new Path(appPath, "workflow.xml");

    //write workflow.xml
    String wfApp = "<workflow-app xmlns='uri:oozie:workflow:0.1' name='test-wf'>" + "    <start to='end'/>"
            + "    <end name='end'/>" + "</workflow-app>";

    Writer writer = new OutputStreamWriter(hdfsFs.create(workflow));
    writer.write(wfApp);/*from  w  ww .  j av a2 s .c  o  m*/
    writer.close();

    //write job.properties
    Properties oozieConf = oozieClient.createConfiguration();
    oozieConf.setProperty(OozieClient.APP_PATH, workflow.toString());
    oozieConf.setProperty(OozieClient.USER_NAME, UserGroupInformation.getCurrentUser().getUserName());

    //submit and check
    final String jobId = oozieClient.submit(oozieConf);
    WorkflowJob wf = oozieClient.getJobInfo(jobId);
    Assert.assertNotNull(wf);
    assertEquals(WorkflowJob.Status.PREP, wf.getStatus());

    LOGGER.info("OOZIE: Workflow: {}", wf.toString());
    hdfsFs.close();

}

From source file:com.stratelia.silverpeas.versioning.jcr.impl.AbstractJcrTestCase.java

protected void createTempFile(String path, String content) throws IOException {
    File attachmentFile = new File(path);
    attachmentFile.deleteOnExit();//from  w  w w.jav a 2 s  .  c o  m
    FileOutputStream out = null;
    Writer writer = null;
    try {
        out = new FileOutputStream(attachmentFile);
        writer = new OutputStreamWriter(out);
        writer.write(content);
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:net.longfalcon.newsj.Nzb.java

private void _doWriteNZBforRelease(Release release, Directory nzbBaseDir) throws IOException, JAXBException {
    long releaseId = release.getId();
    String releaseGuid = release.getGuid();
    String releaseName = release.getName();
    long startTime = System.currentTimeMillis();

    Category category = release.getCategory();
    String categoryName = null;//  www.  j  a  va2s .  co  m
    if (category != null) {
        categoryName = category.getTitle();
    }

    net.longfalcon.newsj.xml.Nzb nzbRoot = new net.longfalcon.newsj.xml.Nzb();
    nzbRoot.setXmlns(_XMLNS);
    Head head = new Head();
    List<Meta> metaElements = head.getMeta();
    Meta categoryMeta = new Meta();
    categoryMeta.setType("category");
    categoryMeta.setvalue(StringEscapeUtils.escapeXml11(categoryName));
    Meta nameMeta = new Meta();
    nameMeta.setType("name");
    nameMeta.setvalue(StringEscapeUtils.escapeXml11(releaseName));
    metaElements.add(categoryMeta);
    metaElements.add(nameMeta);
    nzbRoot.setHead(head);

    List<File> files = nzbRoot.getFile();
    List<Binary> binaries = binaryDAO.findBinariesByReleaseId(releaseId);
    for (Binary binary : binaries) {
        File fileElement = new File();
        fileElement.setPoster(StringEscapeUtils.escapeXml11(binary.getFromName()));
        fileElement.setDate(String.valueOf(binary.getDate().getTime()));
        String subjectString = String.format("%s (1/%s)", StringEscapeUtils.escapeXml11(binary.getName()),
                binary.getTotalParts());
        fileElement.setSubject(subjectString);

        Groups groupsElement = new Groups();
        List<Group> groups = groupsElement.getGroup();
        net.longfalcon.newsj.model.Group group = groupDAO.findGroupByGroupId(binary.getGroupId());
        Group groupElement = new Group();
        groupElement.setvalue(group.getName());
        groups.add(groupElement);

        // TODO: add XRef groups
        fileElement.setGroups(groupsElement);
        Segments segmentsElement = new Segments();
        List<Segment> segments = segmentsElement.getSegment();

        List<Object[]> messageIdSizePartNos = partDAO
                .findDistinctMessageIdSizeAndPartNumberByBinaryId(binary.getId());
        for (Object[] messageIdSizePartNo : messageIdSizePartNos) {
            // messageIdSizePartNo is {String,Long,Integer}
            Segment segment = new Segment();
            segment.setBytes(String.valueOf(messageIdSizePartNo[1]));
            segment.setNumber(String.valueOf(messageIdSizePartNo[2]));

            segment.setvalue(String.valueOf(messageIdSizePartNo[0]));
            segments.add(segment);
        }
        fileElement.setSegments(segmentsElement);

        files.add(fileElement);
    }

    long startFileWriteTime = System.currentTimeMillis();

    FsFile fileHandle = getNzbFileHandle(release, nzbBaseDir);
    Writer writer = new OutputStreamWriter(fileHandle.getOutputStream(), Charset.forName("UTF-8"));
    getMarshaller().marshal(nzbRoot, writer);
    writer.write(String.format("<!-- generated by NewsJ %s -->", config.getReleaseVersion()));
    writer.flush();
    writer.close();

    Period totalTimePeriod = new Period(startTime, System.currentTimeMillis());
    Period buildTimePeriod = new Period(startTime, startFileWriteTime);
    Period writeTimePeriod = new Period(startFileWriteTime, System.currentTimeMillis());
    _log.info(String.format("Wrote NZB for %s in %s;\n build time: %s write time: %s", releaseName,
            _periodFormatter.print(totalTimePeriod), _periodFormatter.print(buildTimePeriod),
            _periodFormatter.print(writeTimePeriod)));
}

From source file:gdt.jgui.entity.folder.JFolderFacetOpenItem.java

/**
 * Execute the response locator./*from   ww w . ja v  a 2s  .c  om*/
 * @param console the main console.
 * @param locator$ the response locator.
 */
@Override
public void response(JMainConsole console, String locator$) {
    //      System.out.println("JFolderFacetItem:response:locator:"+locator$);
    try {
        Properties locator = Locator.toProperties(locator$);
        entihome$ = locator.getProperty(Entigrator.ENTIHOME);
        entityKey$ = locator.getProperty(EntityHandler.ENTITY_KEY);
        String action$ = locator.getProperty(JRequester.REQUESTER_ACTION);
        if (JFolderPanel.ACTION_EDIT_FILE.equals(action$)) {
            String text$ = locator.getProperty(JTextEditor.TEXT);
            String filePath$ = locator.getProperty(JFolderPanel.FILE_PATH);
            String selection$ = locator.getProperty(JEntityDigestDisplay.SELECTION);
            File file = new File(filePath$);
            if (!file.exists())
                file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file, false);
            Writer writer = new OutputStreamWriter(fos, "UTF-8");
            writer.write(text$);
            writer.close();
            fos.close();
            JEntityDigestDisplay edd = new JEntityDigestDisplay();
            String eddLocator$ = edd.getLocator();
            eddLocator$ = Locator.append(eddLocator$, EntityHandler.ENTITY_KEY, entityKey$);
            eddLocator$ = Locator.append(eddLocator$, Entigrator.ENTIHOME, entihome$);
            eddLocator$ = Locator.append(eddLocator$, JEntityDigestDisplay.SELECTION, selection$);
            JConsoleHandler.execute(console, eddLocator$);
            return;
        }
        JEntityFacetPanel efp = new JEntityFacetPanel();
        String efpLocator$ = efp.getLocator();
        efpLocator$ = Locator.append(efpLocator$, Entigrator.ENTIHOME, entihome$);
        efpLocator$ = Locator.append(efpLocator$, EntityHandler.ENTITY_KEY, entityKey$);
        JConsoleHandler.execute(console, efpLocator$);
    } catch (Exception e) {
        LOGGER.severe(e.toString());
    }
}

From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java

/**
 * Exports all projects into separate xml files and adds them to a zip archive.  
 * @return null Always returns null, so user stays on same screen after action performed
 *//*from   ww  w  . jav a  2s.com*/
public String exportAllProjectsToZip() {
    List<PlanProperties> ppList = em.createQuery("select p from PlanProperties p").getResultList();

    if (!ppList.isEmpty()) {
        log.debug("number of plans to export: " + ppList.size());
        String filename = "allprojects.zip";

        String exportPath = OS.getTmpPath() + "export" + System.currentTimeMillis() + "/";
        new File(exportPath).mkdirs();

        String binarydataTempPath = exportPath + "binarydata/";
        File binarydataTempDir = new File(binarydataTempPath);
        binarydataTempDir.mkdirs();

        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(exportPath + filename));
            ZipOutputStream zipOut = new ZipOutputStream(out);

            for (PlanProperties pp : ppList) {
                log.debug("EXPORTING: " + pp.getName());
                ZipEntry zipAdd = new ZipEntry(String.format("%1$03d", pp.getId()) + "-"
                        + FileUtils.makeFilename(pp.getName()) + ".xml");
                zipOut.putNextEntry(zipAdd);
                // export the complete project, including binary data
                exportComplete(pp.getId(), zipOut, binarydataTempPath);
                zipOut.closeEntry();
            }
            zipOut.close();
            out.close();
            new File(exportPath + "finished.info").createNewFile();

            FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, "Export was written to: " + exportPath);
            log.info("Export was written to: " + exportPath);
        } catch (IOException e) {
            FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                    "An error occured while generating the export file.");
            log.error("An error occured while generating the export file.", e);
            File errorInfo = new File(exportPath + "error.info");
            try {
                Writer w = new FileWriter(errorInfo);
                w.write("An error occured while generating the export file:");
                w.write(e.getMessage());
                w.close();
            } catch (IOException e1) {
                log.error("Could not write error file.");
            }

        } finally {
            // remove all binary temp files
            OS.deleteDirectory(binarydataTempDir);
        }

    } else {
        FacesMessages.instance().add("No Projects found!");
    }
    return null;
}

From source file:de.codesourcery.eve.skills.ui.config.AppConfig.java

public void save() throws IOException {

    log.debug("save(): Saving app config to " + file);

    final Properties props = new Properties();

    for (Map.Entry<String, String> e : this.entrySet()) {
        props.setProperty(e.getKey(), e.getValue());
    }/*from  www . j  av  a  2 s  . com*/

    final Writer out = new FileWriter(file, false);
    try {
        props.store(out, "Automatically generated, DO NOT EDIT.");
    } finally {
        out.close();
    }
}