Example usage for java.util LinkedHashMap keySet

List of usage examples for java.util LinkedHashMap keySet

Introduction

In this page you can find the example usage for java.util LinkedHashMap keySet.

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.joey.software.Launcher.microneedleAnalysis.DataAnalysisViewer.java

public CategoryDataset getAVGForeArmData() {

    LinkedHashMap<String, ArrayList<Double>> skinData = new LinkedHashMap<String, ArrayList<Double>>();
    LinkedHashMap<String, ArrayList<Double>> poreData = new LinkedHashMap<String, ArrayList<Double>>();
    LinkedHashMap<String, ArrayList<Double>> poreSkinData = new LinkedHashMap<String, ArrayList<Double>>();

    ArrayList<MeasurmentData> measureData = owner.measures;
    for (MeasurmentData measure : measureData) {
        if (validMeasurment(measure)) {

            ArrayList<Double> holdSkin = skinData.get(measure.view);
            if (holdSkin == null) {
                holdSkin = new ArrayList<Double>();
                skinData.put(measure.view, holdSkin);
            }//  w  ww .j av a 2  s. co m
            holdSkin.add(measure.skinDim.getValue());

            ArrayList<Double> holdPore = poreData.get(measure.view);
            if (holdPore == null) {
                holdPore = new ArrayList<Double>();
                poreData.put(measure.view, holdPore);
            }
            holdPore.add(measure.poreDim.getValue());

            ArrayList<Double> holdPoreSkin = poreSkinData.get(measure.view);
            if (holdPoreSkin == null) {
                holdPoreSkin = new ArrayList<Double>();
                poreSkinData.put(measure.view, holdPoreSkin);
            }
            holdPoreSkin.add(measure.skinPoreDim.getValue());

        }
    }

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    {
        String[] keys = skinData.keySet().toArray(new String[0]);

        for (String key : keys) {
            ArrayList<Double> skin = skinData.get(key);

            if (useSkin.isSelected()) {
                dataset.addValue(
                        DataAnalysisToolkit.getAverage(DataAnalysisToolkit.ListToArrayd(skinData.get(key))),
                        "Skin", key);
            }

            if (usePore.isSelected()) {
                dataset.addValue(
                        DataAnalysisToolkit.getAverage(DataAnalysisToolkit.ListToArrayd(poreData.get(key))),
                        "Pore", key);
            }

            if (usePoreSkin.isSelected()) {
                dataset.addValue(
                        DataAnalysisToolkit.getAverage(DataAnalysisToolkit.ListToArrayd(poreSkinData.get(key))),
                        "SkinPore", key);
            }

            if (useTotal.isSelected()) {
                dataset.addValue(
                        DataAnalysisToolkit.getAverage(DataAnalysisToolkit.ListToArrayd(skinData.get(key)))
                                + DataAnalysisToolkit
                                        .getAverage(DataAnalysisToolkit.ListToArrayd(poreSkinData.get(key))),
                        "Total", key);
            }
        }
    }
    return dataset;
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private Collection<Double> getCountsForChart(LinkedHashMap<String, ChartData> recordMap) {
    Collection<Double> counts = new ArrayList<Double>();
    for (String id : recordMap.keySet()) {
        counts.add(recordMap.get(id).getCount());
    }//from w w  w  .  jav a  2s  .c  o m

    return counts;
}

From source file:ubic.gemma.visualization.ExperimentalDesignVisualizationServiceImpl.java

@Override
public Map<Long, LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>>> sortLayoutSamplesByFactor(
        final Map<Long, LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>>> layouts) {

    Map<Long, LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>>> sortedLayouts = new HashMap<Long, LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>>>();
    StopWatch timer = new StopWatch();
    timer.start();/*  w  ww.j av  a  2  s .c  om*/
    for (Long bioAssaySet : layouts.keySet()) {

        final LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> layout = layouts
                .get(bioAssaySet);

        if (layout == null || layout.size() == 0) {
            log.warn("Null or empty layout for ee: " + bioAssaySet); // does this happen?
            continue;
        }
        LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> sortedLayout = new LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>>();

        Collection<ExperimentalFactor> filteredFactors = extractFactors(layout, false);

        if (filteredFactors.isEmpty()) {
            if (sortedLayouts.containsKey(bioAssaySet)) {
                log.warn("sortedLayouts already contained ee with ID = " + bioAssaySet
                        + ". Value was map with # keys = " + sortedLayouts.get(bioAssaySet).keySet().size());
            }
            sortedLayouts.put(bioAssaySet, sortedLayout);
            continue; // batch was the only factor.
        }

        List<BioMaterialValueObject> bmList = new ArrayList<BioMaterialValueObject>();
        Map<BioMaterialValueObject, BioAssayValueObject> BMtoBA = new HashMap<BioMaterialValueObject, BioAssayValueObject>();

        for (BioAssayValueObject ba : layout.keySet()) {
            BioMaterialValueObject bm = ba.getSample();
            BMtoBA.put(bm, ba);
            bmList.add(bm);

        }

        // sort factors within layout by number of values
        LinkedList<ExperimentalFactor> sortedFactors = (LinkedList<ExperimentalFactor>) ExpressionDataMatrixColumnSort
                .orderFactorsByExperimentalDesignVO(bmList, filteredFactors);

        // this isn't necessary, because we can have factors get dropped if we are looking at a subset.
        // assert sortedFactors.size() == filteredFactors.size();

        List<BioMaterialValueObject> sortedBMList = ExpressionDataMatrixColumnSort
                .orderBiomaterialsBySortedFactorsVO(bmList, sortedFactors);

        assert sortedBMList.size() == bmList.size();

        // sort layout entries according to sorted ba list
        // List<BioAssayValueObject> sortedBAList = new ArrayList<BioAssayValueObject>();
        for (BioMaterialValueObject bm : sortedBMList) {
            BioAssayValueObject ba = BMtoBA.get(bm);
            assert ba != null;

            // sortedBAList.add( bavo );

            // sort factor-value pairs for each biomaterial
            LinkedHashMap<ExperimentalFactor, Double> facs = layout.get(ba);

            LinkedHashMap<ExperimentalFactor, Double> sortedFacs = new LinkedHashMap<ExperimentalFactor, Double>();
            for (ExperimentalFactor fac : sortedFactors) {
                sortedFacs.put(fac, facs.get(fac));
            }

            // assert facs.size() == sortedFacs.size() : "Expected " + facs.size() + " factors, got "
            // + sortedFacs.size();
            sortedLayout.put(ba, sortedFacs);
        }
        sortedLayouts.put(bioAssaySet, sortedLayout);

    }

    if (timer.getTime() > 1000) {
        log.info("Sorting layout samples by factor: " + timer.getTime() + "ms");
    }

    return sortedLayouts;
}

From source file:org.jahia.ajax.gwt.helper.NodeHelper.java

GWTJahiaNode getGWTJahiaNode(JCRNodeWrapper node, List<String> fields, Locale uiLocale) {
    if (fields == null) {
        fields = Collections.emptyList();
    }//from   w ww.j  a  v a  2  s.  c  om
    GWTJahiaNode n = new GWTJahiaNode();
    // get uuid
    try {
        n.setUUID(node.getIdentifier());
    } catch (RepositoryException e) {
        logger.debug("Unable to get uuid for node " + node.getName(), e);
    }

    populateNames(n, node, uiLocale);
    populateDescription(n, node);
    n.setPath(node.getPath());
    n.setUrl(node.getUrl());
    populateNodeTypes(n, node);
    JCRStoreProvider provider = node.getProvider();
    if (provider.isDynamicallyMounted()) {
        n.setProviderKey(StringUtils.substringAfterLast(provider.getMountPoint(), "/"));
    } else {
        n.setProviderKey(provider.getKey());
    }

    if (fields.contains(GWTJahiaNode.PERMISSIONS)) {
        populatePermissions(n, node);
    }

    if (fields.contains(GWTJahiaNode.LOCKS_INFO) && !provider.isSlowConnection()) {
        populateLocksInfo(n, node);
    }

    if (fields.contains(GWTJahiaNode.VISIBILITY_INFO)) {
        populateVisibilityInfo(n, node);
    }

    n.setVersioned(node.isVersioned());
    n.setLanguageCode(node.getLanguage());

    populateSiteInfo(n, node);

    if (node.isFile()) {
        n.setSize(node.getFileContent().getContentLength());

    }
    n.setFile(node.isFile());

    n.setIsShared(false);
    try {
        if (node.isNodeType("mix:shareable") && node.getSharedSet().getSize() > 1) {
            n.setIsShared(true);
        }
    } catch (RepositoryException e) {
        logger.error("Error when getting shares", e);
    }

    try {
        n.setReference(node.isNodeType("jmix:nodeReference"));
    } catch (RepositoryException e1) {
        logger.error("Error checking node type", e1);
    }

    if (fields.contains(GWTJahiaNode.CHILDREN_INFO)) {
        populateChildrenInfo(n, node);
    }

    if (fields.contains(GWTJahiaNode.TAGS)) {
        populateTags(n, node);
    }

    // icons
    if (fields.contains(GWTJahiaNode.ICON)) {
        populateIcon(n, node);
    }

    populateThumbnails(n, node);

    // count
    if (fields.contains(GWTJahiaNode.COUNT)) {
        populateCount(n, node);
    }

    populateStatusInfo(n, node);
    if (supportsWorkspaceManagement(node)) {
        if (fields.contains(GWTJahiaNode.PUBLICATION_INFO)) {
            populatePublicationInfo(n, node);
        }

        if (fields.contains(GWTJahiaNode.QUICK_PUBLICATION_INFO)) {
            populateQuickPublicationInfo(n, node);
        }

        if (fields.contains(GWTJahiaNode.PUBLICATION_INFOS)) {
            populatePublicationInfos(n, node);
        }
        n.set("supportsPublication", supportsPublication(node));
    }

    if (fields.contains(GWTJahiaNode.WORKFLOW_INFO) || fields.contains(GWTJahiaNode.PUBLICATION_INFO)) {
        populateWorkflowInfo(n, node, uiLocale);
    }

    if (fields.contains(GWTJahiaNode.WORKFLOW_INFOS)) {
        populateWorkflowInfos(n, node, uiLocale);
    }

    if (fields.contains(GWTJahiaNode.AVAILABLE_WORKKFLOWS)) {
        populateAvailableWorkflows(n, node);
    }

    if (fields.contains(GWTJahiaNode.PRIMARY_TYPE_LABEL)) {
        populatePrimaryTypeLabel(n, node);
    }

    JCRStoreProvider p = JCRSessionFactory.getInstance().getMountPoints().get(n.getPath());
    if (p != null && p.isDynamicallyMounted()) {
        n.set("j:isDynamicMountPoint", Boolean.TRUE);
    }

    if (n.isFile() && (n.isNodeType("jmix:image") || n.isNodeType("jmix:size"))) {
        // handle width and height
        try {
            if (node.hasProperty("j:height")) {
                n.set("j:height", node.getProperty("j:height").getString());
            }
        } catch (RepositoryException e) {
            logger.error("Cannot get property j:height on node {}", node.getPath());
        }
        try {
            if (node.hasProperty("j:width")) {
                n.set("j:width", node.getProperty("j:width").getString());
            }
        } catch (RepositoryException e) {
            logger.error("Cannot get property j:width on node {}", node.getPath());
        }
    }

    if (fields.contains("j:view") && n.isNodeType("jmix:renderable")) {
        try {
            if (node.hasProperty("j:view")) {
                n.set("j:view", node.getProperty("j:view").getString());
            }
        } catch (RepositoryException e) {
            logger.error("Cannot get property j:view on node {}", node.getPath());
        }
    }

    if (fields.contains(GWTJahiaNode.SITE_LANGUAGES)) {
        populateSiteLanguages(n, node);
    }

    if ((node instanceof JCRSiteNode) && fields.contains("j:resolvedDependencies")) {
        populateDependencies(n, node);
    }
    if (fields.contains(GWTJahiaNode.SUBNODES_CONSTRAINTS_INFO)) {
        populateSubnodesConstraintsInfo(n, node);
    }

    if (fields.contains(GWTJahiaNode.DEFAULT_LANGUAGE)) {
        populateDefaultLanguage(n, node);
    }

    if ((node instanceof JCRSiteNode) && fields.contains(GWTJahiaNode.HOMEPAGE_PATH)) {
        populateHomePage(n, node);
    }

    Boolean isModuleNode = null;

    final JahiaTemplateManagerService templateManagerService = ServicesRegistry.getInstance()
            .getJahiaTemplateManagerService();
    try {
        if (fields.contains("j:versionInfo")) {
            isModuleNode = node.isNodeType("jnt:module");
            if (isModuleNode) {
                populateVersionInfoForModule(n, node);
            }
        }
    } catch (RepositoryException e) {
        logger.error("Cannot get property module version");
    }

    // properties
    for (String field : fields) {
        if (!GWTJahiaNode.RESERVED_FIELDS.contains(field)) {
            try {
                if (field.startsWith("fields-")) {
                    String type = field.substring("fields-".length());
                    PropertyIterator pi = node.getProperties();
                    while (pi.hasNext()) {
                        JCRPropertyWrapper property = (JCRPropertyWrapper) pi.next();
                        if (((ExtendedPropertyDefinition) property.getDefinition()).getItemType()
                                .equals(type)) {
                            setPropertyValue(n, property, node.getSession());
                        }
                    }

                } else if (node.hasProperty(field)) {
                    final JCRPropertyWrapper property = node.getProperty(field);
                    setPropertyValue(n, property, node.getSession());
                } else if (isModuleNode != null ? isModuleNode.booleanValue()
                        : (isModuleNode = node.isNodeType("jnt:module"))) {
                    JahiaTemplatesPackage templatePackageByFileName = templateManagerService
                            .getTemplatePackageById(node.getName());
                    if (templatePackageByFileName != null) {
                        JCRNodeWrapper versionNode = node
                                .getNode(templatePackageByFileName.getVersion().toString());
                        if (versionNode.hasProperty(field)) {
                            final JCRPropertyWrapper property = versionNode.getProperty(field);
                            setPropertyValue(n, property, node.getSession());
                        }
                    }
                }
            } catch (RepositoryException e) {
                logger.error("Cannot get property {} on node {}", field, node.getPath());
            }
        }
    }

    // versions
    if (fields.contains(GWTJahiaNode.VERSIONS) && node.isVersioned()) {
        populateVersions(n, node);
    }

    // resource bundle
    if (fields.contains(GWTJahiaNode.RESOURCE_BUNDLE)) {
        GWTResourceBundle b = GWTResourceBundleUtils.load(node, uiLocale);
        if (b != null) {
            n.set(GWTJahiaNode.RESOURCE_BUNDLE, b);
        }
    }
    populateReference(n, node, fields, uiLocale);

    populateOrdering(n, node);

    populateChildConstraints(n, node);

    populateWCAG(n, node);

    populateInvalidLanguages(n, node);

    List<String> installedModules = (List<String>) n.get("j:installedModules");
    if (installedModules != null) {
        List<JahiaTemplatesPackage> s = new ArrayList<>();
        LinkedHashMap<JahiaTemplatesPackage, List<JahiaTemplatesPackage>> deps = new LinkedHashMap<>();
        for (String packId : installedModules) {
            JahiaTemplatesPackage pack = templateManagerService.getTemplatePackageById(packId);
            if (pack != null) {
                deps.put(pack, new ArrayList<JahiaTemplatesPackage>());
            }
        }
        installedModules.clear();
        for (Map.Entry<JahiaTemplatesPackage, List<JahiaTemplatesPackage>> entry : deps.entrySet()) {
            List<JahiaTemplatesPackage> allDeps = entry.getKey().getDependencies();
            for (JahiaTemplatesPackage dep : allDeps) {
                if (deps.keySet().contains(dep)) {
                    entry.getValue().add(dep);
                }
            }
            if (entry.getValue().isEmpty()) {
                s.add(entry.getKey());
            }
        }
        while (!s.isEmpty()) {
            JahiaTemplatesPackage pack = s.remove(0);
            installedModules.add(pack.getId());
            for (Map.Entry<JahiaTemplatesPackage, List<JahiaTemplatesPackage>> entry : deps.entrySet()) {
                if (entry.getValue().contains(pack)) {
                    entry.getValue().remove(pack);
                    if (entry.getValue().isEmpty()) {
                        s.add(entry.getKey());
                    }
                }
            }
        }
    }

    return n;
}

From source file:org.sakaiproject.profile2.tool.pages.MySearch.java

public MySearch() {

    log.debug("MySearch()");

    disableLink(searchLink);//from   w  w  w. j  a v a  2  s . c  o m

    //check for current search cookie    
    CookieUtils utils = new CookieUtils();
    searchCookie = utils.getCookie(ProfileConstants.SEARCH_COOKIE);

    //setup model to store the actions in the modal windows
    final FriendAction friendActionModel = new FriendAction();

    //get current user info
    final String currentUserUuid = sakaiProxy.getCurrentUserId();
    final String currentUserType = sakaiProxy.getUserType(currentUserUuid);

    /*
     * Combined search form 
     */

    //heading
    Label searchHeading = new Label("searchHeading", new ResourceModel("heading.search"));
    add(searchHeading);

    //setup form
    final StringModel searchStringModel = new StringModel();
    Form<StringModel> searchForm = new Form<StringModel>("searchForm",
            new Model<StringModel>(searchStringModel));
    searchForm.setOutputMarkupId(true);

    //search field
    searchForm.add(new Label("searchLabel", new ResourceModel("text.search.terms.label")));
    searchField = new TextField<String>("searchField", new PropertyModel<String>(searchStringModel, "string"));
    searchField.setRequired(true);
    searchField.setMarkupId("searchinput");
    searchField.setOutputMarkupId(true);
    searchForm.add(searchField);
    searchForm.add(new IconWithClueTip("searchToolTip", ProfileConstants.INFO_IMAGE,
            new ResourceModel("text.search.terms.tooltip")));

    //by name or by interest radio group        
    searchTypeRadioGroup = new RadioGroup<String>("searchTypeRadioGroup");
    // so we can repaint after clicking on search history links
    searchTypeRadioGroup.setOutputMarkupId(true);
    searchTypeRadioGroup.setRenderBodyOnly(false);
    Radio<String> searchTypeRadioName = new Radio<String>("searchTypeName",
            new Model<String>(ProfileConstants.SEARCH_TYPE_NAME));
    searchTypeRadioName.setMarkupId("searchtypenameinput");
    searchTypeRadioName.setOutputMarkupId(true);
    searchTypeRadioName
            .add(new AttributeModifier("title", true, new ResourceModel("text.search.byname.tooltip")));
    searchTypeRadioGroup.add(searchTypeRadioName);
    Radio<String> searchTypeRadioInterest = new Radio<String>("searchTypeInterest",
            new Model<String>(ProfileConstants.SEARCH_TYPE_INTEREST));
    searchTypeRadioInterest.setMarkupId("searchtypeinterestinput");
    searchTypeRadioInterest.setOutputMarkupId(true);
    searchTypeRadioInterest
            .add(new AttributeModifier("title", true, new ResourceModel("text.search.byinterest.tooltip")));
    searchTypeRadioGroup.add(searchTypeRadioInterest);
    searchTypeRadioGroup.add(new Label("searchTypeNameLabel", new ResourceModel("text.search.byname.label")));
    searchTypeRadioGroup
            .add(new Label("searchTypeInterestLabel", new ResourceModel("text.search.byinterest.label")));
    searchForm.add(searchTypeRadioGroup);

    searchForm.add(new Label("connectionsLabel", new ResourceModel("text.search.include.connections")));
    // model is true (include connections by default)
    connectionsCheckBox = new CheckBox("connectionsCheckBox", new Model<Boolean>(true));
    connectionsCheckBox.setMarkupId("includeconnectionsinput");
    connectionsCheckBox.setOutputMarkupId(true);
    //hide if connections disabled globally
    connectionsCheckBox.setVisible(sakaiProxy.isConnectionsEnabledGlobally());
    searchForm.add(connectionsCheckBox);

    final List<Site> worksites = sakaiProxy.getUserSites();
    final boolean hasWorksites = worksites.size() > 0;

    searchForm.add(new Label("worksiteLabel", new ResourceModel("text.search.include.worksite")));
    // model is false (include all worksites by default)
    worksiteCheckBox = new CheckBox("worksiteCheckBox", new Model<Boolean>(false));
    worksiteCheckBox.setMarkupId("limittositeinput");
    worksiteCheckBox.setOutputMarkupId(true);
    worksiteCheckBox.setEnabled(hasWorksites);
    searchForm.add(worksiteCheckBox);

    final IModel<String> defaultWorksiteIdModel;
    if (hasWorksites) {
        defaultWorksiteIdModel = new Model<String>(worksites.get(0).getId());
    } else {
        defaultWorksiteIdModel = new ResourceModel("text.search.no.worksite");
    }

    final LinkedHashMap<String, String> worksiteMap = new LinkedHashMap<String, String>();

    if (hasWorksites) {
        for (Site worksite : worksites) {
            worksiteMap.put(worksite.getId(), worksite.getTitle());
        }
    } else {
        worksiteMap.put(defaultWorksiteIdModel.getObject(), defaultWorksiteIdModel.getObject());
    }

    IModel worksitesModel = new Model() {

        public ArrayList<String> getObject() {
            return new ArrayList<String>(worksiteMap.keySet());
        }
    };

    worksiteChoice = new DropDownChoice("worksiteChoice", defaultWorksiteIdModel, worksitesModel,
            new HashMapChoiceRenderer(worksiteMap));
    worksiteChoice.setMarkupId("worksiteselect");
    worksiteChoice.setOutputMarkupId(true);
    worksiteChoice.setNullValid(false);
    worksiteChoice.setEnabled(hasWorksites);
    searchForm.add(worksiteChoice);

    /* 
     * 
     * RESULTS
     * 
     */

    //search results label/container
    numSearchResultsContainer = new WebMarkupContainer("numSearchResultsContainer");
    numSearchResultsContainer.setOutputMarkupPlaceholderTag(true);
    numSearchResults = new Label("numSearchResults");
    numSearchResults.setOutputMarkupId(true);
    numSearchResults.setEscapeModelStrings(false);
    numSearchResultsContainer.add(numSearchResults);

    //clear results button
    Form<Void> clearResultsForm = new Form<Void>("clearResults");
    clearResultsForm.setOutputMarkupPlaceholderTag(true);

    clearButton = new AjaxButton("clearButton", clearResultsForm) {
        private static final long serialVersionUID = 1L;

        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            // clear cookie if present    
            if (null != searchCookie) {
                CookieUtils utils = new CookieUtils();
                utils.remove(ProfileConstants.SEARCH_COOKIE);
            }

            //clear the fields, hide self, then repaint
            searchField.clearInput();
            searchField.updateModel();

            numSearchResultsContainer.setVisible(false);
            resultsContainer.setVisible(false);
            clearButton.setVisible(false);

            target.add(searchField);
            target.add(numSearchResultsContainer);
            target.add(resultsContainer);
            target.add(this);
        }
    };
    clearButton.setOutputMarkupPlaceholderTag(true);
    if (null == searchCookie) {
        clearButton.setVisible(false); //invisible until we have something to clear
    }
    clearButton.setModel(new ResourceModel("button.search.clear"));
    clearResultsForm.add(clearButton);
    numSearchResultsContainer.add(clearResultsForm);

    add(numSearchResultsContainer);

    // model to wrap search results
    LoadableDetachableModel<List<Person>> resultsModel = new LoadableDetachableModel<List<Person>>() {
        private static final long serialVersionUID = 1L;

        protected List<Person> load() {
            return results;
        }
    };

    //container which wraps list
    resultsContainer = new WebMarkupContainer("searchResultsContainer");
    resultsContainer.setOutputMarkupPlaceholderTag(true);
    if (null == searchCookie) {
        resultsContainer.setVisible(false); //hide initially
    }

    //connection window
    final ModalWindow connectionWindow = new ModalWindow("connectionWindow");

    //search results
    final PageableListView<Person> resultsListView = new PageableListView<Person>("searchResults", resultsModel,
            sakaiProxy.getMaxSearchResultsPerPage()) {

        private static final long serialVersionUID = 1L;

        protected void populateItem(final ListItem<Person> item) {

            Person person = (Person) item.getModelObject();

            //get basic values
            final String userUuid = person.getUuid();
            final String displayName = person.getDisplayName();
            final String userType = person.getType();

            //get connection status
            int connectionStatus = connectionsLogic.getConnectionStatus(currentUserUuid, userUuid);
            boolean friend = (connectionStatus == ProfileConstants.CONNECTION_CONFIRMED) ? true : false;

            //image wrapper, links to profile
            Link<String> friendItem = new Link<String>("searchResultPhotoWrap") {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    setResponsePage(new ViewProfile(userUuid));
                }
            };

            //image
            ProfileImage searchResultPhoto = new ProfileImage("searchResultPhoto", new Model<String>(userUuid));
            searchResultPhoto.setSize(ProfileConstants.PROFILE_IMAGE_THUMBNAIL);
            friendItem.add(searchResultPhoto);

            item.add(friendItem);

            //name and link to profile (if allowed or no link)
            Link<String> profileLink = new Link<String>("searchResultProfileLink",
                    new Model<String>(userUuid)) {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    //if user found themself, go to own profile, else show other profile
                    if (userUuid.equals(currentUserUuid)) {
                        setResponsePage(new MyProfile());
                    } else {
                        //gets userUuid of other user from the link's model
                        setResponsePage(new ViewProfile((String) getModelObject()));
                    }
                }
            };

            profileLink.add(new Label("searchResultName", displayName));
            item.add(profileLink);

            //status component
            ProfileStatusRenderer status = new ProfileStatusRenderer("searchResultStatus", person,
                    "search-result-status-msg", "search-result-status-date") {
                @Override
                public boolean isVisible() {
                    return sakaiProxy.isProfileStatusEnabled();
                }
            };
            status.setOutputMarkupId(true);
            item.add(status);

            /* ACTIONS */
            boolean isFriendsListVisible = privacyLogic.isActionAllowed(userUuid, currentUserUuid,
                    PrivacyType.PRIVACY_OPTION_MYFRIENDS);
            boolean isConnectionAllowed = sakaiProxy.isConnectionAllowedBetweenUserTypes(userType,
                    currentUserType);

            //ADD CONNECTION LINK
            final WebMarkupContainer c1 = new WebMarkupContainer("connectionContainer");
            c1.setOutputMarkupId(true);

            if (!isConnectionAllowed && !sakaiProxy.isConnectionsEnabledGlobally()) {
                //add blank components - TODO turn this into an EmptyLink component
                AjaxLink<Void> emptyLink = new AjaxLink<Void>("connectionLink") {
                    private static final long serialVersionUID = 1L;

                    public void onClick(AjaxRequestTarget target) {
                    }
                };
                emptyLink.add(new Label("connectionLabel"));
                c1.add(emptyLink);
                c1.setVisible(false);
            } else {
                //render the link
                final Label connectionLabel = new Label("connectionLabel");
                connectionLabel.setOutputMarkupId(true);

                final AjaxLink<String> connectionLink = new AjaxLink<String>("connectionLink",
                        new Model<String>(userUuid)) {
                    private static final long serialVersionUID = 1L;

                    public void onClick(AjaxRequestTarget target) {

                        //get this item, reinit some values and set content for modal
                        final String userUuid = (String) getModelObject();
                        connectionWindow.setContent(new AddFriend(connectionWindow.getContentId(),
                                connectionWindow, friendActionModel, currentUserUuid, userUuid));

                        // connection modal window handler 
                        connectionWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
                            private static final long serialVersionUID = 1L;

                            public void onClose(AjaxRequestTarget target) {
                                if (friendActionModel.isRequested()) {
                                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
                                    add(new AttributeModifier("class", true,
                                            new Model<String>("instruction icon connection-request")));
                                    setEnabled(false);
                                    target.add(c1);
                                }
                            }
                        });
                        //in preparation for the window being closed, update the text. this will only
                        //be put into effect if its a successful model update from the window close
                        //connectionLabel.setModel(new ResourceModel("text.friend.requested"));
                        //this.add(new AttributeModifier("class", true, new Model("instruction")));
                        //this.setEnabled(false);
                        //friendActionModel.setUpdateThisComponentOnSuccess(this);

                        connectionWindow.show(target);
                        target.appendJavaScript("fixWindowVertical();");

                    }
                };

                connectionLink.add(connectionLabel);

                //setup 'add connection' link
                if (StringUtils.equals(userUuid, currentUserUuid)) {
                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.self"));
                    connectionLink.add(new AttributeModifier("class", true,
                            new Model<String>("instruction icon profile")));
                    connectionLink.setEnabled(false);
                } else if (friend) {
                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.confirmed"));
                    connectionLink.add(new AttributeModifier("class", true,
                            new Model<String>("instruction icon connection-confirmed")));
                    connectionLink.setEnabled(false);
                } else if (connectionStatus == ProfileConstants.CONNECTION_REQUESTED) {
                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
                    connectionLink.add(new AttributeModifier("class", true,
                            new Model<String>("instruction icon connection-request")));
                    connectionLink.setEnabled(false);
                } else if (connectionStatus == ProfileConstants.CONNECTION_INCOMING) {
                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.pending"));
                    connectionLink.add(new AttributeModifier("class", true,
                            new Model<String>("instruction icon connection-request")));
                    connectionLink.setEnabled(false);
                } else {
                    connectionLabel.setDefaultModel(new ResourceModel("link.friend.add"));
                }
                connectionLink.setOutputMarkupId(true);
                c1.add(connectionLink);
            }

            item.add(c1);

            //VIEW FRIENDS LINK
            WebMarkupContainer c2 = new WebMarkupContainer("viewFriendsContainer");
            c2.setOutputMarkupId(true);

            final AjaxLink<String> viewFriendsLink = new AjaxLink<String>("viewFriendsLink") {
                private static final long serialVersionUID = 1L;

                public void onClick(AjaxRequestTarget target) {
                    //if user found themself, go to MyFriends, else, ViewFriends
                    if (userUuid.equals(currentUserUuid)) {
                        setResponsePage(new MyFriends());
                    } else {
                        setResponsePage(new ViewFriends(userUuid));
                    }
                }
            };
            final Label viewFriendsLabel = new Label("viewFriendsLabel",
                    new ResourceModel("link.view.friends"));
            viewFriendsLink.add(viewFriendsLabel);

            //hide if not allowed
            if (!isFriendsListVisible && !sakaiProxy.isConnectionsEnabledGlobally()) {
                viewFriendsLink.setEnabled(false);
                c2.setVisible(false);
            }
            viewFriendsLink.setOutputMarkupId(true);
            c2.add(viewFriendsLink);
            item.add(c2);

            WebMarkupContainer c3 = new WebMarkupContainer("emailContainer");
            c3.setOutputMarkupId(true);

            ExternalLink emailLink = new ExternalLink("emailLink", "mailto:" + person.getProfile().getEmail(),
                    new ResourceModel("profile.email").getObject());

            c3.add(emailLink);

            if (StringUtils.isBlank(person.getProfile().getEmail())
                    || false == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                            PrivacyType.PRIVACY_OPTION_CONTACTINFO)) {
                c3.setVisible(false);
            }
            item.add(c3);

            WebMarkupContainer c4 = new WebMarkupContainer("websiteContainer");
            c4.setOutputMarkupId(true);

            // TODO home page, university profile URL or academic/research URL (see PRFL-35)
            ExternalLink websiteLink = new ExternalLink("websiteLink", person.getProfile().getHomepage(),
                    new ResourceModel("profile.homepage").getObject()).setPopupSettings(new PopupSettings());

            c4.add(websiteLink);

            if (StringUtils.isBlank(person.getProfile().getHomepage())
                    || false == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                            PrivacyType.PRIVACY_OPTION_CONTACTINFO)) {

                c4.setVisible(false);
            }
            item.add(c4);

            // TODO personal, academic or business (see PRFL-35)

            if (true == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                    PrivacyType.PRIVACY_OPTION_BASICINFO)) {

                item.add(new Label("searchResultSummary", StringUtils
                        .abbreviate(ProfileUtils.stripHtml(person.getProfile().getPersonalSummary()), 200)));
            } else {
                item.add(new Label("searchResultSummary", ""));
            }
        }
    };

    resultsListView.add(new MySearchCookieBehavior(resultsListView));
    resultsContainer.add(resultsListView);

    final PagingNavigator searchResultsNavigator = new PagingNavigator("searchResultsNavigator",
            resultsListView);
    searchResultsNavigator.setOutputMarkupId(true);
    searchResultsNavigator.setVisible(false);

    resultsContainer.add(searchResultsNavigator);

    add(connectionWindow);

    //add results container
    add(resultsContainer);

    /*
     * SEARCH HISTORY
     */

    final WebMarkupContainer searchHistoryContainer = new WebMarkupContainer("searchHistoryContainer");
    searchHistoryContainer.setOutputMarkupPlaceholderTag(true);

    Label searchHistoryLabel = new Label("searchHistoryLabel", new ResourceModel("text.search.history"));
    searchHistoryContainer.add(searchHistoryLabel);

    IModel<List<ProfileSearchTerm>> searchHistoryModel = new LoadableDetachableModel<List<ProfileSearchTerm>>() {

        private static final long serialVersionUID = 1L;

        @Override
        protected List<ProfileSearchTerm> load() {
            List<ProfileSearchTerm> searchHistory = searchLogic.getSearchHistory(currentUserUuid);
            if (null == searchHistory) {
                return new ArrayList<ProfileSearchTerm>();
            } else {
                return searchHistory;
            }
        }

    };
    ListView<ProfileSearchTerm> searchHistoryList = new ListView<ProfileSearchTerm>("searchHistoryList",
            searchHistoryModel) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<ProfileSearchTerm> item) {

            AjaxLink<String> link = new AjaxLink<String>("previousSearchLink") {

                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    if (null != target) {

                        // post view event
                        sakaiProxy.postEvent(ProfileConstants.EVENT_SEARCH_BY_NAME,
                                "/profile/" + currentUserUuid, false);

                        ProfileSearchTerm searchTerm = item.getModelObject();
                        // this will update its position in list
                        searchLogic.addSearchTermToHistory(currentUserUuid, searchTerm);

                        searchStringModel.setString(searchTerm.getSearchTerm());
                        searchTypeRadioGroup.setModel(new Model<String>(searchTerm.getSearchType()));
                        connectionsCheckBox.setModel(new Model<Boolean>(searchTerm.isConnections()));

                        if (null == searchTerm.getWorksite()) {
                            worksiteCheckBox.setModel(new Model<Boolean>(false));
                            worksiteChoice.setModel(new Model(defaultWorksiteIdModel));
                        } else {
                            worksiteCheckBox.setModel(new Model<Boolean>(true));
                            worksiteChoice.setModel(new Model(searchTerm.getWorksite()));
                        }

                        setSearchCookie(searchTerm.getSearchType(), searchTerm.getSearchTerm(),
                                searchTerm.getSearchPageNumber(), searchTerm.isConnections(),
                                searchTerm.getWorksite());

                        if (ProfileConstants.SEARCH_TYPE_NAME.equals(searchTerm.getSearchType())) {

                            searchByName(resultsListView, searchResultsNavigator, searchHistoryContainer,
                                    target, searchTerm.getSearchTerm(), searchTerm.isConnections(),
                                    searchTerm.getWorksite());

                        } else if (ProfileConstants.SEARCH_TYPE_INTEREST.equals(searchTerm.getSearchType())) {

                            searchByInterest(resultsListView, searchResultsNavigator, searchHistoryContainer,
                                    target, searchTerm.getSearchTerm(), searchTerm.isConnections(),
                                    searchTerm.getWorksite());
                        }
                    }
                }

            };
            link.add(new Label("previousSearchLabel", item.getModelObject().getSearchTerm()));
            item.add(link);
        }
    };

    searchHistoryContainer.add(searchHistoryList);
    add(searchHistoryContainer);

    if (null == searchLogic.getSearchHistory(currentUserUuid)) {
        searchHistoryContainer.setVisible(false);
    }

    //clear button
    Form<Void> clearHistoryForm = new Form<Void>("clearHistory");
    clearHistoryForm.setOutputMarkupPlaceholderTag(true);

    clearHistoryButton = new AjaxButton("clearHistoryButton", clearHistoryForm) {
        private static final long serialVersionUID = 1L;

        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            searchLogic.clearSearchHistory(currentUserUuid);

            //clear the fields, hide self, then repaint
            searchField.clearInput();
            searchField.updateModel();

            searchHistoryContainer.setVisible(false);
            clearHistoryButton.setVisible(false);

            target.add(searchField);
            target.add(searchHistoryContainer);
            target.add(this);
        }
    };
    clearHistoryButton.setOutputMarkupPlaceholderTag(true);

    if (null == searchLogic.getSearchHistory(currentUserUuid)) {
        clearHistoryButton.setVisible(false); //invisible until we have something to clear
    }
    clearHistoryButton.setModel(new ResourceModel("button.search.history.clear"));
    clearHistoryForm.add(clearHistoryButton);
    searchHistoryContainer.add(clearHistoryForm);

    /*
     * Combined search submit
     */
    IndicatingAjaxButton searchSubmitButton = new IndicatingAjaxButton("searchSubmit", searchForm) {

        private static final long serialVersionUID = 1L;

        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            if (target != null) {
                //get the model and text entered
                StringModel model = (StringModel) form.getModelObject();
                //PRFL-811 - dont strip this down, we will lose i18n chars.
                //And there is no XSS risk since its only for the current user.
                String searchText = model.getString();

                //get search type
                String searchType = searchTypeRadioGroup.getModelObject();

                log.debug("MySearch search by " + searchType + ": " + searchText);

                if (StringUtils.isBlank(searchText)) {
                    return;
                }

                // save search terms
                ProfileSearchTerm searchTerm = new ProfileSearchTerm();
                searchTerm.setUserUuid(currentUserUuid);
                searchTerm.setSearchType(searchType);
                searchTerm.setSearchTerm(searchText);
                searchTerm.setSearchPageNumber(0);
                searchTerm.setSearchDate(new Date());
                searchTerm.setConnections(connectionsCheckBox.getModelObject());
                // set to worksite or empty depending on value of checkbox
                searchTerm.setWorksite(
                        (worksiteCheckBox.getModelObject() == true) ? worksiteChoice.getValue() : null);

                searchLogic.addSearchTermToHistory(currentUserUuid, searchTerm);

                // set cookie for current search (page 0 when submitting new search)
                setSearchCookie(searchTerm.getSearchType(), URLEncoder.encode(searchTerm.getSearchTerm()),
                        searchTerm.getSearchPageNumber(), searchTerm.isConnections(), searchTerm.getWorksite());

                if (ProfileConstants.SEARCH_TYPE_NAME.equals(searchType)) {

                    searchByName(resultsListView, searchResultsNavigator, searchHistoryContainer, target,
                            searchTerm.getSearchTerm(), searchTerm.isConnections(), searchTerm.getWorksite());

                    //post view event
                    sakaiProxy.postEvent(ProfileConstants.EVENT_SEARCH_BY_NAME, "/profile/" + currentUserUuid,
                            false);
                } else if (ProfileConstants.SEARCH_TYPE_INTEREST.equals(searchType)) {

                    searchByInterest(resultsListView, searchResultsNavigator, searchHistoryContainer, target,
                            searchTerm.getSearchTerm(), searchTerm.isConnections(), searchTerm.getWorksite());

                    //post view event
                    sakaiProxy.postEvent(ProfileConstants.EVENT_SEARCH_BY_INTEREST,
                            "/profile/" + currentUserUuid, false);
                }
            }
        }
    };
    searchSubmitButton.setModel(new ResourceModel("button.search.generic"));
    searchForm.add(searchSubmitButton);
    add(searchForm);

    if (null != searchCookie) {

        String searchString = getCookieSearchString(searchCookie.getValue());
        searchStringModel.setString(searchString);

        Boolean filterConnections = getCookieFilterConnections(searchCookie.getValue());
        String worksiteId = getCookieFilterWorksite(searchCookie.getValue());
        Boolean filterWorksite = (null == worksiteId) ? false : true;

        connectionsCheckBox.setModel(new Model<Boolean>(filterConnections));
        worksiteCheckBox.setModel(new Model<Boolean>(filterWorksite));
        worksiteChoice.setModel(new Model((null == worksiteId) ? defaultWorksiteIdModel : worksiteId));

        if (searchCookie.getValue().startsWith(ProfileConstants.SEARCH_TYPE_NAME)) {
            searchTypeRadioGroup.setModel(new Model<String>(ProfileConstants.SEARCH_TYPE_NAME));
            searchByName(resultsListView, searchResultsNavigator, searchHistoryContainer, null, searchString,
                    filterConnections, worksiteId);

        } else if (searchCookie.getValue().startsWith(ProfileConstants.SEARCH_TYPE_INTEREST)) {
            searchTypeRadioGroup.setModel(new Model<String>(ProfileConstants.SEARCH_TYPE_INTEREST));
            searchByInterest(resultsListView, searchResultsNavigator, searchHistoryContainer, null,
                    searchString, filterConnections, worksiteId);
        }
    } else {
        // default search type is name
        searchTypeRadioGroup.setModel(new Model<String>(ProfileConstants.SEARCH_TYPE_NAME));
    }
}

From source file:com.opengamma.analytics.financial.interestrate.capletstripping.CapletStrippingFunction.java

public CapletStrippingFunction(final List<CapFloor> caps, final YieldCurveBundle yieldCurves,
        final LinkedHashMap<String, double[]> knotPoints,
        final LinkedHashMap<String, Interpolator1D> interpolators,
        final LinkedHashMap<String, ParameterLimitsTransform> parameterTransforms,
        final LinkedHashMap<String, InterpolatedDoublesCurve> knownParameterTermSturctures) {
    Validate.notNull(caps, "caps null");
    Validate.notNull(knotPoints, "null node points");
    Validate.notNull(interpolators, "null interpolators");
    Validate.isTrue(knotPoints.size() == interpolators.size(), "size mismatch between nodes and interpolators");

    if (knownParameterTermSturctures == null) {
        Validate.isTrue(knotPoints.containsKey(ALPHA) && interpolators.containsKey(ALPHA),
                "alpha curve not found");
        Validate.isTrue(knotPoints.containsKey(BETA) && interpolators.containsKey(BETA),
                "beta curve not found");
        Validate.isTrue(knotPoints.containsKey(NU) && interpolators.containsKey(NU), "nu curve not found");
        Validate.isTrue(knotPoints.containsKey(RHO) && interpolators.containsKey(RHO), "rho curve not found");
    } else {/*from   w  ww .j av  a 2  s .  c  o  m*/
        Validate.isTrue((knotPoints.containsKey(ALPHA) && interpolators.containsKey(ALPHA))
                ^ knownParameterTermSturctures.containsKey(ALPHA), "alpha curve not found");
        Validate.isTrue((knotPoints.containsKey(BETA) && interpolators.containsKey(BETA))
                ^ knownParameterTermSturctures.containsKey(BETA), "beta curve not found");
        Validate.isTrue((knotPoints.containsKey(NU) && interpolators.containsKey(NU))
                ^ knownParameterTermSturctures.containsKey(NU), "nu curve not found");
        Validate.isTrue((knotPoints.containsKey(RHO) && interpolators.containsKey(RHO))
                ^ knownParameterTermSturctures.containsKey(RHO), "rho curve not found");
    }

    final LinkedHashMap<String, Interpolator1D> transInterpolators = new LinkedHashMap<String, Interpolator1D>();
    final Set<String> names = interpolators.keySet();
    for (final String name : names) {
        final Interpolator1D temp = new TransformedInterpolator1D(interpolators.get(name),
                parameterTransforms.get(name));
        transInterpolators.put(name, temp);
    }

    _curveBuilder = new InterpolatedCurveBuildingFunction(knotPoints, transInterpolators);

    //  _parameterTransforms = parameterTransforms; //TODO all the check for this

    _capPricers = new ArrayList<CapFloorPricer>(caps.size());
    for (final CapFloor cap : caps) {
        _capPricers.add(new CapFloorPricer(cap, yieldCurves));
    }
    _knownParameterTermStructures = knownParameterTermSturctures;
}

From source file:jp.or.openid.eiwg.scim.operation.Operation.java

/**
 * ?/*from w  w  w.j av  a2 s. c  om*/
 *
 * @param context
 * @param request
 * @param attributes
 * @param requestJson
 */
public LinkedHashMap<String, Object> createUserInfo(ServletContext context, HttpServletRequest request,
        String attributes, String requestJson) {
    LinkedHashMap<String, Object> result = null;

    Set<String> returnAttributeNameSet = new HashSet<>();

    // ?
    setError(0, null, null);

    // ??
    if (attributes != null && !attributes.isEmpty()) {
        // 
        String[] tempList = attributes.split(",");
        for (int i = 0; i < tempList.length; i++) {
            String attributeName = tempList[i].trim();
            // ???????
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, true);
            if (attributeSchema != null && !attributeSchema.isEmpty()) {
                returnAttributeNameSet.add(attributeName);
            } else {
                // ???????
                String message = String.format(MessageConstants.ERROR_INVALID_ATTRIBUTES, attributeName);
                setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                return result;
            }
        }
    }

    // ?
    if (requestJson == null || requestJson.isEmpty()) {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // (JSON)?
    ObjectMapper mapper = new ObjectMapper();
    LinkedHashMap<String, Object> requestObject = null;
    try {
        requestObject = mapper.readValue(requestJson, new TypeReference<LinkedHashMap<String, Object>>() {
        });
    } catch (JsonParseException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (JsonMappingException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (IOException e) {
        setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, MessageConstants.ERROR_UNKNOWN);
        return result;
    }

    // ?
    if (requestObject != null && !requestObject.isEmpty()) {
        Iterator<String> attributeIt = requestObject.keySet().iterator();
        while (attributeIt.hasNext()) {
            // ???
            String attributeName = attributeIt.next();
            // ?
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, true);
            if (attributeSchema != null) {
                // ????
                Object mutability = attributeSchema.get("mutability");
                if (mutability != null && mutability.toString().equalsIgnoreCase("readOnly")) {
                    // readOnly 
                    String message = String.format(MessageConstants.ERROR_READONLY_ATTRIBUTE, attributeName);
                    setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                    return result;
                }

                // ??
                // ()
            } else {
                // ????
                String message = String.format(MessageConstants.ERROR_UNKNOWN_ATTRIBUTE, attributeName);
                setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                return result;
            }
        }
    } else {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // ?
    // ()

    LinkedHashMap<String, Object> newUserInfo = new LinkedHashMap<String, Object>();

    // id?
    UUID uuid = UUID.randomUUID();
    newUserInfo.put("id", uuid.toString());

    Iterator<String> attributeIt = requestObject.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();
        // ?
        Object attributeValue = requestObject.get(attributeName);

        newUserInfo.put(attributeName, attributeValue);
    }

    // meta?
    LinkedHashMap<String, Object> metaValues = new LinkedHashMap<String, Object>();
    // meta.resourceType 
    metaValues.put("resourceType", "User");
    // meta.created 
    SimpleDateFormat xsdDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
    xsdDateTime.setTimeZone(TimeZone.getTimeZone("UTC"));
    metaValues.put("created", xsdDateTime.format(new Date()));
    // meta.location 
    String location = request.getScheme() + "://" + request.getServerName();
    int serverPort = request.getServerPort();
    if (serverPort != 80 && serverPort != 443) {
        location += ":" + Integer.toString(serverPort);
    }
    location += request.getContextPath();
    location += "/scim/Users/" + uuid.toString();
    metaValues.put("location", location);
    newUserInfo.put("meta", metaValues);

    // (??)
    @SuppressWarnings("unchecked")
    ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context
            .getAttribute("Users");
    if (users == null) {
        users = new ArrayList<LinkedHashMap<String, Object>>();
    }
    users.add(newUserInfo);
    context.setAttribute("Users", users);

    // ??
    result = new LinkedHashMap<String, Object>();
    attributeIt = newUserInfo.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();

        // ?
        LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context, attributeName,
                true);
        Object returned = attributeSchema.get("returned");

        if (returned != null && returned.toString().equalsIgnoreCase("never")) {
            continue;
        }

        // ?
        Object attributeValue = newUserInfo.get(attributeName);

        result.put(attributeName, attributeValue);
    }

    return result;
}

From source file:jp.or.openid.eiwg.scim.operation.Operation.java

/**
 * //from w  w w.  j a  v  a 2  s  . co m
 *
 * @param context
 * @param request
 * @param attributes
 * @param requestJson
 */
public LinkedHashMap<String, Object> updateUserInfo(ServletContext context, HttpServletRequest request,
        String targetId, String attributes, String requestJson) {
    LinkedHashMap<String, Object> result = null;

    Set<String> returnAttributeNameSet = new HashSet<>();

    // ?
    setError(0, null, null);

    // ??
    if (attributes != null && !attributes.isEmpty()) {
        // 
        String[] tempList = attributes.split(",");
        for (int i = 0; i < tempList.length; i++) {
            String attributeName = tempList[i].trim();
            // ???????
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, true);
            if (attributeSchema != null && !attributeSchema.isEmpty()) {
                returnAttributeNameSet.add(attributeName);
            } else {
                // ???????
                String message = String.format(MessageConstants.ERROR_INVALID_ATTRIBUTES, attributeName);
                setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                return result;
            }
        }
    }

    // id?
    LinkedHashMap<String, Object> targetInfo = null;
    @SuppressWarnings("unchecked")
    ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context
            .getAttribute("Users");
    Iterator<LinkedHashMap<String, Object>> usersIt = null;
    if (users != null && !users.isEmpty()) {
        usersIt = users.iterator();
        while (usersIt.hasNext()) {
            LinkedHashMap<String, Object> userInfo = usersIt.next();
            Object id = SCIMUtil.getAttribute(userInfo, "id");
            if (id != null && id instanceof String) {
                if (targetId.equals(id.toString())) {
                    targetInfo = userInfo;
                    break;
                }
            }
        }
    }

    if (targetInfo == null) {
        setError(HttpServletResponse.SC_NOT_FOUND, null, MessageConstants.ERROR_NOT_FOUND);
        return result;
    }

    // ?
    if (requestJson == null || requestJson.isEmpty()) {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // (JSON)?
    ObjectMapper mapper = new ObjectMapper();
    LinkedHashMap<String, Object> requestObject = null;
    try {
        requestObject = mapper.readValue(requestJson, new TypeReference<LinkedHashMap<String, Object>>() {
        });
    } catch (JsonParseException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (JsonMappingException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (IOException e) {
        setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, MessageConstants.ERROR_UNKNOWN);
        return result;
    }

    // ?
    if (requestObject != null && !requestObject.isEmpty()) {
        Iterator<String> attributeIt = requestObject.keySet().iterator();
        while (attributeIt.hasNext()) {
            // ???
            String attributeName = attributeIt.next();
            // ?
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, false);
            if (attributeSchema != null) {
                // ????
                Object mutability = attributeSchema.get("mutability");
                if (mutability != null && mutability.toString().equalsIgnoreCase("readOnly")) {
                    // readOnly 
                    String message = String.format(MessageConstants.ERROR_READONLY_ATTRIBUTE, attributeName);
                    setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                    return result;
                }

                // ??
                // ()
            } else {
                if (!attributeName.equalsIgnoreCase("schemas") && !attributeName.equalsIgnoreCase("id")
                        && !attributeName.equalsIgnoreCase("meta")) {
                    // ????
                    String message = String.format(MessageConstants.ERROR_UNKNOWN_ATTRIBUTE, attributeName);
                    setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                    return result;
                }
            }
        }
    } else {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // ?
    // ()

    LinkedHashMap<String, Object> updateUserInfo = new LinkedHashMap<String, Object>();

    // 
    updateUserInfo.put("id", targetId);

    Iterator<String> attributeIt = requestObject.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();
        // ?
        Object attributeValue = requestObject.get(attributeName);

        updateUserInfo.put(attributeName, attributeValue);
    }

    // meta
    Object metaObject = targetInfo.get("meta");
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, Object> metaValues = (LinkedHashMap<String, Object>) metaObject;
    // meta.lastModified 
    SimpleDateFormat xsdDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
    xsdDateTime.setTimeZone(TimeZone.getTimeZone("UTC"));
    metaValues.put("lastModified", xsdDateTime.format(new Date()));

    updateUserInfo.put("meta", metaValues);

    // (??)
    usersIt.remove();
    users.add(updateUserInfo);
    context.setAttribute("Users", users);

    // ??
    result = new LinkedHashMap<String, Object>();
    attributeIt = updateUserInfo.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();

        // ?
        LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context, attributeName,
                true);
        Object returned = attributeSchema.get("returned");

        if (returned != null && returned.toString().equalsIgnoreCase("never")) {
            continue;
        }

        // ?
        Object attributeValue = updateUserInfo.get(attributeName);

        result.put(attributeName, attributeValue);
    }

    return result;
}

From source file:com.tao.realweb.util.StringUtil.java

/** 
*  ??= ??? (a=1,b=2 =>a=1&b=2) // w w w.  j  av a  2s.co  m
*  
* @param map 
* @return 
*/
public static String linkedHashMapToString(LinkedHashMap<String, String> map) {
    if (map != null && map.size() > 0) {
        String result = "";
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String name = (String) it.next();
            String value = (String) map.get(name);
            result += (result.equals("")) ? "" : "&";
            result += String.format("%s=%s", name, value);
        }
        return result;
    }
    return null;
}

From source file:org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptorTest.java

public void checkSamplesData(String samples, List<Variant> allVariants) {
    Query query = new Query();
    QueryOptions options = new QueryOptions(QueryOptions.SORT, true); //no limit;

    System.out.println("options = " + options.toJson());
    query.put(RETURNED_SAMPLES.key(), samples);
    QueryResult<Variant> queryResult = dbAdaptor.get(query, options);
    List<String> samplesName;
    if (samples.isEmpty()) {
        samplesName = Collections.emptyList();
    } else {/* ww w .  ja v a2s  . com*/
        samplesName = query.getAsStringList(VariantDBAdaptor.VariantQueryParams.RETURNED_SAMPLES.key());
    }

    Iterator<Variant> it_1 = allVariants.iterator();
    Iterator<Variant> it_2 = queryResult.getResult().iterator();

    assertEquals(allVariants.size(), queryResult.getResult().size());

    LinkedHashMap<String, Integer> samplesPosition1 = null;
    LinkedHashMap<String, Integer> samplesPosition2 = null;
    for (int i = 0; i < queryResult.getNumResults(); i++) {
        Variant variant1 = it_1.next();
        Variant variant2 = it_2.next();

        assertEquals(variant1.toString(), variant2.toString());

        if (samplesPosition1 == null) {
            samplesPosition1 = variant1.getStudy(studyConfiguration.getStudyName()).getSamplesPosition();
        }
        if (samplesPosition2 == null) {
            samplesPosition2 = variant2.getStudy(studyConfiguration.getStudyName()).getSamplesPosition();
            assertEquals(samplesName, new ArrayList<>(samplesPosition2.keySet()));
        }
        assertSame(samplesPosition1, variant1.getStudy(studyConfiguration.getStudyName()).getSamplesPosition());
        assertSame(samplesPosition2, variant2.getStudy(studyConfiguration.getStudyName()).getSamplesPosition());
        for (String sampleName : samplesName) {
            String gt1 = variant1.getStudy(studyConfiguration.getStudyName()).getSampleData(sampleName, "GT");
            String gt2 = variant2.getStudy(studyConfiguration.getStudyName()).getSampleData(sampleName, "GT");
            assertEquals(sampleName + " " + variant1.getChromosome() + ":" + variant1.getStart(), gt1, gt2);
        }
    }
}