Example usage for java.io RandomAccessFile close

List of usage examples for java.io RandomAccessFile close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this random access file stream and releases any system resources associated with the stream.

Usage

From source file:edu.umass.cs.gigapaxos.AbstractPaxosLogger.java

/**
 * @param strID/*w  w  w  . j  a  v a  2 s.  c  o m*/
 */
public static final void fileLock(Object strID) {
    RandomAccessFile raf = null;
    try {
        String logdir = getLocksDir();
        (new File(logdir)).mkdirs();
        String filename = logdir + "/" + strID;
        File file = new File(filename);
        boolean created = file.createNewFile();
        FileLock lock = (raf = new RandomAccessFile(file, "rw")).getChannel().tryLock();
        if (lock == null)
            throw new RuntimeException("Unable to start node " + strID + " likely because node " + strID
                    + " from " + Util.readFileAsString(filename).split("\n")[0].trim().replaceAll("#", "")
                    + " is already running");
        // lock!=null
        if (created && PaxosConfig.getPropertiesFile() != null) {
            raf.write(("#" + PaxosConfig.getPropertiesFile() + "\n").getBytes());
            raf.write(Util.readFileAsString(PaxosConfig.getPropertiesFile()).getBytes());
        }

    } catch (IOException e) {
        e.printStackTrace();
        if (raf != null)
            try {
                raf.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
    }
}

From source file:org.apache.sshd.server.filesystem.NativeSshFile.java

/**
 * Create input stream for reading./*from  www.java2 s .c  o  m*/
 */
public InputStream createInputStream(final long offset) throws IOException {

    // permission check
    if (!isReadable()) {
        throw new IOException("No read permission : " + file.getName());
    }

    // move to the appropriate offset and create input stream
    final RandomAccessFile raf = new RandomAccessFile(file, "r");
    raf.seek(offset);

    // The IBM jre needs to have both the stream and the random access file
    // objects closed to actually close the file
    return new FileInputStream(raf.getFD()) {
        public void close() throws IOException {
            super.close();
            raf.close();
        }
    };
}

From source file:com.kkbox.toolkit.image.KKImageRequest.java

@Override
public Bitmap doInBackground(Object... params) {
    Bitmap bitmap;/*from   w  w  w . j a  v a  2  s .c o  m*/
    try {
        int readLength;
        cachePath = KKImageManager.getTempImagePath(context, url);
        File cacheFile = new File(cachePath);
        File localFile = null;
        String tempFilePath = context.getCacheDir().getAbsolutePath() + File.separator + "image"
                + File.separator + hashCode();
        if (localPath != null) {
            localFile = new File(localPath);
        }
        try {
            if (cacheFile.exists()) {
                if (actionType == KKImageManager.ActionType.DOWNLOAD) {
                    if (localFile == null || !localFile.exists()) {
                        cryptToFile(cachePath, localPath);
                    }
                    return null;
                } else {
                    bitmap = decodeBitmap(cachePath);
                    if (bitmap != null) {
                        if (localPath != null && saveToLocal && (localFile == null || !localFile.exists())) {
                            cryptToFile(cachePath, localPath);
                        }
                        return bitmap;
                    } else {
                        removeCacheFile();
                    }
                }
            }
            if (localFile != null && localFile.exists()) {
                if (actionType == KKImageManager.ActionType.DOWNLOAD) {
                    return null;
                } else {
                    cryptToFile(localPath, tempFilePath);
                    moveFileTo(tempFilePath, cachePath);
                    bitmap = decodeBitmap(cachePath);
                    if (bitmap != null) {
                        return bitmap;
                    } else {
                        removeCacheFile();
                    }
                }
            }
        } catch (Exception e) {
        }
        // Do fetch server resource if either cache nor local file is not valid to read
        if (!KKImageManager.networkEnabled) {
            return null;
        }
        final HttpGet httpget = new HttpGet(url);
        response = httpclient.execute(httpget);
        final InputStream is = response.getEntity().getContent();
        headers = response.getAllHeaders();
        removeInvalidImageFiles();
        if (actionType == KKImageManager.ActionType.DOWNLOAD) {
            RandomAccessFile tempFile = new RandomAccessFile(tempFilePath, "rw");
            while ((readLength = is.read(buffer, 0, buffer.length)) != -1) {
                if (interuptFlag) {
                    return null;
                }
                if (cipher != null) {
                    buffer = cipher.doFinal(buffer);
                }
                tempFile.write(buffer, 0, readLength);
            }
            tempFile.close();
            moveFileTo(tempFilePath, localPath);
            return null;
        } else {
            RandomAccessFile tempFile;
            try {
                tempFile = new RandomAccessFile(tempFilePath, "rw");
            } catch (IOException e) {
                // we don't save to SD card if cache is full
                return BitmapFactory.decodeStream(is);
            }
            try {
                while ((readLength = is.read(buffer, 0, buffer.length)) != -1) {
                    if (interuptFlag) {
                        return null;
                    }
                    tempFile.write(buffer, 0, readLength);
                }
            } catch (IOException e) {
                tempFile.close();
                return null;
            }
            tempFile.close();
            moveFileTo(tempFilePath, cachePath);
            bitmap = decodeBitmap(cachePath);
            if (bitmap != null) {
                if (saveToLocal && localPath != null) {
                    cryptToFile(cachePath, localPath);
                }
                return bitmap;
            }
        }
    } catch (final Exception e) {
        isNetworkError = true;
        removeInvalidImageFiles();
    }
    return null;
}

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

/** check if nn.getCorruptFiles() returns a file that has corrupted blocks */
@Test(timeout = 300000)/*from   w ww . j a va  2 s.c  om*/
public void testListCorruptFilesCorruptedBlock() throws Exception {
    MiniDFSCluster cluster = null;
    Random random = new Random();

    try {
        Configuration conf = new HdfsConfiguration();
        conf.setInt(DFSConfigKeys.DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY, 1); // datanode scans directories
        conf.setInt(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 3 * 1000); // datanode sends block reports
        // Set short retry timeouts so this test runs faster
        conf.setInt(DFSConfigKeys.DFS_CLIENT_RETRY_WINDOW_BASE, 10);
        cluster = new MiniDFSCluster.Builder(conf).build();
        FileSystem fs = cluster.getFileSystem();

        // create two files with one block each
        DFSTestUtil util = new DFSTestUtil.Builder().setName("testCorruptFilesCorruptedBlock").setNumFiles(2)
                .setMaxLevels(1).setMaxSize(512).build();
        util.createFiles(fs, "/srcdat10");

        // fetch bad file list from namenode. There should be none.
        final NameNode namenode = cluster.getNameNode();
        Collection<FSNamesystem.CorruptFileBlockInfo> badFiles = namenode.getNamesystem()
                .listCorruptFileBlocks("/", null);
        assertTrue("Namenode has " + badFiles.size() + " corrupt files. Expecting None.", badFiles.size() == 0);

        // Now deliberately corrupt one block
        String bpid = cluster.getNamesystem().getBlockPoolId();
        File storageDir = cluster.getInstanceStorageDir(0, 1);
        File data_dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
        assertTrue("data directory does not exist", data_dir.exists());
        List<File> metaFiles = MiniDFSCluster.getAllBlockMetadataFiles(data_dir);
        assertTrue("Data directory does not contain any blocks or there was an " + "IO error",
                metaFiles != null && !metaFiles.isEmpty());
        File metaFile = metaFiles.get(0);
        RandomAccessFile file = new RandomAccessFile(metaFile, "rw");
        FileChannel channel = file.getChannel();
        long position = channel.size() - 2;
        int length = 2;
        byte[] buffer = new byte[length];
        random.nextBytes(buffer);
        channel.write(ByteBuffer.wrap(buffer), position);
        file.close();
        LOG.info("Deliberately corrupting file " + metaFile.getName() + " at offset " + position + " length "
                + length);

        // read all files to trigger detection of corrupted replica
        try {
            util.checkFiles(fs, "/srcdat10");
        } catch (BlockMissingException e) {
            System.out.println("Received BlockMissingException as expected.");
        } catch (IOException e) {
            assertTrue("Corrupted replicas not handled properly. Expecting BlockMissingException "
                    + " but received IOException " + e, false);
        }

        // fetch bad file list from namenode. There should be one file.
        badFiles = namenode.getNamesystem().listCorruptFileBlocks("/", null);
        LOG.info("Namenode has bad files. " + badFiles.size());
        assertTrue("Namenode has " + badFiles.size() + " bad files. Expecting 1.", badFiles.size() == 1);
        util.cleanup(fs, "/srcdat10");
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:com.datasayer.meerkat.MeerJobRunner.java

@SuppressWarnings("unchecked")
@Override//from  ww w . j  a  v  a 2s.c  om
public void bsp(final BSPPeer<Writable, Writable, Writable, Writable, Writable> peer)
        throws IOException, SyncException, InterruptedException {

    while (true) {
        try {
            long currentTime = System.currentTimeMillis();
            FileSystem fs = FileSystem.get(conf);
            if (!fs.isFile(logPath)) {
                System.out.println("can not read input file");
                return;
            }
            RandomAccessFile file = new RandomAccessFile(logPath.toString(), "r");
            long fileLength = file.length();

            if (fileLength > filePointer) {
                file.seek(filePointer);
                String line = null;
                while (file.length() > file.getFilePointer()) {
                    line = file.readLine();
                    line = new String(line.getBytes("8859_1"), "utf-8");
                    guardMeer.observe(line);
                }
                filePointer = file.getFilePointer();
            } else {
                // nothing to do
            }
            file.close();

            long timeDiff = currentTime - this.lastAggregatedTime;
            if (timeDiff >= this.aggregationInterval) {

                peer.sync();

                if (peer.getPeerName().equals(masterName)) {
                    bossMeer.masterCompute(new Iterator<Writable>() {

                        private final int producedMessages = peer.getNumCurrentMessages();
                        private int consumedMessages = 0;

                        @Override
                        public boolean hasNext() {
                            return producedMessages > consumedMessages;
                        }

                        @Override
                        public Writable next() throws NoSuchElementException {
                            if (consumedMessages >= producedMessages) {
                                throw new NoSuchElementException();
                            }

                            try {
                                consumedMessages++;
                                return peer.getCurrentMessage();
                            } catch (IOException e) {
                                throw new NoSuchElementException();
                            }
                        }

                        @Override
                        public void remove() {
                            // BSPPeer.getCurrentMessage originally deletes a message.
                            // Thus, it doesn't need to throw exception.
                            // throw new UnsupportedOperationException();
                        }

                    }, signalMeer);
                    this.lastAggregatedTime = currentTime;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

protected void closeVolInfo(RandomAccessFile file) {
    if (file != null) {
        try {/*from   www.  j  a va 2s .co m*/
            file.close();
        } catch (IOException io) {
            logger.error("failed to close volumeinfo file:" + io.getMessage() + " {" + toString() + "}");
        }
    }
}

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

public void testCorruptBlock() throws Exception {
    Configuration conf = new Configuration();
    conf.setLong("dfs.blockreport.intervalMsec", 1000);
    FileSystem fs = null;//from w w w  .ja v a  2 s. co  m
    DFSClient dfsClient = null;
    LocatedBlocks blocks = null;
    int replicaCount = 0;
    Random random = new Random();
    String outStr = null;

    MiniDFSCluster cluster = null;
    try {
        cluster = new MiniDFSCluster(conf, 3, true, null);
        cluster.waitActive();
        fs = cluster.getFileSystem();
        Path file1 = new Path("/testCorruptBlock");
        DFSTestUtil.createFile(fs, file1, 1024, (short) 3, 0);
        // Wait until file replication has completed
        DFSTestUtil.waitReplication(fs, file1, (short) 3);
        String block = DFSTestUtil.getFirstBlock(fs, file1).getBlockName();

        // Make sure filesystem is in healthy state
        outStr = runFsck(conf, 0, true, "/");
        System.out.println(outStr);
        assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));

        // corrupt replicas 
        File baseDir = new File(System.getProperty("test.build.data", "build/test/data"), "dfs/data");
        for (int i = 0; i < 6; i++) {
            File blockFile = new File(baseDir, "data" + (i + 1) + "/current/" + block);
            if (blockFile.exists()) {
                RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
                FileChannel channel = raFile.getChannel();
                String badString = "BADBAD";
                int rand = random.nextInt((int) channel.size() / 2);
                raFile.seek(rand);
                raFile.write(badString.getBytes());
                raFile.close();
            }
        }
        // Read the file to trigger reportBadBlocks
        try {
            IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(), conf, true);
        } catch (IOException ie) {
            // Ignore exception
        }

        dfsClient = new DFSClient(new InetSocketAddress("localhost", cluster.getNameNodePort()), conf);
        blocks = dfsClient.namenode.getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
        replicaCount = blocks.get(0).getLocations().length;
        while (replicaCount != 3) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ignore) {
            }
            blocks = dfsClient.namenode.getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
            replicaCount = blocks.get(0).getLocations().length;
        }
        assertTrue(blocks.get(0).isCorrupt());

        // Check if fsck reports the same
        outStr = runFsck(conf, 1, true, "/");
        System.out.println(outStr);
        assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
        assertTrue(outStr.contains("testCorruptBlock"));
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:com.roamtouch.menuserver.utils.FileUtils.java

private void removeLastCharacter(File fileName) {

    RandomAccessFile f;
    long length;//from  w ww  . j a  v  a  2 s  . c  om

    try {

        f = new RandomAccessFile(fileName, "rw");
        length = f.length();
        long l;

        if (length > 0)
            l = length - 1;
        else
            l = length;

        f.setLength(l);
        f.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java

private boolean updateINIFile(String javaHome) {
    logger.debug("Updating JAVA_HOME in ini file ::" + javaHome);
    javaHome = "-vm\n" + javaHome + "\n";
    RandomAccessFile file = null;
    boolean isUpdated = false;
    try {/*  ww w  .  j a  v  a2s .com*/
        file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw");
        byte[] text = new byte[(int) file.length()];
        file.readFully(text);
        file.seek(0);
        file.writeBytes(javaHome);
        file.write(text);
        isUpdated = true;
    } catch (IOException ioException) {
        logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException);
    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (IOException ioException) {
            logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException);
        }
    }
    return isUpdated;
}