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, Charset charset) throws IOException 

Source Link

Document

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

Usage

From source file:com.sap.prd.mobile.ios.mios.ForkerTest.java

@Test(expected = IllegalArgumentException.class)
public void testMissingArguments_2() throws Exception {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final PrintStream log = new PrintStream(out, true);

    try {/*from w  w w.j a  v a2  s  .c om*/

        Forker.forkProcess(log, new File(".").getAbsoluteFile(), new String[0]);

    } finally {
        log.close();
    }
}

From source file:com.jayway.restassured.itest.java.GivenWhenThenLoggingITest.java

@Test
public void logResponseThatHasCookiesWithLogDetailCookiesUsingGivenWhenThenSyntax() throws Exception {
    final StringWriter writer = new StringWriter();
    final PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);
    given().config(config().logConfig(logConfig().defaultStream(captor).and().enablePrettyPrinting(false)))
            .when().get("/multiCookie").then().log().cookies().body(equalTo("OK"));
    assertThat(writer.toString(), allOf(startsWith(
            "cookie1=cookieValue1;Domain=localhost\ncookie1=cookieValue2;Comment=\"My Purpose\";Path=/;Domain=localhost;Max-Age=1234567;Secure;Expires="),
            endsWith(";Version=1" + LINE_SEPARATOR)));
}

From source file:io.restassured.itest.java.LogIfValidationFailsITest.java

@Test
public void worksForRequestSpecificationsUsingGivenWhenThenSyntax() throws Exception {
    final StringWriter writer = new StringWriter();
    final PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);

    try {//  w w  w.j a  va2  s.c om
        RestAssured.given().config(RestAssured.config().logConfig(LogConfig.logConfig().defaultStream(captor)))
                .log().ifValidationFails().param("firstName", "John").param("lastName", "Doe")
                .header("Content-type", "application/json").when().get("/greet").then().statusCode(400);

        fail("Should throw AssertionError");
    } catch (AssertionError e) {
        assertThat(writer.toString(), equalTo("Request method:\tGET" + LINE_SEPARATOR
                + "Request URI:\thttp://localhost:8080/greet?firstName=John&lastName=Doe" + LINE_SEPARATOR
                + "Proxy:\t\t\t<none>" + LINE_SEPARATOR + "Request params:\tfirstName=John" + LINE_SEPARATOR
                + "\t\t\t\tlastName=Doe" + LINE_SEPARATOR + "Query params:\t<none>" + LINE_SEPARATOR
                + "Form params:\t<none>" + LINE_SEPARATOR + "Path params:\t<none>" + LINE_SEPARATOR
                + "Multiparts:\t\t<none>" + LINE_SEPARATOR + "Headers:\t\tAccept=*/*" + LINE_SEPARATOR
                + "\t\t\t\tContent-Type=application/json; charset="
                + RestAssured.config().getEncoderConfig().defaultCharsetForContentType(ContentType.JSON)
                + LINE_SEPARATOR + "Cookies:\t\t<none>" + LINE_SEPARATOR + "Body:\t\t\t<none>"
                + LINE_SEPARATOR));
    }
}

From source file:com.jayway.restassured.itest.java.LogIfValidationFailsITest.java

@Test
public void worksForRequestSpecificationsUsingGivenWhenThenSyntax() throws Exception {
    final StringWriter writer = new StringWriter();
    final PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);

    try {/*from   w  ww  .j a  v  a  2s  . c  o m*/
        given().config(RestAssured.config().logConfig(logConfig().defaultStream(captor))).log()
                .ifValidationFails().param("firstName", "John").param("lastName", "Doe")
                .header("Content-type", "application/json").when().get("/greet").then().statusCode(400);

        fail("Should throw AssertionError");
    } catch (AssertionError e) {
        assertThat(writer.toString(), equalTo("Request method:\tGET" + LINE_SEPARATOR
                + "Request path:\thttp://localhost:8080/greet?firstName=John&lastName=Doe" + LINE_SEPARATOR
                + "Proxy:\t\t\t<none>" + LINE_SEPARATOR + "Request params:\tfirstName=John" + LINE_SEPARATOR
                + "\t\t\t\tlastName=Doe" + LINE_SEPARATOR + "Query params:\t<none>" + LINE_SEPARATOR
                + "Form params:\t<none>" + LINE_SEPARATOR + "Path params:\t<none>" + LINE_SEPARATOR
                + "Multiparts:\t\t<none>" + LINE_SEPARATOR + "Headers:\t\tAccept=*/*" + LINE_SEPARATOR
                + "\t\t\t\tContent-Type=application/json; charset="
                + RestAssured.config().getEncoderConfig().defaultCharsetForContentType(ContentType.JSON)
                + LINE_SEPARATOR + "Cookies:\t\t<none>" + LINE_SEPARATOR + "Body:\t\t\t<none>"
                + LINE_SEPARATOR));
    }
}

From source file:com.twinsoft.convertigo.engine.util.FileUtils.java

public static void saveProperties(Map<String, String> map, File file, String encoding) throws IOException {
    PrintStream ps = new PrintStream(file, encoding);
    for (Entry<String, String> entry : map.entrySet()) {
        ps.println(entry.getKey());/*from   ww  w. j  a  v  a  2s  .c  om*/
        ps.println(entry.getValue());
        ps.println();
    }
    ps.close();
}

From source file:com.sap.prd.mobile.ios.mios.ForkerTest.java

@Test(expected = IllegalArgumentException.class)
public void testMissingArguments_3() throws Exception {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final PrintStream log = new PrintStream(out, true);

    try {/*from w  ww.j  av a2 s. c  o  m*/

        Forker.forkProcess(log, new File(".").getAbsoluteFile(), "echo", "", "Hello World");

    } finally {
        log.close();
    }
}

From source file:com.yahoo.pulsar.testclient.PerformanceProducer.java

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");

    try {/*from ww w  . j a  va 2 s . c  o  m*/
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }

    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }

    if (arguments.destinations.size() != 1) {
        System.out.println("Only one topic name is allowed");
        jc.usage();
        System.exit(-1);
    }

    if (arguments.confFile != null) {
        Properties prop = new Properties(System.getProperties());
        prop.load(new FileInputStream(arguments.confFile));

        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("brokerServiceUrl");
        }

        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("webServiceUrl");
        }

        // fallback to previous-version serviceUrl property to maintain backward-compatibility
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
        }

        if (arguments.authPluginClassName == null) {
            arguments.authPluginClassName = prop.getProperty("authPlugin", null);
        }

        if (arguments.authParams == null) {
            arguments.authParams = prop.getProperty("authParams", null);
        }
    }

    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);

    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar perf producer with config: {}", w.writeValueAsString(arguments));

    // Read payload data from file if needed
    byte payloadData[];
    if (arguments.payloadFilename != null) {
        payloadData = Files.readAllBytes(Paths.get(arguments.payloadFilename));
    } else {
        payloadData = new byte[arguments.msgSize];
    }

    // Now processing command line arguments
    String prefixTopicName = arguments.destinations.get(0);
    List<Future<Producer>> futures = Lists.newArrayList();

    EventLoopGroup eventLoopGroup;
    if (SystemUtils.IS_OS_LINUX) {
        eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors(),
                new DefaultThreadFactory("pulsar-perf-producer"));
    } else {
        eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(),
                new DefaultThreadFactory("pulsar-perf-producer"));
    }

    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setConnectionsPerBroker(arguments.maxConnections);
    clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams);
    }

    PulsarClient client = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup);

    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setSendTimeout(0, TimeUnit.SECONDS);
    producerConf.setCompressionType(arguments.compression);
    // enable round robin message routing if it is a partitioned topic
    producerConf.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
    if (arguments.batchTime > 0) {
        producerConf.setBatchingMaxPublishDelay(arguments.batchTime, TimeUnit.MILLISECONDS);
        producerConf.setBatchingEnabled(true);
        producerConf.setMaxPendingMessages(arguments.msgRate);
    }

    for (int i = 0; i < arguments.numTopics; i++) {
        String topic = (arguments.numTopics == 1) ? prefixTopicName
                : String.format("%s-%d", prefixTopicName, i);
        log.info("Adding {} publishers on destination {}", arguments.numProducers, topic);

        for (int j = 0; j < arguments.numProducers; j++) {
            futures.add(client.createProducerAsync(topic, producerConf));
        }
    }

    final List<Producer> producers = Lists.newArrayListWithCapacity(futures.size());
    for (Future<Producer> future : futures) {
        producers.add(future.get());
    }

    log.info("Created {} producers", producers.size());

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            printAggregatedStats();
        }
    });

    Collections.shuffle(producers);
    AtomicBoolean isDone = new AtomicBoolean();

    executor.submit(() -> {
        try {
            RateLimiter rateLimiter = RateLimiter.create(arguments.msgRate);

            long startTime = System.currentTimeMillis();

            // Send messages on all topics/producers
            long totalSent = 0;
            while (true) {
                for (Producer producer : producers) {
                    if (arguments.testTime > 0) {
                        if (System.currentTimeMillis() - startTime > arguments.testTime) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }

                    if (arguments.numMessages > 0) {
                        if (totalSent++ >= arguments.numMessages) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }
                    rateLimiter.acquire();

                    final long sendTime = System.nanoTime();

                    producer.sendAsync(payloadData).thenRun(() -> {
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);

                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);
                    }).exceptionally(ex -> {
                        log.warn("Write error on message", ex);
                        System.exit(-1);
                        return null;
                    });
                }
            }
        } catch (Throwable t) {
            log.error("Got error", t);
        }
    });

    // Print report stats
    long oldTime = System.nanoTime();

    Histogram reportHistogram = null;

    String statsFileName = "perf-producer-" + System.currentTimeMillis() + ".hgrm";
    log.info("Dumping latency stats to {}", statsFileName);

    PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false);
    HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog);

    // Some log header bits
    histogramLogWriter.outputLogFormatVersion();
    histogramLogWriter.outputLegend();

    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }

        if (isDone.get()) {
            break;
        }

        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;

        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;

        reportHistogram = recorder.getIntervalHistogram(reportHistogram);

        log.info(
                "Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}",
                throughputFormat.format(rate), throughputFormat.format(throughput),
                dec.format(reportHistogram.getMean() / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0),
                dec.format(reportHistogram.getMaxValue() / 1000.0));

        histogramLogWriter.outputIntervalHistogram(reportHistogram);
        reportHistogram.reset();

        oldTime = now;
    }

    client.close();
}

From source file:ee.ioc.cs.vsle.util.Console.java

private Console() {
    // create all components and add them
    frame = new JFrame("Java Console");
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = new Dimension((screenSize.width / 2), (screenSize.height / 2));
    int x = (frameSize.width / 2);
    int y = (frameSize.height / 2);
    frame.setBounds(x, y, frameSize.width, frameSize.height);

    textArea = new JTextArea();
    textArea.setEditable(false);// w  w  w  . ja va2  s . c  o  m
    JButton button = new JButton("clear");

    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);
    frame.getContentPane().add(button, BorderLayout.SOUTH);
    frame.setVisible(true);

    frame.addWindowListener(this);
    button.addActionListener(this);

    final PipedInputStream pin = new PipedInputStream();
    try {
        PipedOutputStream pout = new PipedOutputStream(pin);
        System.setOut(new PrintStream(new TeeOutputStream(systemOut, pout), true));
    } catch (java.io.IOException io) {
        textArea.append("Couldn't redirect STDOUT to this console\n" + io.getMessage());
    } catch (SecurityException se) {
        textArea.append("Couldn't redirect STDOUT to this console\n" + se.getMessage());
    }

    final PipedInputStream pin2 = new PipedInputStream();
    try {
        PipedOutputStream pout2 = new PipedOutputStream(pin2);
        System.setErr(new PrintStream(new TeeOutputStream(systemErr, pout2), true));
    } catch (java.io.IOException io) {
        textArea.append("Couldn't redirect STDERR to this console\n" + io.getMessage());
    } catch (SecurityException se) {
        textArea.append("Couldn't redirect STDERR to this console\n" + se.getMessage());
    }

    quit = false; // signals the Threads that they should exit

    sysOutFollower = new StreamFollower(pin, StreamRestorer.SYS_OUT, "Console_out");
    sysOutFollower.start();
    //
    sysErrFollower = new StreamFollower(pin2, StreamRestorer.SYS_ERR, "Console_err");
    sysErrFollower.start();
}

From source file:ca.ualberta.exemplar.evaluation.BenchmarkBinary.java

public BenchmarkBinary(File evaluationFile, File outputFile, String parserName)
        throws FileNotFoundException, UnsupportedEncodingException {
    this.evaluationFile = evaluationFile;

    Parser parser;/*from  w w w . j a va  2 s. com*/
    if ("malt".equalsIgnoreCase(parserName)) {
        parser = new ParserMalt();
    } else {
        parser = new ParserStanford();
    }

    relationExtraction = new RelationExtraction(parser);

    ps = new PrintStream(outputFile, "UTF-8");
    ps.println("Entity1\tRelation\tEntity2\tAnnotated Sentence");
}

From source file:io.restassured.itest.java.FilterITest.java

@Test
public void supportsSpecifyingDefaultFilters() throws Exception {
    final StringWriter writer = new StringWriter();
    final PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);
    RestAssured.filters(//from  w  ww.j  a  va 2 s .  co m
            asList(ErrorLoggingFilter.logErrorsTo(captor), ResponseLoggingFilter.logResponseTo(captor)));
    try {
        expect().body(equalTo("ERROR")).when().get("/409");
    } finally {
        RestAssured.reset();
    }
    String lineSeparator = System.getProperty("line.separator");
    assertThat(writer.toString(), is(
            "HTTP/1.1 409 Conflict\nContent-Type: text/plain;charset=utf-8\nContent-Length: 5\nServer: Jetty(9.3.2.v20150730)\n\nERROR"
                    + lineSeparator
                    + "HTTP/1.1 409 Conflict\nContent-Type: text/plain;charset=utf-8\nContent-Length: 5\nServer: Jetty(9.3.2.v20150730)\n\nERROR"
                    + lineSeparator));
}