Example usage for java.nio.channels Channels newChannel

List of usage examples for java.nio.channels Channels newChannel

Introduction

In this page you can find the example usage for java.nio.channels Channels newChannel.

Prototype

public static WritableByteChannel newChannel(OutputStream out) 

Source Link

Document

Constructs a channel that writes bytes to the given stream.

Usage

From source file:rascal.object.source.FilelBlobSourceIntegrationTest.java

@Test
public void testCopyTo() throws Exception {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    fileBlobSource.copyTo(Channels.newChannel(output));
    byte[] buffer = output.toByteArray();
    String expectedHeaderString = String.format("%s %d", GitObjectType.BLOB, testData.length);
    byte[] expectedHeader = ArrayUtils.add(expectedHeaderString.getBytes(), (byte) 0);
    byte[] header = ArrayUtils.subarray(buffer, 0, expectedHeader.length);
    Assert.assertTrue("Header should be of format \"type(space)size(null byte)\"",
            ArrayUtils.isEquals(expectedHeader, header));
    byte[] content = ArrayUtils.subarray(buffer, expectedHeader.length, buffer.length);
    Assert.assertTrue(ArrayUtils.isEquals(testData, content));
}

From source file:com.sastix.cms.server.services.cache.CacheFileUtilsServiceImpl.java

@Override
public byte[] downloadResource(URL url) throws IOException {
    //create buffer with capacity in bytes
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*from   w w w.  j  a  v a 2s .  c om*/
        ByteBuffer bufIn = ByteBuffer.allocate(1024);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        int bytesRead;
        while ((bytesRead = rbc.read(bufIn)) > 0) {
            baos.write(bufIn.array(), 0, bytesRead);
            bufIn.rewind();
        }
        bufIn.clear();
        return baos.toByteArray();
    } finally {
        baos.close();
    }
}

From source file:org.apache.nifi.jms.cf.TestUtils.java

static String setupActiveMqLibForTesting(boolean clean) {
    String[] urlsStrings = new String[] {
            "http://central.maven.org/maven2/org/apache/activemq/activemq-client/5.13.0/activemq-client-5.13.0.jar",
            "http://central.maven.org/maven2/org/apache/activemq/activemq-broker/5.13.0/activemq-broker-5.13.0.jar",
            "http://central.maven.org/maven2/org/apache/geronimo/specs/geronimo-j2ee-management_1.0_spec/1.0.1/geronimo-j2ee-management_1.0_spec-1.0.1.jar",
            "http://central.maven.org/maven2/org/fusesource/hawtbuf/hawtbuf/1.11/hawtbuf-1.11.jar" };

    try {/* w  w w  .  j av  a  2 s.co m*/
        File activeMqLib = new File("target/active-mq-lib");
        if (activeMqLib.exists() && clean) {
            FileUtils.deleteDirectory(activeMqLib);
        }
        activeMqLib.mkdirs();
        for (String urlString : urlsStrings) {
            URL url = new URL(urlString);
            String path = url.getPath();
            path = path.substring(path.lastIndexOf("/") + 1);
            logger.info("Downloading: " + path);
            ReadableByteChannel rbc = Channels.newChannel(url.openStream());
            try (FileOutputStream fos = new FileOutputStream(new File(activeMqLib, path))) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                fos.close();
            }
        }
        return activeMqLib.getAbsolutePath();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to download ActiveMQ libraries.", e);
    }
}

From source file:examples.utils.CifarReader.java

public static void downloadAndExtract() {

    if (new File("data", TEST_DATA_FILE).exists() == false) {
        try {//  ww w  . j a v  a  2 s .  c  o m
            if (new File("data", ARCHIVE_BINARY_FILE).exists() == false) {
                URL website = new URL("http://www.cs.toronto.edu/~kriz/" + ARCHIVE_BINARY_FILE);
                FileOutputStream fos = new FileOutputStream("data/" + ARCHIVE_BINARY_FILE);
                fos.getChannel().transferFrom(Channels.newChannel(website.openStream()), 0, Long.MAX_VALUE);
                fos.close();
            }
            TarArchiveInputStream tar = new TarArchiveInputStream(
                    new GZIPInputStream(new FileInputStream("data/" + ARCHIVE_BINARY_FILE)));
            TarArchiveEntry entry = null;
            while ((entry = tar.getNextTarEntry()) != null) {
                if (entry.isDirectory()) {
                    new File("data", entry.getName()).mkdirs();
                } else {
                    byte data[] = new byte[2048];
                    int count;
                    BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(new File("data/", entry.getName())), 2048);

                    while ((count = tar.read(data, 0, 2048)) != -1) {
                        bos.write(data, 0, count);
                    }
                    bos.close();
                }
            }
            tar.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.ops4j.pax.runner.platform.internal.StreamUtils.java

/**
 * Copy a stream to a destination. It does not close the streams.
 *
 * @param in          the stream to copy from
 * @param out         the stream to copy to
 * @param progressBar download progress feedback. Can be null.
 *
 * @throws IOException re-thrown/* ww  w  .j  a va2 s.com*/
 */
public static void streamCopy(final InputStream in, final FileChannel out, final ProgressBar progressBar)
        throws IOException {
    NullArgumentException.validateNotNull(in, "Input stream");
    NullArgumentException.validateNotNull(out, "Output stream");
    final long start = System.currentTimeMillis();
    long bytes = 0;
    ProgressBar feedbackBar = progressBar;
    if (feedbackBar == null) {
        feedbackBar = new NullProgressBar();
    }
    try {
        ReadableByteChannel inChannel = Channels.newChannel(in);
        bytes = out.transferFrom(inChannel, 0, Integer.MAX_VALUE);
        inChannel.close();
    } finally {
        feedbackBar.increment(bytes, bytes / Math.max(System.currentTimeMillis() - start, 1));
        feedbackBar.stop();
    }
}

From source file:Dengue.CDengueManager.java

private static void sendInfoToCPU(String pStrJSON, int pIntPort) {

    new Thread(() -> {
        try (Socket client = new Socket(InetAddress.getLocalHost(), pIntPort)) {

            Writer objWriter = Channels.newWriter(Channels.newChannel(client.getOutputStream()),
                    StandardCharsets.US_ASCII.name());
            objWriter.write(pStrJSON);//  w  w  w  .j ava 2  s  .  c  om
            objWriter.flush();

            client.shutdownOutput();

            try (Reader objReader = Channels.newReader(Channels.newChannel(client.getInputStream()),
                    StandardCharsets.US_ASCII.name());
                    BufferedReader objOutReader = new BufferedReader(objReader)) {
                System.out.println((char) objOutReader.read());

            }

        } catch (IOException e) {
            System.out.println(e);
        }
    }).start();
}

From source file:Network.Dengue.CDengueHandler.java

@Override
public void update(Observable o, Object arg) {

    int intReturn = 1;

    Socket objSocket = (Socket) arg;

    StringBuilder objSB = new StringBuilder();

    try {// w  ww  .j  a v  a  2s.c om

        BufferedReader objReader = new BufferedReader(new InputStreamReader(objSocket.getInputStream()));

        objSB.append(objReader.readLine());

        new MDengue().addCluster(objSB.toString());

        CNotificationManager.notifiyDengue();
        CPublisherManager.publishDengue();

    } catch (IOException | ParseException ex) {
        System.out.println(ex);
        intReturn = -1;
    } finally {

        try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()),
                StandardCharsets.US_ASCII.name())) {

            objWriter.append(intReturn + "");

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

From source file:io.uploader.drive.util.FileUtils.java

public static String readAllAndgetMD5(InputStream in) throws IOException {
    com.google.common.hash.HashingInputStream his = null;
    try {//  ww  w .  j a va2 s  .  c o  m
        his = new com.google.common.hash.HashingInputStream(Hashing.md5(), in);

        final int bufferSize = 2097152;
        final ReadableByteChannel inputChannel = Channels.newChannel(his);
        final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
        while (inputChannel.read(buffer) != -1) {
            buffer.clear();
        }
        /*
        byte[] bytesBuffer = new byte[bufferSize] ;
        int r = his.read(bytesBuffer, 0, bufferSize) ;
        while (r != -1)
           r = his.read(bytesBuffer) ;
        */
        HashCode hc = his.hash();
        return (hc != null) ? (hc.toString()) : (null);
    } finally {
        if (his != null)
            his.close();
    }
}

From source file:com.alibaba.otter.shared.common.utils.NioUtils.java

/**
 * ??copy//from  ww  w .  j a v  a2s  .  c o m
 */
public static long copy(InputStream input, OutputStream output, long offset) throws IOException {
    long count = 0;
    long n = 0;
    if (input instanceof FileInputStream) {
        FileChannel inChannel = ((FileInputStream) input).getChannel();
        WritableByteChannel outChannel = Channels.newChannel(output);
        count = inChannel.transferTo(offset, inChannel.size() - offset, outChannel);
    } else if (output instanceof FileOutputStream) {
        FileChannel outChannel = ((FileOutputStream) output).getChannel();
        ReadableByteChannel inChannel = Channels.newChannel(input);
        do {
            n = outChannel.transferFrom(inChannel, offset + count, DEFAULT_BUFFER_SIZE);
            count += n;
        } while (n > 0);
    } else {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];

        input.skip(offset);
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, (int) n);
            count += n;
        }
        // ReadableByteChannel inChannel = Channels.newChannel(input);
        // WritableByteChannel outChannel = Channels.newChannel(output);
        //            
        // //ByteBuffer buffer = new ByteBuffer(DEFAULT_BUFFER_SIZE);
        // ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE);
        // while (-1 != (n = inChannel.read(buffer))) {
        // outChannel.write(buffer);
        // count += n;
        // }
    }
    return count;
}

From source file:Network.Haze.CHazeHandler.java

@Override
public void update(Observable o, Object arg) {

    int intReturn = 1;

    Socket objSocket = (Socket) arg;

    StringBuilder objSB = new StringBuilder();

    try {//  ww  w. j  a  va  2 s  .co m

        BufferedReader objReader = new BufferedReader(new InputStreamReader(objSocket.getInputStream()));

        objSB.append(objReader.readLine());

        new MHaze().addHazeInfo(objSB.toString());

        CNotificationManager.notifiyHaze();
        CPublisherManager.publishHaze();

    } catch (IOException | ParseException ex) {
        System.out.println(ex);
        intReturn = -1;
    } finally {

        try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()),
                StandardCharsets.US_ASCII.name())) {

            objWriter.append(intReturn + "");

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}