Example usage for java.io RandomAccessFile length

List of usage examples for java.io RandomAccessFile length

Introduction

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

Prototype

public native long length() throws IOException;

Source Link

Document

Returns the length of this file.

Usage

From source file:org.kalypso.shape.shp.SHPFile.java

/**
 * Adds a new shape entry to the end of the file.<br>
 * This method is atomic in that sense that if an exception occurs while a shape convertet to bytes, inetad a
 * Null-Shape will be written./* w w  w  . j a va  2 s  .  c  o  m*/
 */
public SHXRecord addShape(final ISHPGeometry shape, final int recordNumber) throws IOException, SHPException {
    if (shape == null)
        throw new SHPException("shape == null not allowed. Add SHPNullShape instead.");

    if (!(shape instanceof SHPNullShape) && shape.getType() != getShapeType())
        throw new SHPException("Cannot add shape, wrong type.");

    final RandomAccessFile raf = getRandomAccessFile();

    final long currentFileLength = raf.length();

    /* Convert shape into bytes and write them in one go */
    final byte[] bytes = writeRecordAsBytes(recordNumber, shape);
    raf.seek(currentFileLength);
    raf.write(bytes);

    /* Update header */
    final SHPEnvelope shapeMbr = shape.getEnvelope();
    expandMbr(shapeMbr);

    /* Create and return index record */
    final int contentLength = bytes.length - RECORD_HEADER_BYTES;
    return new SHXRecord((int) currentFileLength / 2, contentLength / 2);
}

From source file:org.opencms.workplace.tools.sites.CmsSiteFaviconDialog.java

/**
 * @see org.opencms.workplace.administration.A_CmsImportFromHttp#actionCommit()
 *//*from   w  w w.j a va 2  s  . co m*/
@Override
public void actionCommit() throws IOException, ServletException {

    String site = getParamSites();
    try {
        // check if the site stored in the sites parameter exists and is readable
        CmsObject cms = OpenCms.initCmsObject(getCms());
        cms.getRequestContext().setSiteRoot("");
        cms.existsResource(site + "/");

        // copy the file to the server
        copyFileToServer(OpenCms.getSystemInfo().getPackagesRfsPath());
        if ((getParamImportfile() == null) || !getParamImportfile().equals(ICON_NAME)) {
            // file null or name not valid
            throw new CmsException(
                    Messages.get().container(Messages.ERR_INVALID_FAVICON_FILE_1, getParamImportfile()));
        }

        // get the uploaded file content
        String importpath = OpenCms.getSystemInfo().getPackagesRfsPath();
        importpath = OpenCms.getSystemInfo()
                .getAbsoluteRfsPathRelativeToWebInf(importpath + getParamImportfile());
        RandomAccessFile f = new RandomAccessFile(importpath, "r");
        byte[] content = new byte[(int) f.length()];
        f.read(content);
        f.close();

        // check the existence of favicon
        String favCreatePath = site + "/" + ICON_NAME;
        int imageResId = CmsResourceTypeImage.getStaticTypeId();
        if (cms.existsResource(favCreatePath)) {
            // replace the existing favicon
            cms.lockResource(favCreatePath);
            cms.replaceResource(favCreatePath, imageResId, content, new ArrayList<CmsProperty>());
            cms.unlockResource(favCreatePath);
        } else {
            // create the new favicon
            cms.createResource(favCreatePath, imageResId, content, new ArrayList<CmsProperty>());
        }

        // set the dialog parameters
        String title = OpenCms.getSiteManager().getSiteForSiteRoot(site).getTitle();
        Map<String, String[]> params = new HashMap<String, String[]>();
        params.put(CmsSitesOverviewList.PARAM_SITES, new String[] { getParamSites() });
        params.put(CmsSitesOverviewList.PARAM_SITE_TITLE, new String[] { title });
        params.put(PARAM_ACTION, new String[] { DIALOG_INITIAL });

        // forward the request
        getToolManager().jspForwardTool(this, "/sites/detail", params);

    } catch (CmsException e) {
        // error copying the file to the OpenCms server
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(getLocale()), e);
        }
        setException(e);
        return;
    }
}

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

@Test(timeout = 60000)
public void testCorruptEntryLog() 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);//from   w  w w  . j av  a 2s.  com
    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.flush();
    // now lets truncate the file to corrupt the last entry, which simulates a partial write
    File f = new File(curDir, "0.log");
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.setLength(raf.length() - 10);
    raf.close();
    // now see which ledgers are in the log
    logger = new EntryLogger(conf, bookie.getLedgerDirsManager());

    EntryLogMetadata meta = logger.getEntryLogMetadata(0L);
    LOG.info("Extracted Meta From Entry Log {}", meta);
    assertNotNull(meta.getLedgersMap().get(1L));
    assertNull(meta.getLedgersMap().get(2L));
    assertNotNull(meta.getLedgersMap().get(3L));
}

From source file:name.martingeisse.stackd.server.section.storage.FolderBasedSectionStorage.java

/**
 * //w w w  .  jav  a  2 s.  c om
 */
private void saveSectionToFile(final InputStream in, final RandomAccessFile access, final int tocIndex)
        throws IOException {

    // write the section to the end of the file
    final int dataAddress = (int) access.length();
    access.seek(dataAddress);
    final byte[] compressedCubeData = IOUtils.toByteArray(in);
    access.write(compressedCubeData);

    // update the ToC entry
    access.seek(tocIndex * 12);
    access.writeInt(dataAddress);
    access.writeInt(compressedCubeData.length);
    access.writeInt(0);

}

From source file:org.hrva.capture.LogTail.java

/**
 * Tail the given file if the size has changed and return a temp filename.
 *
 * <p>This returns a temp filename if the log being tailed has changed.
 * </p>//from   w  w w  .j  a  v  a 2  s.  co m
 * 
 * <p>The supplied target filename is -- actually -- a format string.
 * The available value, <<tt>{0}</tt> is the sequence number
 * that's saved in the history cache.</p>
 *
 * @param source The log filename to tail
 * @param target A temporary filename into which to save the tail piece.
 * @return temp filename, if the file size changed; otherwise null
 * @throws FileNotFoundException
 * @throws IOException
 */
public String tail(String source, String target) throws FileNotFoundException, IOException {
    // The resulting file name (or null if the log did not grow).
    String temp_name = null;

    // Open our last-time-we-looked file.
    String cache_file_name = global.getProperty("logtail.tail_status_filename", "logtail.history");
    String limit_str = global.getProperty("logtail.file_size_limit", "1m"); // 1 * 1024 * 1024;
    int limit;
    if (limit_str.endsWith("m") || limit_str.endsWith("M")) {
        limit = 1024 * 1024 * Integer.parseInt(limit_str.substring(0, limit_str.length() - 1));
    } else if (limit_str.endsWith("k") || limit_str.endsWith("K")) {
        limit = 1024 * Integer.parseInt(limit_str.substring(0, limit_str.length() - 1));
    } else {
        limit = Integer.parseInt(limit_str);
    }

    Properties state = get_state(cache_file_name);

    // Find the previous size and sequence number
    String prev_size_str = state.getProperty("size." + source, "0");
    long prev_size = Long.parseLong(prev_size_str);
    String seq_str = state.getProperty("seq." + source, "0");
    long sequence = Long.parseLong(seq_str);

    Object[] details = { source, target, seq_str, prev_size_str };
    logger.info(MessageFormat.format("Tailing {0} to {1}", details));
    logger.info(MessageFormat.format("Count {2}, Bytes {3}", details));
    sequence += 1;

    // Attempt to seek to the previous position
    long position = 0;
    File log_to_tail = new File(source);
    RandomAccessFile rdr = new RandomAccessFile(log_to_tail, "r");
    try {
        long current_size = rdr.length();
        if (current_size == prev_size) {
            // Same size.  Nothing more to do here.
            position = current_size;
        } else {
            // Changed size.  Either grew or was truncated.
            if (rdr.length() < prev_size) {
                // Got truncated.  Read from beginning.
                sequence = 0;
                prev_size = 0;
            } else {
                // Got bigger.  Read from where we left off.
                rdr.seek(prev_size);
            }
            // Read to EOF or the limit.  
            // No reason to get greedy.
            int read_size;
            if (current_size - prev_size > limit) {
                read_size = limit;
                rdr.seek(current_size - limit);
            } else {
                read_size = (int) (current_size - prev_size);
            }
            byte[] buffer = new byte[read_size];
            rdr.read(buffer);
            position = rdr.getFilePointer();

            // Write temp file
            Object[] args = { sequence };
            temp_name = MessageFormat.format(target, args);

            File extract = new File(temp_name);
            OutputStream wtr = new FileOutputStream(extract);
            wtr.write(buffer);
        }
    } finally {
        rdr.close();
    }

    // Update our private last-time-we-looked file.
    state.setProperty("size." + source, String.valueOf(position));
    state.setProperty("seq." + source, String.valueOf(sequence));
    save_state(cache_file_name, state);

    Object[] details2 = { source, target, seq_str, prev_size_str, String.valueOf(sequence),
            String.valueOf(position) };
    logger.info(MessageFormat.format("Count {4}, Bytes {5}", details2));

    return temp_name;
}

From source file:org.kalypso.shape.shp.SHPFile.java

@Override
public void close() throws IOException {
    final RandomAccessFile raf = getRandomAccessFile();

    if (isWriting()) {
        // Update header with length
        final long fileLength = raf.length();
        updateHeader((int) fileLength, getMBR());

        /* and write the header */
        raf.seek(0);//  w  w  w . j ava2s . co m

        final ShapeHeader header = getHeader();
        header.write(raf);
    }

    raf.close();
}

From source file:phex.update.UpdateCheckRunner.java

private String getErrorLogFileTail() {
    try {// ww w.  j a  va  2s.  co  m
        File logFile = Environment.getInstance().getPhexConfigFile("phex.error.log");
        if (!logFile.exists()) {
            return null;
        }
        RandomAccessFile raf = new RandomAccessFile(logFile, "r");
        long pos = Math.max(raf.length() - 10 * 1024, 0);
        raf.seek(pos);
        byte[] buffer = new byte[(int) Math.min(10 * 1024, raf.length())];
        int lenRead = raf.read(buffer);
        return new String(buffer, 0, lenRead);
    } catch (IOException exp) {
        NLogger.error(UpdateCheckRunner.class, exp, exp);
        return exp.toString();
    }
}

From source file:IntergrationTest.OCSPIntegrationTest.java

@Before
public void setUp() throws Exception {
    OCSP_URL = new URI("http://localhost:" + serverPort + "/verify-mocked-good");
    OCSP_MODE_URL = new URI("http://localhost:" + serverPort + "/set-response-mode");
    RandomAccessFile raf = new RandomAccessFile("certs/client/client.cer.pem", "r");
    byte[] buf = new byte[(int) raf.length()];
    raf.readFully(buf);//  ww  w.j  av a 2  s.  c  o  m
    raf.close();
    clientCert = readPemCert(buf);
    MatcherAssert.assertThat(clientCert, CoreMatchers.notNullValue());
    issuerCert = getX509Certificate(httpGetBin(getIssuerCertURL(clientCert), true));
    MatcherAssert.assertThat(issuerCert, CoreMatchers.notNullValue());
}

From source file:nl.mpi.handle.util.implementation.HandleUtil.java

/**
 * Gets the website service account private key file from the local file system.
 * @return Returns the private key file as a byte array.
 * @throws java.io.FileNotFoundException Throws <CODE>FileNotFoundException</CODE> if the private key file for the website Handle System service account cannot be found on the local file system.
 * @throws java.io.IOException Throws <CODE>IOException</CODE> if the private key file for the website Handle System service account cannot be accessed.
 *///from w w w.j a v  a2 s  .c  om
public byte[] getPrivateKeyFile() throws IOException {
    byte[] fileBytes = null;

    File privKeyFile = new File(handleAdminKeyFilePath);

    if (privKeyFile.exists() == false) {
        throw new IOException("The admin private key file could not be found.");
    }

    if (privKeyFile.canRead() == false) {
        throw new IOException("The admin private key file cannot be read.");
    }

    RandomAccessFile privateKeyContents = new RandomAccessFile(privKeyFile, "r");

    int length = (int) privateKeyContents.length();

    if (length > 0) {
        fileBytes = new byte[length];
        privateKeyContents.read(fileBytes);
        privateKeyContents.close();
    } else {
        throw new IOException("The private key file is empty.");
    }

    return fileBytes;
}

From source file:com.microsoft.azure.management.datalake.store.uploader.SingleSegmentUploader.java

/**
 * Opens the input stream.//w w w.j  a v  a  2 s.c  o  m
 * @return A {@link RandomAccessFile} stream of the file being uploaded.
 * @throws IOException Thrown if the input stream cannot be opened due to file accessibility or existence.
 */
private RandomAccessFile openInputStream() throws IOException {
    RandomAccessFile stream = new RandomAccessFile(metadata.getInputFilePath(), "r");

    if (segmentMetadata.getOffset() >= stream.length()) {
        throw new IllegalArgumentException("StartOffset is beyond the end of the input file");
    }

    // always seek from the beginning of the file
    stream.seek(0);
    stream.seek(segmentMetadata.getOffset());
    return stream;
}