Example usage for java.util Vector insertElementAt

List of usage examples for java.util Vector insertElementAt

Introduction

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

Prototype

public synchronized void insertElementAt(E obj, int index) 

Source Link

Document

Inserts the specified object as a component in this vector at the specified index .

Usage

From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java

/**
 * @param taxonList//from w ww.jav  a 2  s. co  m
 * @param colNameHash
 * @param taxonTreeDef
 * @param taxonDefXML
 * @return
 */
@SuppressWarnings("unchecked")
public boolean createTaxonDefFromXML(final List<Object> taxonList, final HashSet<String> colNameHash,
        final TaxonTreeDef taxonTreeDef, final String taxonDefXML) {
    if (StringUtils.isNotEmpty(taxonDefXML)) {
        XStream xstream = new XStream();
        TreeDefRow.configXStream(xstream);

        Vector<TreeDefRow> treeDefList = (Vector<TreeDefRow>) xstream.fromXML(taxonDefXML);

        if (colNameHash != null) {
            Hashtable<String, TreeDefItemStandardEntry> stdTreeLevelsHash = new Hashtable<String, TreeDefItemStandardEntry>();
            for (TreeDefItemStandardEntry entry : TaxonTreeDef.getStandardLevelsStatic()) {
                stdTreeLevelsHash.put(entry.getName().toLowerCase(), entry);
            }

            Hashtable<String, TreeDefRow> xmlTreeLevelsHash = new Hashtable<String, TreeDefRow>();
            for (TreeDefRow row : treeDefList) {
                xmlTreeLevelsHash.put(row.getDefName().toLowerCase(), row);
            }

            for (String columnName : colNameHash) {
                String colName = columnName.toLowerCase();

                TreeDefRow treeDefRow = xmlTreeLevelsHash.get(colName);
                if (treeDefRow == null) {
                    log.debug(colName + " NOT found in XML, checking std.");
                    TreeDefItemStandardEntry entry = stdTreeLevelsHash.get(colName);
                    if (entry != null) {
                        for (int i = 0; i < treeDefList.size(); i++) {
                            if (i < treeDefList.size() && entry.getRank() < treeDefList.get(i).getRank()) {
                                log.debug(String.format("Adding '%s' as rank %d.", colName, entry.getRank()));
                                TreeDefRow newRow = new TreeDefRow(entry.getName(), entry.getTitle(),
                                        entry.getRank(), true, // included
                                        false, // enforced
                                        false, // is in Full Name 
                                        false, // is required 
                                        ",");
                                treeDefList.insertElementAt(newRow, i);
                                break;
                            }
                        }
                    } else {
                        //showLocalizedError("The wizard was unable to find '%s' as a standard Taxonomy level.", colName);
                        log.debug(String.format(
                                "The wizard was unable to find '%s' as a standard Taxonomy level.", colName));
                    }
                } else {
                    log.debug(colName + " found in XML");
                }
            }

            for (TreeDefRow row : treeDefList) {
                log.debug(row.getDefName() + "  " + row.getTitle() + "  " + row.getRank());
            }
        }

        TaxonTreeDefItem ttdiRoot = null;
        Taxon txRoot = null;

        TaxonTreeDefItem parent = null;
        int cnt = 0;
        for (TreeDefRow row : treeDefList) {
            if (row.isIncluded() || (row.getDefName() != null
                    && (colNameHash == null || colNameHash.contains(row.getDefName().toLowerCase())))) {
                TaxonTreeDefItem ttdi = new TaxonTreeDefItem();
                ttdi.initialize();
                ttdi.setTreeDef(taxonTreeDef);
                taxonTreeDef.getTreeDefItems().add(ttdi);
                ttdi.setName(row.getDefName());
                ttdi.setTitle(row.getTitle());
                ttdi.setRankId(row.getRank());
                ttdi.setParent(parent);
                ttdi.setFullNameSeparator(row.getSeparator());
                ttdi.setIsEnforced(row.isEnforced());
                ttdi.setIsInFullName(row.isInFullName());

                taxonList.add(ttdi);

                if (cnt == 0) {
                    ttdiRoot = ttdi;

                    Taxon tx = new Taxon();
                    tx.initialize();
                    tx.setDefinition(taxonTreeDef);
                    tx.setDefinitionItem(ttdi);
                    ttdi.getTreeEntries().add(tx);
                    tx.setName(getResourceString("Life"));
                    tx.setFullName(tx.getName());
                    tx.setNodeNumber(1);
                    tx.setHighestChildNodeNumber(1);
                    //tx.setIsAccepted(true);

                    txRoot = tx;
                }

                if (parent != null) {
                    parent.getChildren().add(ttdi);
                }
                parent = ttdi;
                cnt++;
            }
        }

        if (ttdiRoot != null)
            persist(ttdiRoot);
        if (txRoot != null)
            persist(txRoot);

    }
    return true;
}

From source file:org.apache.hadoop.fs.DistributedFSCheck.java

private void analyzeResult(long execTime, String resFileName, boolean viewStats) throws IOException {
    Path reduceFile = new Path(READ_DIR, "part-00000");
    DataInputStream in;/*  ww w  .j a  v a  2s.  c  om*/
    in = new DataInputStream(fs.open(reduceFile));

    BufferedReader lines;
    lines = new BufferedReader(new InputStreamReader(in));
    long blocks = 0;
    long size = 0;
    long time = 0;
    float rate = 0;
    StringTokenizer badBlocks = null;
    long nrBadBlocks = 0;
    String line;
    while ((line = lines.readLine()) != null) {
        StringTokenizer tokens = new StringTokenizer(line, " \t\n\r\f%");
        String attr = tokens.nextToken();
        if (attr.endsWith("blocks"))
            blocks = Long.parseLong(tokens.nextToken());
        else if (attr.endsWith("size"))
            size = Long.parseLong(tokens.nextToken());
        else if (attr.endsWith("time"))
            time = Long.parseLong(tokens.nextToken());
        else if (attr.endsWith("rate"))
            rate = Float.parseFloat(tokens.nextToken());
        else if (attr.endsWith("badBlocks")) {
            badBlocks = new StringTokenizer(tokens.nextToken(), ";");
            nrBadBlocks = badBlocks.countTokens();
        }
    }

    Vector<String> resultLines = new Vector<String>();
    resultLines.add("----- DistributedFSCheck ----- : ");
    resultLines.add("               Date & time: " + new Date(System.currentTimeMillis()));
    resultLines.add("    Total number of blocks: " + blocks);
    resultLines.add("    Total number of  files: " + nrFiles);
    resultLines.add("Number of corrupted blocks: " + nrBadBlocks);

    int nrBadFilesPos = resultLines.size();
    TreeSet<String> badFiles = new TreeSet<String>();
    long nrBadFiles = 0;
    if (nrBadBlocks > 0) {
        resultLines.add("");
        resultLines.add("----- Corrupted Blocks (file@offset) ----- : ");
        while (badBlocks.hasMoreTokens()) {
            String curBlock = badBlocks.nextToken();
            resultLines.add(curBlock);
            badFiles.add(curBlock.substring(0, curBlock.indexOf('@')));
        }
        nrBadFiles = badFiles.size();
    }

    resultLines.insertElementAt(" Number of corrupted files: " + nrBadFiles, nrBadFilesPos);

    if (viewStats) {
        resultLines.add("");
        resultLines.add("-----   Performance  ----- : ");
        resultLines.add("         Total MBytes read: " + size / MEGA);
        resultLines.add("         Throughput mb/sec: " + (float) size * 1000.0 / (time * MEGA));
        resultLines.add("    Average IO rate mb/sec: " + rate / 1000 / blocks);
        resultLines.add("        Test exec time sec: " + (float) execTime / 1000);
    }

    PrintStream res = new PrintStream(new FileOutputStream(new File(resFileName), true));
    for (int i = 0; i < resultLines.size(); i++) {
        String cur = resultLines.get(i);
        LOG.info(cur);
        res.println(cur);
    }
}

From source file:org.apache.ws.security.components.crypto.CryptoBase.java

/**
 * get a byte array given an array of X509 certificates.
 * <p/>/*from  w  w  w . j  ava 2s .  c  o  m*/
 *
 * @param reverse If set the first certificate in the array data will
 *                the last in the byte array
 * @param certs   The certificates to convert
 * @return The byte array for the certificates ordered according
 *         to the reverse flag
 * @throws WSSecurityException
 */
public byte[] getCertificateData(boolean reverse, X509Certificate[] certs) throws WSSecurityException {
    Vector list = new Vector();
    for (int i = 0; i < certs.length; i++) {
        if (reverse) {
            list.insertElementAt(certs[i], 0);
        } else {
            list.add(certs[i]);
        }
    }
    try {
        CertPath path = getCertificateFactory().generateCertPath(list);
        return path.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError", null, e);
    } catch (CertificateException e) {
        throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "parseError", null, e);
    }
}

From source file:org.rhq.bundle.ant.AntMain.java

/**
 * Prints a list of all targets in the specified project to
 * <code>System.out</code>, optionally including subtargets.
 *
 * @param project The project to display a description of.
 *                Must not be <code>null</code>.
 * @param printSubTargets Whether or not subtarget names should also be
 *                        printed.//from  ww w.ja  va2s . co m
 */
private static void printTargets(Project project, boolean printSubTargets) {
    // find the target with the longest name
    int maxLength = 0;
    Map ptargets = removeDuplicateTargets(project.getTargets());
    String targetName;
    String targetDescription;
    Target currentTarget;
    // split the targets in top-level and sub-targets depending
    // on the presence of a description
    Vector topNames = new Vector();
    Vector topDescriptions = new Vector();
    Vector subNames = new Vector();

    for (Iterator i = ptargets.values().iterator(); i.hasNext();) {
        currentTarget = (Target) i.next();
        targetName = currentTarget.getName();
        if (targetName.equals("")) {
            continue;
        }
        targetDescription = currentTarget.getDescription();
        // maintain a sorted list of targets
        if (targetDescription == null) {
            int pos = findTargetPosition(subNames, targetName);
            subNames.insertElementAt(targetName, pos);
        } else {
            int pos = findTargetPosition(topNames, targetName);
            topNames.insertElementAt(targetName, pos);
            topDescriptions.insertElementAt(targetDescription, pos);
            if (targetName.length() > maxLength) {
                maxLength = targetName.length();
            }
        }
    }

    printTargets(project, topNames, topDescriptions, "Main targets:", maxLength);
    //if there were no main targets, we list all subtargets
    //as it means nothing has a description
    if (topNames.size() == 0) {
        printSubTargets = true;
    }
    if (printSubTargets) {
        printTargets(project, subNames, null, "Other targets:", 0);
    }

    String defaultTarget = project.getDefaultTarget();
    if (defaultTarget != null && !"".equals(defaultTarget)) {
        // shouldn't need to check but...
        project.log("Default target: " + defaultTarget);
    }
}

From source file:org.sakaiproject.calendar.tool.CalendarAction.java

/**
 * Build the context for showing week view
 *///from w  w w . j ava2 s.  c  o  m
protected void buildWeekContext(VelocityPortlet portlet, Context context, RunData runData,
        CalendarActionState state) {
    Calendar calendarObj = null;
    //Time st,et = null;
    //CalendarUtil calObj= null;
    MyYear yearObj = null;
    MyMonth monthObj1 = null;
    MyWeek weekObj = null;
    MyDay dayObj = null;
    MyDate dateObj1, dateObj2 = null;
    int dayofweek = 0;

    // new objects of myYear, myMonth, myDay, myWeek classes
    yearObj = new MyYear();
    monthObj1 = new MyMonth();
    weekObj = new MyWeek();
    dayObj = new MyDay();
    dateObj1 = new MyDate();
    CalendarEventVector CalendarEventVectorObj = null;

    //calObj = state.getCalObj();
    String peid = ((JetspeedRunData) runData).getJs_peid();
    SessionState sstate = ((JetspeedRunData) runData).getPortletSessionState(peid);

    Time m_time = TimeService.newTime();
    TimeBreakdown b = m_time.breakdownLocal();
    int stateYear = b.getYear();
    int stateMonth = b.getMonth();
    int stateDay = b.getDay();
    if ((sstate.getAttribute(STATE_YEAR) != null) && (sstate.getAttribute(STATE_MONTH) != null)
            && (sstate.getAttribute(STATE_DAY) != null)) {
        stateYear = ((Integer) sstate.getAttribute(STATE_YEAR)).intValue();
        stateMonth = ((Integer) sstate.getAttribute(STATE_MONTH)).intValue();
        stateDay = ((Integer) sstate.getAttribute(STATE_DAY)).intValue();
    }

    CalendarUtil calObj = new CalendarUtil();
    calObj.setDay(stateYear, stateMonth, stateDay);
    int iii = 0;

    dateObj1.setTodayDate(calObj.getMonthInteger(), calObj.getDayOfMonth(), calObj.getYear());
    yearObj.setYear(calObj.getYear());
    monthObj1.setMonth(calObj.getMonthInteger());
    dayObj.setDay(calObj.getDayOfMonth());
    String calId = state.getPrimaryCalendarReference();

    // this loop will move the calendar to the begining of the week

    if (CalendarService.allowGetCalendar(calId) == false) {
        context.put(ALERT_MSG_KEY, rb.getString("java.alert.younotallow"));
        return;
    } else {
        try {
            calendarObj = CalendarService.getCalendar(calId);
        } catch (IdUnusedException e) {
            try {
                CalendarService.commitCalendar(CalendarService.addCalendar(calId));
                calendarObj = CalendarService.getCalendar(calId);
            } catch (Exception err) {
                context.put(ALERT_MSG_KEY, rb.getString("java.alert.therenoactv"));
                M_log.debug(".buildWeekContext(): " + err);
                return;
            }
        } catch (PermissionException e) {
            context.put(ALERT_MSG_KEY, rb.getString("java.alert.younotperm"));
            M_log.debug(".buildWeekContext(): " + e);
            return;
        }
    }

    if (calendarObj.allowGetEvents() == true) {
        CalendarEventVectorObj = CalendarService.getEvents(
                getCalendarReferenceList(portlet, state.getPrimaryCalendarReference(), isOnWorkspaceTab()),
                getWeekTimeRange(calObj));
    } else {
        CalendarEventVectorObj = new CalendarEventVector();
    }

    calObj.setDay(dateObj1.getYear(), dateObj1.getMonth(), dateObj1.getDay());
    dayofweek = calObj.getDay_Of_Week(true);
    calObj.setPrevDate(dayofweek - 1);

    dayofweek = calObj.getDay_Of_Week(true);

    Time[] pageStartTime = new Time[7];
    Time[] pageEndTime = new Time[7];

    for (int i = 7; i >= dayofweek; i--) {

        Vector eventVector = new Vector();
        Vector eventVector1;
        dateObj2 = new MyDate();
        dateObj2.setTodayDate(calObj.getMonthInteger(), calObj.getDayOfMonth(), calObj.getYear());
        dateObj2.setDayName(calendarUtilGetDay(calObj.getDay_Of_Week(true)));
        dateObj2.setNameOfMonth(calendarUtilGetMonth(calObj.getMonthInteger()));

        if (calObj.getDayOfMonth() == dayObj.getDay())
            dateObj2.setFlag(1);

        if (state.getCurrentPage().equals("third")) {
            eventVector1 = new Vector();
            // JS -- the third page starts at 2PM(14 o'clock), and lasts 20 half-hour
            eventVector = getNewEvents(calObj.getYear(), calObj.getMonthInteger(), calObj.getDayOfMonth(),
                    state, runData, THIRD_PAGE_START_HOUR, 19, context, CalendarEventVectorObj);

            for (int index = 0; index < eventVector1.size(); index++) {
                eventVector.add(eventVector.size(), eventVector1.get(index));
            }

            // Reminder: weekview vm is using 0..6
            pageStartTime[i - 1] = TimeService.newTimeLocal(calObj.getYear(), calObj.getMonthInteger(),
                    calObj.getDayOfMonth(), THIRD_PAGE_START_HOUR, 0, 0, 0);
            pageEndTime[i - 1] = TimeService.newTimeLocal(calObj.getYear(), calObj.getMonthInteger(),
                    calObj.getDayOfMonth(), 23, 59, 0, 0);

        } else if (state.getCurrentPage().equals("second")) {
            eventVector = getNewEvents(calObj.getYear(), calObj.getMonthInteger(), calObj.getDayOfMonth(),
                    state, runData, SECOND_PAGE_START_HOUR, 19, context, CalendarEventVectorObj);
            // Reminder: weekview vm is using 0..6
            pageStartTime[i - 1] = TimeService.newTimeLocal(calObj.getYear(), calObj.getMonthInteger(),
                    calObj.getDayOfMonth(), SECOND_PAGE_START_HOUR, 0, 0, 0);
            pageEndTime[i - 1] = TimeService.newTimeLocal(calObj.getYear(), calObj.getMonthInteger(),
                    calObj.getDayOfMonth(), 17, 59, 0, 0);

        } else {
            eventVector1 = new Vector();
            // JS -- the first page starts at 12AM(0 o'clock), and lasts 20 half-hour
            eventVector1 = getNewEvents(calObj.getYear(), calObj.getMonthInteger(), calObj.getDayOfMonth(),
                    state, runData, FIRST_PAGE_START_HOUR, 19, context, CalendarEventVectorObj);

            for (int index = 0; index < eventVector1.size(); index++) {
                eventVector.insertElementAt(eventVector1.get(index), index);
            }

            // Reminder: weekview vm is using 0..6
            pageStartTime[i - 1] = TimeService.newTimeLocal(calObj.getYear(), calObj.getMonthInteger(),
                    calObj.getDayOfMonth(), 0, 0, 0, 0);
            pageEndTime[i - 1] = TimeService.newTimeLocal(calObj.getYear(), calObj.getMonthInteger(),
                    calObj.getDayOfMonth(), 9, 59, 0, 0);

        }
        dateObj2.setEventBerWeek(eventVector);
        weekObj.setWeek(7 - i, dateObj2);

        // the purpose of this if condition is to check if we reached day 7 if yes do not
        // call next day.
        if (i > dayofweek)
            calObj.nextDate();
    }

    calObj.setDay(yearObj.getYear(), monthObj1.getMonth(), dayObj.getDay());
    context.put("week", weekObj);
    context.put("helper", new Helper());
    context.put("date", dateObj1);
    context.put("page", state.getCurrentPage());
    state.setState("week");
    context.put("tlang", rb);
    context.put("config", configProps);
    context.put("message", state.getState());

    DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL, new ResourceLoader().getLocale());
    formatter.setTimeZone(TimeService.getLocalTimeZone());
    try {
        context.put("beginWeek", formatter.format(calObj.getPrevTime(calObj.getDay_Of_Week(true) - 1)));
    } catch (Exception e) {
        context.put("beginWeek", calObj.getTodayDate());
    }
    try {
        calObj.setNextWeek();
        context.put("endWeek", formatter.format(calObj.getPrevTime(1)));
    } catch (Exception e) {
        context.put("endWeek", calObj.getTodayDate());
    }

    buildMenu(portlet, context, runData, state,
            CalendarPermissions.allowCreateEvents(state.getPrimaryCalendarReference(),
                    state.getSelectedCalendarReference()),
            CalendarPermissions.allowDeleteEvent(state.getPrimaryCalendarReference(),
                    state.getSelectedCalendarReference(), state.getCalendarEventId()),
            CalendarPermissions.allowReviseEvents(state.getPrimaryCalendarReference(),
                    state.getSelectedCalendarReference(), state.getCalendarEventId()),
            CalendarPermissions.allowMergeCalendars(state.getPrimaryCalendarReference()),
            CalendarPermissions.allowModifyCalendarProperties(state.getPrimaryCalendarReference()),
            CalendarPermissions.allowImport(state.getPrimaryCalendarReference()),
            CalendarPermissions.allowSubscribe(state.getPrimaryCalendarReference()),
            CalendarPermissions.allowSubscribeThis(state.getPrimaryCalendarReference()));

    calObj.setDay(yearObj.getYear(), monthObj1.getMonth(), dayObj.getDay());

    context.put("realDate", TimeService.newTime());
    context.put("tlang", rb);
    context.put("config", configProps);
    Vector vec = new Vector();
    context.put("vec", vec);
    Vector conflictVec = new Vector();
    context.put("conflictVec", conflictVec);
    Vector calVec = new Vector();
    context.put("calVec", calVec);
    HashMap hm = new HashMap();
    context.put("hm", hm);
    Integer intObj = Integer.valueOf(0);
    context.put("intObj", intObj);

    context.put("pageStartTime", pageStartTime);
    context.put("pageEndTime", pageEndTime);

    context.put("selectedView", rb.getString("java.byweek"));

    context.put("dayOfWeekNames", calObj.getCalendarDaysOfWeekNames(false));

}

From source file:org.sakaiproject.portal.charon.site.PortalSiteHelperImpl.java

/**
 * Gets the path of sites back to the root of the tree.
 * @param s//from ww w.  j  a v a  2  s .c om
 * @param ourParent
 * @return
 */
private List<Site> getPwd(Site s, String ourParent) {
    if (ourParent == null)
        return null;

    // System.out.println("Getting Current Working Directory for
    // "+s.getId()+" "+s.getTitle());

    int depth = 0;
    Vector<Site> pwd = new Vector<Site>();
    Set<String> added = new HashSet<String>();

    // Add us to the list at the top (will become the end)
    pwd.add(s);
    added.add(s.getId());

    // Make sure we don't go on forever
    while (ourParent != null && depth < 8) {
        depth++;
        Site site = null;
        try {
            site = SiteService.getSiteVisit(ourParent);
        } catch (Exception e) {
            break;
        }
        // We have no patience with loops
        if (added.contains(site.getId()))
            break;

        // System.out.println("Adding Parent "+site.getId()+"
        // "+site.getTitle());
        pwd.insertElementAt(site, 0); // Push down stack
        added.add(site.getId());

        ResourceProperties rp = site.getProperties();
        ourParent = rp.getProperty(PROP_PARENT_ID);
    }

    // PWD is only defined for > 1 site
    if (pwd.size() < 2)
        return null;
    return pwd;
}

From source file:org.sakaiproject.portal.service.SiteNeighbourhoodServiceImpl.java

/**
 * Get All Sites for the current user. If the user is not logged in we
 * return the list of publically viewable gateway sites.
 * // www. j  a  v  a2s . co  m
 * @param includeMyWorkspace
 *        When this is true - include the user's My Workspace as the first
 *        parameter. If false, do not include the MyWorkspace anywhere in
 *        the list. Some uses - such as the portlet styled portal or the rss
 *        styled portal simply want all of the sites with the MyWorkspace
 *        first. Other portals like the basic tabbed portal treats My
 *        Workspace separately from all of the rest of the workspaces.
 * @see org.sakaiproject.portal.api.PortalSiteHelper#getAllSites(javax.servlet.http.HttpServletRequest,
 *      org.sakaiproject.tool.api.Session, boolean)
 */
public List<Site> getAllSites(HttpServletRequest req, Session session, boolean includeMyWorkspace) {

    boolean loggedIn = session.getUserId() != null;
    List<Site> mySites;

    // collect the Publically Viewable Sites
    if (!loggedIn) {
        mySites = getGatewaySites();
        return mySites;
    }

    // collect the user's sites - don't care whether long descriptions are loaded
    mySites = siteService.getUserSites(false);

    // collect the user's preferences
    List prefExclude = new ArrayList();
    List prefOrder = new ArrayList();
    if (session.getUserId() != null) {
        Preferences prefs = preferencesService.getPreferences(session.getUserId());
        ResourceProperties props = prefs.getProperties("sakai:portal:sitenav");

        List l = props.getPropertyList("exclude");
        if (l != null) {
            prefExclude = l;
        }

        l = props.getPropertyList("order");
        if (l != null) {
            prefOrder = l;
        }
    }

    // remove all in exclude from mySites
    List<Site> visibleSites = new ArrayList<Site>();
    for (Site site : mySites) {
        if (!prefExclude.contains(site.getId())) {
            visibleSites.add(site);
        }
    }
    mySites = visibleSites;

    // Prepare to put sites in the right order
    Vector<Site> ordered = new Vector<Site>();
    Set<String> added = new HashSet<String>();

    // First, place or remove MyWorkspace as requested
    Site myWorkspace = getMyWorkspace(session);
    if (myWorkspace != null) {
        if (includeMyWorkspace) {
            ordered.add(myWorkspace);
            added.add(myWorkspace.getId());
        } else {
            int pos = listIndexOf(myWorkspace.getId(), mySites);
            if (pos != -1)
                mySites.remove(pos);
        }
    }

    // re-order mySites to have order first, the rest later
    for (Iterator i = prefOrder.iterator(); i.hasNext();) {
        String id = (String) i.next();

        // find this site in the mySites list
        int pos = listIndexOf(id, mySites);
        if (pos != -1) {
            Site s = mySites.get(pos);
            if (!added.contains(s.getId())) {
                ordered.add(s);
                added.add(s.getId());
            }
        }
    }

    // We only do the child processing if we have less than 200 sites
    boolean haveChildren = false;
    int siteCount = mySites.size();

    // pick up the rest of the top-level-sites
    for (int i = 0; i < mySites.size(); i++) {
        Site s = mySites.get(i);
        if (added.contains(s.getId()))
            continue;
        // Once the user takes over the order, 
        // ignore parent/child sorting put all the sites
        // at the top
        String ourParent = null;
        if (prefOrder.size() == 0) {
            ResourceProperties rp = s.getProperties();
            ourParent = rp.getProperty(SiteService.PROP_PARENT_ID);
        }
        // System.out.println("Top Site:"+s.getTitle()+"
        // parent="+ourParent);
        if (siteCount > 200 || ourParent == null) {
            // System.out.println("Added at root");
            ordered.add(s);
            added.add(s.getId());
        } else {
            haveChildren = true;
        }
    }

    // If and only if we have some child nodes, we repeatedly
    // pull up children nodes to be behind their parents
    // This is O N**2 - so if we had thousands of sites it
    // it would be costly - hence we only do it for < 200 sites
    // and limited depth - that makes it O(N) not O(N**2)
    boolean addedSites = true;
    int depth = 0;
    while (depth < 20 && addedSites && haveChildren) {
        depth++;
        addedSites = false;
        haveChildren = false;
        for (int i = mySites.size() - 1; i >= 0; i--) {
            Site s = mySites.get(i);
            if (added.contains(s.getId()))
                continue;
            ResourceProperties rp = s.getProperties();
            String ourParent = rp.getProperty(SiteService.PROP_PARENT_ID);
            if (ourParent == null)
                continue;
            haveChildren = true;
            // System.out.println("Child Site:"+s.getTitle()+
            // "parent="+ourParent);
            // Search the already added pages for a parent
            // or sibling node
            boolean found = false;
            int j = -1;
            for (j = ordered.size() - 1; j >= 0; j--) {
                Site ps = ordered.get(j);
                // See if this site is our parent
                if (ourParent.equals(ps.getId())) {
                    found = true;
                    break;
                }
                // See if this site is our sibling
                rp = ps.getProperties();
                String peerParent = rp.getProperty(SiteService.PROP_PARENT_ID);
                if (ourParent.equals(peerParent)) {
                    found = true;
                    break;
                }
            }

            // We want to insert *after* the identified node
            j = j + 1;
            if (found && j >= 0 && j < ordered.size()) {
                // System.out.println("Added after parent");
                ordered.insertElementAt(s, j);
                added.add(s.getId());
                addedSites = true; // Worth going another level deeper
            }
        }
    } // End while depth

    // If we still have children drop them at the end
    if (haveChildren)
        for (int i = 0; i < mySites.size(); i++) {
            Site s = mySites.get(i);
            if (added.contains(s.getId()))
                continue;
            // System.out.println("Orphan Site:"+s.getId()+" "+s.getTitle());
            ordered.add(s);
        }

    // All done
    mySites = ordered;
    return mySites;
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

@Override
/**/*www  .ja v a 2  s .  c  om*/
 * @see org.apache.ws.security.components.crypto.Crypto#getCertificateData(boolean,
 * java.security.cert.X509Certificate[])
 */
public byte[] getCertificateData(boolean reverse, X509Certificate[] certs) throws WSSecurityException {
    Vector list = new Vector();
    for (int i = 0; i < certs.length; i++) {
        if (reverse) {
            list.insertElementAt(certs[i], 0);
        } else {
            list.add(certs[i]);
        }
    }
    try {
        CertPath path = getCertificateFactory().generateCertPath(list);
        return path.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError");
    } catch (CertificateException e) {
        throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "parseError");
    }
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

/**
 * @see org.apache.ws.security.components.crypto.Crypto#getCertificateData(boolean,
 *      java.security.cert.X509Certificate[])
 *//*from ww  w  .j a v a  2s .c o m*/
public byte[] getCertificateData(boolean reverse, X509Certificate[] certs) throws WSSecurityException {
    Vector list = new Vector();
    for (int i = 0; i < certs.length; i++) {
        if (reverse) {
            list.insertElementAt(certs[i], 0);
        } else {
            list.add(certs[i]);
        }
    }
    try {
        CertPath path = getCertificateFactory().generateCertPath(list);
        return path.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError");
    } catch (CertificateException e) {
        throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "parseError");
    }
}

From source file:tools.httpserver.custom.ScriptList.java

/**
 * @return a vector containing Scriptengines names and associated languages
 *///w w w .  j  a v  a  2s.  c  o  m
public static Vector<String[]> getScriptEngines() {
    Vector<String[]> vector = new Vector<String[]>();
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    for (ScriptEngineFactory factories : scriptEngineManager.getEngineFactories()) {
        boolean inserted = false;
        for (int i = 0; i < vector.size(); i++) {
            String[] s = vector.elementAt(i);
            if (s[0].compareToIgnoreCase(factories.getEngineName()) > 0) {
                vector.insertElementAt(new String[] { factories.getEngineName(), factories.getLanguageName() },
                        i);
                inserted = true;
                break;
            }
        }
        if (!inserted)
            vector.add(new String[] { factories.getEngineName(), factories.getLanguageName() });
    }
    if (javax.tools.ToolProvider.getSystemJavaCompiler() != null) {
        vector.add(new String[] { "java", "java" });
    }
    return vector;
}