Example usage for java.io RandomAccessFile setLength

List of usage examples for java.io RandomAccessFile setLength

Introduction

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

Prototype

public native void setLength(long newLength) throws IOException;

Source Link

Document

Sets the length of this file.

Usage

From source file:captureplugin.CapturePlugin.java

/**
 * Check the programs after data update.
 *///w w w.  j  av a 2 s .  com
public void handleTvDataUpdateFinished() {
    mNeedsUpdate = true;

    if (mAllowedToShowDialog) {
        mNeedsUpdate = false;

        DeviceIf[] devices = mConfig.getDeviceArray();

        final DefaultTableModel model = new DefaultTableModel() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        model.setColumnCount(5);
        model.setColumnIdentifiers(new String[] { mLocalizer.msg("device", "Device"),
                Localizer.getLocalization(Localizer.I18N_CHANNEL), mLocalizer.msg("date", "Date"),
                ProgramFieldType.START_TIME_TYPE.getLocalizedName(),
                ProgramFieldType.TITLE_TYPE.getLocalizedName() });

        JTable table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.getTableHeader().setResizingAllowed(false);
        table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable renderTable, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(renderTable, value, isSelected, hasFocus, row,
                        column);

                if (value instanceof DeviceIf) {
                    if (((DeviceIf) value).getDeleteRemovedProgramsAutomatically() && !isSelected) {
                        c.setForeground(Color.red);
                    }
                }

                return c;
            }
        });

        int[] columnWidth = new int[5];

        for (int i = 0; i < columnWidth.length; i++) {
            columnWidth[i] = UiUtilities.getStringWidth(table.getFont(), model.getColumnName(i)) + 10;
        }

        for (DeviceIf device : devices) {
            Program[] deleted = device.checkProgramsAfterDataUpdateAndGetDeleted();

            if (deleted != null && deleted.length > 0) {
                for (Program p : deleted) {
                    if (device.getDeleteRemovedProgramsAutomatically() && !p.isExpired() && !p.isOnAir()) {
                        device.remove(UiUtilities.getLastModalChildOf(getParentFrame()), p);
                    } else {
                        device.removeProgramWithoutExecution(p);
                    }

                    if (!p.isExpired()) {
                        Object[] o = new Object[] { device, p.getChannel().getName(), p.getDateString(),
                                p.getTimeString(), p.getTitle() };

                        for (int i = 0; i < columnWidth.length; i++) {
                            columnWidth[i] = Math.max(columnWidth[i],
                                    UiUtilities.getStringWidth(table.getFont(), o[i].toString()) + 10);
                        }

                        model.addRow(o);
                    }
                }
            }

            device.getProgramList();
        }

        if (model.getRowCount() > 0) {
            int sum = 0;

            for (int i = 0; i < columnWidth.length; i++) {
                table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]);

                if (i < columnWidth.length - 1) {
                    table.getColumnModel().getColumn(i).setMaxWidth(columnWidth[i]);
                }

                sum += columnWidth[i];
            }

            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(450, 250));

            if (sum > 500) {
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                scrollPane.getViewport().setPreferredSize(
                        new Dimension(sum, scrollPane.getViewport().getPreferredSize().height));
            }

            JButton export = new JButton(mLocalizer.msg("exportList", "Export list"));
            export.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    chooser.setFileFilter(new FileFilter() {
                        public boolean accept(File f) {
                            return f.isDirectory() || f.toString().toLowerCase().endsWith(".txt");
                        }

                        public String getDescription() {
                            return "*.txt";
                        }
                    });

                    chooser.setSelectedFile(new File("RemovedPrograms.txt"));
                    if (chooser.showSaveDialog(
                            UiUtilities.getLastModalChildOf(getParentFrame())) == JFileChooser.APPROVE_OPTION) {
                        if (chooser.getSelectedFile() != null) {
                            String file = chooser.getSelectedFile().getAbsolutePath();

                            if (!file.toLowerCase().endsWith(".txt") && file.indexOf('.') == -1) {
                                file = file + ".txt";
                            }

                            if (file.indexOf('.') != -1) {
                                try {
                                    RandomAccessFile write = new RandomAccessFile(file, "rw");
                                    write.setLength(0);

                                    String eolStyle = File.separator.equals("/") ? "\n" : "\r\n";

                                    for (int i = 0; i < model.getRowCount(); i++) {
                                        StringBuilder line = new StringBuilder();

                                        for (int j = 0; j < model.getColumnCount(); j++) {
                                            line.append(model.getValueAt(i, j)).append(' ');
                                        }

                                        line.append(eolStyle);

                                        write.writeBytes(line.toString());
                                    }

                                    write.close();
                                } catch (Exception ee) {
                                }
                            }
                        }
                    }
                }
            });

            Object[] message = {
                    mLocalizer.msg("deletedText",
                            "The data was changed and the following programs were deleted:"),
                    scrollPane, export };

            JOptionPane pane = new JOptionPane();
            pane.setMessage(message);
            pane.setMessageType(JOptionPane.PLAIN_MESSAGE);

            final JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(getParentFrame()),
                    mLocalizer.msg("CapturePlugin", "CapturePlugin") + " - "
                            + mLocalizer.msg("deletedTitle", "Deleted programs"));
            d.setResizable(true);
            d.setModal(false);

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    d.setVisible(true);
                }
            });
        }
    }
}

From source file:com.thoughtworks.go.config.GoConfigDataSource.java

public synchronized GoConfigSaveResult writeWithLock(UpdateConfigCommand updatingCommand,
        GoConfigHolder configHolder) {//from ww  w .j  av  a2  s  .  c  o m
    FileChannel channel = null;
    FileOutputStream outputStream = null;
    FileLock lock = null;
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
        channel = randomAccessFile.getChannel();
        lock = channel.lock();

        // Need to convert to xml before we try to write it to the config file.
        // If our cruiseConfig fails XSD validation, we don't want to write it incorrectly.
        String configAsXml = getModifiedConfig(updatingCommand, configHolder);

        randomAccessFile.seek(0);
        randomAccessFile.setLength(0);
        outputStream = new FileOutputStream(randomAccessFile.getFD());
        LOGGER.info(String.format("[Configuration Changed] Saving updated configuration."));
        IOUtils.write(configAsXml, outputStream);
        ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder)
                ? ConfigSaveState.MERGED
                : ConfigSaveState.UPDATED;
        return new GoConfigSaveResult(internalLoad(configAsXml, getConfigUpdatingUser(updatingCommand)),
                configSaveState);
    } catch (ConfigFileHasChangedException e) {
        LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: "
                + e.getMessage(), e);
        throw e;
    } catch (GoConfigInvalidException e) {
        LOGGER.warn("Configuration file is invalid: " + e.getMessage(), e);
        throw bomb(e.getMessage(), e);
    } catch (Exception e) {
        LOGGER.error("Configuration file is not valid: " + e.getMessage(), e);
        throw bomb(e.getMessage(), e);
    } finally {
        if (channel != null && lock != null) {
            try {
                lock.release();
                channel.close();
                IOUtils.closeQuietly(outputStream);
            } catch (IOException e) {
                LOGGER.error("Error occured when releasing file lock and closing file.", e);
            }
        }
        LOGGER.debug("[Config Save] Done writing with lock");
    }
}

From source file:org.digidoc4j.impl.bdoc.BDocContainerTest.java

private String createLargeFile(long size) {
    String fileName = "test_large_file.bdoc";
    try {//from   w  ww  .  j  a v  a 2 s .  com
        RandomAccessFile largeFile = new RandomAccessFile(fileName, "rw");
        largeFile.setLength(size);//todo create large file correctly
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileName;
}

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);
                }/*  ww w .j  ava2 s .c  om*/
            } 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:org.dcache.xrootd.standalone.DataServerHandler.java

/**
 * Obtains the right mover instance using an opaque token in the
 * request and instruct the mover to open the file in the request.
 * Associates the mover with the file-handle that is produced during
 * processing//from   w  ww.j  a  v a 2 s . co m
 */
@Override
protected OpenResponse doOnOpen(ChannelHandlerContext ctx, OpenRequest msg) throws XrootdException {
    try {
        File file = getFile(msg.getPath());
        if (file.isDirectory()) {
            throw new XrootdException(kXR_isDirectory, "Not a file: " + file);
        }

        File parent = file.getParentFile();

        RandomAccessFile raf;
        if (msg.isReadWrite()) {
            if (msg.isMkPath() && !parent.exists() && !parent.mkdirs()) {
                throw new XrootdException(kXR_IOError, "Failed to create directories: " + parent);
            }
            if (msg.isNew() && !file.createNewFile()) {
                throw new XrootdException(kXR_IOError, "Failed to create file: " + file);
            }
            raf = new RandomAccessFile(file, "rw");
        } else {
            raf = new RandomAccessFile(file, "r");
        }

        try {
            if (msg.isReadWrite() && msg.isDelete()) {
                raf.setLength(0);
            }

            FileStatus stat = null;
            if (msg.isRetStat()) {
                stat = getFileStatusOf(file);
            }

            int fd = addOpenFile(raf);
            raf = null;
            return new OpenResponse(msg, fd, null, null, stat);
        } finally {
            if (raf != null) {
                raf.close();
            }
        }
    } catch (FileNotFoundException e) {
        throw new XrootdException(kXR_NotFound, e.getMessage());
    } catch (IOException e) {
        throw new XrootdException(kXR_IOError, e.getMessage());
    }
}

From source file:com.alibaba.otter.node.etl.common.pipe.impl.http.AbstractHttpPipe.java

protected void decodeFile(File file, String key, String crc) {
    // ??/*from w  ww . j a  v  a2  s.  c  om*/
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(file, "rw");

        long totallength = file.length();
        int keyLength = ByteUtils.stringToBytes(key).length;
        int crcLength = ByteUtils.stringToBytes(crc).length;
        // ?
        long pos = totallength - keyLength - crcLength;
        // 
        raf.seek(pos);
        // ?key
        byte[] keyBytes = new byte[keyLength];
        raf.read(keyBytes, 0, keyLength);
        String keystr = ByteUtils.bytesToString(keyBytes);
        if (!key.equals(keystr)) {
            throw new ChecksumException("unmatch garble key with[" + key + "],[" + keystr + "]");
        }

        // ??
        raf.seek(pos + keyLength);
        byte[] crcBytes = new byte[crcLength];
        raf.read(crcBytes, 0, crcLength);
        String crcStr = ByteUtils.bytesToString(crcBytes);
        if (!crc.equals(crcStr)) {
            throw new ChecksumException("unmatch crc with[" + crc + "],[" + crcStr + "]");
        }

        // 
        raf.setLength(pos);
    } catch (Exception e) {
        throw new PipeException("read_encrypted_error", e);
    } finally {
        IOUtils.closeQuietly(raf);
    }
}

From source file:com.baidubce.services.bos.BosClientTest.java

private static File createFile(String fileName, long length) throws IOException {
    File file = new File(fileName);
    RandomAccessFile r = null;
    try {/*  ww  w .j  a  v a  2 s.  c  om*/
        r = new RandomAccessFile(file, "rw");
        r.setLength(length);
    } finally {
        if (r != null) {
            try {
                r.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return file;
}

From source file:org.wso2.msf4j.HttpServerTest.java

public void testStreamUploadFailure() throws IOException {
    //create a random file to be uploaded.
    int size = 20 * 1024;
    File fname = new File(tmpFolder, "testStreamUploadFailure.txt");
    fname.createNewFile();//  w  w  w.j ava 2 s  .  co  m
    RandomAccessFile randf = new RandomAccessFile(fname, "rw");
    randf.setLength(size);
    randf.close();

    HttpURLConnection urlConn = request("/test/v1/stream/upload/fail", HttpMethod.PUT);
    Files.copy(Paths.get(fname.toURI()), urlConn.getOutputStream());
    assertEquals(500, urlConn.getResponseCode());
    urlConn.disconnect();
    fname.delete();
}

From source file:org.wso2.msf4j.HttpServerTest.java

public void testChunkAggregatedUploadFailure() throws IOException {
    //create a random file to be uploaded.
    int size = 78 * 1024;
    File fname = new File(tmpFolder, "testChunkAggregatedUploadFailure.txt");
    fname.createNewFile();// w ww.j av  a 2 s . c  o m
    RandomAccessFile randf = new RandomAccessFile(fname, "rw");
    randf.setLength(size);
    randf.close();

    //test chunked upload
    HttpURLConnection urlConn = request("/test/v1/aggregate/upload", HttpMethod.PUT);
    urlConn.setChunkedStreamingMode(1024);
    Files.copy(Paths.get(fname.toURI()), urlConn.getOutputStream());
    assertEquals(500, urlConn.getResponseCode());
    urlConn.disconnect();
    fname.delete();
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testChunkAggregatedUpload() throws IOException {
    //create a random file to be uploaded.
    int size = 69 * 1024;
    File fname = new File(tmpFolder, "testChunkAggregatedUpload.txt");
    fname.createNewFile();//w  ww.  j a va  2 s.c  o  m
    RandomAccessFile randf = new RandomAccessFile(fname, "rw");
    randf.setLength(size);
    randf.close();

    //test chunked upload
    HttpURLConnection urlConn = request("/test/v1/aggregate/upload", HttpMethod.PUT);
    urlConn.setChunkedStreamingMode(1024);
    Files.copy(Paths.get(fname.toURI()), urlConn.getOutputStream());
    assertEquals(200, urlConn.getResponseCode());

    assertEquals(size, Integer.parseInt(getContent(urlConn).split(":")[1].trim()));
    urlConn.disconnect();
    fname.delete();
}