Example usage for java.io RandomAccessFile seek

List of usage examples for java.io RandomAccessFile seek

Introduction

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

Prototype

public void seek(long pos) throws IOException 

Source Link

Document

Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

Usage

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

@SuppressWarnings("unchecked")
@Override/* www. ja  va 2  s  . co  m*/
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:name.martingeisse.stackd.server.section.storage.FolderBasedSectionStorage.java

/**
 * //www  .  j  a v a  2 s . com
 */
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:com.polarion.pso.license.FetchUserLicenseTypeServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    ISecurityService securityService = (ISecurityService) PlatformContext.getPlatform()
            .lookupService(ISecurityService.class);
    ITrackerService trackerService = (ITrackerService) PlatformContext.getPlatform()
            .lookupService(ITrackerService.class);

    String userId = securityService.getCurrentUser();
    String userName = trackerService.getTrackerUser(userId).getName();

    long cutoff = System.currentTimeMillis() - (1000);
    File directory = new File("./logs/main");

    FileFilter wcFilter = new WildcardFileFilter("log4j-licensing-*.log");
    AgeFileFilter ageFilter = new AgeFileFilter(cutoff);
    FileFilter andFilter = new org.apache.commons.io.filefilter.AndFileFilter((IOFileFilter) ageFilter,
            (IOFileFilter) wcFilter);/*  w  w w  .  j  a  v  a2  s .c o m*/

    Collection<File> matches = FileUtils.listFiles(directory, (IOFileFilter) andFilter, null);

    if (!matches.isEmpty()) {

        File myFile = matches.iterator().next();
        RandomAccessFile licFile = new RandomAccessFile(myFile, "r");

        // Read the last 1024 bytes
        Long fileLength = licFile.length();
        Long offSet = fileLength - 1024;
        byte[] bStr = new byte[1024];
        licFile.seek(offSet);
        licFile.read(bStr);
        licFile.close();

        String logString = new java.lang.String(bStr);

        String[] lineArray = logString.split("\n");

        String searchString = "INFO  PolarionLicensing  - User \'" + userId + "\' logged in";
        Boolean found = false;
        Integer size = lineArray.length - 1;
        String licType = directory.toString();

        for (int i = size; i >= 0; i--) {
            String line = lineArray[i];
            if (line.contains(searchString) && found == false) {
                found = true;
                i = -1;
                Integer startIndex = line.indexOf(searchString) + searchString.length() + 6;
                licType = line.substring(startIndex);
                licType = licType.replace("\r", "");
                licType = licType.trim();
            }
        }

        req.setAttribute("userId", userName);
        req.setAttribute("licType", licType);
    } else {
        req.setAttribute("userId", userName);
        req.setAttribute("licType", "Not Found");
    }

    getServletContext().getRequestDispatcher("/currentUserLicenseType.jsp").forward(req, resp);
}

From source file:org.slc.sli.sample.transform.CcsCsvReader.java

private String tail(File file) {
    try {/*w w  w. j ava  2s.  c om*/
        RandomAccessFile fileHandler = new RandomAccessFile(file, "r");
        long fileLength = file.length() - 1;
        long filePointer;

        for (filePointer = fileLength; filePointer != -1; filePointer--) {
            fileHandler.seek(filePointer);
            int readByte = fileHandler.readByte();

            if (readByte == 0xA) {
                if (filePointer == fileLength) {
                    continue;
                } else {
                    break;
                }
            } else if (readByte == 0xD) {
                if (filePointer == fileLength - 1) {
                    continue;
                } else {
                    break;
                }
            }

        }

        String lastLine = fileHandler.readLine();
        fileHandler.close();

        return lastLine.substring(1);
    } catch (java.io.FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (java.io.IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java

/**
 * Tries to read an existing index from the given tar file. The index is
 * returned if it is found and looks valid (correct checksum, passes
 * sanity checks).// ww w .  j  ava 2  s .  c  o  m
 *
 * @param file tar file
 * @param name name of the tar file, for logging purposes
 * @return tar index, or {@code null} if not found or not valid
 * @throws IOException if the tar file could not be read
 */
private static ByteBuffer loadAndValidateIndex(RandomAccessFile file, String name) throws IOException {
    long length = file.length();
    if (length % BLOCK_SIZE != 0 || length < 6 * BLOCK_SIZE || length > Integer.MAX_VALUE) {
        log.warn("Unexpected size {} of tar file {}", length, name);
        return null; // unexpected file size
    }

    // read the index metadata just before the two final zero blocks
    ByteBuffer meta = ByteBuffer.allocate(16);
    file.seek(length - 2 * BLOCK_SIZE - 16);
    file.readFully(meta.array());
    int crc32 = meta.getInt();
    int count = meta.getInt();
    int bytes = meta.getInt();
    int magic = meta.getInt();

    if (magic != INDEX_MAGIC) {
        return null; // magic byte mismatch
    }

    if (count < 1 || bytes < count * 24 + 16 || bytes % BLOCK_SIZE != 0) {
        log.warn("Invalid index metadata in tar file {}", name);
        return null; // impossible entry and/or byte counts
    }

    // this involves seeking backwards in the file, which might not
    // perform well, but that's OK since we only do this once per file
    ByteBuffer index = ByteBuffer.allocate(count * 24);
    file.seek(length - 2 * BLOCK_SIZE - 16 - count * 24);
    file.readFully(index.array());
    index.mark();

    CRC32 checksum = new CRC32();
    long limit = length - 2 * BLOCK_SIZE - bytes - BLOCK_SIZE;
    long lastmsb = Long.MIN_VALUE;
    long lastlsb = Long.MIN_VALUE;
    byte[] entry = new byte[24];
    for (int i = 0; i < count; i++) {
        index.get(entry);
        checksum.update(entry);

        ByteBuffer buffer = ByteBuffer.wrap(entry);
        long msb = buffer.getLong();
        long lsb = buffer.getLong();
        int offset = buffer.getInt();
        int size = buffer.getInt();

        if (lastmsb > msb || (lastmsb == msb && lastlsb > lsb)) {
            log.warn("Incorrect index ordering in tar file {}", name);
            return null;
        } else if (lastmsb == msb && lastlsb == lsb && i > 0) {
            log.warn("Duplicate index entry in tar file {}", name);
            return null;
        } else if (offset < 0 || offset % BLOCK_SIZE != 0) {
            log.warn("Invalid index entry offset in tar file {}", name);
            return null;
        } else if (size < 1 || offset + size > limit) {
            log.warn("Invalid index entry size in tar file {}", name);
            return null;
        }

        lastmsb = msb;
        lastlsb = lsb;
    }

    if (crc32 != (int) checksum.getValue()) {
        log.warn("Invalid index checksum in tar file {}", name);
        return null; // checksum mismatch
    }

    index.reset();
    return index;
}

From source file:org.archive.wayback.resourcestore.locationdb.FileProxyServlet.java

private DataSource locationToDataSource(String location, long offset) throws IOException {
    DataSource ds = null;/*from  w  ww. j av  a 2 s  .c om*/
    if (location.startsWith("http://")) {
        URL url = new URL(location);
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            port = 80;
        }
        byte GET[] = "GET".getBytes();
        byte HTTP11[] = "HTTP/1.1".getBytes();
        InetAddress addr = InetAddress.getByName(hostname);
        HttpRequestMessage requestMessage = new HttpRequestMessage(GET, url.getFile().getBytes(), HTTP11);
        ANVLRecord headers = new ANVLRecord();
        headers.addLabelValue("Host", hostname);

        if (offset != 0) {
            headers.addLabelValue(RANGE_HTTP_HEADER,
                    HEADER_BYTES_PREFIX + String.valueOf(offset) + HEADER_BYTES_SUFFIX);
        }
        InetSocketAddress sockAddr = new InetSocketAddress(addr, port);
        Socket socket = new Socket();
        socket.setSoTimeout(socketTimeoutMs);
        socket.setReceiveBufferSize(BUF_SIZE);

        socket.connect(sockAddr, connectTimeoutMs);
        OutputStream socketOut = socket.getOutputStream();
        InputStream socketIn = socket.getInputStream();
        socketOut.write(requestMessage.getBytes(true));
        socketOut.write(headers.getUTF8Bytes());
        socketOut.flush();
        HttpResponse response = HttpResponse.load(socketIn);
        String contentType = response.getHeaders().asMap().get("Content-Type");
        if (contentType == null) {
            contentType = "application/unknown";
        }
        String xferEncoding = response.getHeaders().asMap().get("Transfer-Encoding");

        if (xferEncoding != null) {
            if (xferEncoding.equals("chunked")) {
                socketIn = new ChunkedInputStream(socketIn);
            }
        }

        ds = new URLDataSource(socketIn, contentType);

    } else {
        // assume a local file path:
        File f = new File(location);
        if (f.isFile() && f.canRead()) {
            long size = f.length();
            if (size < offset) {
                throw new IOException("short file " + location + " cannot" + " seek to offset " + offset);
            }
            RandomAccessFile raf = new RandomAccessFile(f, "r");
            raf.seek(offset);
            // BUGBUG: is it compressed?
            ds = new FileDataSource(raf, DEFAULT_CONTENT_TYPE);

        } else {
            throw new IOException("No readable file at " + location);
        }

    }

    return ds;
}

From source file:ape.CorruptCommand.java

/**
 * This method is the implementation of the corrupt function.
 * Given an address, it corrupts the file in the given address
 *///from  w ww.ja va 2 s  .  co m
public boolean corrupt(String corruptAddress) throws IOException {
    // Trying to get a random HDFS block file
    if (Main.VERBOSE) {
        System.out.println("Trying to get a random HDFS block file");
    }
    if (corruptAddress == null) {
        corruptAddress = getCorruptAddress();
    }

    // If the above statement failed to set corruptAddress then there was a failure
    if (corruptAddress == null) {
        System.out.println("Could not get a random HDFS block file");
        Main.logger.info("Could not get a random HDFS block file");
        return false;
    }

    byte[] buf;
    int count;

    try {
        RandomAccessFile tmp = new RandomAccessFile(corruptAddress, "rw");
        tmp.seek(offset);
        if (size <= 0) {
            System.out.println("ERROR: The size parameter must be positive");
            Main.logger.info("ERROR: The size parameter must be positive");
            return false;
        }

        buf = new byte[size];

        count = 0;
        if ((count = tmp.read(buf, 0, size)) == -1) {
            System.out.println("The file chosen is smaller than the corruption size (" + size + " bytes)");
            Main.logger.info("The file chosen is smaller than the corruption size (" + size + " bytes)");
            return false;
        }

        for (int i = 0; i < count; i++) {
            buf[i] = 0x3;
        }

        tmp.seek(0);
        tmp.close();
    } catch (FileNotFoundException e1) {
        System.out.println("Cannot open the file on the path given");
        Main.logger.info("Cannot open the file on the path given");
        e1.printStackTrace();
        Main.logger.info(e1);
        return false;
    } catch (IOException e) {
        System.out.println("Corrupting file failed");
        Main.logger.info("Corrupting file failed");
        e.printStackTrace();
        Main.logger.info(e);
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(corruptAddress, "rw");
        raf.seek(offset);
        raf.write(buf, 0, count);
        raf.seek(0);
        raf.close();

        return true;
    } catch (FileNotFoundException e1) {
        System.out.println("Cannot open the file on the path: " + corruptAddress);
        Main.logger.info("Cannot open the file on the path: " + corruptAddress);
        e1.printStackTrace();
        Main.logger.info(e1);
        return false;
    } catch (IOException e) {
        System.out.println("Corrupting file failed");
        Main.logger.info("Corrupting file failed");
        e.printStackTrace();
        Main.logger.info(e);
        return false;
    }
}

From source file:org.jraf.irondad.handler.pixgame.PixGameHandler.java

public String getRandomWord(HandlerContext handlerContext) throws IOException {
    RandomAccessFile file = new RandomAccessFile(
            ((PixGameHandlerConfig) handlerContext.getHandlerConfig()).getDictPath(), "r");
    file.seek((long) (Math.random() * file.length()));
    // Eat the characters of the current line to go to beginning of the next line
    file.readLine();//  w w w  .  ja  v a 2s. c  om
    // Now read and return the line
    return file.readLine();
}

From source file:info.ajaxplorer.client.http.AjxpFileBody.java

public void writeTo(OutputStream out) {
    InputStream in;//from   w  ww. ja  v a 2 s.  co m
    try {
        if (this.chunkSize > 0) {
            //System.out.println("Uploading file part " + this.chunkIndex);
            RandomAccessFile raf = new RandomAccessFile(getFile(), "r");
            int start = chunkIndex * this.chunkSize;
            int count = 0;
            int limit = chunkSize;
            if (chunkIndex == (totalChunks - 1)) {
                limit = lastChunkSize;
            }
            raf.seek(start);
            while (count < limit) {
                int byt = raf.read();
                out.write(byt);
                count++;
            }
            raf.close();
            //System.out.println("Sent " + count);            
        } else {
            in = new FileInputStream(getFile());
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
        }
        this.chunkIndex++;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

/**
 * Corrupt the byte at the given offset in the given file,
 * by subtracting 1 from it./* w  w w  .j a va2s .  co m*/
 */
private void corruptByteInFile(File file, long offset) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    try {
        raf.seek(offset);
        int origByte = raf.read();
        raf.seek(offset);
        raf.writeByte(origByte - 1);
    } finally {
        IOUtils.closeStream(raf);
    }
}