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:fr.jetoile.hadoopunit.component.OozieBootstrapTest.java

@Test
public void oozieShouldStart() throws Exception {

    LOGGER.info("OOZIE: Test Submit Workflow Start");

    FileSystem hdfsFs = ((HdfsBootstrap) HadoopBootstrap.INSTANCE.getService(Component.HDFS))
            .getHdfsFileSystemHandle();//  ww w. j a  va 2 s. co m
    OozieClient oozieClient = ((OozieBootstrap) HadoopBootstrap.INSTANCE.getService(Component.OOZIE))
            .getOozieClient();

    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);
    writer.close();

    //write job.properties
    Properties conf = oozieClient.createConfiguration();
    conf.setProperty(OozieClient.APP_PATH, workflow.toString());
    conf.setProperty(OozieClient.USER_NAME, UserGroupInformation.getCurrentUser().getUserName());
    conf.setProperty("jobTracker", "localhost:37001");
    conf.setProperty("nameNode", "hdfs://localhost:20112");

    //submit and check
    final String jobId = oozieClient.run(conf);
    WorkflowJob wf = oozieClient.getJobInfo(jobId);
    assertNotNull(wf);

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

    while (oozieClient.getJobInfo(jobId).getStatus() != WorkflowJob.Status.RUNNING) {
        System.out.println("========== workflow job status " + oozieClient.getJobInfo(jobId).getStatus());
        Thread.sleep(1000);
    }

    while (oozieClient.getJobInfo(jobId).getStatus() == WorkflowJob.Status.RUNNING) {
        System.out.println("========== workflow job status " + oozieClient.getJobInfo(jobId).getStatus());
        System.out.println("========== job is running");
        Thread.sleep(1000);
    }

    System.out.println(
            "=============== OOZIE: Final Workflow status" + oozieClient.getJobInfo(jobId).getStatus());
    wf = oozieClient.getJobInfo(jobId);
    System.out.println("=============== OOZIE: Workflow: {}" + wf.toString());

    assertEquals(WorkflowJob.Status.SUCCEEDED, wf.getStatus());

    hdfsFs.close();
    assertThat("true").isEqualTo("true");

}

From source file:org.opennms.ng.services.polloutagesconfig.PollOutagesConfigFactory.java

/**
 * {@inheritDoc}/* w w w .j  a  va2  s  .c  o m*/
 */
protected void saveXML(final String xmlString) throws IOException, MarshalException, ValidationException {
    getWriteLock().lock();

    try {
        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.POLL_OUTAGES_CONFIG_FILE_NAME);

        Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8");
        fileWriter.write(xmlString);
        fileWriter.flush();
        fileWriter.close();
    } finally {
        getWriteLock().unlock();
    }
}

From source file:ca.uhn.hl7v2.testpanel.model.MessagesList.java

/**
 * Save all files to work directory/*from ww w.j  a v a 2s .  c om*/
 */
public void dumpToWorkDirectory(File theWorkfilesDir) throws IOException {
    ourLog.info("Flushing work files to directory: " + theWorkfilesDir.getAbsolutePath());

    IOUtils.deleteAllFromDirectory(theWorkfilesDir);

    int index = 0;
    for (Hl7V2MessageCollection next : myMessages) {
        index++;
        String seq = StringUtils.leftPad(Integer.toString(index), 10, '0');

        File nextFile = new File(theWorkfilesDir, next.getId() + "-" + seq + ".xml");
        nextFile.delete();
        Writer nextWriter = new OutputStreamWriter(new FileOutputStream(nextFile), Charset.forName("UTF-8"));
        nextWriter.append(next.exportConfigToXml());
        nextWriter.close();
    }

}

From source file:com.pcms.temp.generate.MarkeWrite.java

public void processTemplate(String templateName, String templateEncoding, Map<?, ?> root, Writer out) {
    try {//from ww w.  j  ava  2 s . co m
        if (StringUtils.isEmpty(templateEncoding)) {
            templateEncoding = _defaultEncoding;
        }
        Template template = _config.getTemplate(templateName, templateEncoding);
        template.process(root, out);

        out.flush();
        out.close();
    } catch (IOException e) {
        _log.error(e.getMessage());
    } catch (TemplateException ex) {
        _log.error(ex.getMessage());
    }
}

From source file:de.ingrid.interfaces.csw.jobs.UpdateJob.java

/**
 * Write the last execution date of this job.
 *
 * @param Date/*from w ww .  j a v a  2s.c  o m*/
 */
public void writeLastExecutionDate(Date date) {
    File dateFile = new File(DATE_FILENAME);

    try {
        Writer output = new BufferedWriter(new FileWriter(dateFile));
        output.write(DATEFORMAT.format(date));
        output.close();
    } catch (Exception e) {
        // delete the date file to make sure we do not use a corrupted
        // version
        if (Files.exists(dateFile.toPath()))
            try {
                Files.delete(dateFile.toPath());
            } catch (IOException e1) {
                log.error("Could not remove " + dateFile + ".", e1);
            }
        log.warn(
                "Could not write to " + DATE_FILENAME + ". " + "The update job fetches all records next time.");
    }
}

From source file:com.github.cchacin.JsonSchemaProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    for (final Element element : roundEnv.getElementsAnnotatedWith(JsonSchema.class)) {
        final TypeElement classElement = (TypeElement) element;
        final PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();

        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                "annotated class: " + classElement.getQualifiedName(), element);

        final String fqClassName = classElement.getQualifiedName().toString();
        final String className = classElement.getSimpleName().toString();
        final String packageName = packageElement.getQualifiedName().toString();

        final JsonSchema jsonSchema = element.getAnnotation(JsonSchema.class);

        try {//from   w w w  . j a v a  2 s .  c  o  m
            final JsonNode node = new ObjectMapper().readTree(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream(jsonSchema.path()));
            vc.put("display", new DisplayTool());
            vc.put("json", node);

            vc.put("className", className);
            vc.put("packageName", packageName);

            final JavaFileObject jfo = filer.createSourceFile(fqClassName + "JsonSchema");

            processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                    "creating source file: " + jfo.toUri());
            final Writer writer = jfo.openWriter();

            processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                    "applying velocity template: " + vt.getName());

            vt.merge(vc, writer);

            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:cn.vlabs.umt.ui.actions.EditTemplateAction.java

public ActionForward saveTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from www.ja  va 2s  . c  o  m

    EditTemplateForm etForm = (EditTemplateForm) form;

    StringBuffer sb = new StringBuffer();
    sb.append(EmailTemplate.SIGN_TITLE).append(etForm.getTitle());
    sb.append(EmailTemplate.SIGN_CONTENT).append(etForm.getContent());

    String templateFileDir = request.getSession().getServletContext().getRealPath("/");
    boolean succ = true;
    try {
        String path = getConfig().getStringProp(EmailTemplate.TEMPLATE_DIR, "WEB-INF/message/");
        String localeddir = path + "/" + Locale.getDefault().toString();
        File f = new File(templateFileDir + localeddir);
        if (!f.exists()) {
            localeddir = path + "/zh_CN";
        }
        templateFileDir += localeddir + "/" + etForm.getTarget();

        Writer writer = new OutputStreamWriter(new FileOutputStream(templateFileDir), "UTF-8");
        writer.write(sb.toString());
        writer.flush();
        writer.close();

    } catch (Exception e) {
        succ = false;
        log.error(e.getLocalizedMessage());
    }

    EmailTemplate email = getEmailTemplate(request, etForm.getTarget());
    request.setAttribute("template", email);
    if (succ) {
        request.setAttribute("succ", "emailtempt.update.success");
    } else {
        request.setAttribute("succ", "emailtempt.update.error");
    }
    request.setAttribute("act", request.getParameter("reAct"));
    return mapping.getInputForward();
}

From source file:com.netxforge.oss2.config.SnmpInterfacePollerConfigFactory.java

/** {@inheritDoc} */
protected synchronized void saveXml(String xml) throws IOException {
    if (xml != null) {
        long timestamp = System.currentTimeMillis();
        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.SNMP_INTERFACE_POLLER_CONFIG_FILE_NAME);
        logStatic().debug("saveXml: saving config file at " + timestamp + ": " + cfgFile.getPath());
        Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8");
        fileWriter.write(xml);/*from   w  w  w. ja  v  a2  s .  co  m*/
        fileWriter.flush();
        fileWriter.close();
        logStatic().debug("saveXml: finished saving config file: " + cfgFile.getPath());
    }
}

From source file:com.misczak.joinmybridge.BridgeJSONSerializer.java

public void savePhoneBook(ArrayList<Bridge> bridgeList)
        throws JSONException, IOException, FileNotFoundException {

    JSONArray array = new JSONArray();

    for (Bridge b : bridgeList) {
        array.put(b.toJSON());//from   w  w  w.  ja v  a  2 s. c o  m
    }

    Writer writer = null;

    try {
        OutputStream out = mContext.openFileOutput(mFileName, Context.MODE_PRIVATE);
        writer = new OutputStreamWriter(out);
        writer.write(array.toString());

    } finally {
        if (writer != null) {
            writer.close();
        }
    }

}

From source file:net.itransformers.idiscover.v2.core.bgpdiscoverer.BGPMapNetworkDiscoverer.java

@Override
public NetworkDiscoveryResult discoverNetwork(List<ConnectionDetails> connectionDetailsList, int depth) {
    NetworkDiscoveryResult result = new NetworkDiscoveryResult();

    for (ConnectionDetails connectionDetails : connectionDetailsList) {

        if (!"javaMRT".equals(connectionDetails.getConnectionType())) {
            logger.debug("Connection details are not for javaMRTfile");

            return null;
        }/*from  ww w .  jav  a  2  s  .  c o m*/

        String pathToFile = connectionDetails.getParam("pathToFile");
        String version = connectionDetails.getParam("version");

        String[] args = new String[4];
        args[0] = "-f";

        args[1] = pathToFile;

        args[2] = "-o";
        String outputFile = "network.graphml";
        args[3] = outputFile;

        Map<String, String> params = CmdLineParser.parseCmdLine(args);

        StringWriter writer = new StringWriter();

        String file = null;
        OutputStream logOutputStream = new NullOutputStream();

        if (params.containsKey("-f")) {
            file = params.get("-f");
        } else {
            logger.info("no file passed");
            System.exit(1);
        }

        ASContainer ases = new ASContainer();
        System.out.println("Start reading MRT file");
        File tmpEdgeFile = null;
        try {
            tmpEdgeFile = File.createTempFile("test" + "_", ".txt");
            System.out.println("Creating edge tmp file: " + tmpEdgeFile.getAbsolutePath());
            Writer edgeWriter = new PrintWriter(tmpEdgeFile);

            Route2GraphmlDumper.dumpToXmlString(new String[] { file }, new PrintWriter(logOutputStream),
                    edgeWriter, ases);
            edgeWriter.close();
            Route2GraphmlDumper.dumpGraphml(ases, writer, tmpEdgeFile);

        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.

        } finally {
            tmpEdgeFile.delete();

        }

        NodeDiscoveryResult result1 = new NodeDiscoveryResult();

        result1.setDiscoveredData("version", version);
        result1.setDiscoveredData("graphml", writer.toString().getBytes());
        result1.setDiscoveredData("discoverer", "javaMRT");

        result.addDiscoveredData(file, result1);

    }
    fireNetworkDiscoveredEvent(result);

    return result;
}