Example usage for java.io RandomAccessFile readFully

List of usage examples for java.io RandomAccessFile readFully

Introduction

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

Prototype

public final void readFully(byte b[]) throws IOException 

Source Link

Document

Reads b.length bytes from this file into the byte array, starting at the current file pointer.

Usage

From source file:com.siblinks.ws.service.impl.CommentServiceImpl.java

/**
 * This method to get image from path directory Image question
 *
 * @param image//w  w  w.j av a2 s  . co  m
 *            name
 *
 */
@Override
@RequestMapping(value = "/getImageQuestion/{name}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageQuestion(@PathVariable(value = "name") final String name) {
    RandomAccessFile t = null;
    ResponseEntity<byte[]> responseEntity = null;
    try {
        if (name != null) {
            String directory = environment.getProperty("directoryImageQuestion");

            String path = directory + "/" + name + ".png";

            t = new RandomAccessFile(path, "r");
            byte[] r = new byte[(int) t.length()];
            t.readFully(r);
            responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    } finally {
        try {
            if (t != null) {
                t.close();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
    return responseEntity;
}

From source file:org.gcaldaemon.api.SyncEngine.java

/**
 * Synchronizes a remote Google Calendar to a local iCalendar (RFC 2445)
 * file. If the local calendar file does not exists, the SyncEngine will
 * download and save the original iCalendar file (with ToDo entries) without
 * any synchronization. Creates daily backups of all Google AND local
 * calendars into the 'backup' subdirectory (under the working directory).
 * //from  w ww .  ja  v  a 2 s  . com
 * @param localCalendar
 *            local calendar file
 * @param remoteCalendar
 *            Google Calendar's private ICAL URL
 *            ("https://www.google.com/calendar/ical/.../basic.ics"), or the
 *            RSS/ATOM feed's URL (= feed converter mode)
 * @param username
 *            full name of the user (eg. "username@gmail.com" or
 *            "username@mydomain.org"), this value is optional in feed
 *            converter mode
 * @param password
 *            Gmail password (in unencrypted, plain text format), this value
 *            is optional in feed converter mode
 * 
 * @throws Exception
 *             any exception (eg. i/o, invalid param, invalid calendar
 *             syntax, etc)
 * 
 * @see #getCacheTimeout
 * @see #setCacheTimeout
 */
public final void synchronize(File localCalendar, URL remoteCalendar, String username, String password)
        throws Exception {

    // Verify required parameters
    if (localCalendar == null) {
        throw new NullPointerException("localCalendar = null");
    }
    if (remoteCalendar == null) {
        throw new NullPointerException("remoteCalendar = null");
    }
    String path = remoteCalendar.getPath();
    if (path.endsWith(".ics")) {

        // Synchronizer mode
        if (username == null || username.length() == 0) {
            throw new NullPointerException("username = null");
        }
        if (username.indexOf('@') == -1) {
            throw new IllegalArgumentException("invalid username");
        }
        if (password == null || password.length() == 0) {
            throw new NullPointerException("password = null");
        }
    } else {

        // Feed converter mode
        checkFeedConverter();
        path = remoteCalendar.toString();
    }

    // Load local calendar file
    byte[] bytes = null;
    if (localCalendar.isFile()) {
        RandomAccessFile file = null;
        try {
            file = new RandomAccessFile(localCalendar, "r");
            bytes = new byte[(int) localCalendar.length()];
            file.readFully(bytes);
        } finally {
            if (file != null) {
                file.close();
            }
        }
    }

    // Create (or reinitialize) the cached instance
    if (configChanged) {
        configChanged = false;
        configurator = new Configurator(null, properties, false, Configurator.MODE_EMBEDDED);
    }

    // Create request container
    Request request = new Request();
    request.body = bytes;
    request.url = path;
    request.username = username;
    request.password = password;
    request.filePath = localCalendar.getAbsolutePath();

    // Do synchronization (if the 'localCalendar' is defined)
    if (bytes != null && bytes.length != 0) {
        configurator.synchronizeNow(request);
    }

    // Return the modified calendar (with ToDo entries)
    CachedCalendar calendar = configurator.getCalendar(request);
    bytes = calendar.toByteArray();

    // Save new content into the calendar file
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(localCalendar);
        out.write(bytes);
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.siblinks.ws.service.impl.ArticleServiceImpl.java

/**
 * {@inheritDoc}/*from   w  w w. ja v  a 2  s .  com*/
 * 
 */
@SuppressWarnings("resource")
@Override
@RequestMapping(value = "/getImageArticle/{arId}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> getImageArticle(@PathVariable(value = "arId") final String arId)
        throws IOException {
    RandomAccessFile t = null;
    Object[] queryParams = { arId };
    String path = null;
    ResponseEntity<byte[]> responseEntity = null;
    try {
        List<Object> readObject = dao.readObjects(SibConstants.SqlMapper.SQL_GET_IMAGE_ARTICLE, queryParams);
        if (((Map) readObject.get(0)).get(Parameters.IMAGE) != null) {
            path = ((Map) readObject.get(0)).get(Parameters.IMAGE).toString();
            // System.out.print(Paths.get("").toAbsolutePath()+path);
            path = Paths.get("").toAbsolutePath() + path;
            byte[] r = null;
            try {
                t = new RandomAccessFile(path, "r");
                r = new byte[(int) t.length()];
                t.readFully(r);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            final HttpHeaders headers = new HttpHeaders();

            responseEntity = new ResponseEntity<byte[]>(r, headers, HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
    } finally {
        if (t != null) {
            t.close();
        }
    }
    return responseEntity;
}

From source file:org.kuali.student.git.model.SvnRevisionMapper.java

private InputStream getInputStream(RevisionMapOffsetProvider offsetProvider, RandomAccessFile dataFile)
        throws IOException {

    RevisionMapOffset revisionOffset = offsetProvider.getRevisionMapOffset();

    if (revisionOffset == null)
        return null;

    byte[] data = new byte[(int) revisionOffset.getTotalBytes()];

    dataFile.seek(revisionOffset.getStartBtyeOffset());

    dataFile.readFully(data);

    return new BZip2CompressorInputStream(new ByteArrayInputStream(data));

}

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

private final String loadToDoBlock(Request request) throws Exception {
    String toDoBlock = (String) toDoCache.get(request.url);
    if (toDoBlock != null) {
        return toDoBlock;
    }/*from  ww w . j av a  2 s  . co m*/
    File file = getToDoFile(request);
    if (file.exists()) {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            byte[] bytes = new byte[(int) raf.length()];
            raf.readFully(bytes);
            raf.close();
            toDoBlock = StringUtils.decodeToString(bytes, StringUtils.UTF_8);
            if (toDoCache.size() > MAX_CACHE_SIZE) {
                toDoCache.clear();
            }
            toDoCache.put(request.url, toDoBlock);
            return toDoBlock;
        } catch (Exception ioError) {
            try {
                raf.close();
            } catch (Exception ignored) {
            }
            if (file != null) {
                file.delete();
            }
        }
    }
    return null;
}

From source file:com.siblinks.ws.service.impl.MentorServiceImpl.java

/**
 * {@inheritDoc}/*from www.  j  a va2 s . c  o  m*/
 */
@Override
@RequestMapping(value = "/getImageAboutMentor/{id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> getImageAboutMentor(@PathVariable(value = "id") final String id) {
    ResponseEntity<byte[]> responseEntity = null;
    try {
        Map<String, String> queryParams = new HashMap<String, String>();
        List<Object> readObject = null;

        queryParams.put("id", id);
        String entityName = SibConstants.SqlMapper.SQL_GET_IMAGE_ABOUT_MENTOR;
        String path = null;

        readObject = dao.readObjects(entityName, queryParams);
        if (((Map) readObject.get(0)).get(Parameters.IMAGE) != null) {
            path = ((Map) readObject.get(0)).get(Parameters.IMAGE).toString();

            RandomAccessFile t = null;
            byte[] r = null;
            try {
                t = new RandomAccessFile(path, "r");
                r = new byte[(int) t.length()];
                t.readFully(r);
                responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK);
            } catch (IOException e) {
                logger.debug("Some thing wrong", e);
                responseEntity = new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
            } finally {
                // Close file
                if (t != null) {
                    try {
                        t.close();
                    } catch (IOException e) {
                        // Do nothing
                    }
                }
            }
        } else {
            responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }
    } catch (DAOException e) {
        e.printStackTrace();
        new SimpleResponse(SibConstants.FAILURE, "Mentor", "getImageAboutMentor", e.getMessage());
    }
    return responseEntity;
}

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

private final void manageBackups(CachedCalendar calendar, long now) throws Exception {

    // Get backup dir
    File backupDirectory = new File(workDirectory, "backup");
    if (!backupDirectory.isDirectory()) {
        backupDirectory.mkdirs();//from   ww w .  ja va2 s  .c  o  m
    }

    // Cleanup backup directory
    if (backupFiles.size() == 1) {
        String[] files = backupDirectory.list();
        File backup;
        for (int i = 0; i < files.length; i++) {
            backup = new File(backupDirectory, files[i]);
            if (now - backup.lastModified() > backupTimeout) {
                backup.delete();
            }
        }
    }

    // Generate backup file names (2007-05-12-ical-3947856328.bak)
    String hashCode = Long.toString(Math.abs(calendar.url.hashCode()));
    String date = BACKUP_FORMAT.format(new Date(now));
    String icalFileName = date + "-ical-" + hashCode + ".ics";
    String gcalFileName = date + "-gcal-" + hashCode + ".ics";
    File icalBackupFile = new File(backupDirectory, icalFileName);
    File gcalBackupFile = new File(backupDirectory, gcalFileName);

    // Save Google backup
    byte[] bytes = calendar.toByteArray();
    saveBackup(gcalBackupFile, bytes);

    // Save local backup
    if (calendar.filePath == null) {
        return;
    }
    File localFile = new File(calendar.filePath);
    if (!localFile.isFile()) {
        return;
    }
    if (icalBackupFile.exists()) {
        return;
    }
    RandomAccessFile in = null;
    try {
        in = new RandomAccessFile(localFile, "r");
        bytes = new byte[(int) localFile.length()];
        in.readFully(bytes);
        in.close();
        saveBackup(icalBackupFile, bytes);
    } catch (Exception ioException) {
        if (in != null) {
            in.close();
        }
    }
}

From source file:gate.util.reporting.PRTimeReporter.java

/**
 * Reads the given file upside down.//w w w  .  ja  va2  s .c  om
 *
 * @param fileToBeRead
 *          An object of type File representing the file to be read.
 * @param chunkSize
 *          An integer specifying the size of the chunks in which file will be
 *          read.
 * @return A long value pointing to the start position of the given file
 *         chunk.
 * @throws BenchmarkReportInputFileFormatException
 */
private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException {
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(fileToBeRead, "r");
        Vector<String> lastNlines = new Vector<String>();
        int delta = 0;
        long curPos = raf.length() - 1;
        long fromPos;
        byte[] bytearray;
        while (true) {
            fromPos = curPos - chunkSize;
            if (fromPos <= 0) {
                raf.seek(0);
                bytearray = new byte[(int) curPos];
                raf.readFully(bytearray);
                if (parseLinesFromLast(bytearray, lastNlines)) {
                    if (fromPos < 0)
                        fromPos = 0;
                }
                break;
            } else {
                raf.seek(fromPos);
                bytearray = new byte[chunkSize];
                raf.readFully(bytearray);
                if (parseLinesFromLast(bytearray, lastNlines)) {
                    break;
                }
                delta = (lastNlines.get(lastNlines.size() - 1)).length();
                lastNlines.remove(lastNlines.size() - 1);
                curPos = fromPos + delta;
            }
        }
        if (fromPos < 0)
            throw new BenchmarkReportInputFileFormatException(
                    getBenchmarkFile().getAbsolutePath() + " does not contain a marker named "
                            + getLogicalStart() + " indicating logical start of a run.");
        return fromPos;

    } catch (IOException e) {
        e.printStackTrace();
        return -1;
    } finally {
        IOUtils.closeQuietly(raf);
    }
}

From source file:org.chililog.server.workbench.StaticFileRequestHandler.java

/**
 * Process the message//www . jav a 2 s .  c o  m
 */
@Override
public void processMessage(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();

    // We don't handle 100 Continue because we only allow GET method.
    if (request.getMethod() != HttpMethod.GET) {
        sendError(ctx, e, METHOD_NOT_ALLOWED, null);
        return;
    }

    // Check
    final String filePath = convertUriToPhysicalFilePath(request.getUri());
    if (filePath == null) {
        sendError(ctx, e, FORBIDDEN, null);
        return;
    }
    File file = new File(filePath);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, e, NOT_FOUND, String.format("%s not exist", file.getCanonicalPath()));
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, e, FORBIDDEN, String.format("%s not a file", file.getCanonicalPath()));
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.getHeader(HttpHeaders.Names.IF_MODIFIED_SINCE);
    if (!StringUtils.isBlank(ifModifiedSince)) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client does not have milliseconds 
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx, e);
            return;
        }
    }

    // Open file for sending back
    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, e, NOT_FOUND, null);
        return;
    }
    long fileLength = raf.length();

    // Log
    writeLogEntry(e, OK, null);

    // Create the response
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);

    // Write the content.
    Channel ch = e.getChannel();
    ChannelFuture writeFuture;
    if (AppProperties.getInstance().getWorkbenchSslEnabled()) {
        // Cannot use zero-copy with HTTPS

        // Write the initial line and the header.
        ch.write(response);

        // Write chunks
        writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // Now that we are using Execution Handlers, we cannot do zero-copy.
        // Do as per with compression (which is what most browser will ask for)
        byte[] buffer = new byte[(int) fileLength];
        raf.readFully(buffer);
        raf.close();

        response.setContent(ChannelBuffers.copiedBuffer(buffer));
        writeFuture = ch.write(response);

        /*
         * // No encryption - use zero-copy. // However zero-copy does not seem to work with compression // Only use
         * zero-copy for large files like movies and music // Write the initial line and the header.
         * ch.write(response); // Zero-copy final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0,
         * fileLength); writeFuture = ch.write(region); writeFuture.addListener(new ChannelFutureProgressListener()
         * { public void operationComplete(ChannelFuture future) { region.releaseExternalResources(); } public void
         * operationProgressed(ChannelFuture future, long amount, long current, long total) {
         * _logger.debug("Zero-Coping file %s: %d / %d (+%d) bytes", filePath, current, total, amount); } });
         */
    }

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:gate.util.reporting.DocTimeReporter.java

/**
 * A method for reading the file upside down.
 *
 * @param fileToBeRead// w  ww .  ja v  a2  s . com
 *          An object of the file to be read.
 * @param chunkSize
 *          An integer specifying the size of the chunks in which file will be
 *          read.
 * @return A long value pointing to the start position of the given file
 *         chunk.
 */
private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException {
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(fileToBeRead, "r");
        Vector<String> lastNlines = new Vector<String>();
        int delta = 0;
        long curPos = 0;
        curPos = raf.length() - 1;
        long fromPos;
        byte[] bytearray;
        while (true) {
            fromPos = curPos - chunkSize;
            if (fromPos <= 0) {
                raf.seek(0);
                bytearray = new byte[(int) curPos];
                raf.readFully(bytearray);
                if (parseLinesFromLast(bytearray, lastNlines, fromPos)) {
                    if (fromPos < 0)
                        fromPos = 0;
                }
                break;
            } else {
                raf.seek(fromPos);
                bytearray = new byte[chunkSize];
                raf.readFully(bytearray);
                if (parseLinesFromLast(bytearray, lastNlines, fromPos)) {
                    break;
                }
                delta = lastNlines.get(lastNlines.size() - 1).length();
                lastNlines.remove(lastNlines.size() - 1);
                curPos = fromPos + delta;
            }
        }
        if (fromPos < 0)
            throw new BenchmarkReportInputFileFormatException(
                    getBenchmarkFile() + " does not contain a marker named " + getLogicalStart()
                            + " indicating logical start of a run.");
        return fromPos;

    } catch (IOException e) {
        e.printStackTrace();
        return -1;
    } finally {
        IOUtils.closeQuietly(raf);
    }
}