Example usage for java.io PipedOutputStream flush

List of usage examples for java.io PipedOutputStream flush

Introduction

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

Prototype

public synchronized void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    PipedOutputStream out = new PipedOutputStream();
    Main in = new Main();

    out.connect(in);/*from w w  w  . j av  a2 s  .  c om*/

    out.write(70);
    out.write(71);

    out.flush();

    // print what we wrote
    for (int i = 0; i < 2; i++) {
        System.out.println((char) in.read());
    }
    out.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    PipedOutputStream out = new PipedOutputStream();
    Main in = new Main();

    out.connect(in);//from www. j  a v a 2  s . c  o m

    out.write(70);
    out.write(71);
    out.write(72);

    out.flush();

    for (int i = 0; i < 3; i++) {
        System.out.println((char) in.read());
    }
    out.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    byte[] b = { 'h', 'e', 'l', 'l', 'o' };

    PipedOutputStream out = new PipedOutputStream();
    Main in = new Main();

    out.connect(in);/*from  w  w w . j a v a  2s  . co m*/

    // write something
    out.write(b, 0, 3);

    // flush the stream
    out.flush();

    // print what we wrote
    for (int i = 0; i < 3; i++) {
        System.out.print((char) in.read());
    }
    out.close();
}

From source file:Main.java

public static void produceData(PipedOutputStream pos) {
    try {/* ww w . j ava2  s .  co  m*/
        for (int i = 1; i <= 50; i++) {
            pos.write((byte) i);
            pos.flush();
            System.out.println("Writing: " + i);
            Thread.sleep(500);
        }
        pos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.xebialabs.overthere.cifs.telnet.CifsTelnetConnection.java

private static void handleReceivedLine(final ByteArrayOutputStream outputBuf, final String outputBufStr,
        final PipedOutputStream toCallersStdout) throws IOException {
    if (!outputBufStr.contains(DETECTABLE_WINDOWS_PROMPT)) {
        toCallersStdout.write(outputBuf.toByteArray());
        toCallersStdout.flush();
    }/*from www . j a  v a2 s.  com*/
    outputBuf.reset();
}

From source file:com.blacklocus.jres.http.HttpMethods.java

static HttpEntity createEntity(final Object payload) throws IOException {
    final HttpEntity entity;
    if (payload instanceof InputStream) {

        if (LOG.isDebugEnabled()) {
            String stream = IOUtils.toString((InputStream) payload);
            LOG.debug(stream);/* w w  w  .ja  v a  2  s  . c om*/
            entity = new StringEntity(stream, ContentType.APPLICATION_JSON);
        } else {
            entity = new InputStreamEntity((InputStream) payload, ContentType.APPLICATION_JSON);
        }

    } else if (payload instanceof String) {

        LOG.debug((String) payload);
        entity = new StringEntity((String) payload, ContentType.APPLICATION_JSON);

    } else { // anything else will be serialized with Jackson

        if (LOG.isDebugEnabled()) {
            String json = ObjectMappers.toJson(payload);
            LOG.debug(json);
            entity = new StringEntity(json, ContentType.APPLICATION_JSON);

        } else {
            final PipedOutputStream pipedOutputStream = new PipedOutputStream();
            final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
            PIPER.submit(new ExceptingRunnable() {
                @Override
                protected void go() throws Exception {
                    try {
                        ObjectMappers.NORMAL.writeValue(pipedOutputStream, payload);
                        pipedOutputStream.flush();
                    } finally {
                        IOUtils.closeQuietly(pipedOutputStream);
                    }
                }
            });
            entity = new InputStreamEntity(pipedInputStream, ContentType.APPLICATION_JSON);
        }

    }
    return entity;
}

From source file:edu.umn.msi.tropix.common.io.impl.AsyncStreamCopierImplTest.java

@Test(groups = "unit", timeOut = 1000, invocationCount = 10)
public void close() throws IOException, InterruptedException {
    final AsyncStreamCopierImpl copier = new AsyncStreamCopierImpl();
    final Reference<Thread> threadReference = new Reference<Thread>();
    final Reference<Throwable> throwableReference = new Reference<Throwable>();
    copier.setExecutor(new Executor() {
        public void execute(final Runnable runnable) {
            final Thread thread = new Thread(runnable);
            threadReference.set(thread);
            thread.start();//w  w  w  .j a  v  a  2 s  .co  m
            thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                public void uncaughtException(final Thread arg0, final Throwable throwable) {
                    throwableReference.set(throwable);
                }
            });
        }
    });
    final PipedOutputStream pipedOutputStream = new PipedOutputStream();
    final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
    final ByteArrayOutputStream copiedStream = new ByteArrayOutputStream();
    copier.copy(pipedInputStream, copiedStream, true);
    Thread.sleep(3);
    assert new String(copiedStream.toByteArray()).equals("");
    pipedOutputStream.write("Hello ".getBytes());
    pipedOutputStream.flush();
    while (!new String(copiedStream.toByteArray()).equals("Hello ")) {
        Thread.sleep(1);
    }
    pipedOutputStream.write("World!".getBytes());
    pipedOutputStream.flush();
    while (!new String(copiedStream.toByteArray()).equals("Hello World!")) {
        Thread.sleep(1);
    }
    assert threadReference.get().isAlive();
    pipedOutputStream.close();
    while (threadReference.get().isAlive()) {
        Thread.sleep(1);
    }
    assert throwableReference.get() == null;
}

From source file:custom.SevenZFileExt.java

public InputStream getInputStream(final int bufferSize) {
    final PipedInputStream in = new PipedInputStream(bufferSize);
    try {//from w w  w.  java  2 s . co m
        final PipedOutputStream out = new PipedOutputStream(in);
        Thread thread = new Thread(() -> {
            try {
                byte[] buffer = new byte[bufferSize];
                int len = read(buffer);
                while (len > 0) {
                    try {
                        out.write(buffer, 0, len);
                        len = read(buffer);
                    } catch (Exception ex) {
                        LOGGER.error(ex.getMessage(), ex);
                    }
                }
                out.flush();
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception ex) {
                        LOGGER.error(ex.getMessage(), ex);
                    }
                }
            }
        });
        thread.setName("GenerateInputStreamSeven7File");
        thread.start();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return in;
}

From source file:gov.vha.isaac.rf2.filter.RF2Filter.java

private void handleFile(Path inputFile, Path outputFile) throws IOException {
    boolean justCopy = true;
    boolean justSkip = false;

    if (inputFile.toFile().getName().toLowerCase().endsWith(".txt")) {
        justCopy = false;//from   w  ww  .  j a  va2  s .c  o m
        //Filter the file
        BufferedReader fileReader = new BufferedReader(
                new InputStreamReader(new BOMInputStream(new FileInputStream(inputFile.toFile())), "UTF-8"));
        BufferedWriter fileWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile.toFile()), "UTF-8"));
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        CSVReader csvReader = new CSVReader(new InputStreamReader(pis), '\t', CSVParser.NULL_CHARACTER); //don't look for quotes, the data is bad, and has floating instances of '"' all by itself

        boolean firstLine = true;
        String line = null;
        long kept = 0;
        long skipped = 0;
        long total = 0;

        int moduleColumn = -1;

        while ((line = fileReader.readLine()) != null) {
            total++;
            //Write this line into the CSV parser
            pos.write(line.getBytes());
            pos.write("\r\n".getBytes());
            pos.flush();
            String[] fields = csvReader.readNext();

            boolean correctModule = false;
            for (String ms : moduleStrings_) {
                if (moduleColumn >= 0 && fields[moduleColumn].equals(ms)) {
                    correctModule = true;
                    break;
                }
            }

            if (firstLine || correctModule) {
                kept++;
                fileWriter.write(line);
                fileWriter.write("\r\n");
            } else {
                //don't write line
                skipped++;
            }

            if (firstLine) {

                log("Filtering file " + inputDirectory.toPath().relativize(inputFile).toString());
                firstLine = false;
                if (fields.length < 2) {
                    log("txt file doesn't look like a data file - abort and just copy.");
                    justCopy = true;
                    break;
                }
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].equals("moduleId")) {
                        moduleColumn = i;
                        break;
                    }
                }
                if (moduleColumn < 0) {
                    log("No moduleId column found - skipping file");
                    justSkip = true;
                    break;
                }
            }
        }

        fileReader.close();
        csvReader.close();
        fileWriter.close();

        if (!justCopy) {
            log("Kept " + kept + " Skipped " + skipped + " out of " + total + " lines in "
                    + inputDirectory.toPath().relativize(inputFile).toString());
        }
    }

    if (justCopy) {
        //Just copy the file
        Files.copy(inputFile, outputFile, StandardCopyOption.REPLACE_EXISTING);
        log("Copied file " + inputDirectory.toPath().relativize(inputFile).toString());
    }

    if (justSkip) {
        Files.delete(outputFile);
        log("Skipped file " + inputDirectory.toPath().relativize(inputFile).toString()
                + " because it doesn't contain a moduleId");
    }
}

From source file:eu.scape_project.service.ConnectorService.java

private void addMetadata(final Session session, final Object metadata, final String path)
        throws RepositoryException {
    final StringBuilder sparql = new StringBuilder("PREFIX scape: <" + SCAPE_NAMESPACE + "> ");
    try {// w ww.j a v  a  2 s  . c o  m

        /* use piped streams to copy the data to the repo */
        final PipedInputStream dcSrc = new PipedInputStream();
        final PipedOutputStream dcSink = new PipedOutputStream();
        dcSink.connect(dcSrc);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    ConnectorService.this.marshaller.getJaxbMarshaller().marshal(metadata, dcSink);
                    dcSink.flush();
                    dcSink.close();
                } catch (JAXBException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                } catch (IOException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }
            }
        }).start();

        final Datastream ds = datastreamService.createDatastream(session, path, "text/xml", null, dcSrc);
        final Node desc = ds.getNode();
        desc.addMixin("scape:metadata");

        final IdentifierTranslator subjects = new DefaultIdentifierTranslator();
        final String dsUri = subjects.getSubject(desc.getPath()).getURI();
        /* get the type of the metadata */
        String type = "unknown";
        String schema = "";

        if (metadata.getClass() == ElementContainer.class) {
            type = "dublin-core";
            schema = "http://purl.org/dc/elements/1.1/";
        } else if (metadata.getClass() == GbsType.class) {
            type = "gbs";
            schema = "http://books.google.com/gbs";
        } else if (metadata.getClass() == Fits.class) {
            type = "fits";
            schema = "http://hul.harvard.edu/ois/xml/ns/fits/fits_output";
        } else if (metadata.getClass() == AudioType.class) {
            type = "audiomd";
            schema = "http://www.loc.gov/audioMD/";
        } else if (metadata.getClass() == RecordType.class) {
            type = "marc21";
            schema = "http://www.loc.gov/MARC21/slim";
        } else if (metadata.getClass() == Mix.class) {
            type = "mix";
            schema = "http://www.loc.gov/mix/v20";
        } else if (metadata.getClass() == VideoType.class) {
            type = "videomd";
            schema = "http://www.loc.gov/videoMD/";
        } else if (metadata.getClass() == PremisComplexType.class) {
            type = "premis-provenance";
            schema = "info:lc/xmlns/premis-v2";
        } else if (metadata.getClass() == RightsComplexType.class) {
            type = "premis-rights";
            schema = "info:lc/xmlns/premis-v2";
        } else if (metadata.getClass() == TextMD.class) {
            type = "textmd";
            schema = "info:lc/xmlns/textmd-v3";
        }

        /* add a sparql query to set the type of this object */
        sparql.append("INSERT DATA {<" + dsUri + "> " + prefix(HAS_TYPE) + " '" + type + "'};");
        sparql.append("INSERT DATA {<" + dsUri + "> " + prefix(HAS_SCHEMA) + " '" + schema + "'};");

        ds.updatePropertiesDataset(subjects, sparql.toString());

    } catch (IOException e) {
        throw new RepositoryException(e);
    } catch (InvalidChecksumException e) {
        throw new RepositoryException(e);
    }
}