Example usage for java.util Vector elementAt

List of usage examples for java.util Vector elementAt

Introduction

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

Prototype

public synchronized E elementAt(int index) 

Source Link

Document

Returns the component at the specified index.

Usage

From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java

public static void importKeyCert(Password password, Vector<Vector<Object>> pkeyinfo_collection,
        Vector<Vector<Object>> cert_collection) throws Exception {

    logger.debug("ConfigurationUtils.importKeyCert()");
    CryptoManager cm = CryptoManager.getInstance();
    CryptoToken token = cm.getInternalKeyStorageToken();
    CryptoStore store = token.getCryptoStore();

    deleteExistingCerts();//from  w  w  w. j  a va 2  s .c o m

    ArrayList<String> masterList = getMasterCertKeyList();

    logger.debug("Importing new keys:");
    for (int i = 0; i < pkeyinfo_collection.size(); i++) {
        Vector<Object> pkeyinfo_v = pkeyinfo_collection.elementAt(i);
        byte[] epki = (byte[]) pkeyinfo_v.elementAt(0);
        String nickname = (String) pkeyinfo_v.elementAt(1);
        logger.debug("- Key: " + nickname);

        if (!importRequired(masterList, nickname)) {
            logger.debug("  Key not in master list, ignore key");
            continue;
        }

        logger.debug("  Find cert with subject DN " + nickname);
        // TODO: use better mechanism to find the cert
        byte[] x509cert = getX509Cert(nickname, cert_collection);
        if (x509cert == null) {
            logger.debug("  Certificate is missing/removed, ignore key");
            continue;
        }

        X509Certificate cert = cm.importCACertPackage(x509cert);
        logger.debug("  Imported cert " + cert.getSerialNumber());

        // get public key
        PublicKey publicKey = cert.getPublicKey();

        // delete the cert again
        try {
            store.deleteCert(cert);
        } catch (NoSuchItemOnTokenException e) {
            // this is OK
        }

        try {
            // first true without BMPString-encoding the passphrase.
            store.importEncryptedPrivateKeyInfo(null, password, nickname, publicKey, epki);
        } catch (Exception e) {
            // if that failed, try again with BMPString-encoded
            // passphrase.  This is required for PKCS #12 PBE
            // schemes and for PKCS #12 files using PBES2 generated
            // by NSS < 3.31
            store.importEncryptedPrivateKeyInfo(new PasswordConverter(), password, nickname, publicKey, epki);
        }
    }

    logger.debug("Importing new certificates:");
    for (int i = 0; i < cert_collection.size(); i++) {

        Vector<Object> cert_v = cert_collection.elementAt(i);
        byte[] cert = (byte[]) cert_v.elementAt(0);

        if (cert_v.size() > 1) {
            String name = (String) cert_v.elementAt(1);
            logger.debug("- Certificate: " + name);

            if (!masterList.contains(name)) {
                logger.debug("  Certificate not in master list, ignore certificate");
                continue;
            }

            // we need to delete the trusted CA certificate if it is
            // the same as the ca signing certificate
            boolean isCASigningCert = isCASigningCert(name);
            logger.debug("  CA signing cert: " + isCASigningCert);

            if (isCASigningCert) {
                X509Certificate certchain = getX509CertFromToken(cert);
                if (certchain != null) {
                    if (store instanceof PK11Store) {
                        try {
                            logger.debug("  Deleting trusted CA cert");
                            PK11Store pk11store = (PK11Store) store;
                            pk11store.deleteCertOnly(certchain);
                        } catch (Exception e) {
                            logger.warn("Unable to delete trusted CA cert: " + e);
                        }
                    }
                }
            }

            X509Certificate xcert = cm.importUserCACertPackage(cert, name);
            logger.debug("  Imported cert " + xcert.getSerialNumber());
            InternalCertificate icert = (InternalCertificate) xcert;

            if (isCASigningCert) {
                // set trust flags to CT,C,C
                icert.setSSLTrust(InternalCertificate.TRUSTED_CA | InternalCertificate.TRUSTED_CLIENT_CA
                        | InternalCertificate.VALID_CA);
                icert.setEmailTrust(InternalCertificate.TRUSTED_CA | InternalCertificate.VALID_CA);
                icert.setObjectSigningTrust(InternalCertificate.TRUSTED_CA | InternalCertificate.VALID_CA);

            } else if (isAuditSigningCert(name)) {
                // set trust flags to u,u,Pu
                icert.setObjectSigningTrust(InternalCertificate.USER | InternalCertificate.VALID_PEER
                        | InternalCertificate.TRUSTED_PEER);
            }

        } else {
            cm.importCACertPackage(cert);
        }
    }
}

From source file:mesquite.lib.MesquiteModule.java

/** A request for the MesquiteModule to perform a command.  It is passed two strings, the name of the command and the arguments.
This should be overridden by any module that wants to respond to a command.*/
public Object doCommand(String commandName, String arguments, CommandChecker checker) {
    if (checker.compare(MesquiteModule.class, null, null, commandName, "showEmployeeTree")) {
        EmployeeTree etM = (EmployeeTree) findImmediateEmployeeWithDuty(EmployeeTree.class);
        if (etM == null)
            etM = (EmployeeTree) hireEmployee(EmployeeTree.class, null);
        if (etM != null)
            etM.showEmployeeTreeWindow(this);
        return etM;
    } else if (checker.compare(MesquiteModule.class, "Show employers of this module", null, commandName,
            "employers")) {
        logln(getEmployerPath());//from  w w w .j a  va 2s.co  m
    } else if (checker.compare(MesquiteModule.class, "Executes a shell script", "[path to script file]",
            commandName, "executeShellScript")) {
        String scriptPath = parser.getFirstToken(arguments);
        if (StringUtil.blank(scriptPath))
            return null;
        else {
            ShellScriptUtil.executeAndWaitForShell(scriptPath, getName());
        }
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "dumpParameterTree")) {
        System.out.println("=============\nParameters of modules of window of " + getName() + "\n"
                + listEmployeeParameters("") + "\n=============");
    } else if (checker.compare(MesquiteModule.class, "Shows manual in browser", null, commandName,
            "showManual")) {
        showManual();
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "showCommandPage")) {
        showWebPage(getCommandPagePath(), true);
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "showMiniInfoWindow")) {
        return new ModuleInfoWindow(module);
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "openSourceInEclipse")) {
        openSourceInEclipse();
    } else if (checker.compare(getClass(), "Logs last result string", null, commandName,
            "logLastResultString")) {
        logln("Last result:\n" + lastResultString);
    } else if (checker.compare(getClass(), "Returns last result string", null, commandName,
            "getLastResultString")) {
        return lastResultString;
    } else if (checker.compare(getClass(), "Returns last MesquiteNumber result", null, commandName,
            "getLastResult")) {
        return lastResult;
    }

    else if (checker.compare(MesquiteModule.class, null, null, commandName, "setAssignedID")) {
        if (getFileCoordinator() != null && getFileCoordinator().permanentIDExists(arguments))
            assignedIDString = getPermanentIDString(); // make new one if old exists
        else
            assignedIDString = arguments;
        if (getFileCoordinator() != null)
            getFileCoordinator().broadCastAssignedID(this, arguments);
        else
            mesquiteTrunk.broadCastAssignedID(this, arguments);
        return assignedIDString;
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "getWindow")) {
        return getModuleWindow();
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "getContainingWindow")) {
        return containerOfModule();
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "saveMacro")) {
        MesquiteTrunk.snapshotMode = getMacroSnapshotMode();
        MesquiteModule mb = getMacroSnapshotModule();
        if (mb == null) {
            discreetAlert("The Macro snapshot module can't be found.");
            return null;
        }
        boolean otherModule = !mb.equals(this);
        String prefix = "";
        if (otherModule) {
            prefix = "\t" + getMacroSnapshotModuleCommand() + ";" + StringUtil.lineEnding();
            prefix += "\t\ttell It;" + StringUtil.lineEnding();
        }
        String recipe = Snapshot.getSnapshotCommands(getMacroSnapshotModule(), null, "");
        if (otherModule) {
            recipe = prefix + recipe + "\t\tendTell;" + StringUtil.lineEnding();

        }
        MesquiteMacro.saveMacro(this, "Untitled Macro for " + getNameForMenuItem(), 0, recipe);
        MesquiteTrunk.snapshotMode = Snapshot.SNAPALL;
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "applyMacro")) {
        MesquiteModuleInfo mmi = getModuleInfo();
        if (mmi == null)
            return null;
        Vector macros = mmi.getMacros();
        if (macros == null || macros.size() <= 0)
            return null;
        MesquiteInteger io = new MesquiteInteger(0);
        int macroNumber = MesquiteInteger.fromString(arguments, io);
        if (macroNumber >= 0 && macroNumber < macros.size()) {
            MesquiteMacro macro = (MesquiteMacro) macros.elementAt(macroNumber);
            if (macro != null) {
                Puppeteer p = new Puppeteer(this);
                p.applyMacroFile(macro.getPath(), this);
            }
        }

        return null;
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "showWindow")) {
        if (getModuleWindow() != null) {
            getModuleWindow().setVisible(true, MesquiteThread.isScripting());
            //getModuleWindow().repaintAll();
        }
        return getModuleWindow();
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "showWindowForce")) {

        if (getModuleWindow() != null) {
            getModuleWindow().setVisible(true);
            getModuleWindow().getParentFrame().showFrontWindow();
            //getModuleWindow().repaint();
        }
        return getModuleWindow();
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "repaintWindow")) {
        if (getModuleWindow() != null) {
            getModuleWindow().repaintAll();
        }
        return null;
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "showFile")) {
        if (arguments == null)
            return null;
        FileCoordinator fc = getFileCoordinator();
        if (fc != null)
            return fc.displayFile(MesquiteFile.composePath(getProject().getHomeDirectoryName(),
                    parser.getFirstToken(arguments)), -1); //

    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "getFileCoordinator")) {
        return getFileCoordinator();
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "getProject")) {
        return getProject();
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "getProjectID")) {
        MesquiteProject proj = getProject();
        if (proj != null)
            return new MesquiteInteger((int) proj.getID());
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "getEmployee")) {
        MesquiteModule mb = findEmployeeWithName(parser.getFirstToken(arguments));
        return mb;
        //TODO: add getEmployeeWithDuty and pass duty class name
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "getImmediateEmployee")) {
        MesquiteModule mb = findEmployeeWithName(parser.getFirstToken(arguments), true);
        return mb;
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "hireEmployee")) {
        MesquiteModule mb = hireNamedEmployee(MesquiteModule.class, arguments);
        return mb;
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "notifyParametersChanged")) {
        parametersChanged();
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "fireEmployee")) {
        MesquiteModule mb = findEmployeeWithName(parser.getFirstToken(arguments));
        if (mb != null)
            fireEmployee(mb);
    } else if (checker.compare(MesquiteModule.class, null, null, commandName, "resign")) {
        iQuit();
    } else if (checker.getAccumulateMode()) {
        if (this instanceof CommandableOwner) {
            Commandable[] commandables = ((CommandableOwner) this).getCommandablesForAccumulation();

            for (int i = 0; commandables != null && i < commandables.length; i++) {
                checker.addString("<ul><li><strong>Commands for "
                        + getShortClassName(commandables[i].getClass()) + "</strong>");
                checker.accumulateOnlyFrom(commandables[i].getClass());
                commandables[i].doCommand(null, null, checker);//
                checker.addString("</ul>");
            }
        }
    } else {
        //AFTERDEMO:
        if (commandName != null && !checker.getAccumulateMode() && checker.warnIfNoResponse) {
            MesquiteMessage.warnProgrammer("Module " + getName() + " (" + (getClass().getName())
                    + ") did not respond to command " + commandName + " with arguments (" + arguments + ")");
        }
    }
    /* // the following should be place so that superclasses can respond to command, at least where latter is commandable
         else 
      return  super.doCommand(commandName, arguments, checker);
     */
    return null;
}

From source file:io.snappydata.hydra.cluster.SnappyTest.java

protected void executeSnappyStreamingJob(Vector jobClassNames, String logFileName) {
    String snappyJobScript = getScriptLocation("snappy-job.sh");
    String curlCommand1 = null, curlCommand2 = null, curlCommand3 = null, contextName = null, APP_PROPS = null;
    ProcessBuilder pb = null;//from   ww  w.j  a  v  a2s . c om
    File log = null;
    File logFile = null;
    userAppJar = SnappyPrms.getUserAppJar();
    snappyTest.verifyDataForJobExecution(jobClassNames, userAppJar);
    leadHost = getLeadHost();
    String leadPort = (String) SnappyBB.getBB().getSharedMap().get("primaryLeadPort");
    try {
        for (int i = 0; i < jobClassNames.size(); i++) {
            String userJob = (String) jobClassNames.elementAt(i);
            if (SnappyPrms.getCommaSepAPPProps() == null) {
                APP_PROPS = "shufflePartitions=" + SnappyPrms.getShufflePartitions();
            } else {
                APP_PROPS = SnappyPrms.getCommaSepAPPProps() + ",shufflePartitions="
                        + SnappyPrms.getShufflePartitions();
            }
            contextName = "snappyStreamingContext" + System.currentTimeMillis();
            String contextFactory = "org.apache.spark.sql.streaming.SnappyStreamingContextFactory";
            curlCommand1 = "curl --data-binary @" + snappyTest.getUserAppJarLocation(userAppJar, jarPath) + " "
                    + leadHost + ":" + leadPort + "/jars/myapp";
            curlCommand2 = "curl -d  \"\"" + " '" + leadHost + ":" + leadPort + "/" + "contexts/" + contextName
                    + "?context-factory=" + contextFactory + "'";
            curlCommand3 = "curl -d " + APP_PROPS + " '" + leadHost + ":" + leadPort
                    + "/jobs?appName=myapp&classPath=" + userJob + "&context=" + contextName + "'";
            pb = new ProcessBuilder("/bin/bash", "-c", curlCommand1);
            log = new File(".");
            String dest = log.getCanonicalPath() + File.separator + logFileName;
            logFile = new File(dest);
            snappyTest.executeProcess(pb, logFile);
            pb = new ProcessBuilder("/bin/bash", "-c", curlCommand2);
            snappyTest.executeProcess(pb, logFile);
            pb = new ProcessBuilder("/bin/bash", "-c", curlCommand3);
            snappyTest.executeProcess(pb, logFile);
        }
        snappyTest.getSnappyJobsStatus(snappyJobScript, logFile, leadPort);
    } catch (IOException e) {
        throw new TestException("IOException occurred while retriving destination logFile path " + log
                + "\nError Message:" + e.getMessage());
    }
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Creates all parent directories specified in a complete relative
 * pathname. Attempts to create existing directories will not cause
 * errors.//from  w  w w.jav  a 2s  .com
 *
 * @param ftp the FTP client instance to use to execute FTP actions on
 *        the remote server.
 * @param filename the name of the file whose parents should be created.
 * @throws IOException under non documented circumstances
 * @throws BuildException if it is impossible to cd to a remote directory
 *
 */
protected void createParents(FTPClient ftp, String filename) throws IOException, BuildException {

    File dir = new File(filename);
    if (dirCache.contains(dir)) {
        return;
    }

    Vector parents = new Vector();
    String dirname;

    while ((dirname = dir.getParent()) != null) {
        File checkDir = new File(dirname);
        if (dirCache.contains(checkDir)) {
            break;
        }
        dir = checkDir;
        parents.addElement(dir);
    }

    // find first non cached dir
    int i = parents.size() - 1;

    if (i >= 0) {
        String cwd = ftp.printWorkingDirectory();
        String parent = dir.getParent();
        if (parent != null) {
            if (!ftp.changeWorkingDirectory(resolveFile(parent))) {
                throw new BuildException("could not change to " + "directory: " + ftp.getReplyString());
            }
        }

        while (i >= 0) {
            dir = (File) parents.elementAt(i--);
            // check if dir exists by trying to change into it.
            if (!ftp.changeWorkingDirectory(dir.getName())) {
                // could not change to it - try to create it
                log("creating remote directory " + resolveFile(dir.getPath()), Project.MSG_VERBOSE);
                if (!ftp.makeDirectory(dir.getName())) {
                    handleMkDirFailure(ftp);
                }
                if (!ftp.changeWorkingDirectory(dir.getName())) {
                    throw new BuildException("could not change to " + "directory: " + ftp.getReplyString());
                }
            }
            dirCache.add(dir);
        }
        ftp.changeWorkingDirectory(cwd);
    }
}

From source file:org.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java

/**
 * Notifies the application components that a new current directory has been selected
 * /*from   w  ww  .j  a v  a2  s .co m*/
 * @param dir the directory that was selected, null is ignored
 */
public void notifySelectedDirectory(FileObject dir, String connectionId) throws FileSystemException {
    if (dir == null || connectionId == null)
        return;
    if (getCurrentDirectory() != null && dir.equals(getCurrentDirectory()))
        return;

    setCurrentDirectory(dir);
    setCurrentConnectionId(connectionId);

    //System.err.println("notifySelectedDirectory currentDirectory:" 
    //      + currentDirectory + " notify dir:" + dir );

    // Processing...
    VFSUtil.setUiStateListContents(shell, getCurrentDirectory().getName().toString());

    notifySelectedFiles(null);

    /* Table view:
     * Displays the contents of the selected directory.
     */
    workerUpdate(dir, connectionId, false);

    /* Combo view:
     * Sets the combo box to point to the selected directory.
     */
    final FileObject[] comboRoots = (FileObject[]) combo.getData(COMBODATA_ROOTS);
    int comboEntry = -1;
    if (comboRoots != null) {
        for (int i = 0; i < comboRoots.length; ++i) {
            if (dir.equals(comboRoots[i])) {
                comboEntry = i;
                break;
            }
        }
    }

    if (comboEntry == -1)
        combo.setText(dir.getName().toString());
    else
        combo.select(comboEntry);

    /* Tree view:
     * If not already expanded, recursively expands the parents of the specified
     * directory until it is visible.
     */
    Vector /* of FileObject */ path = new Vector();

    // Build a stack of paths from the root of the tree
    while (dir != null) {
        path.add(dir);
        //dir = dir.getParentFile();

        try {
            dir = dir.getParent();
        } catch (Exception e) {
            System.err.println("notifySelectedDirectory:" + e);
        }
    }

    //System.out.println("notifySelectedDirectory currentDirectory:" 
    //      + currentDirectory + " dir:" + dir + " tree path:" + path);

    // Recursively expand the tree to get to the specified directory
    TreeItem[] items = tree.getItems();
    TreeItem lastItem = null;
    String destConnectionId = null;
    TreeItem item = null;
    // filter by connection first
    for (int k = 0; k < items.length; ++k) {
        item = items[k];
        destConnectionId = (String) item.getData(TREEITEMDATA_CONNECTIONID);
        if (connectionId.equals(connectionId)) {
            items = items[k].getItems();
        }
    }

    for (int i = path.size() - 1; i >= 0; --i) {
        final FileObject pathElement = (FileObject) path.elementAt(i);

        // Search for a particular FileObject in the array of tree items
        // No guarantee that the items are sorted in any recognizable fashion, so we'll
        // just sequential scan.  There shouldn't be more than a few thousand entries.
        item = null;
        for (int k = 0; k < items.length; ++k) {
            item = items[k];
            if (item.isDisposed())
                continue;

            final String fileURI = ((String) item.getData(TREEITEMDATA_URI));
            destConnectionId = (String) item.getData(TREEITEMDATA_CONNECTIONID);

            // Resolving the children will attempt a server connection. This will hang the UI if the server is down
            // Thus perform a comparison by Host/Scheme/Path only
            // Cannot just compare the URI strings cuz FileObject hides the port number

            if (connectionId.equals(destConnectionId) && VFSUtil.compareURIs(fileURI, pathElement.toString()))
                break;
        }

        if (item == null)
            break;
        lastItem = item;

        if (i != 0 && !item.getExpanded()) {
            treeExpandItem(item);
            item.setExpanded(true);
        }
        items = item.getItems();
    }
    if (connectionId.equals(destConnectionId)) {
        tree.setSelection((lastItem != null) ? new TreeItem[] { lastItem } : new TreeItem[0]);
    }

    /* Shell:
     * Sets the title to indicate the selected directory
     */
    VFSUtil.setUiStateIdle(shell, VFSUtil.stripUserTokens(getCurrentDirectory().toString()));
}

From source file:io.snappydata.hydra.cluster.SnappyTest.java

public void executeSnappyJob(Vector jobClassNames, String logFileName, String userAppJar, String jarPath,
        String appName) {//from   w w  w  . j a  v  a  2s  . c o  m
    String snappyJobScript = getScriptLocation("snappy-job.sh");
    File log = null, logFile = null;
    //        userAppJar = SnappyPrms.getUserAppJar();
    if (appName == null)
        appName = SnappyPrms.getUserAppName();
    snappyTest.verifyDataForJobExecution(jobClassNames, userAppJar);
    leadHost = getLeadHost();
    String leadPort = (String) SnappyBB.getBB().getSharedMap().get("primaryLeadPort");
    Log.getLogWriter().info("primaryLead Port is : " + leadPort);
    try {
        for (int i = 0; i < jobClassNames.size(); i++) {
            String userJob = (String) jobClassNames.elementAt(i);
            String APP_PROPS = null;
            if (SnappyPrms.getCommaSepAPPProps() == null) {
                APP_PROPS = "logFileName=" + logFileName + ",shufflePartitions="
                        + SnappyPrms.getShufflePartitions();
            } else {
                APP_PROPS = SnappyPrms.getCommaSepAPPProps() + ",logFileName=" + logFileName
                        + ",shufflePartitions=" + SnappyPrms.getShufflePartitions();
            }
            String curlCommand1 = "curl --data-binary @" + snappyTest.getUserAppJarLocation(userAppJar, jarPath)
                    + " " + leadHost + ":" + leadPort + "/jars/" + appName;
            String curlCommand2 = "curl -d " + APP_PROPS + " '" + leadHost + ":" + leadPort + "/jobs?appName="
                    + appName + "&classPath=" + userJob + "'";
            ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", curlCommand1);
            log = new File(".");
            String dest = log.getCanonicalPath() + File.separator + logFileName;
            logFile = new File(dest);
            snappyTest.executeProcess(pb, logFile);
            pb = new ProcessBuilder("/bin/bash", "-c", curlCommand2);
            snappyTest.executeProcess(pb, logFile);
        }
        boolean retry = snappyTest.getSnappyJobsStatus(snappyJobScript, logFile, leadPort);
        if (retry && jobSubmissionCount <= SnappyPrms.getRetryCountForJob()) {
            jobSubmissionCount++;
            Thread.sleep(6000);
            Log.getLogWriter().info(
                    "Job failed due to primary lead node failover. Resubmitting the job to new primary lead node.....");
            retrievePrimaryLeadHost();
            HydraTask_executeSnappyJob();
        }
    } catch (IOException e) {
        throw new TestException("IOException occurred while retriving destination logFile path " + log
                + "\nError Message:" + e.getMessage());
    } catch (InterruptedException e) {
        throw new TestException(
                "Exception occurred while waiting for the snappy streaming job process re-execution."
                        + "\nError Message:" + e.getMessage());
    }
}

From source file:edu.ku.brc.af.core.expresssearch.SearchTableConfig.java

/**
 * This code is not my finest hour. What needs to be re-worked is not paring each term each time.
 * @param searchTerm/*from w ww  .j  av  a2s .  co m*/
 * @param idsOnly
 * @param ids
 * @return
 */
public String getSQL(final List<SearchTermField> terms, final boolean idsOnly, final Vector<Integer> ids,
        final boolean isHQL) {
    StringBuilder sqlStr = new StringBuilder("SELECT ");

    DBTableInfo ti = getTableInfo(); // this sets the data member tableInfo

    String primaryKey = ti.getIdFieldName();
    if (!isHQL) {
        primaryKey = primaryKey.substring(0, 1).toUpperCase() + primaryKey.substring(1, primaryKey.length());
        primaryKey = StringUtils.replace(primaryKey, "Id", "ID");
    }

    sqlStr.append("DISTINCT ");
    sqlStr.append(tableInfo.getAbbrev());
    sqlStr.append('.');
    sqlStr.append(primaryKey);

    if (!idsOnly) {
        for (DisplayFieldConfig field : displayFields) {
            sqlStr.append(',');
            sqlStr.append(tableInfo.getAbbrev());
            sqlStr.append('.');
            sqlStr.append(field.getFieldInfo().getName());

            if (field.getFieldInfo().isPartialDate()) {
                sqlStr.append(',');
                sqlStr.append(tableInfo.getAbbrev());
                sqlStr.append('.');
                sqlStr.append(field.getFieldInfo().getDatePrecisionName());
            }
        }
    }

    sqlStr.append(" FROM ");
    sqlStr.append(isHQL ? ti.getClassObj().getSimpleName() : ti.getName());
    sqlStr.append(" as ");
    sqlStr.append(tableInfo.getAbbrev());

    String joinSnipet = QueryAdjusterForDomain.getInstance().getJoinClause(tableInfo, isHQL,
            tableInfo.getAbbrev(), false);
    if (joinSnipet != null) {
        sqlStr.append(' ');
        sqlStr.append(joinSnipet);
        sqlStr.append(' ');
    }

    sqlStr.append(" WHERE ");

    boolean addParen = false;
    String sqlSnipet = QueryAdjusterForDomain.getInstance().getSpecialColumns(tableInfo, isHQL, false,
            tableInfo.getAbbrev());
    if (StringUtils.isNotEmpty(sqlSnipet)) {
        sqlStr.append(sqlSnipet);
        sqlStr.append(" AND (");
        addParen = true;
    }

    if (ids != null || terms.size() == 0) {
        int inListMax = 2500;
        int inI = 0;
        sqlStr.append("(");
        int i = 0;
        for (; i < ids.size(); i++) {
            if (inI == inListMax) {
                sqlStr.append(")");
                inI = 0;
            }
            if (inI == 0) {
                if (i > 0) {
                    sqlStr.append(" OR ");
                }
                sqlStr.append(tableInfo.getAbbrev());
                sqlStr.append('.');
                sqlStr.append(primaryKey);
                sqlStr.append(" IN (");
            }
            if (inI > 0)
                sqlStr.append(',');
            sqlStr.append(ids.elementAt(i).toString());

            inI++;
        }
        if (inI > 0) {
            sqlStr.append(")");
        }
        sqlStr.append(")");

    } /*else
      {
      String sqlSnipet = QueryAdjusterForDomain.getInstance().getSpecialColumns(tableInfo, isHQL, false, tableInfo.getAbbrev()); 
      if (sqlSnipet != null)
      {
          sqlStr.append(sqlSnipet);
          sqlStr.append(" AND (");
          addParen = true;
      }
      }*/

    StringBuilder orderBy = new StringBuilder();
    int orderByCnt = 0;

    //----------------------------------------------------------------------------------------------
    // NOTE: If a full date was type in and it was parsed as such
    // and it couldn't be something else, then it only searches date fields.
    //----------------------------------------------------------------------------------------------

    int cnt = 0;

    if (terms.size() > 0) {
        for (SearchTermField term : terms) {
            if (!term.isSingleChar()) {
                String termStr = term.getTermLowerCase();
                String abbrev = tableInfo.getAbbrev();

                for (SearchFieldConfig searchField : searchFields) {
                    String numericTermStr = null;
                    String clause = null;
                    DBFieldInfo fi = searchField.getFieldInfo();
                    boolean isFieldDate = fi.getDataClass() == Date.class
                            || searchField.getFieldInfo().getDataClass() == Calendar.class;
                    String fieldName = isHQL ? fi.getName() : fi.getColumn();

                    boolean isFormatted = false;
                    UIFieldFormatterIFace formatter = fi.getFormatter();

                    if (formatter != null) {
                        if (formatter.isNumeric()) {
                            isFormatted = term.isOn(SearchTermField.IS_NUMERIC)
                                    && !term.isOn(SearchTermField.HAS_DEC_POINT);
                            if (isFormatted) {
                                numericTermStr = (String) formatter.formatFromUI(termStr);
                            }

                        } else {
                            if (formatter.isLengthOK(termStr.length())) {
                                isFormatted = true;
                                if (!formatter.isValid(term.getTerm())) {
                                    continue;
                                }
                            }
                        }
                    }

                    if (ids == null) {
                        if (isFieldDate) {
                            boolean isDate = term.isOn(SearchTermField.IS_DATE);
                            if (isDate || term.isOn(SearchTermField.IS_YEAR_OF_DATE)) {
                                if (isDate) {
                                    if (isFieldDate) {
                                        clause = abbrev + '.' + fieldName + " = " + "'" + termStr + "'";
                                    } else {
                                        continue;
                                    }

                                } else {
                                    clause = "YEAR(" + abbrev + '.' + fi.getName() + ") = " + termStr;
                                }
                            } else {
                                continue;
                            }

                        } else {
                            if (fi.getDataClass() == Float.class || fi.getDataClass() == Double.class
                                    || fi.getDataClass() == BigDecimal.class) {
                                if (!term.isOn(SearchTermField.IS_NUMERIC)) {
                                    continue;
                                }
                                clause = fieldName + " = " + termStr;

                            } else if (fi.getDataClass() == Byte.class || fi.getDataClass() == Short.class
                                    || fi.getDataClass() == Integer.class || fi.getDataClass() == Long.class) {
                                if (!term.isOn(SearchTermField.IS_NUMERIC)
                                        || term.isOn(SearchTermField.HAS_DEC_POINT)) {
                                    continue;
                                }
                                clause = abbrev + '.' + fieldName + " = " + termStr;

                            } else if (isFormatted) {
                                clause = abbrev + '.' + fieldName + " = " + "'"
                                        + (numericTermStr != null ? numericTermStr : termStr) + "'";

                            } else {
                                clause = ESTermParser.getInstance().createWhereClause(term, abbrev, fieldName);

                                /*boolean startWildCard = term.isOn(SearchTermField.STARTS_WILDCARD);
                                boolean endWildCard   = term.isOn(SearchTermField.ENDS_WILDCARD);
                                if (startWildCard || endWildCard)
                                {
                                clause = "LOWER(" + abbrev + '.' + fieldName + ") LIKE " + (startWildCard ? "'%" : "'") + termStr + (endWildCard ? "%'" : "'");
                                } else
                                {
                                clause = "LOWER(" + abbrev + '.' + fieldName + ") = " + "'" + termStr + "'";
                                }*/
                            }
                        }

                        if (clause != null) {
                            if (cnt > 0)
                                sqlStr.append(" OR ");
                            sqlStr.append(clause);
                        }
                    }

                    cnt++;

                    if (!idsOnly) {
                        if (searchField.getIsSortable()) {
                            if (orderByCnt == 0) {
                                orderBy.append(" ORDER BY ");
                            } else {
                                orderBy.append(", ");
                            }
                            orderBy.append(abbrev);
                            orderBy.append('.');
                            orderBy.append(searchField.getFieldName());
                            orderBy.append(searchField.getIsAscending() ? " ASC" : " DESC");

                            orderByCnt++;
                        }
                    }
                }
            }
        }
    }

    if (addParen) {
        sqlStr.append(")");
    }

    if (cnt == 0 && terms.size() > 0) {
        return null;
    }

    if (orderByCnt > 0) {
        sqlStr.append(orderBy);
    }

    //System.err.println(sqlStr.toString());
    return sqlStr.toString();

}

From source file:com.ricemap.spateDB.core.RTree.java

/**
 * k nearest neighbor query Note: Current algorithm is approximate just for
 * simplicity. Writing an exact algorithm is on our TODO list
 * //from w  w  w.jav  a 2 s.  c o  m
 * @param qx
 * @param qy
 * @param k
 * @param output
 */
public int knn(final double qt, final double qx, final double qy, int k,
        final ResultCollector2<T, Double> output) {
    double query_area = ((getMBR().x2 - getMBR().x1) * (getMBR().y2 - getMBR().y1)) * k / getElementCount();
    double query_radius = Math.sqrt(query_area / Math.PI);

    boolean result_correct;
    final Vector<Double> distances = new Vector<Double>();
    final Vector<T> shapes = new Vector<T>();
    // Find results in the range and increase this range if needed to ensure
    // correctness of the answer
    do {
        // Initialize result and query range
        distances.clear();
        shapes.clear();
        Prism queryRange = new Prism();
        queryRange.x1 = qx - query_radius / 2;
        queryRange.y1 = qy - query_radius / 2;
        queryRange.x2 = qx + query_radius / 2;
        queryRange.y2 = qy + query_radius / 2;
        // Retrieve all results in range
        searchColumnar(queryRange, new ResultCollector<Writable>() {
            @Override
            public void collect(Writable shape) {
                distances.add(((T) shape).distanceTo(qt, qx, qy));
                shapes.add((T) ((T) shape).clone());
            }
        }, null);
        if (shapes.size() < k) {
            // Didn't find k elements in range, double the range to get more
            // items
            if (shapes.size() == getElementCount()) {
                // Already returned all possible elements
                result_correct = true;
            } else {
                query_radius *= 2;
                result_correct = false;
            }
        } else {
            // Sort items by distance to get the kth neighbor
            IndexedSortable s = new IndexedSortable() {
                @Override
                public void swap(int i, int j) {
                    double temp_distance = distances.elementAt(i);
                    distances.set(i, distances.elementAt(j));
                    distances.set(j, temp_distance);

                    T temp_shape = shapes.elementAt(i);
                    shapes.set(i, shapes.elementAt(j));
                    shapes.set(j, temp_shape);
                }

                @Override
                public int compare(int i, int j) {
                    // Note. Equality is not important to check because
                    // items with the
                    // same distance can be ordered anyway.
                    if (distances.elementAt(i) < distances.elementAt(j))
                        return -1;
                    return 1;
                }
            };
            IndexedSorter sorter = new QuickSort();
            sorter.sort(s, 0, shapes.size());
            if (distances.elementAt(k - 1) > query_radius) {
                result_correct = false;
                query_radius = distances.elementAt(k);
            } else {
                result_correct = true;
            }
        }
    } while (!result_correct);

    int result_size = Math.min(k, shapes.size());
    if (output != null) {
        for (int i = 0; i < result_size; i++) {
            output.collect(shapes.elementAt(i), distances.elementAt(i));
        }
    }
    return result_size;
}

From source file:net.sf.jabref.JabRef.java

public Optional<Vector<ParserResult>> processArguments(String[] args, boolean initialStartup) {

    cli = new JabRefCLI(args);

    if (!cli.isBlank() && cli.isDebugLogging()) {
        JabRefLogger.setDebug();//  w  w  w.j a va  2s  .co  m
    }

    if (initialStartup && cli.isShowVersion()) {
        cli.displayVersion();
    }

    if (initialStartup && cli.isHelp()) {
        cli.printUsage();
        return Optional.empty();
    }

    // Check if we should reset all preferences to default values:
    if (cli.isPreferencesReset()) {
        String value = cli.getPreferencesReset();
        if ("all".equals(value.trim())) {
            try {
                System.out.println(Localization.lang("Setting all preferences to default values."));
                Globals.prefs.clear();
            } catch (BackingStoreException e) {
                System.err.println(Localization.lang("Unable to clear preferences."));
                e.printStackTrace();
            }
        } else {
            String[] keys = value.split(",");
            for (String key : keys) {
                if (Globals.prefs.hasKey(key.trim())) {
                    System.out.println(Localization.lang("Resetting preference key '%0'", key.trim()));
                    Globals.prefs.clear(key.trim());
                } else {
                    System.out.println(Localization.lang("Unknown preference key '%0'", key.trim()));
                }
            }
        }

    }

    // Check if we should import preferences from a file:
    if (cli.isPreferencesImport()) {
        try {
            Globals.prefs.importPreferences(cli.getPreferencesImport());
            CustomEntryTypesManager.loadCustomEntryTypes(Globals.prefs);
            ExportFormats.initAllExports();
        } catch (JabRefException ex) {
            LOGGER.error("Cannot import preferences", ex);
        }
    }

    // Vector to put imported/loaded database(s) in.
    Vector<ParserResult> loaded = new Vector<>();
    Vector<String> toImport = new Vector<>();
    if (!cli.isBlank() && (cli.getLeftOver().length > 0)) {
        for (String aLeftOver : cli.getLeftOver()) {
            // Leftover arguments that have a "bib" extension are interpreted as
            // bib files to open. Other files, and files that could not be opened
            // as bib, we try to import instead.
            boolean bibExtension = aLeftOver.toLowerCase().endsWith("bib");
            ParserResult pr = null;
            if (bibExtension) {
                pr = JabRef.openBibFile(aLeftOver, false);
            }

            if ((pr == null) || (pr == ParserResult.INVALID_FORMAT)) {
                // We will try to import this file. Normally we
                // will import it into a new tab, but if this import has
                // been initiated by another instance through the remote
                // listener, we will instead import it into the current database.
                // This will enable easy integration with web browsers that can
                // open a reference file in JabRef.
                if (initialStartup) {
                    toImport.add(aLeftOver);
                } else {
                    loaded.add(JabRef.importToOpenBase(aLeftOver).orElse(ParserResult.INVALID_FORMAT));
                }
            } else if (pr != ParserResult.FILE_LOCKED) {
                loaded.add(pr);
            }

        }
    }

    if (!cli.isBlank() && cli.isFileImport()) {
        toImport.add(cli.getFileImport());
    }

    for (String filenameString : toImport) {
        importFile(filenameString).ifPresent(loaded::add);
    }

    if (!cli.isBlank() && cli.isImportToOpenBase()) {
        importToOpenBase(cli.getImportToOpenBase()).ifPresent(loaded::add);
    }

    if (!cli.isBlank() && cli.isFetcherEngine()) {
        fetch(cli.getFetcherEngine()).ifPresent(loaded::add);
    }

    if (cli.isExportMatches()) {
        if (!loaded.isEmpty()) {
            String[] data = cli.getExportMatches().split(",");
            String searchTerm = data[0].replace("\\$", " "); //enables blanks within the search term:
            //? stands for a blank
            ParserResult pr = loaded.elementAt(loaded.size() - 1);
            BibDatabase dataBase = pr.getDatabase();

            SearchQuery query = new SearchQuery(searchTerm,
                    Globals.prefs.getBoolean(JabRefPreferences.SEARCH_CASE_SENSITIVE),
                    Globals.prefs.getBoolean(JabRefPreferences.SEARCH_REG_EXP));
            BibDatabase newBase = new DatabaseSearcher(query, dataBase).getDatabaseFromMatches(); //newBase contains only match entries

            //export database
            if ((newBase != null) && (newBase.getEntryCount() > 0)) {
                String formatName;

                //read in the export format, take default format if no format entered
                switch (data.length) {
                case 3:
                    formatName = data[2];
                    break;
                case 2:
                    //default ExportFormat: HTML table (with Abstract & BibTeX)
                    formatName = "tablerefsabsbib";
                    break;
                default:
                    System.err.println(Localization.lang("Output file missing").concat(". \n \t ")
                            .concat(Localization.lang("Usage")).concat(": ")
                            + JabRefCLI.getExportMatchesSyntax());
                    return Optional.empty();
                } //end switch

                //export new database
                IExportFormat format = ExportFormats.getExportFormat(formatName);
                if (format == null) {
                    System.err.println(Localization.lang("Unknown export format") + ": " + formatName);
                } else {
                    // We have an ExportFormat instance:
                    try {
                        System.out.println(Localization.lang("Exporting") + ": " + data[1]);
                        format.performExport(newBase, pr.getMetaData(), data[1], pr.getEncoding(), null);
                    } catch (Exception ex) {
                        System.err.println(Localization.lang("Could not export file") + " '" + data[1] + "': "
                                + ex.getMessage());
                    }
                }
            } /*end if newBase != null*/ else {
                System.err.println(Localization.lang("No search matches."));
            }
        } else {
            System.err.println(Localization.lang("The output option depends on a valid input option."));
        } //end if(loaded.size > 0)
    }

    if (cli.isGenerateBibtexKeys()) {
        regenerateBibtexKeys(loaded);
    }

    if (cli.isAutomaticallySetFileLinks()) {
        automaticallySetFileLinks(loaded);
    }

    if (cli.isFileExport()) {
        if (!loaded.isEmpty()) {
            String[] data = cli.getFileExport().split(",");

            if (data.length == 1) {
                // This signals that the latest import should be stored in BibTeX
                // format to the given file.
                if (!loaded.isEmpty()) {
                    ParserResult pr = loaded.elementAt(loaded.size() - 1);
                    if (!pr.isInvalid()) {
                        try {
                            System.out.println(Localization.lang("Saving") + ": " + data[0]);
                            SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs);
                            Defaults defaults = new Defaults(BibDatabaseMode.fromPreference(
                                    Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_DEFAULT_MODE)));
                            BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
                            SaveSession session = databaseWriter.saveDatabase(
                                    new BibDatabaseContext(pr.getDatabase(), pr.getMetaData(), defaults),
                                    prefs);

                            // Show just a warning message if encoding didn't work for all characters:
                            if (!session.getWriter().couldEncodeAll()) {
                                System.err.println(Localization.lang("Warning") + ": " + Localization.lang(
                                        "The chosen encoding '%0' could not encode the following characters:",
                                        session.getEncoding().displayName()) + " "
                                        + session.getWriter().getProblemCharacters());
                            }
                            session.commit(new File(data[0]));
                        } catch (SaveException ex) {
                            System.err.println(Localization.lang("Could not save file.") + "\n"
                                    + ex.getLocalizedMessage());
                        }
                    }
                } else {
                    System.err
                            .println(Localization.lang("The output option depends on a valid import option."));
                }
            } else if (data.length == 2) {
                // This signals that the latest import should be stored in the given
                // format to the given file.
                ParserResult pr = loaded.elementAt(loaded.size() - 1);

                // Set the global variable for this database's file directory before exporting,
                // so formatters can resolve linked files correctly.
                // (This is an ugly hack!)
                File theFile = pr.getFile();
                if (!theFile.isAbsolute()) {
                    theFile = theFile.getAbsoluteFile();
                }
                MetaData metaData = pr.getMetaData();
                metaData.setFile(theFile);
                Globals.prefs.fileDirForDatabase = metaData.getFileDirectory(Globals.FILE_FIELD)
                        .toArray(new String[0]);
                Globals.prefs.databaseFile = metaData.getFile();
                System.out.println(Localization.lang("Exporting") + ": " + data[0]);
                IExportFormat format = ExportFormats.getExportFormat(data[1]);
                if (format == null) {
                    System.err.println(Localization.lang("Unknown export format") + ": " + data[1]);
                } else {
                    // We have an ExportFormat instance:
                    try {
                        format.performExport(pr.getDatabase(), pr.getMetaData(), data[0], pr.getEncoding(),
                                null);
                    } catch (Exception ex) {
                        System.err.println(Localization.lang("Could not export file") + " '" + data[0] + "': "
                                + ex.getMessage());
                    }
                }

            }
        } else {
            System.err.println(Localization.lang("The output option depends on a valid import option."));
        }
    }

    LOGGER.debug("Finished export");

    if (cli.isPreferencesExport()) {
        try {
            Globals.prefs.exportPreferences(cli.getPreferencesExport());
        } catch (JabRefException ex) {
            LOGGER.error("Cannot export preferences", ex);
        }
    }

    if (!cli.isBlank() && cli.isAuxImport()) {
        boolean usageMsg = false;

        if (!loaded.isEmpty()) // bibtex file loaded
        {
            String[] data = cli.getAuxImport().split(",");

            if (data.length == 2) {
                ParserResult pr = loaded.firstElement();
                AuxCommandLine acl = new AuxCommandLine(data[0], pr.getDatabase());
                BibDatabase newBase = acl.perform();

                boolean notSavedMsg = false;

                // write an output, if something could be resolved
                if (newBase != null) {
                    if (newBase.getEntryCount() > 0) {
                        String subName = StringUtil.getCorrectFileName(data[1], "bib");

                        try {
                            System.out.println(Localization.lang("Saving") + ": " + subName);
                            SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs);
                            BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
                            Defaults defaults = new Defaults(BibDatabaseMode.fromPreference(
                                    Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_DEFAULT_MODE)));
                            SaveSession session = databaseWriter
                                    .saveDatabase(new BibDatabaseContext(newBase, defaults), prefs);

                            // Show just a warning message if encoding didn't work for all characters:
                            if (!session.getWriter().couldEncodeAll()) {
                                System.err.println(Localization.lang("Warning") + ": " + Localization.lang(
                                        "The chosen encoding '%0' could not encode the following characters:",
                                        session.getEncoding().displayName()) + " "
                                        + session.getWriter().getProblemCharacters());
                            }
                            session.commit(new File(subName));
                        } catch (SaveException ex) {
                            System.err.println(Localization.lang("Could not save file.") + "\n"
                                    + ex.getLocalizedMessage());
                        }

                        notSavedMsg = true;
                    }
                }

                if (!notSavedMsg) {
                    System.out.println(Localization.lang("no database generated"));
                }
            } else {
                usageMsg = true;
            }
        } else {
            usageMsg = true;
        }

        if (usageMsg) {
            System.out.println(Localization.lang("no base-BibTeX-file specified") + "!");
            System.out.println(Localization.lang("usage") + " :");
            System.out.println("jabref --aux infile[.aux],outfile[.bib] base-BibTeX-file");
        }
    }

    return Optional.of(loaded);
}

From source file:gov.nih.nci.evs.browser.utils.DataUtils.java

public static String wrapWord(String line) {
    if (line == null)
        return null;
    if (line.indexOf(" ") != -1)
        return line;
    Vector v = parseData(line, "_");
    if (v.size() > 8) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            String t = (String) v.elementAt(i);
            buf.append(t + "_");
        }/*from  w  w w .j  a  va 2s. c om*/
        buf.append(" ");
        for (int i = 4; i < v.size(); i++) {
            String t = (String) v.elementAt(i);
            buf.append(t + "_");
        }
        String s = buf.toString();
        return s.substring(0, s.length() - 1);
    }
    return line;
}