Example usage for java.util TreeSet iterator

List of usage examples for java.util TreeSet iterator

Introduction

In this page you can find the example usage for java.util TreeSet iterator.

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this set in ascending order.

Usage

From source file:org.openmrs.module.clinicalsummary.rule.antenatal.grouped.DatetimeBasedConceptFilteredRule.java

/**
 * @see org.openmrs.logic.Rule#eval(org.openmrs.logic.LogicContext, Integer, java.util.Map)
 *//*from www  .  j a  v  a2  s.c  o m*/
@Override
protected Result evaluate(final LogicContext context, final Integer patientId,
        final Map<String, Object> parameters) {
    Result result = new Result();

    Object conceptObjects = parameters.get(EvaluableConstants.OBS_CONCEPT);
    Map<Concept, Integer> conceptNamePositions = searchPositions(conceptObjects);

    ObsWithRestrictionRule obsWithRestrictionRule = new ObsWithStringRestrictionRule();
    Result obsResults = obsWithRestrictionRule.eval(context, patientId, parameters);

    Map<Date, Result[]> obsResultDates = new HashMap<Date, Result[]>();
    for (Result obsResult : obsResults) {
        Obs obs = (Obs) obsResult.getResultObject();
        Date obsDatetime = obs.getObsDatetime();
        // see if we already have obs array for this date
        Result[] obsResultDate = obsResultDates.get(obsDatetime);
        if (obsResultDate == null) {
            obsResultDate = new Result[CollectionUtils.size(conceptNamePositions)];
            obsResultDates.put(obsDatetime, obsResultDate);
        }
        // search the concept in the concept ordering map
        Integer position = conceptNamePositions.get(obs.getConcept());
        if (position != null)
            obsResultDate[position] = obsResult;
    }

    TreeSet<Date> keys = new TreeSet<Date>(new Comparator<Date>() {

        public int compare(final Date firstDate, final Date secondDate) {
            return firstDate.equals(secondDate) ? 0 : firstDate.after(secondDate) ? -1 : 1;
        }
    });
    keys.addAll(obsResultDates.keySet());

    // TODO: need to merge the two loop into one
    Integer counter = 0;
    Iterator<Date> iterator = keys.iterator();
    while (iterator.hasNext() && counter < 5) {
        Date date = iterator.next();
        // create the grouped results
        Result groupedResult = new Result();
        groupedResult.add(new Result(date));
        groupedResult.addAll(Arrays.asList(obsResultDates.get(date)));
        // add them to the main result of the rule
        result.add(groupedResult);
        // increase the counter as we only want last 5
        counter++;
    }

    Collections.reverse(result);

    return result;
}

From source file:org.skb.tribe.Tribe.java

/**
 * Do all options that require Tribe to exit after processing them, such as help or version or
 * print an stg file.//  www .j  av  a 2s . co  m
 * @param pass Pass=1 means and we have to print an stg file, we cannot do that.
 */
private void doExitOptions(int pass) {
    TribeProperties prop = TribeProperties.getInstance();

    if (pass == 1 && !(prop.getValueCli(TribeProperties.tpmKeyTgtLanguage)).tsIsType(TEnum.TS_NULL))
        return;

    if (pass == 1 && !(prop.getValueCli(TribeProperties.tpmKeySrcLanguage)).tsIsType(TEnum.TS_NULL))
        return;

    ReportManager repMgr = ReportManager.getInstance();

    Boolean defOpt = false;
    try {
        defOpt = ((TSBoolean) prop.getValue(TribeProperties.tpmKeyDefaultOptions)).tsvalue;
    } catch (Exception e) {
    }
    if (defOpt == true) {
        System.out.println("Default Configuration:");
        System.out.println("  [Option] = [Default Configuration]");
        System.out.println();

        //repMgr.defaults();
        TreeSet<String> ts = new TreeSet<String>(this.prop.getRows());
        for (Iterator<String> i = ts.iterator(); i.hasNext(); i.hasNext()) {
            String current = i.next();
            if (!(prop.get(current, TSPropertyMap.pmValCliOptionType)).tsIsType(TEnum.TS_NULL)) {
                if (!(prop.get(current, TSPropertyMap.pmValValueFile)).tsIsType(TEnum.TS_NULL)
                        || !(prop.get(current, TSPropertyMap.pmValValueCli)).tsIsType(TEnum.TS_NULL))
                    System.out.println("    " + current + " = " + prop.getValue(current));
                else
                    System.out.println("    " + current + " = " + prop.getValueDefault(current));
            }
        }
        this.footer();
        System.exit(0);
    }

    Boolean showHelp = false;
    try {
        showHelp = ((TSBoolean) prop.getValue(TribeProperties.tpmKeyShowHelp)).tsvalue;
    } catch (Exception e) {
    }

    if (showHelp == true) {
        this.header();
        this.cli.usage();
        this.footer();
        System.exit(0);
    }

    Boolean showVersion = false;
    try {
        showVersion = ((TSBoolean) prop.getValue(TribeProperties.tpmKeyShowVersion)).tsvalue;
    } catch (Exception e) {
    }

    if (showVersion == true) {
        this.header();
        System.exit(0);
    }

    Boolean showLang = false;
    try {
        showLang = ((TSBoolean) prop.getValue(TribeProperties.tpmKeyShowLanguages)).tsvalue;
    } catch (Exception e) {
    }

    if (showLang == true) {
        repMgr.reportMessageNoFile(
                "supported languages = " + prop.getValueDefault(TribeProperties.tpmKeyLanguages));
        System.exit(0);
    }

    if (!(prop.getValueCli(TribeProperties.tpmKeyPrStgFileTribe)).tsIsType(TEnum.TS_NULL)) {
        System.out.println(repMgr.toString());
        System.exit(0);
    }
}

From source file:com.alfaariss.oa.profile.aselect.logout.LogoutManager.java

private String createSignature(Map<String, String> mapRequest) throws OAException {
    String sSignature = null;//www  .j av  a2s .c  o  m
    try {
        if (_cryptoManager == null) {
            _logger.warn("No crypto manager available");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        Signature signature = _cryptoManager.getSignature();
        if (signature == null) {
            _logger.warn("No signature object found");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        StringBuffer sbSignatureData = new StringBuffer();
        TreeSet<String> sortedSet = new TreeSet<String>(mapRequest.keySet());
        for (Iterator<String> iter = sortedSet.iterator(); iter.hasNext();) {
            String sKey = iter.next();
            sbSignatureData.append(mapRequest.get(sKey));
        }

        PrivateKey keyPrivate = _cryptoManager.getPrivateKey();
        if (keyPrivate == null) {
            _logger.error("No private key available");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
        signature.initSign(keyPrivate);
        signature.update(sbSignatureData.toString().getBytes(ASelectProcessor.CHARSET));

        byte[] baSignature = signature.sign();

        byte[] baEncSignature = Base64.encodeBase64(baSignature);
        sSignature = new String(baEncSignature, ASelectProcessor.CHARSET);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not create signature for data: " + mapRequest, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    return sSignature;
}

From source file:evaluation.Evaluator.java

/**
 * This function removes duplicates from an array of given labels. It is used while
 * reading the file with the predicted labels.
 *
 * @param labels    the array with the labels to be checked for duplicates
 *///w w  w.j  a va2s  . com
public String[] removeDuplicates(String labels[]) {
    TreeSet aset = new TreeSet();
    aset.addAll(Arrays.asList(labels));

    int num_of_labels = aset.size();

    String finallabels[] = new String[num_of_labels];
    Iterator iterator = aset.iterator();
    int k = 0;
    while (iterator.hasNext()) {
        finallabels[k++] = (String) iterator.next();
    }

    return finallabels;
}

From source file:com.alfaariss.oa.authentication.remote.aselect.logout.LogoutManager.java

private String createSignature(Map<String, String> mapRequest) throws OAException {
    String sSignature = null;//from   w  w  w  . j a v a  2  s .co m
    try {
        if (_cryptoManager == null) {
            _logger.warn("No crypto manager available");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        Signature signature = _cryptoManager.getSignature();
        if (signature == null) {
            _logger.warn("No signature object found");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        StringBuffer sbSignatureData = new StringBuffer();
        TreeSet<String> sortedSet = new TreeSet<String>(mapRequest.keySet());
        for (Iterator<String> iter = sortedSet.iterator(); iter.hasNext();) {
            String sKey = iter.next();
            sbSignatureData.append(mapRequest.get(sKey));
        }

        PrivateKey keyPrivate = _cryptoManager.getPrivateKey();
        if (keyPrivate == null) {
            _logger.error("No private key available");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
        signature.initSign(keyPrivate);
        signature.update(sbSignatureData.toString().getBytes(CHARSET));

        byte[] baSignature = signature.sign();

        byte[] baEncSignature = Base64.encodeBase64(baSignature);
        sSignature = new String(baEncSignature, CHARSET);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not create signature for data: " + mapRequest, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    return sSignature;
}

From source file:org.hyperic.hq.ui.action.portlet.availsummary.ViewAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    WebUser user = RequestUtils.getWebUser(session);
    DashboardConfig dashConfig = dashboardManager
            .findDashboard((Integer) session.getAttribute(Constants.SELECTED_DASHBOARD_ID), user, authzBoss);

    if (dashConfig == null) {
        return new ActionRedirect("/Dashboard.do");
    }//from   w w w  .  j  a va 2  s  . c o  m

    ConfigResponse dashPrefs = dashConfig.getConfig();

    String token;
    long ts = System.currentTimeMillis();

    try {
        token = RequestUtils.getStringParameter(request, "token");
        if (token != null) {
            //token should be alpha-numeric
            if (!token.matches("^[\\w-]*$")) {
                log.warn("Token cleared by xss filter: " + token);
                token = null;
            }
        }
    } catch (ParameterNotFoundException e) {
        token = null;
    }

    String resKey = PropertiesForm.RESOURCES;
    String numKey = PropertiesForm.NUM_TO_SHOW;
    String titleKey = PropertiesForm.TITLE;

    if (token != null) {
        resKey += token;
        numKey += token;
        titleKey += token;
    }

    List<AppdefEntityID> entityIds = DashboardUtils.preferencesAsEntityIds(resKey, dashPrefs);

    // Can only do Platforms, Servers, and Services
    for (Iterator<AppdefEntityID> it = entityIds.iterator(); it.hasNext();) {
        AppdefEntityID aeid = it.next();

        if (aeid.isPlatform() || aeid.isServer() || aeid.isService()) {
            continue;
        }

        it.remove();
    }

    AppdefEntityID[] arrayIds = entityIds.toArray(new AppdefEntityID[entityIds.size()]);
    int count = Integer.parseInt(dashPrefs.getValue(numKey, "10"));
    int sessionId = user.getSessionId().intValue();

    CacheEntry[] ents = new CacheEntry[arrayIds.length];
    List<Integer> measurements = new ArrayList<Integer>(arrayIds.length);
    Map<String, AvailSummary> res = new HashMap<String, AvailSummary>();
    long interval = 0;
    ArrayList<String> toRemove = new ArrayList<String>();
    for (int i = 0; i < arrayIds.length; i++) {
        AppdefEntityID id = arrayIds[i];
        try {
            ents[i] = loadData(sessionId, id);
        } catch (AppdefEntityNotFoundException e) {
            toRemove.add(id.getAppdefKey());
        }

        if (ents[i] != null && ents[i].getMeasurement() != null) {
            measurements.add(i, ents[i].getMeasurement().getId());
            if (ents[i].getMeasurement().getInterval() > interval) {
                interval = ents[i].getMeasurement().getInterval();
            }
        } else {
            measurements.add(i, null);
        }
    }

    MetricValue[] vals = measurementBoss.getLastMetricValue(sessionId, measurements, interval);

    for (int i = 0; i < ents.length; i++) {
        CacheEntry ent = ents[i];
        MetricValue val = vals[i];

        // If no avail measurement is scheduled, skip this resource
        if (ent != null && val != null) {
            if (ent.getType() == null) {
                AppdefResourceValue resVal = appdefBoss.findById(sessionId, arrayIds[i]);
                if (resVal == null) {
                    continue;
                }
                ent.setType(resVal.getAppdefResourceTypeValue());
            }

            String name = ent.getType().getName();
            AvailSummary summary = res.get(name);
            if (summary == null) {
                summary = new AvailSummary(ent.getType());
                res.put(name, summary);
            }
            summary.setAvailability(val.getValue());
        }
    }

    JSONObject availSummary = new JSONObject();
    List<JSONObject> types = new ArrayList<JSONObject>();

    TreeSet<AvailSummary> sortedSet = new TreeSet<AvailSummary>(new AvailSummaryComparator());
    sortedSet.addAll(res.values());

    for (Iterator<AvailSummary> i = sortedSet.iterator(); i.hasNext() && count-- > 0;) {
        AvailSummary summary = i.next();
        JSONObject typeSummary = new JSONObject();
        typeSummary.put("resourceTypeName", summary.getTypeName());
        typeSummary.put("numUp", summary.getNumUp());
        typeSummary.put("numDown", summary.getNumDown());
        typeSummary.put("appdefType", summary.getAppdefType());
        typeSummary.put("appdefTypeId", summary.getAppdefTypeId());

        types.add(typeSummary);
    }

    availSummary.put("availSummary", types);

    if (token != null) {
        availSummary.put("token", token);
    } else {
        availSummary.put("token", JSONObject.NULL);
    }
    availSummary.put("title", dashPrefs.getValue(titleKey, ""));

    response.getWriter().write(availSummary.toString());

    log.debug("Availability summary loaded in " + (System.currentTimeMillis() - ts) + " ms");

    if (toRemove.size() > 0) {
        log.debug("Removing " + toRemove.size() + " missing resources.");
        DashboardUtils.removeResources(toRemove.toArray(new String[toRemove.size()]), resKey, dashPrefs);
    }

    return null;
}

From source file:com.miz.mizuu.fragments.CoverSearchFragment.java

private void showContent() {
    mProgressBar.setVisibility(View.GONE);
    mAdapter.notifyDataSetChanged();//from   w ww.j a v a2 s . co m

    TreeSet<String> languages = new TreeSet<String>();
    for (int i = 0; i < mCovers.size(); i++)
        if (!mCovers.get(i).getLanguage().equals("Null"))
            languages.add(mCovers.get(i).getLanguage());

    mItems = new String[languages.size() + 1];
    mItems[0] = getString(R.string.stringShowAllLanguages);
    Iterator<String> itr = languages.iterator();
    int i = 1;
    while (itr.hasNext()) {
        mItems[i] = itr.next();
        i++;
    }

    getActivity().invalidateOptionsMenu();
}

From source file:com.miz.mizuu.fragments.CollectionCoverSearchFragment.java

private void showContent() {
    mProgressBar.setVisibility(View.GONE);
    mAdapter.notifyDataSetChanged();/*w w w.  j  ava  2  s  . c o m*/

    TreeSet<String> languages = new TreeSet<String>();
    for (int i = 0; i < mCovers.size(); i++) {
        if (!mCovers.get(i).getLanguage().equals("Null"))
            languages.add(mCovers.get(i).getLanguage());
    }

    mItems = new String[languages.size() + 1];
    mItems[0] = getString(R.string.stringShowAllLanguages);
    Iterator<String> itr = languages.iterator();
    int i = 1;
    while (itr.hasNext()) {
        mItems[i] = itr.next();
        i++;
    }

    getActivity().invalidateOptionsMenu();
}

From source file:org.kepler.sms.NamedOntModel.java

/**
 * gets a list of the named classes in the ontology
 * // ww  w.  j  av  a  2 s. c  o m
 * @param sorted
 *            Return sorted list if true
 * @return A sorted list of named ontology classes
 */
public Iterator<NamedOntClass> getNamedClasses() {

    //use TreeSet instead of Vector so contains() is fast. TreeSet also
    //gives ascending natural ordering sorting for free. fix for bug #4539
    //Vector<NamedOntClass> results = new Vector<NamedOntClass>();
    TreeSet<NamedOntClass> results = new TreeSet<NamedOntClass>();
    NamedOntClass noc = null;
    for (OWLClass c : _ontology.getReferencedClasses()) {
        noc = new NamedOntClass(c, _ontology);

        if (!results.contains(noc))
            results.add(noc);
    }

    return results.iterator();
}

From source file:com.autentia.intra.jsf.schedule.renderer.BitacoreAbstractCompactScheduleRenderer.java

/**
 * <p>// w ww  .  j av a2 s . c o  m
 * Draw the schedule entries in the specified day cell
 * </p>
 *
 * @param context  the FacesContext
 * @param schedule the schedule
 * @param day      the day
 * @param writer   the ResponseWriter
 * @throws IOException when the entries could not be drawn
 */
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer)
        throws IOException {
    final String clientId = schedule.getClientId(context);
    final FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context);
    final String formId = parentFormInfo == null ? null : parentFormInfo.getFormName();
    final TreeSet entrySet = new TreeSet(comparator);

    for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) {
        ScheduleEntry entry = (ScheduleEntry) entryIterator.next();
        entrySet.add(entry);
    }

    for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) {
        ScheduleEntry entry = (ScheduleEntry) entryIterator.next();
        writer.startElement(HTML.TR_ELEM, schedule);
        writer.startElement(HTML.TD_ELEM, schedule);

        if (isSelected(schedule, entry)) {
            writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "selected"), null);
        }

        // compose the CSS style for the entry box
        StringBuffer entryStyle = new StringBuffer();
        entryStyle.append("width: 100%;");
        String entryColor = getEntryRenderer(schedule).getColor(context, schedule, entry,
                isSelected(schedule, entry));
        if (isSelected(schedule, entry) && entryColor != null) {
            entryStyle.append(" background-color: ");
            entryStyle.append(entryColor);
            entryStyle.append(";");
            entryStyle.append(" border-color: ");
            entryStyle.append(entryColor);
            entryStyle.append(";");
        }

        writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null);

        // draw the tooltip
        if (showTooltip(schedule)) {
            getEntryRenderer(schedule).renderToolTip(context, writer, schedule, entry,
                    isSelected(schedule, entry));
        }

        if (!isSelected(schedule, entry) && !schedule.isReadonly()) {
            writer.startElement("a", schedule);
            writer.writeAttribute("href", "#", null);

            writer.writeAttribute(HTML.ONMOUSEUP_ATTR,
                    "fireEntrySelected('" + formId + "', '" + clientId + "', '" + entry.getId() + "');", null);
        }

        // draw the content
        getEntryRenderer(schedule).renderContent(context, writer, schedule, day, entry, true,
                isSelected(schedule, entry));

        if (!isSelected(schedule, entry) && !schedule.isReadonly()) {
            writer.endElement("a");
        }

        writer.endElement(HTML.TD_ELEM);
        writer.endElement(HTML.TR_ELEM);
    }
}