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.heliosapm.benchmarks.json.JSONUnmarshalling.java

public static final ChannelBuffer serializeToBuffer(final ChannelBufferFactory bfactory,
        final Person... object) {
    if (object == null)
        throw new IllegalArgumentException("Object was null");
    OutputStream os = null;/*ww w  .j a  va2s  .c om*/
    Writer wos = null;
    try {
        //          final ChannelBuffer b = bfactory.getBuffer(1024);
        final ChannelBuffer b = ChannelBuffers.dynamicBuffer(PERSON_APPROX_SIZE * object.length, bfactory);
        os = new ChannelBufferOutputStream(b);
        wos = new OutputStreamWriter(os, UTF8);
        jsonMapper.writeValue(wos, object);
        return b;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (wos != null)
            try {
                wos.close();
            } catch (Exception x) {
                /* No Op */}
        if (os != null)
            try {
                os.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:io.sqp.core.jackson.JacksonMessageEncoder.java

public void encode(Writer writer, SqpMessage message) throws IOException {
    MessageType type = message.getType();
    try {//from  w w w  . j  a v a2s  .co m
        writer.write(type.getId());
    } catch (IOException e) {
        writer.close();
        throw e;
    }

    if (!type.hasContent()) {
        writer.close();
        return;
    }

    ObjectMapper mapper = JacksonObjectMapperFactory.objectMapper(DataFormat.Text);
    mapper.writeValue(writer, message);
}

From source file:com.amazonaws.codedeploy.AWSClients.java

private File createTestFile() throws IOException {
    File file = File.createTempFile("codedeploy-jenkins-plugin", ".txt");
    file.deleteOnExit();/*from w w w  . j  a v  a  2  s.  c  o m*/

    Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    writer.write("");
    writer.close();

    return file;
}

From source file:net.sf.taverna.cagrid.activity.CaGridActivity.java

/**
 * Load the trusted caGrid CAs' certificates and store them in 
 * the Truststore and in a special folder (inside Taverna's security 
 * conf folder) so that globus can look them up as well.
 *//*from  ww w  .ja  v  a 2  s . c  om*/
private static void loadCaGridCAsCertificates() {

    // If not already done, import the caGrid Trusted CAs' certificates into Taverna's truststore
    // Get the location of Taverna's security configuration directory
    File secConfigDirectory = CMUtil.getSecurityConfigurationDirectory();
    File caGridSecConfigDirectory = new File(secConfigDirectory, "cagrid");
    caGridSecConfigDirectory.mkdirs();
    // Tructes CAs folder
    File trustedCertsDirectory = new File(caGridSecConfigDirectory, "trusted-certificates");
    trustedCertsDirectory.mkdirs();

    // Set the system property read by Globus to determine the location 
    // of the folder containing the caGrid trusted CAs' certificates 
    System.setProperty("X509_CERT_DIR", trustedCertsDirectory.getAbsolutePath());

    // Get the file which existence implies that caGrid trusted CAs have been loaded
    File caCertsLoadedFile = new File(caGridSecConfigDirectory, "trustedCAsLoaded.txt");

    if (!caCertsLoadedFile.exists() || System.getenv("TWS_USER_PROXY") != null) {
        logger.info("caGrid plugin is loading trusted certificates \n of caGrid CAs into Credential Manager.");

        if (System.getenv("TWS_USER_PROXY") == null) {
            JOptionPane.showMessageDialog(null,
                    "caGrid plugin is loading trusted certificates \n of caGrid CAs into Credential Manager.",
                    "CaGrid plugin message", JOptionPane.INFORMATION_MESSAGE);
        }
        List<String> certificateResources = new ArrayList<String>();
        certificateResources.add("1c3f2ca8.0");
        certificateResources.add("62f4fd66.0");
        certificateResources.add("68907d53.0");
        certificateResources.add("8e3e7e54.0");
        certificateResources.add("d1b603c3.0");
        certificateResources.add("ed524cf5.0");
        certificateResources.add("0ad31d10.0");
        certificateResources.add("17e36bb5.0");
        certificateResources.add("f3b3491b.0");
        certificateResources.add("d0b62510.0");//to be replaced by its CA cert

        CredentialManager cm = null;
        try {
            //TODO something wrong here, needs correction
            cm = CredentialManager.getInstance();

        } catch (CMException cmex) {
            // We are in deep trouble here - something's wrong with Credential Manager
            String exMessage = "Failed to instantiate Credential Manager - cannot load caGrid CAs' certificates.";
            JOptionPane.showMessageDialog(null, exMessage, "CaGrid plugin message", JOptionPane.ERROR_MESSAGE);
            cmex.printStackTrace();
            logger.error(exMessage);
            return;
        }

        for (String certificate : certificateResources) {
            InputStream certStream = null;
            try {
                String certificateResourcePath = "/trusted-certificates/" + certificate;
                certStream = CaGridActivity.class.getResourceAsStream(certificateResourcePath);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                // The following should be able to load PKCS #7 certificate chain files
                // as well as ASN.1 DER or PEM-encoded (sequences of) certificates
                Collection<? extends Certificate> chain = cf.generateCertificates(certStream);
                certStream.close();
                // Use only the first cert in the chain - we know there will be only one inside 
                X509Certificate cert = (X509Certificate) chain.iterator().next();
                // Save to Credential Manager's Truststore
                cm.saveTrustedCertificate(cert);
                // Save to the trusted-certificates directory inside cagrid security conf directory
                File certificateFile = new File(trustedCertsDirectory, certificate);
                InputStream certStreamNew = null;
                BufferedOutputStream fOut = null;
                try {
                    // Reload the certificate resource
                    certStreamNew = CaGridActivity.class.getResourceAsStream(certificateResourcePath);
                    fOut = new BufferedOutputStream(new FileOutputStream(certificateFile));
                    IOUtils.copy(certStreamNew, fOut);
                } catch (Exception ex) {
                    String exMessage = "Failed to save caGrid CA's certificate " + certificate
                            + " to cagrid security folder " + certificateFile + " for globus.";
                    logger.error(exMessage, ex);
                } finally {
                    if (fOut != null) {
                        try {
                            fOut.close();
                        } catch (Exception ex) {
                            logger.error("Can't close certificate resource " + certificateFile, ex);
                        }
                    }
                    if (certStreamNew != null) {
                        try {
                            certStreamNew.close();
                        } catch (Exception ex) {
                            logger.error("Can't close certificate resource " + certificate, ex);
                        }
                    }
                }
            } catch (Exception ex) {
                String exMessage = "Failed to load or save caGrid CA's certificate " + certificate
                        + " to Truststore.";
                logger.error(exMessage, ex);
            }
        }
        Writer out = null;
        try {
            out = new BufferedWriter(new FileWriter(caCertsLoadedFile));
            out.write("true"); // just write anything to the file
        } catch (IOException e) {
            // ignore
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception ex) {
                // ignore
            }
        }
    }
}

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

/** {@inheritDoc} */
protected synchronized void saveXml(String xml) throws IOException {
    if (xml != null) {
        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.CAPSD_CONFIG_FILE_NAME);
        Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8");
        fileWriter.write(xml);/*from  w  ww .ja va  2  s. co m*/
        fileWriter.flush();
        fileWriter.close();
    }
}

From source file:com.natpryce.piazza.pluginConfiguration.PiazzaConfiguration.java

void writeElementTo(Element element, Writer writer) throws IOException {
    try {/*  w  ww  .  j a  v a 2 s .c  o m*/
        XMLOutputter outputter = new XMLOutputter();
        outputter.output(element, writer);
        writer.close();
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:com.facebook.hiveio.testing.LocalHiveServer.java

private File writeDataToFile(String tableName, String[] data) throws IOException {
    File dataFile = new File(rootDir(), tableName);
    Writer writer = Files.newWriter(dataFile, Charsets.UTF_8);
    for (String line : data) {
        writer.write(line);//from   ww  w .j  a  v a2s .co  m
        writer.write("\n");
    }
    writer.close();
    return dataFile;
}

From source file:com.streamsets.datacollector.http.TestLogServlet.java

private String startServer() throws Exception {
    try {/*from w  w w .  ja va2 s  . c  om*/
        logFile = new File(baseDir, "test.log");
        Writer writer = new FileWriter(logFile);
        writer.write("hello\n");
        writer.close();
        Thread.sleep(1000); // for log files to have different lastModified timestamp
        oldLogFile = new File(baseDir, "test.log.1");
        writer = new FileWriter(oldLogFile);
        writer.write("bye\n");
        writer.close();
        File log4fConfig = new File(baseDir, "log4j.properties");
        writer = new FileWriter(log4fConfig);
        writer.write(LogUtils.LOG4J_APPENDER_STREAMSETS_FILE_PROPERTY + "=" + logFile.getAbsolutePath() + "\n");
        writer.write(LogUtils.LOG4J_APPENDER_STREAMSETS_LAYOUT_CONVERSION_PATTERN + "=" + CONVERSION_PATTERN);
        writer.close();

        int port = getRandomPort();
        Configuration conf = new Configuration();
        conf.set(WebServerTask.HTTP_PORT_KEY, port);
        conf.set(WebServerTask.AUTHENTICATION_KEY, "none");
        writer = new FileWriter(
                new File(System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR),
                        "sdc.properties"));
        conf.save(writer);
        writer.close();
        ObjectGraph dagger = ObjectGraph.create(MainStandalonePipelineManagerModule.class);
        RuntimeInfo runtimeInfo = dagger.get(RuntimeInfo.class);
        runtimeInfo.setAttribute(RuntimeInfo.LOG4J_CONFIGURATION_URL_ATTR,
                new URL("file://" + baseDir + "/log4j.properties"));
        server = dagger.get(TaskWrapper.class);

        server.init();
        server.run();
        return "http://127.0.0.1:" + port;
    } catch (Exception e) {
        System.out.println("Got exception " + e);
        return null;
    }
}

From source file:iotest.ModifyArtifactsTest.java

@Test
public void modifyAppServletXml()
        throws UnsupportedEncodingException, FileNotFoundException, IOException, JDOMException {

    System.out.println("please select app-servlet.xml file ");
    JFileChooser fc = new JFileChooser();
    int retValue = fc.showOpenDialog(new JPanel());
    if (retValue == JFileChooser.APPROVE_OPTION) {
        File f = fc.getSelectedFile();

        SAXBuilder builder = new SAXBuilder();

        Document document = (Document) builder.build(f);
        Element rootNode = document.getRootElement();

        List<Element> list = rootNode.getChildren("component-scan",
                Namespace.getNamespace("http://www.springframework.org/schema/context"));

        Element e = list.get(0);//from w  w w  .jav  a 2s.  c  o m

        String cnt = "<context:exclude-filter type=\"regex\" expression=\"pegasus\\.module\\.jfilelooder\\..*\" />";

        e.addContent(cnt);

        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()) {
            @Override
            public String escapeElementEntities(String str) {
                return str;
            }
        };

        Writer writer = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
        outputter.output(document, writer);
        writer.close();
    } else {
        System.out.println("Next time select a file.");
        System.exit(1);
    }

}

From source file:de.mpg.escidoc.services.fledgeddata.webservice.oaiServlet.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well.
 * The verb widget is taken from the request and used to invoke an
 * OAIVerb object of the corresponding kind to do the actual work of the verb.
 *
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */// w  ww  . java2 s  .  co m
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean serviceUnavailable = isServiceUnavailable();
    HashMap serverVerbs = ServerVerb.getVerbs();
    request.setCharacterEncoding("UTF-8");

    if (serviceUnavailable) {
        LOGGER.info("[FDS] oai servcice set to 'unavailable' in properties file.");
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "[FDS] Sorry. This server is down for maintenance");
    } else {
        try {
            String result = getResult(request, response, serverVerbs);
            Writer out = getWriter(request, response);
            out.write(result);
            out.close();

        } catch (OAIInternalServerError e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (SocketException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}