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:org.geowebcache.s3.S3BlobStore.java

private ByteArrayInputStream toByteArray(final Resource blob) throws StorageException {
    final byte[] bytes;
    if (blob instanceof ByteArrayResource) {
        bytes = ((ByteArrayResource) blob).getContents();
    } else {/*from w w  w  . j a v  a2  s. c o  m*/
        ByteArrayOutputStream out = new ByteArrayOutputStream((int) blob.getSize());
        WritableByteChannel channel = Channels.newChannel(out);
        try {
            blob.transferTo(channel);
        } catch (IOException e) {
            throw new StorageException("Error copying blob contents", e);
        }
        bytes = out.toByteArray();
    }
    ByteArrayInputStream input = new ByteArrayInputStream(bytes);
    return input;
}

From source file:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

protected long getContent(String hexId, Path f) throws IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpGet request = new HttpGet(server.getURI() + "/lfs/objects/" + hexId);
        HttpResponse response = client.execute(request);
        checkResponseStatus(response);//w  w w  .  jav a 2s  .  c  o m
        HttpEntity entity = response.getEntity();
        long pos = 0;
        try (InputStream in = entity.getContent();
                ReadableByteChannel inChannel = Channels.newChannel(in);
                FileChannel outChannel = FileChannel.open(f, StandardOpenOption.CREATE_NEW,
                        StandardOpenOption.WRITE)) {
            long transferred;
            do {
                transferred = outChannel.transferFrom(inChannel, pos, MiB);
                pos += transferred;
            } while (transferred > 0);
        }
        return pos;
    }
}

From source file:hk.hku.cecid.corvus.http.EnvelopQuerySender.java

/**
 * [@EVENT] This method is invoked when received the reply HTTP  response from the server.
 * <br/><br/>/*from w  w  w  .j  a v a 2s.co m*/
 * It saves the response body stream and then available to get through by {@link #getEnvelopStream()}
 */
protected void onResponse() throws Exception {
    HttpMethod post = this.getExecutedMethod();
    InputStream ins = post.getResponseBodyAsStream();

    /*
     * We have to pipe the content to either memory or storage because the response stream
     * is directly extracted from socket which is going to close upon the connection 
     * has been closed.
     */
    if (ins.available() < THRESHOLD) {
        byte[] envelop = IOHandler.readBytes(ins);
        this.envelopStream = new ByteArrayInputStream(envelop);
    } else {
        // Create a temporary file at TMP directory.
        File envelopTmp = new File(BASE_PATH + this.hashCode());
        envelopTmp.deleteOnExit();
        // Pipe the content to the TMP file.
        FileChannel fChannel = new FileInputStream(envelopTmp).getChannel();
        fChannel.transferFrom(Channels.newChannel(ins), 0, ins.available());
        fChannel.close();
        // Create an buffered stream to the file.
        this.envelopStream = new BufferedInputStream(new FileInputStream(envelopTmp));
        // InputStream is closed automatically.
    }
}

From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java

@Test(enabled = true, invocationCount = 1)
public void write() throws IOException, FileBackException {

    fileContext.fileOperationSupplier(() -> FileOperation.WRITE);

    final ByteBuffer fileKey = randomFileKey();
    fileContext.targetKeySupplier(() -> fileKey);

    final Path leafPath = LocalFileBack.leafPath(rootPath, fileKey, true);

    final byte[] fileBytes = randomFileBytes();
    final boolean fileWritten = Files.isRegularFile(leafPath) || current().nextBoolean();
    if (fileWritten) {
        Files.write(leafPath, fileBytes, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
        logger.trace("file written");
    }//w w  w. j ava  2  s  .  c om

    fileContext.sourceChannelSupplier(() -> Channels.newChannel(new ByteArrayInputStream(fileBytes)));

    fileContext.targetChannelConsumer(v -> {
        try {
            final long copied = IOUtils.copyLarge(new ByteArrayInputStream(fileBytes),
                    Channels.newOutputStream(v));
        } catch (final IOException ioe) {
            logger.error("failed to copy", ioe);
        }
    });

    fileBack.operate(fileContext);

    if (fileWritten) {
        final byte[] actual = Files.readAllBytes(leafPath);
        assertEquals(actual, fileBytes);
    }
}

From source file:org.evilco.bot.powersweeper.platform.DriverManager.java

/**
 * Extracts a driver archive./*from www. ja  va  2  s .  c o m*/
 * @param file The archive file.
 * @throws IOException
 */
protected void extract(File file) throws IOException {
    // get input stream
    ZipInputStream inputStream = new ZipInputStream(new FileInputStream(file));
    FileOutputStream outputStream = null;

    try {
        // initialize variable
        ZipEntry entry;

        // copy all files
        while ((entry = inputStream.getNextEntry()) != null) {
            // log
            getLogger().info(
                    "Extracting file " + entry.getName() + " from driver archive " + file.getName() + ".");

            // create file reference
            File outputFile = new File(this.getDriverNativeFile().getParentFile(), entry.getName());

            // ensure parent exists
            outputFile.getParentFile().mkdirs();

            // copy file
            ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
            outputStream = new FileOutputStream(outputFile);
            outputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);

            // close stream
            outputStream.close();
            outputStream = null;
        }
    } finally {
        if (inputStream != null)
            IOUtils.closeQuietly(inputStream);
        if (outputStream != null)
            IOUtils.closeQuietly(outputStream);
    }
}

From source file:org.openhab.binding.plugwise.internal.Stick.java

/**
 * Initialize this device and open the serial port
 * //from  w  w  w.j  a va  2  s.  c  o m
 * @throws PlugwiseInitializationException if port can not be opened
 */
@SuppressWarnings("rawtypes")
private void initialize() throws PlugwiseInitializationException {

    //Flush the deviceCache
    if (this.plugwiseDeviceCache != null) {
        plugwiseDeviceCache = Collections.synchronizedList(new ArrayList<PlugwiseDevice>());
    }

    // parse ports and if the default port is found, initialized the reader
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
        if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (id.getName().equals(port)) {
                logger.debug("Serial port '{}' has been found.", port);
                portId = id;
            }
        }
    }
    if (portId != null) {
        // initialize serial port
        try {
            serialPort = (SerialPort) portId.open("openHAB", 2000);
        } catch (PortInUseException e) {
            throw new PlugwiseInitializationException(e);
        }

        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException e) {
            throw new PlugwiseInitializationException(e);
        }

        // activate the DATA_AVAILABLE notifier
        serialPort.notifyOnDataAvailable(true);

        try {
            // set port parameters
            serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
            throw new PlugwiseInitializationException(e);
        }

        try {
            // get the output stream
            outputChannel = Channels.newChannel(serialPort.getOutputStream());
        } catch (IOException e) {
            throw new PlugwiseInitializationException(e);
        }
    } else {
        StringBuilder sb = new StringBuilder();
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
            if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                sb.append(id.getName() + "\n");
            }
        }
        throw new PlugwiseInitializationException(
                "Serial port '" + port + "' could not be found. Available ports are:\n" + sb.toString());
    }

    // set up the Quartz jobs

    Scheduler sched = null;
    try {
        sched = StdSchedulerFactory.getDefaultScheduler();
    } catch (SchedulerException e) {
        logger.error("Error getting a reference to the Quartz Scheduler");
    }

    JobDataMap map = new JobDataMap();
    map.put("Stick", this);

    JobDetail job = newJob(SendJob.class).withIdentity("Send-0", "Plugwise").usingJobData(map).build();

    Trigger trigger = newTrigger().withIdentity("Send-0", "Plugwise").startNow().build();

    try {
        sched.getListenerManager().addJobListener(new SendJobListener("JobListener-" + job.getKey().toString()),
                KeyMatcher.keyEquals(job.getKey()));
    } catch (SchedulerException e1) {
        logger.error("An exception occured while attaching a Quartz Send Job Listener");
    }

    try {
        sched.scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        logger.error("Error scheduling a job with the Quartz Scheduler");
    }

    map = new JobDataMap();
    map.put("Stick", this);

    job = newJob(ProcessMessageJob.class).withIdentity("ProcessMessage", "Plugwise").usingJobData(map).build();

    trigger = newTrigger().withIdentity("ProcessMessage", "Plugwise").startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInMilliseconds(50)).build();

    try {
        sched.scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        logger.error("Error scheduling a job with the Quartz Scheduler");
    }

    // initialise the Stick
    initialised = true;
    InitialiseRequestMessage message = new InitialiseRequestMessage();
    sendMessage(message);

}

From source file:org.apache.flex.utilities.converter.retrievers.download.DownloadRetriever.java

protected void performFastDownload(URL sourceUrl, File targetFile) throws IOException {
    final URLConnection connection = sourceUrl.openConnection();
    final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
    final FileOutputStream fos = new FileOutputStream(targetFile);

    ////////////////////////////////////////////////////////////////////////////////
    // Do the downloading.
    ////////////////////////////////////////////////////////////////////////////////

    final long expectedSize = connection.getContentLength();
    long transferedSize = 0L;

    System.out.println("===========================================================");
    System.out.println("Downloading " + sourceUrl.toString());
    if (expectedSize > 1014 * 1024) {
        System.out.println("Expected size: " + (expectedSize / 1024 / 1024) + "MB");
    } else {// ww  w.ja  va  2  s. c  o m
        System.out.println("Expected size: " + (expectedSize / 1024) + "KB");
    }
    final ProgressBar progressBar = new ProgressBar(expectedSize);
    while (transferedSize < expectedSize) {
        transferedSize += fos.getChannel().transferFrom(rbc, transferedSize, 1 << 20);
        progressBar.updateProgress(transferedSize);
    }
    fos.close();
    System.out.println();
    System.out.println("Finished downloading.");
    System.out.println("===========================================================");
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * Downloads data from the given URL and saves it to the given file
 * @param url The url to download from//from   w w w  .  j av a  2 s  .c o  m
 * @param file The file to save to.
 *
 * TODO: how to handle partial downloads? Old file is overwritten as soon as FileOutputStream is created.
 */
public static void downloadToFile(URL url, File file) throws IOException {
    file.getParentFile().mkdirs();
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fos = new FileOutputStream(file);
    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    fos.close();
}

From source file:com.recomdata.transmart.data.export.util.FileWriterUtil.java

public void writeFile(String url, File outputURLFile) {

    try {/* w ww  .jav  a  2  s.  c  o  m*/
        URL celFileURL = new URL(url);
        ReadableByteChannel rbc = Channels.newChannel(celFileURL.openStream());
        FileOutputStream fos = new FileOutputStream(outputURLFile);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    } catch (MalformedURLException e) {
        log.info("Bad URL: " + url);
    } catch (IOException e) {
        log.info("IO Error:" + e.getMessage());
    }
}