Example usage for org.apache.wicket.util.cookies CookieUtils getCookie

List of usage examples for org.apache.wicket.util.cookies CookieUtils getCookie

Introduction

In this page you can find the example usage for org.apache.wicket.util.cookies CookieUtils getCookie.

Prototype

public Cookie getCookie(final String name) 

Source Link

Document

Gets the cookie with 'name' attached to the latest WebRequest.

Usage

From source file:org.apache.syncope.client.enduser.resources.InfoResource.java

License:Apache License

@Override
protected ResourceResponse newResourceResponse(final IResource.Attributes attributes) {
    ResourceResponse response = new ResourceResponse();

    try {/*  ww  w . jav  a 2  s.co m*/
        final CookieUtils sessionCookieUtils = SyncopeEnduserSession.get().getCookieUtils();
        // set XSRF_TOKEN cookie
        if (!SyncopeEnduserSession.get().isXsrfTokenGenerated()
                && (sessionCookieUtils.getCookie(SyncopeEnduserConstants.XSRF_COOKIE) == null
                        || StringUtils.isBlank(sessionCookieUtils.getCookie(SyncopeEnduserConstants.XSRF_COOKIE)
                                .getValue()))) {
            LOG.debug("Set XSRF-TOKEN cookie");
            SyncopeEnduserSession.get().setXsrfTokenGenerated(true);
            sessionCookieUtils.save(SyncopeEnduserConstants.XSRF_COOKIE,
                    SaltGenerator.generate(SyncopeEnduserSession.get().getId()));
        }
        response.setWriteCallback(new WriteCallback() {

            @Override
            public void writeData(final IResource.Attributes attributes) throws IOException {
                attributes.getResponse().write(MAPPER.writeValueAsString(PlatformInfoAdapter
                        .toPlatformInfoRequest(SyncopeEnduserSession.get().getPlatformInfo())));
            }
        });
        response.setStatusCode(Response.Status.OK.getStatusCode());
    } catch (Exception e) {
        LOG.error("Error retrieving syncope info", e);
        response.setError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                new StringBuilder().append("ErrorMessage{{ ").append(e.getMessage()).append(" }}").toString());
    }

    return response;
}

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

License:Educational Community License

/**
 * Does the actual rendering of the page
 * @param userUuid/*from   w ww .ja  v a2s  .com*/
 */
private void renderMyProfile(final String userUuid) {

    //don't do this for super users viewing other people's profiles as otherwise there is no way back to own profile
    if (!sakaiProxy.isSuperUserAndProxiedToUser(userUuid)) {
        disableLink(myProfileLink);
    }

    //add the feedback panel for any error messages
    FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackPanel");
    add(feedbackPanel);
    feedbackPanel.setVisible(false); //hide by default

    //get the prefs record, or a default if none exists yet
    final ProfilePreferences prefs = preferencesLogic.getPreferencesRecordForUser(userUuid);

    //if null, throw exception
    if (prefs == null) {
        throw new ProfilePreferencesNotDefinedException(
                "Couldn't create default preferences record for " + userUuid);
    }

    //get SakaiPerson for this user
    SakaiPerson sakaiPerson = sakaiProxy.getSakaiPerson(userUuid);
    //if null, create one 
    if (sakaiPerson == null) {
        log.warn("No SakaiPerson for " + userUuid + ". Creating one.");
        sakaiPerson = sakaiProxy.createSakaiPerson(userUuid);
        //if its still null, throw exception
        if (sakaiPerson == null) {
            throw new ProfileNotDefinedException("Couldn't create a SakaiPerson for " + userUuid);
        }
        //post create event
        sakaiProxy.postEvent(ProfileConstants.EVENT_PROFILE_NEW, userUuid, true);
    }

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

    //get some values from SakaiPerson or SakaiProxy if empty
    //SakaiPerson returns NULL strings if value is not set, not blank ones

    //these must come from Account to keep it all in sync
    //we *could* get a User object here and get the values.
    String userDisplayName = sakaiProxy.getUserDisplayName(userUuid);
    /*
    String userFirstName = sakaiProxy.getUserFirstName(userId);
    String userLastName = sakaiProxy.getUserLastName(userId);
    */

    String userEmail = sakaiProxy.getUserEmail(userUuid);

    //create instance of the UserProfile class
    //we then pass the userProfile in the constructor to the child panels
    final UserProfile userProfile = new UserProfile();

    //get rest of values from SakaiPerson and setup UserProfile
    userProfile.setUserUuid(userUuid);

    userProfile.setNickname(sakaiPerson.getNickname());
    userProfile.setDateOfBirth(sakaiPerson.getDateOfBirth());
    userProfile.setDisplayName(userDisplayName);
    //userProfile.setFirstName(userFirstName);
    //userProfile.setLastName(userLastName);
    //userProfile.setMiddleName(sakaiPerson.getInitials());

    userProfile.setEmail(userEmail);
    userProfile.setHomepage(sakaiPerson.getLabeledURI());
    userProfile.setHomephone(sakaiPerson.getHomePhone());
    userProfile.setWorkphone(sakaiPerson.getTelephoneNumber());
    userProfile.setMobilephone(sakaiPerson.getMobile());
    userProfile.setFacsimile(sakaiPerson.getFacsimileTelephoneNumber());

    userProfile.setDepartment(sakaiPerson.getOrganizationalUnit());
    userProfile.setPosition(sakaiPerson.getTitle());
    userProfile.setSchool(sakaiPerson.getCampus());
    userProfile.setRoom(sakaiPerson.getRoomNumber());

    userProfile.setCourse(sakaiPerson.getEducationCourse());
    userProfile.setSubjects(sakaiPerson.getEducationSubjects());

    userProfile.setStaffProfile(sakaiPerson.getStaffProfile());
    userProfile.setAcademicProfileUrl(sakaiPerson.getAcademicProfileUrl());
    userProfile.setUniversityProfileUrl(sakaiPerson.getUniversityProfileUrl());
    userProfile.setPublications(sakaiPerson.getPublications());

    // business fields
    userProfile.setBusinessBiography(sakaiPerson.getBusinessBiography());
    userProfile.setCompanyProfiles(profileLogic.getCompanyProfiles(userUuid));

    userProfile.setFavouriteBooks(sakaiPerson.getFavouriteBooks());
    userProfile.setFavouriteTvShows(sakaiPerson.getFavouriteTvShows());
    userProfile.setFavouriteMovies(sakaiPerson.getFavouriteMovies());
    userProfile.setFavouriteQuotes(sakaiPerson.getFavouriteQuotes());
    userProfile.setPersonalSummary(sakaiPerson.getNotes());

    // social networking fields
    SocialNetworkingInfo socialInfo = profileLogic.getSocialNetworkingInfo(userProfile.getUserUuid());
    if (socialInfo == null) {
        socialInfo = new SocialNetworkingInfo();
    }
    userProfile.setSocialInfo(socialInfo);

    //PRFL-97 workaround. SakaiPerson table needs to be upgraded so locked is not null, but this handles it if not upgraded.
    if (sakaiPerson.getLocked() == null) {
        userProfile.setLocked(false);
        this.setLocked(false);
    } else {
        this.setLocked(sakaiPerson.getLocked());
        userProfile.setLocked(this.isLocked());
    }

    //what type of picture changing method do we use?
    int profilePictureType = sakaiProxy.getProfilePictureType();

    //change picture panel (upload or url depending on property)
    final Panel changePicture;

    //render appropriate panel with appropriate constructor ie if superUser etc
    if (profilePictureType == ProfileConstants.PICTURE_SETTING_UPLOAD) {

        if (sakaiProxy.isSuperUserAndProxiedToUser(userUuid)) {
            changePicture = new ChangeProfilePictureUpload("changePicture", userUuid);
        } else {
            changePicture = new ChangeProfilePictureUpload("changePicture");
        }
    } else if (profilePictureType == ProfileConstants.PICTURE_SETTING_URL) {
        if (sakaiProxy.isSuperUserAndProxiedToUser(userUuid)) {
            changePicture = new ChangeProfilePictureUrl("changePicture", userUuid);
        } else {
            changePicture = new ChangeProfilePictureUrl("changePicture");
        }
    } else if (profilePictureType == ProfileConstants.PICTURE_SETTING_OFFICIAL) {
        //cannot edit anything if using official images
        changePicture = new EmptyPanel("changePicture");
    } else {
        //no valid option for changing picture was returned from the Profile2 API.
        log.error("Invalid picture type returned: " + profilePictureType);
        changePicture = new EmptyPanel("changePicture");
    }
    changePicture.setOutputMarkupPlaceholderTag(true);
    changePicture.setVisible(false);
    add(changePicture);

    //add the current picture
    add(new ProfileImage("photo", new Model<String>(userUuid)));

    //change profile image button
    AjaxLink<Void> changePictureLink = new AjaxLink<Void>("changePictureLink") {
        private static final long serialVersionUID = 1L;

        public void onClick(AjaxRequestTarget target) {

            //show the panel
            changePicture.setVisible(true);
            target.add(changePicture);

            //resize iframe to fit it
            target.appendJavaScript("resizeFrame('grow');");
        }

    };
    changePictureLink.add(new Label("changePictureLabel", new ResourceModel("link.change.profile.picture")));

    //is picture changing disabled? (property, or locked)
    if ((!sakaiProxy.isProfilePictureChangeEnabled() || userProfile.isLocked()) && !sakaiProxy.isSuperUser()) {
        changePictureLink.setEnabled(false);
        changePictureLink.setVisible(false);
    }

    //if using official images, is the user allowed to select an alternate?
    //or have they specified the official image in their preferences.
    if (sakaiProxy.isOfficialImageEnabledGlobally()
            && (!sakaiProxy.isUsingOfficialImageButAlternateSelectionEnabled() || prefs.isUseOfficialImage())) {
        changePictureLink.setEnabled(false);
        changePictureLink.setVisible(false);
    }

    add(changePictureLink);

    /* SIDELINKS */
    WebMarkupContainer sideLinks = new WebMarkupContainer("sideLinks");
    int visibleSideLinksCount = 0;

    //ADMIN: ADD AS CONNECTION
    if (sakaiProxy.isSuperUserAndProxiedToUser(userUuid)) {

        //init
        boolean friend = false;
        boolean friendRequestToThisPerson = false;
        boolean friendRequestFromThisPerson = false;
        String currentUserUuid = sakaiProxy.getCurrentUserId();
        String nickname = userProfile.getNickname();
        if (StringUtils.isBlank(nickname)) {
            nickname = "";
        }

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

        //setup friend status
        friend = connectionsLogic.isUserXFriendOfUserY(userUuid, currentUserUuid);
        if (!friend) {
            friendRequestToThisPerson = connectionsLogic.isFriendRequestPending(currentUserUuid, userUuid);
        }
        if (!friend && !friendRequestToThisPerson) {
            friendRequestFromThisPerson = connectionsLogic.isFriendRequestPending(userUuid, currentUserUuid);
        }

        WebMarkupContainer addFriendContainer = new WebMarkupContainer("addFriendContainer");
        final ModalWindow addFriendWindow = new ModalWindow("addFriendWindow");

        //link
        final AjaxLink<Void> addFriendLink = new AjaxLink<Void>("addFriendLink") {
            private static final long serialVersionUID = 1L;

            public void onClick(AjaxRequestTarget target) {
                addFriendWindow.show(target);
            }
        };
        final Label addFriendLabel = new Label("addFriendLabel");
        addFriendLink.add(addFriendLabel);
        addFriendContainer.add(addFriendLink);

        //setup link/label and windows
        if (friend) {
            addFriendLabel.setDefaultModel(new ResourceModel("text.friend.confirmed"));
            addFriendLink.add(new AttributeModifier("class", true,
                    new Model<String>("instruction icon connection-confirmed")));
            addFriendLink.setEnabled(false);
        } else if (friendRequestToThisPerson) {
            addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
            addFriendLink.add(new AttributeModifier("class", true,
                    new Model<String>("instruction icon connection-request")));
            addFriendLink.setEnabled(false);
        } else if (friendRequestFromThisPerson) {
            //TODO (confirm pending friend request link)
            //could be done by setting the content off the addFriendWindow.
            //will need to rename some links to make more generic and set the onClick and setContent in here for link and window
            addFriendLabel.setDefaultModel(new ResourceModel("text.friend.pending"));
            addFriendLink.add(new AttributeModifier("class", true,
                    new Model<String>("instruction icon connection-request")));
            addFriendLink.setEnabled(false);
        } else {
            addFriendLabel.setDefaultModel(
                    new StringResourceModel("link.friend.add.name", null, new Object[] { nickname }));
            addFriendLink.add(new AttributeModifier("class", true, new Model<String>("icon connection-add")));
            addFriendWindow.setContent(new AddFriend(addFriendWindow.getContentId(), addFriendWindow,
                    friendActionModel, currentUserUuid, userUuid));
        }

        sideLinks.add(addFriendContainer);

        //ADD FRIEND MODAL WINDOW HANDLER 
        addFriendWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
            private static final long serialVersionUID = 1L;

            public void onClose(AjaxRequestTarget target) {
                if (friendActionModel.isRequested()) {
                    //friend was successfully requested, update label and link
                    addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
                    addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction")));
                    addFriendLink.setEnabled(false);
                    target.add(addFriendLink);
                }
            }
        });

        add(addFriendWindow);

        if (sakaiProxy.isConnectionsEnabledGlobally()) {
            visibleSideLinksCount++;
        } else {
            addFriendContainer.setVisible(false);
        }

        //ADMIN: LOCK/UNLOCK A PROFILE
        WebMarkupContainer lockProfileContainer = new WebMarkupContainer("lockProfileContainer");
        final Label lockProfileLabel = new Label("lockProfileLabel");

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

            public void onClick(AjaxRequestTarget target) {
                //toggle it to be opposite of what it currently is, update labels and icons
                boolean locked = isLocked();
                if (sakaiProxy.toggleProfileLocked(userUuid, !locked)) {
                    setLocked(!locked);
                    log.info("MyProfile(): SuperUser toggled lock status of profile for " + userUuid + " to "
                            + !locked);
                    lockProfileLabel.setDefaultModel(new ResourceModel("link.profile.locked." + isLocked()));
                    add(new AttributeModifier("title", true,
                            new ResourceModel("text.profile.locked." + isLocked())));
                    if (isLocked()) {
                        add(new AttributeModifier("class", true, new Model<String>("icon locked")));
                    } else {
                        add(new AttributeModifier("class", true, new Model<String>("icon unlocked")));
                    }
                    target.add(this);
                }
            }
        };

        //set init icon for locked
        if (isLocked()) {
            lockProfileLink.add(new AttributeModifier("class", true, new Model<String>("icon locked")));
        } else {
            lockProfileLink.add(new AttributeModifier("class", true, new Model<String>("icon unlocked")));
        }

        lockProfileLink.add(lockProfileLabel);

        //setup link/label and windows with special property based on locked status
        lockProfileLabel.setDefaultModel(new ResourceModel("link.profile.locked." + isLocked()));
        lockProfileLink.add(
                new AttributeModifier("title", true, new ResourceModel("text.profile.locked." + isLocked())));

        lockProfileContainer.add(lockProfileLink);

        sideLinks.add(lockProfileContainer);

        visibleSideLinksCount++;

    } else {
        //blank components
        WebMarkupContainer addFriendContainer = new WebMarkupContainer("addFriendContainer");
        addFriendContainer.add(new AjaxLink("addFriendLink") {
            public void onClick(AjaxRequestTarget target) {
            }
        }).add(new Label("addFriendLabel"));
        sideLinks.add(addFriendContainer);
        add(new WebMarkupContainer("addFriendWindow"));

        WebMarkupContainer lockProfileContainer = new WebMarkupContainer("lockProfileContainer");
        lockProfileContainer.add(new AjaxLink("lockProfileLink") {
            public void onClick(AjaxRequestTarget target) {
            }
        }).add(new Label("lockProfileLabel"));
        sideLinks.add(lockProfileContainer);
    }

    //hide entire list if no links to show
    if (visibleSideLinksCount == 0) {
        sideLinks.setVisible(false);
    }

    add(sideLinks);

    //status panel
    Panel myStatusPanel = new MyStatusPanel("myStatusPanel", userProfile);
    add(myStatusPanel);

    List<ITab> tabs = new ArrayList<ITab>();

    AjaxTabbedPanel tabbedPanel = new AjaxTabbedPanel("myProfileTabs", tabs) {

        private static final long serialVersionUID = 1L;

        // overridden so we can add tooltips to tabs
        @Override
        protected WebMarkupContainer newLink(String linkId, final int index) {
            WebMarkupContainer link = super.newLink(linkId, index);

            if (ProfileConstants.TAB_INDEX_PROFILE == index) {
                link.add(new AttributeModifier("title", true, new ResourceModel("link.tab.profile.tooltip")));

            } else if (ProfileConstants.TAB_INDEX_WALL == index) {
                link.add(new AttributeModifier("title", true, new ResourceModel("link.tab.wall.tooltip")));
            }
            return link;
        }
    };

    CookieUtils utils = new CookieUtils();
    Cookie tabCookie = utils.getCookie(ProfileConstants.TAB_COOKIE);

    if (sakaiProxy.isProfileFieldsEnabled()) {
        tabs.add(new AbstractTab(new ResourceModel("link.tab.profile")) {

            private static final long serialVersionUID = 1L;

            @Override
            public Panel getPanel(String panelId) {

                setTabCookie(ProfileConstants.TAB_INDEX_PROFILE);
                MyProfilePanelState panelState = new MyProfilePanelState();
                panelState.showBusinessDisplay = sakaiProxy.isBusinessProfileEnabled();
                panelState.showSocialNetworkingDisplay = sakaiProxy.isSocialProfileEnabled();
                panelState.showInterestsDisplay = sakaiProxy.isInterestsProfileEnabled();
                panelState.showStaffDisplay = sakaiProxy.isStaffProfileEnabled();
                panelState.showStudentDisplay = sakaiProxy.isStudentProfileEnabled();
                return new MyProfilePanel(panelId, userProfile, panelState);
            }

        });
    }

    if (true == sakaiProxy.isWallEnabledGlobally()) {

        tabs.add(new AbstractTab(new ResourceModel("link.tab.wall")) {

            private static final long serialVersionUID = 1L;

            @Override
            public Panel getPanel(String panelId) {

                setTabCookie(ProfileConstants.TAB_INDEX_WALL);
                if (true == sakaiProxy.isSuperUser()) {
                    return new MyWallPanel(panelId, userUuid);
                } else {
                    return new MyWallPanel(panelId);
                }
            }
        });

        if (true == sakaiProxy.isWallDefaultProfilePage() && null == tabCookie) {

            tabbedPanel.setSelectedTab(ProfileConstants.TAB_INDEX_WALL);
        }
    }

    if (null != tabCookie) {
        try {
            tabbedPanel.setSelectedTab(Integer.parseInt(tabCookie.getValue()));
        } catch (IndexOutOfBoundsException e) {
            //do nothing. This will be thrown if the cookie contains a value > the number of tabs but thats ok.
        }
    }

    add(tabbedPanel);

    //kudos panel
    add(new AjaxLazyLoadPanel("myKudos") {
        private static final long serialVersionUID = 1L;

        @Override
        public Component getLazyLoadComponent(String markupId) {
            if (sakaiProxy.isMyKudosEnabledGlobally() && prefs.isShowKudos()) {

                int score = kudosLogic.getKudos(userUuid);
                if (score > 0) {
                    return new KudosPanel(markupId, userUuid, userUuid, score);
                }
            }
            return new EmptyPanel(markupId);
        }
    });

    //friends feed panel for self - lazy loaded
    add(new NotifyingAjaxLazyLoadPanel("friendsFeed") {
        private static final long serialVersionUID = 1L;

        @Override
        public Component getLazyLoadComponent(String markupId) {
            if (sakaiProxy.isConnectionsEnabledGlobally()) {
                return new FriendsFeed(markupId, userUuid, userUuid);
            }
            return new EmptyPanel(markupId);
        }

        @Override
        public void renderHead(IHeaderResponse response) {
            response.render(OnLoadHeaderItem.forScript("resizeFrame('grow');"));
        }
    });

    //gallery feed panel
    add(new NotifyingAjaxLazyLoadPanel("galleryFeed") {
        private static final long serialVersionUID = 1L;

        @Override
        public Component getLazyLoadComponent(String markupId) {
            if (sakaiProxy.isProfileGalleryEnabledGlobally() && prefs.isShowGalleryFeed()) {
                return new GalleryFeed(markupId, userUuid, userUuid).setOutputMarkupId(true);
            } else {
                return new EmptyPanel(markupId);
            }
        }

        @Override
        public void renderHead(IHeaderResponse response) {
            response.render(OnLoadHeaderItem.forScript("resizeFrame('grow');"));
        }

    });
}

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

License:Educational Community License

public MySearch() {

    log.debug("MySearch()");

    disableLink(searchLink);//from   w w  w . j a v  a2s.c  om

    //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:org.sakaiproject.profile2.tool.pages.ViewProfile.java

License:Educational Community License

public ViewProfile(final String userUuid, final String tab) {

    log.debug("ViewProfile()");

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

    //get current user info
    User currentUser = sakaiProxy.getUserQuietly(sakaiProxy.getCurrentUserId());
    final String currentUserId = currentUser.getId();
    String currentUserType = currentUser.getType();

    //double check, if somehow got to own ViewPage, redirect to MyProfile instead
    if (userUuid.equals(currentUserId)) {
        log.warn("ViewProfile: user " + userUuid + " accessed ViewProfile for self. Redirecting...");
        throw new RestartResponseException(new MyProfile());
    }/*from  w  w w  .j a v a  2s.  c  o m*/

    //check if super user, to grant editing rights to another user's profile
    if (sakaiProxy.isSuperUser()) {
        log.warn("ViewProfile: superUser " + currentUserId + " accessed ViewProfile for " + userUuid
                + ". Redirecting to allow edit.");
        throw new RestartResponseException(new MyProfile(userUuid));
    }

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

    /* DEPRECATED via PRFL-24 when privacy was relaxed
    if(!isProfileAllowed) {
       throw new ProfileIllegalAccessException("User: " + currentUserId + " is not allowed to view profile for: " + userUuid);
    }
    */

    //get some values from User
    User user = sakaiProxy.getUserQuietly(userUuid);
    String userDisplayName = user.getDisplayName();
    String userType = user.getType();

    //init
    final boolean friend;
    boolean friendRequestToThisPerson = false;
    boolean friendRequestFromThisPerson = false;

    //friend?
    friend = connectionsLogic.isUserXFriendOfUserY(userUuid, currentUserId);

    //if not friend, has a friend request already been made to this person?
    if (!friend) {
        friendRequestToThisPerson = connectionsLogic.isFriendRequestPending(currentUserId, userUuid);
    }

    //if not friend and no friend request to this person, has a friend request been made from this person to the current user?
    if (!friend && !friendRequestToThisPerson) {
        friendRequestFromThisPerson = connectionsLogic.isFriendRequestPending(userUuid, currentUserId);
    }

    //privacy checks
    final ProfilePrivacy privacy = privacyLogic.getPrivacyRecordForUser(userUuid);

    boolean isFriendsListVisible = privacyLogic.isActionAllowed(userUuid, currentUserId,
            PrivacyType.PRIVACY_OPTION_MYFRIENDS);
    boolean isKudosVisible = privacyLogic.isActionAllowed(userUuid, currentUserId,
            PrivacyType.PRIVACY_OPTION_MYKUDOS);
    boolean isGalleryVisible = privacyLogic.isActionAllowed(userUuid, currentUserId,
            PrivacyType.PRIVACY_OPTION_MYPICTURES);
    boolean isConnectionAllowed = sakaiProxy.isConnectionAllowedBetweenUserTypes(currentUserType, userType);
    boolean isOnlineStatusVisible = privacyLogic.isActionAllowed(userUuid, currentUserId,
            PrivacyType.PRIVACY_OPTION_ONLINESTATUS);

    final ProfilePreferences prefs = preferencesLogic.getPreferencesRecordForUser(userUuid);

    /* IMAGE */
    add(new ProfileImage("photo", new Model<String>(userUuid)));

    /* NAME */
    Label profileName = new Label("profileName", userDisplayName);
    add(profileName);

    /* ONLINE PRESENCE INDICATOR */
    if (sakaiProxy.isOnlineStatusEnabledGlobally() && prefs.isShowOnlineStatus() && isOnlineStatusVisible) {
        add(new OnlinePresenceIndicator("online", userUuid));
    } else {
        add(new EmptyPanel("online"));
    }

    /*STATUS PANEL */
    if (sakaiProxy.isProfileStatusEnabled()) {
        add(new ProfileStatusRenderer("status", userUuid, privacy, null, "tiny"));
    } else {
        add(new EmptyPanel("status"));
    }

    /* TABS */
    List<ITab> tabs = new ArrayList<ITab>();

    AjaxTabbedPanel tabbedPanel = new AjaxTabbedPanel("viewProfileTabs", tabs) {

        private static final long serialVersionUID = 1L;

        // overridden so we can add tooltips to tabs
        @Override
        protected WebMarkupContainer newLink(String linkId, final int index) {
            WebMarkupContainer link = super.newLink(linkId, index);

            if (ProfileConstants.TAB_INDEX_PROFILE == index) {
                link.add(new AttributeModifier("title", true, new ResourceModel("link.tab.profile.tooltip")));

            } else if (ProfileConstants.TAB_INDEX_WALL == index) {
                link.add(new AttributeModifier("title", true, new ResourceModel("link.tab.wall.tooltip")));
            }
            return link;
        }
    };

    CookieUtils utils = new CookieUtils();
    Cookie tabCookie = utils.getCookie(ProfileConstants.TAB_COOKIE);

    if (sakaiProxy.isProfileFieldsEnabled()) {
        tabs.add(new AbstractTab(new ResourceModel("link.tab.profile")) {

            private static final long serialVersionUID = 1L;

            @Override
            public Panel getPanel(String panelId) {

                setTabCookie(ProfileConstants.TAB_INDEX_PROFILE);
                return new ViewProfilePanel(panelId, userUuid, currentUserId, privacy, friend);
            }
        });
    }

    if (sakaiProxy.isWallEnabledGlobally()) {

        tabs.add(new AbstractTab(new ResourceModel("link.tab.wall")) {

            private static final long serialVersionUID = 1L;

            @Override
            public Panel getPanel(String panelId) {

                setTabCookie(ProfileConstants.TAB_INDEX_WALL);
                return new ViewWallPanel(panelId, userUuid);
            }
        });

        if (sakaiProxy.isWallDefaultProfilePage() && null == tabCookie) {

            tabbedPanel.setSelectedTab(ProfileConstants.TAB_INDEX_WALL);
        }
    }

    if (null != tab) {
        tabbedPanel.setSelectedTab(Integer.parseInt(tab));
    } else if (null != tabCookie) {
        try {
            tabbedPanel.setSelectedTab(Integer.parseInt(tabCookie.getValue()));
        } catch (IndexOutOfBoundsException e) {
            //do nothing. This will be thrown if the cookie contains a value > the number of tabs but thats ok.
        }
    }

    add(tabbedPanel);

    /* SIDELINKS */
    WebMarkupContainer sideLinks = new WebMarkupContainer("sideLinks");
    int visibleSideLinksCount = 0;

    WebMarkupContainer addFriendContainer = new WebMarkupContainer("addFriendContainer");

    //ADD FRIEND MODAL WINDOW
    final ModalWindow addFriendWindow = new ModalWindow("addFriendWindow");

    //FRIEND LINK/STATUS
    final AjaxLink<Void> addFriendLink = new AjaxLink<Void>("addFriendLink") {
        private static final long serialVersionUID = 1L;

        public void onClick(AjaxRequestTarget target) {
            addFriendWindow.show(target);
        }
    };

    final Label addFriendLabel = new Label("addFriendLabel");
    addFriendLink.add(addFriendLabel);

    addFriendContainer.add(addFriendLink);

    //setup link/label and windows
    if (friend) {
        addFriendLabel.setDefaultModel(new ResourceModel("text.friend.confirmed"));
        addFriendLink.add(new AttributeModifier("class", true,
                new Model<String>("instruction icon connection-confirmed")));
        addFriendLink.setEnabled(false);
    } else if (friendRequestToThisPerson) {
        addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
        addFriendLink.add(
                new AttributeModifier("class", true, new Model<String>("instruction icon connection-request")));
        addFriendLink.setEnabled(false);
    } else if (friendRequestFromThisPerson) {
        //TODO (confirm pending friend request link)
        //could be done by setting the content off the addFriendWindow.
        //will need to rename some links to make more generic and set the onClick and setContent in here for link and window
        addFriendLabel.setDefaultModel(new ResourceModel("text.friend.pending"));
        addFriendLink.add(
                new AttributeModifier("class", true, new Model<String>("instruction icon connection-request")));
        addFriendLink.setEnabled(false);
    } else {
        addFriendLabel.setDefaultModel(
                new StringResourceModel("link.friend.add.name", null, new Object[] { user.getFirstName() }));
        addFriendWindow.setContent(new AddFriend(addFriendWindow.getContentId(), addFriendWindow,
                friendActionModel, currentUserId, userUuid));
    }
    sideLinks.add(addFriendContainer);

    //ADD FRIEND MODAL WINDOW HANDLER 
    addFriendWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
        private static final long serialVersionUID = 1L;

        public void onClose(AjaxRequestTarget target) {
            if (friendActionModel.isRequested()) {
                //friend was successfully requested, update label and link
                addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
                addFriendLink.add(new AttributeModifier("class", true,
                        new Model<String>("instruction icon connection-request")));
                addFriendLink.setEnabled(false);
                target.add(addFriendLink);
            }
        }
    });
    addFriendWindow.setVisible(sakaiProxy.isConnectionsEnabledGlobally());
    add(addFriendWindow);

    //hide connection link if not allowed
    if (!isConnectionAllowed && !sakaiProxy.isConnectionsEnabledGlobally()) {
        addFriendContainer.setVisible(false);
    } else {
        visibleSideLinksCount++;
    }

    //hide entire list if no links to show
    if (visibleSideLinksCount == 0) {
        sideLinks.setVisible(false);
    }

    add(sideLinks);

    /* KUDOS PANEL */
    if (sakaiProxy.isMyKudosEnabledGlobally() && isKudosVisible) {
        add(new AjaxLazyLoadPanel("myKudos") {
            private static final long serialVersionUID = 1L;

            @Override
            public Component getLazyLoadComponent(String markupId) {
                if (prefs.isShowKudos()) {

                    int score = kudosLogic.getKudos(userUuid);
                    if (score > 0) {
                        return new KudosPanel(markupId, userUuid, currentUserId, score);
                    }
                }
                return new EmptyPanel(markupId);
            }
        });
    } else {
        add(new EmptyPanel("myKudos").setVisible(false));
    }

    /* FRIENDS FEED PANEL */
    if (sakaiProxy.isConnectionsEnabledGlobally() && isFriendsListVisible) {
        add(new AjaxLazyLoadPanel("friendsFeed") {
            private static final long serialVersionUID = 1L;

            @Override
            public Component getLazyLoadComponent(String markupId) {
                return new FriendsFeed(markupId, userUuid, currentUserId);
            }

        });
    } else {
        add(new EmptyPanel("friendsFeed").setVisible(false));
    }

    /* GALLERY FEED PANEL */
    if (sakaiProxy.isProfileGalleryEnabledGlobally() && isGalleryVisible && prefs.isShowGalleryFeed()) {
        add(new AjaxLazyLoadPanel("galleryFeed") {
            private static final long serialVersionUID = 1L;

            @Override
            public Component getLazyLoadComponent(String markupId) {
                return new GalleryFeed(markupId, userUuid, currentUserId).setOutputMarkupId(true);
            }
        });
    } else {
        add(new EmptyPanel("galleryFeed").setVisible(false));
    }
}