Example usage for java.text DateFormat MEDIUM

List of usage examples for java.text DateFormat MEDIUM

Introduction

In this page you can find the example usage for java.text DateFormat MEDIUM.

Prototype

int MEDIUM

To view the source code for java.text DateFormat MEDIUM.

Click Source Link

Document

Constant for medium style pattern.

Usage

From source file:DateUtil.java

/**
 * Formats given date and time according to specified locale and <code>DateFormat.MEDIUM</code> style
 *
 * @param date   Date object to convert/* ww  w.  ja va  2 s . c o  m*/
 * @param locale Locale to use for formatting date and time
 * @return String representation of date and time according to given locale and <code>DateFormat.MEDIUM</code> style
 * @see java.text.DateFormat
 * @see java.text.DateFormat#MEDIUM
 */
public static String formatDateTime(Date date, Locale locale) {
    return formatDateTime(date, locale, DateFormat.MEDIUM, DateFormat.MEDIUM);
}

From source file:org.openmrs.web.WebUtil.java

public static String formatDate(Date date, Locale locale, FORMAT_TYPE type) {
    log.debug("Formatting date: " + date + " with locale " + locale);

    DateFormat dateFormat = null;

    if (type == FORMAT_TYPE.TIMESTAMP) {
        String dateTimeFormat = Context.getAdministrationService()
                .getGlobalPropertyValue(OpenmrsConstants.GP_SEARCH_DATE_DISPLAY_FORMAT, null);
        if (StringUtils.isEmpty(dateTimeFormat)) {
            dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        } else {//from  w  w w.j  ava 2  s  .c o  m
            dateFormat = new OpenmrsDateFormat(new SimpleDateFormat(dateTimeFormat), locale);
        }
    } else if (type == FORMAT_TYPE.TIME) {
        String timeFormat = Context.getAdministrationService()
                .getGlobalPropertyValue(OpenmrsConstants.GP_SEARCH_DATE_DISPLAY_FORMAT, null);
        if (StringUtils.isEmpty(timeFormat)) {
            dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        } else {
            dateFormat = new OpenmrsDateFormat(new SimpleDateFormat(timeFormat), locale);
        }
    } else if (type == FORMAT_TYPE.DATE) {
        String formatValue = Context.getAdministrationService()
                .getGlobalPropertyValue(OpenmrsConstants.GP_SEARCH_DATE_DISPLAY_FORMAT, "");
        if (StringUtils.isEmpty(formatValue)) {
            dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
        } else {
            dateFormat = new OpenmrsDateFormat(new SimpleDateFormat(formatValue), locale);
        }
    }
    return date == null ? "" : dateFormat.format(date);
}

From source file:free.yhc.netmbuddy.utils.Utils.java

public static void init(Context aAppContext) {
    // This is called first for module initialization.
    // So, ANY DEPENDENCY to other module is NOT allowed
    eAssert(!sInitialized);//from  ww w . j  a v  a 2  s.  c o m
    if (!sInitialized)
        sInitialized = true;

    new File(Policy.APPDATA_DIR).mkdirs();
    new File(Policy.APPDATA_VIDDIR).mkdirs();
    new File(Policy.APPDATA_LOGDIR).mkdirs();

    // Clear/Create cache directory!
    File cacheF = new File(Policy.APPDATA_CACHEDIR);
    FileUtils.removeFileRecursive(cacheF, cacheF);
    cacheF.mkdirs();

    // Clear/Make temp directory!
    File tempF = new File(Policy.APPDATA_TMPDIR);
    FileUtils.removeFileRecursive(tempF, tempF);
    tempF.mkdirs();

    if (LOGF) {
        new File(Policy.APPDATA_LOGDIR).mkdirs();
        String dateText = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.ENGLISH)
                .format(new Date(System.currentTimeMillis()));
        dateText = dateText.replace(' ', '_');
        File logF = new File(Policy.APPDATA_LOGDIR + dateText + ".log");
        try {
            sLogWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(logF)));
        } catch (FileNotFoundException e) {
            eAssert(false);
        }
    }

    sAppContext = aAppContext;
    sUiHandler = new Handler();
    sPrefs = PreferenceManager.getDefaultSharedPreferences(getAppContext());

}

From source file:org.sakaiproject.feedback.tool.entityproviders.FeedbackEntityProvider.java

private String handleReport(final EntityView view, final Map<String, Object> params, final String type) {

    final String userId = developerHelperService.getCurrentUserId();

    if (view.getPathSegments().length != 3) {
        return BAD_REQUEST;
    }//from  w  w  w  .j a v  a2  s .c  o m

    // Because the Feedback Tool EntityProvider parses URLs using forward slashes
    // (see /direct/feedback/describe) we replace forward slashes with a constant
    // and substitute them back here
    // TODO Doesn't this have a possible NPE?
    final String siteId = view.getPathSegment(1).replaceAll(FeedbackTool.FORWARD_SLASH, "/");

    if (logger.isDebugEnabled())
        logger.debug("Site ID: " + siteId);

    final String title = (String) params.get("title");
    final String description = (String) params.get("description");
    final boolean siteExists = new Boolean((String) params.get("siteExists"));

    final String browserNameAndVersion = requestGetter.getRequest().getHeader("User-Agent");
    final String osNameAndVersion = (String) params.get("oscpu");
    final String windowHeight = (String) params.get("windowHeight");
    final String windowWidth = (String) params.get("windowWidth");
    final String browserSize = windowWidth + " x " + windowHeight + " pixels";
    final String screenHeight = (String) params.get("screenHeight");
    final String screenWidth = (String) params.get("screenWidth");
    final String screenSize = screenWidth + " x " + screenHeight + " pixels";
    final String plugins = (String) params.get("plugins");
    final String ip = requestGetter.getRequest().getRemoteAddr();
    int fmt = DateFormat.MEDIUM;
    Locale locale = sakaiProxy.getLocale();
    DateFormat format = DateFormat.getDateTimeInstance(fmt, fmt, locale);
    final String currentTime = format.format(new Date());

    if (title == null || title.isEmpty()) {
        logger.debug("Subject incorrect. Returning " + BAD_TITLE + " ...");
        return BAD_TITLE;
    }

    if (description == null || description.isEmpty()) {
        logger.debug("No summary. Returning " + BAD_DESCRIPTION + " ...");
        return BAD_DESCRIPTION;
    }

    if (logger.isDebugEnabled())
        logger.debug("title: " + title + ". description: " + description);

    String toAddress = null;

    boolean addNoContactMessage = false;

    // The senderAddress can be either picked up from the current user's
    // account, or manually entered by the user submitting the report.
    String senderAddress = null;

    if (userId != null) {
        senderAddress = sakaiProxy.getUser(userId).getEmail();

        String alternativeRecipientId = (String) params.get("alternativerecipient");

        if (alternativeRecipientId != null && alternativeRecipientId.length() > 0) {
            User alternativeRecipientUser = sakaiProxy.getUser(alternativeRecipientId);

            if (alternativeRecipientUser != null) {
                toAddress = alternativeRecipientUser.getEmail();
                addNoContactMessage = true;
            } else {
                try {
                    //validate site contact email address
                    InternetAddress emailAddr = new InternetAddress(alternativeRecipientId);
                    emailAddr.validate();
                    toAddress = alternativeRecipientId;
                } catch (AddressException ex) {
                    logger.error(
                            "Incorrectly formed site contact email address. Returning BADLY_FORMED_RECIPIENT...");
                    return BADLY_FORMED_RECIPIENT;
                }
            }
        } else {
            toAddress = getToAddress(type, siteId);
        }
    } else {
        // Recaptcha
        if (sakaiProxy.getConfigBoolean("user.recaptcha.enabled", false)) {
            String publicKey = sakaiProxy.getConfigString("user.recaptcha.public-key", "");
            String privateKey = sakaiProxy.getConfigString("user.recaptcha.private-key", "");
            ReCaptcha captcha = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
            String challengeField = (String) params.get("recaptcha_challenge_field");
            String responseField = (String) params.get("recaptcha_response_field");
            if (challengeField == null)
                challengeField = "";
            if (responseField == null)
                responseField = "";
            String remoteAddress = requestGetter.getRequest().getRemoteAddr();
            ReCaptchaResponse response = captcha.checkAnswer(remoteAddress, challengeField, responseField);
            if (!response.isValid()) {
                logger.warn("Recaptcha failed with this message: " + response.getErrorMessage());
                return RECAPTCHA_FAILURE;
            }
        }

        senderAddress = (String) params.get("senderaddress");
        if (senderAddress == null || senderAddress.length() == 0) {
            logger.error("No sender email address for non logged in user. Returning BAD REQUEST ...");
            return BAD_REQUEST;
        }

        toAddress = getToAddress(type, siteId);
    }

    if (toAddress == null || toAddress.isEmpty()) {
        logger.error("No recipient. Returning BAD REQUEST ...");
        return BAD_REQUEST;
    }

    if (senderAddress != null && senderAddress.length() > 0) {
        List<FileItem> attachments = null;

        try {
            attachments = getAttachments(params);
            sakaiProxy.sendEmail(userId, senderAddress, toAddress, addNoContactMessage, siteId, type, title,
                    description, attachments, siteExists, browserNameAndVersion, osNameAndVersion, browserSize,
                    screenSize, plugins, ip, currentTime);
            db.logReport(userId, senderAddress, siteId, type, title, description);
            return SUCCESS;
        } catch (AttachmentsTooBigException atbe) {
            logger.error("The total size of the attachments exceeded the permitted limit of "
                    + maxAttachmentsBytes + ". '" + ATTACHMENTS_TOO_BIG + "' will be returned to the client.");
            return ATTACHMENTS_TOO_BIG;
        } catch (SQLException sqlException) {
            logger.error("Caught exception while generating report. '" + Database.DB_ERROR
                    + "' will be returned to the client.", sqlException);
            return Database.DB_ERROR;
        } catch (Exception e) {
            logger.error("Caught exception while sending email or generating report. '" + ERROR
                    + "' will be returned to the client.", e);
            return ERROR;
        }
    } else {
        logger.error("Failed to determine a sender address No email or report will be generated. '"
                + NO_SENDER_ADDRESS + "' will be returned to the client.");
        return NO_SENDER_ADDRESS;
    }
}

From source file:org.nuxeo.ecm.core.schema.types.constraints.DateIntervalConstraint.java

@Override
public String getErrorMessage(Object invalidValue, Locale locale) {
    // test whether there's a custom translation for this field constraint specific translation
    // the expected key is label.schema.constraint.violation.[ConstraintName].mininmaxin ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].minexmaxin ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].mininmaxex ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].minexmaxex ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].minin ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].minex ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].maxin ou
    // the expected key is label.schema.constraint.violation.[ConstraintName].maxex
    // follow the AbstractConstraint behavior otherwise
    Locale computedLocale = locale != null ? locale : Constraint.MESSAGES_DEFAULT_LANG;
    Object[] params;/*from  w  ww  . j a v a  2 s .co m*/
    String subKey = (minTime != null ? (includingMin ? "minin" : "minex") : "")
            + (maxTime != null ? (includingMax ? "maxin" : "maxex") : "");
    DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM, computedLocale);
    if (minTime != null && maxTime != null) {
        String min = format.format(new Date(minTime));
        String max = format.format(new Date(maxTime));
        params = new Object[] { min, max };
    } else if (minTime != null) {
        String min = format.format(new Date(minTime));
        params = new Object[] { min };
    } else {
        String max = format.format(new Date(maxTime));
        params = new Object[] { max };
    }
    List<String> pathTokens = new ArrayList<String>();
    pathTokens.add(MESSAGES_KEY);
    pathTokens.add(DateIntervalConstraint.NAME);
    pathTokens.add(subKey);
    String key = StringUtils.join(pathTokens, '.');
    String message = getMessageString(MESSAGES_BUNDLE, key, params, computedLocale);
    if (message != null && !message.trim().isEmpty() && !key.equals(message)) {
        // use a custom constraint message if there's one
        return message;
    } else {
        // follow AbstractConstraint behavior otherwise
        return super.getErrorMessage(invalidValue, computedLocale);
    }
}

From source file:org.sakaiproject.evaluation.tool.producers.EvaluationAssignProducer.java

public void fill(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    // local variables used in the render logic
    String currentUserId = commonLogic.getCurrentUserId();
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
    DateFormat dtf = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, locale);

    navBarRenderer.makeNavBar(tofill, NavBarRenderer.NAV_ELEMENT, this.getViewID());

    EvalViewParameters evalViewParams = (EvalViewParameters) viewparams;
    if (evalViewParams.evaluationId == null) {
        throw new IllegalArgumentException("Cannot access this view unless the evaluationId is set");
    }/* w  ww.ja  v a2 s.  c o  m*/

    /**
     * This is the evaluation we are working with on this page,
     * this should ONLY be read from, do not change any of these fields
     */
    EvalEvaluation evaluation = evaluationService.getEvaluationById(evalViewParams.evaluationId);

    //Are we using the selection options (UCT)? YES
    boolean useSelectionOptions = ((Boolean) settings.get(EvalSettings.ENABLE_INSTRUCTOR_ASSISTANT_SELECTION));

    //find out is this evaluation will contain any Instructor/TA questions based in it's template
    List<String> validItemCategories;
    boolean hasInstructorQuestions = true;
    boolean hasAssistantQuestions = true;
    if (useSelectionOptions) {
        validItemCategories = renderingUtils.extractCategoriesInTemplate(evaluation.getTemplate().getId());
        hasInstructorQuestions = validItemCategories.contains(EvalConstants.ITEM_CATEGORY_INSTRUCTOR);
        hasAssistantQuestions = validItemCategories.contains(EvalConstants.ITEM_CATEGORY_ASSISTANT);
    }

    LOG.debug("Template id: " + evaluation.getTemplate().getId() + " useSelectionOptions: "
            + useSelectionOptions + " hasInstructorQuestions: " + hasInstructorQuestions
            + " hasAssistantQuestions: " + hasAssistantQuestions);

    String actionBean = "setupEvalBean.";
    Boolean newEval = false;

    UIInternalLink.make(tofill, "eval-settings-link", UIMessage.make("evalsettings.page.title"),
            new EvalViewParameters(EvaluationSettingsProducer.VIEW_ID, evalViewParams.evaluationId));
    if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(evaluation.getState())) {
        // creating a new eval
        UIMessage.make(tofill, "eval-start-text", "starteval.page.title");
        newEval = true;
    }

    UIMessage.make(tofill, "assign-eval-edit-page-title", "assigneval.assign.page.title",
            new Object[] { evaluation.getTitle() });
    UIMessage.make(tofill, "assign-eval-instructions", "assigneval.assign.instructions",
            new Object[] { evaluation.getTitle() });

    UIMessage.make(tofill, "evalAssignInstructions", "evaluationassignconfirm.eval.assign.instructions",
            new Object[] { df.format(evaluation.getStartDate()) });

    // display info about the evaluation (dates and what not)
    UIOutput.make(tofill, "startDate", dtf.format(evaluation.getStartDate()));

    if (evaluation.getDueDate() != null) {
        UIBranchContainer branch = UIBranchContainer.make(tofill, "showDueDate:");
        UIOutput.make(branch, "dueDate", dtf.format(evaluation.getDueDate()));
    }

    if (evaluation.getStopDate() != null) {
        UIBranchContainer branch = UIBranchContainer.make(tofill, "showStopDate:");
        UIOutput.make(branch, "stopDate", dtf.format(evaluation.getStopDate()));
    }

    if (evaluation.getViewDate() != null) {
        UIBranchContainer branch = UIBranchContainer.make(tofill, "showViewDate:");
        UIOutput.make(branch, "viewDate", dtf.format(evaluation.getViewDate()));
    }

    /* 
     * About this form.
     * 
     * This is a GET form that has 2 UISelects, one for Hierarchy Nodes, and
     * one for Eval Groups (which includes adhoc groups).  They are interspered
     * and mixed together. In order to do this easily we pass in empty String
     * arrays for the option values and labels in the UISelects. This is partially
     * because rendering each individual checkbox requires and integer indicating
     * it's position, and this view is too complicated to generate these arrays
     * ahead of time.  So we generate the String Arrays on the fly, using the list.size()-1
     * at each point to get this index.  Then at the very end we update the UISelect's
     * with the appropriate optionlist and optionnames. This actually works 
     * really good and the wizard feels much smoother than it did with the 
     * old session bean.
     * 
     * Also see the comments on HierarchyTreeNodeSelectRenderer. 
     * 
     */
    UIForm form = UIForm.make(tofill, "eval-assign-form");

    // Things for building the UISelect of Hierarchy Node Checkboxes
    List<String> hierNodesLabels = new ArrayList<>();
    List<String> hierNodesValues = new ArrayList<>();
    UISelect hierarchyNodesSelect = UISelect.makeMultiple(form, "hierarchyNodeSelectHolder", new String[] {},
            new String[] {}, (useSelectionOptions ? actionBean : "") + "selectedHierarchyNodeIDs",
            evalViewParams.selectedHierarchyNodeIDs);
    String hierNodesSelectID = hierarchyNodesSelect.getFullID();

    // Things for building the UISelect of Eval Group Checkboxes
    List<String> evalGroupsLabels = new ArrayList<>();
    List<String> evalGroupsValues = new ArrayList<>();
    UISelect evalGroupsSelect = UISelect.makeMultiple(form, "evalGroupSelectHolder", new String[] {},
            new String[] {}, (useSelectionOptions ? actionBean : "") + "selectedGroupIDs",
            evalViewParams.selectedGroupIDs == null ? new String[] {} : evalViewParams.selectedGroupIDs);
    String evalGroupsSelectID = evalGroupsSelect.getFullID();

    /*
     * About the 4 collapsable areas.
     * 
     * What's happening here is that we have 4 areas: hierarchy, groups, 
     * new adhoc groups, and existing adhoc groups that can be hidden and selected
     * which a checkbox for each one.
     * 
     */

    Boolean useAdHocGroups = (Boolean) settings.get(EvalSettings.ENABLE_ADHOC_GROUPS);
    Boolean showHierarchy = (Boolean) settings.get(EvalSettings.DISPLAY_HIERARCHY_OPTIONS);

    // NOTE: this is the one place where the perms should be used instead of user assignments (there are no assignments yet) -AZ

    // get the current eval group id (ie: reference site id) that the user is in now
    String currentEvalGroupId = commonLogic.getCurrentEvalGroup();
    // get the current eval group id (ie: site id) that the user is in now
    String currentSiteId = EntityReference.getIdFromRef(currentEvalGroupId);

    // get the groups that this user is allowed to assign evals to
    List<EvalGroup> assignEvalGroups;
    // for backwards compatibility we will pull the list of groups the user is being evaluated in as well and merge it in
    List<EvalGroup> beEvalGroups;

    Boolean isGroupFilterEnabled = (Boolean) settings.get(EvalSettings.ENABLE_FILTER_ASSIGNABLE_GROUPS);

    if (isGroupFilterEnabled) {
        assignEvalGroups = commonLogic.getFilteredEvalGroupsForUser(currentUserId,
                EvalConstants.PERM_ASSIGN_EVALUATION, currentSiteId);
        beEvalGroups = commonLogic.getFilteredEvalGroupsForUser(currentUserId, EvalConstants.PERM_BE_EVALUATED,
                currentSiteId);
    } else {
        assignEvalGroups = commonLogic.getEvalGroupsForUser(currentUserId,
                EvalConstants.PERM_ASSIGN_EVALUATION);
        beEvalGroups = commonLogic.getEvalGroupsForUser(currentUserId, EvalConstants.PERM_BE_EVALUATED);
    }

    /*
     * EVALSYS-987- Side effect
     * remove ad hoc groups from view as they are handled already in another 
     * section in the same view. 
     */
    List<EvalGroup> evalGroups = new ArrayList<>();
    for (EvalGroup evalGroup : assignEvalGroups) {
        if (!evalGroups.contains(evalGroup) && !EvalConstants.GROUP_TYPE_ADHOC.equals(evalGroup.type)) {
            evalGroups.add(evalGroup);
        }
    }

    for (EvalGroup evalGroup : beEvalGroups) {
        if (!evalGroups.contains(evalGroup) && !EvalConstants.GROUP_TYPE_ADHOC.equals(evalGroup.type)) {
            evalGroups.add(evalGroup);
        }
    }

    if (evalGroups.size() > 0) {
        Map<String, EvalGroup> groupsMap = new HashMap<>();
        for (int i = 0; i < evalGroups.size(); i++) {
            EvalGroup c = (EvalGroup) evalGroups.get(i);
            groupsMap.put(c.evalGroupId, c);
        }

        /*
         * Area 1. Selection GUI for Hierarchy Nodes and Evaluation Groups
         */
        if (showHierarchy) {
            //need to determine who can see what nodes in the hierarchy:
            //null means the user is an admin, empty means the user has no access
            Set<String> parentNodes = null;
            Set<String> accessNodes = null;
            if (!commonLogic.isUserAdmin(currentUserId)) {
                parentNodes = new HashSet<>();
                accessNodes = new HashSet<>();
                Set<EvalHierarchyNode> nodes = hierarchyLogic.getNodesForUserPerm(currentUserId,
                        EvalConstants.HIERARCHY_PERM_ASSIGN_EVALUATION);
                for (EvalHierarchyNode node : nodes) {
                    accessNodes.add(node.id);
                    accessNodes.addAll(node.childNodeIds);
                    parentNodes.add(node.id);
                    parentNodes.addAll(node.parentNodeIds);
                }
            }

            UIBranchContainer hierarchyArea = UIBranchContainer.make(form, "hierarchy-node-area:");

            hierUtil.renderSelectHierarchyNodesTree(hierarchyArea, "hierarchy-tree-select:", evalGroupsSelectID,
                    hierNodesSelectID, evalGroupsLabels, evalGroupsValues, hierNodesLabels, hierNodesValues,
                    evalViewParams, accessNodes, parentNodes, evaluation.getSectionAwareness());

            addCollapseControl(tofill, hierarchyArea, "initJSHierarchyToggle", "hierarchy-assignment-area",
                    "hide-button", "show-button", evalViewParams.expanded == null);

            form.parameters.add(new UIELBinding(actionBean + "expanded", evalViewParams.expanded));
        }

        /*
         * Area 2. display checkboxes for selecting the non-hierarchy groups
         */
        UIBranchContainer evalgroupArea = UIBranchContainer.make(form, "evalgroups-area:");

        // If both the hierarchy and adhoc groups are disabled, don't hide the
        // selection area and don't make it collapsable, since it will be the
        // only thing on the screen.
        if (!showHierarchy && !useAdHocGroups) {
            UIOutput.make(evalgroupArea, "evalgroups-assignment-area");
        } else {
            addCollapseControl(tofill, evalgroupArea, "initJSGroupsToggle", "evalgroups-assignment-area",
                    "hide-button", "show-button", true);
        }

        String[] nonAssignedEvalGroupIDs = getEvalGroupIDsNotAssignedInHierarchy(evalGroups)
                .toArray(new String[] {});

        List<EvalGroup> unassignedEvalGroups = new ArrayList<>();
        for (String nonAssignedEvalGroupID : nonAssignedEvalGroupIDs) {
            unassignedEvalGroups.add(groupsMap.get(nonAssignedEvalGroupID));
        }

        if (!unassignedEvalGroups.isEmpty()) {

            // sort the list by title 
            Collections.sort(unassignedEvalGroups, new ComparatorsUtils.GroupComparatorByTitle());

            //Move current site to top of this list EVALSYS-762.
            int count2 = 0;
            for (EvalGroup group : unassignedEvalGroups) {
                if (group.evalGroupId.equals(currentEvalGroupId)) {
                    unassignedEvalGroups.remove(count2);
                    unassignedEvalGroups.add(0, group);
                    break;
                }
                count2++;
            }

            List<String> assignGroupsIds = new ArrayList<>();
            String groupSelectionOTP = "assignGroupSelectionSettings.";
            if (!newEval) {
                Map<Long, List<EvalAssignGroup>> selectedGroupsMap = evaluationService
                        .getAssignGroupsForEvals(new Long[] { evalViewParams.evaluationId }, true, null);
                List<EvalAssignGroup> assignGroups = selectedGroupsMap.get(evalViewParams.evaluationId);
                for (EvalAssignGroup assGroup : assignGroups) {
                    assignGroupsIds.add(assGroup.getEvalGroupId());

                    //Add group selection settings to form to support EVALSYS-778
                    if (useSelectionOptions) {
                        Map<String, String> selectionOptions = assGroup.getSelectionOptions();
                        form.parameters.add(new UIELBinding(
                                groupSelectionOTP + assGroup.getEvalGroupId()
                                        .replaceAll(EvalConstants.GROUP_ID_SITE_PREFIX, "") + ".instructor",
                                selectionOptions.get(EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR)));
                        form.parameters.add(new UIELBinding(
                                groupSelectionOTP + assGroup.getEvalGroupId()
                                        .replaceAll(EvalConstants.GROUP_ID_SITE_PREFIX, "") + ".assistant",
                                selectionOptions.get(EvalAssignGroup.SELECTION_TYPE_ASSISTANT)));
                    }
                }
            }

            int count = 0;
            int countUnpublishedGroups = 0;
            for (EvalGroup evalGroup : unassignedEvalGroups) {
                if (evalGroup != null) {

                    String evalGroupId = evalGroup.evalGroupId;

                    boolean hasEvaluators = true;

                    if (!EvalConstants.EVALUATION_AUTHCONTROL_NONE.equals(evaluation.getAuthControl())) {
                        int numEvaluatorsInSite = commonLogic.countUserIdsForEvalGroup(evalGroupId,
                                EvalConstants.PERM_TAKE_EVALUATION, evaluation.getSectionAwareness());
                        hasEvaluators = numEvaluatorsInSite > 0;
                    }

                    boolean isPublished = commonLogic.isEvalGroupPublished(evalGroupId);

                    UIBranchContainer checkboxRow = UIBranchContainer.make(evalgroupArea, "groups:",
                            count + "");
                    if (count % 2 == 0) {
                        checkboxRow.decorate(new UIStyleDecorator("itemsListOddLine")); // must match the existing CSS class
                    }
                    checkboxRow.decorate(new UIFreeAttributeDecorator("rel", count + "")); // table row counter for JS use in EVALSYS-618

                    //keep deselected user info as a result of changes in EVALSYS-660
                    Set<String> deselectedInsructorIds = new HashSet<>();
                    Set<String> deselectedAssistantIds = new HashSet<>();

                    //Assign attribute to row to help JS set checkbox selection to true
                    if (assignGroupsIds.contains(evalGroupId)) {
                        checkboxRow.decorate(new UIStyleDecorator("selectedGroup"));
                    }

                    if (useSelectionOptions) {

                        if (!newEval) {
                            //Get saved selection settings for this eval
                            List<EvalAssignUser> deselectedInsructors = evaluationService
                                    .getParticipantsForEval(evalViewParams.evaluationId, null,
                                            new String[] { evalGroupId }, EvalAssignUser.TYPE_EVALUATEE,
                                            EvalAssignUser.STATUS_REMOVED, null, null);
                            List<EvalAssignUser> deselectedAssistants = evaluationService
                                    .getParticipantsForEval(evalViewParams.evaluationId, null,
                                            new String[] { evalGroupId }, EvalAssignUser.TYPE_ASSISTANT,
                                            EvalAssignUser.STATUS_REMOVED, null, null);

                            //check for already deselected users that match this groupId
                            for (EvalAssignUser deselectedUser : deselectedInsructors) {
                                deselectedInsructorIds.add(deselectedUser.getUserId());
                            }
                            for (EvalAssignUser deselectedUser : deselectedAssistants) {
                                deselectedAssistantIds.add(deselectedUser.getUserId());
                            }

                        } else {
                            //add blank selection options for this group for use by evalAssign.js
                            form.parameters
                                    .add(new UIELBinding(
                                            groupSelectionOTP + evalGroupId.replaceAll(
                                                    EvalConstants.GROUP_ID_SITE_PREFIX, "") + ".instructor",
                                            ""));
                            form.parameters
                                    .add(new UIELBinding(
                                            groupSelectionOTP + evalGroupId.replaceAll(
                                                    EvalConstants.GROUP_ID_SITE_PREFIX, "") + ".assistant",
                                            ""));
                        }
                    }

                    evalGroupsLabels.add(evalGroup.title);
                    evalGroupsValues.add(evalGroupId);

                    String evalUsersLocator = "selectedEvaluationUsersLocator.";

                    UISelectChoice choice = UISelectChoice.make(checkboxRow, "evalGroupId", evalGroupsSelectID,
                            evalGroupsLabels.size() - 1);

                    if (!hasEvaluators) {
                        choice.decorate(new UIDisabledDecorator());
                    }

                    if (useSelectionOptions) {
                        form.parameters.add(new UIELBinding(
                                evalUsersLocator
                                        + evalGroupId.replaceAll(EvalConstants.GROUP_ID_SITE_PREFIX, "")
                                        + ".deselectedInstructors",
                                deselectedInsructorIds.toArray(new String[deselectedInsructorIds.size()])));
                        form.parameters.add(new UIELBinding(
                                evalUsersLocator
                                        + evalGroupId.replaceAll(EvalConstants.GROUP_ID_SITE_PREFIX, "")
                                        + ".deselectedAssistants",
                                deselectedAssistantIds.toArray(new String[deselectedAssistantIds.size()])));

                        //add ordering bindings
                        form.parameters.add(new UIELBinding(evalUsersLocator
                                + evalGroupId.replaceAll(EvalConstants.GROUP_ID_SITE_PREFIX, "")
                                + ".orderingInstructors", new String[] {}));
                        form.parameters.add(new UIELBinding(evalUsersLocator
                                + evalGroupId.replaceAll(EvalConstants.GROUP_ID_SITE_PREFIX, "")
                                + ".orderingAssistants", new String[] {}));
                    }

                    // get title from the map since it is faster
                    UIOutput title = UIOutput.make(checkboxRow, "groupTitle", evalGroup.title);

                    if (!isPublished) {
                        title.decorate(new UIStyleDecorator("elementAlertBack"));
                        countUnpublishedGroups++;
                    }

                    if (useSelectionOptions) {
                        if (hasEvaluators) {
                            int totalUsers = commonLogic.countUserIdsForEvalGroup(evalGroupId,
                                    EvalConstants.PERM_BE_EVALUATED, evaluation.getSectionAwareness());
                            if (totalUsers > 0 && hasInstructorQuestions) {
                                int currentUsers = deselectedInsructorIds.size() >= 0
                                        ? (totalUsers - deselectedInsructorIds.size())
                                        : totalUsers;
                                UIInternalLink link = UIInternalLink.make(checkboxRow, "select-instructors",
                                        UIMessage.make("assignselect.instructors.select",
                                                new Object[] { currentUsers, totalUsers }),
                                        new EvalViewParameters(EvaluationAssignSelectProducer.VIEW_ID,
                                                evaluation.getId(), evalGroupId,
                                                EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR));
                                link.decorate(new UIStyleDecorator("addItem total:" + totalUsers));
                                link.decorate(new UITooltipDecorator(
                                        messageLocator.getMessage("assignselect.instructors.page.title")));
                            }
                            totalUsers = commonLogic.countUserIdsForEvalGroup(evalGroup.evalGroupId,
                                    EvalConstants.PERM_ASSISTANT_ROLE, evaluation.getSectionAwareness());
                            if (totalUsers > 0 && hasAssistantQuestions) {
                                int currentUsers = deselectedAssistantIds.size() >= 0
                                        ? (totalUsers - deselectedAssistantIds.size())
                                        : totalUsers;
                                UIInternalLink link = UIInternalLink.make(checkboxRow, "select-tas",
                                        UIMessage.make("assignselect.tas.select",
                                                new Object[] { currentUsers, totalUsers }),
                                        new EvalViewParameters(EvaluationAssignSelectProducer.VIEW_ID,
                                                evaluation.getId(), evalGroup.evalGroupId,
                                                EvalAssignGroup.SELECTION_TYPE_ASSISTANT));
                                link.decorate(new UIStyleDecorator("addItem total:" + totalUsers));
                                link.decorate(new UITooltipDecorator(
                                        messageLocator.getMessage("assignselect.tas.page.title")));
                            }
                        } else {
                            title.decorate(new UIStyleDecorator("instruction"));
                            UIMessage.make(checkboxRow, "select-no", "assigneval.cannot.assign");
                        }
                    }

                    UILabelTargetDecorator.targetLabel(title, choice); // make title a label for checkbox

                    count++;
                }
            }
            if (countUnpublishedGroups > 0) {
                UIMessage.make(tofill, "assign-eval-instructions-group-notpublished",
                        "assigneval.assign.instructions.notpublished");
            }

        }

    } else {
        // TODO tell user there are no groups to assign to
    }

    /*
     * Area 3: Selection GUI for Adhoc Groups
     */
    String[] adhocGroupRowIds = new String[] {};
    if (useAdHocGroups) {
        UIBranchContainer adhocGroupsArea = UIBranchContainer.make(form, "use-adhoc-groups-area:");

        UIMessage.make(adhocGroupsArea, "adhoc-groups-deleted", "modifyadhocgroup.group.deleted");
        addCollapseControl(tofill, adhocGroupsArea, "initJSAdhocToggle", "adhocgroups-assignment-area",
                "hide-button", "show-button", false);

        // Table of Existing adhoc groups for selection
        List<EvalAdhocGroup> myAdhocGroups = commonLogic.getAdhocGroupsForOwner(currentUserId);
        if (myAdhocGroups.size() > 0) {
            UIOutput.make(adhocGroupsArea, "adhoc-groups-table");

            ArrayList<String> adhocGroupRowIdsArray = new ArrayList<>(myAdhocGroups.size());
            int count = 0;
            for (EvalAdhocGroup adhocGroup : myAdhocGroups) {
                UIBranchContainer tableRow = UIBranchContainer.make(adhocGroupsArea, "groups:");
                adhocGroupRowIdsArray.add(tableRow.getFullID());
                if (count % 2 == 0) {
                    tableRow.decorate(new UIStyleDecorator("itemsListOddLine")); // must match the existing CSS class
                }

                evalGroupsLabels.add(adhocGroup.getTitle());
                evalGroupsValues.add(adhocGroup.getEvalGroupId());

                UISelectChoice choice = UISelectChoice.make(tableRow, "evalGroupId", evalGroupsSelectID,
                        evalGroupsLabels.size() - 1);

                // get title from the map since it is faster
                UIOutput title = UIOutput.make(tableRow, "groupTitle", adhocGroup.getTitle());
                UILabelTargetDecorator.targetLabel(title, choice); // make title a label for checkbox

                // Link to allow editing an existing group
                UIInternalLink.make(tableRow, "editGroupLink",
                        UIMessage.make("assigneval.page.adhocgroups.editgrouplink"),
                        new AdhocGroupParams(ModifyAdhocGroupProducer.VIEW_ID, adhocGroup.getId(),
                                vsh.getFullURL(evalViewParams)));
                // add delete option - https://bugs.caret.cam.ac.uk/browse/CTL-1310
                if (currentUserId.equals(adhocGroup.getOwner()) || commonLogic.isUserAdmin(currentUserId)) {
                    String deleteLink = commonLogic.getEntityURL(AdhocGroupEntityProvider.ENTITY_PREFIX,
                            adhocGroup.getId().toString());
                    UILink.make(tableRow, "deleteGroupLink", UIMessage.make("general.command.delete"),
                            deleteLink);
                }
                count++;
            }
            adhocGroupRowIds = adhocGroupRowIdsArray.toArray(new String[adhocGroupRowIdsArray.size()]);
        }
        UIInternalLink.make(adhocGroupsArea, "new-adhocgroup-link",
                UIMessage.make("assigneval.page.adhocgroups.newgrouplink"),
                new AdhocGroupParams(ModifyAdhocGroupProducer.VIEW_ID, null, vsh.getFullURL(evalViewParams)));
    }

    // Add all the groups and hierarchy nodes back to the UISelect Many's. see
    // the large comment further up.
    evalGroupsSelect.optionlist = UIOutputMany.make(evalGroupsValues.toArray(new String[] {}));
    evalGroupsSelect.optionnames = UIOutputMany.make(evalGroupsLabels.toArray(new String[] {}));

    hierarchyNodesSelect.optionlist = UIOutputMany.make(hierNodesValues.toArray(new String[] {}));
    hierarchyNodesSelect.optionnames = UIOutputMany.make(hierNodesLabels.toArray(new String[] {}));

    form.parameters.add(new UIELBinding(actionBean + "evaluationId", evalViewParams.evaluationId));

    UIMessage.make(form, "back-button", "general.back.button");

    if (useSelectionOptions) {
        UIOutput.make(tofill, "JS-facebox");
        UIOutput.make(tofill, "JS-facebox-assign");
        UIOutput.make(tofill, "JS-assign");
        UIMessage.make(form, "select-column-title", "assignselect.page.column.title");
        form.type = EarlyRequestParser.ACTION_REQUEST;
        UICommand.make(form, "confirmAssignCourses", UIMessage.make("evaluationassignconfirm.done.button"),
                actionBean + "completeConfirmAction");
    } else {
        // this is a get form which does not submit to a backing bean
        EvalViewParameters formViewParams = (EvalViewParameters) evalViewParams.copyBase();
        formViewParams.viewID = EvaluationAssignConfirmProducer.VIEW_ID;
        form.viewparams = formViewParams;
        form.type = EarlyRequestParser.RENDER_REQUEST;
        // all command buttons are just HTML now so no more bindings
        UIMessage assignButton = UIMessage.make(form, "confirmAssignCourses",
                "assigneval.save.assigned.button");

        // activate the adhoc groups deletion javascript
        if (useAdHocGroups) {
            UIInitBlock.make(tofill, "initJavaScriptAdhoc", "EvalSystem.initEvalAssignAdhocDelete",
                    new Object[] { adhocGroupRowIds });
        }

        // Error message to be triggered by javascript if users doesn't select anything
        // There is a 'evalgroupselect' class on each input checkbox that the JS
        // can check for now.
        UIMessage assignErrorDiv = UIMessage.make(tofill, "nogroups-error", "assigneval.invalid.selection");

        boolean anonymousAllowed = false;
        if (EvalConstants.EVALUATION_AUTHCONTROL_NONE.equals(evaluation.getAuthControl())) {
            anonymousAllowed = true;
        }
        UIInitBlock.make(tofill, "initJavaScript", "EvalSystem.initEvalAssignValidation", new Object[] {
                form.getFullID(), assignErrorDiv.getFullID(), assignButton.getFullID(), anonymousAllowed });
    }

}

From source file:at.alladin.rmbt.controlServer.TestResultDetailResource.java

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();/*from  w ww .  j ava 2 s .  com*/

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT_DETAIL"), clientIpRaw));

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            String lang = request.optString("language");
            JSONArray options = request.optJSONArray("options");
            if (options != null) {
                for (int i = 0; i < options.length(); i++) {
                    final String op = options.optString(i, null);
                    if (op != null) {
                        if (OPTION_WITH_KEYS.equals(op.toUpperCase(Locale.US))) {
                            optionWithKeys = true;
                        }
                    }
                }
            }

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            } else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

            //                System.out.println(request.toString(4));

            if (conn != null) {

                final Client client = new Client(conn);
                final Test test = new Test(conn);
                TestNdt ndt = new TestNdt(conn);

                final String testUuid = request.optString("test_uuid");
                if (testUuid != null && test.getTestByUuid(UUID.fromString(testUuid)) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {

                    if (!ndt.loadByTestId(test.getUid()))
                        ndt = null;

                    final Locale locale = new Locale(lang);
                    final Format format = new SignificantFormat(2, locale);

                    final JSONArray resultList = new JSONArray();

                    final JSONObject singleItem = addObject(resultList, "time");
                    final Field timeField = test.getField("time");
                    if (!timeField.isNull()) {
                        final Date date = ((TimestampField) timeField).getDate();
                        final long time = date.getTime();
                        singleItem.put("time", time); //csv 3

                        final Field timezoneField = test.getField("timezone");
                        if (!timezoneField.isNull()) {
                            final String tzString = timezoneField.toString();
                            final TimeZone tz = TimeZone.getTimeZone(timezoneField.toString());
                            singleItem.put("timezone", tzString);

                            final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                                    DateFormat.MEDIUM, locale);
                            dateFormat.setTimeZone(tz);
                            singleItem.put("value", dateFormat.format(date));

                            final Format tzFormat = new DecimalFormat("+0.##;-0.##",
                                    new DecimalFormatSymbols(locale));

                            final float offset = tz.getOffset(time) / 1000f / 60f / 60f;
                            addString(resultList, "timezone", String.format("UTC%sh", tzFormat.format(offset)));
                        }
                    }

                    // speed download in Mbit/s (converted from kbit/s) - csv 10 (in kbit/s)
                    final Field downloadField = test.getField("speed_download");
                    if (!downloadField.isNull()) {
                        final String download = format.format(downloadField.doubleValue() / 1000d);
                        addString(resultList, "speed_download",
                                String.format("%s %s", download, labels.getString("RESULT_DOWNLOAD_UNIT")));
                    }

                    // speed upload im MBit/s (converted from kbit/s) - csv 11 (in kbit/s)
                    final Field uploadField = test.getField("speed_upload");
                    if (!uploadField.isNull()) {
                        final String upload = format.format(uploadField.doubleValue() / 1000d);
                        addString(resultList, "speed_upload",
                                String.format("%s %s", upload, labels.getString("RESULT_UPLOAD_UNIT")));
                    }

                    // median ping in ms
                    final Field pingMedianField = test.getField("ping_median");
                    if (!pingMedianField.isNull()) {
                        final String pingMedian = format.format(pingMedianField.doubleValue() / 1000000d);
                        addString(resultList, "ping_median",
                                String.format("%s %s", pingMedian, labels.getString("RESULT_PING_UNIT")));
                    }

                    // signal strength RSSI in dBm - csv 13
                    final Field signalStrengthField = test.getField("signal_strength");
                    if (!signalStrengthField.isNull())
                        addString(resultList, "signal_strength", String.format("%d %s",
                                signalStrengthField.intValue(), labels.getString("RESULT_SIGNAL_UNIT")));

                    //signal strength RSRP in dBm (LTE) - csv 29
                    final Field lteRsrpField = test.getField("lte_rsrp");
                    if (!lteRsrpField.isNull())
                        addString(resultList, "signal_rsrp", String.format("%d %s", lteRsrpField.intValue(),
                                labels.getString("RESULT_SIGNAL_UNIT")));

                    //signal quality in LTE, RSRQ in dB
                    final Field lteRsrqField = test.getField("lte_rsrq");
                    if (!lteRsrqField.isNull())
                        addString(resultList, "signal_rsrq", String.format("%d %s", lteRsrqField.intValue(),
                                labels.getString("RESULT_DB_UNIT")));

                    // network, eg. "3G (HSPA+)
                    //TODO fix helper-function
                    final Field networkTypeField = test.getField("network_type");
                    if (!networkTypeField.isNull())
                        addString(resultList, "network_type",
                                Helperfunctions.getNetworkTypeName(networkTypeField.intValue()));

                    // geo-location
                    JSONObject locationJson = getGeoLocation(this, test, settings, conn, labels);

                    if (locationJson != null) {
                        if (locationJson.has("location")) {
                            addString(resultList, "location", locationJson.getString("location"));
                        }
                        if (locationJson.has("country_location")) {
                            addString(resultList, "country_location",
                                    locationJson.getString("country_location"));
                        }
                        if (locationJson.has("motion")) {
                            addString(resultList, "motion", locationJson.getString("motion"));
                        }
                    }

                    // country derived from AS registry
                    final Field countryAsnField = test.getField("country_asn");
                    if (!countryAsnField.isNull())
                        addString(resultList, "country_asn", countryAsnField.toString());

                    // country derived from geo-IP database
                    final Field countryGeoipField = test.getField("country_geoip");
                    if (!countryGeoipField.isNull())
                        addString(resultList, "country_geoip", countryGeoipField.toString());

                    final Field zipCodeField = test.getField("zip_code");
                    if (!zipCodeField.isNull()) {
                        final String zipCode = zipCodeField.toString();
                        final int zipCodeInt = zipCodeField.intValue();
                        if (zipCodeInt > 999 || zipCodeInt <= 9999) // plausibility of zip code (must be 4 digits in Austria)
                            addString(resultList, "zip_code", zipCode);
                    }

                    final Field dataField = test.getField("data");
                    if (!Strings.isNullOrEmpty(dataField.toString())) {
                        final JSONObject data = new JSONObject(dataField.toString());

                        if (data.has("region"))
                            addString(resultList, "region", data.getString("region"));
                        if (data.has("municipality"))
                            addString(resultList, "municipality", data.getString("municipality"));
                        if (data.has("settlement"))
                            addString(resultList, "settlement", data.getString("settlement"));
                        if (data.has("whitespace"))
                            addString(resultList, "whitespace", data.getString("whitespace"));

                        if (data.has("cell_id"))
                            addString(resultList, "cell_id", data.getString("cell_id"));
                        if (data.has("cell_name"))
                            addString(resultList, "cell_name", data.getString("cell_name"));
                        if (data.has("cell_id_multiple") && data.getBoolean("cell_id_multiple"))
                            addString(resultList, "cell_id_multiple",
                                    getTranslation("value", "cell_id_multiple"));
                    }

                    final Field speedTestDurationField = test.getField("speed_test_duration");
                    if (!speedTestDurationField.isNull()) {
                        final String speedTestDuration = format
                                .format(speedTestDurationField.doubleValue() / 1000d);
                        addString(resultList, "speed_test_duration", String.format("%s %s", speedTestDuration,
                                labels.getString("RESULT_DURATION_UNIT")));
                    }

                    // public client ip (private)
                    addString(resultList, "client_public_ip", test.getField("client_public_ip"));

                    // AS number - csv 24
                    addString(resultList, "client_public_ip_as", test.getField("public_ip_asn"));

                    // name of AS
                    addString(resultList, "client_public_ip_as_name", test.getField("public_ip_as_name"));

                    // reverse hostname (from ip) - (private)
                    addString(resultList, "client_public_ip_rdns", test.getField("public_ip_rdns"));

                    // operator - derived from provider_id (only for pre-defined operators)
                    //TODO replace provider-information by more generic information
                    addString(resultList, "provider", test.getField("provider_id_name"));

                    // type of client local ip (private)
                    addString(resultList, "client_local_ip", test.getField("client_ip_local_type"));

                    // nat-translation of client - csv 23
                    addString(resultList, "nat_type", test.getField("nat_type"));

                    // wifi base station id SSID (numberic) eg 01:2c:3d..
                    addString(resultList, "wifi_ssid", test.getField("wifi_ssid"));
                    // wifi base station id - BSSID (text) eg 'my hotspot'
                    addString(resultList, "wifi_bssid", test.getField("wifi_bssid"));

                    // nominal link speed of wifi connection in MBit/s
                    final Field linkSpeedField = test.getField("wifi_link_speed");
                    if (!linkSpeedField.isNull())
                        addString(resultList, "wifi_link_speed", String.format("%s %s",
                                linkSpeedField.toString(), labels.getString("RESULT_WIFI_LINK_SPEED_UNIT")));
                    // name of mobile network operator (eg. 'T-Mobile AT')
                    addString(resultList, "network_operator_name", test.getField("network_operator_name"));

                    // mobile network name derived from MCC/MNC of network, eg. '232-01'
                    final Field networkOperatorField = test.getField("network_operator");

                    // mobile provider name, eg. 'Hutchison Drei' (derived from mobile_provider_id)
                    final Field mobileProviderNameField = test.getField("mobile_provider_name");
                    if (mobileProviderNameField.isNull()) // eg. '248-02'
                        addString(resultList, "network_operator", networkOperatorField);
                    else {
                        if (networkOperatorField.isNull())
                            addString(resultList, "network_operator", mobileProviderNameField);
                        else // eg. 'Hutchison Drei (232-10)'
                            addString(resultList, "network_operator",
                                    String.format("%s (%s)", mobileProviderNameField, networkOperatorField));
                    }

                    addString(resultList, "network_sim_operator_name",
                            test.getField("network_sim_operator_name"));

                    final Field networkSimOperatorField = test.getField("network_sim_operator");
                    final Field networkSimOperatorTextField = test
                            .getField("network_sim_operator_mcc_mnc_text");
                    if (networkSimOperatorTextField.isNull())
                        addString(resultList, "network_sim_operator", networkSimOperatorField);
                    else
                        addString(resultList, "network_sim_operator",
                                String.format("%s (%s)", networkSimOperatorTextField, networkSimOperatorField));

                    final Field roamingTypeField = test.getField("roaming_type");
                    if (!roamingTypeField.isNull())
                        addString(resultList, "roaming",
                                Helperfunctions.getRoamingType(labels, roamingTypeField.intValue()));

                    final long totalDownload = test.getField("total_bytes_download").longValue();
                    final long totalUpload = test.getField("total_bytes_upload").longValue();
                    final long totalBytes = totalDownload + totalUpload;
                    if (totalBytes > 0) {
                        final String totalBytesString = format.format(totalBytes / (1000d * 1000d));
                        addString(resultList, "total_bytes", String.format("%s %s", totalBytesString,
                                labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }

                    // interface volumes - total including control-server and pre-tests (and other tests)
                    final long totalIfDownload = test.getField("test_if_bytes_download").longValue();
                    final long totalIfUpload = test.getField("test_if_bytes_upload").longValue();
                    // output only total of down- and upload
                    final long totalIfBytes = totalIfDownload + totalIfUpload;
                    if (totalIfBytes > 0) {
                        final String totalIfBytesString = format.format(totalIfBytes / (1000d * 1000d));
                        addString(resultList, "total_if_bytes", String.format("%s %s", totalIfBytesString,
                                labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // interface volumes during test
                    // download test - volume in download direction
                    final long testDlIfBytesDownload = test.getField("testdl_if_bytes_download").longValue();
                    if (testDlIfBytesDownload > 0l) {
                        final String testDlIfBytesDownloadString = format
                                .format(testDlIfBytesDownload / (1000d * 1000d));
                        addString(resultList, "testdl_if_bytes_download", String.format("%s %s",
                                testDlIfBytesDownloadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // download test - volume in upload direction
                    final long testDlIfBytesUpload = test.getField("testdl_if_bytes_upload").longValue();
                    if (testDlIfBytesUpload > 0l) {
                        final String testDlIfBytesUploadString = format
                                .format(testDlIfBytesUpload / (1000d * 1000d));
                        addString(resultList, "testdl_if_bytes_upload", String.format("%s %s",
                                testDlIfBytesUploadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // upload test - volume in upload direction
                    final long testUlIfBytesUpload = test.getField("testul_if_bytes_upload").longValue();
                    if (testUlIfBytesUpload > 0l) {
                        final String testUlIfBytesUploadString = format
                                .format(testUlIfBytesUpload / (1000d * 1000d));
                        addString(resultList, "testul_if_bytes_upload", String.format("%s %s",
                                testUlIfBytesUploadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // upload test - volume in download direction
                    final long testUlIfBytesDownload = test.getField("testul_if_bytes_download").longValue();
                    if (testDlIfBytesDownload > 0l) {
                        final String testUlIfBytesDownloadString = format
                                .format(testUlIfBytesDownload / (1000d * 1000d));
                        addString(resultList, "testul_if_bytes_download", String.format("%s %s",
                                testUlIfBytesDownloadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }

                    //start time download-test 
                    final Field time_dl_ns = test.getField("time_dl_ns");
                    if (!time_dl_ns.isNull()) {
                        addString(resultList, "time_dl",
                                String.format("%s %s", format.format(time_dl_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //duration download-test 
                    final Field duration_download_ns = test.getField("nsec_download");
                    if (!duration_download_ns.isNull()) {
                        addString(resultList, "duration_dl",
                                String.format("%s %s",
                                        format.format(duration_download_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //start time upload-test 
                    final Field time_ul_ns = test.getField("time_ul_ns");
                    if (!time_ul_ns.isNull()) {
                        addString(resultList, "time_ul",
                                String.format("%s %s", format.format(time_ul_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //duration upload-test 
                    final Field duration_upload_ns = test.getField("nsec_upload");
                    if (!duration_upload_ns.isNull()) {
                        addString(resultList, "duration_ul",
                                String.format("%s %s",
                                        format.format(duration_upload_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    if (ndt != null) {
                        final String downloadNdt = format.format(ndt.getField("s2cspd").doubleValue());
                        addString(resultList, "speed_download_ndt",
                                String.format("%s %s", downloadNdt, labels.getString("RESULT_DOWNLOAD_UNIT")));

                        final String uploaddNdt = format.format(ndt.getField("c2sspd").doubleValue());
                        addString(resultList, "speed_upload_ndt",
                                String.format("%s %s", uploaddNdt, labels.getString("RESULT_UPLOAD_UNIT")));

                        // final String pingNdt =
                        // format.format(ndt.getField("avgrtt").doubleValue());
                        // addString(resultList, "ping_ndt",
                        // String.format("%s %s", pingNdt,
                        // labels.getString("RESULT_PING_UNIT")));
                    }

                    addString(resultList, "server_name", test.getField("server_name"));
                    addString(resultList, "plattform", test.getField("plattform"));
                    addString(resultList, "os_version", test.getField("os_version"));
                    addString(resultList, "model", test.getField("model_fullname"));
                    addString(resultList, "client_name", test.getField("client_name"));
                    addString(resultList, "client_software_version", test.getField("client_software_version"));
                    final String encryption = test.getField("encryption").toString();

                    if (encryption != null) {
                        addString(resultList, "encryption",
                                "NONE".equals(encryption) ? labels.getString("key_encryption_false")
                                        : labels.getString("key_encryption_true"));
                    }

                    addString(resultList, "client_version", test.getField("client_version"));

                    addString(resultList, "duration", String.format("%d %s",
                            test.getField("duration").intValue(), labels.getString("RESULT_DURATION_UNIT")));

                    // number of threads for download-test
                    final Field num_threads = test.getField("num_threads");
                    if (!num_threads.isNull()) {
                        addInt(resultList, "num_threads", num_threads);
                    }

                    //number of threads for upload-test
                    final Field num_threads_ul = test.getField("num_threads_ul");
                    if (!num_threads_ul.isNull()) {
                        addInt(resultList, "num_threads_ul", num_threads_ul);
                    }

                    //dz 2013-11-09 removed UUID from details as users might get confused by two
                    //              ids;
                    //addString(resultList, "uuid", String.format("T%s", test.getField("uuid")));

                    final Field openTestUUIDField = test.getField("open_test_uuid");
                    if (!openTestUUIDField.isNull())
                        addString(resultList, "open_test_uuid", String.format("O%s", openTestUUIDField));

                    //number of threads for upload-test
                    final Field tag = test.getField("tag");
                    if (!tag.isNull()) {
                        addString(resultList, "tag", tag);
                    }

                    if (ndt != null) {
                        addString(resultList, "ndt_details_main", ndt.getField("main"));
                        addString(resultList, "ndt_details_stat", ndt.getField("stat"));
                        addString(resultList, "ndt_details_diag", ndt.getField("diag"));
                    }

                    if (resultList.length() == 0)
                        errorList.addError("ERROR_DB_GET_TESTRESULT_DETAIL");

                    answer.put("testresultdetail", resultList);
                } else
                    errorList.addError("ERROR_REQUEST_TEST_RESULT_DETAIL_NO_UUID");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();

    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT_DETAIL_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:org.sakaiproject.poll.tool.producers.PollToolProducer.java

public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    voteBean.setPoll(null);//from  w  w w. java  2  s .  co  m
    voteBean.voteCollection = null;

    String locale = localegetter.get().toString();
    Map<String, String> langMap = new HashMap<String, String>();
    langMap.put("lang", locale);
    langMap.put("xml:lang", locale);

    UIOutput.make(tofill, "polls-html", null).decorate(new UIFreeAttributeDecorator(langMap));

    UIOutput.make(tofill, "poll-list-title", messageLocator.getMessage("poll_list_title"));

    boolean renderDelete = false;
    //populate the action links
    if (this.isAllowedPollAdd() || this.isSiteOwner()) {
        UIBranchContainer actions = UIBranchContainer.make(tofill, "actions:", Integer.toString(0));
        LOG.debug("this user has some admin functions");
        if (this.isAllowedPollAdd()) {
            LOG.debug("User can add polls");
            //UIOutput.make(tofill, "poll-add", messageLocator
            //       .getMessage("action_add_poll"));
            UIInternalLink.make(actions, NAVIGATE_ADD, UIMessage.make("action_add_poll"),
                    new PollViewParameters(AddPollProducer.VIEW_ID, "New 0"));
        }
        if (this.isSiteOwner()) {
            UIInternalLink.make(actions, NAVIGATE_PERMISSIONS, UIMessage.make("action_set_permissions"),
                    new SimpleViewParameters(PermissionsProducer.VIEW_ID));
        }
    }

    List<Poll> polls = new ArrayList<Poll>();

    String siteId = externalLogic.getCurrentLocationId();
    if (siteId != null) {
        polls = pollListManager.findAllPolls(siteId);
    } else {
        LOG.warn("Unable to get siteid!");

    }

    if (polls.isEmpty()) {
        UIOutput.make(tofill, "no-polls", messageLocator.getMessage("poll_list_empty"));
        UIOutput.make(tofill, "add-poll-icon");
        if (this.isAllowedPollAdd()) {
            UIInternalLink.make(tofill, "add-poll", UIMessage.make("new_poll_title"),
                    new PollViewParameters(AddPollProducer.VIEW_ID, "New 0"));
        }
    } else {
        // fix for broken en_ZA locale in JRE http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488119
        Locale M_locale = null;
        String langLoc[] = localegetter.get().toString().split("_");
        if (langLoc.length >= 2) {
            if ("en".equals(langLoc[0]) && "ZA".equals(langLoc[1]))
                M_locale = new Locale("en", "GB");
            else
                M_locale = new Locale(langLoc[0], langLoc[1]);
        } else {
            M_locale = new Locale(langLoc[0]);
        }

        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
        TimeZone tz = externalLogic.getLocalTimeZone();
        df.setTimeZone(tz);
        //m_log.debug("got timezone: " + tz.getDisplayName());

        UIOutput.make(tofill, "poll_list_remove_confirm",
                messageLocator.getMessage("poll_list_remove_confirm"));
        UIOutput.make(tofill, "poll_list_reset_confirm", messageLocator.getMessage("poll_list_reset_confirm"));

        UIForm deleteForm = UIForm.make(tofill, "delete-poll-form");
        // Create a multiple selection control for the tasks to be deleted.
        // We will fill in the options at the loop end once we have collected them.
        UISelect deleteselect = UISelect.makeMultiple(deleteForm, "delete-poll", null,
                "#{pollToolBean.deleteids}", new String[] {});

        //get the headers for the table
        /*UIMessage.make(deleteForm, "poll-question-title","poll_question_title");
        UIMessage.make(deleteForm, "poll-open-title", "poll_open_title");
        UIMessage.make(deleteForm, "poll-close-title", "poll_close_title");*/
        UIMessage.make(deleteForm, "poll-result-title", "poll_result_title");
        UIMessage.make(deleteForm, "poll-remove-title", "poll_remove_title");

        UILink question = UILink.make(tofill, "poll-question-title",
                messageLocator.getMessage("poll_question_title"), "#");
        question.decorators = new DecoratorList(
                new UITooltipDecorator(messageLocator.getMessage("poll_question_title_tooltip")));
        UILink open = UILink.make(tofill, "poll-open-title", messageLocator.getMessage("poll_open_title"), "#");
        open.decorators = new DecoratorList(
                new UITooltipDecorator(messageLocator.getMessage("poll_open_title_tooltip")));
        UILink close = UILink.make(tofill, "poll-close-title", messageLocator.getMessage("poll_close_title"),
                "#");
        close.decorators = new DecoratorList(
                new UITooltipDecorator(messageLocator.getMessage("poll_close_title_tooltip")));

        StringList deletable = new StringList();

        for (int i = 0; i < polls.size(); i++) {
            Poll poll = (Poll) polls.get(i);

            boolean canVote = pollVoteManager.pollIsVotable(poll);
            UIBranchContainer pollrow = UIBranchContainer.make(deleteForm,
                    canVote ? "poll-row:votable" : "poll-row:nonvotable", poll.getPollId().toString());
            LOG.debug("adding poll row for " + poll.getText());

            if (canVote) {
                UIInternalLink voteLink = UIInternalLink.make(pollrow, NAVIGATE_VOTE, poll.getText(),
                        new PollViewParameters(PollVoteProducer.VIEW_ID, poll.getPollId().toString()));
                //we need to add a decorator for the alt text
                voteLink.decorators = new DecoratorList(new UITooltipDecorator(
                        messageLocator.getMessage("poll_vote_title") + ":" + poll.getText()));

            } else {
                //the poll is lazily loaded so get the options
                poll.setOptions(pollListManager.getOptionsForPoll(poll.getPollId()));

                //is this not votable because of no options?
                if (poll.getPollOptions().size() == 0)
                    UIOutput.make(pollrow, "poll-text",
                            poll.getText() + " (" + messageLocator.getMessage("poll_no_options") + ")");
                else
                    UIOutput.make(pollrow, "poll-text", poll.getText());
            }

            if (pollListManager.isAllowedViewResults(poll, externalLogic.getCurrentUserId())) {
                UIInternalLink resultsLink = UIInternalLink.make(pollrow, "poll-results",
                        messageLocator.getMessage("action_view_results"),
                        new PollViewParameters(ResultsProducer.VIEW_ID, poll.getPollId().toString()));
                resultsLink.decorators = new DecoratorList(new UITooltipDecorator(
                        messageLocator.getMessage("action_view_results") + ":" + poll.getText()));

            }

            if (poll.getVoteOpen() != null)
                UIOutput.make(pollrow, "poll-open-date",
                        df.format(poll.getVoteOpen())).decorators = new DecoratorList(
                                new UIFreeAttributeDecorator("name",
                                        "realDate:" + poll.getVoteOpen().toString()));
            else
                UIVerbatim.make(pollrow, "poll-open-date", "  ");

            if (poll.getVoteClose() != null)
                UIOutput.make(pollrow, "poll-close-date",
                        df.format(poll.getVoteClose())).decorators = new DecoratorList(
                                new UIFreeAttributeDecorator("name",
                                        "realDate:" + poll.getVoteClose().toString()));
            else
                UIVerbatim.make(pollrow, "poll-close-date", "  ");

            if (pollCanEdit(poll)) {
                UIInternalLink editLink = UIInternalLink.make(pollrow, "poll-revise",
                        messageLocator.getMessage("action_revise_poll"),
                        new PollViewParameters(AddPollProducer.VIEW_ID, poll.getPollId().toString()));
                editLink.decorators = new DecoratorList(new UITooltipDecorator(
                        messageLocator.getMessage("action_revise_poll") + ":" + poll.getText()));

            }
            if (pollCanDelete(poll)) {
                deletable.add(poll.getPollId().toString());
                UISelectChoice delete = UISelectChoice.make(pollrow, "poll-select", deleteselect.getFullID(),
                        (deletable.size() - 1));
                delete.decorators = new DecoratorList(new UITooltipDecorator(
                        UIMessage.make("delete_poll_tooltip", new String[] { poll.getText() })));
                UIMessage message = UIMessage.make(pollrow, "delete-label", "delete_poll_tooltip",
                        new String[] { poll.getText() });
                UILabelTargetDecorator.targetLabel(message, delete);
                LOG.debug("this poll can be deleted");
                renderDelete = true;

            }
        }

        deleteselect.optionlist.setValue(deletable.toStringArray());
        deleteForm.parameters.add(new UIELBinding("#{pollToolBean.siteID}", siteId));

        if (renderDelete)
            UICommand.make(deleteForm, "delete-polls", UIMessage.make("poll_list_delete"),
                    "#{pollToolBean.processActionDelete}").decorators = new DecoratorList(
                            new UITooltipDecorator(messageLocator.getMessage("poll_list_delete_tooltip")));
        UICommand.make(deleteForm, "reset-polls-votes", UIMessage.make("poll_list_reset"),
                "#{pollToolBean.processActionResetVotes}").decorators = new DecoratorList(
                        new UITooltipDecorator(messageLocator.getMessage("poll_list_reset_tooltip")));
    }
}

From source file:org.apache.commons.vfs.example.Shell.java

/**
 * Does an 'ls' command.//w  w w .j a v  a  2 s.  co  m
 */
private void ls(final String[] cmd) throws FileSystemException {
    int pos = 1;
    final boolean recursive;
    if (cmd.length > pos && cmd[pos].equals("-R")) {
        recursive = true;
        pos++;
    } else {
        recursive = false;
    }

    final FileObject file;
    if (cmd.length > pos) {
        file = mgr.resolveFile(cwd, cmd[pos]);
    } else {
        file = cwd;
    }

    if (file.getType() == FileType.FOLDER) {
        // List the contents
        System.out.println("Contents of " + file.getName());
        listChildren(file, recursive, "");
    } else {
        // Stat the file
        System.out.println(file.getName());
        final FileContent content = file.getContent();
        System.out.println("Size: " + content.getSize() + " bytes.");
        final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime()));
        System.out.println("Last modified: " + lastMod);
    }
}

From source file:org.jivesoftware.util.JiveGlobals.java

/**
 * Formats a Date object to return a date using the global locale.
 *
 * @param date the Date to format./*from w  w w.ja  v  a 2s  .  c  o  m*/
 * @return a String representing the date.
 */
public static String formatDate(Date date) {
    if (dateFormat == null) {
        if (properties != null) {
            dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, getLocale());
            dateFormat.setTimeZone(getTimeZone());
        } else {
            DateFormat instance = DateFormat.getDateInstance(DateFormat.MEDIUM, getLocale());
            instance.setTimeZone(getTimeZone());
            return instance.format(date);
        }
    }
    return dateFormat.format(date);
}