Example usage for java.io PrintStream close

List of usage examples for java.io PrintStream close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the stream.

Usage

From source file:org.apache.hadoop.fs.CopyOfTestDFSIO.java

private void analyzeResult(FileSystem fs, TestType testType, long execTime, String resFileName)
        throws IOException {
    Path reduceFile = getReduceFilePath(testType);
    long tasks = 0;
    long size = 0;
    long time = 0;
    float rate = 0;
    float sqrate = 0;
    DataInputStream in = null;/*ww w  . j a  va 2s .com*/
    BufferedReader lines = null;
    StringBuffer IOTime = new StringBuffer(500);
    try {

        in = new DataInputStream(fs.open(reduceFile));
        lines = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = lines.readLine()) != null) {
            StringTokenizer tokens = new StringTokenizer(line, " \t\n\r\f%");
            String attr = tokens.nextToken();
            if (attr.endsWith(":tasks"))
                tasks = Long.parseLong(tokens.nextToken());
            else if (attr.endsWith(":size"))
                size = Long.parseLong(tokens.nextToken());
            else if (attr.endsWith(":time"))
                time = Long.parseLong(tokens.nextToken());
            else if (attr.endsWith(":rate"))
                rate = Float.parseFloat(tokens.nextToken());
            else if (attr.endsWith(":sqrate"))
                sqrate = Float.parseFloat(tokens.nextToken());
            else if (attr.contains(":EachIOtime")) {
                IOTime.append("\n");
                IOTime.append(line.split(":")[0] + "\t" + line.split(":")[2]);
            }
        }
    } finally {
        if (in != null)
            in.close();
        if (lines != null)
            lines.close();
    }

    double med = rate / 1000 / tasks;
    double stdDev = Math.sqrt(Math.abs(sqrate / 1000 / tasks - med * med));
    String resultLines[] = { "----- TestDFSIO ----- : " + testType,
            "           Date & time: " + new Date(System.currentTimeMillis()),
            "       Number of files: " + tasks, "Total MBytes processed: " + toMB(size),
            "file.blocksize: " + config.get("file.blocksize"),
            "dfs.replication: " + config.get("dfs.replication"),
            "     Throughput mb/sec: " + size * 1000.0 / (time * MEGA), "Average IO rate mb/sec: " + med,
            " IO rate std deviation: " + stdDev, "    Test exec time sec: " + (float) execTime / 1000,
            IOTime.toString() };

    PrintStream res = null;
    try {
        res = new PrintStream(new FileOutputStream(new File(resFileName), true));
        for (int i = 0; i < resultLines.length; i++) {
            LOG.info(resultLines[i]);
            res.println(resultLines[i]);
        }
    } finally {
        if (res != null)
            res.close();
    }
}

From source file:hudson.plugins.jobConfigHistory.FileHistoryDao.java

/**
 * Creates a new history entry and saves the slave configuration.
 *
 * @param node node.//from  w  w  w .j ava2  s. co  m
 * @param content content.
 * @param operation operation.
 */
void createNewHistoryEntryAndSaveConfig(Node node, String content, final String operation) {
    final File timestampedDir = createNewHistoryEntry(node, operation);
    final File nodeConfigHistoryFile = new File(timestampedDir, "config.xml");
    PrintStream stream = null;
    try {
        stream = new PrintStream(nodeConfigHistoryFile);
        stream.print(content);
    } catch (IOException ex) {
        throw new RuntimeException("Unable to write " + nodeConfigHistoryFile, ex);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }

}

From source file:org.apache.hive.beeline.TestBeeLineWithArgs.java

/**
 * Attempt to execute a simple script file with the -f or -i option
 * to BeeLine (or both) to  test for presence of an expected pattern
 * in the output (stdout or stderr), fail if not found.
 * Print PASSED or FAILED//w  w w.  j av a  2 s. c  om
 * @param scriptText script to test the output for
 * @param argList arguments to be passed to the script file to execute and produce output
 * @param streamType Whether match should be done against STDERR or STDOUT
 * @param expectedMatches List of Tuple's defining the pattern to match and result of matching
 * @param modes testing modes we have to run the script as
 * @throws Exception on command execution error
 */
private void testScriptFile(String scriptText, List<String> argList, OutStream streamType,
        List<Tuple<String>> expectedMatches, List<Modes> modes) throws Throwable {
    // Put the script content in a temp file
    File scriptFile = File.createTempFile(this.getClass().getSimpleName(), "temp");
    System.out.println("script file is " + scriptFile.getAbsolutePath());
    scriptFile.deleteOnExit();
    PrintStream os = new PrintStream(new FileOutputStream(scriptFile));
    os.print(scriptText);
    os.close();

    List<Tuple<Pattern>> patternsToBeMatched = Lists.transform(expectedMatches,
            new Function<Tuple<String>, Tuple<Pattern>>() {
                @Override
                public Tuple<Pattern> apply(Tuple<String> tuple) {
                    return new Tuple<>(Pattern.compile(".*" + tuple.pattern + ".*", Pattern.DOTALL),
                            tuple.shouldMatch);
                }
            });

    for (Modes mode : modes) {
        String output = mode.output(scriptFile, argList, streamType);
        for (Tuple<Pattern> patternToMatch : patternsToBeMatched) {
            Matcher m = patternToMatch.pattern.matcher(output);
            boolean matches = m.matches();
            if (patternToMatch.shouldMatch != matches) {
                //failed
                fail("Output" + output + " should" + (patternToMatch.shouldMatch ? "" : " not") + " contain "
                        + patternToMatch.pattern.pattern());
            }
        }
    }
    scriptFile.delete();
}

From source file:it.greenvulcano.jmx.impl.KarafJMXEntryPoint.java

/**
 * Initializes the modeler./*from   w ww . ja v  a 2 s.  co  m*/
 */
private void initModeler(Node conf) throws Exception {
    // The modeler requires an InputStream in order to configure itself,
    // so we need to serialize the configuration.

    DOMWriter writer = new DOMWriter();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream print = new PrintStream(out);

    // Read the DTD and put it in the out stream, in order to avoid the
    // exceptions
    // raised by the XML parser.
    //
    InputStream istream = getClass().getClassLoader().getResourceAsStream(MODELER_DTD);
    if (istream != null) {
        byte[] buf = new byte[2048];
        int l = 0;
        while ((l = istream.read(buf)) != -1) {
            print.write(buf, 0, l);
        }
        print.flush();
        istream.close();
    } else {
        LOG.warn(MODELER_DTD + " NOT FOUND. PLEASE, IGNORE FOLLOWING EXCEPTIONS.");
    }

    writer.write(conf, print);
    print.flush();
    print.close();

    // Prepares the input stream and initializes the modeler's Registry
    //
    ByteArrayInputStream stream = new ByteArrayInputStream(out.toByteArray());
    registry.loadDescriptors(stream);
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

/** Send a SOAP request to the registry server. Main entry point for
 * this class. If credentials have been set on the registry connection,
 * they will be used to sign the request.
 *
 * @param requestString//from   w w  w  .  ja v a2  s . co m
 *     String that will be placed in the body of the
 *     SOAP message to be sent to the server
 *
 * @param attachments
 *     HashMap consisting of entries each of which
 *     corresponds to an attachment where the entry key is the ContentId
 *     and the entry value is a javax.activation.DataHandler of the
 *     attachment. A parameter value of null means no attachments.
 *
 * @return
 *     RegistryResponseHolder that represents the response from the
 *     server
 */
@SuppressWarnings("unchecked")
public RegistryResponseHolder sendSoapRequest(String requestString, Map<?, ?> attachments)
        throws JAXRException {
    boolean logRequests = Boolean.valueOf(
            CommonProperties.getInstance().getProperty("eric.common.soapMessenger.logRequests", "false"))
            .booleanValue();

    if (logRequests) {
        PrintStream requestLogPS = null;
        try {
            requestLogPS = new PrintStream(
                    new FileOutputStream(java.io.File.createTempFile("SOAPMessenger_requestLog", ".xml")));
            requestLogPS.println(requestString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (requestLogPS != null) {
                requestLogPS.close();
            }
        }
    }

    // =================================================================

    //        // Remove the XML Declaration, if any
    //        if (requestString.startsWith("<?xml")) {
    //            requestString = requestString.substring(requestString.indexOf("?>")+2).trim();
    //        }
    //
    //        StringBuffer soapText = new StringBuffer(
    //                "<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
    //
    //      soapText.append("<soap-env:Header>\n");
    //      // tell server about our superior SOAP Fault capabilities
    //      soapText.append("<");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(" xmlns='");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
    //      soapText.append("'>");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);
    //      soapText.append("</");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(">\n");
    //      soapText.append("</soap-env:Header>\n");

    //      soapText.append("<soap-env:Body>\n");
    //        soapText.append(requestString);
    //        soapText.append("</soap-env:Body>");
    //        soapText.append("</soap-env:Envelope>");

    MessageFactory messageFactory;
    SOAPMessage message = null;
    SOAPPart sp = null;
    SOAPEnvelope se = null;
    SOAPBody sb = null;
    SOAPHeader sh = null;

    if (log.isTraceEnabled()) {
        log.trace("requestString=\"" + requestString + "\"");
    }
    try {

        messageFactory = MessageFactory.newInstance();
        message = messageFactory.createMessage();

        sp = message.getSOAPPart();
        se = sp.getEnvelope();
        sb = se.getBody();
        sh = se.getHeader();

        /*
         * <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
         *       <soap-env:Header>
         *          <capabilities xmlns="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</capabilities>
         *
         * change with explicit namespace
         *          <ns1:capabilities xmlns:ns1="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</ns1:capabilities>
                
         */
        SOAPHeaderElement capabilityElement = sh
                .addHeaderElement(se.createName(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName, "ns1",
                        BindingUtility.SOAP_CAPABILITY_HEADER_Namespace));
        //           capabilityElement.addAttribute(
        //                 se.createName("xmlns"), 
        //                 BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
        capabilityElement.setTextContent(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);

        /*
         * body
         */

        // Remove the XML Declaration, if any
        if (requestString.startsWith("<?xml")) {
            requestString = requestString.substring(requestString.indexOf("?>") + 2).trim();
        }

        // Generate DOM Document from request xml string
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        InputStream stream = new ByteArrayInputStream(requestString.getBytes("UTF-8"));

        // Inject request into body
        sb.addDocument(builderFactory.newDocumentBuilder().parse(stream));

        // Is it never the case that there attachments but no credentials
        if ((attachments != null) && !attachments.isEmpty()) {
            addAttachments(message, attachments);
        }

        if (credentialInfo == null) {
            throw new JAXRException(resourceBundle.getString("message.credentialInfo"));
        }

        WSS4JSecurityUtilSAML.signSOAPEnvelopeOnClientSAML(se, credentialInfo);

        SOAPMessage response = send(message);

        // Check to see if the session has expired
        // by checking for an error response code
        // TODO: what error code to we look for?
        if (isSessionExpired(response)) {
            credentialInfo.sessionId = null;
            // sign the SOAPMessage this time
            // TODO: session - add method to do the signing
            // signSOAPMessage(msg);
            // send signed message
            // SOAPMessage response = send(msg);
        }

        // Process the main SOAPPart of the response
        //check for soapfault and throw RegistryException
        SOAPFault fault = response.getSOAPBody().getFault();
        if (fault != null) {
            throw createRegistryException(fault);
        }

        Reader reader = processResponseBody(response, "Response");

        RegistryResponseType ebResponse = null;

        try {
            Object obj = BindingUtility.getInstance().getJAXBContext().createUnmarshaller()
                    .unmarshal(new InputSource(reader));

            if (obj instanceof JAXBElement<?>)
                // if Element: take ComplexType from Element
                obj = ((JAXBElement<RegistryResponseType>) obj).getValue();

            ebResponse = (RegistryResponseType) obj;
        } catch (Exception x) {
            log.error(CommonResourceBundle.getInstance().getString("message.FailedToUnmarshalServerResponse"),
                    x);
            throw new JAXRException(resourceBundle.getString("message.invalidServerResponse"));
        }

        // Process the attachments of the response if any
        HashMap<String, Object> responseAttachments = processResponseAttachments(response);

        return new RegistryResponseHolder(ebResponse, responseAttachments);

    } catch (SAXException e) {
        throw new JAXRException(e);

    } catch (ParserConfigurationException e) {
        throw new JAXRException(e);

    } catch (UnsupportedEncodingException x) {
        throw new JAXRException(x);

    } catch (MessagingException x) {
        throw new JAXRException(x);

    } catch (FileNotFoundException x) {
        throw new JAXRException(x);

    } catch (IOException e) {
        throw new JAXRException(e);

    } catch (SOAPException x) {
        x.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.cannotConnect"), x);

    } catch (TransformerConfigurationException x) {
        throw new JAXRException(x);

    } catch (TransformerException x) {
        throw new JAXRException(x);
    }
}

From source file:net.rim.ejde.internal.ui.views.profiler.ProfilerView.java

private void saveRawData(File xmlFile) {
    RIA ria = RIA.getCurrentDebugger();//w  ww  .j av  a 2  s.  co m
    if (ria == null) {
        return;
    }
    if (xmlFile == null) {
        return;
    }
    if (!xmlFile.exists()) {
        xmlFile = ProjectUtils.createFile(xmlFile);
        if (xmlFile == null || !xmlFile.exists()) {
            return;
        }
    }
    PrintStream out = null;
    try {
        out = new PrintStream(new FileOutputStream(xmlFile));
        ria.profileDumpRawXML(out);
    } catch (Exception e) {
        log.error(e);
        MessageDialog.openError(ContextManager.getActiveWorkbenchShell(), Messages.ErrorHandler_DIALOG_TITLE,
                e.getMessage());
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.TestContainerLaunch.java

/**
 * Test that script exists with non-zero exit code when command fails.
 * @throws IOException/*from  ww w  . j  a v a  2 s .co m*/
 */
@Test(timeout = 10000)
public void testShellScriptBuilderNonZeroExitCode() throws IOException {
    ShellScriptBuilder builder = ShellScriptBuilder.create();
    builder.command(Arrays.asList(new String[] { "unknownCommand" }));
    File shellFile = Shell.appendScriptExtension(tmpDir, "testShellScriptBuilderError");
    PrintStream writer = new PrintStream(new FileOutputStream(shellFile));
    builder.write(writer);
    writer.close();
    try {
        FileUtil.setExecutable(shellFile, true);

        Shell.ShellCommandExecutor shexc = new Shell.ShellCommandExecutor(
                new String[] { shellFile.getAbsolutePath() }, tmpDir);
        try {
            shexc.execute();
            fail("builder shell command was expected to throw");
        } catch (IOException e) {
            // expected
            System.out.println("Received an expected exception: " + e.getMessage());
        }
    } finally {
        FileUtil.fullyDelete(shellFile);
    }
}

From source file:org.apache.hadoop.metrics2.sink.RollingFileSystemSink.java

/**
 * Schedule the current interval's directory to be flushed. If this ends up
 * running after the top of the next interval, it will execute immediately.
 *
 * @param when the time the thread should run
 *//*from  w ww .  jav  a  2  s  .  co m*/
private void scheduleFlush(Date when) {
    // Store the current currentDirPath to close later
    final PrintStream toClose = currentOutStream;

    flushTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            synchronized (lock) {
                // This close may have already been done by a putMetrics() call. If it
                // has, the PrintStream will swallow the exception, which is fine.
                toClose.close();
            }

            hasFlushed = true;
        }
    }, when);
}

From source file:org.apache.hadoop.yarn.server.nodemanager.DockerContainerExecutor.java

@Override
/**/*from   ww  w  .  j  a  va2 s .  c  o  m*/
 * Filter the environment variables that may conflict with the ones set in
 * the docker image and write them out to an OutputStream.
 */
public void writeLaunchEnv(OutputStream out, Map<String, String> environment, Map<Path, List<String>> resources,
        List<String> command, Path logDir) throws IOException {
    ContainerLaunch.ShellScriptBuilder sb = ContainerLaunch.ShellScriptBuilder.create();

    //Remove environments that may conflict with the ones in Docker image.
    Set<String> exclusionSet = new HashSet<String>();
    exclusionSet.add(YarnConfiguration.NM_DOCKER_CONTAINER_EXECUTOR_IMAGE_NAME);
    exclusionSet.add(ApplicationConstants.Environment.HADOOP_YARN_HOME.name());
    exclusionSet.add(ApplicationConstants.Environment.HADOOP_COMMON_HOME.name());
    exclusionSet.add(ApplicationConstants.Environment.HADOOP_HDFS_HOME.name());
    exclusionSet.add(ApplicationConstants.Environment.HADOOP_CONF_DIR.name());
    exclusionSet.add(ApplicationConstants.Environment.JAVA_HOME.name());

    if (environment != null) {
        for (Map.Entry<String, String> env : environment.entrySet()) {
            if (!exclusionSet.contains(env.getKey())) {
                sb.env(env.getKey().toString(), env.getValue().toString());
            }
        }
    }
    if (resources != null) {
        for (Map.Entry<Path, List<String>> entry : resources.entrySet()) {
            for (String linkName : entry.getValue()) {
                sb.symlink(entry.getKey(), new Path(linkName));
            }
        }
    }

    // dump debugging information if configured
    if (getConf() != null && getConf().getBoolean(YarnConfiguration.NM_LOG_CONTAINER_DEBUG_INFO,
            YarnConfiguration.DEFAULT_NM_LOG_CONTAINER_DEBUG_INFO)) {
        sb.copyDebugInformation(new Path(ContainerLaunch.CONTAINER_SCRIPT),
                new Path(logDir, ContainerLaunch.CONTAINER_SCRIPT));
        sb.listDebugInformation(new Path(logDir, DIRECTORY_CONTENTS));
    }

    sb.command(command);

    PrintStream pout = null;
    PrintStream ps = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        pout = new PrintStream(out, false, "UTF-8");
        if (LOG.isDebugEnabled()) {
            ps = new PrintStream(baos, false, "UTF-8");
            sb.write(ps);
        }
        sb.write(pout);

    } finally {
        if (out != null) {
            out.close();
        }
        if (ps != null) {
            ps.close();
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Script: " + baos.toString("UTF-8"));
    }
}

From source file:net.sf.vntconverter.VntConverter.java

/**
 * Enkodiert eine UTF-8-Textdatei in eine vNote-Datei.
 *//*from   ww  w . j  a va  2 s. c om*/
private void encode(File in, File out) {
    PrintStream ps = null;
    try {
        ps = new PrintStream(out, "UTF-8");
        ps.println("BEGIN:VNOTE");
        ps.println("VERSION:1.1");
        String content = getFileContent(in);
        String encodedContent = "BODY;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:" + encode(content);
        while (encodedContent.length() > 0) {
            if (encodedContent.length() > 74) {
                ps.println(encodedContent.substring(0, 74) + "=");
                encodedContent = encodedContent.substring(74);
            } else {
                ps.println(encodedContent);
                encodedContent = "";
            }
        }
        String lastModified = VNT_DATE_FORMAT.format(new Date(out.lastModified()));
        ps.println("DCREATED:" + lastModified);
        ps.println("LAST-MODIFIED:" + lastModified);
        ps.println("END:VNOTE");
    } catch (Exception e) {
        throw new RuntimeException("Exception caught in VntConverter.encode(in, out):", e);
    } finally {
        if (ps != null) {
            ps.close();
        }
    }
}