@Override @Transactional public UserProfile setAlerts( String userAuthId, List<String> monthlyAlerts, List<String> weeklyAlerts) { UserProfile user = getUserByAuthId(userAuthId); log.debug( "updating alerts for user: {}; Montly alerts: {}; weekly alerts: {}", new Object[] { user.getDisplayName(), StringUtils.join(monthlyAlerts, ","), StringUtils.join(weeklyAlerts, ",") }); List<String> allAlerts; if (monthlyAlerts != null && weeklyAlerts != null) { allAlerts = new ArrayList<String>(monthlyAlerts.size() + weeklyAlerts.size()); allAlerts.addAll(getAlertsList(monthlyAlerts, UserProfile.MONTHLY_ALERT_SUFFIX)); allAlerts.addAll(getAlertsList(weeklyAlerts, UserProfile.WEEKLY_ALERT_SUFFIX)); } else if (monthlyAlerts != null) { allAlerts = new ArrayList<String>(monthlyAlerts.size()); allAlerts.addAll(getAlertsList(monthlyAlerts, UserProfile.MONTHLY_ALERT_SUFFIX)); } else if (weeklyAlerts != null) { allAlerts = new ArrayList<String>(weeklyAlerts.size()); allAlerts.addAll(getAlertsList(weeklyAlerts, UserProfile.WEEKLY_ALERT_SUFFIX)); } else { allAlerts = new ArrayList<String>(0); } user.setAlertsList(allAlerts); hibernateTemplate.update(user); return user; }
/** * Save the user's search * * @return */ @Transactional(rollbackFor = {Throwable.class}) @SuppressWarnings("unchecked") public String saveSearch() { final UserProfile user = getCurrentUser(); if (user == null) { log.info("User is null for saving search"); addActionError("You must be logged in"); return ERROR; } // Make sure the user is authenticated, is this redundant? this.permissionsService.checkLogin(user.getAuthId()); if (searchName == null || searchName.length() == 0) { addActionError("Search name must be specified."); return INPUT; } List<SavedSearchView> savedSearchViewList = userService.getSavedSearches(this.getCurrentUser().getID()); for (SavedSearchView savedSearchView : savedSearchViewList) { if (savedSearchView.getSearchName().equals(this.searchName)) { addActionError("Search name must be unique."); return INPUT; } } userService.saveSearch( user.getID(), getSearchParameters(), searchName, this.weekly, this.monthly); return SUCCESS; }
@Override @Transactional(rollbackFor = {Throwable.class}) public UserProfile login(final String authId, final UserLogin loginInfo) { log.debug("logging in user with auth id {}", authId); UserProfile user = getUserByAuthId(authId); if (user != null && this.advancedLogging) { loginInfo.setUserProfileID(user.getID()); hibernateTemplate.save(loginInfo); } return user; }
@Override @Transactional(rollbackFor = {Throwable.class}) public UserProfile updateProfile(final UserProfile userProfile) throws NoSuchUserException { // get the user by auth id UserProfile existingUser = getUserByAuthId(userProfile.getAuthId()); if (existingUser == null) { throw new NoSuchUserException(); } log.debug("Found a user with authID: {}, updating profile", userProfile.getAuthId()); copyFields(userProfile, existingUser); hibernateTemplate.update(existingUser); return existingUser; }
/** {@inheritDoc} */ @Transactional(rollbackFor = {Throwable.class}) public void deleteSavedSearch(Long userProfileId, Long savedSearchId) { UserProfile userProfile = (UserProfile) DataAccessUtils.uniqueResult( hibernateTemplate.findByCriteria( DetachedCriteria.forClass(UserProfile.class) .add(Restrictions.eq("ID", userProfileId)) .setFetchMode("savedSearches", FetchMode.JOIN) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY))); List<SavedSearch> savedSearches = userProfile.getSavedSearches(); for (Iterator<SavedSearch> it = savedSearches.iterator(); it.hasNext(); ) { SavedSearch savedSearch = it.next(); if (savedSearch.getID().equals(savedSearchId)) { it.remove(); } } hibernateTemplate.update(userProfile); }
/** {@inheritDoc} */ @Transactional(rollbackFor = {Throwable.class}) public List<SavedSearchView> getSavedSearches(Long userProfileId) { UserProfile userProfile = (UserProfile) DataAccessUtils.uniqueResult( hibernateTemplate.findByCriteria( DetachedCriteria.forClass(UserProfile.class) .add(Restrictions.eq("ID", userProfileId)) .setFetchMode("savedSearches", FetchMode.JOIN) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY))); List<SavedSearch> searches = userProfile.getSavedSearches(); List<SavedSearchView> searchViews = new ArrayList<SavedSearchView>(searches.size()); for (SavedSearch savedSearch : searches) { searchViews.add(new SavedSearchView(savedSearch)); } return searchViews; }
@Override @Transactional public UserProfile setSavedSearchAlerts( String userAuthId, List<String> monthlyAlerts, List<String> weeklyAlerts, List<String> deleteAlerts) { UserProfile user = getUserByAuthId(userAuthId); log.debug( "updating alerts for user: {}; Montly alerts: {}; weekly alerts: {}; delete alerts: {}", new Object[] { user.getDisplayName(), StringUtils.join(monthlyAlerts, ","), StringUtils.join(weeklyAlerts, ","), StringUtils.join(deleteAlerts, ",") }); List<SavedSearchView> searches = getSavedSearches(user.getID()); Set<String> weeklyItems = new HashSet<String>(weeklyAlerts); Set<String> monthlyItems = new HashSet<String>(monthlyAlerts); Set<String> deleteItems = new HashSet<String>(deleteAlerts); for (SavedSearchView savedSearch : searches) { // This method should only change user defined search alerts, not journal alerts if (savedSearch.getSearchType() == SavedSearchType.USER_DEFINED) { String idstr = String.valueOf(savedSearch.getSavedSearchId()); boolean delete = deleteItems.contains(idstr); if (delete) { deleteSavedSearch(user.getID(), savedSearch.getSavedSearchId()); } else { boolean weekly = weeklyItems.contains(idstr); boolean monthly = monthlyItems.contains(idstr); if (weekly != savedSearch.getWeekly() || monthly != savedSearch.getMonthly()) { updateSavedSearch(savedSearch.getSavedSearchId(), weekly, monthly); } } } } return user; }
/** {@inheritDoc} */ @Transactional(rollbackFor = {Throwable.class}) public UserProfile setFilteredWeeklySearchAlert( Long userProfileId, String[] subjects, String journal) { SearchParameters searchParameters = new SearchParameters(); searchParameters.setQuery("*:*"); searchParameters.setFilterJournals(new String[] {journal}); searchParameters.setFilterSubjectsDisjunction(subjects); // We store the saved search here as JSON instead of serializing the object cuz JSON rocks SavedSearchQuery query = saveSearchQuery(searchParameters); UserProfile user = getUser(userProfileId); SavedSearch newSearch = null; // See if a record exists already, we only allow one weekly alert of type JOURNAL_ALERT per // journal // We key off of the title as it is not user facing for (SavedSearch savedSearch : user.getSavedSearches()) { if (savedSearch.getSearchType() == SavedSearchType.JOURNAL_ALERT && savedSearch.getWeekly() && savedSearch.getSearchName().equals(journal)) { newSearch = savedSearch; } } if (newSearch == null) { newSearch = new SavedSearch(journal, query); newSearch.setSearchType(SavedSearchType.JOURNAL_ALERT); newSearch.setWeekly(true); newSearch.setMonthly(false); user.getSavedSearches().add(newSearch); } else { newSearch.setSearchQuery(query); } hibernateTemplate.save(user); return user; }
/** {@inheritDoc} */ @Transactional(rollbackFor = {Throwable.class}) @SuppressWarnings("unchecked") public void saveSearch( Long userProfileId, SearchParameters searchParameters, String name, boolean weekly, boolean monthly) { UserProfile user = hibernateTemplate.get(UserProfile.class, userProfileId); SavedSearchQuery query = saveSearchQuery(searchParameters); SavedSearch savedSearch = new SavedSearch(name, query); savedSearch.setSearchType(SavedSearchType.USER_DEFINED); savedSearch.setWeekly(weekly); savedSearch.setMonthly(monthly); user.getSavedSearches().add(savedSearch); hibernateTemplate.save(user); }
/** {@inheritDoc} */ @Transactional(rollbackFor = {Throwable.class}) public UserProfile removedFilteredWeeklySearchAlert(Long userProfileId, String journal) { UserProfile user = getUser(userProfileId); SavedSearch oldSearch = null; // We key off of the title as it is not user facing for (SavedSearch savedSearch : user.getSavedSearches()) { if (savedSearch.getSearchType() == SavedSearchType.JOURNAL_ALERT && savedSearch.getWeekly() && savedSearch.getSearchName().equals(journal)) { oldSearch = savedSearch; } } if (oldSearch != null) { user.getSavedSearches().remove(oldSearch); } hibernateTemplate.save(user); return user; }
@Override @Transactional public Long createComment( UserProfile user, String articleDoi, String title, String body, String ciStatement) { if (articleDoi == null) { throw new IllegalArgumentException("Attempted to create comment with null article id"); } else if (user == null || user.getID() == null) { throw new IllegalArgumentException("Attempted to create comment without a creator"); } else if (body == null || body.isEmpty()) { throw new IllegalArgumentException("Attempted to create comment with no body"); } log.debug( "Creating comment on article: {}; title: {}; body: {}", new Object[] {articleDoi, title, body}); Long articleID; try { articleID = (Long) hibernateTemplate .findByCriteria( DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("doi", articleDoi)) .setProjection(Projections.id())) .get(0); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("Invalid doi: " + articleDoi); } // generate an annotation uri Annotation comment = new Annotation(user, AnnotationType.COMMENT, articleID); comment.setAnnotationUri(URIGenerator.generate(comment)); comment.setTitle(title); comment.setBody(body); comment.setCompetingInterestBody(ciStatement); Long id = (Long) hibernateTemplate.save(comment); return id; }
@Override public UserProfile getProfileForDisplay(UserProfile userProfile, boolean showPrivateFields) { UserProfile display = new UserProfile(); copyFields(userProfile, display); if (!showPrivateFields) { log.debug("Removing private fields for display on user: {}", userProfile.getDisplayName()); display.setOrganizationName(null); display.setOrganizationType(null); display.setPostalAddress(null); display.setPositionType(null); } // escape html in all string fields BeanWrapper wrapper = new BeanWrapperImpl(display); for (PropertyDescriptor property : wrapper.getPropertyDescriptors()) { if (String.class.isAssignableFrom(property.getPropertyType())) { String name = property.getName(); wrapper.setPropertyValue( name, TextUtils.escapeHtml((String) wrapper.getPropertyValue(name))); } } return display; }
/** * Some unit tests delete all users. This is a way to restore them. This logic is very similar to * logic in HibernateTestSessionFactory afterPropertiesSet function */ protected void restoreDefaultUsers() { try { // Create an admin user to test admin functions UserRole adminRole = new UserRole("admin"); Set<UserRole.Permission> perms = new HashSet<UserRole.Permission>(); perms.add(UserRole.Permission.ACCESS_ADMIN); perms.add(UserRole.Permission.INGEST_ARTICLE); perms.add(UserRole.Permission.MANAGE_FLAGS); perms.add(UserRole.Permission.MANAGE_ANNOTATIONS); perms.add(UserRole.Permission.MANAGE_USERS); perms.add(UserRole.Permission.MANAGE_ROLES); perms.add(UserRole.Permission.MANAGE_JOURNALS); perms.add(UserRole.Permission.MANAGE_SEARCH); perms.add(UserRole.Permission.MANAGE_CACHES); perms.add(UserRole.Permission.CROSS_PUB_ARTICLES); perms.add(UserRole.Permission.DELETE_ARTICLES); perms.add(UserRole.Permission.VIEW_UNPUBBED_ARTICLES); adminRole.setPermissions(perms); dummyDataStore.store(adminRole); UserProfile admin = new UserProfile(); admin.setAuthId(BaseTest.DEFAULT_ADMIN_AUTHID); admin.setEmail("*****@*****.**"); admin.setDisplayName("testAdmin"); admin.setPassword("adminPass"); admin.setRoles(new HashSet<UserRole>(1)); admin.getRoles().add(adminRole); dummyDataStore.store(admin); UserRole editorialRole = new UserRole("editorial"); perms = new HashSet<UserRole.Permission>(); perms.add(UserRole.Permission.ACCESS_ADMIN); perms.add(UserRole.Permission.VIEW_UNPUBBED_ARTICLES); editorialRole.setPermissions(perms); dummyDataStore.store(editorialRole); UserProfile editorial = new UserProfile(); editorial.setAuthId(BaseTest.DEFAULT_EDITORIAL_AUTHID); editorial.setEmail("*****@*****.**"); editorial.setDisplayName("editorialAdmin"); editorial.setPassword("pass"); editorial.setRoles(new HashSet<UserRole>(1)); editorial.getRoles().add(editorialRole); dummyDataStore.store(editorial); UserProfile nonAdmin = new UserProfile(); nonAdmin.setAuthId(BaseTest.DEFAULT_USER_AUTHID); nonAdmin.setEmail("*****@*****.**"); nonAdmin.setDisplayName("testNonAdmin"); nonAdmin.setPassword("nonAdminPass"); dummyDataStore.store(nonAdmin); } catch (DataAccessException ex) { // must've already inserted the users } }
/** * Copy fields for updating or display. Does <b>not</b> copy some fields: * * <ul> * <li>ID: never overwrite IDs on hibernate objects * <li>userAccountUri: these don't come down from display layer, so we don't want to overwrite * with null * <li>userProfileUri: these don't come down from display layer, so we don't want to overwrite * with null * <li>roles: don't want to overwrite a user's roles when updating their profile * </ul> * * @param source * @param destination */ private void copyFields(UserProfile source, UserProfile destination) { destination.setAuthId(source.getAuthId()); destination.setRealName(source.getRealName()); destination.setGivenNames(source.getGivenNames()); destination.setSurname(source.getSurname()); destination.setTitle(source.getTitle()); destination.setGender(source.getGender()); destination.setEmail(source.getEmail()); destination.setHomePage(source.getHomePage()); destination.setWeblog(source.getWeblog()); destination.setPublications(source.getPublications()); destination.setDisplayName(source.getDisplayName()); destination.setSuffix(source.getSuffix()); destination.setPositionType(source.getPositionType()); destination.setOrganizationName(source.getOrganizationName()); destination.setOrganizationType(source.getOrganizationType()); destination.setPostalAddress(source.getPostalAddress()); destination.setCity(source.getCity()); destination.setCountry(source.getCountry()); destination.setBiography(source.getBiography()); destination.setInterests(source.getInterests()); destination.setResearchAreas(source.getResearchAreas()); destination.setOrganizationVisibility(source.getOrganizationVisibility()); destination.setAlertsJournals(source.getAlertsJournals()); }