Example usage for java.nio.channels WritableByteChannel write

List of usage examples for java.nio.channels WritableByteChannel write

Introduction

In this page you can find the example usage for java.nio.channels WritableByteChannel write.

Prototype

public int write(ByteBuffer src) throws IOException;

Source Link

Document

Writes a sequence of bytes to this channel from the given buffer.

Usage

From source file:org.lnicholls.galleon.togo.ToGo.java

public boolean Download(Video video, CancelDownload cancelDownload) {

    ServerConfiguration serverConfiguration = Server.getServer().getServerConfiguration();
    GoBackConfiguration goBackConfiguration = Server.getServer().getGoBackConfiguration();

    ArrayList videos = new ArrayList();

    GetMethod get = null;/*from ww  w.  j av  a 2s  .co  m*/

    try {

        URL url = new URL(video.getUrl());

        Protocol protocol = new Protocol("https", new TiVoSSLProtocolSocketFactory(), 443);

        HttpClient client = new HttpClient();

        // TODO How to get TiVo address??

        client.getHostConfiguration().setHost(url.getHost(), 443, protocol);

        String password = Tools.decrypt(serverConfiguration.getMediaAccessKey());

        if (video.getParentalControls() != null && video.getParentalControls().booleanValue())

        {

            if (serverConfiguration.getPassword() == null)

                throw new NullPointerException("Parental Controls Password is null");

            password = password + Tools.decrypt(serverConfiguration.getPassword());

        }

        Credentials credentials = new UsernamePasswordCredentials("tivo", password);

        //client.getState().setCredentials("TiVo DVR", url.getHost(), credentials);

        client.getState().setCredentials(null, url.getHost(), credentials);

        get = new GetMethod(video.getUrl());

        client.executeMethod(get);

        if (get.getStatusCode() != 200)

        {

            log.debug("Status code: " + get.getStatusCode());

            return false;

        }

        InputStream input = get.getResponseBodyAsStream();

        String path = serverConfiguration.getRecordingsPath();

        File dir = new File(path);

        if (!dir.exists()) {

            dir.mkdirs();

        }

        String name = getFilename(video);
        File file = null;
        if (goBackConfiguration.isGroupByShow()) {
            if (video.getSeriesTitle() != null && video.getSeriesTitle().trim().length() > 0) {
                path = path + File.separator + clean(video.getSeriesTitle());
                File filePath = new File(path);
                if (!filePath.exists())
                    filePath.mkdirs();
                file = new File(path + File.separator + name);
            } else
                file = new File(path + File.separator + name);
        } else {
            file = new File(path + File.separator + name);
        }

        // TODO Handle retransfers

        /*
                
        if (file.exists() && video.getStatus()!=Video.STATUS_DOWNLOADING)
                
        {
                
           log.debug("duplicate file: "+file);
                
           try {
                
              List list = VideoManager.findByPath(file.getCanonicalPath());
                
              if (list!=null && list.size()>0)
                
              {
                
          video.setDownloadSize(file.length());
                
          video.setDownloadTime(0);
                
          video.setPath(file.getCanonicalPath());
                
          video.setStatus(Video.STATUS_DELETED);
                
          VideoManager.updateVideo(video);
                
          return true;
                
              }
                
           } catch (HibernateException ex) {
                
              log.error("Video update failed", ex);
                
           }
                
        }
                
        */

        log.info("Downloading: " + name);

        WritableByteChannel channel = new FileOutputStream(file, false).getChannel();

        long total = 0;

        double diff = 0.0;

        ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 4);

        byte[] bytes = new byte[1024 * 4];

        int amount = 0;

        int index = 0;

        long target = video.getSize();

        long start = System.currentTimeMillis();

        long last = start;

        while (amount == 0 && total < target) {

            while (amount >= 0 && !cancelDownload.cancel()) {

                if (index == amount) {

                    amount = input.read(bytes);

                    index = 0;

                    total = total + amount;

                }

                while (index < amount && buf.hasRemaining()) {

                    buf.put(bytes[index++]);

                }

                buf.flip();

                int numWritten = channel.write(buf);

                if (buf.hasRemaining()) {

                    buf.compact();

                } else {

                    buf.clear();

                }

                if ((System.currentTimeMillis() - last > 10000) && (total > 0)) {

                    try {

                        video = VideoManager.retrieveVideo(video.getId());

                        if (video.getStatus() == Video.STATUS_DOWNLOADING) {

                            diff = (System.currentTimeMillis() - start) / 1000.0;

                            if (diff > 0) {

                                video.setDownloadSize(total);

                                video.setDownloadTime((int) diff);

                                VideoManager.updateVideo(video);

                            }

                        }

                    } catch (HibernateException ex) {

                        log.error("Video update failed", ex);

                    }

                    last = System.currentTimeMillis();

                }

            }

            if (cancelDownload.cancel()) {

                channel.close();

                return false;

            }

        }

        diff = (System.currentTimeMillis() - start) / 1000.0;

        channel.close();

        if (diff != 0)

            log.info("Download rate=" + (total / 1024) / diff + " KBps");

        try {

            video.setPath(file.getCanonicalPath());

            VideoManager.updateVideo(video);

        } catch (HibernateException ex) {

            log.error("Video update failed", ex);

        }

    } catch (MalformedURLException ex) {

        Tools.logException(ToGo.class, ex, video.getUrl());

        return false;

    } catch (Exception ex) {

        Tools.logException(ToGo.class, ex, video.getUrl());

        return false;

    } finally {

        if (get != null)

            get.releaseConnection();

    }

    return true;

}

From source file:edu.harvard.iq.dvn.core.web.ExploreDataPage.java

private void writeFile(File fileIn, String dataIn, int bufSize) {
    ByteBuffer dataByteBuffer = ByteBuffer.wrap(dataIn.getBytes());

    try {/*from w  ww  .  j a  va 2s  .co m*/
        FileOutputStream outputFile = null;
        outputFile = new FileOutputStream(fileIn, true);
        WritableByteChannel outChannel = outputFile.getChannel();

        try {
            outChannel.write(dataByteBuffer);
            outputFile.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    } catch (IOException e) {
        throw new EJBException(e);
    }
}

From source file:com.linkedin.databus.core.DbusEventBuffer.java

/**
 * Batch interface to write events within a range out into a WritableByteChannel
 * @param range//from  ww w.j av a2 s  . com
 * @param writeChannel
 * @param encoding
 * @return number of bytes written
 */
public int batchWrite(Range range, WritableByteChannel writeChannel, Encoding encoding) {
    long startOffset = range.start;
    long endOffset = range.end;
    assert (_bufferPositionParser.bufferIndex(startOffset) == _bufferPositionParser.bufferIndex(endOffset));
    ByteBuffer buf = _buffers[_bufferPositionParser.bufferIndex(startOffset)];
    int endBufferOffset = _bufferPositionParser.bufferOffset(endOffset);
    int startBufferOffset = _bufferPositionParser.bufferOffset(startOffset);
    int bytesWritten = 0;
    switch (encoding) {
    case BINARY: {
        ByteBuffer writeBuf = buf.duplicate().order(_eventFactory.getByteOrder());
        writeBuf.position(startBufferOffset);
        writeBuf.limit(endBufferOffset);
        try {
            bytesWritten = writeChannel.write(writeBuf);
        } catch (IOException e1) {
            LOG.error("batchWrite error: " + e1.getMessage(), e1);
            throw new RuntimeException(e1);
        }
        break;
    }
    case JSON:
    case JSON_PLAIN_VALUE: {
        DbusEventInternalReadable e = _eventFactory.createReadOnlyDbusEventFromBuffer(buf, startBufferOffset);
        int currentBufferOffset = startBufferOffset;
        while (currentBufferOffset != endBufferOffset) {
            e = e.reset(buf, currentBufferOffset);
            e.writeTo(writeChannel, encoding);
            currentBufferOffset += e.size();
        }
    }
    }

    return (bytesWritten);
}

From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java

private void writeFile(File fileIn, String dataIn, int bufSize) {
    ByteBuffer dataByteBuffer = ByteBuffer.wrap(dataIn.getBytes());
    try {/*from  w  w  w  .j  a  va  2s  .  c  om*/
        FileOutputStream outputFile = new FileOutputStream(fileIn, true);
        WritableByteChannel outChannel = outputFile.getChannel();
        try {
            outChannel.write(dataByteBuffer);
            outputFile.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    } catch (IOException e) {
        throw new EJBException(e);
    }
}

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnNewJavaFieldCutter.java

public void cutColumns(InputStream in, int noCardsPerCase, int caseLength, String delimitor, String tabFileName)
        throws IOException {

    if (delimitor == null) {
        delimitor = defaultDelimitor;//from  www . j a v a2  s  .  c  o m
    }

    OUT_LEN = colwidth; // calculated by parseList
    dbgLog.fine("out_len=" + OUT_LEN);

    String firstline = null;

    if (caseLength == 0) {

        int cread;
        int ccounter = 0;

        firstline = "";

        while (caseLength == 0 && (cread = in.read()) != -1) {
            ccounter++;
            if (cread == '\n') {
                caseLength = ccounter;
            }
            char c = (char) cread;
            firstline = firstline + c;
        }

    }

    if (caseLength == 0) {
        throw new IOException("Subsetting failed: could not read incoming byte stream. "
                + "(Requested file may be unavailable or missing)");

    }

    REC_LEN = caseLength;
    dbgLog.fine("REC_LEN=" + REC_LEN);

    for (int i = 0; i < cargSet.get(Long.valueOf(noCardsPerCase)).size(); i++) {
        int varEndOffset = cargSet.get(Long.valueOf(noCardsPerCase)).get(i).get(1);

        if (REC_LEN <= varEndOffset + 1) {
            throw new IOException("Failed to subset incoming byte stream. Invalid input. "
                    + "(Detected the first record of " + REC_LEN + " bytes; "
                    + "one of the columns requested ends at " + varEndOffset + " bytes).");
        }
    }

    Boolean dottednotation = false;
    Boolean foundData = false;

    // cutting a data file

    ReadableByteChannel rbc = Channels.newChannel(in);
    // input byte-buffer size = row-length + 1(=> new line char)
    ByteBuffer inbuffer = ByteBuffer.allocate(REC_LEN);

    OutputStream outs = new FileOutputStream(tabFileName);
    WritableByteChannel outc = Channels.newChannel(outs);
    ByteBuffer outbuffer = null;

    int pos = 0;
    int offset = 0;
    int outoffset = 0;

    int begin = 0;
    int end = 0;
    int blankoffset = 0;

    int blanktail = 0;
    int k;

    try {
        // lc: line counter
        int lc = 0;
        while (firstline != null || rbc.read(inbuffer) != -1) {

            if (firstline != null) {
                // we have the first line saved as a String:
                inbuffer.put(firstline.getBytes());
                firstline = null;
            }

            // calculate i-th card number
            lc++;
            k = lc % noCardsPerCase;
            if (k == 0) {
                k = noCardsPerCase;
            }
            //out.println("***** " +lc+ "-th line, recod k=" + k + " *****");
            byte[] line_read = new byte[OUT_LEN];
            byte[] junk = new byte[REC_LEN];
            byte[] line_final = new byte[OUT_LEN];

            //out.println("READ: " + offset);
            inbuffer.rewind();

            offset = 0;
            outoffset = 0;

            // how many variables are cut from this k-th card
            int noColumns = cargSet.get(Long.valueOf(k)).size();

            //out.println("noColumns=" + noColumns);
            //out.println("cargSet k =" + cargSet.get(Long.valueOf(k)));

            for (int i = 0; i < noColumns; i++) {
                //out.println("**** " + i +"-th col ****");
                begin = cargSet.get(Long.valueOf(k)).get(i).get(0); // bounds[2 * i];
                end = cargSet.get(Long.valueOf(k)).get(i).get(1); // bounds[2 * i + 1];

                //out.println("i: begin: " + begin + "\ti: end:" + end);

                try {
                    // throw away offect bytes
                    if (begin - offset - 1 > 0) {
                        inbuffer.get(junk, 0, (begin - offset - 1));
                    }
                    // get requested bytes
                    inbuffer.get(line_read, outoffset, (end - begin + 1));
                    // set outbound data
                    outbounds[2 * i] = outoffset;
                    outbounds[2 * i + 1] = outoffset + (end - begin);
                    // current position moved to outoffset
                    pos = outoffset;

                    dottednotation = false;
                    foundData = false;

                    blankoffset = 0;
                    blanktail = 0;

                    // as position increases
                    while (pos <= (outoffset + (end - begin))) {

                        //out.println("pos=" + pos + "\tline_read[pos]=" +
                        //    new String(line_read).replace("\000", "\052"));

                        // decimal octal
                        // 48 =>0 60
                        // 46 => . 56
                        // 32 = space 40

                        // dot: 
                        if (line_read[pos] == '\056') {
                            dottednotation = true;
                        }

                        // space:
                        if (line_read[pos] == '\040') {
                            if (foundData) {
                                blanktail = blanktail > 0 ? blanktail : pos - 1;
                            } else {
                                blankoffset = pos + 1;
                            }
                        } else {
                            foundData = true;
                            blanktail = 0;
                        }

                        pos++;
                    }
                    // increase the outoffset by width
                    outoffset += (end - begin + 1);
                    // dot false
                    if (!dottednotation) {
                        if (blankoffset > 0) {
                            // set outbound value to blankoffset
                            outbounds[2 * i] = blankoffset;
                        }
                        if (blanktail > 0) {
                            outbounds[2 * i + 1] = blanktail;
                        }
                    }

                } catch (BufferUnderflowException bufe) {
                    //bufe.printStackTrace();
                    throw new IOException(bufe.getMessage());
                }
                // set offset to the value of end-position
                offset = end;
            }

            outoffset = 0;
            // for each var
            for (int i = 0; i < noColumns; i++) {
                begin = outbounds[2 * i];
                end = outbounds[2 * i + 1];
                //out.println("begin=" + begin + "\t end=" + end);
                for (int j = begin; j <= end; j++) {
                    line_final[outoffset++] = line_read[j];
                }

                if (i < (noColumns - 1)) {
                    line_final[outoffset++] = '\011'; // tab x09
                } else {
                    if (k == cargSet.size()) {
                        line_final[outoffset++] = '\012'; // LF x0A
                    } else {
                        line_final[outoffset++] = '\011'; // tab x09
                    }
                }
            }
            //out.println("line_final=" +
            //    new String(line_final).replace("\000", "\052"));
            outbuffer = ByteBuffer.wrap(line_final, 0, outoffset);
            outc.write(outbuffer);
            inbuffer.clear();

        } // while loop
    } catch (IOException ex) {
        //ex.printStackTrace();
        throw new IOException("Failed to subset incoming fixed-field stream: " + ex.getMessage());
    }

}

From source file:com.sonicle.webtop.mail.Service.java

public static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
        throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
    while (src.read(buffer) != -1) {
        // prepare the buffer to be drained
        buffer.flip();//from w  w  w. j  a  v a  2 s  .  com
        // write to the channel, may block
        dest.write(buffer);
        // If partial transfer, shift remainder down
        // If buffer is empty, same as doing clear()
        buffer.compact();
    }
    // EOF will leave buffer in fill state
    buffer.flip();
    // make sure the buffer is fully drained.
    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}