Example usage for java.util Set toString

List of usage examples for java.util Set toString

Introduction

In this page you can find the example usage for java.util Set toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.cloudera.cli.validator.components.ParcelFileRunner.java

@Override
public boolean run(String target, Writer writer) throws IOException {
    File parcelFile = new File(target);
    writer.write(String.format("Validating: %s\n", parcelFile.getPath()));

    if (!checkExistence(parcelFile, false, writer)) {
        return false;
    }//from   w  w  w  .ja v  a 2s .  c om

    String expectedDir;
    String distro;
    Matcher parcelMatcher = PARCEL_PATTERN.matcher(parcelFile.getName());
    if (parcelMatcher.find()) {
        expectedDir = parcelMatcher.group(1) + '-' + parcelMatcher.group(2);
        distro = parcelMatcher.group(3);
    } else {
        writer.write(String.format("==> %s is not a valid parcel filename\n", parcelFile.getName()));
        return false;
    }

    if (!KNOWN_DISTROS.contains(distro)) {
        writer.write(String.format("==> %s does not appear to be a distro supported by CM\n", distro));
    }

    FileInputStream fin = null;
    BufferedInputStream bin = null;
    GzipCompressorInputStream gin = null;
    TarArchiveInputStream tin = null;
    try {
        InputStream in = null;

        fin = new FileInputStream(parcelFile);
        bin = new BufferedInputStream(fin);
        try {
            gin = new GzipCompressorInputStream(bin);
            in = gin;
        } catch (IOException e) {
            // It's not compressed. Proceed as if uncompressed tar.
            writer.write(String.format("==> Warning: Parcel is not compressed with gzip\n"));
            in = bin;
        }
        tin = new TarArchiveInputStream(in);

        byte[] parcelJson = null;
        byte[] alternativesJson = null;
        byte[] permissionsJson = null;

        Map<String, Boolean> tarEntries = Maps.newHashMap();
        Set<String> unexpectedDirs = Sets.newHashSet();
        for (TarArchiveEntry e = tin.getNextTarEntry(); e != null; e = tin.getNextTarEntry()) {
            String name = e.getName();

            // Remove trailing '/'
            tarEntries.put(name.replaceAll("/$", ""), e.isDirectory());

            if (!StringUtils.startsWith(name, expectedDir)) {
                unexpectedDirs.add(name.split("/")[0]);
            }

            if (e.getName().equals(expectedDir + PARCEL_JSON_PATH)) {
                parcelJson = new byte[(int) e.getSize()];
                tin.read(parcelJson);
            } else if (e.getName().equals(expectedDir + ALTERNATIVES_JSON_PATH)) {
                alternativesJson = new byte[(int) e.getSize()];
                tin.read(alternativesJson);
            } else if (e.getName().equals(expectedDir + PERMISSIONS_JSON_PATH)) {
                permissionsJson = new byte[(int) e.getSize()];
                tin.read(permissionsJson);
            }
        }

        boolean ret = true;

        if (!unexpectedDirs.isEmpty()) {
            writer.write(String.format("==> The following unexpected top level directories were observed: %s\n",
                    unexpectedDirs.toString()));
            writer.write(
                    String.format("===> The only valid top level directory, based on parcel filename, is: %s\n",
                            expectedDir));
            ret = false;
        }

        ret &= checkParcelJson(expectedDir, parcelJson, tarEntries, writer);
        ret &= checkAlternatives(expectedDir, alternativesJson, tarEntries, writer);
        ret &= checkPermissions(expectedDir, permissionsJson, tarEntries, writer);

        return ret;
    } catch (IOException e) {
        writer.write(String.format("==> %s: %s\n", e.getClass().getName(), e.getMessage()));
        return false;
    } finally {
        IOUtils.closeQuietly(tin);
        IOUtils.closeQuietly(gin);
        IOUtils.closeQuietly(bin);
        IOUtils.closeQuietly(fin);
    }
}

From source file:storm.mesos.schedulers.StormSchedulerImpl.java

@Override
public List<WorkerSlot> allSlotsAvailableForScheduling(Map<Protos.OfferID, Protos.Offer> offers,
        Collection<SupervisorDetails> existingSupervisors, Topologies topologies,
        Set<String> topologiesMissingAssignments) {
    if (topologiesMissingAssignments.isEmpty()) {
        removeOfferRequest(MesosCommon.TOPOLOGIES_OFFERS_REQUEST_KEY);
    } else {/*from  w w  w . j  a  va  2s .  c  om*/
        addOfferRequest(MesosCommon.TOPOLOGIES_OFFERS_REQUEST_KEY);
    }
    if (offersRequestTracker.isEmpty()) {
        if (!offers.isEmpty()) {
            log.info(
                    "Declining all offers that are currently buffered because no topologies nor tasks need assignments. Declined offer ids: {}",
                    offerMapKeySetToString(offers));
            for (Protos.OfferID offerId : offers.keySet()) {
                driver.declineOffer(offerId);
            }
            offers.clear();
        }
        if (!offersSuppressed) {
            log.info(
                    "(SUPPRESS OFFERS) We don't have any topologies nor tasks that need assignments, but offers are still flowing. Suppressing offers.");
            driver.suppressOffers();
            offersSuppressed = true;
        }
        return new ArrayList<>();
    }

    log.info("Topologies that need assignments: {}", topologiesMissingAssignments.toString());

    if (offersSuppressed) {
        log.info(
                "(REVIVE OFFERS) We have topologies or tasks that need assignments, but offers are currently suppressed. Reviving offers.");
        driver.reviveOffers();
        offersSuppressed = false;
        // Note: We still have _offersLock at this point, so we return the empty ArrayList if we happen to have no offers
        // this way we can release the lock and acquire new offers. Otherwise proceed through the logic below to see if we
        // can make any slots on the offer(s) we do have
        if (offers.isEmpty()) {
            return new ArrayList<>();
        }
    }

    List<WorkerSlot> allSlots = new ArrayList<>();
    Map<String, AggregatedOffers> aggregatedOffersPerNode = MesosCommon.getAggregatedOffersPerNode(offers);

    for (String currentTopology : topologiesMissingAssignments) {
        TopologyDetails topologyDetails = topologies.getById(currentTopology);
        int slotsNeeded = topologyDetails.getNumWorkers();

        log.info("Trying to find {} slots for {}", slotsNeeded, topologyDetails.getId());
        if (slotsNeeded <= 0) {
            continue;
        }

        Set<String> nodesWithExistingSupervisors = new HashSet<>();
        for (String currentNode : aggregatedOffersPerNode.keySet()) {
            if (SchedulerUtils.supervisorExists(MesosCommon.getMesosFrameworkName(mesosStormConf), currentNode,
                    existingSupervisors, currentTopology)) {
                nodesWithExistingSupervisors.add(currentNode);
            }
        }

        List<MesosWorkerSlot> mesosWorkerSlotList = getMesosWorkerSlots(aggregatedOffersPerNode,
                nodesWithExistingSupervisors, topologyDetails);
        for (MesosWorkerSlot mesosWorkerSlot : mesosWorkerSlotList) {
            String slotId = String.format("%s:%s", mesosWorkerSlot.getNodeId(), mesosWorkerSlot.getPort());
            mesosWorkerSlotMap.put(slotId, mesosWorkerSlot);
            allSlots.add(mesosWorkerSlot);
        }

        log.info("Number of available slots for {}: {}", topologyDetails.getId(), mesosWorkerSlotList.size());
    }

    List<String> slotsStrings = new ArrayList<String>();
    for (WorkerSlot slot : allSlots) {
        slotsStrings.add("" + slot.getNodeId() + ":" + slot.getPort());
    }
    log.info("allSlotsAvailableForScheduling: {} available slots: [{}]", allSlots.size(),
            StringUtils.join(slotsStrings, ", "));
    return allSlots;
}

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

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

    // force the headers to expire this - http://jira.sakaiproject.org/jira/browse/EVALSYS-621
    RenderingUtils.setNoCacheHeaders(httpServletResponse);

    boolean canAccess = false; // can a user access this evaluation
    boolean userCanAccess = false; // can THIS user take this evaluation
    boolean isUserSitePublished = true; //is the users' valid group(s) published? At least one group must be

    String currentUserId = commonLogic.getCurrentUserId();

    // set the session timeout to 5 hours
    evalExternalLogic.setSessionTimeout(18000);

    // use a date which is related to the current users locale
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);

    UIMessage.make(tofill, "page-title", "takeeval.page.title");

    // get passed in get params
    EvalViewParameters evalTakeViewParams = (EvalViewParameters) viewparams;
    Long evaluationId = evalTakeViewParams.evaluationId;
    if (evaluationId == null) {
        // redirect over to the main view maybe?? (not sure how to do this in RSF)
        LOG.debug("User (" + currentUserId + ") cannot take evaluation, eval id is not set");
        throw new IllegalArgumentException(
                "Invalid evaluationId: id must be set and cannot be null, cannot load evaluation");
    }/*  w  w  w  . jav  a 2 s . c  om*/
    String evalGroupId = evalTakeViewParams.evalGroupId;
    responseId = evalTakeViewParams.responseId;

    // get the evaluation based on the passed in VPs
    EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId);
    if (eval == null) {
        throw new IllegalArgumentException(
                "Invalid evaluationId (" + evaluationId + "), cannot load evaluation");
    }

    if (!evalTakeViewParams.external) {
        UIBranchContainer navTool = UIBranchContainer.make(tofill, "navIntraTool:");
        UIInternalLink.make(navTool, "summary-link", UIMessage.make("summary.page.title"),
                new SimpleViewParameters(SummaryProducer.VIEW_ID));
    }

    UIMessage.make(tofill, "eval-title-header", "takeeval.eval.title.header");
    UIOutput.make(tofill, "evalTitle", eval.getTitle());

    /* check the states of the evaluation first to give the user a tip that this eval is not takeable,
     * also avoids wasting time checking permissions when the evaluation certainly is closed,
     * also allows us to give the user a nice custom message
     */
    String evalState = evaluationService.returnAndFixEvalState(eval, true); // make sure state is up to date
    if (EvalUtils.checkStateBefore(evalState, EvalConstants.EVALUATION_STATE_ACTIVE, false)) {
        String dueDate = "--------";
        if (eval.getDueDate() != null) {
            dueDate = df.format(eval.getDueDate());
        }
        UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.not.open",
                new String[] { df.format(eval.getStartDate()), dueDate });
        LOG.info("User (" + currentUserId + ") cannot take evaluation yet, not open until: "
                + eval.getStartDate());
    } else if (EvalUtils.checkStateAfter(evalState, EvalConstants.EVALUATION_STATE_CLOSED, true)) {
        UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.closed",
                new String[] { df.format(eval.getDueDate()) });
        LOG.info(
                "User (" + currentUserId + ") cannot take evaluation anymore, closed on: " + eval.getDueDate());
    } else {
        // eval state is possible to take eval
        canAccess = true;
    }

    List<EvalGroup> validGroups = new ArrayList<>(); // stores EvalGroup objects
    if (canAccess) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("User (" + currentUserId + ") can take evalution (" + evaluationId + ")");
        }
        // eval is accessible so check user can take it
        if (evalGroupId != null) {
            // there was an eval group passed in so make sure things are ok
            if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, evalGroupId)) {
                userCanAccess = true;
            } else {
                isUserSitePublished = false;
            }
        }

        // select the first eval group the current user can take evaluation in,
        // also store the total number so we can give the user a list to choose from if there are more than one
        Map<Long, List<EvalAssignGroup>> m = evaluationService
                .getAssignGroupsForEvals(new Long[] { evaluationId }, true, null);
        if (!commonLogic.isUserAnonymous(currentUserId) && commonLogic.isUserAdmin(currentUserId)) {
            // special case, the super admin can always access
            userCanAccess = true;
            List<EvalAssignGroup> assignGroups = m.get(evaluationId);
            for (int i = 0; i < assignGroups.size(); i++) {
                EvalAssignGroup assignGroup = assignGroups.get(i);
                if (evalGroupId == null) {
                    // set the evalGroupId to the first valid group if unset
                    evalGroupId = assignGroup.getEvalGroupId();
                }
                validGroups.add(commonLogic.makeEvalGroupObject(assignGroup.getEvalGroupId()));
            }
        } else {
            EvalGroup[] evalGroups;
            if (EvalConstants.EVALUATION_AUTHCONTROL_NONE.equals(eval.getAuthControl())) {
                // anonymous eval allows any group to be evaluated
                List<EvalAssignGroup> assignGroups = m.get(evaluationId);
                evalGroups = new EvalGroup[assignGroups.size()];
                for (int i = 0; i < assignGroups.size(); i++) {
                    EvalAssignGroup assignGroup = assignGroups.get(i);
                    evalGroups[i] = commonLogic.makeEvalGroupObject(assignGroup.getEvalGroupId());
                }
            } else {
                List<EvalAssignUser> userAssignments = evaluationService.getParticipantsForEval(evaluationId,
                        currentUserId, null, EvalAssignUser.TYPE_EVALUATOR, null, null, null);
                Set<String> evalGroupIds = EvalUtils.getGroupIdsFromUserAssignments(userAssignments);
                List<EvalGroup> groups = EvalUtils.makeGroupsFromGroupsIds(evalGroupIds, commonLogic);
                evalGroups = EvalUtils.getGroupsInCommon(groups, m.get(evaluationId));
            }
            for (EvalGroup group : evalGroups) {
                if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, group.evalGroupId)) {
                    if (evalGroupId == null) {
                        // set the evalGroupId to the first valid group if unset
                        evalGroupId = group.evalGroupId;
                        userCanAccess = true;
                    }
                    validGroups.add(commonLogic.makeEvalGroupObject(group.evalGroupId));
                }
            }
            isUserSitePublished = userCanAccess;
        }

        if (!isUserSitePublished) {
            userCanAccess = false;
            UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.site.notpublished");
            LOG.info(
                    "User (" + currentUserId + ") cannot take evaluation because his site(s) are unpublished.");
        } else if (userCanAccess) {
            // check if we had a failure during a previous submit and get the missingKeys out if there are some
            Set<String> missingKeys = new HashSet<>();
            if (messages.isError() && messages.size() > 0) {
                for (int i = 0; i < messages.size(); i++) {
                    TargettedMessage message = messages.messageAt(i);
                    Exception e = message.exception;
                    if (e instanceof ResponseSaveException) {
                        ResponseSaveException rse = (ResponseSaveException) e;
                        if (rse.missingItemAnswerKeys != null && rse.missingItemAnswerKeys.length > 0) {
                            missingKeys.addAll(Arrays.asList(rse.missingItemAnswerKeys));
                        }
                        break;
                    }
                }
            }

            // load up the response if this user has one already
            if (responseId == null) {
                response = evaluationService.getResponseForUserAndGroup(evaluationId, currentUserId,
                        evalGroupId);
                if (response == null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("User (" + currentUserId + ") has no previous response for eval ("
                                + evaluationId + ")");
                    }
                    // create the initial response if there is not one
                    // EVALSYS-360 because of a hibernate issue this will not work, do a binding instead -AZ
                    //responseId = localResponsesLogic.createResponse(evaluationId, currentUserId, evalGroupId);
                } else {
                    responseId = response.getId();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("User (" + currentUserId + ") has previous response (" + responseId
                                + ") in eval (" + evaluationId + ")");
                    }
                }
            }

            if (responseId != null) {
                // load up the previous responses for this user (no need to attempt to load if the response is new, there will be no answers yet)
                answerMap = localResponsesLogic.getAnswersMapByTempItemAndAssociated(responseId);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("User (" + currentUserId + "), eval (" + evaluationId
                            + "), previous answers map: " + answerMap);
                }
            }

            // show the switch group selection and form if there are other valid groups for this user
            if (validGroups.size() > 1) {
                String[] values = new String[validGroups.size()];
                String[] labels = new String[validGroups.size()];
                for (int i = 0; i < validGroups.size(); i++) {
                    EvalGroup group = validGroups.get(i);
                    values[i] = group.evalGroupId;
                    labels[i] = group.title;
                }
                // show the switch group selection and form
                UIBranchContainer showSwitchGroup = UIBranchContainer.make(tofill, "show-switch-group:");
                UIMessage.make(showSwitchGroup, "switch-group-header", "takeeval.switch.group.header");
                UIForm chooseGroupForm = UIForm.make(showSwitchGroup, "switch-group-form",
                        new EvalViewParameters(TakeEvalProducer.VIEW_ID, evaluationId, responseId,
                                evalGroupId));
                UISelect.make(chooseGroupForm, "switch-group-list", values, labels, "#{evalGroupId}");
            }

            // fill in group title
            EvalGroup evalGroup = commonLogic.makeEvalGroupObject(evalGroupId);
            UIBranchContainer groupTitle = UIBranchContainer.make(tofill, "show-group-title:");
            UIMessage.make(groupTitle, "group-title-header", "takeeval.group.title.header");
            UIOutput.make(groupTitle, "group-title", evalGroup.title);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Begin render of eval: " + eval.getTitle() + " (" + evaluationId + "), group: "
                        + groupTitle + " (" + evalGroupId + ")");
            }

            // show instructions if not null
            if (eval.getInstructions() != null && !("".equals(eval.getInstructions()))) {
                UIBranchContainer instructions = UIBranchContainer.make(tofill, "show-eval-instructions:");
                UIMessage.make(instructions, "eval-instructions-header", "takeeval.instructions.header");
                UIVerbatim.make(instructions, "eval-instructions", eval.getInstructions());
            }

            // get the setting and make sure it cannot be null (fix for http://www.caret.cam.ac.uk/jira/browse/CTL-531)
            Boolean studentAllowedLeaveUnanswered = (Boolean) evalSettings
                    .get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
            if (studentAllowedLeaveUnanswered == null) {
                studentAllowedLeaveUnanswered = EvalUtils.safeBool(eval.getBlankResponsesAllowed(), false);
            }
            // show a warning to the user if all items must be filled in
            if (studentAllowedLeaveUnanswered == false) {
                UIBranchContainer note = UIBranchContainer.make(tofill, "show-eval-note:");
                UIMessage.make(note, "eval-note-text", "takeeval.user.must.answer.all.note");
            }

            UIBranchContainer formBranch = UIBranchContainer.make(tofill, "form-branch:");
            UIForm form = UIForm.make(formBranch, "evaluationForm");

            // bind the evaluation and evalGroup to the ones in the take eval bean
            String evalOTP = "evaluationBeanLocator.";
            form.parameters
                    .add(new UIELBinding("#{takeEvalBean.eval}", new ELReference(evalOTP + eval.getId())));
            form.parameters.add(new UIELBinding("#{takeEvalBean.evalGroupId}", evalGroupId));

            // BEGIN the complex task of rendering the evaluation items

            // make the TI data structure
            TemplateItemDataList tidl = new TemplateItemDataList(evaluationId, evalGroupId, evaluationService,
                    authoringService, hierarchyLogic, null);
            Set<String> instructorIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_INSTRUCTOR);
            Set<String> assistantIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_ASSISTANT);
            List<String> associatedTypes = tidl.getAssociateTypes();
            if (LOG.isDebugEnabled()) {
                LOG.debug("TIDL: eval=" + evaluationId + ", group=" + evalGroupId + ", items="
                        + tidl.getTemplateItemsCount() + " instructorIds: " + instructorIds + ", "
                        + " associatedTypes: " + associatedTypes);
            }

            // SELECTION Code - EVALSYS-618
            Boolean selectionsEnabled = (Boolean) evalSettings
                    .get(EvalSettings.ENABLE_INSTRUCTOR_ASSISTANT_SELECTION);
            String instructorSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL;
            String assistantSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Selections: enabled=" + selectionsEnabled + ", inst=" + instructorSelectionOption
                        + ", asst=" + assistantSelectionOption);
            }
            Map<String, String[]> savedSelections = new HashMap<>();
            if (response != null) {
                savedSelections = response.getSelections();
            }
            if (selectionsEnabled) {
                // only do the selection calculations if it is enabled
                EvalAssignGroup assignGroup = evaluationService.getAssignGroupByEvalAndGroupId(evaluationId,
                        evalGroupId);
                Map<String, String> selectorType = new HashMap<>();
                instructorSelectionOption = EvalUtils
                        .getSelectionSetting(EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR, assignGroup, null);
                selectorType.put(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, instructorSelectionOption);
                Boolean assistantsEnabled = (Boolean) evalSettings.get(EvalSettings.ENABLE_ASSISTANT_CATEGORY);
                if (assistantsEnabled) {
                    assistantSelectionOption = EvalUtils
                            .getSelectionSetting(EvalAssignGroup.SELECTION_TYPE_ASSISTANT, assignGroup, null);
                    selectorType.put(EvalConstants.ITEM_CATEGORY_ASSISTANT, assistantSelectionOption);
                }
                if (response != null) {
                    // emit currently selected people into hidden element for JS use
                    Set<String> savedIds = new HashSet<>();
                    for (String selectKey : savedSelections.keySet()) {
                        String[] usersFound = savedSelections.get(selectKey);
                        savedIds.add(usersFound[0]);
                    }
                    UIOutput savedSel = UIOutput.make(formBranch, "selectedPeopleInResponse",
                            savedIds.toString());
                    savedSel.decorators = new DecoratorList(
                            new UIIDStrategyDecorator("selectedPeopleInResponse"));
                }
                Iterator<Map.Entry<String, String>> selector = selectorType.entrySet().iterator();
                while (selector.hasNext()) {
                    Map.Entry<String, String> pairs = selector.next();
                    String selectKey = (String) pairs.getKey();
                    String selectKeyLowerCaps = selectKey.toLowerCase();
                    String selectValue = (String) pairs.getValue();
                    String uiTag = "select-" + selectKeyLowerCaps;
                    String selectionOTP = "#{takeEvalBean.selection" + selectKeyLowerCaps + "Ids}";
                    Set<String> selectUserIds = new HashSet<>();
                    if (selectKeyLowerCaps.equals(SELECT_KEY_INSTRUCTOR)) {
                        selectUserIds = instructorIds;
                    } else if (selectKeyLowerCaps.equals(SELECT_KEY_ASSISTANT)) {
                        selectUserIds = assistantIds;
                    }

                    // We render the selection controls if there are at least two
                    // Instructors/TAs
                    if (selectUserIds.size() > 1 && associatedTypes.contains(selectKey)) {
                        if (selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) {
                            // nothing special to do in all case
                        } else if (EvalAssignGroup.SELECTION_OPTION_MULTIPLE.equals(selectValue)) {
                            UIBranchContainer showSwitchGroup = UIBranchContainer.make(form,
                                    uiTag + "-multiple:");
                            // Things for building the UISelect of Assignment Checkboxes
                            List<String> assLabels = new ArrayList<>();
                            List<String> assValues = new ArrayList<>();
                            UISelect assSelect = UISelect.makeMultiple(showSwitchGroup,
                                    uiTag + "-multiple-holder", new String[] {}, new String[] {}, selectionOTP,
                                    new String[] {});
                            String assSelectID = assSelect.getFullID();
                            for (String userId : selectUserIds) {
                                EvalUser user = commonLogic.getEvalUserById(userId);
                                assValues.add(user.userId);
                                assLabels.add(user.displayName);
                                UIBranchContainer row = UIBranchContainer.make(showSwitchGroup,
                                        uiTag + "-multiple-row:");
                                UISelectChoice.make(row, uiTag + "-multiple-box", assSelectID,
                                        assLabels.size() - 1);
                                UISelectLabel.make(row, uiTag + "-multiple-label", assSelectID,
                                        assLabels.size() - 1);
                            }
                            assSelect.optionlist = UIOutputMany.make(assValues.toArray(new String[] {}));
                            assSelect.optionnames = UIOutputMany.make(assLabels.toArray(new String[] {}));
                        } else if (EvalAssignGroup.SELECTION_OPTION_ONE.equals(selectValue)) {
                            List<String> value = new ArrayList<>();
                            List<String> label = new ArrayList<>();
                            value.add("default");
                            label.add(messageLocator.getMessage("takeeval.selection.dropdown"));
                            List<EvalUser> users = commonLogic.getEvalUsersByIds(new ArrayList(selectUserIds));

                            for (EvalUser user : users) {
                                value.add(user.userId);
                                label.add(user.displayName);
                            }
                            UIBranchContainer showSwitchGroup = UIBranchContainer.make(form, uiTag + "-one:");
                            UIOutput.make(showSwitchGroup, uiTag + "-one-header");
                            UISelect.make(showSwitchGroup, uiTag + "-one-list",
                                    value.toArray(new String[value.size()]),
                                    label.toArray(new String[label.size()]), selectionOTP);
                        } else {
                            throw new IllegalStateException("Invalid selection option (" + selectValue
                                    + "): do not know how to handle this.");
                        }
                    } else if (selectUserIds.size() == 1 && associatedTypes.contains(selectKey)) {
                        // handle case where there are selections set but ONLY 1 user in the role.
                        if (!selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) {
                            for (String userId : selectUserIds) {
                                form.parameters.add(new UIELBinding(selectionOTP, userId));
                            }
                        }
                    } else {
                        // handle case where there are selections set but no users in the roles.
                        if (!selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) {
                            form.parameters.add(new UIELBinding(selectionOTP, "none"));
                        }
                    }
                }
            }

            // loop through the TIGs and handle each associated category
            Boolean useCourseCategoryOnly = (Boolean) evalSettings
                    .get(EvalSettings.ITEM_USE_COURSE_CATEGORY_ONLY);
            if (LOG.isDebugEnabled()) {
                LOG.debug("TIGs: useCourseCategoryOnly=" + useCourseCategoryOnly);
            }
            for (TemplateItemGroup tig : tidl.getTemplateItemGroups()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("TIGs: tig.associateType=" + tig.associateType);
                }
                UIBranchContainer categorySectionBranch = UIBranchContainer.make(form, "categorySection:");
                // only do headers if we are allowed to use categories
                if (!useCourseCategoryOnly) {
                    // handle printing the category header
                    if (EvalConstants.ITEM_CATEGORY_COURSE.equals(tig.associateType)) {
                        UIMessage.make(categorySectionBranch, "categoryHeader",
                                "takeeval.group.questions.header");
                    } else if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(tig.associateType)) {
                        showHeaders(categorySectionBranch, tig.associateType, tig.associateId, instructorIds,
                                instructorSelectionOption, savedSelections);
                    } else if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(tig.associateType)) {
                        showHeaders(categorySectionBranch, tig.associateType, tig.associateId, assistantIds,
                                assistantSelectionOption, savedSelections);
                    }
                }

                // loop through the hierarchy node groups
                if (LOG.isDebugEnabled()) {
                    LOG.debug("TIGs: tig.hierarchyNodeGroups=" + tig.hierarchyNodeGroups.size());
                }
                for (HierarchyNodeGroup hng : tig.hierarchyNodeGroups) {
                    // render a node title
                    if (hng.node != null) {
                        // Showing the section title is system configurable via the administrate view
                        Boolean showHierSectionTitle = (Boolean) evalSettings
                                .get(EvalSettings.DISPLAY_HIERARCHY_HEADERS);
                        if (showHierSectionTitle) {
                            UIBranchContainer nodeTitleBranch = UIBranchContainer.make(categorySectionBranch,
                                    "itemrow:nodeSection");
                            UIOutput.make(nodeTitleBranch, "nodeTitle", hng.node.title);
                        }
                    }

                    List<DataTemplateItem> dtis = hng.getDataTemplateItems(false);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("DTIs: count=" + dtis.size());
                    }
                    for (int i = 0; i < dtis.size(); i++) {
                        DataTemplateItem dti = dtis.get(i);
                        UIBranchContainer nodeItemsBranch = UIBranchContainer.make(categorySectionBranch,
                                "itemrow:templateItem");
                        if (i % 2 != 0) {
                            nodeItemsBranch.decorate(new UIStyleDecorator("itemsListOddLine")); // must match the existing CSS class
                        }
                        renderItemPrep(nodeItemsBranch, form, dti, eval, missingKeys);
                    }
                }

            }

            if (response != null && !response.complete) {
                UIMessage.make(tofill, "saveEvaluationWithoutSubmitWarning", "takeeval.saved.warning");
            }
            Boolean saveEvaluationWithoutSubmit = (Boolean) evalSettings
                    .get(EvalSettings.STUDENT_SAVE_WITHOUT_SUBMIT);
            if (saveEvaluationWithoutSubmit && (response == null || !response.complete)) {
                UICommand.make(form, "saveEvaluationWithoutSubmit", UIMessage.make("takeeval.save.button"),
                        "#{takeEvalBean.saveEvaluationWithoutSubmit}");
            }
            UICommand.make(form, "submitEvaluation", UIMessage.make("takeeval.submit.button"),
                    "#{takeEvalBean.submitEvaluation}");
            Boolean studentCancelAllowed = (Boolean) evalSettings.get(EvalSettings.STUDENT_CANCEL_ALLOWED);
            if (studentCancelAllowed) {
                UIMessage.make(form, "cancelEvaluation", "general.cancel.button");
                // populate the URL we will activate (do NOT use summary-link here)
                UIInternalLink.make(tofill, "dashboard-link",
                        new SimpleViewParameters(SummaryProducer.VIEW_ID));
            }
        } else {
            // user cannot access eval so give them a sad message
            EvalUser current = commonLogic.getEvalUserById(currentUserId);
            UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.user.cannot.take",
                    new String[] { current.displayName, current.email, current.username });
            LOG.info("User (" + currentUserId + ") cannot take evaluation: " + eval.getId());
        }
    }
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

@Test
public void testGrantDuplicatePrivilege() throws Exception {
    String roleName = "test-privilege";
    String grantor = "g1";
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    long seqId = sentryStore.createSentryRole(roleName).getSequenceId();
    TSentryPrivilege privilege = new TSentryPrivilege();
    privilege.setPrivilegeScope("TABLE");
    privilege.setServerName(server);//from ww w. j ava 2 s .co  m
    privilege.setDbName(db);
    privilege.setTableName(table);
    privilege.setAction(AccessConstants.ALL);
    privilege.setCreateTime(System.currentTimeMillis());
    assertEquals(seqId + 1,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege).getSequenceId());
    assertEquals(seqId + 2,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege).getSequenceId());
    privilege.setServerName("Server1");
    privilege.setDbName("DB1");
    privilege.setTableName("TBL1");
    assertEquals(seqId + 3,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege).getSequenceId());
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

@Test
public void testGrantRevokePrivilege() throws Exception {
    String roleName = "test-privilege";
    String grantor = "g1";
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    long seqId = sentryStore.createSentryRole(roleName).getSequenceId();
    TSentryPrivilege privilege = new TSentryPrivilege();
    privilege.setPrivilegeScope("TABLE");
    privilege.setServerName(server);/*from w  ww .  ja  v  a  2s.c  o  m*/
    privilege.setDbName(db);
    privilege.setTableName(table);
    privilege.setAction(AccessConstants.ALL);
    privilege.setCreateTime(System.currentTimeMillis());
    assertEquals(seqId + 1,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege).getSequenceId());
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());
    privilege.setAction(AccessConstants.SELECT);
    assertEquals(seqId + 2,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege).getSequenceId());
    // after having ALL and revoking SELECT, we should have INSERT
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());
    MSentryPrivilege mPrivilege = Iterables.get(privileges, 0);
    assertEquals(server, mPrivilege.getServerName());
    assertEquals(db, mPrivilege.getDbName());
    assertEquals(table, mPrivilege.getTableName());
    assertEquals(AccessConstants.INSERT, mPrivilege.getAction());
    assertFalse(mPrivilege.getGrantOption());
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

/**
 * Much like testPrivilegeCleanup, make a lot of privileges and make sure
 * they get cleaned up.  The difference here is that the privileges are
 * created by granting ALL and then removing SELECT - thus leaving INSERT.
 * This test exists because the revocation plays havoc with the orphan
 * cleanup thread.// ww w.j  ava2s  .  com
 * @throws Exception
 */
@Ignore("Disabled with SENTRY-545 following SENTRY-140 problems")
@Test
public void testPrivilegeCleanup2() throws Exception {
    final String roleName = "test-priv-cleanup";
    final String grantor = "g1";
    final String server = "server";
    final String dBase = "db";
    final String table = "table-";

    sentryStore.createSentryRole(roleName);

    // Create NUM_PRIVS unique privilege objects in the database once more,
    // this time granting ALL and revoking SELECT to make INSERT.
    for (int i = 0; i < NUM_PRIVS; i++) {
        TSentryPrivilege priv = new TSentryPrivilege();
        priv.setPrivilegeScope("DATABASE");
        priv.setServerName(server);
        priv.setAction(AccessConstants.ALL);
        priv.setCreateTime(System.currentTimeMillis());
        priv.setTableName(table + i);
        priv.setDbName(dBase);
        priv.setGrantOption(TSentryGrantOption.TRUE);
        sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, priv);

        priv.setAction(AccessConstants.SELECT);
        priv.setGrantOption(TSentryGrantOption.UNSET);
        sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, priv);
        // after having ALL and revoking SELECT, we should have INSERT
        MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
        Set<MSentryPrivilege> privileges = role.getPrivileges();
        assertEquals(privileges.toString(), i + 1, privileges.size());
        MSentryPrivilege mPrivilege = Iterables.get(privileges, 0);
        assertEquals(AccessConstants.INSERT, mPrivilege.getAction());
    }

    // Drop the role and clean up as before
    sentryStore.dropSentryRole(roleName);
    verifyOrphanCleanup();
}

From source file:ubic.pubmedgate.resolve.evaluation.SpeciesEvaluation.java

public void compare() throws Exception {
    // go through all abstracts
    // get human species IDs
    // get lineaus species IDs
    ParamKeeper params = new ParamKeeper();
    SpeciesLoader loader = new SpeciesLoader();
    List<ConnectionsDocument> documents = p2g.getDocuments();
    for (ConnectionsDocument doc : documents) {
        Map<String, String> result = new HashMap<String, String>();
        Set<String> taggedSpecies = doc.getLinnaeusSpecies();
        taggedSpecies.removeAll(loader.getFilteredIDs());

        Set<String> annotatedSpecies = new HashSet<String>();
        Set<String> unMappedComments = new HashSet<String>();
        Set<String> comments = new HashSet<String>();

        if (doc.getConnections() != null) {
            for (Connection c : doc.getConnections()) {
                // log.info( c.getComment() );
                String anSpecies = c.getComment();
                if (anSpecies != null) {
                    Set<String> mappedIDs = loader.getIDfromAnnotatedSpecies(anSpecies);
                    comments.add(anSpecies);
                    if (mappedIDs != null) {
                        annotatedSpecies.addAll(mappedIDs);
                    } else {
                        // if the comment/species tag cannot be mapped and is not blank, then keep track
                        if (!anSpecies.equals("") && !anSpecies.equals("animal not identified"))
                            unMappedComments.add(anSpecies);
                    }/*from ww  w .  jav a 2  s .c  om*/
                }
            }
        }

        result.put("Intersection Size", "" + Util.intersectSize(taggedSpecies, annotatedSpecies));
        result.put("Lineaus Size", "" + taggedSpecies.size());
        result.put("Mapped Annotated Size", "" + annotatedSpecies.size());
        result.put("Unmapped Annotated Size", "" + unMappedComments.size());
        result.put("Lineaus", taggedSpecies.toString());
        result.put("Annotated", annotatedSpecies.toString());
        result.put("Unmapped Annotated", unMappedComments.toString());
        result.put("Intersection", "" + Util.intersect(taggedSpecies, annotatedSpecies));
        result.put("Annotations", comments.toString());
        result.put("PMID", doc.getPMID());

        params.addParamInstance(result);
        // compute precision + recall, pre document?
        // output sizes and intersect for everyone, then use spreadsheet
    }
    params.writeExcel("/grp/java/workspace/PubMedIDtoGate/spreadsheets/" + "speciesEvaluation.xls");
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

@Test
public void testRevokeAllGrantOption() throws Exception {
    // 1. set local group mapping
    // user0->group0->role0
    String grantor = "g1";
    String[] users = { "user0" };
    String[] roles = { "role0" };
    String[] groups = { "group0" };
    for (int i = 0; i < users.length; i++) {
        addGroupsToUser(users[i], groups[i]);
        sentryStore.createSentryRole(roles[i]);
        Set<TSentryGroup> tGroups = Sets.newHashSet();
        TSentryGroup tGroup = new TSentryGroup(groups[i]);
        tGroups.add(tGroup);/*w  w w  .  j  a v  a  2  s. com*/
        sentryStore.alterSentryRoleAddGroups(grantor, roles[i], tGroups);
    }
    writePolicyFile();

    // 2. g1 grant select on table tb1 to role0, with grant option
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    String roleName = roles[0];
    grantor = "g1";
    TSentryPrivilege privilege = new TSentryPrivilege();
    privilege.setPrivilegeScope("TABLE");
    privilege.setServerName(server);
    privilege.setDbName(db);
    privilege.setTableName(table);
    privilege.setAction(AccessConstants.SELECT);
    privilege.setCreateTime(System.currentTimeMillis());
    privilege.setGrantOption(TSentryGrantOption.TRUE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege);

    // 3. g1 grant select on table tb1 to role0, no grant option
    roleName = roles[0];
    grantor = "g1";
    privilege.setGrantOption(TSentryGrantOption.FALSE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege);

    // 4. g1 revoke all privilege from role0
    roleName = roles[0];
    grantor = "g1";
    privilege.setGrantOption(TSentryGrantOption.UNSET);
    sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege);
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 0, privileges.size());
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

@Test
public void testGrantRevokePrivilegeWithGrantOption() throws Exception {
    String roleName = "test-grantOption-table";
    String grantor = "g1";
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    TSentryGrantOption grantOption = TSentryGrantOption.TRUE;
    long seqId = sentryStore.createSentryRole(roleName).getSequenceId();
    TSentryPrivilege privilege = new TSentryPrivilege();
    privilege.setPrivilegeScope("TABLE");
    privilege.setServerName(server);/*from   w w  w .j a  va 2 s. c om*/
    privilege.setDbName(db);
    privilege.setTableName(table);
    privilege.setAction(AccessConstants.ALL);
    privilege.setCreateTime(System.currentTimeMillis());
    privilege.setGrantOption(grantOption);
    assertEquals(seqId + 1,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege).getSequenceId());
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());
    assertEquals(Boolean.valueOf(privilege.getGrantOption().toString()),
            Iterables.get(privileges, 0).getGrantOption());
    assertEquals(seqId + 2,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege).getSequenceId());
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(0, privileges.size());

    roleName = "test-grantOption-db";
    sentryStore.createSentryRole(roleName);
    privilege = new TSentryPrivilege();
    privilege.setPrivilegeScope("DATABASE");
    privilege.setServerName(server);
    privilege.setDbName(db);
    privilege.setAction(AccessConstants.ALL);
    privilege.setGrantOption(TSentryGrantOption.TRUE);
    privilege.setCreateTime(System.currentTimeMillis());
    privilege.setGrantOption(grantOption);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege);
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());

    privilege.setAction(AccessConstants.SELECT);
    privilege.setGrantOption(TSentryGrantOption.UNSET);
    sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege);
    // after having ALL and revoking SELECT, we should have INSERT
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());
    MSentryPrivilege mPrivilege = Iterables.get(privileges, 0);
    assertEquals(server, mPrivilege.getServerName());
    assertEquals(db, mPrivilege.getDbName());
    assertEquals(AccessConstants.INSERT, mPrivilege.getAction());
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

@Test
public void testGrantRevokeMultiPrivileges() throws Exception {
    String roleName = "test-privilege";
    String grantor = "g1";
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    String[] columns = { "c1", "c2", "c3", "c4" };
    long seqId = sentryStore.createSentryRole(roleName).getSequenceId();
    Set<TSentryPrivilege> tPrivileges = Sets.newHashSet();
    for (String column : columns) {
        TSentryPrivilege privilege = new TSentryPrivilege();
        privilege.setPrivilegeScope("Column");
        privilege.setServerName(server);
        privilege.setDbName(db);/*from  www  . j  av  a  2  s.  c  om*/
        privilege.setTableName(table);
        privilege.setColumnName(column);
        privilege.setAction(AccessConstants.SELECT);
        privilege.setCreateTime(System.currentTimeMillis());
        tPrivileges.add(privilege);
    }
    assertEquals(seqId + 1,
            sentryStore.alterSentryRoleGrantPrivileges(grantor, roleName, tPrivileges).getSequenceId());
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 4, privileges.size());

    tPrivileges = Sets.newHashSet();
    for (int i = 0; i < 2; i++) {
        TSentryPrivilege privilege = new TSentryPrivilege();
        privilege.setPrivilegeScope("Column");
        privilege.setServerName(server);
        privilege.setDbName(db);
        privilege.setTableName(table);
        privilege.setColumnName(columns[i]);
        privilege.setAction(AccessConstants.SELECT);
        privilege.setCreateTime(System.currentTimeMillis());
        tPrivileges.add(privilege);
    }
    assertEquals(seqId + 2,
            sentryStore.alterSentryRoleRevokePrivileges(grantor, roleName, tPrivileges).getSequenceId());
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());

    TSentryPrivilege privilege = new TSentryPrivilege();
    privilege.setPrivilegeScope("Table");
    privilege.setServerName(server);
    privilege.setDbName(db);
    privilege.setTableName(table);
    privilege.setAction(AccessConstants.SELECT);
    privilege.setCreateTime(System.currentTimeMillis());
    assertEquals(seqId + 3,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege).getSequenceId());
    // After revoking table scope, we will have 0 privileges
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 0, privileges.size());
}