Example usage for java.util TreeMap size

List of usage examples for java.util TreeMap size

Introduction

In this page you can find the example usage for java.util TreeMap size.

Prototype

int size

To view the source code for java.util TreeMap size.

Click Source Link

Document

The number of entries in the tree

Usage

From source file:org.alfresco.repo.content.cleanup.ContentStoreCleaner.java

/**
 * /*from w  ww . jav  a  2 s . c  o m*/
 * @param maxTimeExclusive      the max orphan time (exclusive)
 * @param batchSize             the maximum number of orphans to process
 * @return                      Returns the last processed orphan ID or <tt>null</tt> if nothing was processed
 */
private Long cleanBatch(final long maxTimeExclusive, final int batchSize) {
    // Get a bunch of cleanable URLs
    final TreeMap<Long, String> urlsById = new TreeMap<Long, String>();
    ContentUrlHandler contentUrlHandler = new ContentUrlHandler() {
        @Override
        public void handle(Long id, String contentUrl, Long orphanTime) {
            urlsById.put(id, contentUrl);
        }
    };
    // Get a bunch of cleanable URLs
    contentDataDAO.getContentUrlsOrphaned(contentUrlHandler, maxTimeExclusive, batchSize);

    // Shortcut, if necessary
    if (urlsById.size() == 0) {
        return null;
    }

    // Compile list of IDs and do a mass delete, recording the IDs to find the largest
    Long lastId = urlsById.lastKey();
    List<Long> ids = new ArrayList<Long>(urlsById.keySet());
    contentDataDAO.deleteContentUrls(ids);
    // No problems, so far (ALF-1998: contentStoreCleanerJob leads to foreign key exception)

    // Now attempt to physically delete the URLs
    for (Long id : ids) {
        String contentUrl = urlsById.get(id);
        // Handle failures
        boolean deleted = eagerContentStoreCleaner.deleteFromStores(contentUrl);
        if (!deleted) {
            switch (deletionFailureAction) {
            case KEEP_URL:
                // Keep the URL, but with an orphan time of 0 so that it is recorded
                contentDataDAO.createContentUrlOrphaned(contentUrl, new Date(0L));
            case IGNORE:
                break;
            default:
                throw new IllegalStateException("Unknown deletion failure action: " + deletionFailureAction);
            }
        }
    }

    // Done
    return lastId;
}

From source file:org.eclipse.gyrex.cloud.internal.queue.ZooKeeperQueue.java

@Override
public IMessage consumeMessage(final long timeout, final TimeUnit unit)
        throws IllegalArgumentException, IllegalStateException, SecurityException, InterruptedException {
    /*/*from w w w.  j  av  a  2  s.co m*/
     * We want to get the node with the smallest sequence number. But
     * other clients may remove and add nodes concurrently. Thus, we
     * need to further check if the node can be returned. It might be
     * gone by the time we check. If that happens we just continue with
     * the next node.
     */
    if ((timeout > 0) && (unit == null)) {
        throw new IllegalArgumentException("unit must not be null when timeout is specified");
    }
    final long abortTime = timeout > 0 ? unit.toMillis(timeout) + System.currentTimeMillis() : 0;
    TreeMap<Long, String> queueChildren;
    while (true) {
        try {
            queueChildren = readQueueChildren(null);
        } catch (final Exception e) {
            if (e instanceof KeeperException.NoNodeException) {
                throw new IllegalStateException(String.format("queue '%s' does not exist", id));
            }
            throw new QueueOperationFailedException(id, "CONSUME_MESSAGES", e);
        }

        // iterate over all children
        if (queueChildren.size() > 0) {
            for (final String childName : queueChildren.values()) {
                if (childName != null) {
                    // read message
                    final Message message = readQueueMessage(childName);
                    // check if we have a valid message
                    if ((message == null) || message.isHidden()) {
                        continue;
                    }
                    // try to consume the message
                    if (!message.consume(false)) {
                        continue;
                    }
                    return message;
                }
            }
        }

        // at this point no children are available
        if (abortTime <= 0) {
            // abort
            return null;
        }

        // wait for the timeout
        final long diff = abortTime - System.currentTimeMillis();
        if (diff > 0) {
            Thread.sleep(Math.max(diff / 2, 250));
        } else {
            // wait time elapsed
            return null;
        }
    }
}

From source file:org.apache.felix.webconsole.internal.compendium.ComponentsServlet.java

private void renderServletResult(final PrintWriter printWriter, final Component component) throws IOException {
    final JSONWriter jsonWriter = new JSONWriter(printWriter);
    try {//  w  w  w. ja va 2  s  .  co  m
        jsonWriter.object();

        final ScrService scrService = getScrService();
        if (scrService == null) {
            jsonWriter.key("status");
            jsonWriter.value("Apache Felix Declarative Service required for this function");
        } else {
            final Component[] serviceComponents = scrService.getComponents();

            if (serviceComponents == null || serviceComponents.length == 0) {
                jsonWriter.key("status");
                jsonWriter.value("No components installed currently");
            } else {
                // order components by name
                TreeMap componentMap = new TreeMap();
                for (int i = 0; i < serviceComponents.length; i++) {
                    Component tempComp = serviceComponents[i];
                    componentMap.put(tempComp.getName(), tempComp);
                }

                final StringBuffer strBuffer = new StringBuffer();
                strBuffer.append(componentMap.size());
                strBuffer.append(" component");
                if (componentMap.size() != 1) {
                    strBuffer.append('s');
                }
                strBuffer.append(" installed.");
                jsonWriter.key("status");
                jsonWriter.value(strBuffer.toString());

                // render components
                jsonWriter.key("data");
                jsonWriter.array();
                if (component != null) {
                    jsonComponent(jsonWriter, component, true);
                } else {
                    for (Iterator ci = componentMap.values().iterator(); ci.hasNext();) {
                        jsonComponent(jsonWriter, (Component) ci.next(), false);
                    }
                }
                jsonWriter.endArray();
            }
        }

        jsonWriter.endObject();
    } catch (JSONException je) {
        throw new IOException(je.toString());
    }
}

From source file:GitBackend.GitAPI.java

private void printCommitMap(TreeMap<DateTime, RevCommit> commitMap) {
    Iterator it = commitMap.entrySet().iterator();

    System.out.println("Number of commits here: " + commitMap.size());
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        RevCommit commit = (RevCommit) pair.getValue();
        System.out.println(pair.getKey() + " --- " + commit.getName());

    }//  w  ww  .  j a va 2s  . c o m
}

From source file:org.rti.zcore.dar.utils.WidgetUtils.java

/**
 * @param conn//from  w ww .jav  a2s.  co  m
 * @param pageItem
 * @param widgetType
* @param currentFieldNameIdentifier - If this is one of the special patient bridge forms, this value helps the system locate the correct field to render the widget.
* @param bridgeId - id of the record from the patient bridge table.
 * @return String used to render the widget
 */
public static String getOne(Connection conn, PageItem pageItem, String value, Long formId, Long encounterId,
        String widgetType, String currentFieldNameIdentifier, Long bridgeId) {

    String item = null;
    FormField formField = pageItem.getForm_field();
    Long formFieldId = formField.getId();
    Long pageItemId = pageItem.getId();
    StringBuffer sbuf = new StringBuffer();
    String inputType = pageItem.getInputType();
    value = value.trim();
    Set multiEnumList = null;

    // multiselect enums require special handling, since their enums come from their parent.
    if (inputType.equals("multiselect_item")) {
        Integer enumValue = null;
        String colName = formField.getStarSchemaName();
        if (!value.equals("")) {
            // Fetch the actual enum id
            try {
                enumValue = (Integer) EncountersDAO.getValue(conn, encounterId, formId, colName);
            } catch (ServletException e) {
                log.error(e);
            } catch (SQLException e) {
                log.error(e);
            }
            FieldEnumeration enumeration = (FieldEnumeration) DynaSiteObjects.getFieldEnumerations()
                    .get(Long.valueOf(enumValue));
            Long enumFormFieldId = enumeration.getFieldId();
            TreeMap enumMap = (TreeMap) DynaSiteObjects.getFieldEnumerationsByField().get(enumFormFieldId);
            if (enumMap.size() != 0) {
                Set fieldEnumSet = enumMap.entrySet();
                Set enumSet = new TreeSet(new DisplayOrderComparator());
                for (Iterator iterator = fieldEnumSet.iterator(); iterator.hasNext();) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    FieldEnumeration fieldEnumeration = (FieldEnumeration) entry.getValue();
                    enumSet.add(fieldEnumeration);
                }
                formField.setEnumerations(enumSet);
            }
        } else {
            Long masterId = Long.valueOf(pageItem.getVisibleDependencies1());
            if (masterId != null && masterId.intValue() > 0) {
                TreeMap enumMap = (TreeMap) DynaSiteObjects.getFieldEnumerationsByField().get(masterId);
                try {
                    if (enumMap.size() != 0) {
                        Set fieldEnumSet = enumMap.entrySet();
                        Set enumSet = new TreeSet(new DisplayOrderComparator());
                        for (Iterator iterator = fieldEnumSet.iterator(); iterator.hasNext();) {
                            Map.Entry entry = (Map.Entry) iterator.next();
                            FieldEnumeration fieldEnumeration = (FieldEnumeration) entry.getValue();
                            enumSet.add(fieldEnumeration);
                        }
                        formField.setEnumerations(enumSet);
                    }
                } catch (NullPointerException e) {
                    log.error("Error getting multiselect_item enum by pageItemId: masterId: " + masterId
                            + " pageItemId -  " + pageItemId + " field id: " + formFieldId);
                }
            } else {
                log.error("Error getting multiselect_item enum by pageItemId: masterId: " + masterId
                        + " pageItemId -  " + pageItemId + " field id: " + formFieldId);
            }
        }

        // it's a bit of a process to get the correct formfield - please bare w/ me...
        //HashMap map = (HashMap) DynaSiteObjects.getFieldToPageItem().get(formId);   // get map of pageItems to formfield
        //Long enumPageItemId =  (Long) map.get(enumFormFieldId);
        //PageItem enumPageItem = (PageItem) DynaSiteObjects.getPageItems().get(enumPageItemId);
        // we may just need the fieldenum from dynasite....
        //FormField enumFormfield =  (FormField) map.get(enumFormFieldId);
    }

    String visibleEnumIdTrigger1 = null;
    if (pageItem.getVisibleEnumIdTrigger1() != null) {
        if (pageItem.getVisibleEnumIdTrigger1().equals("")) {
            visibleEnumIdTrigger1 = "0";
        } else {
            visibleEnumIdTrigger1 = pageItem.getVisibleEnumIdTrigger1();
        }
    } else {
        visibleEnumIdTrigger1 = "0";
    }

    String visibleEnumIdTrigger2 = null;
    if (pageItem.getVisibleEnumIdTrigger2() != null) {
        if (pageItem.getVisibleEnumIdTrigger2().equals("")) {
            visibleEnumIdTrigger2 = "0";
        } else {
            visibleEnumIdTrigger2 = pageItem.getVisibleEnumIdTrigger2();
        }
    } else {
        visibleEnumIdTrigger2 = "0";
    }

    // some of the inputTypes are not stored properly - we'll get them from formField
    if (formField.getType() != null) {
        if (formField.getType().equals("Yes/No")) {
            inputType = "Yes/No";
        } else if (formField.getType().equals("sex")) {
            inputType = "sex";
        }
    }

    // some widgets are shared
    if (inputType.equals("radio")) {
        inputType = "select";
    }

    String dep = null;
    String update = null;

    String formProperty = null;
    String widgetName = null;
    if (widgetType.equals("Chart")) {
        formProperty = "field" + String.valueOf(encounterId) + "." + String.valueOf(formFieldId);
        widgetName = "inputWidget" + String.valueOf(encounterId) + "." + String.valueOf(formFieldId);
    } else if (widgetType.equals("Metadata")) {
        formProperty = "field" + inputType;
        widgetName = "inputWidget" + inputType;
    } else {
        formProperty = "field" + String.valueOf(formFieldId);
        widgetName = "inputWidget" + String.valueOf(formFieldId);
    }

    String updateRecord = null;
    Form encounterForm = (Form) DynaSiteObjects.getForms().get(formId);

    if (encounterForm.getFormTypeId() == 6) { // patient bridge table form
        if (bridgeId == 0) {
            updateRecord = "createRecord('" + inputType + "', " + formFieldId + " ," + pageItemId + " ,"
                    + formId + ", " + encounterId + " , '" + widgetType + "', '" + currentFieldNameIdentifier
                    + "');";
        } else {
            updateRecord = "updateRecord('" + inputType + "', " + formFieldId + " ," + pageItemId + " ,"
                    + formId + ", " + encounterId + " , '" + widgetType + "', " + bridgeId + " , '"
                    + currentFieldNameIdentifier + "');";
        }
    } else {
        updateRecord = "updateRecord('" + inputType + "', " + formFieldId + " ," + pageItemId + " ," + formId
                + ", " + encounterId + " , '" + widgetType + "');";
    }

    if (widgetType.equals("Chart")) {
        /* if (formFieldId.intValue() == 1563) {
        updateRecord = "updateRecordChart('" + inputType + "', "
                + formFieldId + " ," + pageItemId + " ," + formId + ", " + encounterId + " , '" + widgetType + "','');";
         } else {*/
        updateRecord = "updateRecordChart('" + inputType + "', " + formFieldId + " ," + pageItemId + " ,"
                + formId + ", " + encounterId + " , '" + widgetType + "','');";
        //  }
    } else if (widgetType.equals("patientid")) {
        updateRecord = "updateRecord('" + inputType + "', " + formFieldId + " ," + pageItemId + " ," + formId
                + ", " + encounterId + " , 'patient');";
    } else if (widgetType.equals("Metadata")) {
        updateRecord = "updateRecordMetadata('" + inputType + "', " + encounterId + ");";
    }

    String updateRecordIdNameY = "updateRecordIdName('" + inputType + "', " + formFieldId + " ," + pageItemId
            + " ," + formId + ", " + encounterId + ", 'Y', '" + widgetType + "');";
    String updateRecordIdNameN = "updateRecordIdName('" + inputType + "', " + formFieldId + " ," + pageItemId
            + " ," + formId + ", " + encounterId + ", 'N', '" + widgetType + "');";
    // Choices for update are "onclick, onmouseout, onchange"

    String dep1 = "toggleField('dropdown', " + visibleEnumIdTrigger1 + ", '"
            + pageItem.getVisibleDependencies1() + "','" + formField.getId() + "');";
    String dep2 = "toggleField2DepsChoice('dropdown', " + visibleEnumIdTrigger1 + ", '"
            + pageItem.getVisibleDependencies1() + "'," + visibleEnumIdTrigger2 + ", '"
            + pageItem.getVisibleDependencies2() + "', '" + formField.getId() + "');";
    String depSm = "toggleFieldSafeMotherhood('dropdown', " + visibleEnumIdTrigger1 + ", '"
            + pageItem.getVisibleDependencies1() + "'," + visibleEnumIdTrigger2 + ", '"
            + pageItem.getVisibleDependencies2() + "', '" + formField.getId() + "');";

    if ((inputType.equals("emptyDate")) || (inputType.equals("birthdate")) || (inputType.equals("dateToday"))
            || (inputType.equals("dateOneMonthFuture"))) {
        String month = DateUtils.getMonth();
        String day = DateUtils.getDay();
        String year = DateUtils.getYear();
        String lastTwoYears = String.valueOf(new Integer(year).intValue() - 2);
        String eightyYears = String.valueOf(new Integer(year).intValue() - 80);
        String twoYears = String.valueOf(new Integer(year).intValue() + 2);
        String startYear;
        String endYear;
        if (inputType.equals("birthdate")) {
            startYear = eightyYears;
            endYear = year;
        } else {
            startYear = lastTwoYears;
            endYear = twoYears;
        }
        sbuf.append("<span onclick=\"showCalendar('" + year + "','" + month + "','" + day
                + "','dd/MM/yyyy','form" + formId + "','" + formProperty + "',event," + startYear + ","
                + endYear + ");\">"
                + "<img alt=\"Select Date\" border=\"0\" src=\"/dar/images/calendar.gif\" align=\"middle\">"
                + "</span>\n");
        sbuf.append("<span id=\"span" + formProperty + "\" onclick=\"showCalendar('" + year + "','" + month
                + "','" + day + "','dd/MM/yyyy','form" + formId + "','" + formProperty + "',event," + startYear
                + "," + endYear + ");\"></span>\n");
        sbuf.append("<span style=\"display:none;\">\n" + "   <input type=\"text\" id=\"" + widgetName
                + "\" name=\"field" + formFieldId + "\"/>\n" + "</span>\n");
        sbuf.append("<input type=\"button\" name=\"_add\" value=\"Change\""
                + getEventHandler("onclick", updateRecord, encounterId) + ">\n");
        item = sbuf.toString();

    } else if (inputType.equals("select") || inputType.equals("select-dwr")
            || inputType.equals("select-multitoggle")) {
        Set enumList = formField.getEnumerations();
        renderSelect(visibleEnumIdTrigger1, sbuf, widgetName, formFieldId, updateRecord, dep1, encounterId,
                pageItem, visibleEnumIdTrigger2, dep2, value, enumList);
        item = sbuf.toString();
    } else if (inputType.equals("dropdown")) {
        // Process the dynamic dropdown lists
        List<DropdownItem> dropdownItems = null;
        if (pageItem.getInputType().equals("dropdown")) {
            try {
                dropdownItems = WidgetUtils.getList(conn, pageItem.getDropdownTable(),
                        pageItem.getDropdownColumn(), pageItem.getDropdownConstraint(),
                        pageItem.getDropdownOrderByClause(), DropdownItem.class);
            } catch (SQLException e) {
                log.error(e);
            } catch (ServletException e) {
                log.error(e);
            }
        }
        renderSelect(visibleEnumIdTrigger1, sbuf, widgetName, formFieldId, updateRecord, dep1, encounterId,
                pageItem, visibleEnumIdTrigger2, dep2, value, dropdownItems, bridgeId,
                currentFieldNameIdentifier);
        item = sbuf.toString();
    } else if (inputType.equals("multiselect_item")) {
        Set enumList = formField.getEnumerations();
        renderSelect(visibleEnumIdTrigger1, sbuf, widgetName, formFieldId, updateRecord, dep1, encounterId,
                pageItem, visibleEnumIdTrigger2, dep2, value, enumList);
        item = sbuf.toString();
    } else if (inputType.equals("multiselect_enum")) {
        item = "Please make a selection from one of the following choices below.";
    } else if (inputType.equals("patientid_districts")) {
        List districts = DynaSiteObjects.getDistricts();
        sbuf.append("<select id=\"" + widgetName + "\" name=\"field" + formFieldId + "\""
                + getEventHandler("onchange", updateRecord, encounterId) + ">\n");
        sbuf.append("   <option value=\"\">No Information</option>\n");
        for (int i = 0; i < districts.size(); i++) {
            District district = (District) districts.get(i);
            if (value.equals(district.getDistrictId())) {
                sbuf.append("   <option value=\"" + district.getDistrictId() + "\" selected>"
                        + district.getDistrictName() + " (" + district.getDistrictId() + ")" + "</option>\n");
            } else {
                sbuf.append("   <option value=\"" + district.getDistrictId() + "\">"
                        + district.getDistrictName() + " (" + district.getDistrictId() + ")" + "</option>\n");
            }
        }
        sbuf.append("</select>\n");
        item = sbuf.toString();
    } else if (inputType.equals("patientid_sites") || inputType.equals("sites")
            || inputType.equals("sites_not_selected")) {
        List sites = null;
        sites = DynaSiteObjects.getClinics();
        sbuf.append("<select id=\"" + widgetName + "\" name=\"field" + formFieldId + "\""
                + getEventHandler("onchange", updateRecord, encounterId) + ">\n");
        sbuf.append("   <option value=\"\">No Information</option>\n");
        for (int i = 0; i < sites.size(); i++) {
            Site site = (Site) sites.get(i);
            if (site.getInactive() == null) {
                String siteId = null;
                String abbrev = null;
                if (inputType.equals("patientid_sites")) {
                    //siteId = site.getSiteAlphaId().substring(0, 2);
                    siteId = site.getSiteAlphaId();
                    abbrev = " (" + siteId + ")";
                } else {
                    siteId = site.getId().toString();
                    abbrev = "";
                }
                if (value.equals(site.getSiteAlphaId())) {
                    sbuf.append("   <option value=\"" + siteId + "\" selected>" + site.getName() + abbrev
                            + "</option>\n");
                } else {
                    sbuf.append(
                            "   <option value=\"" + siteId + "\">" + site.getName() + abbrev + "</option>\n");
                }
            }
        }
        sbuf.append("</select>\n");
        item = sbuf.toString();
    } else if (inputType.equals("patientid")) {
        //ExecutionContext exec = ExecutionContext.get();
        WebContext exec = WebContextFactory.get();
        SessionUtil zeprs_session = null;
        String patientSiteId = null;
        try {
            zeprs_session = (SessionUtil) exec.getSession().getAttribute("zeprs_session");
            patientSiteId = zeprs_session.getClientSettings().getSiteId().toString();
        } catch (Exception e) {
            // unit testing - it's ok...
        }
        Site site = (Site) DynaSiteObjects.getClinicMap().get(new Long(patientSiteId));
        String siteAlphaId = site.getSiteAlphaId().substring(0, 2);
        String clinicId = site.getSiteAlphaId().substring(2, 3);
        ArrayList uthSubsites = new ArrayList();
        uthSubsites.add("A");
        uthSubsites.add("B");
        uthSubsites.add("C");
        uthSubsites.add("D");

        sbuf.append("<input type=\"hidden\" id=\"district\" value=\"5040\">\n");
        //sbuf.append("<input type=\"text\" id=\"site\" value=\"" + siteAlphaId + "\">\n");
        sbuf.append("<input type=\"hidden\" id=\"site\" value=\"\">\n");
        sbuf.append(
                "<br/>Select Subsite: <select id=\"subsite\" onchange=\"calcPatientId();\"><option> -- </option>\n");
        if (clinicId.equals("A") || clinicId.equals("B") || clinicId.equals("C") || clinicId.equals("D")) {
            for (int i = 0; i < uthSubsites.size(); i++) {
                String subsite = (String) uthSubsites.get(i);
                if (clinicId.equals(subsite)) {
                    sbuf.append("<option value=\"" + subsite + "\" selected=\"selected\">* " + subsite
                            + " *</option>\n");
                } else {
                    sbuf.append("<option value=\"" + subsite + "\"> " + subsite + " </option>\n");
                }
            }
        } else {
            int subsite = 0;
            while (subsite <= 10) {
                int clinicIdInt = new Integer(clinicId);
                if (clinicIdInt == subsite) {
                    sbuf.append("<option value=\"" + subsite + "\" selected=\"selected\">* " + subsite
                            + " *</option>\n");
                } else {
                    sbuf.append("<option value=\"" + subsite + "\"> " + subsite + " </option>\n");
                }
                subsite++;
            }
        }
        sbuf.append("</select>\n");
        sbuf.append(
                "<input class=\"ibutton\" onclick=\"copySite();setPatientID('patient','Please select District and clinic fields.','patientid');\" value=\"Get New ID\" title=\"Get New ID\" type=\"button\">\n");
        sbuf.append("<span id=\"spanpatient\"></span>");
        sbuf.append(
                "<div id=\"patientIdRow\"><br/> -- or -- <br/><br/>If patient already has an ID please enter the last five digits:");
        sbuf.append("<span id=\"patientIdFields\">\n"
                + "                <input id=\"patientid\" name=\"patientid\" size=\"4\" maxlength=\"5\" onchange=\"copySite();calcPatientId()\" type=\"text\">\n"
                + "                <input id=\"checksum\" name=\"checksum\" onchange=\"calcPatientId()\" type=\"hidden\">\n"
                + "                <input id=\"checkPatientId\" class=\"ibutton\" onclick='copySite();checkPatientID(\"patient\",\"Please select/enter all of the Patient ID fields.\",\"patientid\");' value=\"Check ID\" title=\"Check ID\" type=\"button\">\n"
                + "            </span>\n</div>\n");
        sbuf.append("<span id=\"d1\" class=\"reply\"></span>\n");
        sbuf.append("<input id=\"patient\" type=\"hidden\" name=\"field" + formFieldId
                + "\" size=\"20\" maxlength=\"255\"" + "\" value=\"" + value + "\"/>\n");
        // sbuf.append("<input id=\"" + widgetName + "\" type=\"text\" name=\"field" + formFieldId + "\" size=\"20\" maxlength=\"255\"" + "\" value=\"" + value + "\"" + getEventHandler("onchange", updateRecord, encounterId) + "/>\n");
        sbuf.append("<input id=\"siteId\" type=\"hidden\" name=\"field" + formFieldId + "\"/>\n");

        /*if ((pageItem.getSize() != null) && (pageItem.getSize().intValue() > 0)) {
        sbuf.append("<input id=\"" + widgetName + "\" type=\"text\" name=\"field" + formFieldId + "\" size=\"" + pageItem.getSize() + "\" maxlength=\"" + pageItem.getMaxlength() + "\" value=\"" + value + "\"" + getEventHandler("onchange", updateRecord, encounterId) + "/>\n");
        } else {
        }*/
        item = sbuf.toString();
    } else if (inputType.equals("currentMedicine")) {
        List drugs = null;
        // drugs = DrugsDAO.getAll();
        drugs = DynaSiteObjects.getDrugs();
        sbuf.append("<select id=\"" + widgetName + "\" name=\"field" + formFieldId + "\""
                + getEventHandler("onchange", updateRecord, encounterId) + ">\n");
        sbuf.append("   <option value=\"\">No Information</option>\n");
        for (int i = 0; i < drugs.size(); i++) {
            Drugs drug = (Drugs) drugs.get(i);
            //if (value.equals(drug.getName())) {
            Pattern pattern = Pattern.compile(drug.getName());
            Matcher matcher = pattern.matcher(value);
            if (matcher.find() == true) {
                if (drug.getTeratogenic() != null) {
                    sbuf.append(
                            "   <option value=\"" + drug.getId() + "\" selected  class=\"teratogenicAlert\">"
                                    + drug.getName() + " *" + drug.getTeratogenic() + "*</option>\n");
                } else {
                    sbuf.append("   <option value=\"" + drug.getId() + "\" selected>" + drug.getName()
                            + "</option>\n");
                }
            } else {
                if (drug.getTeratogenic() != null) {
                    sbuf.append("   <option value=\"" + drug.getId() + "\" class=\"teratogenicAlert\">"
                            + drug.getName() + " *" + drug.getTeratogenic() + "*</option>\n");
                } else {
                    sbuf.append("   <option value=\"" + drug.getId() + "\">" + drug.getName() + "</option>\n");
                }
            }
        }
        sbuf.append("</select>\n");
        item = sbuf.toString();

    } else if (inputType.equals("firm")) {
        sbuf.append("<select id=\"" + widgetName + "\" name=\"field" + formFieldId + "\""
                + getEventHandler("onchange", updateRecord, encounterId) + ">\n");
        sbuf.append("   <option value=\"\">No Information</option>\n");
        ArrayList firms = new ArrayList();
        firms.add("A");
        firms.add("B");
        firms.add("C");
        firms.add("D");
        firms.add("E");
        for (int i = 0; i < firms.size(); i++) {
            String firm = (String) firms.get(i);
            sbuf.append("   <option value=\"" + firm + "\">" + firm + "</option>\n");
        }
        sbuf.append("</select>\n");
        item = sbuf.toString();

    } else if (inputType.equals("ega") || inputType.equals("ega_pregnancyDating")) {

        sbuf.append("<select id=\"" + widgetName + "\" name=\"field" + formFieldId + "\""
                + getEventHandler("onchange", updateRecord, encounterId) + ">\n");
        sbuf.append("   <option value=\"\">No Information</option>\n");
        for (int i = 0; i < 350; i++) {

            int days = i % 7;
            int weeks = i / 7;
            String thisEga = weeks + ", " + days + "/7";
            if (value.equals(thisEga)) {
                sbuf.append("   <option value=\"" + i + "\" selected>" + weeks + " weeks, " + days + "/ 7 days"
                        + "</option>\n");
            } else {
                sbuf.append("   <option value=\"" + i + "\">" + weeks + " weeks, " + days + "/ 7 days"
                        + "</option>\n");
            }
        }
        sbuf.append("</select>\n");
        item = sbuf.toString();
    } else if (inputType.equals("textarea")) {
        Integer cols = pageItem.getCols();
        Integer rows = pageItem.getRows();
        if (cols == 0) {
            cols = 32;
        }
        if (rows == 0) {
            rows = 2;
        }
        if (!value.trim().equals("")) {
            sbuf.append("<textarea id=\"" + widgetName + "\" name=\"" + widgetName + "\" cols=\"" + cols
                    + "\" rows=\"" + rows + "\"" + getEventHandler("onchange", updateRecord, encounterId) + ">"
                    + value + "</textarea>\n");
        } else {
            sbuf.append("<textarea id=\"" + widgetName + "\" name=\"" + widgetName + "\" cols=\"" + cols
                    + "\" rows=\"" + rows + "\"" + getEventHandler("onchange", updateRecord, encounterId)
                    + "/>\n");
        }
        item = sbuf.toString();

    } else if (inputType.equals("checkbox") || inputType.equals("checkbox_dwr")) {
        if (value.equals("Yes")) {
            sbuf.append("<input type=\"checkbox\" checked id=\"" + widgetName + "\" name=\"field" + formFieldId
                    + "\" " + getEventHandler("onchange", updateRecord, encounterId) + ">" + "\n");
        } else if (value.equals("1")) {
            sbuf.append("<input type=\"checkbox\" checked id=\"" + widgetName + "\" name=\"field" + formFieldId
                    + "\" " + getEventHandler("onchange", updateRecord, encounterId) + ">" + "\n");
        } else {
            sbuf.append("<input type=\"checkbox\" id=\"" + widgetName + "\" name=\"field" + formFieldId + "\" "
                    + getEventHandler("onchange", updateRecord, encounterId) + ">" + "\n");
        }
        item = sbuf.toString();

    } else if (inputType.equals("text") || inputType.equals("text-dwr")) {
        if ((pageItem.getSize() != null) && (pageItem.getSize().intValue() > 0)) {
            sbuf.append(
                    "<input id=\"" + widgetName + "\" type=\"text\" name=\"field" + formFieldId + "\" size=\""
                            + pageItem.getSize() + "\" maxlength=\"" + pageItem.getMaxlength() + "\" value=\""
                            + value + "\"" + getEventHandler("onchange", updateRecord, encounterId) + "/>\n");
        } else {
            sbuf.append("<input id=\"" + widgetName + "\" type=\"text\" name=\"field" + formFieldId
                    + "\" size=\"20\" maxlength=\"255\" value=\"" + value + "\""
                    + getEventHandler("onchange", updateRecord, encounterId) + "/>\n");
        }
        // sbuf.append("<input type=\"button\" name=\"_add\" value=\"Change\"" + onClick + ">\n");
        item = sbuf.toString();

    } else if (inputType.equals("month_no_label")) {
        if ((pageItem.getSize() != null) && (pageItem.getSize().intValue() > 0)) {
            sbuf.append("<input id=\"" + widgetName + "\" type=\"text\" name=\"field" + formFieldId
                    + "\" size=\"" + pageItem.getSize() + "\" maxlength=\"" + pageItem.getMaxlength() + "\""
                    + getEventHandler("onchange", updateRecord, encounterId) + "/>\n");
        } else {
            sbuf.append("<input id=\"" + widgetName + "\" type=\"text\" name=\"field" + formFieldId
                    + "\" size=\"20\" maxlength=\"255\""
                    + getEventHandler("onchange", updateRecord, encounterId) + "/>\n");
        }
        // sbuf.append("<input type=\"button\" name=\"_add\" value=\"Change\"" + onClick + ">\n");
        item = sbuf.toString();

    } else if (inputType.equals("Yes/No")) {
        if (value.equals("true")) {
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldY" + formFieldId
                    + "\" value=\"1\" checked " + getEventHandler("onclick", updateRecordIdNameY, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Yes</label>\n");
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldN" + formFieldId
                    + "\" value=\"0\" " + getEventHandler("onclick", updateRecordIdNameN, encounterId)
                    + "/><label for=\"" + formFieldId + "\">No</label>\n");
        } else if (value.equals("Yes")) {
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldY" + formFieldId
                    + "\" value=\"1\" checked " + getEventHandler("onclick", updateRecordIdNameY, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Yes</label>\n");
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldN" + formFieldId
                    + "\" value=\"0\" " + getEventHandler("onclick", updateRecordIdNameN, encounterId)
                    + "/><label for=\"" + formFieldId + "\">No</label>\n");
        } else if (value.equals("false")) {
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldY" + formFieldId
                    + "\" value=\"1\" " + getEventHandler("onclick", updateRecordIdNameY, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Yes</label>\n");
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldN" + formFieldId
                    + "\" value=\"0\" checked " + getEventHandler("onclick", updateRecordIdNameN, encounterId)
                    + "/><label for=\"" + formFieldId + "\">No</label>\n");
        } else if (value.equals("No")) {
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldY" + formFieldId
                    + "\" value=\"1\" " + getEventHandler("onclick", updateRecordIdNameY, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Yes</label>\n");
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldN" + formFieldId
                    + "\" value=\"0\" checked " + getEventHandler("onclick", updateRecordIdNameN, encounterId)
                    + "/><label for=\"" + formFieldId + "\">No</label>\n");
        } else {
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldY" + formFieldId
                    + "\" value=\"1\" " + getEventHandler("onclick", updateRecordIdNameY, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Yes</label>\n");
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldN" + formFieldId
                    + "\" value=\"0\" " + getEventHandler("onclick", updateRecordIdNameN, encounterId)
                    + "/><label for=\"" + formFieldId + "\">No</label>\n");
        }
        item = sbuf.toString();
    } else if (inputType.equals("sex")) {
        if (value.equals("Female")) {
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldY" + formFieldId
                    + "\" value=\"1\" checked " + getEventHandler("onclick", updateRecordIdNameY, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Female</label>\n");
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldN" + formFieldId
                    + "\" value=\"2\" " + getEventHandler("onclick", updateRecordIdNameN, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Male</label>\n");
        } else if (value.equals("Male")) {
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldY" + formFieldId
                    + "\" value=\"1\" " + getEventHandler("onclick", updateRecordIdNameY, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Female</label>\n");
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldN" + formFieldId
                    + "\" value=\"2\" checked " + getEventHandler("onclick", updateRecordIdNameN, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Male</label>\n");
        } else {
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldY" + formFieldId
                    + "\" value=\"1\" " + getEventHandler("onclick", updateRecordIdNameY, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Female</label>\n");
            sbuf.append("<input type=\"radio\" name=\"field" + formFieldId + "\" id=\"fieldN" + formFieldId
                    + "\" value=\"2\" " + getEventHandler("onclick", updateRecordIdNameN, encounterId)
                    + "/><label for=\"" + formFieldId + "\">Male</label>\n");
        }
        item = sbuf.toString();
    } else if (inputType.equals("apgar")) {
        sbuf.append("<p>Click a value from each row to calculate the Apgar score.</p>");
        sbuf.append("<table border=1 cellspacing=\"0\" cellpadding=2 id=\"" + formFieldId + "apgar\">\n"
                + "\t<tr bgcolor=\"#99ccff\" id=\"" + formFieldId + "min\">\n" + "\t\t<th>Signs</th>\n"
                + "\t\t<th>0</th>\n" + "\t\t<th>1</th>\n" + "\n" + "\t\t<th>2</th>\n" + "\t\t<th id=\""
                + formFieldId
                + "1min\" style=\"background-color: #0033cc; color: White;\" onMouseOver=\"this.style.cursor='pointer'\" onClick=\"whatMin(this.id);\"><br>score</th>\n"
                + "\t</tr>\n" + "\n" + "\t<tr id=\"" + formFieldId + "h\">\n"
                + "\t\t<th align=right>Heart Rate</th>\n" + "\n" + "\t\t<td align=center id=\"" + formFieldId
                + "h0\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Absent</td>\n" + "\t\t<td align=center id=\"" + formFieldId
                + "h1\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Below 100</td>\n" + "\t\t<td align=center id=\"" + formFieldId
                + "h2\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Above 100</td>\n" + "\t\t<td class=\"score\" id=\"" + formFieldId
                + "1h\" onClick=\"whatMin(this.id," + formFieldId + ");\">&nbsp;</td>\n" + "\t</tr>\n" + "\n"
                + "\t<tr id=\"" + formFieldId + "r\">\n" + "\t\t<th align=right>Respiratory Effort</th>\n"
                + "\t\t<td align=center id=\"" + formFieldId
                + "r0\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Absent</td>\n" + "\n" + "\t\t<td align=center id=\"" + formFieldId
                + "r1\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Slow, irregular</td>\n" + "\t\t<td align=center id=\"" + formFieldId
                + "r2\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Good, crying</td>\n" + "\t\t<td class=\"score\" id=\"" + formFieldId
                + "1r\" onClick=\"whatMin(this.id," + formFieldId + ");\">&nbsp;</td>\n" + "\t</tr>\n" + "\n"
                + "\t<tr id=\"" + formFieldId + "m\">\n" + "\t\t<th align=right>Muscle Tone</th>\n"
                + "\t\t<td align=center id=\"" + formFieldId
                + "m0\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Nil (Limp)</td>\n" + "\t\t<td align=center id=\"" + formFieldId
                + "m1\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Some flexion<br>of extremities</td>\n" + "\n"
                + "\t\t<td align=center id=\"" + formFieldId
                + "m2\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Active motion</td>\n" + "\t\t<td class=\"score\" id=\"" + formFieldId
                + "1m\" onClick=\"whatMin(this.id," + formFieldId + ");\">&nbsp;</td>\n" + "\n" + "\t</tr>\n"
                + "\n" + "\t<tr id=\"" + formFieldId + "x\">\n"
                + "\t\t<th align=right>Reflex irritability</th>\n" + "\t\t<td align=center id=\"" + formFieldId
                + "x0\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">No response</td>\n" + "\n" + "\t\t<td align=center id=\"" + formFieldId
                + "x1\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Grimace</td>\n" + "\t\t<td align=center id=\"" + formFieldId
                + "x2\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Vigorous Cry</td>\n" + "\t\t<td class=\"score\" id=\"" + formFieldId
                + "1x\" onClick=\"whatMin(this.id," + formFieldId + ");\">&nbsp;</td>\n" + "\t</tr>\n" + "\n"
                + "\t<tr id=\"" + formFieldId + "c\">\n" + "\t\t<th align=right>Color</th>\n"
                + "\t\t<td align=center id=\"" + formFieldId
                + "c0\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Blue, pale</td>\n" + "\t\t<td align=center id=\"" + formFieldId
                + "c1\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Body pink,<br>extremities blue</td>\n" + "\n"
                + "\t\t<td align=center id=\"" + formFieldId
                + "c2\" onMouseOver=\"bgclr(this,1); this.style.cursor='pointer'\" onMouseOut=\"bgclr(this,0);\" onClick=\"bgclr(this,2,"
                + formFieldId + ");\">Completely pink</td>\n" + "\t\t<td class=\"score\" id=\"" + formFieldId
                + "1c\" onClick=\"whatMin(this.id," + formFieldId + ");\">&nbsp;</td>\n" + "\t</tr>\n" + "\n"
                + "\t<tr id=\"" + formFieldId + "total\">\n"
                + "\t\t<th height=\"44px\" colspan=4 align=right>\n" + "\t\t\tTOTAL SCORE :&nbsp;\n"
                + "\t\t</th>\n" + "\t\t<td class=\"score\" id=\"" + formFieldId
                + "1score\" onClick=\"whatMin(this.id," + formFieldId + ");\">&nbsp;</td>\n" + "\t</tr>\n"
                + "</table>");
        sbuf.append("<input type=\"button\" name=\"_add\" value=\"Change\""
                + getEventHandler("onclick", updateRecord, encounterId) + ">\n");
        sbuf.append("<input id=\"inputWidget" + formFieldId + "\" type=\"text\" name=\"field" + formFieldId
                + "\" size=\"20\" maxlength=\"255\"/>\n");
        // sbuf.append("<input type=\"button\" name=\"_add\" value=\"Change\"" + onClick + ">\n");
        item = sbuf.toString();
    } else if (inputType.equals("fundal_height")) {
        sbuf.append("<select id=\"" + widgetName + "\" name=\"field" + formFieldId + "\""
                + getEventHandler("onchange", updateRecord, encounterId) + ">\n");
        sbuf.append("   <option value=\"\"> -- </option>\n"); // routine ante chart - use " -- " for not recorded.
        if (value.equals("6")) {
            sbuf.append("   <option value=\"6\" selected><12</option>\n");
        } else {
            sbuf.append("   <option value=\"6\"><12</option>\n");
        }

        for (int i = 12; i < 55; i++) {
            if (value.equals(String.valueOf(i))) {
                sbuf.append("   <option value=\"" + i + "\" selected>" + i + "</option>\n");
            } else {
                sbuf.append("   <option value=\"" + i + "\">" + i + "</option>\n");
            }
        }
        sbuf.append("</select>\n");
        item = sbuf.toString();

        //    sbuf.append("<input id=\"" + widgetName + "\" type=\"text\" name=\"field" + formFieldId + "\" size=\"3\" maxlength=\"3\" value=\"" + value + "\"" + getEventHandler("onchange", updateRecord, encounterId) + "/>\n");
        //  item = sbuf.toString();
    } else if (inputType.equals("hidden-no-edit")) {
        sbuf.append("Editing forbidden for this value.\n");
        item = sbuf.toString();
    } else if (inputType.equals("hidden-no-listing")) {
        sbuf.append("Editing forbidden for this value.\n");
        item = sbuf.toString();
    } else {
        if (inputType.startsWith("SiteId")) { //Encounter record metadata
            List sites = null;
            sites = DynaSiteObjects.getClinics();
            sbuf.append("<select id=\"" + widgetName + "\" name=\"field" + inputType + "\""
                    + getEventHandler("onchange", updateRecord, encounterId) + ">\n");
            sbuf.append("   <option value=\"\">No Information</option>\n");
            for (int i = 0; i < sites.size(); i++) {
                Site site = (Site) sites.get(i);
                if (site.getInactive() == null) {
                    String siteId = site.getId().toString();
                    if (value.equals(site.getSiteAlphaId())) {
                        sbuf.append("   <option value=\"" + siteId + "\" selected>" + site.getName()
                                + "</option>\n");
                    } else {
                        sbuf.append("   <option value=\"" + siteId + "\">" + site.getName() + "</option>\n");
                    }
                }
            }
            sbuf.append("</select>\n");
            item = sbuf.toString();
        } else {
            sbuf.append("*tbd* " + inputType + "\n");
            item = sbuf.toString();
        }
    }
    return item;
}

From source file:com.sfs.whichdoctor.analysis.GroupAnalysisDAOImpl.java

/**
 * Builds the order.// ww  w.  j  a v a2 s  . c  om
 *
 * @param referenceObjects the reference objects
 * @param groupClass the group class
 *
 * @return the tree map< string, integer>
 */
private TreeMap<String, Integer> buildOrder(final TreeMap<Integer, Object> referenceObjects,
        final String groupClass) {

    if (referenceObjects == null) {
        throw new NullPointerException("The reference objects map cannot be null");
    }
    if (groupClass == null) {
        throw new NullPointerException("The group class string cannot be null");
    }

    dataLogger.debug("Building order for " + groupClass + ", with a size of: " + referenceObjects.size());

    TreeMap<String, Integer> orderMap = new TreeMap<String, Integer>();

    for (Integer referenceGUID : referenceObjects.keySet()) {
        Object reference = referenceObjects.get(referenceGUID);
        String orderKey = GroupAnalysisBean.getOrderKey(reference, groupClass);
        orderMap.put(orderKey, referenceGUID);
    }

    return orderMap;
}

From source file:com.inmobi.conduit.local.LocalStreamService.java

private void populateCheckpointPathForCollector(Table<String, String, String> checkpointPaths,
        TreeMap<String, FileStatus> collectorPaths) {
    // Last file in sorted ascending order to be check-pointed for this
    // collector/*from w w  w .ja va  2 s  . c om*/
    if (collectorPaths != null && collectorPaths.size() > 0) {
        Entry<String, FileStatus> entry = collectorPaths.lastEntry();
        Path filePath = entry.getValue().getPath();
        String streamName = getCategoryFromSrcPath(filePath);
        String collectorName = filePath.getParent().getName();
        String checkpointPath = filePath.getName();
        checkpointPaths.put(streamName, collectorName, checkpointPath);
    }
}

From source file:org.sakaiproject.tool.assessment.ui.listener.author.SaveAssessmentSettings.java

public AssessmentFacade save(AssessmentSettingsBean assessmentSettings,
        boolean isFromConfirmPublishAssessmentListener) {
    // create an assessment based on the title entered and the assessment
    // template selected
    // #1 - set Assessment
    Long assessmentId = assessmentSettings.getAssessmentId();
    //log.info("**** save assessment assessmentId ="+assessmentId.toString());
    ItemAuthorBean iAuthor = new ItemAuthorBean();
    //System.out.println("assessmentSettings.getFeedbackAuthoring: "+assessmentSettings.getFeedbackAuthoring());
    iAuthor.setShowFeedbackAuthoring(assessmentSettings.getFeedbackAuthoring());
    //System.out.println("iAuthor.getShowFeedbackAuthoring :"+iAuthor.getShowFeedbackAuthoring());
    AssessmentService assessmentService = new AssessmentService();
    AssessmentFacade assessment = assessmentService.getAssessment(assessmentId.toString());
    //log.info("** assessment = "+assessment);
    assessment.setTitle(/*from  w  w w . j  a v  a 2s  .co  m*/
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getTitle()));
    //assessment.setTitle(assessmentSettings.getTitle());
    assessment.setDescription(assessmentSettings.getDescription());
    assessment.updateAssessmentMetaData(AssessmentMetaDataIfc.AUTHORS,
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getAuthors()));

    // #2 - set AssessmentAccessControl
    AssessmentAccessControl control = (AssessmentAccessControl) assessment.getAssessmentAccessControl();
    if (control == null) {
        control = new AssessmentAccessControl();
        // need to fix accessControl so it can take AssessmentFacade later
        control.setAssessmentBase(assessment.getData());
    }
    // a. LATER set dueDate, retractDate, startDate, releaseTo
    if (isFromConfirmPublishAssessmentListener) {
        if (assessmentSettings.getStartDate() != null) {
            control.setStartDate(assessmentSettings.getStartDate());
        } else {
            control.setStartDate(new Date());
        }
    } else {
        control.setStartDate(assessmentSettings.getStartDate());
    }
    control.setDueDate(assessmentSettings.getDueDate());
    control.setRetractDate(assessmentSettings.getRetractDate());
    control.setFeedbackDate(assessmentSettings.getFeedbackDate());
    control.setReleaseTo(assessmentSettings.getReleaseTo());
    //log.info("control RELEASETO ="+control.getReleaseTo());
    //log.info("settings RELEASETO ="+assessmentSettings.getReleaseTo());

    // b. set Timed Assessment
    //log.info("** Time limit update to = "+assessmentSettings.getTimeLimit().intValue());
    control.setTimeLimit(assessmentSettings.getTimeLimit());
    if (assessmentSettings.getTimedAssessment())
        control.setTimedAssessment(AssessmentAccessControl.TIMED_ASSESSMENT);
    else
        control.setTimedAssessment(AssessmentAccessControl.DO_NOT_TIMED_ASSESSMENT);

    // c. set Assessment Orgainzation
    if (assessmentSettings.getItemNavigation() != null) {
        String nav = assessmentSettings.getItemNavigation();
        if ("1".equals(nav)) {
            assessmentSettings.setAssessmentFormat("1");
        }
        control.setItemNavigation(Integer.valueOf(nav));
    }
    if (assessmentSettings.getItemNumbering() != null)
        control.setItemNumbering(new Integer(assessmentSettings.getItemNumbering()));
    if (assessmentSettings.getAssessmentFormat() != null)
        control.setAssessmentFormat(new Integer(assessmentSettings.getAssessmentFormat()));

    if (assessmentSettings.getIsMarkForReview())
        control.setMarkForReview(AssessmentAccessControl.MARK_FOR_REVIEW);
    else {
        control.setMarkForReview(AssessmentAccessControl.NOT_MARK_FOR_REVIEW);
    }

    // d. set Submissions
    if (assessmentSettings.getUnlimitedSubmissions() != null) {
        if (!assessmentSettings.getUnlimitedSubmissions()
                .equals(AssessmentAccessControlIfc.UNLIMITED_SUBMISSIONS.toString())) {
            control.setUnlimitedSubmissions(Boolean.FALSE);
            if (assessmentSettings.getSubmissionsAllowed() != null)
                control.setSubmissionsAllowed(new Integer(assessmentSettings.getSubmissionsAllowed()));
            else
                control.setSubmissionsAllowed(Integer.valueOf("1"));
        } else {
            control.setUnlimitedSubmissions(Boolean.TRUE);
            control.setSubmissionsAllowed(null);
        }
    }

    //log.info("**unlimited submission="+assessmentSettings.getUnlimitedSubmissions());
    //log.info("**allowed="+control.getSubmissionsAllowed());

    if (assessmentSettings.getLateHandling() != null) {
        control.setLateHandling(new Integer(assessmentSettings.getLateHandling()));
    }
    if (assessmentSettings.getSubmissionsSaved() != null) {
        control.setSubmissionsSaved(new Integer(assessmentSettings.getSubmissionsSaved()));
    }

    if (assessmentSettings.getAutoSubmit())
        control.setAutoSubmit(AssessmentAccessControl.AUTO_SUBMIT);
    else {
        control.setAutoSubmit(AssessmentAccessControl.DO_NOT_AUTO_SUBMIT);
    }
    assessment.setAssessmentAccessControl(control);

    // e. set Submission Messages
    control.setSubmissionMessage(assessmentSettings.getSubmissionMessage());
    // f. set username
    control.setUsername(
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getUsername()));
    // g. set password
    control.setPassword(
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getPassword()));
    // h. set finalPageUrl

    String finalPageUrl = "";
    if (assessmentSettings.getFinalPageUrl() != null) {
        finalPageUrl = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log,
                assessmentSettings.getFinalPageUrl().trim());
        if (finalPageUrl.length() != 0 && !finalPageUrl.toLowerCase().startsWith("http")) {
            finalPageUrl = "http://" + finalPageUrl;
        }
    }
    control.setFinalPageUrl(finalPageUrl);

    //#3 Feedback
    AssessmentFeedback feedback = (AssessmentFeedback) assessment.getAssessmentFeedback();
    if (feedback == null) {
        feedback = new AssessmentFeedback();
        // need to fix feeback so it can take AssessmentFacade later
        feedback.setAssessmentBase(assessment.getData());
    }
    if (assessmentSettings.getFeedbackDelivery() != null)
        feedback.setFeedbackDelivery(new Integer(assessmentSettings.getFeedbackDelivery()));
    if (StringUtils.isNotBlank(assessmentSettings.getFeedbackComponentOption()))
        feedback.setFeedbackComponentOption(new Integer(assessmentSettings.getFeedbackComponentOption()));
    if (assessmentSettings.getFeedbackAuthoring() != null)
        feedback.setFeedbackAuthoring(new Integer(assessmentSettings.getFeedbackAuthoring()));
    // if 'No feedback' (it corresponds to value 3) is selected, 
    // all components are unchecked
    if (feedback.getFeedbackDelivery().equals(new Integer("3"))) {
        feedback.setShowQuestionText(false);
        feedback.setShowStudentResponse(false);
        feedback.setShowCorrectResponse(false);
        feedback.setShowStudentScore(false);
        feedback.setShowStudentQuestionScore(false);
        feedback.setShowQuestionLevelFeedback(false);
        feedback.setShowSelectionLevelFeedback(false);
        feedback.setShowGraderComments(false);
        feedback.setShowStatistics(false);
    } else {
        feedback.setShowQuestionText(Boolean.valueOf(assessmentSettings.getShowQuestionText()));
        feedback.setShowStudentResponse(Boolean.valueOf(assessmentSettings.getShowStudentResponse()));
        feedback.setShowCorrectResponse(Boolean.valueOf(assessmentSettings.getShowCorrectResponse()));
        feedback.setShowStudentScore(Boolean.valueOf(assessmentSettings.getShowStudentScore()));
        feedback.setShowStudentQuestionScore(Boolean.valueOf(assessmentSettings.getShowStudentQuestionScore()));
        feedback.setShowQuestionLevelFeedback(
                Boolean.valueOf(assessmentSettings.getShowQuestionLevelFeedback()));
        feedback.setShowSelectionLevelFeedback(
                Boolean.valueOf(assessmentSettings.getShowSelectionLevelFeedback()));
        feedback.setShowGraderComments(Boolean.valueOf(assessmentSettings.getShowGraderComments()));
        feedback.setShowStatistics(Boolean.valueOf(assessmentSettings.getShowStatistics()));
    }
    assessment.setAssessmentFeedback(feedback);

    // g. set Grading
    EvaluationModel evaluation = (EvaluationModel) assessment.getEvaluationModel();
    if (evaluation == null) {
        evaluation = new EvaluationModel();
        // need to fix evaluation so it can take AssessmentFacade later
        evaluation.setAssessmentBase(assessment.getData());
    }

    String firstTargetSelected = assessmentSettings.getFirstTargetSelected();
    if ("Anonymous Users".equals(firstTargetSelected)) {
        evaluation.setAnonymousGrading(Integer.valueOf("1"));
        evaluation.setToGradeBook("2");
    } else {
        if (assessmentSettings.getAnonymousGrading()) {
            evaluation.setAnonymousGrading(Integer.valueOf(1));
        } else {
            evaluation.setAnonymousGrading(Integer.valueOf(2));
        }
        if (assessmentSettings.getToDefaultGradebook()) {
            evaluation.setToGradeBook("1");
        } else {
            evaluation.setToGradeBook("2");
        }
    }

    if (assessmentSettings.getScoringType() != null)
        evaluation.setScoringType(new Integer(assessmentSettings.getScoringType()));
    assessment.setEvaluationModel(evaluation);

    // h. update ValueMap: it contains value for teh checkboxes in
    // authorSettings.jsp for: hasAvailableDate, hasDueDate,
    // hasRetractDate, hasAnonymous, hasAuthenticatedUser, hasIpAddress,
    // hasUsernamePassword,
    // hasTimeAssessment,hasAutoSubmit, hasPartMetaData, hasQuestionMetaData
    HashMap h = assessmentSettings.getValueMap();
    h = addExtendedTimeValuesToMetaData(assessment, assessmentSettings);
    updateMetaWithValueMap(assessment, h);

    // i. set Graphics
    assessment.updateAssessmentMetaData(AssessmentMetaDataIfc.BGCOLOR,
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getBgColor()));
    assessment.updateAssessmentMetaData(AssessmentMetaDataIfc.BGIMAGE,
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getBgImage()));

    // j. set objectives,rubrics,keywords
    assessment.updateAssessmentMetaData(AssessmentMetaDataIfc.KEYWORDS,
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getKeywords()));
    assessment.updateAssessmentMetaData(AssessmentMetaDataIfc.OBJECTIVES,
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getObjectives()));
    assessment.updateAssessmentMetaData(AssessmentMetaDataIfc.RUBRICS,
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, assessmentSettings.getRubrics()));

    // jj. save assessment first, then deal with ip
    assessmentService.saveAssessment(assessment);
    assessmentService.deleteAllSecuredIP(assessment);

    // k. set ipAddresses

    HashSet ipSet = new HashSet();
    String ipAddresses = assessmentSettings.getIpAddresses();
    if (ipAddresses == null)
        ipAddresses = "";

    String[] ip = ipAddresses.split("\\n");
    for (int j = 0; j < ip.length; j++) {
        if (ip[j] != null && !ip[j].equals("\r")) {

            ipSet.add(new SecuredIPAddress(assessment.getData(), null, ip[j]));
        }
    }
    assessment.setSecuredIPAddressSet(ipSet);

    // kk. secure delivery settings
    SecureDeliveryServiceAPI secureDeliveryService = SamigoApiFactory.getInstance()
            .getSecureDeliveryServiceAPI();
    assessment.updateAssessmentMetaData(SecureDeliveryServiceAPI.MODULE_KEY,
            assessmentSettings.getSecureDeliveryModule());
    String encryptedPassword = secureDeliveryService.encryptPassword(
            assessmentSettings.getSecureDeliveryModule(),
            assessmentSettings.getSecureDeliveryModuleExitPassword());
    assessment.updateAssessmentMetaData(SecureDeliveryServiceAPI.EXITPWD_KEY,
            TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, encryptedPassword));

    // kkk. remove the existing title decoration (if any) and then add the new one (if any)    
    String titleDecoration = assessment.getAssessmentMetaDataByLabel(SecureDeliveryServiceAPI.TITLE_DECORATION);
    String newTitle;
    if (titleDecoration != null)
        newTitle = assessment.getTitle().replace(titleDecoration, "");
    else
        newTitle = assessment.getTitle();

    // getTitleDecoration() returns "" if null or NONE module is passed
    titleDecoration = secureDeliveryService.getTitleDecoration(assessmentSettings.getSecureDeliveryModule(),
            new ResourceLoader().getLocale());
    if (titleDecoration != null && !titleDecoration.trim().equals("")) {
        newTitle = newTitle + " " + titleDecoration;
    }

    assessment.setTitle(newTitle);
    assessment.updateAssessmentMetaData(SecureDeliveryServiceAPI.TITLE_DECORATION, titleDecoration);

    // l. FINALLY: save the assessment
    assessmentService.saveAssessment(assessment);

    // added by daisyf, 10/10/06
    updateAttachment(assessment.getAssessmentAttachmentList(), assessmentSettings.getAttachmentList(),
            (AssessmentIfc) assessment.getData(), true);
    EventTrackingService.post(EventTrackingService.newEvent("sam.setting.edit", "siteId="
            + AgentFacade.getCurrentSiteId() + ", assessmentId=" + assessmentSettings.getAssessmentId(), true));

    AuthzQueriesFacadeAPI authz = PersistenceService.getInstance().getAuthzQueriesFacade();
    if (assessmentSettings.getReleaseTo().equals(AssessmentAccessControl.RELEASE_TO_SELECTED_GROUPS)) {
        authz.removeAuthorizationByQualifierAndFunction(assessmentId.toString(), "TAKE_ASSESSMENT");
        String[] groupsAuthorized = assessmentSettings.getGroupsAuthorizedToSave();//getGroupsAuthorized();
        if (groupsAuthorized != null && groupsAuthorized.length > 0) {
            for (int i = 0; i < groupsAuthorized.length; i++) {
                authz.createAuthorization(groupsAuthorized[i], "TAKE_ASSESSMENT", assessmentId.toString());
            }

            PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService();
            TreeMap groupsForSite = publishedAssessmentService.getGroupsForSite();
            if (groupsForSite != null && groupsForSite.size() > 0) {
                String releaseToGroups = getReleaseToGroupsAsString(groupsForSite, groupsAuthorized);
                assessmentSettings.setReleaseToGroupsAsString(releaseToGroups);
            }
        }
    } else { // releaseTo is not "Selected Groups" - clean up old/orphaned group permissions if necessary
        Collection groups = null;
        try {
            Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
            groups = site.getGroups();
        } catch (IdUnusedException ex) {
            // No site available
        }
        if (groups != null && groups.size() > 0) {
            Iterator groupIter = groups.iterator();
            while (groupIter.hasNext()) {
                Group group = (Group) groupIter.next();
                //try {
                authz.removeAuthorizationByAgentQualifierAndFunction(group.getId(), assessmentId.toString(),
                        "TAKE_ASSESSMENT");
                //}
                //catch (Exception ex) {
                // No authz permission data for the group
                //}
            }
        }
    }

    assessment = assessmentService.getAssessment(assessmentId.toString());

    return assessment;
}

From source file:com.sec.ose.osi.report.standard.data.BillOfMaterialsRowGenerator.java

private String getFileCountForFolders(ArrayList<IdentifiedFilesRow> fileEntList) {

    TreeMap<String, Integer> map = new TreeMap<String, Integer>(); // parent path, value

    if (fileEntList == null || fileEntList.size() == 0)
        return "<None>";

    for (IdentifiedFilesRow ent : fileEntList) {
        String parentPath = (new File(ent.getFullPath())).getParent();
        if (parentPath == null)
            parentPath = "";

        if (map.containsKey(parentPath) == false) {
            map.put(parentPath, 0);/*from   w w w .  j  av  a2  s. c  om*/
        }

        map.put(parentPath, map.get(parentPath) + 1);
    }

    if (map.size() == 0)
        return "";
    if (map.size() == 1)
        return ("(" + map.get(map.firstKey()) + " files)\n");

    String msg = "";
    for (String path : map.keySet()) {
        msg += path;
        if (!path.endsWith("/"))
            msg += "/ ";
        msg += "(" + map.get(path) + " files)\n";
    }
    msg = msg.replace("\\", "/");

    if (msg.length() > 0) {
        return msg.substring(0, msg.length() - 1);
    }

    return "";
}

From source file:org.lockss.servlet.AddContentTab.java

private Page doHtmlStatusTable0() throws IOException {
    page = new Page();
    addJS("js/DisplayContentTab.js");
    HttpSession session = getSession();//w  w w . j  av  a 2  s  .  c  o m
    Object actionMessage = session.getAttribute("actionMessage");
    if (actionMessage != null) {
        Block messageDiv = new Block(Block.Div);
        Image closeMessageImage = new Image(CLOSE_ICON);
        closeMessageImage.alt("Close message bar");
        closeMessageImage.attribute("title", "Close message bar");
        closeMessageImage.attribute("class", "messageDivClose");
        closeMessageImage.attribute("onclick", "hideMessages();");
        messageDiv.add(closeMessageImage);
        messageDiv.attribute("class", "messageDiv");
        Block messageSpan = new Block(Block.Span);
        messageSpan.add(actionMessage.toString());
        messageDiv.add(messageSpan);
        session.setAttribute("actionMessage", null);
        page.add(messageDiv);
    }
    Table divTable = createTabDiv(auStart);
    Collection<TitleSet> sets = getTitleSetsByName(auStart, auEnd, pluginMgr);
    for (TitleSet ts : sets) {
        if (!"All active AUs".equals(ts.getName()) && !"All inactive AUs".equals(ts.getName())) {
            String cleanNameString = cleanName(ts.getName());
            Collection<TitleConfig> titles = ts.getTitles();
            TreeMap<String, List<TitleConfig>> titleMap = orderTitleConfigByTitle(titles);
            createTitleRow(divTable, ts.getName(), titleMap.size());
            createAuRow(divTable, titleMap, cleanNameString);
            addClearRow(divTable, cleanNameString, false);
        }
    }
    Form tabForm = new Form();
    tabForm.method("POST");
    tabForm.attribute("id", "submitForm");
    tabForm.add(divTable);
    if (sets.size() > 0) {
        Input formAdd = new Input("submit", "addSubmit");
        formAdd.attribute("value", "Add selected");
        formAdd.attribute("id", "add-submit");
        formAdd.attribute("class", "submit-button");
        formAdd.attribute("onclick", "button='add'");
        tabForm.add(formAdd);
        Input formDelete = new Input("submit", "deleteSubmit");
        formDelete.attribute("value", "Delete selected");
        formDelete.attribute("id", "delete-submit");
        formDelete.attribute("class", "submit-button");
        formDelete.attribute("onclick", "button='delete'");
        tabForm.add(formDelete);
    }
    page.add(tabForm);
    return page;
}