Example usage for java.io RandomAccessFile write

List of usage examples for java.io RandomAccessFile write

Introduction

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

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.

Usage

From source file:org.multibit.file.FileHandler.java

/**
 * Delete a file with an overwrite of all of the data.
 * //from  w w w . j  av  a 2  s .  c o m
 * Set bit patterns are used rather than random numbers to avoid a
 * futex_wait_queue_me error on Linux systems (related to /dev/random usage)
 * 
 * @param file
 * @throws IOException
 */
public static void secureDelete(File file) throws IOException {
    log.debug("Start of secureDelete");

    RandomAccessFile raf = null;
    if (file != null && file.exists()) {
        try {
            // Prep for file delete as this can be fiddly on windows.
            // Make sure it is writable and any references to it are garbage
            // collected and finalized.
            file.setWritable(true);
            System.gc();

            long length = file.length();
            raf = new RandomAccessFile(file, "rws");
            raf.seek(0);
            raf.getFilePointer();
            int pos = 0;
            while (pos < length) {
                raf.write(SECURE_DELETE_FILL_BYTES);
                pos += SECURE_DELETE_FILL_BYTES.length;
            }
        } finally {
            if (raf != null) {
                raf.close();
                raf = null;
            }
        }
        boolean deleteSuccess = file.delete();
        log.debug("Result of delete of file '" + file.getAbsolutePath() + "' was " + deleteSuccess);
    }
    log.debug("End of secureDelete");
}

From source file:org.apache.flume.channel.file.TestFileChannelRestart.java

@Test
public void testCorruptCheckpointCompleteMarkerMostSignificant4Bytes() throws Exception {
    Map<String, String> overrides = Maps.newHashMap();
    channel = createFileChannel(overrides);
    channel.start();//from w ww .  j a  v a  2 s  . co m
    Assert.assertTrue(channel.isOpen());
    Set<String> in = putEvents(channel, "restart", 10, 100);
    Assert.assertEquals(100, in.size());
    forceCheckpoint(channel);
    channel.stop();
    File checkpoint = new File(checkpointDir, "checkpoint");
    RandomAccessFile writer = new RandomAccessFile(checkpoint, "rw");
    writer.seek(EventQueueBackingStoreFile.INDEX_CHECKPOINT_MARKER * Serialization.SIZE_OF_LONG);
    writer.write(new byte[] { (byte) 1, (byte) 5 });
    writer.getFD().sync();
    writer.close();
    channel = createFileChannel(overrides);
    channel.start();
    Assert.assertTrue(channel.isOpen());
    Set<String> out = consumeChannel(channel);
    Assert.assertTrue(channel.didFullReplayDueToBadCheckpointException());
    compareInputAndOut(in, out);
}

From source file:org.kchine.rpf.PoolUtils.java

public static String currentWinProcessID() throws Exception {

    String pslistpath = System.getProperty("java.io.tmpdir") + "/rpf/WinTools/" + "ps.exe";
    System.out.println(pslistpath);
    File pslistFile = new File(pslistpath);
    if (!pslistFile.exists()) {
        pslistFile.getParentFile().mkdirs();
        InputStream is = PoolUtils.class.getResourceAsStream("/wintools/ps.exe");
        RandomAccessFile raf = new RandomAccessFile(pslistFile, "rw");
        raf.setLength(0);/*from   w  w w.  jav a 2  s. com*/
        int b;
        while ((b = is.read()) != -1)
            raf.write((byte) b);
        raf.close();
    }
    String[] command = new String[] { pslistpath };
    Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);
    final StringBuffer psPrint = new StringBuffer();
    final StringBuffer psError = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    psPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    psError.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("ps exit code : " + exitVal);

    BufferedReader reader = new BufferedReader(new StringReader(psPrint.toString()));
    String line;
    int i = 0;
    while (!(line = reader.readLine()).startsWith("PID  PPID  THR PR NAME"))
        ++i;
    ++i;
    while ((line = reader.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(line, " ");
        st.nextElement();
        String PPID = (String) st.nextElement();
        st.nextElement();
        st.nextElement();
        if (line.endsWith("\\ps.exe"))
            return PPID;
        ++i;
    }
    return null;
}

From source file:org.andrewberman.sync.PDFDownloader.java

void retrievePDFsFromHTML() throws Exception {
    if (!baseDir.exists() || !baseDir.canWrite() || !baseDir.isDirectory()) {
        throw new Exception("Error: Destination is read-only or does not exist.");
    }/*from  w  ww  .j a  v  a  2s . c o m*/
    String base = baseDir.getCanonicalPath() + sep;

    syncBibTex();

    do {
        Thread.sleep(InheritMe.BETWEEN_PDF_DOWNLOADS_SLEEP_TIME);
        getArticleInfo();

        /*
         * First thing's first, create folders and insert the URL links if necessary.
         */
        if (subTags) {
            status("Creating folders and links...");
            createTagFoldersAndLinks(tagSet);
            status("Folders and links created!");
            //            Thread.sleep(PAUSE_TIME/10);
        }

        List<CiteULikeReference> articlesWithoutPDFs = this.getArticlesWithoutPDFs(this.refs);
        List<CiteULikeReference> articlesWithPDFs = new ArrayList<CiteULikeReference>();
        articlesWithPDFs.addAll(this.refs);
        articlesWithPDFs.removeAll(articlesWithoutPDFs);

        itemMax = articlesWithPDFs.size();
        itemNum = 0;

        int i = -1;
        for (CiteULikeReference ref : articlesWithPDFs) {
            System.out.println(ref.userfiles);
            itemNum++;
            i++;
            waitOrExit();

            setArticleLink("Current article ID: " + ref.article_id, ref.href);

            try {
                waitOrExit();
                // Grab the article page's text to get the date.
                Date remote = null;
                //               if (this.uploadNewer) {
                String articleContent = get(ref.href);
                remote = getStampFromArticlePage(articleContent);
                System.out.println("Remote timestamp: " + remote);
                //               }

                status("Checking for existing file...");

                for (String fileName : ref.userfiles.keySet()) {
                    waitOrExit();
                    String fullPath = ref.userfiles.get(fileName);
                    System.out.println(fileName + " -> " + fullPath);

                    /*
                     * Try and put the year first.
                     */
                    String[] bits = fileName.split("_");
                    String yearS = "";
                    String otherFilename = "";
                    String targetFilename = "";
                    if (bits.length == 3) {
                        String flipped = bits[1] + "_" + bits[0] + "_" + bits[2];
                        if (flipFilename) {
                            otherFilename = fileName;
                            targetFilename = flipped;
                        } else {
                            targetFilename = fileName;
                            otherFilename = flipped;
                        }
                        if (subYears) {
                            yearS = String.valueOf(bits[1]);
                        }
                    } else {
                        targetFilename = fileName;
                        otherFilename = fileName;
                    }

                    /*
                     * If we're organized by tags, add a destination file for each of this PDf's tags.
                     * If not, then just add the one outputFile to the outputFiles array. 
                     */
                    ArrayList<File> outputFiles = new ArrayList<File>();
                    ArrayList<File> maybeNewFiles = new ArrayList<File>();
                    File altFile = null;
                    File myFile = null;

                    // Keep track of the newest file and its timestamp.
                    File newestFile = null;
                    long newestStamp = 0;

                    if (subTags && ref.getTags().size() > 0) {
                        for (String tag : ref.getTags()) {
                            if (tag.equalsIgnoreCase("no-tag"))
                                tag = "";
                            String curDir = base + tag + sep;
                            curDir += yearS;
                            myFile = new File(curDir + sep + targetFilename);
                            altFile = new File(curDir + sep + otherFilename);
                            if (myFile.exists()) {
                                newestFile = returnNewer(newestFile, myFile);
                            } else if (altFile.exists()) {
                                try {
                                    altFile.renameTo(myFile);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                //                        outputFiles.add(myFile);
                            } else {
                                outputFiles.add(myFile);
                            }
                        }
                    } else {
                        myFile = new File(base + yearS + sep + targetFilename);
                        altFile = new File(base + yearS + sep + otherFilename);
                        maybeNewFiles.add(myFile);
                        maybeNewFiles.add(altFile);
                        if (myFile.exists()) {
                            newestFile = returnNewer(newestFile, myFile);
                        } else if (altFile.exists()) {
                            try {
                                altFile.renameTo(myFile);
                            } catch (Exception e) {
                                e.printStackTrace();
                                System.exit(0);
                            }
                            //                     outputFiles.add(myFile);
                        } else {
                            outputFiles.add(myFile);
                        }
                    }

                    // If we have a newest file, check against the server to see if it's much newer.
                    if (newestFile != null && remote != null) {
                        Date local = new Date(newestFile.lastModified());
                        long lT = local.getTime();
                        long rT = remote.getTime();
                        if (lT - rT > (1000) * (60) * (1)) // Fudge factor of 1 minute.
                        {
                            if (uploadNewer) {
                                System.err.println("Local file is newer than remote! Uploading...");
                                status("Local file was modified! Uploading...");

                                // OK. Since CiteULike now uses hashing to evaluate the identity of files, we have to first delete
                                // the existing attachment with this filename.
                                String url = this.BASE_URL + "personal_pdf_delete?";
                                url += "username=" + this.username;
                                url += "&article_id=" + ref.article_id;

                                // Parse the userfile_id from the filename:
                                String userFileId = ref.userfileIds.get(fileName);
                                url += "&userfile_id=" + userFileId;
                                System.out.println(url);
                                get(url);

                                uploadPDF(ref.article_id, newestFile);

                                // Re-collect the timestamp, and re-stamp the local file. This is done so they match after re-uploading.
                                String newContent = get(ref.href);
                                Date remote2 = getStampFromArticlePage(newContent);
                                newestFile.setLastModified(remote2.getTime());
                            }
                        }
                    }
                    if (outputFiles.size() == 0) {
                        status("Already up-to-date!");
                        utd++;
                        continue;
                    }

                    Thread.sleep(200);
                    /*
                     * Download the PDF to the first file.
                     */
                    waitOrExit();
                    status("Downloading...");
                    File f = outputFiles.remove(0);

                    try {
                        String fileUrl = this.BASE_URL + fullPath;
                        this.retriesLeft = 2;
                        downloadURLToFile(fileUrl, f);
                        if (remote != null)
                            f.setLastModified(remote.getTime());
                    } catch (Exception e) {
                        e.printStackTrace();
                        f.delete();
                        throw e;
                    }
                    dl++;

                    /*
                     * Go through rest of tags, and copy file accordingly.
                     * NOTE: This is only entered if this file needs to be copied over locally.
                     */
                    for (int j = 0; j < outputFiles.size(); j++) {
                        status("Copying PDF...");
                        File f2 = outputFiles.get(j);
                        if (f2.exists()) {
                            if (f2.lastModified() > newestStamp) {
                                newestFile = f2;
                                newestStamp = f2.lastModified();
                            }
                            continue;
                        }
                        f2.getParentFile().mkdirs();
                        f2.createNewFile();
                        RandomAccessFile in = new RandomAccessFile(f, "r");
                        RandomAccessFile out = new RandomAccessFile(f2, "rw");

                        byte[] b = new byte[(int) in.length()];
                        in.readFully(b);
                        out.write(b);

                        in.close();
                        out.close();

                        f2.setLastModified(remote.getTime());
                    }
                }
            } catch (Exception e) {
                err++;
                e.printStackTrace();
                status("Failed. See the Java console for more info.");
                Thread.sleep(PAUSE_TIME / 2);
                continue;
            }
        }
    } while (this.refs.size() > 0);
    this.pageNum = 0;
    status("Finished. " + dl + " new, " + utd + " up-to-date and " + err + " failed.");
    out.println("Done!");
}

From source file:com.yifanlu.PSXperiaTool.PSXperiaTool.java

private void patchGame() throws IOException {
    /*/*ww  w . jav a 2s.  c  o  m*/
     * Custom patch format (config/game-patch.bin) is as follows:
     * 0x8 byte little endian: Address in game image to start patching
     * 0x8 byte little endian: Length of patch
     * If there are more patches, repeat after reading the length of patch
     * Note that all games will be patched the same way, so if a game is broken before patching, it will still be broken!
     */
    nextStep("Patching game.");
    File gamePatch = new File(mTempDir, "/config/game-patch.bin");
    if (!gamePatch.exists())
        return;
    Logger.info("Making a copy of game.");
    File tempGame = new File(mTempDir, "game.iso");
    FileUtils.copyFile(mInputFile, tempGame);
    RandomAccessFile game = new RandomAccessFile(tempGame, "rw");
    InputStream patch = new FileInputStream(gamePatch);
    while (true) {
        byte[] rawPatchAddr = new byte[8];
        byte[] rawPatchLen = new byte[8];
        if (patch.read(rawPatchAddr) + patch.read(rawPatchLen) < rawPatchAddr.length + rawPatchLen.length)
            break;
        ByteBuffer bb = ByteBuffer.wrap(rawPatchAddr);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        long patchAddr = bb.getLong();
        bb = ByteBuffer.wrap(rawPatchLen);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        long patchLen = bb.getLong();

        game.seek(patchAddr);
        while (patchLen-- > 0) {
            game.write(patch.read());
        }
    }
    mInputFile = tempGame;
    game.close();
    patch.close();
    Logger.debug("Done patching game.");
}

From source file:com.teletalk.jserver.util.filedb.LowLevelFileDBTest.java

/**
 * testCorruptData/*from   w  w w. ja  v a  2 s. c o m*/
 */
public void testCorruptData() {
    logger.info("BEGIN testCorruptData.");

    String fileNameBase = BASE_PATH + "fileDBCorrupt/fileDBCorrupt";
    new File(fileNameBase).mkdirs();

    try {
        new File(fileNameBase + ".idx").delete();
        new File(fileNameBase + ".dat").delete();

        final int allocationUnitSize = 10;
        final int blockSize = (allocationUnitSize + DefaultDataFile.BLOCK_HEADER_SIZE
                + DefaultDataFile.BLOCK_FOOTER_SIZE);

        LowLevelFileDB lowLevelFileDB = new LowLevelFileDB("LowLevelFileDB", fileNameBase, blockSize, 2, 2,
                LowLevelFileDB.READ_WRITE_MODE);

        String dataString = "DATA123456";
        byte[] data = dataString.getBytes();
        lowLevelFileDB.insertItem("key1", data);
        lowLevelFileDB.insertItem("key2", data);
        lowLevelFileDB.insertItem("key3", data);

        lowLevelFileDB.closeFileDB();

        byte[] corruptHeader = new byte[DefaultDataFile.BLOCK_HEADER_SIZE];

        // Destroy header of first data block
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileNameBase + ".dat", "rw");
        randomAccessFile.seek(DefaultDataFile.DATA_FILE_HEADER_SIZE);
        randomAccessFile.write(corruptHeader);
        randomAccessFile.close();

        // Destroy header of second index block
        randomAccessFile = new RandomAccessFile(fileNameBase + ".idx", "rw");
        randomAccessFile.seek(DefaultDataFile.DATA_FILE_HEADER_SIZE + lowLevelFileDB.getIndexFileBlockSize());
        randomAccessFile.write(corruptHeader);
        randomAccessFile.close();

        // Reopen
        lowLevelFileDB = new LowLevelFileDB("LowLevelFileDB", fileNameBase, 20, 2, 2,
                LowLevelFileDB.READ_WRITE_MODE);

        byte[] readData = lowLevelFileDB.getItem("key1");
        if (readData != null)
            super.fail("Item with key 'key1' shouldn't exist!");
        readData = lowLevelFileDB.getItem("key2");
        if (readData != null)
            super.fail("Item with key 'key2' shouldn't exist!");
        readData = lowLevelFileDB.getItem("key3");
        if (readData == null)
            super.fail("Item with key 'key3' wasn't found!");
        if (!dataString.equals(new String(readData)))
            super.fail("Data for item with key 'key3' was invalid!");

        lowLevelFileDB.closeFileDB();

        FileDeletor.delete("fileDBCorrupt");
        new File(fileNameBase + ".idx").delete();
        new File(fileNameBase + ".dat").delete();
    } catch (Exception e) {
        e.printStackTrace();
        super.fail("Error - " + e);
    }

    logger.info("END testCorruptData.");
}

From source file:org.kchine.r.server.manager.ServerManager.java

synchronized public static RServices createRInternal(String RBinPath, boolean forceEmbedded, boolean keepAlive,
        String codeServerHostIp, int codeServerPort, Properties namingInfo, int memoryMinMegabytes,
        int memoryMaxMegabytes, String name, final boolean showProgress, URL[] codeUrls, String logFile,
        String applicationType, final Runnable rShutdownHook, String forcedIP, String mainClassName,
        boolean useCreationCallback) throws Exception {

    final JTextArea[] createRProgressArea = new JTextArea[1];
    final JProgressBar[] createRProgressBar = new JProgressBar[1];
    final JFrame[] createRProgressFrame = new JFrame[1];
    ProgessLoggerInterface progressLogger = new ProgessLoggerInterface() {
        public void logProgress(String message) {

            System.out.println(">>" + message);
            try {
                if (showProgress) {
                    createRProgressArea[0].setText(message);
                }/*from  www  .  j a  v a  2  s.  c  o  m*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    if (showProgress) {
        createRProgressArea[0] = new JTextArea();
        createRProgressBar[0] = new JProgressBar(0, 100);
        createRProgressFrame[0] = new JFrame("Creating R Server on Local Host");

        Runnable runnable = new Runnable() {
            public void run() {

                createRProgressFrame[0].setUndecorated(true);

                JPanel p = new JPanel(new BorderLayout());
                createRProgressArea[0].setForeground(Color.white);
                createRProgressArea[0].setBackground(new Color(0x00, 0x80, 0x80));
                createRProgressArea[0]
                        .setBorder(BorderFactory.createLineBorder(new Color(0x00, 0x80, 0x80), 3));
                createRProgressArea[0].setEditable(false);
                p.setBorder(BorderFactory.createLineBorder(Color.black, 3));

                createRProgressBar[0].setForeground(Color.white);
                createRProgressBar[0].setBackground(new Color(0x00, 0x80, 0x80));
                createRProgressBar[0].setIndeterminate(true);

                p.setBackground(new Color(0x00, 0x80, 0x80));
                p.add(createRProgressBar[0], BorderLayout.SOUTH);
                p.add(createRProgressArea[0], BorderLayout.CENTER);
                createRProgressFrame[0].add(p);

                createRProgressFrame[0].pack();
                createRProgressFrame[0].setSize(600, 64);
                createRProgressFrame[0].setVisible(true);
                createRProgressFrame[0].setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

                PoolUtils.locateInScreenCenter(createRProgressFrame[0]);
            }
        };
        if (SwingUtilities.isEventDispatchThread())
            runnable.run();
        else {
            SwingUtilities.invokeLater(runnable);
        }
    }

    boolean useClassPath = (codeUrls == null || codeUrls.length == 0)
            && (applicationType == null || applicationType.equals("") || applicationType.equals("standard"));
    System.out.println("application type : " + applicationType);
    System.out.println("!! use class path : " + useClassPath);
    System.out.println("java.class.path : " + System.getProperty("java.class.path"));

    try {

        progressLogger.logProgress("Inspecting R installation..");
        new File(INSTALL_DIR).mkdir();

        String rpath = null;
        String rversion = null;
        String userrjavapath = null;
        String[] rinfo = null;

        if (RBinPath != null && !RBinPath.equals("")) {
            rinfo = getRInfo(RBinPath);
            if (rinfo == null) {
                throw new ServantCreationFailed();
            }
            rpath = rinfo[0];
            rversion = rinfo[1];
            userrjavapath = rinfo[2];
        } else if (new File(INSTALL_DIR + "R/" + EMBEDDED_R).exists()) {

            rinfo = getRInfo(INSTALL_DIR + "R/" + EMBEDDED_R + "/bin/R.exe");
            if (rinfo == null) {
                throw new ServantCreationFailed();
            }
            rpath = rinfo[0];
            rversion = rinfo[1];
            userrjavapath = rinfo[2];

            System.setProperty("use.default.libs", "true");

        } else if (!forceEmbedded) {

            String rhome = System.getenv("R_HOME");
            if (rhome == null) {
                rinfo = getRInfo(null);
            } else {
                if (!rhome.endsWith("/")) {
                    rhome = rhome + "/";
                }
                System.out.println("R_HOME is set to :" + rhome);
                rinfo = getRInfo(rhome + "bin/R");
            }

            System.out.println("+rinfo:" + rinfo + " " + Arrays.toString(rinfo));
            rpath = rinfo != null ? rinfo[0] : null;
            rversion = (rinfo != null ? rinfo[1] : "");
            userrjavapath = (rinfo != null ? rinfo[2] : "");
        }

        System.out.println("rpath:" + rpath);
        System.out.println("rversion:" + rversion);
        System.out.println("user rjava path:" + userrjavapath);
        if (rpath == null) {

            String noRCause = System.getenv("R_HOME") == null ? "R is not accessible from the command line"
                    : "Your R_HOME is invalid";
            if (isWindowsOs()) {

                int n;
                if (forceEmbedded) {
                    n = JOptionPane.OK_OPTION;
                } else {
                    n = JOptionPane.showConfirmDialog(null,
                            noRCause + "\nWould you like to use the Embedded R?", "",
                            JOptionPane.YES_NO_OPTION);
                }
                if (n == JOptionPane.OK_OPTION) {
                    String rZipFileName = null;
                    rZipFileName = "http://biocep-distrib.r-forge.r-project.org/r/" + EMBEDDED_R + ".zip";
                    URL rUrl = new URL(rZipFileName);
                    InputStream is = rUrl.openConnection().getInputStream();
                    unzip(is, INSTALL_DIR + "R/", null, BUFFER_SIZE, true, "Unzipping R..", ENTRIES_NUMBER);

                    rinfo = getRInfo(INSTALL_DIR + "R/" + EMBEDDED_R + "/bin/R.exe");
                    if (rinfo == null) {
                        throw new ServantCreationFailed();
                    }
                    rpath = rinfo[0];
                    rversion = rinfo[1];
                    userrjavapath = rinfo[2];
                    System.setProperty("use.default.libs", "true");

                } else {
                    JOptionPane.showMessageDialog(null,
                            "please add R to your System path or set R_HOME to the root Directory of your local R installation\n");
                    throw new ServantCreationFailed();
                }

            } else {
                if (showProgress) {
                    JOptionPane.showMessageDialog(null, noRCause
                            + "\nplease add R to your System path \nor set R_HOME to the root Directory of your local R installation\n");
                } else {
                    System.out.println(noRCause
                            + "\n please add R to your System path \nor set R_HOME to the root Directory of your local R installation");
                }
                throw new ServantCreationFailed();
            }

        }

        progressLogger.logProgress("R installation inspection done.");

        boolean useDefaultUserLibs = (System.getenv("BIOCEP_USE_DEFAULT_LIBS") != null
                && System.getenv("BIOCEP_USE_DEFAULT_LIBS").equalsIgnoreCase("false"))
                || (System.getProperty("use.default.libs") != null
                        && System.getProperty("use.default.libs").equalsIgnoreCase("true"));

        if (System.getProperty("use.default.libs") == null
                || System.getProperty("use.default.libs").equals("")) {
            System.setProperty("use.default.libs", new Boolean(useDefaultUserLibs).toString().toLowerCase());
        }

        if (!rpath.endsWith("/") && !rpath.endsWith("\\"))
            rpath += "/";

        String rlibs = (INSTALL_DIR + "library/"
                + rversion.substring(0, rversion.lastIndexOf(' ')).replace(' ', '-')).replace('\\', '/');
        new File(rlibs).mkdirs();

        Vector<String> envVector = new Vector<String>();
        {
            Map<String, String> osenv = System.getenv();
            String OS_PATH = osenv.get("PATH");
            if (OS_PATH == null)
                OS_PATH = osenv.get("Path");
            if (OS_PATH == null)
                OS_PATH = "";

            Map<String, String> env = new HashMap<String, String>(osenv);

            env.put("Path",
                    rpath + (isWindowsOs() ? "bin" : "lib") + System.getProperty("path.separator") + OS_PATH);
            if (sci != null && isWindowsOs()) {
                env.put("Path", sci_dll_path + System.getProperty("path.separator") + env.get("Path"));
            }

            env.put("LD_LIBRARY_PATH", rpath + (isWindowsOs() ? "bin" : "lib"));
            if (sci != null) {
                env.put("SCI", sci);
                env.put("SCIHOME", sci);
                env.put("SCI_DISABLE_TK", "1");
                env.put("SCI_JAVA_ENABLE_HEADLESS", "1");

                if (!isWindowsOs()) {
                    env.put("LD_LIBRARY_PATH",
                            sci_dll_path + System.getProperty("path.separator") + env.get("LD_LIBRARY_PATH"));
                }
            }

            env.put("R_HOME", rpath);

            String R_LIBS = null;
            if (useDefaultUserLibs) {
                R_LIBS = (System.getenv("R_LIBS") != null ? System.getenv("R_LIBS") : "");
            } else {
                R_LIBS = rlibs + System.getProperty("path.separator")
                        + (System.getenv("R_LIBS") != null ? System.getenv("R_LIBS") : "");
            }

            System.out.println("R_LIBS:" + R_LIBS);
            env.put("R_LIBS", R_LIBS);

            if (System.getenv("JDK_HOME") != null)
                env.put("JAVA_HOME", System.getenv("JDK_HOME"));

            for (String k : env.keySet()) {
                envVector.add(k + "=" + env.get(k));
            }
            System.out.println("envVector:" + envVector);
        }

        String[] requiredPackages = null;
        if (useDefaultUserLibs) {
            requiredPackages = new String[0];
        } else {
            if (isWindowsOs()) {
                requiredPackages = new String[] { "rJava", "JavaGD", "iplots", "TypeInfo", "Cairo" };
            } else {
                requiredPackages = new String[] { "rJava", "JavaGD", "iplots", "TypeInfo" };
            }
        }

        Vector<String> installLibBatch = new Vector<String>();
        installLibBatch.add("source('http://bioconductor.org/biocLite.R')");

        Vector<String> missingPackages = new Vector<String>();
        for (int i = 0; i < requiredPackages.length; ++i) {
            if (!new File(rlibs + "/" + requiredPackages[i]).exists()) {
                installLibBatch.add("biocLite('" + requiredPackages[i] + "',lib='" + rlibs + "')");
                missingPackages.add(requiredPackages[i]);
            }
        }

        progressLogger.logProgress("Installing missing packages " + missingPackages + "..\n"
                + "This doesn't alter your R installation and may take several minutes. It will be done only once");

        if (installLibBatch.size() > 1) {

            File installPackagesFile = new File(INSTALL_DIR + "installRequiredPackages.R");
            File installPackagesOutputFile = new File(INSTALL_DIR + "installRequiredPackages.Rout");

            FileWriter fw = new FileWriter(installPackagesFile);
            PrintWriter pw = new PrintWriter(fw);
            for (int i = 0; i < installLibBatch.size(); ++i) {
                pw.println(installLibBatch.elementAt(i));
            }
            fw.close();

            Vector<String> installCommand = new Vector<String>();
            installCommand.add(rpath + "bin/R");
            installCommand.add("CMD");
            installCommand.add("BATCH");
            installCommand.add("--no-save");
            installCommand.add(installPackagesFile.getAbsolutePath());
            installCommand.add(installPackagesOutputFile.getAbsolutePath());

            System.out.println(installCommand);

            final Process installProc = Runtime.getRuntime().exec(installCommand.toArray(new String[0]),
                    envVector.toArray(new String[0]));
            final Vector<String> installPrint = new Vector<String>();
            final Vector<String> installErrorPrint = new Vector<String>();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(installProc.getErrorStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            installErrorPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(installProc.getInputStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            installPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            installProc.waitFor();

            if (installPackagesOutputFile.exists()
                    && installPackagesOutputFile.lastModified() > installPackagesFile.lastModified()) {
                BufferedReader br = new BufferedReader(new FileReader(installPackagesOutputFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }

            Vector<String> missingLibs = new Vector<String>();

            for (int i = 0; i < requiredPackages.length; ++i) {
                if (!new File(rlibs + "/" + requiredPackages[i]).exists()) {
                    missingLibs.add(requiredPackages[i]);
                }
                /*
                 * if (getLibraryPath(requiredPackages[i], rpath, rlibs) ==
                 * null) { missingLibs.add(requiredPackages[i]); }
                 */
            }

            if (missingLibs.size() > 0) {
                System.out.println(
                        "The following packages probably couldn't be automatically installed\n" + missingLibs);
                throw new ServantCreationFailed();
            }

        }

        progressLogger.logProgress("All Required Packages Are Installed.");

        progressLogger.logProgress("Generating Bootstrap Classes..");

        String bootstrap = (INSTALL_DIR + "classes/org/kchine/r/server/manager/bootstrap").replace('\\', '/');
        System.out.println(bootstrap);
        if (!new File(bootstrap).exists())
            new File(bootstrap).mkdirs();
        InputStream is = ServerManager.class
                .getResourceAsStream("/org/kchine/r/server/manager/bootstrap/Boot.class");
        byte[] buffer = new byte[is.available()];
        try {
            for (int i = 0; i < buffer.length; ++i) {
                int b = is.read();
                buffer[i] = (byte) b;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RandomAccessFile raf = new RandomAccessFile(bootstrap + "/Boot.class", "rw");
        raf.setLength(0);
        raf.write(buffer);
        raf.close();
        progressLogger.logProgress("Bootstrap Classes Generated.");

        // ---------------------------------------

        if (!isWindowsOs() && !new File(INSTALL_DIR + "VRWorkbench.sh").exists()) {
            try {

                progressLogger.logProgress("Generating Launcher Batch..");

                String launcherFile = INSTALL_DIR + "VRWorkbench.sh";
                FileWriter fw = new FileWriter(launcherFile);
                PrintWriter pw = new PrintWriter(fw);
                pw.println("javaws http://biocep-distrib.r-forge.r-project.org/rworkbench.jnlp");
                fw.close();

                progressLogger.logProgress("Launcher Batch generated..");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // ---------------------------------------

        // String jripath = getLibraryPath("rJava", rpath, rlibs) + "jri/";
        String java_library_path = null;
        if (useDefaultUserLibs) {
            java_library_path = userrjavapath + "/jri/";
            System.out.println("jripath:" + java_library_path + "\n");
        } else {
            java_library_path = rlibs + "/rJava/jri/";
            System.out.println("jripath:" + java_library_path + "\n");
        }

        if (sci != null) {
            java_library_path += System.getProperty("path.separator") + sci_dll_path;
        }

        System.out.println("java.library.path" + java_library_path);

        String cp = null;
        if (useClassPath) {
            cp = PoolUtils.getAbsoluteClassPath();
        } else {
            cp = INSTALL_DIR + "classes";
        }

        if (sci != null) {
            if (isWindowsOs()) {
                cp = cp + System.getProperty("path.separator") + sci + "modules/javasci/jar/javasci.jar";
            } else {
                String scilabLibraryDir = INSTALL_DIR + "scilab/javasci/" + SCILAB_VERSION + "/";
                if (new File(scilabLibraryDir).exists())
                    new File(scilabLibraryDir).mkdirs();
                try {
                    PoolUtils.cacheJar(
                            new URL("http://www.biocep.net/scilab/" + SCILAB_VERSION + "/" + "javasci.jar"),
                            scilabLibraryDir, PoolUtils.LOG_PRGRESS_TO_SYSTEM_OUT, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                cp = cp + System.getProperty("path.separator") + scilabLibraryDir + "javasci.jar";
            }

        }

        Vector<File> extraJarFiles = new Vector<File>();

        try {

            File[] flist = new File(INSTALL_DIR).listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".jar");
                }
            });
            Arrays.sort(flist);
            for (int i = 0; i < flist.length; ++i) {
                extraJarFiles.add(flist[i]);
            }

            System.out.println("Insiders Extra Jars:" + Arrays.toString(flist));

            if (System.getenv().get("BIOCEP_EXTRA_JARS_LOCATION") != null) {
                flist = new File(System.getenv().get("BIOCEP_EXTRA_JARS_LOCATION"))
                        .listFiles(new FilenameFilter() {
                            public boolean accept(File dir, String name) {
                                return name.endsWith(".jar");
                            }
                        });

                Arrays.sort(flist);
                System.out.println("Outsiders Extra Jars:" + Arrays.toString(flist));
                for (int i = 0; i < flist.length; ++i) {
                    extraJarFiles.add(flist[i]);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        ManagedServant[] servantHolder = new ManagedServant[1];
        RemoteException[] exceptionHolder = new RemoteException[1];

        CreationCallBack callBack = null;
        String listenerStub = null;

        progressLogger.logProgress("Creating R Server..");

        try {

            if (useCreationCallback) {
                callBack = new CreationCallBack(servantHolder, exceptionHolder);
                listenerStub = PoolUtils.stubToHex(callBack);
            }

            String uid = null;

            if (name != null && !name.equals("") && name.contains("%{uid}")) {
                if (uid == null)
                    uid = UUID.randomUUID().toString();
                name = PoolUtils.replaceAll(name, "%{uid}", uid);
            }

            if (logFile != null && !logFile.equals("") && logFile.contains("%{uid}")) {
                if (uid == null)
                    uid = UUID.randomUUID().toString();
                logFile = PoolUtils.replaceAll(logFile, "%{uid}", uid);
            }

            Vector<String> command = new Vector<String>();

            command.add((isWindowsOs() ? "\"" : "") + System.getProperty("java.home") + "/bin/java"
                    + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-DXms" + memoryMinMegabytes + "m"
                    + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-DXmx" + memoryMaxMegabytes + "m"
                    + (isWindowsOs() ? "\"" : ""));

            command.add("-cp");
            command.add((isWindowsOs() ? "\"" : "") + cp + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-Djava.library.path=" + java_library_path
                    + (isWindowsOs() ? "\"" : ""));

            String codeBase = "http://" + codeServerHostIp + ":" + codeServerPort + "/classes/";

            if (codeUrls != null && codeUrls.length > 0) {
                for (int i = 0; i < codeUrls.length; ++i)
                    codeBase += " " + codeUrls[i].toString();
            }

            if (extraJarFiles.size() > 0) {
                for (int i = 0; i < extraJarFiles.size(); ++i)
                    codeBase += " " + extraJarFiles.elementAt(i).toURI().toURL().toString();
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Djava.rmi.server.codebase=" + codeBase
                    + (isWindowsOs() ? "\"" : ""));
            if (keepAlive) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dpreloadall=true" + (isWindowsOs() ? "\"" : ""));
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dservantclass=server.RServantImpl"
                    + (isWindowsOs() ? "\"" : ""));

            if (name == null || name.equals("")) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dprivate=true" + (isWindowsOs() ? "\"" : ""));
            } else {
                command.add((isWindowsOs() ? "\"" : "") + "-Dname=" + name + (isWindowsOs() ? "\"" : ""));
            }

            if (useCreationCallback) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dlistener.stub=" + listenerStub
                        + (isWindowsOs() ? "\"" : ""));
            }

            if (forcedIP != null && !forcedIP.equals("")) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dhost.ip.forced=" + forcedIP
                        + (isWindowsOs() ? "\"" : ""));
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dapply.sandbox=false" + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dworking.dir.root=" + INSTALL_DIR + "wdir"
                    + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-Dkeepalive=" + keepAlive + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dcode.server.host=" + codeServerHostIp
                    + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dcode.server.port=" + codeServerPort
                    + (isWindowsOs() ? "\"" : ""));

            for (int i = 0; i < namingVars.length; ++i) {
                String var = namingVars[i];
                if (namingInfo.getProperty(var) != null && !namingInfo.getProperty(var).equals("")) {
                    command.add((isWindowsOs() ? "\"" : "") + "-D" + var + "=" + namingInfo.get(var)
                            + (isWindowsOs() ? "\"" : ""));
                }
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dapplication_type="
                    + (applicationType == null ? "" : applicationType) + (isWindowsOs() ? "\"" : ""));

            if (logFile != null && !logFile.equals("")) {
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.rootCategory=DEBUG,A1,A2,A3"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A1=org.apache.log4j.ConsoleAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A1.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A1.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A2=org.kchine.rpf.RemoteAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A2.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A2.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A3=org.apache.log4j.FileAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A3.file=" + logFile
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A3.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A3.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));
            }

            if (useClassPath) {
                command.add(mainClassName);
            } else {
                command.add("org.kchine.r.server.manager.bootstrap.Boot");
            }

            command.add("http://" + codeServerHostIp + ":" + codeServerPort + "/classes/");

            if (codeUrls != null && codeUrls.length > 0) {
                for (int i = 0; i < codeUrls.length; ++i) {
                    command.add(codeUrls[i].toString());
                }
            }

            if (extraJarFiles.size() > 0) {
                for (int i = 0; i < extraJarFiles.size(); ++i)
                    command.add(extraJarFiles.elementAt(i).toURI().toURL().toString());
            }

            final Process proc = Runtime.getRuntime().exec(command.toArray(new String[0]),
                    envVector.toArray(new String[0]));
            if (rShutdownHook != null) {
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            proc.waitFor();
                            rShutdownHook.run();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

            final Vector<String> outPrint = new Vector<String>();
            final Vector<String> errorPrint = new Vector<String>();

            System.out.println(" command : " + command);

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            errorPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    System.out.println();
                }
            }).start();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            outPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            if (useCreationCallback) {
                long t1 = System.currentTimeMillis();
                while (servantHolder[0] == null && exceptionHolder[0] == null) {
                    if (System.currentTimeMillis() - t1 >= SERVANT_CREATION_TIMEOUT_MILLISEC)
                        throw new ServantCreationTimeout();
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                }
                if (exceptionHolder[0] != null) {
                    throw exceptionHolder[0];
                }
                progressLogger.logProgress("R Server Created.");
                return (RServices) servantHolder[0];
            } else {
                return null;
            }

        } finally {
            if (callBack != null) {
                UnicastRemoteObject.unexportObject(callBack, true);
            }
        }
    } finally {
        if (showProgress) {
            createRProgressFrame[0].dispose();
        }
    }
}

From source file:com.example.android.vault.EncryptedDocument.java

/**
 * Encrypt and write the given stream as a full section. Writes section
 * header and encrypted data starting at the current file offset. When
 * finished, file offset is at the end of the entire section.
 *///from w  w  w .  jav  a 2s . co m
private int writeSection(RandomAccessFile f, InputStream in) throws IOException, GeneralSecurityException {
    final long start = f.getFilePointer();

    // Write header; we'll come back later to finalize details
    final Section section = new Section();
    section.write(f);

    final long dataStart = f.getFilePointer();

    mRandom.nextBytes(section.iv);

    final IvParameterSpec ivSpec = new IvParameterSpec(section.iv);
    mCipher.init(Cipher.ENCRYPT_MODE, mDataKey, ivSpec);
    mMac.init(mMacKey);

    int plainLength = 0;
    byte[] inbuf = new byte[8192];
    byte[] outbuf;
    int n;
    while ((n = in.read(inbuf)) != -1) {
        plainLength += n;
        outbuf = mCipher.update(inbuf, 0, n);
        if (outbuf != null) {
            mMac.update(outbuf);
            f.write(outbuf);
        }
    }

    outbuf = mCipher.doFinal();
    if (outbuf != null) {
        mMac.update(outbuf);
        f.write(outbuf);
    }

    section.setMac(mMac.doFinal());

    final long dataEnd = f.getFilePointer();
    section.length = dataEnd - dataStart;

    // Rewind and update header
    f.seek(start);
    section.write(f);
    f.seek(dataEnd);

    return plainLength;
}

From source file:net.sf.ehcache.DiskStoreTest.java

/**
 * Tests how data is written to a random access file.
 * <p/>// w w  w .  j  av  a2 s.  com
 * It makes sure that bytes are immediately written to disk after a write.
 */
public void testWriteToFile() throws IOException {
    // Create and set up file
    String dataFileName = "fileTest";
    RandomAccessFile file = getRandomAccessFile(dataFileName);

    //write data to the file
    byte[] buffer = new byte[1024];
    for (int i = 0; i < 100; i++) {
        file.write(buffer);
    }

    assertEquals(1024 * 100, file.length());

}

From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java

/**
 * Obtains a file lock on the repository lock file.
 *//*w w  w  .  j a va 2  s. co m*/
protected RepositoryFileLock obtainRepositoryFileLock(final boolean shared, final int timeout)
        throws IOException {
    Log logger = this.getLog();

    if (logger.isDebugEnabled())
        logger.debug("Obtaining repository file lock (shared: " + shared + ").");

    RepositoryFileLock repositoryFileLock = null;
    FileLock lock = null;
    final long beginWait = System.currentTimeMillis();

    while (repositoryFileLock == null) {
        try {
            RandomAccessFile lockFile = new RandomAccessFile(
                    new File(moduleRepositoryDirectory, LOCK_FILE_NAME), "rws");
            FileChannel channel = lockFile.getChannel();

            // Attempt to obtain a lock on the file
            lock = channel.tryLock(0L, Long.MAX_VALUE, shared);
            if (!shared && (lockFile.length() == 0)) {
                lockFile.write(new String("LOCK").getBytes());
                lockFile.getFD().sync();
            }
            repositoryFileLock = new RepositoryFileLock(lockFile, lock);
        } catch (IOException ioe) {
            if (logger.isDebugEnabled())
                logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ioe);
            if (timeout < 0)
                throw ioe;
        } catch (OverlappingFileLockException ofle) {
            if (logger.isDebugEnabled())
                logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ofle);
            if (timeout < 0)
                throw ofle;
        }

        if (repositoryFileLock == null) // This statement shouldn't be reaced if timeout is < 0
        {
            if ((System.currentTimeMillis() - beginWait) > timeout) // Wait a maximum of timeout milliseconds on lock
            {
                throw new IOException("Timeout while waiting for file lock on repository lock file!");
            } else {
                // Otherwise - wait a while before trying to obtain a lock again
                try {
                    Thread.sleep(Math.min(250, timeout - (System.currentTimeMillis() - beginWait)));
                } catch (InterruptedException ie) {
                }
            }
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("Repository file lock (shared: " + shared + ") obtained.");

    return repositoryFileLock;
}