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:org.apache.ws.security.components.crypto.CryptoBase.java

/**
 * Lookup X509 Certificates in the keystore according to a given DN of the subject of the certificate
 * <p/>//  ww  w.  j  av  a 2  s . c om
 * The search gets all alias names of the keystore and gets the certificate (chain)
 * for each alias. Then the DN of the certificate is compared with the parameters.
 *
 * @param subjectDN The DN of subject to look for in the keystore
 * @return Vector with all alias of certificates with the same DN as given in the parameters
 * @throws org.apache.ws.security.WSSecurityException
 *
 */
public String[] getAliasesForDN(String subjectDN) throws WSSecurityException {

    //
    // Convert the subject DN to a java X500Principal object first. This is to ensure
    // interop with a DN constructed from .NET, where e.g. it uses "S" instead of "ST".
    // Then convert it to a BouncyCastle X509Name, which will order the attributes of
    // the DN in a particular way (see WSS-168). If the conversion to an X500Principal
    // object fails (e.g. if the DN contains "E" instead of "EMAILADDRESS"), then fall
    // back on a direct conversion to a BC X509Name
    //
    Object subject;
    try {
        X500Principal subjectRDN = new X500Principal(subjectDN);
        subject = createBCX509Name(subjectRDN.getName());
    } catch (java.lang.IllegalArgumentException ex) {
        subject = createBCX509Name(subjectDN);
    }
    Vector aliases = getAlias(subject, keystore);

    //If we can't find the issuer in the keystore then look at cacerts
    if (aliases.size() == 0 && cacerts != null) {
        aliases = getAlias(subject, cacerts);
    }

    // Convert the vector into an array
    String[] result = new String[aliases.size()];
    for (int i = 0; i < aliases.size(); i++) {
        result[i] = (String) aliases.elementAt(i);
    }

    return result;
}

From source file:org.ecoinformatics.seek.dataquery.DBTablesGenerator.java

private synchronized void loadDataIntoTable(String tableName, Entity table, InputStream dataStream)
        throws SQLException, ClassNotFoundException, IllegalArgumentException, Exception {
    if (dataStream == null) {
        return;// w w  w.ja va2  s .  co  m
    }

    PreparedStatement pStatement = null;
    Connection conn = DatabaseFactory.getDBConnection();
    conn.setAutoCommit(false);
    try {
        String insertCommand = generateInsertCommand(tableName, table);
        pStatement = conn.prepareStatement(insertCommand);
        // int length = data.length;

        if (!table.getIsImageEntity() && table.isSimpleDelimited()) {
            // create SimpleDelimiter reader
            int numCols = table.getAttributes().length;
            String delimiter = table.getDelimiter();
            int numHeaderLines = table.getNumHeaderLines();
            String lineEnding = table.getPhysicalLineDelimiter();
            if (lineEnding == null || lineEnding.trim().equals("")) {
                lineEnding = table.getRecordDelimiter();
            }
            int numRecords = table.getNumRecords();
            boolean stripHeader = true;
            DelimitedReader simpleReader = new DelimitedReader(dataStream, numCols, delimiter, numHeaderLines,
                    lineEnding, numRecords, stripHeader);
            Vector row = simpleReader.getRowDataVectorFromStream();
            while (!row.isEmpty()) {
                // insert one row data into table
                int sizeOfRow = row.size();
                for (int j = 0; j < sizeOfRow; j++) {
                    String dataElement = (String) row.elementAt(j);
                    // get data type for the vector which already has the
                    // cloumn java
                    // type info after parsing attribute in private method
                    // parseAttributeList
                    String javaType = (String) dbJavaDataTypeList.elementAt(j);
                    // this method will binding data into preparedstatement
                    // base on
                    // java data type
                    // The index of pstatement start 1 (Not 0), so it should
                    // j+1.
                    pStatement = setupPreparedStatmentParameter(j + 1, pStatement, dataElement, javaType);

                }
                pStatement.execute();
                row = simpleReader.getRowDataVectorFromStream();
            }
        } else if (!table.getIsImageEntity() && !table.isSimpleDelimited()) {
            TextComplexFormatDataReader complexReader = new TextComplexFormatDataReader(dataStream, table);
            Vector row = complexReader.getRowDataVectorFromStream();
            while (!row.isEmpty()) {
                // insert one row data into table
                int sizeOfRow = row.size();
                for (int j = 0; j < sizeOfRow; j++) {
                    String dataElement = (String) row.elementAt(j);
                    dataElement = dataElement.trim();
                    // System.out.println("The data is "+ dataElement);
                    // get data type for the vector which already has the
                    // cloumn java
                    // type info after parsing attribute in private method
                    // parseAttributeList
                    String javaType = (String) dbJavaDataTypeList.elementAt(j);
                    // this method will binding data into preparedstatement
                    // base on
                    // java data type
                    // The index of pstatement start 1 (Not 0), so it should
                    // j+1.
                    pStatement = setupPreparedStatmentParameter(j + 1, pStatement, dataElement, javaType);

                }
                pStatement.execute();
                row = complexReader.getRowDataVectorFromStream();
            }
        }

    } catch (SQLException sqle) {
        conn.rollback();
        pStatement.close();
        conn.close();
        throw sqle;
    } catch (IllegalArgumentException le) {
        conn.rollback();
        pStatement.close();
        conn.close();
        throw le;
    } catch (Exception ue) {
        conn.rollback();
        pStatement.close();
        conn.close();
        throw ue;
    }
    conn.commit();
    pStatement.close();
    conn.close();
}

From source file:chibi.gemmaanalysis.LinkMatrix.java

/**
 * /*from   w  w w . j a va  2s  .  com*/
 */
public void outputStat() {
    int maxNum = 50;
    Vector<Integer> count = new Vector<Integer>(maxNum);
    for (int i = 0; i < maxNum; i++)
        count.add(0);
    for (int i = 0; i < this.linkCountMatrix.rows(); i++) {
        for (int j = i + 1; j < this.linkCountMatrix.columns(); j++) {
            int num = this.linkCountMatrix.bitCount(i, j);
            if (num == 0)
                continue;
            if (num > maxNum) {
                for (; maxNum < num; maxNum++)
                    count.add(0);
            }
            Integer tmpno = count.elementAt(num - 1);
            tmpno = tmpno + 1;
            count.setElementAt(tmpno, num - 1);
        }
    }
    for (int i = 0; i < count.size(); i++) {
        System.err.print(i + "[" + count.elementAt(i) + "] ");
        if (i % 10 == 0)
            System.err.println("");
    }
}

From source file:org.openxdata.server.sms.FormSmsParser.java

/**
 * Get the validation error messages in a filled form.
 * /* ww w  . j  a va  2 s  .  c  o m*/
 * @param formData the form data to validate.
 * @param ruleRequiredQtns a list of questions which become required after a firing of some rules.
 * @return a comma separated list of validation error messages if any, else null.
 */
@SuppressWarnings("unchecked")
private String getValidationErrorMsg(org.openxdata.model.FormData formData,
        Vector<QuestionData> ruleRequiredQtns) {
    String sErrors = null;

    //Check if form has any questions.
    Vector<PageData> pages = formData.getPages();
    if (pages == null || pages.size() == 0) {
        sErrors = MSG_FORM_HAS_NO_QUESTIONS;
        return sErrors;
    }

    //First get error messages for required fields which have not been answered
    //and answers not allowed for the data type.
    for (byte i = 0; i < pages.size(); i++) {
        PageData page = (PageData) pages.elementAt(i);
        for (byte j = 0; j < page.getQuestions().size(); j++) {
            QuestionData qtn = (QuestionData) page.getQuestions().elementAt(j);
            if (!ruleRequiredQtns.contains(qtn) && !qtn.isValid())
                sErrors = addErrorMsg(sErrors, MSG_ANSWER_REQUIRED_FOR + " " + qtn.getDef().getText());

            //Do data type validation
            String msg = getTypeErrorMsg(qtn);
            if (msg != null)
                sErrors = addErrorMsg(sErrors, msg);
        }
    }

    //Check if form has any validation rules.
    Vector<ValidationRule> rules = formData.getDef().getValidationRules();
    if (rules == null)
        return sErrors;

    //Deal with the user supplied validation rules
    for (int index = 0; index < rules.size(); index++) {
        ValidationRule rule = (ValidationRule) rules.elementAt(index);
        rule.setFormData(formData);
        if (!rule.isValid())
            sErrors = addErrorMsg(sErrors, rule.getErrorMessage());
    }

    return sErrors;
}

From source file:org.ecoinformatics.seek.datasource.eml.eml2.EML2MetadataSpecification.java

/**
 * This method will transfer ResultsetType java object to array of
 * ResultRecord java object. The ResultRecord object can be shown in kepler.
 * If the results is null or there is no record in the result, null will be
 * return/*from   www.  j  a v  a  2 s.c  om*/
 * 
 * @param ResultsetType
 *            results the result need to be transform
 * @param String
 *            endpoints the search end point
 * @return ResultRecord[] the resultrecord need be returned.
 */
public ResultRecord[] transformResultset(ResultsetType results, String endpoint, CompositeEntity container)
        throws SAXException, IOException, EcoGridException, NameDuplicationException, IllegalActionException {
    Eml200DataSource[] resultRecordArray = null;
    if (results == null) {
        return resultRecordArray;
    }

    // get titlstring and entity name string from configure file
    String titleReturnFieldString = null;
    String entityReturnFieldString = null;
    // xpath for config file
    String titlePath = "//" + ECOGRIDPATH + "/" + RETURNFIELDTYPELIST + "/" + RETURNFIELD + "[@" + NAMESPACE
            + "='" + namespace + "' and @" + RETURNFIELDTYPE + "='" + RETURNFIELDTITLE + "']";

    String entityPath = "//" + ECOGRIDPATH + "/" + RETURNFIELDTYPELIST + "/" + RETURNFIELD + "[@" + NAMESPACE
            + "='" + namespace + "' and @" + RETURNFIELDTYPE + "='" + RETURNFIELDENTITY + "']";

    List titlePathList = null;
    List entityPathList = null;

    //get the specific configuration we want
    ConfigurationProperty ecogridProperty = ConfigurationManager.getInstance()
            .getProperty(ConfigurationManager.getModule("ecogrid"));
    ConfigurationProperty returnFieldTypeList = ecogridProperty.getProperty("returnFieldTypeList");
    //findthe namespace properties
    List returnFieldTypeNamespaceList = returnFieldTypeList.findProperties(NAMESPACE, namespace, true);
    //find the properties out of the correct namespace properties that also have the correct returnfieldtype
    titlePathList = ConfigurationProperty.findProperties(returnFieldTypeNamespaceList, RETURNFIELDTYPE,
            RETURNFIELDTITLE, false);
    //get the value list for the properties
    titlePathList = ConfigurationProperty.getValueList(titlePathList, "value", true);

    if (titlePathList.isEmpty()) {
        log.debug("Couldn't get title from config Eml200EcoGridQueryTransfer.transformResultset");
        throw new EcoGridException("Couldn't get title returnfield from config");
    }

    entityPathList = ConfigurationProperty.findProperties(returnFieldTypeNamespaceList, RETURNFIELDTYPE,
            RETURNFIELDENTITY, false);
    //get the value list for the properties
    entityPathList = ConfigurationProperty.getValueList(entityPathList, "value", true);

    if (entityPathList.isEmpty()) {
        log.debug("Couldn't get entity returnfield from config Eml200EcoGridQueryTransfer.transformResultset");
        throw new EcoGridException("Couldn't get entity returnfield from config");
    }
    // only choose the first one in vector as title returnfied or
    // entityreturn
    // field
    titleReturnFieldString = (String) titlePathList.get(0);
    entityReturnFieldString = (String) entityPathList.get(0);

    // transfer ResultType to a vector of eml2resultsetItem and
    // sorted the vector
    Vector resultsetItemList = transformResultsetType(results, titleReturnFieldString, entityReturnFieldString);
    // transfer the sored vector (contains eml2resultsetitem object to an
    // array
    // of ResultRecord
    int arraySize = resultsetItemList.size();
    _numResults = arraySize;

    resultRecordArray = new Eml200DataSource[arraySize];
    Hashtable titleList = new Hashtable();// This hashtable is for keeping
    // track
    // if there is a duplicate title

    KeplerLSID EML200ActorLSID = null;
    for (int i = 0; i < arraySize; i++) {
        try {
            SortableResultRecord source = (SortableResultRecord) resultsetItemList.elementAt(i);
            String title = source.getTitle();
            log.debug("The title is " + title);
            String id = source.getId();
            log.debug("The id is " + id);
            Vector entityList = source.getEntityList();
            // if couldn't find id, skip this record
            if (id == null || id.trim().equals("")) {
                continue;
            }

            // if couldn't find title, assign a one to it -- <j>
            if (title == null || title.trim().equals("")) {
                title = "<" + i + ">";
            }
            if (titleList.containsKey(title)) {
                title = title + " " + i;
            }
            //make it unique in the result tree
            if (container.getEntity(title) != null) {
                String hint = "another service";
                if (endpoint.lastIndexOf("/") > -1) {
                    hint = endpoint.substring(endpoint.lastIndexOf("/") + 1);
                }
                title = title + " (" + hint + ")";
            }
            titleList.put(title, title);
            Eml200DataSource newRecord = new Eml200DataSource(container, title);
            newRecord.setRecordId(id);
            newRecord.setEndpoint(endpoint);
            newRecord.setNamespace(namespace);
            for (int j = 0; j < entityList.size(); j++) {
                String entityNameString = (String) entityList.elementAt(j);
                log.debug("The entiy name will be " + entityNameString);
                newRecord.addRecordDetail(entityNameString);

            }
            Eml200DataSource.generateDocumentationForInstance(newRecord);

            // look up EML200DataSource class LSID and create and add
            // NamedObjID attribute to instance
            if (EML200ActorLSID == null) {
                KARCacheManager kcm = KARCacheManager.getInstance();
                Vector<KARCacheContent> list = kcm.getKARCacheContents();
                for (KARCacheContent content : list) {
                    if (content.getCacheContent().getClassName().equals(Eml200DataSource.class.getName())) {
                        EML200ActorLSID = content.getLsid();
                    }
                }
            }
            NamedObjId lsidSA = new NamedObjId(newRecord, NamedObjId.NAME);
            lsidSA.setExpression(EML200ActorLSID);

            resultRecordArray[i] = newRecord;
        } catch (Exception e) {
            continue;
        }
    } // for
    return resultRecordArray;
}

From source file:dao.PblogMessageDaoDb.java

private int getNodeLevel(String rid, Vector msgs, Blog pBlogMsg) {
    if (RegexStrUtil.isNull(rid) || (msgs == null) || (pBlogMsg == null)) {
        throw new BaseDaoException("params are null");
    }/*from ww w .  j  a v  a  2  s  .  co m*/

    int j = 0;
    Iterator iterator = msgs.iterator();
    if (rid != null) {
        while (iterator.hasNext()) {
            Vector replies = (Vector) iterator.next();
            if (replies == null) {
                //logger.info("replies is null ");
                continue;
            }
            for (int i = 0; i < replies.size(); i++) {
                if (rid.equalsIgnoreCase(((Blog) replies.elementAt(i)).getValue(DbConstants.REPLY_ID))) {
                    String levelStr = ((Blog) replies.elementAt(i)).getValue(DbConstants.LEVEL);

                    //logger.info("level = " + levelStr + "msgs rid " + ((Blog)replies.elementAt(i)).getValue(DbConstants.MESSAGE_ID) );
                    if (levelStr != null) {
                        Integer level = new Integer(levelStr);
                        //logger.info("level Integer = " + level);
                        level++;
                        //logger.info("level Integer = " + level.toString() + " j = " + j);
                        pBlogMsg.setValue("level", level.toString());
                    }
                    return (j + 1);
                }
            }
            j++;
        }
    }
    return -1;
}

From source file:uk.ac.leeds.ccg.andyt.projects.moses.process.RegressionReport_UK1.java

public void writeAggregateStatisticsForOptimisationConstraints_HSARHP_ISARCEP(String a_OutputDir_String)
        throws Exception {
    HashMap a_HID_HSARDataRecordVector_HashMap = _HSARDataHandler.get_HID_HSARDataRecordVector_HashMap();
    HashMap a_ID_RecordID_HashMap = _ISARDataHandler.get_ID_RecordID_HashMap();
    File optimisationConstraints_SARs = new File(a_OutputDir_String, "OptimisationConstraints_SARs.csv");
    FileOutputStream a_FileOutputStream = new FileOutputStream(optimisationConstraints_SARs);
    OutputDataHandler_OptimisationConstraints.writeHSARHP_ISARCEPHeader(a_FileOutputStream);
    a_FileOutputStream.flush();/*from  www.j a  va2s.  c o  m*/
    HashMap<String, Integer> a_SARCounts = null;
    CASDataRecord a_CASDataRecord;
    TreeSet<String> a_LADCodes_TreeSet = _CASDataHandler.getLADCodes_TreeSet();
    String s2;
    String s1;
    Iterator<String> a_Iterator_String = a_LADCodes_TreeSet.iterator();
    while (a_Iterator_String.hasNext()) {
        // Need to reorder data for each LAD as OAs not necessarily returned
        // in any order and an ordered result is wanted
        TreeMap<String, HashMap<String, Integer>> resultsForLAD = new TreeMap<String, HashMap<String, Integer>>();
        boolean setPrevious_OA_String = true;
        s1 = a_Iterator_String.next();
        s2 = s1.substring(0, 3);
        File resultsFile = new File(a_OutputDir_String + s2 + "/" + s1 + "/population.csv");
        // A few results are missing
        if (resultsFile.exists()) {
            System.out.println(resultsFile.toString() + " exists");
            String previous_OA_String = "";
            BufferedReader aBufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(resultsFile)));
            StreamTokenizer aStreamTokenizer = new StreamTokenizer(aBufferedReader);
            Generic_StaticIO.setStreamTokenizerSyntax1(aStreamTokenizer);
            String line = "";
            int tokenType = aStreamTokenizer.nextToken();
            while (tokenType != StreamTokenizer.TT_EOF) {
                switch (tokenType) {
                case StreamTokenizer.TT_EOL:
                    //System.out.println(line);
                    String[] lineFields = line.split(",");
                    String a_OA_String = lineFields[0];
                    if (previous_OA_String.equalsIgnoreCase(a_OA_String)) {
                        if (lineFields[1].equalsIgnoreCase("HP")) {
                            //System.out.println("HP");
                            // From the id of a household get a Vector 
                            // of HSARDataRecords
                            Vector household = (Vector) a_HID_HSARDataRecordVector_HashMap
                                    .get(new Integer(lineFields[2]));
                            HSARDataRecord a_HSARDataRecord;
                            for (int i = 0; i < household.size(); i++) {
                                a_HSARDataRecord = (HSARDataRecord) household.elementAt(i);
                                GeneticAlgorithm_HSARHP_ISARCEP.addToCounts(a_HSARDataRecord, a_SARCounts,
                                        _Random);
                            }
                            //System.out.println(a_HSARDataRecord.toString());
                        } else {
                            //System.out.println("CEP");
                            // From the id of the ISARDataRecord get the
                            // ISARRecordID.
                            long a_ISARRecordID = (Long) a_ID_RecordID_HashMap.get(new Long(lineFields[2]));
                            ISARDataRecord a_ISARDataRecord = _ISARDataHandler
                                    .getISARDataRecord(a_ISARRecordID);
                            GeneticAlgorithm_HSARHP_ISARCEP.addToCountsCEP(a_ISARDataRecord, a_SARCounts,
                                    _Random);
                        }
                    } else {
                        // Store result
                        if (setPrevious_OA_String) {
                            previous_OA_String = a_OA_String;
                            setPrevious_OA_String = false;
                        } else {
                            // Store
                            resultsForLAD.put(previous_OA_String, a_SARCounts);
                        }
                        // Initialise/Re-initialise
                        a_CASDataRecord = (CASDataRecord) _CASDataHandler.getDataRecord(a_OA_String);
                        Object[] fitnessCounts = GeneticAlgorithm_HSARHP_ISARCEP
                                .getFitnessCounts(a_CASDataRecord);
                        a_SARCounts = (HashMap<String, Integer>) fitnessCounts[1];
                        // Start a new aggregation
                        if (lineFields[1].equalsIgnoreCase("HP")) {
                            //System.out.println("HP");
                            // From the id of a household get a Vector
                            // of HSARDataRecords
                            Vector household = (Vector) a_HID_HSARDataRecordVector_HashMap
                                    .get(new Integer(lineFields[2]));
                            HSARDataRecord a_HSARDataRecord;
                            for (int i = 0; i < household.size(); i++) {
                                a_HSARDataRecord = (HSARDataRecord) household.elementAt(i);
                                GeneticAlgorithm_HSARHP_ISARCEP.addToCounts(a_HSARDataRecord, a_SARCounts,
                                        _Random);
                            }
                            //System.out.println(a_HSARDataRecord.toString());
                        } else {
                            //System.out.println("CEP");
                            // From the id of the ISARDataRecord get the
                            // ISARRecordID.
                            long a_ISARRecordID = (Long) a_ID_RecordID_HashMap.get(new Long(lineFields[2]));
                            ISARDataRecord a_ISARDataRecord = _ISARDataHandler
                                    .getISARDataRecord(a_ISARRecordID);
                            GeneticAlgorithm_HSARHP_ISARCEP.addToCountsCEP(a_ISARDataRecord, a_SARCounts,
                                    _Random);
                            //System.out.println(a_ISARDataRecord.toString());
                        }
                        //a_OA_String = lineFields[0];
                    }
                    previous_OA_String = a_OA_String;
                    break;
                case StreamTokenizer.TT_WORD:
                    line = aStreamTokenizer.sval;
                    break;
                }
                tokenType = aStreamTokenizer.nextToken();
            }
        } else {
            System.out.println(resultsFile.toString() + " !exists");
        }
        Iterator<String> string_Iterator = resultsForLAD.keySet().iterator();
        while (string_Iterator.hasNext()) {
            String oa_Code = string_Iterator.next();
            OutputDataHandler_OptimisationConstraints.writeHSARHP_ISARCEP(resultsForLAD.get(oa_Code), oa_Code,
                    a_FileOutputStream);
        }
    }
    a_FileOutputStream.close();
}

From source file:charva.awt.Window.java

/**
 * Process an event off the event queue.  This method can be extended by
 * subclasses of Window to deal with application-specific events.
 *///w w  w .  j  a  v a  2s  .c  om
protected void processEvent(AWTEvent evt_) {
    Object source = evt_.getSource();

    if (evt_ instanceof AdjustmentEvent)
        ((Adjustable) source).processAdjustmentEvent((AdjustmentEvent) evt_);

    else if (evt_ instanceof ScrollEvent) {
        ((Scrollable) source).processScrollEvent((ScrollEvent) evt_);
        requestFocus();
        super.requestSync();
    } else if (evt_ instanceof PaintEvent) {

        /* Unless the affected component is totally obscured by
         * windows that are stacked above it, we must redraw its
         * window and all the windows above it.
         */
        if (!((Component) source).isTotallyObscured()) {

            Vector windowlist = _term.getWindowList();
            synchronized (windowlist) {

                /* We have to draw the window rather than just the affected
                 * component, because setVisible(false) may have been set on
                 * the component.
                 */
                Window ancestor = ((Component) source).getAncestorWindow();
                ancestor.draw();

                /* Ignore windows that are underneath the window that
                 * contains the component that generated the PaintEvent.
                 */
                Window w = null;
                int i;
                for (i = 0; i < windowlist.size(); i++) {
                    w = (Window) windowlist.elementAt(i);
                    if (w == ancestor)
                        break;
                }

                /* Redraw all the windows _above_ the one that generated
                 * the PaintEvent.
                 */
                for (; i < windowlist.size(); i++) {
                    w = (Window) windowlist.elementAt(i);
                    w.draw();
                }
            }

            super.requestSync();
        }
    } else if (evt_ instanceof SyncEvent) {
        _term.sync();
    } else if (evt_ instanceof WindowEvent) {
        WindowEvent we = (WindowEvent) evt_;
        we.getWindow().processWindowEvent(we);

        /* Now, having given the WindowListener objects a chance to
         * process the WindowEvent, we must check if it was a
         * WINDOW_CLOSING event sent to this window.
         */
        if (we.getID() == AWTEvent.WINDOW_CLOSING) {

            we.getWindow()._windowClosed = true;

            /* Remove this window from the list of those displayed,
             * and blank out the screen area where the window was
             * displayed.
             */
            _term.removeWindow(we.getWindow());
            _term.blankBox(_origin, _size);

            /* Now redraw all of the windows, from the bottom to the
             * top.
             */
            Vector winlist = _term.getWindowList();
            Window window = null;
            synchronized (winlist) {
                for (int i = 0; i < winlist.size(); i++) {
                    window = (Window) winlist.elementAt(i);
                    window.draw();
                }
                if (window != null) // (there may be no windows left)
                    window.requestFocus();
            }

            /* Put a SyncEvent onto the SyncQueue.  The SyncThread will
             * sleep for 50 msec before putting it onto the EventQueue,
             * from which it will be picked up by the active Window
             * (i.e. an instance of this class), which will then call
             * Toolkit.sync() directly.  This is done to avoid calling
             * sync() after the close of a window and again after the
             * display of a new window which might be displayed
             * immediately afterwards.
             */
            if (window != null)
                SyncQueue.getInstance().postEvent(new SyncEvent(window));
        }
    } // end if WindowEvent
    else if (evt_ instanceof GarbageCollectionEvent) {
        SyncQueue.getInstance().postEvent(evt_);
    } else if (evt_ instanceof InvocationEvent) {
        ((InvocationEvent) evt_).dispatch();
    } else {
        /* It is a KeyEvent, MouseEvent, ActionEvent, ItemEvent,
         * FocusEvent or a custom type of event.
         */
        ((Component) source).processEvent(evt_);
    }
}

From source file:com.granule.json.utils.internal.JSONObject.java

/**
 * Internal method to write out all children JSON objects attached to this JSON object.
 * @param writer The writer to use while writing the JSON text.
 * @param depth The indention depth of the JSON text.
 * @param compact Flag to denote whether or not to write in nice indent format, or compact format.
 * @throws IOException Trhown if an error occurs on write.
 *//*from  ww w  .j a  va2s.co  m*/
private void writeChildren(Writer writer, int depth, boolean compact) throws IOException {
    if (logger.isLoggable(Level.FINER))
        logger.entering(className, "writeChildren(Writer, int, boolean)");

    if (!jsonObjects.isEmpty()) {
        Enumeration keys = jsonObjects.keys();
        while (keys.hasMoreElements()) {
            String objName = (String) keys.nextElement();
            Vector vect = (Vector) jsonObjects.get(objName);
            if (vect != null && !vect.isEmpty()) {
                /**
                 * Non-array versus array elements.
                 */
                if (vect.size() == 1) {
                    if (logger.isLoggable(Level.FINEST))
                        logger.logp(Level.FINEST, className, "writeChildren(Writer, int, boolean)",
                                "Writing child object: [" + objName + "]");

                    JSONObject obj = (JSONObject) vect.elementAt(0);
                    obj.writeObject(writer, depth + 1, false, compact);
                    if (keys.hasMoreElements()) {
                        try {
                            if (!compact) {
                                if (!obj.isTextOnlyObject() && !obj.isEmptyObject()) {
                                    writeIndention(writer, depth + 1);
                                }
                                writer.write(",\n");
                            } else {
                                writer.write(",");
                            }
                        } catch (Exception ex) {
                            IOException iox = new IOException("Error occurred on serialization of JSON text.");
                            iox.initCause(ex);
                            throw iox;
                        }
                    } else {
                        if (obj.isTextOnlyObject() && !compact) {
                            writer.write("\n");
                        }
                    }
                } else {
                    if (logger.isLoggable(Level.FINEST))
                        logger.logp(Level.FINEST, className, "writeChildren(Writer, int, boolean)",
                                "Writing array of JSON objects with attribute name: [" + objName + "]");

                    try {
                        if (!compact) {
                            writeIndention(writer, depth + 1);
                            writer.write("\"" + objName + "\"");
                            writer.write(" : [\n");
                        } else {
                            writer.write("\"" + objName + "\"");
                            writer.write(":[");
                        }
                        for (int i = 0; i < vect.size(); i++) {
                            JSONObject obj = (JSONObject) vect.elementAt(i);
                            obj.writeObject(writer, depth + 2, true, compact);

                            /**
                             * Still more we haven't handled.
                             */
                            if (i != (vect.size() - 1)) {
                                if (!compact) {
                                    if (!obj.isTextOnlyObject() && !obj.isEmptyObject()) {
                                        writeIndention(writer, depth + 2);
                                    }
                                    writer.write(",\n");
                                } else {
                                    writer.write(",");
                                }
                            }
                        }

                        if (!compact) {
                            writer.write("\n");
                            writeIndention(writer, depth + 1);
                        }

                        writer.write("]");
                        if (keys.hasMoreElements()) {
                            writer.write(",");
                        }

                        if (!compact) {
                            writer.write("\n");
                        }
                    } catch (Exception ex) {
                        IOException iox = new IOException("Error occurred on serialization of JSON text.");
                        iox.initCause(ex);
                        throw iox;
                    }
                }
            }
        }
    }

    if (logger.isLoggable(Level.FINER))
        logger.exiting(className, "writeChildren(Writer, int, boolean)");
}

From source file:com.cloudbase.CBHelper.java

/**
 * Runs a search over a collection and applies the given list of aggregation commands to the output.
 * @param collection The name of the collection to run the search over
 * @param aggregateConditions A List of CBDataAggregationCommand objects
 * @param handler a block of code to be executed once the request is completed
 *//*from  www  .  jav  a2  s.  c o  m*/
public void searchDocumentAggregate(String collection, Vector aggregateConditions,
        CBHelperResponder responder) {
    JSONArray serializedAggregateConditions = new JSONArray();
    try {
        for (int i = 0; i < aggregateConditions.size(); i++) {
            CBDataAggregationCommand curComm = (CBDataAggregationCommand) aggregateConditions.elementAt(i);

            JSONObject curSerializedCondition = new JSONObject();
            curSerializedCondition.put(curComm.getCommandType(), curComm.serializeAggregateConditions());

            serializedAggregateConditions.put(curSerializedCondition);
        }

        String url = this.getUrl() + this.appCode + "/" + collection + "/aggregate";

        JSONObject paramsToPrepare = new JSONObject();
        paramsToPrepare.put("cb_aggregate_key", serializedAggregateConditions);

        Hashtable preparedPost = this.preparePostParams(paramsToPrepare, null);
        CBHelperRequest req = new CBHelperRequest(url, "data");
        req.setPostData(preparedPost);
        req.setResponder(responder);

        this.getApplicationRefernce().invokeLater(req);
    } catch (Exception e) {
        e.printStackTrace();
    }
}