Example usage for java.io RandomAccessFile getChannel

List of usage examples for java.io RandomAccessFile getChannel

Introduction

In this page you can find the example usage for java.io RandomAccessFile getChannel.

Prototype

public final FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file.

Usage

From source file:interactivespaces.master.resource.deployment.internal.NettyHttpRemoteRepositoryMasterWebServerHandler.java

/**
 * Attempt to handle an HTTP request by scanning through all registered
 * handlers.//from   www.j  a v  a2s.  c om
 *
 * @param context
 *          the context for the request
 * @param req
 *          the request
 * @return {@code true} if the request was handled
 *
 * @throws IOException
 *           something bad happened
 */
private boolean handleWebRequest(ChannelHandlerContext context, HttpRequest req) throws IOException {
    String url = req.getUri();
    int pos = url.indexOf('?');
    if (pos != -1)
        url = url.substring(0, pos);

    int luriPrefixLength = uriPrefix.length();
    String bundleName = url.substring(url.indexOf(uriPrefix) + luriPrefixLength);

    File file = featureRepository.getFeatureFile(bundleName);
    if (file == null) {
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        // sendError(ctx, NOT_FOUND);

        return false;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);

    Channel channel = context.getChannel();

    // Write the initial line and the header.
    channel.write(response);

    // Write the content.
    ChannelFuture writeFuture;
    if (channel.getPipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = channel.write(region);
        writeFuture.addListener(new ChannelFutureProgressListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                region.releaseExternalResources();
            }

            @Override
            public void operationProgressed(ChannelFuture arg0, long arg1, long arg2, long arg3)
                    throws Exception {
                // Do nothing
            }

        });
    }

    // Decide whether to close the connection or not.
    if (!isKeepAlive(req)) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }

    return true;
}

From source file:org.apache.cordova.core.FileUtils.java

/**
 * Truncate the file to size/*from   w  ww  .  ja  v a  2s. co m*/
 *
 * @param filename
 * @param size
 * @throws FileNotFoundException, IOException
 * @throws NoModificationAllowedException
 */
private long truncateFile(String filename, long size)
        throws FileNotFoundException, IOException, NoModificationAllowedException {
    if (filename.startsWith("content://")) {
        throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
    }

    filename = FileHelper.getRealPath(filename, cordova);

    RandomAccessFile raf = new RandomAccessFile(filename, "rw");
    try {
        if (raf.length() >= size) {
            FileChannel channel = raf.getChannel();
            channel.truncate(size);
            return size;
        }

        return raf.length();
    } finally {
        raf.close();
    }
}

From source file:com.linkedin.helix.store.file.FilePropertyStore.java

@Override
public boolean compareAndSet(String key, T expected, T update, Comparator<T> comparator,
        boolean createIfAbsent) {
    String path = getPath(key);//  ww w . j av  a 2 s.  co m
    File file = new File(path);
    //    FileInputStream fin = null;
    //    FileOutputStream fout = null;
    RandomAccessFile raFile = null;
    FileLock fLock = null;

    try {
        _readWriteLock.writeLock().lock();

        if (createIfAbsent) {
            file.createNewFile();
        }

        //      fin = new FileInputStream(file);
        //      FileChannel fChannel = fin.getChannel();
        raFile = new RandomAccessFile(file, "rw");
        FileChannel fChannel = raFile.getChannel();
        fLock = fChannel.lock();

        T current = getProperty(key);
        if (comparator.compare(current, expected) == 0) {
            //        fout = new FileOutputStream(file);
            //
            //        byte[] bytes = _serializer.serialize(update);
            //        fout.write(bytes);
            setProperty(key, update);
            return true;
        }

        return false;
    } catch (FileNotFoundException e) {
        logger.error("fail to compareAndSet. path:" + path, e);
        return false;
    } catch (Exception e) {
        logger.error("fail to compareAndSet. path:" + path, e);
        return false;
    } finally {
        _readWriteLock.writeLock().unlock();
        try {
            if (fLock != null && fLock.isValid()) {
                fLock.release();
            }

            if (raFile != null) {
                raFile.close();
            }

            //        if (fin != null)
            //        {
            //          fin.close();
            //        }
            //
            //        if (fout != null)
            //        {
            //          fout.close();
            //        }
        } catch (IOException e) {
            logger.error("fail to close file. path:" + path, e);
        }
    }

}

From source file:org.geotools.data.shapefile.ShpFiles.java

/**
 * @patch/*from   ww w  .  j  a v  a2s .  com*/
 * 
 * If an user name or password was established then it uses them
 * to login
 */
public ReadableByteChannel getReadChannel(ShpFileType type, FileReader requestor) throws IOException {
    URL url = acquireRead(type, requestor);
    ReadableByteChannel channel = null;
    try {
        if (isLocal()) {
            File file = DataUtilities.urlToFile(url);
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            channel = new FileChannelDecorator(raf.getChannel(), this, url, requestor);
        } else {
            InputStream in;
            if (compressed) {
                InputStream compressedIs = es.juntadeandalucia.panelGestion.negocio.utiles.Utils
                        .getInputStream(url, user, password);
                in = es.juntadeandalucia.panelGestion.negocio.utiles.Utils
                        .getShapefileFromCompressed(compressedIs, type);
            } else {
                in = RemoteFileReader.getInputStream(url, user, password);
            }
            channel = new ReadableByteChannelDecorator(Channels.newChannel(in), this, url, requestor);
        }
    } catch (Throwable e) {
        unlockRead(url, requestor);
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof Error) {
            throw (Error) e;
        } else {
            throw new RuntimeException(e);
        }
    }
    return channel;
}

From source file:org.geotools.data.shapefile.ShpFiles.java

/**
 * Obtain a WritableByteChannel from the given URL. If the url protocol is file, a FileChannel
 * will be returned. Currently, this method will return a generic channel for remote urls,
 * however both shape and dbf writing can only occur with a local FileChannel channel.
 * /*from w  ww .ja  v a 2 s  .  co  m*/
 * <p>
 * A write lock is obtained when this method is called and released when the channel is closed.
 * </p>
 * 
 * 
 * @param type
 *           the type of file to open the stream to.
 * @param requestor
 *           the object requesting the stream
 * 
 * @return a WritableByteChannel for the provided file type
 * 
 * @throws IOException
 *            if there is an error opening the stream
 */
public WritableByteChannel getWriteChannel(ShpFileType type, FileWriter requestor) throws IOException {

    URL url = acquireWrite(type, requestor);

    try {
        WritableByteChannel channel;
        if (isLocal()) {

            File file = DataUtilities.urlToFile(url);

            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            channel = new FileChannelDecorator(raf.getChannel(), this, url, requestor);

            ((FileChannel) channel).lock();

        } else {
            OutputStream out = url.openConnection().getOutputStream();
            channel = new WritableByteChannelDecorator(Channels.newChannel(out), this, url, requestor);
        }

        return channel;
    } catch (Throwable e) {
        unlockWrite(url, requestor);
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof Error) {
            throw (Error) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.apache.flume.channel.file.Log.java

/**
 * Attempts to acquire an exclusive lock on the directory.
 *
 * @return A lock object representing the newly-acquired lock or
 * <code>null</code> if directory is already locked.
 * @throws IOException if locking fails.
 *//*from   ww  w.  j  a  v a 2s  .c om*/
@SuppressWarnings("resource")
private FileLock tryLock(File dir) throws IOException {
    File lockF = new File(dir, FILE_LOCK);
    lockF.deleteOnExit();
    RandomAccessFile file = new RandomAccessFile(lockF, "rws");
    FileLock res = null;
    try {
        res = file.getChannel().tryLock();
    } catch (OverlappingFileLockException oe) {
        file.close();
        return null;
    } catch (IOException e) {
        LOGGER.error("Cannot create lock on " + lockF, e);
        file.close();
        throw e;
    }
    return res;
}

From source file:org.apache.tajo.HttpFileServerHandler.java

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    if (request.getMethod() != HttpMethod.GET) {
        sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;/*from   w  w w. j  av a  2s  .co  m*/
    }

    final String path = sanitizeUri(request.getUri());
    if (path == null) {
        sendError(ctx, HttpResponseStatus.FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, HttpResponseStatus.FORBIDDEN);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response);

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture writeFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ctx.write(region, ctx.newProgressivePromise());
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        writeFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                    throws Exception {
                LOG.trace(String.format("%s: %d / %d", path, progress, total));
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                LOG.trace(future.channel() + " Transfer complete.");
            }
        });
    }

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.apache.hadoop.hdfs.TestFileAppend4.java

/**
 * Corrupt all of the blocks in the blocksBeingWritten dir
 * for the specified datanode number. The corruption is
 * specifically the last checksum chunk of the file being
 * modified by writing random data into it.
 *///from   www.j  a  v  a 2 s  .  co m
private void corruptDataNode(int dnNumber, CorruptionType type) throws Exception {
    // get the FS data of the specified datanode
    File data_dir = new File(System.getProperty("test.build.data"),
            "dfs/data/data" + Integer.toString(dnNumber * 2 + 1) + "/blocksBeingWritten");
    int corrupted = 0;
    for (File block : data_dir.listFiles()) {
        // only touch the actual data, not the metadata (with CRC)
        if (block.getName().startsWith("blk_") && !block.getName().endsWith("meta")) {
            if (type == CorruptionType.CORRUPT_LAST_CHUNK) {
                RandomAccessFile file = new RandomAccessFile(block, "rw");
                FileChannel channel = file.getChannel();
                Random r = new Random();
                long lastBlockSize = channel.size() % 512;
                long position = channel.size() - lastBlockSize;
                int length = r.nextInt((int) (channel.size() - position + 1));
                byte[] buffer = new byte[length];
                r.nextBytes(buffer);

                channel.write(ByteBuffer.wrap(buffer), position);
                System.out.println("Deliberately corrupting file " + block.getName() + " at offset " + position
                        + " length " + length);
                file.close();

            } else if (type == CorruptionType.TRUNCATE_BLOCK_TO_ZERO) {
                LOG.info("Truncating block file at " + block);
                RandomAccessFile blockFile = new RandomAccessFile(block, "rw");
                blockFile.setLength(0);
                blockFile.close();

                RandomAccessFile metaFile = new RandomAccessFile(FSDataset.findMetaFile(block), "rw");
                metaFile.setLength(0);
                metaFile.close();
            } else if (type == CorruptionType.TRUNCATE_BLOCK_HALF) {
                FSDatasetTestUtil.truncateBlockFile(block, block.length() / 2);
            } else {
                assert false;
            }
            ++corrupted;
        }
    }
    assertTrue("Should have some data in bbw to corrupt", corrupted > 0);
}

From source file:com.stimulus.archiva.domain.Volume.java

public void save() throws ConfigurationException {
    try {//from www .j  av a 2  s.c o m
        Config.getConfig().getConfigAutoLoadService().block();
        if (getStatus() != Status.NEW && isEjected())
            return;

        if (getStatus() == Status.EJECTED)
            return;

        if (getStatus() == Status.NEW) {
            setStatus(Status.UNUSED);
            readyFileSystem();
            if (getStatus() == Status.UNUSED) {
                try {
                    calculateSpace();
                } catch (Exception e) {
                    logger.error("failed to retrieve disk space {" + toString() + "}", e);
                }
            }
        }

        synchronized (volumeinfoLock) {
            logger.debug("save() volumeinfo");
            RandomAccessFile randomAccessFile = null;
            try {
                randomAccessFile = getRandomAccessFile("rw");
            } catch (FileNotFoundException fnfe) {
                logger.error("failed to write to volumeinfo:" + fnfe.getMessage(), fnfe);
                logger.warn("ensure mailarchiva service is running under account with sufficient privileges");
                closeVolInfo(randomAccessFile);
                return;
            }
            logger.debug(
                    "open volumeinfo file for write {file='" + getPath() + File.separator + INFO_FILE + "'");
            FileChannel channel = randomAccessFile.getChannel();
            /* FileLock fileLock = null;
            try {
               fileLock = channel.lock();
            } catch(IOException io) {
               logger.error("failed to obtain lock to volumeinfo file:"+io.getMessage()+" {"+toString()+"}");
               closeVolInfo(randomAccessFile);
               return;
            } catch(OverlappingFileLockException ofle) {
               logger.error("failed to obtain lock to volumeinfo file:"+ofle.getMessage()+" {"+toString()+"}");
               closeVolInfo(randomAccessFile);
               return;
            }*/
            writeVolumeInfoLines(randomAccessFile);
            /*
            try {
               fileLock.release();
            } catch (IOException io) {
               logger.error("failed to release the write lock on volumeinfo file:"+io.getMessage()+" {"+toString()+"}");
            }
            */
            try {
                channel.close();
            } catch (IOException io) {
                logger.error("failed to close volumeinfo file:" + io.getMessage() + " {" + toString() + "}");
            }
            closeVolInfo(randomAccessFile);
        }
    } finally {
        Config.getConfig().getConfigAutoLoadService().unblock();
    }
}

From source file:com.yobidrive.diskmap.needles.NeedleManager.java

private FileChannel getImportChannel(int logNumber, String extension, boolean recovery)
        throws NeedleManagerException {
    FileChannel needleChannel = null;
    String fileName = Integer.toHexString(logNumber);
    while (fileName.length() < 8)
        fileName = "0" + fileName;
    fileName = fileName + extension;//  w  w  w .  j a va  2s  . com
    File needleFile = new File(recovery ? logDir : importDir, fileName);
    if (needleFile.exists() && needleFile.canRead()) {
        RandomAccessFile needleRFile;
        try {
            needleRFile = new RandomAccessFile(needleFile, "r"); // Read only mode
        } catch (Throwable th) {
            logger.error("Needle log file not found " + logPath + "/" + fileName);
            throw new NeedleManagerException();
        }
        needleChannel = needleRFile.getChannel();
    }
    return needleChannel;
}