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:com.evolveum.midpoint.model.impl.controller.ModelDiagController.java

private LogFileContentType getLogFileFragment(File logFile, Long fromPosition, Long maxSize)
        throws IOException {
    LogFileContentType rv = new LogFileContentType();
    RandomAccessFile log = null;
    try {/*from  w w w .j  a v a 2s.  c  o  m*/
        log = new RandomAccessFile(logFile, "r");
        long currentLength = log.length();
        rv.setLogFileSize(currentLength);

        long start;
        if (fromPosition == null) {
            start = 0;
        } else if (fromPosition >= 0) {
            start = fromPosition;
        } else {
            start = Math.max(currentLength + fromPosition, 0);
        }
        rv.setAt(start);
        log.seek(start);
        long bytesToRead = Math.max(currentLength - start, 0);
        if (maxSize != null && maxSize < bytesToRead) {
            bytesToRead = maxSize;
            rv.setComplete(false);
        } else {
            rv.setComplete(true);
        }
        if (bytesToRead == 0) {
            return rv;
        } else if (bytesToRead > Integer.MAX_VALUE) {
            throw new IllegalStateException("Too many bytes to read from log file: " + bytesToRead);
        }
        byte[] buffer = new byte[(int) bytesToRead];
        log.readFully(buffer);
        rv.setContent(new String(buffer));
        return rv;
    } finally {
        if (log != null) {
            IOUtils.closeQuietly(log);
        }
    }
}

From source file:com.liferay.portal.util.FileImpl.java

public byte[] getBytes(File file) throws IOException {
    if ((file == null) || !file.exists()) {
        return null;
    }//from   ww  w .j a v  a2 s.  co m

    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");

    byte[] bytes = new byte[(int) randomAccessFile.length()];

    randomAccessFile.readFully(bytes);

    randomAccessFile.close();

    return bytes;
}

From source file:com.hly.component.download.DownloadTransaction.java

public void run() {
    // TODO ?Daemon
    InputStream is = null;//w  w  w.  ja  v a  2 s. c om
    HttpURLConnection conn = null;
    RandomAccessFile randomFile = null;
    File tmpFile = null;
    try {
        // ?uri
        tmpFile = new File(mTempLocalUri);
        File parentFile = tmpFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        if (!tmpFile.exists()) {
            tmpFile.createNewFile();
        }
        randomFile = new RandomAccessFile(mTempLocalUri, "rw");
        long fileLength = randomFile.length();
        completeSize = fileLength;

        if (isCancel) {
            return;
        }
        String connUrl = mUri;
        // ?uri????
        // getRedirectUrl(connUrl);
        if (!T.ckIsEmpty(mRedirectUri)) {
            connUrl = mRedirectUri;
        }
        conn = getHttpConnetion(connUrl);
        conn.setRequestProperty("range", "bytes=" + fileLength + "-");
        conn.connect();

        int contentLength = conn.getContentLength();
        totalSize = completeSize + contentLength;
        if (contentLength == -1 || contentLength > 0) {
            //    
            randomFile.seek(fileLength);
            byte[] buffer = new byte[8192];
            is = conn.getInputStream();
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                if (isCancel) {
                    return;
                }
                randomFile.write(buffer, 0, length);
                completeSize += length;
                notifyProgress(length);
            }
        }
        mTransactionState.setState(TransactionState.SUCCESS);
    } catch (Throwable t) {
        Log.w(TAG, Log.getStackTraceString(t));
    } finally {
        isRunning = false;
        isCancel = false;
        try {
            if (randomFile != null) {
                randomFile.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            conn.disconnect();
        }

        if (mTransactionState.getState() != TransactionState.SUCCESS) {
            mTransactionState.setState(TransactionState.FAILED);
            Log.e(TAG, "Delivery failed.");
        } else {
            if (tmpFile == null) {
                mTransactionState.setState(TransactionState.FAILED);
            } else {
                File localFile = new File(this.mLocalUri);
                boolean flag = tmpFile.renameTo(localFile);
                if (flag) {
                    Log.d(TAG, "rename pic succ" + this.mLocalUri);
                } else {
                    mTransactionState.setState(TransactionState.FAILED);
                    Log.d(TAG, "rename pic failed" + this.mLocalUri);
                }
            }
        }
        notifyObservers();
    }
}

From source file:com.devilyang.musicstation.cache.ACache.java

/**
 * ? byte ?/*from   w  w w .  ja va 2 s.co m*/
 * 
 * @param key
 * @return byte ?
 */
public byte[] getAsBinary(String key) {
    RandomAccessFile RAFile = null;
    boolean removeFile = false;
    try {
        File file = mCacheManager.get(key);
        if (!file.exists())
            return null;
        RAFile = new RandomAccessFile(file, "r");
        byte[] byteArray = new byte[(int) RAFile.length()];
        RAFile.read(byteArray);
        if (!Utils.isDue(byteArray)) {
            return Utils.clearDateInfo(byteArray);
        } else {
            removeFile = true;
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (RAFile != null) {
            try {
                RAFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (removeFile)
            remove(key);
    }
}

From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String path = "";
    Map params = (Map) request.getAttribute(PARAMS);
    String type = (String) params.get(TYPE);
    if (type.equals(DownloadManager.DOWNLOAD_TYPE_KICKSTART)) {
        return getStreamInfoKickstart(mapping, form, request, response, path);
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER)) {
        String url = ConfigDefaults.get().getCobblerServerUrl() + (String) params.get(URL_STRING);
        KickstartHelper helper = new KickstartHelper(request);
        String data = "";
        if (helper.isProxyRequest()) {
            data = KickstartManager.getInstance().renderKickstart(helper.getKickstartHost(), url);
        } else {/*from  w  w w. j a  v  a 2s .  com*/
            data = KickstartManager.getInstance().renderKickstart(url);
        }
        setTextContentInfo(response, data.length());
        return getStreamForText(data.getBytes());
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER_API)) {
        // read data from POST body
        String postData = new String();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            postData += line;
        }

        // Send data
        URL url = new URL(ConfigDefaults.get().getCobblerServerUrl() + "/cobbler_api");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        // this will write POST /download//cobbler_api instead of
        // POST /cobbler_api, but cobbler do not mind
        wr.write(postData, 0, postData.length());
        wr.flush();
        conn.connect();

        // Get the response
        String output = new String();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            output += line;
        }
        wr.close();

        KickstartHelper helper = new KickstartHelper(request);
        if (helper.isProxyRequest()) {
            // Search/replacing all instances of cobbler host with host
            // we pass in, for use with Spacewalk Proxy.
            output = output.replaceAll(ConfigDefaults.get().getCobblerHost(), helper.getForwardedHost());
        }

        setXmlContentInfo(response, output.length());
        return getStreamForXml(output.getBytes());
    } else {
        Long fileId = (Long) params.get(FILEID);
        Long userid = (Long) params.get(USERID);
        User user = UserFactory.lookupById(userid);
        if (type.equals(DownloadManager.DOWNLOAD_TYPE_PACKAGE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            setBinaryContentInfo(response, pack.getPackageSize().intValue());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + pack.getPath();
            return getStreamForBinary(path);
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_SOURCE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            List<PackageSource> src = PackageFactory.lookupPackageSources(pack);
            if (!src.isEmpty()) {
                setBinaryContentInfo(response, src.get(0).getPackageSize().intValue());
                path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + src.get(0).getPath();
                return getStreamForBinary(path);
            }
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_REPO_LOG)) {
            Channel c = ChannelFactory.lookupById(fileId);
            ChannelManager.verifyChannelAdmin(user, fileId);
            StringBuilder output = new StringBuilder();
            for (String fileName : ChannelManager.getLatestSyncLogFiles(c)) {
                RandomAccessFile file = new RandomAccessFile(fileName, "r");
                long fileLength = file.length();
                if (fileLength > DOWNLOAD_REPO_LOG_LENGTH) {
                    file.seek(fileLength - DOWNLOAD_REPO_LOG_LENGTH);
                    // throw away text till end of the actual line
                    file.readLine();
                } else {
                    file.seek(0);
                }
                String line;
                while ((line = file.readLine()) != null) {
                    output.append(line);
                    output.append("\n");
                }
                file.close();
                if (output.length() > DOWNLOAD_REPO_LOG_MIN_LENGTH) {
                    break;
                }
            }

            setTextContentInfo(response, output.length());
            return getStreamForText(output.toString().getBytes());
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_CRASHFILE)) {
            CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(user, fileId);
            String crashPath = crashFile.getCrash().getStoragePath();
            setBinaryContentInfo(response, (int) crashFile.getFilesize());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashPath + "/"
                    + crashFile.getFilename();
            return getStreamForBinary(path);

        }
    }

    throw new UnknownDownloadTypeException(
            "The specified download type " + type + " is not currently supported");

}

From source file:au.org.ala.layers.web.UserDataService.java

private void setImageBlank(HttpServletResponse response) {
    if (blankImageBytes == null && blankImageObject != null) {
        synchronized (blankImageObject) {
            if (blankImageBytes == null) {
                try {
                    RandomAccessFile raf = new RandomAccessFile(
                            UserDataService.class.getResource("/blank.png").getFile(), "r");
                    blankImageBytes = new byte[(int) raf.length()];
                    raf.read(blankImageBytes);
                    raf.close();//from www  . j a  v  a2 s  .co  m
                } catch (IOException e) {
                    logger.error("error reading default blank tile", e);
                }
            }
        }
    }
    if (blankImageObject != null) {
        response.setContentType("image/png");
        try {
            ServletOutputStream outStream = response.getOutputStream();
            outStream.write(blankImageBytes);
            outStream.flush();
            outStream.close();
        } catch (IOException e) {
            logger.error("error outputting blank tile", e);
        }
    }
}

From source file:hudson.FilePathTest.java

private void checkTarUntarRoundTrip(String filePrefix, long fileSize) throws Exception {
    final File tmpDir = temp.newFolder(filePrefix);
    final File tempFile = new File(tmpDir, filePrefix + ".log");
    RandomAccessFile file = new RandomAccessFile(tempFile, "rw");
    final File tarFile = new File(tmpDir, filePrefix + ".tar");

    file.setLength(fileSize);/*from   w ww .  ja  v a 2  s. c o  m*/
    assumeTrue(fileSize == file.length());
    file.close();

    // Compress archive
    final FilePath tmpDirPath = new FilePath(tmpDir);
    int tar = tmpDirPath.tar(new FileOutputStream(tarFile), tempFile.getName());
    assertEquals("One file should have been compressed", 1, tar);

    // Decompress
    FilePath outDir = new FilePath(temp.newFolder(filePrefix + "_out"));
    final FilePath outFile = outDir.child(tempFile.getName());
    tmpDirPath.child(tarFile.getName()).untar(outDir, TarCompression.NONE);
    assertEquals("Result file after the roundtrip differs from the initial file",
            new FilePath(tempFile).digest(), outFile.digest());
}

From source file:org.openmeetings.servlet.outputhandler.ExportToImage.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {//from w ww  . j  ava2s . com
        if (getUserManagement() == null || getSessionManagement() == null || getGenerateImage() == null) {
            return;
        }

        String sid = httpServletRequest.getParameter("sid");
        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        String hash = httpServletRequest.getParameter("hash");
        if (hash == null) {
            hash = "";
        }
        log.debug("hash: " + hash);

        String fileName = httpServletRequest.getParameter("fileName");
        if (fileName == null) {
            fileName = "file_xyz";
        }

        String exportType = httpServletRequest.getParameter("exportType");
        if (exportType == null) {
            exportType = "svg";
        }

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        log.debug("users_id: " + users_id);
        log.debug("user_level: " + user_level);

        if (user_level != null && user_level > 0 && hash != "") {

            PrintBean pBean = PrintService.getPrintItemByHash(hash);

            // Whiteboard Objects
            @SuppressWarnings("rawtypes")
            List whiteBoardMap = pBean.getMap();

            // Get a DOMImplementation.
            DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

            // Create an instance of org.w3c.dom.Document.
            // String svgNS = "http://www.w3.org/2000/svg";
            String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;

            Document document = domImpl.createDocument(svgNS, "svg", null);

            // Get the root element (the 'svg' element).
            Element svgRoot = document.getDocumentElement();

            // Set the width and height attributes on the root 'svg'
            // element.
            svgRoot.setAttributeNS(null, "width", "" + pBean.getWidth());
            svgRoot.setAttributeNS(null, "height", "" + pBean.getHeight());

            log.debug("pBean.getWidth(),pBean.getHeight()" + pBean.getWidth() + "," + pBean.getHeight());

            // Create an instance of the SVG Generator.
            SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

            svgGenerator = WhiteboardMapToSVG.getInstance().convertMapToSVG(svgGenerator, whiteBoardMap);

            // Finally, stream out SVG to the standard output using
            // UTF-8 encoding.
            boolean useCSS = true; // we want to use CSS style attributes
            // Writer out = new OutputStreamWriter(System.out, "UTF-8");

            if (exportType.equals("svg")) {
                // OutputStream out = httpServletResponse.getOutputStream();
                // httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                // httpServletResponse.setHeader("Content-Disposition","attachment; filename=\""
                // + requestedFile + "\"");
                Writer out = httpServletResponse.getWriter();

                svgGenerator.stream(out, useCSS);

            } else if (exportType.equals("png") || exportType.equals("jpg") || exportType.equals("gif")
                    || exportType.equals("tif") || exportType.equals("pdf")) {

                String current_dir = getServletContext().getRealPath("/");
                String working_dir = current_dir + OpenmeetingsVariables.UPLOAD_TEMP_DIR + File.separatorChar;

                String requestedFileSVG = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date())
                        + ".svg";
                String resultFileName = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + "."
                        + exportType;

                log.debug("current_dir: " + current_dir);
                log.debug("working_dir: " + working_dir);
                log.debug("requestedFileSVG: " + requestedFileSVG);
                log.debug("resultFileName: " + resultFileName);

                File svgFile = new File(working_dir + requestedFileSVG);
                File resultFile = new File(working_dir + resultFileName);

                log.debug("svgFile: " + svgFile.getAbsolutePath());
                log.debug("resultFile: " + resultFile.getAbsolutePath());
                log.debug("svgFile P: " + svgFile.getPath());
                log.debug("resultFile P: " + resultFile.getPath());

                FileWriter out = new FileWriter(svgFile);
                svgGenerator.stream(out, useCSS);

                // Get file and handle download
                RandomAccessFile rf = new RandomAccessFile(resultFile.getAbsoluteFile(), "r");

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                OutputStream outStream = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");
                httpServletResponse.setHeader("Content-Disposition",
                        "attachment; filename=\"" + resultFileName + "\"");
                httpServletResponse.setHeader("Content-Length", "" + rf.length());

                byte[] buffer = new byte[1024];
                int readed = -1;

                while ((readed = rf.read(buffer, 0, buffer.length)) > -1) {
                    outStream.write(buffer, 0, readed);
                }
                outStream.close();
                rf.close();

                out.flush();
                out.close();

            }

        }

    } catch (Exception er) {
        log.error("ERROR ", er);
        System.out.println("Error exporting: " + er);
        er.printStackTrace();
    }
}

From source file:net.gleamynode.oil.impl.wal.store.FileLogStore.java

public void open() {
    if (isOpen()) {
        throw new IllegalStateException();
    }/*from   w  w w  .ja  v  a  2  s.co  m*/

    parseProperties();

    try {
        File parentDir = file.getCanonicalFile().getParentFile();

        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
    } catch (IOException e) {
        throw new OilException("failed to get parent directory path.", e);
    }

    RandomAccessFile raf = null;

    if (!useExternalCatalog) {
        catalog = new ClassCatalog(file.getPath() + ".cat");
    }

    boolean done = false;

    try {
        raf = new RandomAccessFile(file, "rw");
        raf.seek(0L);
        reader = new FileLogReader(catalog, raf, new FileInputStream(raf.getFD()), maxItemSize);
        raf = new RandomAccessFile(file, "rw");
        raf.seek(raf.length());
        writer = new FileLogWriter(catalog, new FileOutputStream(raf.getFD()), maxItemSize);

        flusher = new Flusher();
        flusher.start();
        done = true;
    } catch (IOException e) {
        throw new OilException(e);
    } finally {
        if (!done) {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }

                reader = null;
            }

            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                }

                writer = null;
            }

            if (!useExternalCatalog) {
                catalog.close();
            }
        }
    }
}

From source file:org.apache.james.mailrepository.file.MBoxMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#store(Mail)
 *///from   w  w  w  . ja  va2s  . co m
public void store(Mail mc) {

    if ((getLogger().isDebugEnabled())) {
        String logBuffer = this.getClass().getName() + " Will store message to file " + mboxFile;

        getLogger().debug(logBuffer);
    }
    this.mList = null;
    // Now make up the from header
    String fromHeader = null;
    String message = null;
    try {
        message = getRawMessage(mc.getMessage());
        // check for nullsender
        if (mc.getMessage().getFrom() == null) {
            fromHeader = "From   " + dy.format(Calendar.getInstance().getTime());
        } else {
            fromHeader = "From " + mc.getMessage().getFrom()[0] + " "
                    + dy.format(Calendar.getInstance().getTime());
        }

    } catch (IOException e) {
        getLogger().error("Unable to parse mime message for " + mboxFile, e);
    } catch (MessagingException e) {
        getLogger().error("Unable to parse mime message for " + mboxFile, e);
    }
    // And save only the new stuff to disk
    RandomAccessFile saveFile;
    try {
        saveFile = new RandomAccessFile(mboxFile, "rw");
        saveFile.seek(saveFile.length()); // Move to the end
        saveFile.writeBytes((fromHeader + "\n"));
        saveFile.writeBytes((message + "\n"));
        saveFile.close();

    } catch (FileNotFoundException e) {
        getLogger().error("Unable to save(open) file (File not found) " + mboxFile, e);
    } catch (IOException e) {
        getLogger().error("Unable to write file (General I/O problem) " + mboxFile, e);
    }
}