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:org.apache.hadoop.hdfs.server.datanode.DataStorage.java

public boolean isConversionNeeded(StorageDirectory sd) throws IOException {
    File oldF = new File(sd.getRoot(), "storage");
    if (!oldF.exists())
        return false;
    // check the layout version inside the storage file
    // Lock and Read old storage file
    RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws");
    FileLock oldLock = oldFile.getChannel().tryLock();
    try {/*from   www  .j  a v a2 s.c om*/
        oldFile.seek(0);
        int oldVersion = oldFile.readInt();
        if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION)
            return false;
    } finally {
        oldLock.release();
        oldFile.close();
    }
    return true;
}

From source file:org.apache.hadoop.hdfs.server.namenode.EditLogFileOutputStream.java

/**
 * Creates output buffers and file object.
 * /* w  w  w .j  a  v a 2s.c  om*/
 * @param conf
 *          Configuration object
 * @param name
 *          File name to store edit log
 * @param size
 *          Size of flush buffer
 * @throws IOException
 */
public EditLogFileOutputStream(Configuration conf, File name, int size) throws IOException {
    super();
    shouldSyncWritesAndSkipFsync = conf.getBoolean(DFSConfigKeys.DFS_NAMENODE_EDITS_NOEDITLOGCHANNELFLUSH,
            DFSConfigKeys.DFS_NAMENODE_EDITS_NOEDITLOGCHANNELFLUSH_DEFAULT);

    file = name;
    doubleBuf = new EditsDoubleBuffer(size);
    RandomAccessFile rp;
    if (shouldSyncWritesAndSkipFsync) {
        rp = new RandomAccessFile(name, "rws");
    } else {
        rp = new RandomAccessFile(name, "rw");
    }
    fp = new FileOutputStream(rp.getFD()); // open for append
    fc = rp.getChannel();
    fc.position(fc.size());
}

From source file:org.gcaldaemon.core.Configurator.java

public static final void copyFile(File from, File to) throws Exception {
    if (from == null || to == null || !from.exists()) {
        return;//from  ww  w.  j a v  a  2 s .  c o m
    }
    RandomAccessFile fromFile = null;
    RandomAccessFile toFile = null;
    try {
        fromFile = new RandomAccessFile(from, "r");
        toFile = new RandomAccessFile(to, "rw");
        FileChannel fromChannel = fromFile.getChannel();
        FileChannel toChannel = toFile.getChannel();
        long length = fromFile.length();
        long start = 0;
        while (start < length) {
            start += fromChannel.transferTo(start, length - start, toChannel);
        }
        fromChannel.close();
        toChannel.close();
    } finally {
        if (fromFile != null) {
            fromFile.close();
        }
        if (toFile != null) {
            toFile.close();
        }
    }
}

From source file:no.sesat.search.http.filters.SiteJspLoaderFilter.java

private void downloadJsp(final HttpServletRequest request, final String jsp) throws MalformedURLException {

    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from  w ww. j  av  a  2s.  c  o  m*/

    byte[] golden = new byte[0];

    // search skins for the jsp and write it out to "golden"
    for (Site site = (Site) request.getAttribute(Site.NAME_KEY); 0 == golden.length; site = site.getParent()) {

        if (null == site) {
            if (null == config.getServletContext().getResource(jsp)) {
                throw new ResourceLoadException("Unable to find " + jsp + " in any skin");
            }
            break;
        }

        final Site finalSite = site;
        final BytecodeLoader bcLoader = UrlResourceLoader.newBytecodeLoader(finalSite.getSiteContext(), jsp,
                null);
        bcLoader.abut();
        golden = bcLoader.getBytecode();
    }

    // if golden now contains data save it to a local (ie local web application) file
    if (0 < golden.length) {
        try {
            final File file = new File(root + jsp);

            // create the directory structure
            file.getParentFile().mkdirs();

            // check existing file
            boolean needsUpdating = true;
            final boolean fileExisted = file.exists();
            if (!fileExisted) {
                file.createNewFile();
            }

            // channel.lock() only synchronises file access between programs, but not between threads inside
            //  the current JVM. The latter results in the OverlappingFileLockException.
            //  At least this is my current understanding of java.nio.channels
            //   It may be that no synchronisation or locking is required at all. A beer to whom answers :-)
            // So we must provide synchronisation between our own threads,
            //  synchronisation against the file's path (using the JVM's String.intern() functionality)
            //  should work. (I can't imagine this string be used for any other synchronisation purposes).
            synchronized (file.toString().intern()) {

                RandomAccessFile fileAccess = null;
                FileChannel channel = null;

                try {

                    fileAccess = new RandomAccessFile(file, "rws");
                    channel = fileAccess.getChannel();

                    channel.lock();

                    if (fileExisted) {

                        final byte[] bytes = new byte[(int) channel.size()];
                        final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
                        int reads;
                        do {
                            reads = channel.read(byteBuffer);
                        } while (0 < reads);

                        needsUpdating = !Arrays.equals(golden, bytes);
                    }

                    if (needsUpdating) {
                        // download file from skin
                        channel.write(ByteBuffer.wrap(golden), 0);
                        file.deleteOnExit();
                    }
                } finally {
                    if (null != channel) {
                        channel.close();
                    }
                    if (null != fileAccess) {
                        fileAccess.close();
                    }

                    LOG.debug("resource created as " + config.getServletContext().getResource(jsp));
                }
            }

        } catch (IOException ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }

    stopWatch.stop();
    LOG.trace("SiteJspLoaderFilter.downloadJsp(..) took " + stopWatch);
}

From source file:com.eviware.loadui.launcher.LoadUILauncher.java

private void ensureNoOtherInstance() {
    try {/*from  w  ww  .j a  v a 2s.  c  o m*/
        File bundleCache = new File(configProps.getProperty("org.osgi.framework.storage"));
        if (!bundleCache.isDirectory())
            if (!bundleCache.mkdirs())
                throw new RuntimeException("Unable to create directory: " + bundleCache.getAbsolutePath());

        File lockFile = new File(bundleCache, "loadui.lock");
        if (!lockFile.exists())
            if (!lockFile.createNewFile())
                throw new RuntimeException("Unable to create file: " + lockFile.getAbsolutePath());

        try {
            @SuppressWarnings("resource")
            RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile, "rw");
            FileLock lock = randomAccessFile.getChannel().tryLock();
            if (lock == null) {
                ErrorHandler.promptRestart("An instance of LoadUI is already running!");
                exitInError();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (OverlappingFileLockException e) {
        System.err.println("An instance of loadUI is already running!");
        exitInError();
    } catch (IOException e) {
        e.printStackTrace();
        exitInError();
    }
}

From source file:omero.util.TempFileManager.java

/**
 * Attempts to delete all directories under self.userdir other than the one
 * owned by this process. If a directory is locked, it is skipped.
 *//* w  ww  .  j  a  va2  s . c  om*/
@SuppressWarnings("unchecked")
protected void cleanUserDir() throws IOException {
    log.debug("Cleaning user dir: " + userDir.getAbsolutePath());
    List<File> files = Arrays.asList(userDir.listFiles());
    final String d = dir.getCanonicalPath();
    for (File file : files) {
        String f = file.getCanonicalPath();
        if (f.equals(d)) {
            log.debug("Skipping self: " + d);
            continue;
        }
        File lock = new File(file, ".lock");
        RandomAccessFile raf = new RandomAccessFile(lock, "rw");
        try {
            FileLock fl = raf.getChannel().tryLock();
            if (fl == null) {
                System.out.println("Locked: " + f);
                continue;
            }
        } catch (Exception e) {
            System.out.println("Locked: " + f);
            continue;
        }
        FileUtils.deleteDirectory(file);
        System.out.println("Deleted: " + f);
    }
}

From source file:org.ednovo.gooru.application.util.ResourceProcessor.java

public void postPdfUpdate(final String resourceGooruOid) throws Exception {

    new TransactionBox() {

        @Override/*from w  w w  . ja  va 2s .  com*/
        public void execute() {

            try {

                logger.info("Updating Resource: " + resourceGooruOid);
                Resource resource = resourceRepository.findResourceByContentGooruId(resourceGooruOid);
                String repoPath = resource.getOrganization().getNfsStorageArea().getInternalPath()
                        + resource.getFolder();
                /*
                 * getGooruImageUtil().scaleImage(repoPath +
                 * resource.getThumbnail(), repoPath, null,
                 * ResourceImageUtil.RESOURCE_THUMBNAIL_SIZES);
                 */
                ResourceInfo resourceInfo = resourceRepository.findResourceInfo(resource.getGooruOid());
                if (resourceInfo == null) {
                    resourceInfo = new ResourceInfo();
                    resourceInfo.setResource(resource);
                }

                resourceInfo.setLastUpdated(new Date());

                RandomAccessFile raf = new RandomAccessFile(new File(repoPath + resource.getUrl()), "r");
                FileChannel channel = raf.getChannel();
                ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
                PDFFile pdffile = new PDFFile(buf);
                resourceInfo.setNumOfPages(pdffile.getNumPages());

                resourceRepository.save(resourceInfo);
                resource.setResourceInfo(resourceInfo);
                resourceRepository.save(resource);

                s3ResourceApiHandler.uploadResourceFolder(resource);

            } catch (Exception ex) {
                logger.error("Error while generating thumbnail ", ex);
                s3ResourceApiHandler.uploadResourceFolderWithNewSession(resourceGooruOid);
            }
        }
    };
}

From source file:acromusashi.kafka.log.producer.WinApacheLogProducer.java

/**
 * ????/* w w w  .  j  av a 2s .co m*/
 *
 * @param random 
 * @return ?????
 * @throws IOException 
 */
private byte[] readToEnd(RandomAccessFile random) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_ALLOCATE_SIZE);

    while ((random.getChannel().read(buffer)) != -1) {
        out.write(buffer.array());
        buffer.clear();
    }

    return out.toByteArray();
}

From source file:net.ontopia.infoset.content.FileContentStore.java

private void allocateNewBlock() throws ContentStoreException {
    RandomAccessFile out = null;
    boolean exception_thrown = false;
    try {//from   ww  w . ja  v a  2s  . c om
        out = new RandomAccessFile(key_file, "rws");

        for (int i = 0; i < MAX_SPINS; i++) {
            // acquire exclusive lock
            FileLock l = out.getChannel().tryLock();

            if (l == null) {
                // wait a little before trying again
                try {
                    Thread.sleep(SPIN_TIMEOUT);
                } catch (InterruptedException e) {
                }
                continue;

            } else {
                try {
                    // allocate new key
                    int old_key;
                    int new_key;
                    String content = null;

                    if (out.length() == 0) {
                        old_key = 0;
                        new_key = old_key + KEY_BLOCK_SIZE;

                    } else {
                        try {
                            content = out.readUTF();
                            old_key = Integer.parseInt(content);
                            new_key = old_key + KEY_BLOCK_SIZE;
                        } catch (NumberFormatException e) {
                            if (content.length() > 100)
                                content = content.substring(0, 100) + "...";
                            throw new ContentStoreException(
                                    "Content store key file corrupted. Contained: '" + content + "'");
                        }
                    }

                    // truncate key file and write out new key
                    out.seek(0);
                    out.writeUTF(Integer.toString(new_key));

                    end_of_key_block = new_key;
                    last_key = old_key;
                    return;
                } finally {
                    // release file lock
                    try {
                        l.release();
                    } catch (Throwable t) {
                        throw new ContentStoreException("Could not release key file lock.", t);
                    }
                }
            }
        }
        throw new ContentStoreException("Block allocation timed out.");

    } catch (ContentStoreException e) {
        exception_thrown = true;
        throw e;

    } catch (Throwable t) {
        exception_thrown = true;
        throw new ContentStoreException(t);

    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                if (!exception_thrown)
                    throw new ContentStoreException("Problems occurred when closing content store.", e);
            }
        }
    }
}

From source file:com.norconex.commons.lang.io.CachedInputStream.java

@SuppressWarnings("resource")
private void createInputStreamFromCache() throws FileNotFoundException {
    if (fileCache != null) {
        LOG.debug("Creating new input stream from file cache.");
        RandomAccessFile f = new RandomAccessFile(fileCache, "r");
        FileChannel channel = f.getChannel();
        inputStream = Channels.newInputStream(channel);
    } else {//  w ww . j ava  2 s  . co  m
        LOG.debug("Creating new input stream from memory cache.");
        inputStream = new ByteArrayInputStream(memCache);
    }
    needNewStream = false;
}