Example usage for java.util Vector toArray

List of usage examples for java.util Vector toArray

Introduction

In this page you can find the example usage for java.util Vector toArray.

Prototype

@SuppressWarnings("unchecked")
public synchronized <T> T[] toArray(T[] a) 

Source Link

Document

Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.

Usage

From source file:edu.umn.cs.spatialHadoop.operations.Repartition.java

public static CellInfo[] packInRectangles(Path[] files, Path outFile, OperationsParams params,
        Rectangle fileMBR) throws IOException {
    final Vector<Point> sample = new Vector<Point>();

    float sample_ratio = params.getFloat(SpatialSite.SAMPLE_RATIO, 0.01f);
    long sample_size = params.getLong(SpatialSite.SAMPLE_SIZE, 100 * 1024 * 1024);

    LOG.info("Reading a sample of " + (int) Math.round(sample_ratio * 100) + "%");
    ResultCollector<Point> resultCollector = new ResultCollector<Point>() {
        @Override/*from   w  w  w.  j a v  a2  s.  co  m*/
        public void collect(Point value) {
            sample.add(value.clone());
        }
    };
    OperationsParams params2 = new OperationsParams(params);
    params2.setFloat("ratio", sample_ratio);
    params2.setLong("size", sample_size);
    params2.setClass("outshape", Point.class, TextSerializable.class);
    Sampler.sample(files, resultCollector, params2);
    LOG.info("Finished reading a sample of size: " + sample.size() + " records");

    long inFileSize = Sampler.sizeOfLastProcessedFile;

    // Compute an approximate MBR to determine the desired number of rows
    // and columns
    Rectangle approxMBR;
    if (fileMBR == null) {
        approxMBR = new Rectangle(Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE);
        for (Point pt : sample)
            approxMBR.expand(pt);
    } else {
        approxMBR = fileMBR;
    }
    GridInfo gridInfo = new GridInfo(approxMBR.x1, approxMBR.y1, approxMBR.x2, approxMBR.y2);
    FileSystem outFs = outFile.getFileSystem(params);
    @SuppressWarnings("deprecation")
    long blocksize = outFs.getDefaultBlockSize();
    gridInfo.calculateCellDimensions(Math.max(1, (int) ((inFileSize + blocksize / 2) / blocksize)));
    if (fileMBR == null)
        gridInfo.set(-Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);
    else
        gridInfo.set(fileMBR);

    Rectangle[] rectangles = RTree.packInRectangles(gridInfo, sample.toArray(new Point[sample.size()]));
    CellInfo[] cellsInfo = new CellInfo[rectangles.length];
    for (int i = 0; i < rectangles.length; i++)
        cellsInfo[i] = new CellInfo(i + 1, rectangles[i]);

    return cellsInfo;
}

From source file:edu.ku.brc.af.core.db.MySQLBackupService.java

/**
 * @param restoreFilePath/*from   w  w w  .  jav a  2 s . c  o m*/
 * @param mysqlLoc
 * @param databaseName
 * @return
 */
public boolean doRestore(final String restoreFilePath, final String mysqlLoc, final String databaseName,
        final String userName, final String password) {
    FileInputStream input = null;
    try {
        Vector<String> args = new Vector<String>();
        args.add(mysqlLoc);
        args.add("--user=" + userName);
        args.add("--password=" + password);
        args.add(databaseName);
        Process process = Runtime.getRuntime().exec(args.toArray(new String[0]));

        //Thread.sleep(100);

        OutputStream out = process.getOutputStream();

        // wait as long it takes till the other process has prompted.
        try {
            File inFile = new File(restoreFilePath);
            input = new FileInputStream(inFile);
            try {
                //long totalBytes = 0;
                byte[] bytes = new byte[8192 * 4]; // 32K
                do {
                    int numBytes = input.read(bytes, 0, bytes.length);
                    //totalBytes += numBytes;
                    //System.out.println(numBytes+" / "+totalBytes);
                    if (numBytes > 0) {
                        out.write(bytes, 0, numBytes);
                    } else {
                        break;
                    }
                } while (true);
            } finally {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            errorMsg = ex.toString();
            return false;

        } catch (Exception ex) {
            ex.printStackTrace();
            return false;

        } finally {
            out.flush();
            out.close();
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
            //System.err.println(line);
        }

        in = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        StringBuilder sb = new StringBuilder();
        while ((line = in.readLine()) != null) {
            if (line.startsWith("ERR")) {
                sb.append(line);
                sb.append("\n");
            }
        }
        errorMsg = sb.toString();

        //System.out.println("errorMsg: ["+errorMsg+"]");

        return errorMsg == null || errorMsg.isEmpty();

    } catch (Exception ex) {
        ex.printStackTrace();
        errorMsg = ex.toString();
    }
    return false;
}

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 w ww  . j av  a2s .  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.myargmenuplanner.data.FetchJsonDataTask.java

private void getDataFoodFromJson(String JsonStr) throws JSONException {

    final String JSON_LIST = "foods";
    final String JSON_TITLE = "title";
    final String JSON_IMAGE_ID = "image_id";
    final String JSON_DESCRIPTION = "description";
    final String JSON_TIME = "time";
    final String JSON_ID = "id";

    try {/*from  w ww. j  a  v a  2s .  co m*/
        JSONObject dataJson = new JSONObject(JsonStr);
        JSONArray moviesArray = dataJson.getJSONArray(JSON_LIST);

        Vector<ContentValues> cVVector = new Vector<ContentValues>(moviesArray.length());

        for (int i = 0; i < moviesArray.length(); i++) {

            JSONObject movie = moviesArray.getJSONObject(i);
            String title = movie.getString(JSON_TITLE);
            String image_id = movie.getString(JSON_IMAGE_ID);
            String description = movie.getString(JSON_DESCRIPTION);
            String time = movie.getString(JSON_TIME);
            String id = movie.getString(JSON_ID);

            ContentValues foodsValues = new ContentValues();

            foodsValues.put(FoodEntry.COLUMN_ID, id);
            foodsValues.put(FoodEntry.COLUMN_TITLE, title);
            foodsValues.put(FoodEntry.COLUMN_IMAGE_ID, image_id);
            foodsValues.put(FoodEntry.COLUMN_DESCRIPTION, description);
            foodsValues.put(FoodEntry.COLUMN_TIME, time);
            cVVector.add(foodsValues);

        }
        int inserted = 0;

        //            delete database
        int rowdeleted = mContext.getContentResolver().delete(FoodEntry.CONTENT_URI, null, null);

        //            // add to database
        Log.i(LOG_TAG, "Creando registros en base de datos. Tabla Food: ");
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            inserted = mContext.getContentResolver().bulkInsert(FoodEntry.CONTENT_URI, cvArray);
            Log.i(LOG_TAG, "Registros nuevos creados en tabla Food: " + inserted);
        }

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }

}

From source file:org.schabi.newpipe.services.youtube.YoutubeVideoExtractor.java

@Override
public VideoInfo.VideoStream[] getVideoStreams() {
    try {/*from  w  w w.  j a va2s .  c  o  m*/
        //------------------------------------
        // extract video stream url
        //------------------------------------
        String encoded_url_map = playerArgs.getString("url_encoded_fmt_stream_map");
        Vector<VideoInfo.VideoStream> videoStreams = new Vector<>();
        for (String url_data_str : encoded_url_map.split(",")) {
            Map<String, String> tags = new HashMap<>();
            for (String raw_tag : Parser.unescapeEntities(url_data_str, true).split("&")) {
                String[] split_tag = raw_tag.split("=");
                tags.put(split_tag[0], split_tag[1]);
            }

            int itag = Integer.parseInt(tags.get("itag"));
            String streamUrl = URLDecoder.decode(tags.get("url"), "UTF-8");

            // if video has a signature: decrypt it and add it to the url
            if (tags.get("s") != null) {
                streamUrl = streamUrl + "&signature=" + decryptSignature(tags.get("s"), decryptionCode);
            }

            if (resolveFormat(itag) != -1) {
                videoStreams.add(new VideoInfo.VideoStream(streamUrl, resolveFormat(itag),
                        resolveResolutionString(itag)));
            }
        }
        return videoStreams.toArray(new VideoInfo.VideoStream[videoStreams.size()]);

    } catch (Exception e) {
        Log.e(TAG, "Failed to get video stream");
        e.printStackTrace();
        return new VideoInfo.VideoStream[0];
    }
}

From source file:org.apache.webdav.lib.methods.PropFindMethod.java

/**
 * Property names setter./*from  ww w. ja  va 2s.  c o  m*/
 * The enumeration may contain strings with or without a namespace prefix
 * but the preferred way is to provide PropertyName objects.
 *
 * @param propertyNames List of the property names
 */
public void setPropertyNames(Enumeration propertyNames) {
    checkNotUsed();

    Vector list = new Vector();
    while (propertyNames.hasMoreElements()) {

        Object item = propertyNames.nextElement();

        if (item instanceof PropertyName) {
            list.add(item);
        } else if (item instanceof String) {
            String propertyName = (String) item;

            int length = propertyName.length();
            boolean found = false;
            int i = 1;
            while (!found && (i <= length)) {
                char chr = propertyName.charAt(length - i);
                if (!Character.isUnicodeIdentifierPart(chr) && chr != '-' && chr != '_' && chr != '.') {
                    found = true;
                } else {
                    i++;
                }
            }
            if ((i == 1) || (i >= length)) {
                list.add(new PropertyName("DAV:", propertyName));
            } else {
                String namespace = propertyName.substring(0, length + 1 - i);
                String localName = propertyName.substring(length + 1 - i);
                list.add(new PropertyName(namespace, localName));
            }
        } else {
            // unknown type
            // ignore
        }
    }

    this.propertyNames = (PropertyName[]) list.toArray(new PropertyName[list.size()]);
}

From source file:org.freedesktop.dbus.Message.java

/**
 * Demarshall one value from a buffer./*w  w  w .  j  a  v  a2s .co  m*/
 * 
 * @param sigb
 *            A buffer of the D-Bus signature.
 * @param buf
 *            The buffer to demarshall from.
 * @param ofs
 *            An array of two ints, the offset into the signature buffer
 *            and the offset into the data buffer. These values will be
 *            updated to the start of the next value ofter demarshalling.
 * @param contained
 *            converts nested arrays to Lists
 * @return The demarshalled value.
 */
private Object extractone(byte[] sigb, byte[] buf, int[] ofs, boolean contained) throws DBusException {
    if (log.isTraceEnabled()) {
        log.trace("Extracting type: " + ((char) sigb[ofs[0]]) + " from offset " + ofs[1]);
    }
    Object rv = null;
    ofs[1] = align(ofs[1], sigb[ofs[0]]);
    switch (sigb[ofs[0]]) {
    case ArgumentType.BYTE:
        rv = buf[ofs[1]++];
        break;
    case ArgumentType.UINT32:
        rv = new UInt32(demarshallint(buf, ofs[1], 4));
        ofs[1] += 4;
        break;
    case ArgumentType.INT32:
        rv = (int) demarshallint(buf, ofs[1], 4);
        ofs[1] += 4;
        break;
    case ArgumentType.INT16:
        rv = (short) demarshallint(buf, ofs[1], 2);
        ofs[1] += 2;
        break;
    case ArgumentType.UINT16:
        rv = new UInt16((int) demarshallint(buf, ofs[1], 2));
        ofs[1] += 2;
        break;
    case ArgumentType.INT64:
        rv = demarshallint(buf, ofs[1], 8);
        ofs[1] += 8;
        break;
    case ArgumentType.UINT64:
        long top;
        long bottom;
        if (this.big) {
            top = demarshallint(buf, ofs[1], 4);
            ofs[1] += 4;
            bottom = demarshallint(buf, ofs[1], 4);
        } else {
            bottom = demarshallint(buf, ofs[1], 4);
            ofs[1] += 4;
            top = demarshallint(buf, ofs[1], 4);
        }
        rv = new UInt64(top, bottom);
        ofs[1] += 4;
        break;
    case ArgumentType.DOUBLE:
        long l = demarshallint(buf, ofs[1], 8);
        ofs[1] += 8;
        rv = Double.longBitsToDouble(l);
        break;
    case ArgumentType.FLOAT:
        int rf = (int) demarshallint(buf, ofs[1], 4);
        ofs[1] += 4;
        rv = Float.intBitsToFloat(rf);
        break;
    case ArgumentType.BOOLEAN:
        rf = (int) demarshallint(buf, ofs[1], 4);
        ofs[1] += 4;
        rv = (1 == rf) ? Boolean.TRUE : Boolean.FALSE;
        break;
    case ArgumentType.ARRAY:
        long size = demarshallint(buf, ofs[1], 4);
        if (log.isTraceEnabled()) {
            log.trace("Reading array of size: " + size);
        }
        ofs[1] += 4;
        byte algn = (byte) getAlignment(sigb[++ofs[0]]);
        ofs[1] = align(ofs[1], sigb[ofs[0]]);
        int length = (int) (size / algn);
        if (length > AbstractConnection.MAX_ARRAY_LENGTH)
            throw new MarshallingException("Arrays must not exceed " + AbstractConnection.MAX_ARRAY_LENGTH);
        // optimise primatives
        switch (sigb[ofs[0]]) {
        case ArgumentType.BYTE:
            rv = new byte[length];
            System.arraycopy(buf, ofs[1], rv, 0, length);
            ofs[1] += size;
            break;
        case ArgumentType.INT16:
            rv = new short[length];
            for (int j = 0; j < length; j++, ofs[1] += algn)
                ((short[]) rv)[j] = (short) demarshallint(buf, ofs[1], algn);
            break;
        case ArgumentType.INT32:
            rv = new int[length];
            for (int j = 0; j < length; j++, ofs[1] += algn)
                ((int[]) rv)[j] = (int) demarshallint(buf, ofs[1], algn);
            break;
        case ArgumentType.INT64:
            rv = new long[length];
            for (int j = 0; j < length; j++, ofs[1] += algn)
                ((long[]) rv)[j] = demarshallint(buf, ofs[1], algn);
            break;
        case ArgumentType.BOOLEAN:
            rv = new boolean[length];
            for (int j = 0; j < length; j++, ofs[1] += algn)
                ((boolean[]) rv)[j] = (1 == demarshallint(buf, ofs[1], algn));
            break;
        case ArgumentType.FLOAT:
            rv = new float[length];
            for (int j = 0; j < length; j++, ofs[1] += algn)
                ((float[]) rv)[j] = Float.intBitsToFloat((int) demarshallint(buf, ofs[1], algn));
            break;
        case ArgumentType.DOUBLE:
            rv = new double[length];
            for (int j = 0; j < length; j++, ofs[1] += algn)
                ((double[]) rv)[j] = Double.longBitsToDouble(demarshallint(buf, ofs[1], algn));
            break;
        case ArgumentType.DICT_ENTRY1:
            if (0 == size) {
                // advance the type parser even on 0-size arrays.
                Vector<Type> temp = new Vector<>();
                byte[] temp2 = new byte[sigb.length - ofs[0]];
                System.arraycopy(sigb, ofs[0], temp2, 0, temp2.length);
                String temp3 = new String(temp2);
                // ofs[0] gets incremented anyway. Leave one character on the stack
                int temp4 = Marshalling.getJavaType(temp3, temp, 1) - 1;
                ofs[0] += temp4;
                if (log.isTraceEnabled()) {
                    log.trace("Aligned type: " + temp3 + " " + temp4 + " " + ofs[0]);
                }
            }
            int ofssave = ofs[0];
            long end = ofs[1] + size;
            Vector<Object[]> entries = new Vector<>();
            while (ofs[1] < end) {
                ofs[0] = ofssave;
                entries.add((Object[]) extractone(sigb, buf, ofs, true));
            }
            rv = new DBusMap<>(entries.toArray(new Object[0][]));
            break;
        default:
            if (0 == size) {
                // advance the type parser even on 0-size arrays.
                Vector<Type> temp = new Vector<>();
                byte[] temp2 = new byte[sigb.length - ofs[0]];
                System.arraycopy(sigb, ofs[0], temp2, 0, temp2.length);
                String temp3 = new String(temp2);
                // ofs[0] gets incremented anyway. Leave one character on the stack
                int temp4 = Marshalling.getJavaType(temp3, temp, 1) - 1;
                ofs[0] += temp4;
                if (log.isTraceEnabled()) {
                    log.trace("Aligned type: " + temp3 + " " + temp4 + " " + ofs[0]);
                }
            }
            ofssave = ofs[0];
            end = ofs[1] + size;
            Vector<Object> contents = new Vector<>();
            while (ofs[1] < end) {
                ofs[0] = ofssave;
                contents.add(extractone(sigb, buf, ofs, true));
            }
            rv = contents;
        }
        if (contained && !(rv instanceof List) && !(rv instanceof Map))
            rv = ArrayFrob.listify(rv);
        break;
    case ArgumentType.STRUCT1:
        Vector<Object> contents = new Vector<>();
        while (sigb[++ofs[0]] != ArgumentType.STRUCT2)
            contents.add(extractone(sigb, buf, ofs, true));
        rv = contents.toArray();
        break;
    case ArgumentType.DICT_ENTRY1:
        Object[] decontents = new Object[2];
        if (log.isTraceEnabled()) {
            Hex h = new Hex();
            log.trace(
                    "Extracting Dict Entry (" + h.encode(Arrays.copyOfRange(sigb, ofs[0], sigb.length - ofs[0]))
                            + ") from: " + h.encode(Arrays.copyOfRange(buf, ofs[1], buf.length - ofs[1])));
        }
        ofs[0]++;
        decontents[0] = extractone(sigb, buf, ofs, true);
        ofs[0]++;
        decontents[1] = extractone(sigb, buf, ofs, true);
        ofs[0]++;
        rv = decontents;
        break;
    case ArgumentType.VARIANT:
        int[] newofs = new int[] { 0, ofs[1] };
        String sig = (String) extract(ArgumentType.SIGNATURE_STRING, buf, newofs)[0];
        newofs[0] = 0;
        rv = new Variant<>(extract(sig, buf, newofs)[0], sig);
        ofs[1] = newofs[1];
        break;
    case ArgumentType.STRING:
        length = (int) demarshallint(buf, ofs[1], 4);
        ofs[1] += 4;
        try {
            rv = new String(buf, ofs[1], length, "UTF-8");
        } catch (UnsupportedEncodingException UEe) {
            throw new DBusException("System does not support UTF-8 encoding", UEe);
        }
        ofs[1] += length + 1;
        break;
    case ArgumentType.OBJECT_PATH:
        length = (int) demarshallint(buf, ofs[1], 4);
        ofs[1] += 4;
        rv = new ObjectPath(getSource(), new String(buf, ofs[1], length));
        ofs[1] += length + 1;
        break;
    case ArgumentType.SIGNATURE:
        length = (buf[ofs[1]++] & 0xFF);
        rv = new String(buf, ofs[1], length);
        ofs[1] += length + 1;
        break;
    default:
        throw new UnknownTypeCodeException(sigb[ofs[0]]);
    }
    if (log.isDebugEnabled()) {
        if (rv instanceof Object[])
            log.trace("Extracted: " + Arrays.deepToString((Object[]) rv) + " (now at " + ofs[1] + ")");
        else
            log.trace("Extracted: " + rv + " (now at " + ofs[1] + ")");
    }
    return rv;
}

From source file:org.apache.webdav.lib.methods.ReportMethod.java

/**
 * Property names setter./*w  w w . ja v a2 s  . c om*/
 * The enumeration may contain strings with or without a namespace prefix
 * but the preferred way is to provide PropertyName objects.
 *
 * @param propertyNames List of the property names
 */
public void setPropertyNames(Enumeration propertyNames) {
    checkNotUsed();

    Vector list = new Vector();
    while (propertyNames.hasMoreElements()) {

        Object item = propertyNames.nextElement();

        if (item instanceof PropertyName) {
            list.add(item);
        } else if (item instanceof String) {
            String propertyName = (String) item;

            int length = propertyName.length();
            boolean found = false;
            int i = 1;
            while (!found && (i <= length)) {
                char chr = propertyName.charAt(length - i);
                if (!Character.isUnicodeIdentifierPart(chr) && chr != '-' && chr != '_' && chr != '.') {
                    found = true;
                } else {
                    i++;
                }
            }
            if ((i == 1) || (i >= length)) {
                list.add(new PropertyName("DAV:", propertyName));
            } else {
                String namespace = propertyName.substring(0, length + 1 - i);
                String localName = propertyName.substring(length + 1 - i);
                list.add(new PropertyName(namespace, localName));
            }
        } else {
            throw new IllegalArgumentException("Invalid object given for property.");
        }
    }

    this.propertyNames = (PropertyName[]) list.toArray(new PropertyName[list.size()]);

    if (this.type == ALL)
        this.type = SUB_SET;
}

From source file:org.ow2.aspirerfid.reader.rp.hal.impl.intermecif5.IntermecIF5Controller.java

public Observation[] identify(String[] readPointNames) throws HardwareException {
    // Each read point gets its own Observation
    Observation[] observations = new Observation[readPointNames.length];

    // currentInventory.clear();

    // ==============Start===============
    ArrayList<String> tags;
    // Vector[] tagIds = new Vector[readPointNames.length];
    String[] line;//from   w  ww.  j av  a2  s .c o m
    // final char SPACE = ' ';
    // ===============End==============

    for (int i = 0; i < readPointNames.length; i++) {

        observations[i] = new Observation();
        observations[i].setHalName(this.halName);
        observations[i].setReadPointName(readPointNames[i]);
        // Get the tag IDs on this antenna
        // Vector<String> v = new Vector<String>();
        Vector<String> tagIds = new Vector<String>();
        // Iterator it = ((HashSet)
        // reader.get(readPointNames[i])).iterator();

        // ==============Start==========
        // tagIds[i] = new Vector();
        tags = read(null, readPoints.get(readPointNames[i]).toString());
        for (String reading : tags) {
            line = reading.split(" ");
            // line[1]: antenna id
            // line[0]: epcid
            tagIds.add(line[0]);
        }
        // ==========End======================

        // while (it.hasNext()) {
        // Tag t = (Tag) it.next();
        // v.add(t.getTagID());
        // }

        int len = tagIds.size();
        String v_arr[] = new String[len];
        v_arr = tagIds.toArray(v_arr);
        TagDescriptor[] td_arr = new TagDescriptor[v_arr.length];
        String idTConf;
        try {
            idTConf = config.getString("idTypesConfig");
        } catch (Exception e) {
            idTConf = null;
        }

        for (int j = 0; j < td_arr.length; j++) {
            IDType idType = IDType.getIdType("EPC", idTConf);
            byte[] accada_sim_tid_bytes = ByteBlock.hexStringToByteArray("E2656656");
            EPCTransponderModel tagModel = EPCTransponderModel.getEpcTrasponderModel(accada_sim_tid_bytes,
                    epcTransponderModelsConfig);
            MemoryBankDescriptor[] memoryBankDescriptors = new MemoryBankDescriptor[4];
            memoryBankDescriptors[0] = new MemoryBankDescriptor(tagModel.getReservedSize(),
                    tagModel.getReservedReadable(), tagModel.getReservedWriteable());
            memoryBankDescriptors[1] = new MemoryBankDescriptor(tagModel.getEpcSize(),
                    tagModel.getEpcReadable(), tagModel.getEpcWriteable());
            memoryBankDescriptors[2] = new MemoryBankDescriptor(tagModel.getTidSize(),
                    tagModel.getTidReadable(), tagModel.getTidWriteable());
            memoryBankDescriptors[3] = new MemoryBankDescriptor(tagModel.getUserSize(),
                    tagModel.getUserReadable(), tagModel.getUserWriteable());
            MemoryDescriptor memoryDescriptor = new MemoryDescriptor(memoryBankDescriptors);
            td_arr[j] = new TagDescriptor(idType, memoryDescriptor);
        }
        observations[i].setTagDescriptors(td_arr);
        observations[i].setIds(v_arr);
        observations[i].setTimestamp(System.currentTimeMillis());

        if (!readPoints.containsKey(readPointNames[i])) {
            log.error("Read point \"" + readPointNames[i] + "\" is not ready.");
            observations[i].setIds(new String[0]);
            observations[i].setTagDescriptors(new TagDescriptor[0]);
            observations[i].successful = false;
        } else if (continuousIdentifyErrors.contains(readPointNames[i])) {
            observations[i].successful = false;
        } else if (identifyError.contains(readPointNames[i])) {
            observations[i].successful = false;
            identifyError.remove(readPointNames[i]);
        } else {
            observations[i].successful = true;
        }

        log.debug(observations[i].toString());
    }
    return observations;
}

From source file:org.parosproxy.paros.network.HttpMessage.java

public String[] getParamNames() {
    Vector<String> v = new Vector<>();
    // Get the params names from the query
    SortedSet<String> pns = this.getParamNameSet(HtmlParameter.Type.url);
    Iterator<String> iterator = pns.iterator();
    while (iterator.hasNext()) {
        String name = iterator.next();
        if (name != null) {
            v.add(name);// w  w w  . j  a v  a  2 s .  c o  m
        }
    }
    if (getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.POST)) {
        // Get the param names from the POST
        pns = this.getParamNameSet(HtmlParameter.Type.form);
        iterator = pns.iterator();
        while (iterator.hasNext()) {
            String name = iterator.next();
            if (name != null) {
                v.add(name);
            }

        }
    }
    String[] a = new String[v.size()];
    v.toArray(a);
    return a;
}