Java Code Examples for java.nio.channels.ReadableByteChannel

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project kuromoji, under directory /src/main/java/org/atilika/kuromoji/dict/.

Source file: TokenInfoDictionary.java

  26 
vote

protected void loadDictionary(InputStream is) throws IOException {
  DataInputStream dis=new DataInputStream(is);
  int size=dis.readInt();
  ByteBuffer tmpBuffer=ByteBuffer.allocateDirect(size);
  ReadableByteChannel channel=Channels.newChannel(is);
  channel.read(tmpBuffer);
  is.close();
  buffer=tmpBuffer.asReadOnlyBuffer();
}
 

Example 2

From project CIShell, under directory /templates/org.cishell.templates/src/org/cishell/templates/dataset/.

Source file: DatasetFactory.java

  24 
vote

private File copyFile(File dir,String path) throws IOException {
  URL entry=bContext.getBundle().getEntry(path);
  path=path.replace('/',File.separatorChar);
  File outFile=File.createTempFile(getName(path) + "-",".tmp",dir);
  FileOutputStream outStream=new FileOutputStream(outFile);
  ReadableByteChannel in=Channels.newChannel(entry.openStream());
  FileChannel out=outStream.getChannel();
  out.transferFrom(in,0,Integer.MAX_VALUE);
  in.close();
  out.close();
  return outFile;
}
 

Example 3

From project core_4, under directory /impl/src/main/java/org/richfaces/util/.

Source file: Util.java

  22 
vote

public static void copyStreamContent(InputStream is,OutputStream os) throws IOException {
  ReadableByteChannel inChannel=Channels.newChannel(is);
  WritableByteChannel outChannel=Channels.newChannel(os);
  ByteBuffer buffer=ByteBuffer.allocate(8192);
  int read;
  while ((read=inChannel.read(buffer)) > 0) {
    buffer.rewind();
    buffer.limit(read);
    while (read > 0) {
      read-=outChannel.write(buffer);
    }
    buffer.clear();
  }
}
 

Example 4

From project en4j, under directory /NBPlatformApp/NoteRepositoryJDBM/src/main/java/com/rubenlaguna/en4j/noterepositoryjdbm/.

Source file: ResourceImpl.java

  22 
vote

private byte[] getData(InputStream inputStream) throws IOException {
  BufferedInputStream is=new BufferedInputStream(inputStream);
  ReadableByteChannel isc=Channels.newChannel(is);
  ByteArrayOutputStream os=new ByteArrayOutputStream();
  WritableByteChannel osc=Channels.newChannel(os);
  ByteBuffer bb=ByteBuffer.allocate(32000);
  while (isc.read(bb) != -1) {
    bb.flip();
    osc.write(bb);
    bb.clear();
  }
  return os.toByteArray();
}
 

Example 5

From project eucalyptus, under directory /clc/modules/storage-manager/src/edu/ucsb/eucalyptus/cloud/ws/.

Source file: Bukkit.java

  22 
vote

private void unzipImage(String decryptedImageName,String tarredImageName) throws Exception {
  GZIPInputStream in=new GZIPInputStream(new FileInputStream(new File(decryptedImageName)));
  File outFile=new File(tarredImageName);
  ReadableByteChannel inChannel=Channels.newChannel(in);
  WritableByteChannel outChannel=new FileOutputStream(outFile).getChannel();
  ByteBuffer buffer=ByteBuffer.allocate(WalrusQueryDispatcher.DATA_MESSAGE_SIZE);
  while (inChannel.read(buffer) != -1) {
    buffer.flip();
    outChannel.write(buffer);
    buffer.clear();
  }
  outChannel.close();
  inChannel.close();
}
 

Example 6

From project Flume-Hive, under directory /src/javatest/com/cloudera/flume/handlers/exec/.

Source file: TestExecNioSource.java

  22 
vote

@Ignore @Test(timeout=1000) public void testNewChannelBlockingSemantics() throws IOException {
  ReadableByteChannel ch=Channels.newChannel(System.in);
  ByteBuffer buf=ByteBuffer.allocate(10);
  int rdSz=ch.read(buf);
  assertTrue(rdSz < 0);
}
 

Example 7

From project flume_1, under directory /flume-core/src/test/java/com/cloudera/flume/handlers/exec/.

Source file: TestExecNioSource.java

  22 
vote

@Ignore @Test(timeout=1000) public void testNewChannelBlockingSemantics() throws IOException {
  ReadableByteChannel ch=Channels.newChannel(System.in);
  ByteBuffer buf=ByteBuffer.allocate(10);
  int rdSz=ch.read(buf);
  assertTrue(rdSz < 0);
}
 

Example 8

From project GNDMS, under directory /stuff/src/de/zib/gndms/stuff/devel/.

Source file: StreamCopyNIO.java

  22 
vote

/** 
 * Copies the content of is to os using a buffer of size bs. Copying is performed using non-blocking io channels. The source and destionation streams are NOT closed automatically.
 * @param is The source stream.
 * @param os The destination stream.
 * @param bs The buffer size
 * @return The count of copied bytes.
 * @throws IOException
 */
public static int copyStream(InputStream is,OutputStream os,int bs) throws IOException {
  ReadableByteChannel sc=Channels.newChannel(is);
  WritableByteChannel oc=Channels.newChannel(os);
  ByteBuffer buf=ByteBuffer.allocate(bs);
  int bc;
  int tbc=0;
  while ((bc=sc.read(buf)) != -1) {
    buf.flip();
    while (buf.hasRemaining())     oc.write(buf);
    buf.clear();
    tbc+=bc;
  }
  return tbc;
}
 

Example 9

From project httpcore, under directory /httpcore-nio/src/main/java/org/apache/http/nio/entity/.

Source file: EntityAsyncContentProducer.java

  22 
vote

public void close() throws IOException {
  ReadableByteChannel local=this.channel;
  this.channel=null;
  if (local != null) {
    local.close();
  }
}
 

Example 10

From project Jobs, under directory /src/main/java/me/zford/jobs/util/.

Source file: FileDownloader.java

  22 
vote

public static void downloadFile(URL url,File file) throws IOException {
  ReadableByteChannel rbc=Channels.newChannel(url.openStream());
  FileOutputStream fos=new FileOutputStream(file);
  fos.getChannel().transferFrom(rbc,0,1 << 24);
  fos.close();
}
 

Example 11

From project mcore, under directory /src/com/massivecraft/mcore4/util/.

Source file: DiscUtil.java

  22 
vote

public static boolean downloadUrl(String urlstring,File file){
  try {
    URL url=new URL(urlstring);
    ReadableByteChannel rbc=Channels.newChannel(url.openStream());
    FileOutputStream fos=new FileOutputStream(file);
    fos.getChannel().transferFrom(rbc,0,1 << 24);
    return true;
  }
 catch (  Exception e) {
    e.printStackTrace();
    return false;
  }
}
 

Example 12

From project PocketVDC, under directory /src/sate/pocketvdc/util/.

Source file: Grid.java

  22 
vote

/** 
 * Writes default grid data from resources to grid data file in application directory
 * @throws IOException
 */
private static void loadDefaultGrids(Context cxt,File dataFile) throws IOException {
  InputStream input=cxt.getResources().openRawResource(R.raw.griddata);
  ReadableByteChannel in=Channels.newChannel(input);
  FileChannel out=new FileOutputStream(dataFile).getChannel();
  out.transferFrom(in,0,40000);
  in.close();
  out.close();
}
 

Example 13

From project bson4jackson, under directory /src/test/java/de/undercouch/bson4jackson/io/.

Source file: DynamicOutputBufferTest.java

  21 
vote

@Test public void putString() throws Exception {
  DynamicOutputBuffer db=new DynamicOutputBuffer(2);
  db.putString("Hello");
  assertEquals(10,db.size());
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  db.writeTo(baos);
  ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
  ReadableByteChannel channel=Channels.newChannel(bais);
  ByteBuffer buf=ByteBuffer.allocate(10);
  channel.read(buf);
  buf.flip();
  CharBuffer cbuf=buf.asCharBuffer();
  char[] c=new char[5];
  cbuf.get(c);
  String s=String.valueOf(c);
  assertEquals("Hello",s);
}
 

Example 14

From project BukkitUtilities, under directory /src/main/java/name/richardson/james/bukkit/utilities/updater/.

Source file: PluginUpdater.java

  21 
vote

private void getMavenMetaData(final File storage) throws IOException {
  final StringBuilder path=new StringBuilder();
  path.append(this.repositoryURL);
  path.append("/");
  path.append(this.groupId.replace(".","/"));
  path.append("/");
  path.append(this.artifactId);
  path.append("/maven-metadata.xml");
  final URL url=new URL(path.toString());
  ReadableByteChannel rbc=null;
  FileOutputStream fos=null;
  try {
    this.logger.debug(this,"fetching-resource",url.toString());
    rbc=Channels.newChannel(url.openStream());
    this.logger.debug(this,"saving-resource",url.toString());
    fos=new FileOutputStream(storage);
    fos.getChannel().transferFrom(rbc,0,1 << 24);
  }
  finally {
    rbc.close();
    fos.close();
  }
}
 

Example 15

From project capedwarf-blue, under directory /blobstore/src/main/java/org/jboss/capedwarf/blobstore/.

Source file: JBossBlobstoreService.java

  21 
vote

private BlobKey storeUploadedBlob(Part part) throws IOException {
  JBossFileService fileService=getFileService();
  AppEngineFile file=fileService.createNewBlobFile(part.getContentType(),ServletUtils.getFileName(part));
  ReadableByteChannel in=Channels.newChannel(part.getInputStream());
  try {
    FileWriteChannel out=fileService.openWriteChannel(file,true);
    try {
      IOUtils.copy(in,out);
    }
  finally {
      out.closeFinally();
    }
  }
  finally {
    in.close();
  }
  return fileService.getBlobKey(file);
}
 

Example 16

From project enterprise, under directory /com/src/main/java/org/neo4j/com/.

Source file: ServerUtil.java

  21 
vote

public static <T>void applyReceivedTransactions(Response<T> response,GraphDatabaseAPI graphDb,TxHandler txHandler) throws IOException {
  XaDataSourceManager dataSourceManager=graphDb.getXaDataSourceManager();
  try {
    for (    Triplet<String,Long,TxExtractor> tx : IteratorUtil.asIterable(response.transactions())) {
      String resourceName=tx.first();
      XaDataSource dataSource=dataSourceManager.getXaDataSource(resourceName);
      txHandler.accept(tx,dataSource);
      ReadableByteChannel txStream=tx.third().extract();
      try {
        dataSource.applyCommittedTransaction(tx.second(),txStream);
      }
  finally {
        txStream.close();
      }
    }
    txHandler.done();
  }
  finally {
    response.close();
  }
}
 

Example 17

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/sql/.

Source file: FileSupportImpl.java

  21 
vote

/** 
 * @see net.sf.hajdbc.sql.FileSupport#createFile(java.io.InputStream)
 */
@Override public File createFile(InputStream inputStream) throws E {
  try {
    File file=this.createTempFile();
    FileOutputStream output=new FileOutputStream(file);
    try {
      FileChannel fileChannel=output.getChannel();
      ReadableByteChannel inputChannel=Channels.newChannel(inputStream);
      ByteBuffer buffer=ByteBuffer.allocate(BUFFER_SIZE);
      while (inputChannel.read(buffer) > 0) {
        buffer.flip();
        fileChannel.write(buffer);
        buffer.compact();
      }
      return file;
    }
  finally {
      Resources.close(output);
    }
  }
 catch (  IOException e) {
    throw this.exceptionFactory.createException(e);
  }
}
 

Example 18

From project message-wrapper, under directory /src/main/java/jp/co/worksap/message/wrapper/.

Source file: CharsetGuesser.java

  21 
vote

private boolean canDecode(InputStream input,Charset charset) throws IOException {
  ReadableByteChannel channel=Channels.newChannel(input);
  CharsetDecoder decoder=charset.newDecoder();
  ByteBuffer byteBuffer=ByteBuffer.allocate(SIZE * 2);
  CharBuffer charBuffer=CharBuffer.allocate(SIZE);
  boolean endOfInput=false;
  while (!endOfInput) {
    int n=channel.read(byteBuffer);
    byteBuffer.flip();
    endOfInput=(n == -1);
    CoderResult coderResult=decoder.decode(byteBuffer,charBuffer,endOfInput);
    if (coderResult.isError()) {
      return false;
    }
    charBuffer.clear();
    while (coderResult == CoderResult.OVERFLOW) {
      coderResult=decoder.decode(byteBuffer,charBuffer,endOfInput);
      charBuffer.clear();
    }
    byteBuffer.compact();
  }
  CoderResult coderResult;
  while ((coderResult=decoder.flush(charBuffer)) == CoderResult.OVERFLOW) {
    charBuffer.clear();
  }
  if (coderResult.isError()) {
    return false;
  }
  return true;
}
 

Example 19

From project mmoCore, under directory /src/main/java/mmo/Core/.

Source file: MMOCore.java

  21 
vote

public void getUpdate(final MMOPlugin mmo){
  try {
    FileOutputStream fos=null;
    try {
      final File directory=new File(getServer().getUpdateFolder());
      if (!directory.exists()) {
        try {
          directory.mkdir();
        }
 catch (        SecurityException e1) {
        }
      }
      final File newFile=new File(directory.getPath(),mmo.description.getName() + ".jar");
      if (newFile.canWrite()) {
        final URL url=new URL("http://mmo.rycochet.net/" + mmo.description.getName() + ".jar");
        final HttpURLConnection con=(HttpURLConnection)(url.openConnection());
        final ReadableByteChannel rbc=Channels.newChannel(con.getInputStream());
        fos=new FileOutputStream(newFile);
        fos.getChannel().transferFrom(rbc,0,1 << 24);
      }
    }
 catch (    Exception e) {
    }
 finally {
      if (fos != null) {
        try {
          fos.close();
        }
 catch (        IOException e) {
        }
      }
    }
  }
 catch (  Exception e) {
  }
}
 

Example 20

From project mvel, under directory /src/main/java/org/mvel2/util/.

Source file: ParseTools.java

  21 
vote

public static char[] loadFromFile(File file,String encoding) throws IOException {
  if (!file.exists())   throw new RuntimeException("cannot find file: " + file.getName());
  FileInputStream inStream=null;
  ReadableByteChannel fc=null;
  try {
    fc=(inStream=new FileInputStream(file)).getChannel();
    ByteBuffer buf=allocateDirect(10);
    StringAppender sb=new StringAppender((int)file.length(),encoding);
    int read=0;
    while (read >= 0) {
      buf.rewind();
      read=fc.read(buf);
      buf.rewind();
      for (; read > 0; read--) {
        sb.append(buf.get());
      }
    }
    return sb.toChars();
  }
 catch (  FileNotFoundException e) {
  }
 finally {
    if (inStream != null)     inStream.close();
    if (fc != null)     fc.close();
  }
  return null;
}
 

Example 21

From project NarrowtuxLib, under directory /src/main/java/com/narrowtux/narrowtuxlib/.

Source file: NarrowtuxLib.java

  21 
vote

protected void update(){
  if (!isUpdateAvailable()) {
    return;
  }
  try {
    File directory=new File(Bukkit.getServer().getUpdateFolder());
    if (!directory.exists()) {
      directory.mkdir();
    }
    File plugin=new File(directory.getPath(),"NarrowtuxLib.jar");
    if (!plugin.exists()) {
      URL bukkitContrib=new URL("http://tetragaming.com/narrowtux/plugins/NarrowtuxLib.jar");
      HttpURLConnection con=(HttpURLConnection)(bukkitContrib.openConnection());
      System.setProperty("http.agent","");
      con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30");
      ReadableByteChannel rbc=Channels.newChannel(con.getInputStream());
      FileOutputStream fos=new FileOutputStream(plugin);
      fos.getChannel().transferFrom(rbc,0,1 << 24);
    }
  }
 catch (  Exception e) {
  }
}
 

Example 22

From project open-data-node, under directory /src/main/java/sk/opendata/odn/harvester/.

Source file: AbstractHarvester.java

  21 
vote

/** 
 * Update our data using data harvested from source.
 * @throws OdnHarvesterException when some harvesting error occurs
 * @throws OdnSerializationException when some serialization error occurs
 * @throws OdnRepositoryException when some repository error occurs
 */
public void update() throws OdnHarvesterException, OdnSerializationException, OdnRepositoryException {
  File tempFile=null;
  logger.info("harvesting started (" + this.sourceUrl.toExternalForm() + ")");
  try {
    tempFile=File.createTempFile(ODN_HARVESTER_TMP_PREF,ODN_HARVESTER_TMP_SUFF);
    tempFile.deleteOnExit();
    URLConnection csvConnection=getSourceUrl().openConnection();
    csvConnection.setRequestProperty("User-Agent","Open Data Node (http://opendata.sk/liferay/open-data-node)");
    ReadableByteChannel rbc=Channels.newChannel(csvConnection.getInputStream());
    FileOutputStream fos=new FileOutputStream(tempFile);
    long count=fos.getChannel().transferFrom(rbc,0,Long.MAX_VALUE);
    logger.debug("downloaded " + Long.toString(count) + " bytes from "+ sourceUrl.toExternalForm()+ " to "+ tempFile.getAbsolutePath());
    fos.close();
    rbc.close();
    performEtl(tempFile);
    if (!tempFile.delete())     logger.error("failed to delete temporary file " + tempFile.getAbsolutePath());
  }
 catch (  IOException e) {
    logger.error("IO exception",e);
  }
  logger.info("harvesting finished (" + this.sourceUrl.toExternalForm() + ")");
}
 

Example 23

From project org.ops4j.pax.runner, under directory /pax-runner-platform/src/main/java/org/ops4j/pax/runner/platform/internal/.

Source file: StreamUtils.java

  21 
vote

/** 
 * 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
 */
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();
  }
}
 

Example 24

From project RoyalCommands, under directory /src/org/royaldev/royalcommands/.

Source file: RUtils.java

  21 
vote

public static boolean downloadFile(String s,String saveto){
  try {
    URL website=new URL(s);
    ReadableByteChannel rbc=Channels.newChannel(website.openStream());
    File save=new File(saveto);
    if (!save.exists()) {
      save.getParentFile().mkdirs();
      save.createNewFile();
    }
    FileOutputStream fos=new FileOutputStream(saveto);
    while (fos.getChannel().transferFrom(rbc,0,1 << 24) > 0) {
    }
    fos.flush();
    fos.close();
    rbc.close();
    return true;
  }
 catch (  MalformedURLException e) {
    RoyalCommands.instance.getLogger().severe("Could not download " + s + ": "+ e.getMessage());
  }
catch (  IOException e) {
    RoyalCommands.instance.getLogger().severe("Could not download " + s + ": "+ e.getMessage());
  }
  return false;
}
 

Example 25

From project servicemix-utils, under directory /src/main/java/org/apache/servicemix/util/.

Source file: FileUtil.java

  21 
vote

/** 
 * Copies the whole content from the input stream to the output stream using nio channels to speed it up.
 * @param input  the input stream
 * @param output the output stream
 * @throws IOException if any IO error occurs during read/write
 */
public static void fastCopy(final InputStream input,final OutputStream output) throws IOException {
  final ReadableByteChannel src=Channels.newChannel(input);
  final WritableByteChannel dest=Channels.newChannel(output);
  final ByteBuffer buffer=ByteBuffer.allocateDirect(16 * 1024);
  while (src.read(buffer) != -1) {
    buffer.flip();
    dest.write(buffer);
    buffer.compact();
  }
  buffer.flip();
  while (buffer.hasRemaining()) {
    dest.write(buffer);
  }
  src.close();
  dest.close();
}
 

Example 26

From project SpoutTrade_1, under directory /src/main/java/net/ark3l/SpoutTrade/Updater/.

Source file: UpdateChecker.java

  21 
vote

public static void checkForUpdates(Plugin plugin){
  Log.info("Checking for updates...");
  try {
    BukkitDevDownload bdd=getBukkitDevDownload("spouttrade");
    String[] version=bdd.getVersion().split(" ");
    if (!plugin.getDescription().getVersion().equalsIgnoreCase(version[0])) {
      Log.warning("This version is out of date!");
      Log.warning("This version: " + plugin.getDescription().getVersion());
      Log.warning("Latest version: " + version[0]);
      URL google=new URL(bdd.getLink());
      ReadableByteChannel rbc=Channels.newChannel(google.openStream());
      File directory=new File(plugin.getServer().getUpdateFolder());
      if (!directory.exists()) {
        directory.mkdirs();
      }
      File file=new File(directory.getPath(),"SpoutTrade.jar");
      if (file.exists()) {
        Log.info("Jar already exists in update folder.");
      }
 else {
        Log.info("Downloading latest version.");
        FileOutputStream fos=new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc,0,1 << 24);
        fos.close();
      }
    }
  }
 catch (  Exception e) {
    Log.severe("Error while checking for updates!");
  }
}
 

Example 27

From project TahoeLAFS-android, under directory /src/org/allmydata/tahoelafs/.

Source file: RESTClient.java

  21 
vote

public void download(String url,String dst) throws IOException {
  Log.i(TAG,"Downloading " + url + " to "+ dst);
  Log.d(TAG,"Opening url " + url);
  InputStream in=openURL(url);
  Log.d(TAG,"Opening destination file " + dst);
  OutputStream out=new FileOutputStream(dst);
  Log.d(TAG,"Writing file");
  final ReadableByteChannel inputChannel=Channels.newChannel(in);
  final WritableByteChannel outputChannel=Channels.newChannel(out);
  fastChannelCopy(inputChannel,outputChannel);
  inputChannel.close();
  outputChannel.close();
  Log.d(TAG,"Closing HTTP connection");
  in.close();
  Log.d(TAG,"Closing file");
  out.close();
}
 

Example 28

From project Terasology, under directory /src/main/java/org/terasology/game/.

Source file: TerasologyApplet.java

  21 
vote

private void obtainMods(){
  String[] mods=getParameter("mods").split(",");
  String modsPath=getParameter("mods_path") + "mods/";
  for (  String mod : mods) {
    try {
      URL url=new URL(modsPath + mod);
      ReadableByteChannel rbc=Channels.newChannel(url.openStream());
      FileOutputStream fos=new FileOutputStream(new File(PathManager.getInstance().getModPath(),mod));
      long readBytes=fos.getChannel().transferFrom(rbc,0,1 << 24);
      while (readBytes == 1 << 24) {
        readBytes=fos.getChannel().transferFrom(rbc,0,1 << 24);
      }
      fos.close();
    }
 catch (    MalformedURLException e) {
      logger.error("Unable to obtain mod '{}'",mod,e);
    }
catch (    FileNotFoundException e) {
      logger.error("Unable to obtain mod '{}'",mod,e);
    }
catch (    IOException e) {
      logger.error("Unable to obtain mod '{}'",mod,e);
    }
  }
}
 

Example 29

From project TeraSpout, under directory /src/main/java/org/terasology/game/.

Source file: TerasologyApplet.java

  21 
vote

private void obtainMods(){
  String[] mods=getParameter("mods").split(",");
  String modsPath=getParameter("mods_path") + "mods/";
  for (  String mod : mods) {
    try {
      URL url=new URL(modsPath + mod);
      ReadableByteChannel rbc=Channels.newChannel(url.openStream());
      FileOutputStream fos=new FileOutputStream(new File(PathManager.getInstance().getModPath(),mod));
      long readBytes=fos.getChannel().transferFrom(rbc,0,1 << 24);
      while (readBytes == 1 << 24) {
        readBytes=fos.getChannel().transferFrom(rbc,0,1 << 24);
      }
      fos.close();
    }
 catch (    MalformedURLException e) {
      Logger.getLogger(TerasologyApplet.class.getName()).log(Level.SEVERE,"Unable to obtain mod '" + mod + "'",e);
    }
catch (    FileNotFoundException e) {
      Logger.getLogger(TerasologyApplet.class.getName()).log(Level.SEVERE,"Unable to obtain mod '" + mod + "'",e);
    }
catch (    IOException e) {
      Logger.getLogger(TerasologyApplet.class.getName()).log(Level.SEVERE,"Unable to obtain mod '" + mod + "'",e);
    }
  }
}
 

Example 30

From project torquebox, under directory /modules/web/src/main/java/org/torquebox/web/rack/.

Source file: RewindableChannel.java

  21 
vote

protected FileChannel getTempFileChannel() throws java.io.IOException {
  if (tempFileChannel == null) {
    File tmpDir=new File(System.getProperty("jboss.server.temp.dir"));
    tempFile=File.createTempFile("TorqueBoxRewindableChannel",null,tmpDir);
    tempFileRandom=new RandomAccessFile(tempFile,"rw");
    tempFileChannel=tempFileRandom.getChannel();
    ReadableByteChannel inputChannel=Channels.newChannel(this.inputStream);
    long bytesRead=0;
    long transferPosition=0;
    while ((bytesRead=tempFileChannel.transferFrom(inputChannel,transferPosition,1024 * 4)) > 0) {
      transferPosition+=bytesRead;
    }
    inputChannel.close();
  }
  return tempFileChannel;
}
 

Example 31

From project Waypoint, under directory /src/me/pirogoeth/waypoint/util/.

Source file: AutoUpdate.java

  21 
vote

public void doUpdate(){
  if (!checkUpdate()) {
    return;
  }
  try {
    URL source=new URL("http://maio.me/downloads/Waypoint/Waypoint.jar");
    File directory=new File(Bukkit.getServer().getUpdateFolder());
    if (!directory.exists()) {
      directory.mkdir();
    }
    File controller=new File(directory.getPath(),"Waypoint.jar");
    if (!controller.exists()) {
      HttpURLConnection con=(HttpURLConnection)(source.openConnection());
      ReadableByteChannel rbc=Channels.newChannel(con.getInputStream());
      FileOutputStream fos=new FileOutputStream(controller);
      fos.getChannel().transferFrom(rbc,0,1 << 24);
      fos.close();
    }
  }
 catch (  Exception e) {
  }
}
 

Example 32

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/net/io/.

Source file: PacketInputStream.java

  19 
vote

/** 
 * Reads a packet from the provided channel, appending to any partially read packet. If the entire packet data is not yet available, <code>readPacket</code> will return false, otherwise true. <p> <em>Note:</em> when this method returns true, it is required that the caller read <em>all</em> of the packet data from the stream before again calling  {@link #readPacket} as the previous packet'sdata will be elimitated upon the subsequent call.
 * @return true if the entire packet has been read, false if the buffercontains only a partial packet.
 */
public boolean readPacket(ReadableByteChannel source) throws IOException {
  if (_buffer.limit() == _length) {
    _buffer.limit(_have);
    _buffer.position(_length);
    _buffer.compact();
    _have-=_length;
    _length=decodeLength();
  }
  if (checkForCompletePacket()) {
    return true;
  }
  do {
    int got=source.read(_buffer);
    if (got == -1) {
      throw new EOFException();
    }
    _have+=got;
    if (_length == -1) {
      _length=decodeLength();
    }
    if (_buffer.remaining() > 0) {
      break;
    }
    if ((_length > 0) && (_have >= _length)) {
      break;
    }
    int newSize=_buffer.capacity() << 1;
    newSize=newSize > _length ? newSize : _length + 16;
    ByteBuffer newbuf=ByteBuffer.allocate(newSize);
    newbuf.put((ByteBuffer)_buffer.flip());
    _buffer=newbuf;
  }
 while (_buffer.capacity() < MAX_BUFFER_CAPACITY);
  return checkForCompletePacket();
}
 

Example 33

From project android-aac-enc, under directory /src/com/coremedia/iso/boxes/mdat/.

Source file: MediaDataBox.java

  19 
vote

public void parse(ReadableByteChannel readableByteChannel,ByteBuffer header,long contentSize,BoxParser boxParser) throws IOException {
  this.header=header;
  if (readableByteChannel instanceof FileChannel && contentSize > 1024 * 1024) {
    content=((FileChannel)readableByteChannel).map(FileChannel.MapMode.READ_ONLY,((FileChannel)readableByteChannel).position(),contentSize);
    ((FileChannel)readableByteChannel).position(((FileChannel)readableByteChannel).position() + contentSize);
  }
 else {
    content=ChannelHelper.readFully(readableByteChannel,l2i(contentSize));
  }
}
 

Example 34

From project android_external_guava, under directory /src/com/google/common/io/.

Source file: ByteStreams.java

  19 
vote

/** 
 * Copies all bytes from the readable channel to the writable channel. Does not close or flush either channel.
 * @param from the readable channel to read from
 * @param to the writable channel to write to
 * @return the number of bytes copied
 * @throws IOException if an I/O error occurs
 */
public static long copy(ReadableByteChannel from,WritableByteChannel to) throws IOException {
  ByteBuffer buf=ByteBuffer.allocate(BUF_SIZE);
  long total=0;
  while (from.read(buf) != -1) {
    buf.flip();
    while (buf.hasRemaining()) {
      total+=to.write(buf);
    }
    buf.clear();
  }
  return total;
}
 

Example 35

From project daap, under directory /src/main/java/org/ardverk/daap/nio/.

Source file: DaapLineReaderNIO.java

  19 
vote

/** 
 * @param in
 * @throws IOException
 * @return
 */
public String read(ByteBuffer in,ReadableByteChannel channel) throws IOException {
  complete=false;
  if (in.remaining() > 0) {
    String line=line(in);
    if (line != null) {
      if (line.length() == 0)       return null;
      return line;
    }
  }
  in.clear();
  int len=channel.read(in);
  if (len < 0) {
    lineBuf=null;
    throw new IOException("Socket closed");
  }
  in.flip();
  String line=line(in);
  if (line != null) {
    if (line.length() != 0) {
      return line;
    }
  }
  return null;
}
 

Example 36

From project flapjack, under directory /flapjack/src/main/java/flapjack/io/.

Source file: FileUtilImpl.java

  19 
vote

public void close(ReadableByteChannel channel){
  if (channel != null) {
    try {
      channel.close();
    }
 catch (    IOException e) {
      throw new RuntimeException(e);
    }
  }
}
 

Example 37

From project gecko, under directory /src/main/java/com/taobao/gecko/core/nio/impl/.

Source file: NioTCPSession.java

  19 
vote

protected final int blockingRead() throws ClosedChannelException, IOException {
  int n=0;
  final Selector readSelector=SelectorFactory.getSelector();
  SelectionKey tmpKey=null;
  try {
    if (this.selectableChannel.isOpen()) {
      tmpKey=this.selectableChannel.register(readSelector,0);
      tmpKey.interestOps(tmpKey.interestOps() | SelectionKey.OP_READ);
      final int code=readSelector.select(500);
      tmpKey.interestOps(tmpKey.interestOps() & ~SelectionKey.OP_READ);
      if (code > 0) {
        do {
          n=((ReadableByteChannel)this.selectableChannel).read(this.readBuffer.buf());
          if (log.isDebugEnabled()) {
            log.debug("use temp selector read " + n + " bytes");
          }
        }
 while (n > 0 && this.readBuffer.hasRemaining());
        this.readBuffer.flip();
        this.decode();
        this.readBuffer.compact();
      }
    }
  }
  finally {
    if (tmpKey != null) {
      tmpKey.cancel();
      tmpKey=null;
    }
    if (readSelector != null) {
      readSelector.selectNow();
      SelectorFactory.returnSelector(readSelector);
    }
  }
  return n;
}
 

Example 38

From project hawtdispatch, under directory /hawtdispatch-transport/src/main/java/org/fusesource/hawtdispatch/transport/.

Source file: SslProtocolCodec.java

  19 
vote

private void initNext(){
  if (next != null) {
    this.next.setTransport(new TransportFilter(transport){
      public ReadableByteChannel getReadChannel(){
        return sslReadChannel;
      }
      public WritableByteChannel getWriteChannel(){
        return sslWriteChannel;
      }
    }
);
  }
}
 

Example 39

From project hs4j, under directory /src/main/java/com/google/code/hs4j/network/nio/impl/.

Source file: NioTCPSession.java

  19 
vote

/** 
 * Blocking read using temp selector
 * @return
 * @throws ClosedChannelException
 * @throws IOException
 */
protected final int blockingRead() throws ClosedChannelException, IOException {
  int n=0;
  Selector readSelector=SelectorFactory.getSelector();
  SelectionKey tmpKey=null;
  try {
    if (selectableChannel.isOpen()) {
      tmpKey=selectableChannel.register(readSelector,0);
      tmpKey.interestOps(tmpKey.interestOps() | SelectionKey.OP_READ);
      int code=readSelector.select(500);
      tmpKey.interestOps(tmpKey.interestOps() & ~SelectionKey.OP_READ);
      if (code > 0) {
        do {
          n=((ReadableByteChannel)selectableChannel).read(readBuffer.buf());
          if (log.isDebugEnabled()) {
            log.debug("use temp selector read " + n + " bytes");
          }
        }
 while (n > 0 && readBuffer.hasRemaining());
        readBuffer.flip();
        decode();
        readBuffer.compact();
      }
    }
  }
  finally {
    if (tmpKey != null) {
      tmpKey.cancel();
      tmpKey=null;
    }
    if (readSelector != null) {
      readSelector.selectNow();
      SelectorFactory.returnSelector(readSelector);
    }
  }
  return n;
}
 

Example 40

From project IOCipher, under directory /src/info/guardianproject/iocipher/.

Source file: IOCipherFileChannel.java

  19 
vote

/** 
 * Reads up to  {@code count} bytes from {@code src} and stores them in thischannel's file starting at  {@code position}. No bytes are transferred if {@code position} is larger than the size of this channel's file. Lessthan  {@code count} bytes are transferred if there are less bytesremaining in the source channel or if the source channel is non-blocking and has less than  {@code count} bytes immediately available in its outputbuffer. <p> Note that this channel's position is not modified.
 * @param src the source channel to read bytes from.
 * @param position the non-negative start position.
 * @param count the non-negative number of bytes to transfer.
 * @return the number of bytes that are transferred.
 * @throws IllegalArgumentException if the parameters are invalid.
 * @throws NonReadableChannelException if the source channel is not readable.
 * @throws NonWritableChannelException if this channel is not writable.
 * @throws ClosedChannelException if either channel has already been closed.
 * @throws AsynchronousCloseException if either channel is closed by other threads during this operation.
 * @throws ClosedByInterruptException if the thread is interrupted during this operation.
 * @throws IOException if any I/O error occurs.
 */
public long transferFrom(ReadableByteChannel src,long position,long count) throws IOException {
  checkOpen();
  if (!src.isOpen()) {
    throw new ClosedChannelException();
  }
  checkWritable();
  if (position < 0 || count < 0 || count > Integer.MAX_VALUE) {
    throw new IllegalArgumentException("position=" + position + " count="+ count);
  }
  if (position > size()) {
    return 0;
  }
  ByteBuffer buffer=ByteBuffer.allocate((int)count);
  src.read(buffer);
  buffer.flip();
  return write(buffer,position);
}
 

Example 41

From project jafka, under directory /src/main/java/com/sohu/jafka/network/.

Source file: BoundedByteBufferReceive.java

  19 
vote

public int readFrom(ReadableByteChannel channel) throws IOException {
  expectIncomplete();
  int read=0;
  if (sizeBuffer.remaining() > 0) {
    read+=Utils.read(channel,sizeBuffer);
  }
  if (contentBuffer == null && !sizeBuffer.hasRemaining()) {
    sizeBuffer.rewind();
    int size=sizeBuffer.getInt();
    if (size <= 0) {
      throw new InvalidRequestException(format("%d is not a valid request size.",size));
    }
    if (size > maxRequestSize) {
      final String msg="Request of length %d is not valid, it is larger than the maximum size of %d bytes.";
      throw new InvalidRequestException(format(msg,size,maxRequestSize));
    }
    contentBuffer=byteBufferAllocate(size);
  }
  if (contentBuffer != null) {
    read=Utils.read(channel,contentBuffer);
    if (!contentBuffer.hasRemaining()) {
      contentBuffer.rewind();
      setCompleted();
    }
  }
  return read;
}
 

Example 42

From project krati, under directory /krati-main/src/main/java/krati/core/segment/.

Source file: SegmentIndexBuffer.java

  19 
vote

/** 
 * Reads from the specified <code>channel</code> into this SegmentIndexBuffer.
 * @param channel - the readable channel
 * @return the number of bytes read from the specified channel.
 * @throws IOException
 */
public int read(ReadableByteChannel channel) throws IOException {
  ByteBuffer header=ByteBuffer.allocate(HEADER_LENGTH);
  read(channel,header,HEADER_LENGTH,"Invalid Header");
  int segmentId=header.getInt(0);
  long lastForcedTime=header.getLong(4);
  int size=header.getInt(12);
  int dataLength=size << 3;
  ByteBuffer data=ByteBuffer.allocate(dataLength);
  read(channel,data,dataLength,"Invalid Data");
  ByteBuffer md5=ByteBuffer.allocate(MD5_LENGTH);
  read(channel,md5,MD5_LENGTH,"Invalid MD5");
  try {
    MessageDigest m=MessageDigest.getInstance("MD5");
    m.reset();
    m.update(header.array());
    m.update(data.array());
    byte[] digest=ensure128BitMD5(m.digest());
    if (Arrays.equals(md5.array(),digest)) {
      setSegmentId(segmentId);
      setSegmentLastForcedTime(lastForcedTime);
      data.flip();
      put(data);
    }
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IOException(e);
  }
  return (dataLength + HEADER_FOOTER_LENGTH);
}
 

Example 43

From project narya, under directory /core/src/main/java/com/threerings/io/.

Source file: FramedInputStream.java

  19 
vote

/** 
 * Reads a frame from the provided channel, appending to any partially read frame. If the entire frame data is not yet available, <code>readFrame</code> will return false, otherwise true. <p> <em>Note:</em> when this method returns true, it is required that the caller read <em>all</em> of the frame data from the stream before again calling  {@link #readFrame} as the previous frame'sdata will be elimitated upon the subsequent call.
 * @return true if the entire frame has been read, false if the buffercontains only a partial frame.
 */
public boolean readFrame(ReadableByteChannel source) throws IOException {
  if (_buffer.limit() == _length) {
    _buffer.limit(_have);
    _buffer.position(_length);
    _buffer.compact();
    _have-=_length;
    _length=decodeLength();
  }
  if (checkForCompleteFrame()) {
    return true;
  }
  do {
    int got=source.read(_buffer);
    if (got == -1) {
      throw new EOFException();
    }
    _have+=got;
    if (_length == -1) {
      _length=decodeLength();
    }
    if (_buffer.remaining() > 0) {
      break;
    }
    if ((_length > 0) && (_have >= _length)) {
      break;
    }
    ByteBuffer newbuf=ByteBuffer.allocate(_buffer.capacity() << 1);
    newbuf.put((ByteBuffer)_buffer.flip());
    _buffer=newbuf;
  }
 while (_buffer.capacity() < MAX_BUFFER_CAPACITY);
  return checkForCompleteFrame();
}
 

Example 44

From project netifera, under directory /platform/com.netifera.platform.net/com.netifera.platform.net.sockets/src/com/netifera/platform/net/sockets/internal/.

Source file: SocketEngineService.java

  19 
vote

public <A>Future<Integer> asynchronousRead(final AsynchronousSelectableChannel channel,final ByteBuffer dst,long timeout,TimeUnit unit,final A attachment,final CompletionHandler<Integer,? super A> handler){
  long deadline=System.currentTimeMillis() + unit.toMillis(timeout);
  SelectionFuture<Integer,A> future=new SelectionFuture<Integer,A>(handler,attachment,deadline,logger,new Callable<Integer>(){
    public Integer call() throws Exception {
      Integer count=((ReadableByteChannel)channel.getWrappedChannel()).read(dst);
      if (count <= 0)       throw new ClosedChannelException();
      return count;
    }
  }
);
  SelectionContext context=contextMap.get(channel);
  if (context == null) {
    logger.error("Context not found on read() " + channel);
    handler.cancelled(attachment);
    return null;
  }
  context.enqueueRead(future);
  registrationQueue.add(context);
  selector.wakeup();
  return future;
}
 

Example 45

From project netty, under directory /handler/src/main/java/io/netty/handler/stream/.

Source file: ChunkedNioStream.java

  19 
vote

/** 
 * Creates a new instance that fetches data from the specified channel.
 * @param chunkSize the number of bytes to fetch on each{@link #nextChunk()} call
 */
public ChunkedNioStream(ReadableByteChannel in,int chunkSize){
  if (in == null) {
    throw new NullPointerException("in");
  }
  if (chunkSize <= 0) {
    throw new IllegalArgumentException("chunkSize: " + chunkSize + " (expected: a positive integer)");
  }
  this.in=in;
  offset=0;
  this.chunkSize=chunkSize;
  byteBuffer=ByteBuffer.allocate(chunkSize);
}
 

Example 46

From project platform_external_guava, under directory /src/com/google/common/io/.

Source file: ByteStreams.java

  19 
vote

/** 
 * Copies all bytes from the readable channel to the writable channel. Does not close or flush either channel.
 * @param from the readable channel to read from
 * @param to the writable channel to write to
 * @return the number of bytes copied
 * @throws IOException if an I/O error occurs
 */
public static long copy(ReadableByteChannel from,WritableByteChannel to) throws IOException {
  ByteBuffer buf=ByteBuffer.allocate(BUF_SIZE);
  long total=0;
  while (from.read(buf) != -1) {
    buf.flip();
    while (buf.hasRemaining()) {
      total+=to.write(buf);
    }
    buf.clear();
  }
  return total;
}
 

Example 47

From project SpoutcraftLauncher, under directory /src/main/java/org/spoutcraft/launcher/util/.

Source file: Download.java

  19 
vote

public MonitorThread(Thread downloadThread,ReadableByteChannel rbc){
  super("Download Monitor Thread");
  this.setDaemon(true);
  this.rbc=rbc;
  this.downloadThread=downloadThread;
}
 

Example 48

From project stirling, under directory /src/main/java/stirling/itch/io/.

Source file: MessageIterator.java

  19 
vote

public MessageIterator(ReadableByteChannel channel,MessageParser<Message> parser,int readBufferSize){
  this.channel=channel;
  this.parser=parser;
  this.buffer=ByteBuffer.allocate(readBufferSize);
  buffer.order(ByteOrder.BIG_ENDIAN);
  refill();
  next=read();
}
 

Example 49

From project xmemcached, under directory /src/main/java/com/google/code/yanf4j/nio/impl/.

Source file: NioTCPSession.java

  19 
vote

/** 
 * Blocking read using temp selector
 * @return
 * @throws ClosedChannelException
 * @throws IOException
 */
protected final int blockingRead() throws ClosedChannelException, IOException {
  int n=0;
  int readCount=0;
  Selector readSelector=SelectorFactory.getSelector();
  SelectionKey tmpKey=null;
  try {
    if (this.selectableChannel.isOpen()) {
      tmpKey=this.selectableChannel.register(readSelector,0);
      tmpKey.interestOps(tmpKey.interestOps() | SelectionKey.OP_READ);
      int code=readSelector.select(500);
      tmpKey.interestOps(tmpKey.interestOps() & ~SelectionKey.OP_READ);
      if (code > 0) {
        do {
          n=((ReadableByteChannel)this.selectableChannel).read(this.readBuffer.buf());
          readCount+=n;
          if (log.isDebugEnabled()) {
            log.debug("use temp selector read " + n + " bytes");
          }
        }
 while (n > 0 && this.readBuffer.hasRemaining());
        if (readCount > 0) {
          decodeAndDispatch();
        }
      }
    }
  }
  finally {
    if (tmpKey != null) {
      tmpKey.cancel();
      tmpKey=null;
    }
    if (readSelector != null) {
      readSelector.selectNow();
      SelectorFactory.returnSelector(readSelector);
    }
  }
  return readCount;
}
 

Example 50

From project xnio_1, under directory /api/src/main/java/org/xnio/channels/.

Source file: Channels.java

  19 
vote

/** 
 * Simple utility method to execute a blocking read on a readable byte channel.  This method blocks until the channel is readable, and then the message is read.
 * @param channel the channel to read from
 * @param buffer the buffer into which bytes are to be transferred
 * @param < C > the channel type
 * @return the number of bytes read
 * @throws IOException if an I/O exception occurs
 * @since 1.2
 */
public static <C extends ReadableByteChannel & SuspendableReadChannel>int readBlocking(C channel,ByteBuffer buffer) throws IOException {
  int res;
  while ((res=channel.read(buffer)) == 0 && buffer.hasRemaining()) {
    channel.awaitReadable();
  }
  return res;
}
 

Example 51

From project zoie, under directory /zoie-core/src/main/java/proj/zoie/api/.

Source file: DefaultDirectoryManager.java

  19 
vote

public boolean transferFromChannelToFile(ReadableByteChannel channel,String fileName) throws IOException {
  if (!_location.exists()) {
    _location.mkdirs();
  }
  long dataLen=ChannelUtil.readLong(channel);
  if (dataLen < 0)   return false;
  File file=new File(_location,fileName);
  RandomAccessFile raf=null;
  FileChannel fc=null;
  try {
    log.info("transferFromChannelToFile for " + fileName + " with "+ dataLen+ " bytes");
    raf=new RandomAccessFile(file,"rw");
    fc=raf.getChannel();
    long position=0;
    do {
      position+=fc.transferFrom(channel,position,dataLen - position);
    }
 while (position < dataLen);
    return true;
  }
  finally {
    try {
      if (fc != null)       fc.close();
    }
  finally {
      if (raf != null)       raf.close();
    }
  }
}