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:com.vtls.opensource.jhove.JHOVEDocumentFactory.java

/**
 * Populate the representation information for JHOVE Document from a specific File.
 * @param representation a RepInfo /*www .  j  av  a  2 s  .  c om*/
 * @param file  a File containing the representation information
 * @throws IOException
 */
private void populateRepresentation(RepInfo representation, File file) throws IOException {
    // Iterate through the modules and process.
    Iterator iterator = m_module_list.iterator();
    while (iterator.hasNext()) {
        Module module = (Module) iterator.next();
        module.setBase(m_jhove);
        module.setVerbosity(Module.MINIMUM_VERBOSITY);

        // m_logger.info(module.toString());
        RepInfo persistent = (RepInfo) representation.clone();

        if (module.hasFeature("edu.harvard.hul.ois.jhove.canValidate")) {
            try {
                module.applyDefaultParams();
                if (module.isRandomAccess()) {
                    RandomAccessFile ra_file = new RandomAccessFile(file, "r");
                    module.parse(ra_file, persistent);
                    ra_file.close();
                } else {
                    InputStream stream = new FileInputStream(file);
                    int parse = module.parse(stream, persistent, 0);
                    while (parse != 0) {
                        stream.close();
                        stream = new FileInputStream(file);
                        parse = module.parse(stream, persistent, parse);
                    }
                    stream.close();
                }

                if (persistent.getWellFormed() == RepInfo.TRUE)
                    representation.copy(persistent);
                else
                    representation.setSigMatch(persistent.getSigMatch());
            } catch (Exception e) {
                continue;
            }
        }
    }
}

From source file:org.apache.bookkeeper.bookie.EntryLogTest.java

/**
 * Explicitely try to recover using the ledgers map index at the end of the entry log
 *///from   www . java  2 s.c  o  m
@Test(timeout = 60000)
public void testRecoverFromLedgersMapOnV0EntryLog() throws Exception {
    File tmpDir = createTempDir("bkTest", ".dir");
    File curDir = Bookie.getCurrentDirectory(tmpDir);
    Bookie.checkDirectoryStructure(curDir);

    int gcWaitTime = 1000;
    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();
    conf.setGcWaitTime(gcWaitTime);
    conf.setLedgerDirNames(new String[] { tmpDir.toString() });
    Bookie bookie = new Bookie(conf);

    // create some entries
    EntryLogger logger = ((InterleavedLedgerStorage) bookie.ledgerStorage).entryLogger;
    logger.addEntry(1, generateEntry(1, 1));
    logger.addEntry(3, generateEntry(3, 1));
    logger.addEntry(2, generateEntry(2, 1));
    logger.addEntry(1, generateEntry(1, 2));
    logger.rollLog();

    // Rewrite the entry log header to be on V0 format
    File f = new File(curDir, "0.log");
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(EntryLogger.HEADER_VERSION_POSITION);
    // Write zeros to indicate V0 + no ledgers map info
    raf.write(new byte[4 + 8]);
    raf.close();

    // now see which ledgers are in the log
    logger = new EntryLogger(conf, bookie.getLedgerDirsManager());

    try {
        logger.extractEntryLogMetadataFromIndex(0L);
        fail("Should not be possible to recover from ledgers map index");
    } catch (IOException e) {
        // Ok
    }

    // Public method should succeed by falling back to scanning the file
    EntryLogMetadata meta = logger.getEntryLogMetadata(0L);
    LOG.info("Extracted Meta From Entry Log {}", meta);
    assertEquals(60, meta.getLedgersMap().get(1L).longValue());
    assertEquals(30, meta.getLedgersMap().get(2L).longValue());
    assertEquals(30, meta.getLedgersMap().get(3L).longValue());
    assertNull(meta.getLedgersMap().get(4L));
    assertEquals(120, meta.getTotalSize());
    assertEquals(120, meta.getRemainingSize());
}

From source file:com.v2soft.misto.Providers.MapnikProvider.java

@Override
public synchronized boolean prepareTileImage(TileInfo info) {
    try {//  w  ww  .  j  av  a  2 s  . c  o m
        String local_name = String.format("%d_%d_%d.png", info.getZoom(), info.getLongitude(),
                info.getLatitude());
        if (!mLocalCache.isFileInCache(local_name)) {
            String query = String.format("http://%s/%d/%d/%d%s", BASE_HOST, info.getZoom(), info.getLongitude(),
                    info.getLatitude(), IMAGE_EXT);
            Log.d("Uploading tile ", query);

            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            int timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT) 
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            DefaultHttpClient client = new DefaultHttpClient(httpParameters);

            HttpGet request = new HttpGet(query);

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MONTH, 1);
                RandomAccessFile out = mLocalCache.addFile(local_name, cal.getTime());
                InputStream in = entity.getContent();
                byte[] buffer = new byte[4096];
                int readed = 0;
                while ((readed = in.read(buffer)) > 0) {
                    out.write(buffer, 0, readed);
                }
                out.close();
                in.close();
            }
        }
        InputStream in = mLocalCache.getFileInputStream(local_name);
        final Bitmap bitmap = BitmapFactory.decodeStream(in);
        BitmapManager.registerBitmap(bitmap, info.toString());
        info.setBitmap(bitmap);
        in.close();
        return true;
    } catch (Exception e) {
        Log.d("MapnikProvider::prepareTileImage", e.toString());
    }
    return false;
}

From source file:fi.vtt.nubomedia.armodule.Ar3DHandler.java

private String getFile(String path) throws IOException {
    RandomAccessFile in = new RandomAccessFile(new File(path), "r");
    FileChannel ch = in.getChannel();
    long size = ch.size();
    byte[] buf = new byte[(int) size];
    in.read(buf, 0, buf.length);/*ww w.j a  va2 s. c om*/
    in.close();
    return new String(buf);
}

From source file:org.apache.cassandra.db.VerifyTest.java

@Test
public void testVerifyIncorrectDigest() throws IOException, WriteTimeoutException {
    CompactionManager.instance.disableAutoCompaction();
    Keyspace keyspace = Keyspace.open(KEYSPACE);
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CORRUPT_CF);

    fillCF(cfs, KEYSPACE, CORRUPT_CF, 2);

    List<Row> rows = cfs.getRangeSlice(Util.range("", ""), null, new IdentityQueryFilter(), 1000);

    SSTableReader sstable = cfs.getSSTables().iterator().next();

    RandomAccessFile file = new RandomAccessFile(sstable.descriptor.filenameFor(Component.DIGEST), "rw");
    Long correctChecksum = Long.parseLong(file.readLine());
    file.close();

    writeChecksum(++correctChecksum, sstable.descriptor.filenameFor(Component.DIGEST));

    Verifier verifier = new Verifier(cfs, sstable, false);
    try {//from   w w w.j  ava 2s  .c  om
        verifier.verify(false);
        fail("Expected a CorruptSSTableException to be thrown");
    } catch (CorruptSSTableException err) {
    }
}

From source file:com.adaptris.fs.NioWorkerTest.java

@Test
public void testLockWhileWriting() throws Exception {
    NioWorker worker = createWorker();/* w  w  w.java  2 s . c  o m*/
    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    f.delete();
    try {
        RandomAccessFile raf = new RandomAccessFile(f, "rwd");
        FileLock lock = raf.getChannel().lock();
        try {
            // Use the write method, because this "bypasses" the file.exists() check
            worker.write(BYTES, f);
            fail();
        } catch (FsException expected) {
            assertEquals(OverlappingFileLockException.class, expected.getCause().getClass());
        }
        lock.release();
        raf.close();
        f.delete();
        worker.put(BYTES, f);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

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

@Test
public void testValidateEditLogWithCorruptHeader() throws IOException {
    File testDir = new File(TEST_DIR, "testValidateEditLogWithCorruptHeader");
    SortedMap<Long, Long> offsetToTxId = Maps.newTreeMap();
    File logFile = prepareUnfinalizedTestEditLog(testDir, 2, offsetToTxId);
    RandomAccessFile rwf = new RandomAccessFile(logFile, "rw");
    try {// w  w w.  j av  a 2  s  .  c o m
        rwf.seek(0);
        rwf.writeLong(42); // corrupt header
    } finally {
        rwf.close();
    }
    EditLogValidation validation = EditLogFileInputStream.validateEditLog(logFile);
    assertTrue(validation.hasCorruptHeader());
}

From source file:org.apache.cassandra.db.VerifyTest.java

@Test
public void testVerifyCorruptRowCorrectDigest() throws IOException, WriteTimeoutException {
    CompactionManager.instance.disableAutoCompaction();
    Keyspace keyspace = Keyspace.open(KEYSPACE);
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CORRUPT_CF2);

    fillCF(cfs, KEYSPACE, CORRUPT_CF2, 2);

    List<Row> rows = cfs.getRangeSlice(Util.range("", ""), null, new IdentityQueryFilter(), 1000);

    SSTableReader sstable = cfs.getSSTables().iterator().next();

    // overwrite one row with garbage
    long row0Start = sstable.getPosition(RowPosition.ForKey.get(ByteBufferUtil.bytes("0"), sstable.partitioner),
            SSTableReader.Operator.EQ).position;
    long row1Start = sstable.getPosition(RowPosition.ForKey.get(ByteBufferUtil.bytes("1"), sstable.partitioner),
            SSTableReader.Operator.EQ).position;
    long startPosition = row0Start < row1Start ? row0Start : row1Start;
    long endPosition = row0Start < row1Start ? row1Start : row0Start;

    RandomAccessFile file = new RandomAccessFile(sstable.getFilename(), "rw");
    file.seek(startPosition);/*from ww w.  jav  a 2  s . com*/
    file.writeBytes(StringUtils.repeat('z', (int) 2));
    file.close();

    // Update the Digest to have the right Checksum
    writeChecksum(simpleFullChecksum(sstable.getFilename()), sstable.descriptor.filenameFor(Component.DIGEST));

    Verifier verifier = new Verifier(cfs, sstable, false);

    // First a simple verify checking digest, which should succeed
    try {
        verifier.verify(false);
    } catch (CorruptSSTableException err) {
        fail("Simple verify should have succeeded as digest matched");
    }

    // Now try extended verify
    try {
        verifier.verify(true);

    } catch (CorruptSSTableException err) {
        return;
    }
    fail("Expected a CorruptSSTableException to be thrown");

}

From source file:net.naijatek.myalumni.util.utilities.FileUtil.java

public static String[] getLastLines(final File file, final int linesToReturn, final String logType)
        throws IOException, FileNotFoundException {

    final int AVERAGE_CHARS_PER_LINE = 250;
    final int BYTES_PER_CHAR = 2;

    RandomAccessFile randomAccessFile = null;
    StringBuffer buffer = new StringBuffer(linesToReturn * AVERAGE_CHARS_PER_LINE);
    int lineTotal = 0;
    try {/*w  w  w.  j a va2  s  .  c om*/
        randomAccessFile = new RandomAccessFile(file, "r");
        long byteTotal = randomAccessFile.length();
        long byteEstimateToRead = linesToReturn * AVERAGE_CHARS_PER_LINE * BYTES_PER_CHAR;

        long offset = byteTotal - byteEstimateToRead;
        if (offset < 0) {
            offset = 0;
        }

        randomAccessFile.seek(offset);
        //log.debug("SKIP IS ::" + offset);

        String line = null;
        String lineUTF8 = null;
        while ((line = randomAccessFile.readLine()) != null) {
            lineUTF8 = new String(line.getBytes("ISO8859_1"), "UTF-8");
            lineTotal++;
            buffer.append(lineUTF8).append("\n");
        }
    } finally {
        if (randomAccessFile != null) {
            try {
                randomAccessFile.close();
            } catch (IOException ex) {
            }
        }
    }

    //String[] resultLines = new String[linesToReturn];
    ArrayList<String> resultLines = new ArrayList<String>();
    BufferedReader in = null;
    try {
        in = new BufferedReader(new StringReader(buffer.toString()));

        int start = lineTotal /* + 2 */ - linesToReturn; // Ex : 55 - 10 = 45 ~ offset
        if (start < 0) {
            start = 0; // not start line
        }
        for (int i = 0; i < start; i++) {
            in.readLine(); // loop until the offset. Ex: loop 0, 1 ~~ 2 lines
        }

        int i = 0;
        String line = null;
        while ((line = in.readLine()) != null) {
            if (logType.equalsIgnoreCase("ALL")) {
                //resultLines[i] = line;
                resultLines.add(line);
                i++;
            } else if (line.indexOf(logType) > -1) {
                //resultLines[i] = line;
                resultLines.add(line);
                i++;
            }
        }
    } catch (IOException ie) {
        logger.error("Error" + ie);
        throw ie;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
            }
        }
    }

    String[] resultLines1 = new String[resultLines.size()];
    String tmp = new String();
    for (int i = 0; i < resultLines.size(); i++) {
        tmp = (String) resultLines.get(i);
        resultLines1[i] = tmp;
    }

    return resultLines1;
}

From source file:com.adaptris.core.fs.NonDeletingFsConsumerTest.java

private void resize(List<File> files) throws IOException {
    for (File f : files) {
        long currentSize = f.length();
        RandomAccessFile raf = new RandomAccessFile(f, "rwd");
        try {//from  ww  w.  ja v a 2s. c  o m
            raf.setLength(currentSize + 1);
        } finally {
            raf.close();
        }
    }
}