Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

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

Prototype

public PrintStream(File file) throws FileNotFoundException 

Source Link

Document

Creates a new print stream, without automatic line flushing, with the specified file.

Usage

From source file:Clases.cCifrado.java

public String pedirClave(String dato) {

    String clave = "";
    Scanner sc = new Scanner(System.in);
    Socket socket;/*from   ww w. j  av a  2  s  .c o  m*/
    try {
        String ipServidor = receptor;
        int pto = puerto;
        System.out.println("conectando con el servidor...");
        socket = new Socket(ipServidor, pto);
        Scanner entrada = new Scanner(socket.getInputStream());
        PrintStream salidaServer = new PrintStream(socket.getOutputStream());
        salidaServer.println(dato);
        clave = entrada.nextLine();
        System.out.println("Dato recibido: " + clave);
        socket.close();

    } catch (IOException ex) {
        System.err.println("Cliente> " + ex.getMessage());
    }
    return clave;
}

From source file:de.fau.cs.osr.hddiff.utils.HDDiffTreeVisualizer.java

private void drawDotGraph(File output, DiffNode root1, DiffNode root2) {
    nextColor = 0;/*from   ww w. ja va  2s.  c  o  m*/
    File dotFile;
    try {
        dotFile = new File(URLEncoder.encode(output.getPath(), "UTF-8") + ".dot");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        return;
    }
    try (PrintStream ps = new PrintStream(dotFile)) {
        ps.println("digraph G {");

        drawNode(ps, "t1", root1, 0);
        drawNode(ps, "t2", root2, 0);

        ps.println("}");
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    callDot(dotFile);
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineToolTest.java

@Test
public void testMain_latexml_non_operators() throws Exception {

    String testFile = "latexml";

    String[] argv = { getTestResourceAsFilepath(testFile + ".input.xml") };

    ByteArrayOutputStream stdoutContent = new ByteArrayOutputStream();
    PrintStream stdout = System.out;

    System.setOut(new PrintStream(stdoutContent));
    MathMLUnificatorCommandLineTool.main(argv);
    System.setOut(stdout);//w  w  w.  j  a v a2 s .c  o  m

    String output = stdoutContent.toString(StandardCharsets.UTF_8.toString());

    System.out.println("testMain_latexml_non_operators  non-operators output:\n" + output);
    assertEquals(
            IOUtils.toString(getExpectedXMLTestResource(testFile + ".non-operator"), StandardCharsets.UTF_8),
            output);

}

From source file:com.thoughtworks.go.agent.bootstrapper.AgentBootstrapperFunctionalTest.java

@Test
public void shouldLoadAndBootstrapJarUsingAgentBootstrapCode_specifiedInAgentManifestFile() throws Exception {
    if (!OS_CHECKER.satisfy()) {
        PrintStream err = System.err;
        try {//ww  w.j  a  v a  2s . c  o  m
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            System.setErr(new PrintStream(os));
            File agentJar = new File("agent.jar");
            agentJar.delete();
            new AgentBootstrapper() {
                @Override
                void jvmExit(int returnValue) {
                }
            }.go(false,
                    new AgentBootstrapperArgs(new URL("http://" + "localhost" + ":" + server.getPort() + "/go"),
                            null, AgentBootstrapperArgs.SslMode.NONE));
            agentJar.delete();
            assertThat(new String(os.toByteArray()), containsString("Hello World Fellas!"));
        } finally {
            System.setErr(err);
        }
    }
}

From source file:edu.vt.middleware.crypt.signature.SignatureCliTest.java

/**
 * @param  partialLine  Partial command line.
 * @param  pubKey  Public key file./*w ww . j  av a2 s .c om*/
 * @param  privKey  Private key file.
 *
 * @throws  Exception  On test failure.
 */
@Test(groups = { "cli", "signature" }, dataProvider = "testdata")
public void testSignatureCli(final String partialLine, final String pubKey, final String privKey)
        throws Exception {
    final String pubKeyPath = KEY_DIR_PATH + pubKey;
    final String privKeyPath = KEY_DIR_PATH + privKey;
    final PrintStream oldStdOut = System.out;
    try {
        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outStream));

        // Compute signature and verify it
        String fullLine = partialLine + " -sign " + " -key " + privKeyPath + " -in " + TEST_PLAINTEXT;
        logger.info("Testing signature CLI sign operation with command line:\n\t" + fullLine);
        SignatureCli.main(CliHelper.splitArgs(fullLine));

        final String sig = outStream.toString();
        Assert.assertTrue(sig.length() > 0);

        // Write signature out to file for use in verify step
        new File(TEST_OUTPUT_DIR).mkdir();

        final File sigFile = new File(TEST_OUTPUT_DIR + "sig.out");
        final BufferedOutputStream sigOs = new BufferedOutputStream(new FileOutputStream(sigFile));
        try {
            sigOs.write(outStream.toByteArray());
        } finally {
            sigOs.close();
        }
        outStream.reset();

        // Verify signature
        fullLine = partialLine + " -verify " + sigFile + " -key " + pubKeyPath + " -in " + TEST_PLAINTEXT;
        logger.info("Testing signature CLI verify operation with command " + "line:\n\t" + fullLine);
        SignatureCli.main(CliHelper.splitArgs(fullLine));

        final String result = outStream.toString();
        AssertJUnit.assertTrue(result.indexOf("SUCCESS") != -1);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // Restore STDOUT
        System.setOut(oldStdOut);
    }
}

From source file:li.klass.fhem.fhem.TelnetConnection.java

public RequestResult<String> executeCommand(String command, Context context) {
    LOG.info("executeTask command {}", command);

    final TelnetClient telnetClient = new TelnetClient();
    telnetClient.setConnectTimeout(getConnectionTimeoutMilliSeconds(context));

    BufferedOutputStream bufferedOutputStream = null;
    PrintStream printStream = null;

    String errorHost = serverSpec.getIp() + ":" + serverSpec.getPort();
    try {/*w  w  w.j  a va 2s.  co m*/
        telnetClient.connect(serverSpec.getIp(), serverSpec.getPort());

        OutputStream outputStream = telnetClient.getOutputStream();
        InputStream inputStream = telnetClient.getInputStream();

        bufferedOutputStream = new BufferedOutputStream(outputStream);
        printStream = new PrintStream(outputStream);

        boolean passwordSent = false;
        String passwordRead = readUntil(inputStream, PASSWORD_PROMPT);
        if (passwordRead != null && passwordRead.contains(PASSWORD_PROMPT)) {
            LOG.info("sending password");
            writeCommand(printStream, serverSpec.getPassword());
            passwordSent = true;
        }

        writeCommand(printStream, "\n\n");

        if (!waitForFilledStream(inputStream, 5000)) {
            return new RequestResult<>(RequestResultError.HOST_CONNECTION_ERROR);
        }

        // to discard
        String toDiscard = read(inputStream);
        LOG.debug("discarding {}", toDiscard);

        writeCommand(printStream, command);

        // If we send an xmllist, we are done when finding the closing FHZINFO tag.
        // If another command is used, the tag ending delimiter is obsolete, not found and
        // therefore not used. We just read until the stream ends.
        String result;
        if (command.equals("xmllist")) {
            result = readUntil(inputStream, "</FHZINFO>");
        } else {
            result = read(inputStream);
        }

        if (result == null && passwordSent) {
            return new RequestResult<>(RequestResultError.AUTHENTICATION_ERROR);
        } else if (result == null) {
            return new RequestResult<>(RequestResultError.INVALID_CONTENT);
        }

        telnetClient.disconnect();

        int startPos = result.indexOf(", try help");
        if (startPos != -1) {
            result = result.substring(startPos + ", try help".length());
        }

        startPos = result.indexOf("<");
        if (startPos != -1) {
            result = result.substring(startPos);
        }

        result = result.replaceAll("Bye...", "").replaceAll("fhem>", "");
        result = new String(result.getBytes("UTF8"));
        LOG.debug("result is {}", result);

        return new RequestResult<>(result);

    } catch (SocketTimeoutException e) {
        LOG.error("timeout", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.CONNECTION_TIMEOUT);
    } catch (UnsupportedEncodingException e) {
        // this may never happen, as UTF8 is known ...
        setErrorInErrorHolderFor(e, errorHost, command);
        throw new IllegalStateException("unsupported encoding", e);
    } catch (SocketException e) {
        // We handle host connection errors directly after connecting to the server by waiting
        // for some token for some seconds. Afterwards, the only possibility for an error
        // is that the FHEM server ends the connection after receiving an invalid password.
        LOG.error("SocketException", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.AUTHENTICATION_ERROR);
    } catch (IOException e) {
        LOG.error("IOException", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.HOST_CONNECTION_ERROR);
    } finally {
        CloseableUtil.close(printStream, bufferedOutputStream);
    }
}

From source file:edu.byu.softwareDist.manager.impl.SendEmailImpl.java

private static File saveTemplateToDisk(final FileSet fileSet) {
    File f = null;//from  www.  j a va 2  s  . co m
    PrintStream out = null;
    try {
        f = File.createTempFile("software-distribution-email-content." + fileSet.getFileSetId() + "-", ".vm");
        out = new PrintStream(new FileOutputStream(f));
        out.print(fileSet.getEmailContent());
        out.flush();
        return f;
    } catch (IOException e) {
        LOG.error("Error writing template to temporary file.", e);
        return null;
    } finally {
        if (f != null) {
            f.deleteOnExit();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.ryantenney.metrics.spring.ReporterTest.java

public static PrintStream testPrintStream() {
    return new PrintStream(new ByteArrayOutputStream());
}

From source file:com.artnaseef.jmeter.report.ResultCodesPerSecondReport.java

@Override
public void onFeedStart(String uri, Properties reportProperties) throws Exception {
    this.feedUri = uri;

    this.extractReportProperties(reportProperties);

    this.chartSeries = new LinkedList<>();
    this.samplesByReportCode = new TreeMap<>();
    this.dataset = new XYSeriesCollection();

    if (this.detailOutputFile != null) {
        this.detailFileWriter = new PrintStream(this.detailOutputFile);
    }/*w  ww  .  j  a  v a2s.  co  m*/
}

From source file:com.stimulus.archiva.index.VolumeIndex.java

public VolumeIndex(Indexer indexer, Volume volume) {
    logger.debug("creating new volume index {" + volume + "}");
    this.volume = volume;
    this.indexer = indexer;
    try {// w  ww .  j a v  a2  s .  co  m
        indexLogFile = getIndexLogFile(volume);
        if (indexLogFile != null) {
            if (indexLogFile.length() > 10485760)
                indexLogFile.delete();
            indexLogOut = new PrintStream(indexLogFile);
        }
        logger.debug("set index log file path {path='" + indexLogFile.getCanonicalPath() + "'}");
    } catch (Exception e) {
        logger.error("failed to open index log file:" + e.getMessage(), e);
    }
    startup();
}