diff --git a/dspace-api/src/main/java/org/dspace/content/factory/ContentServiceFactory.java b/dspace-api/src/main/java/org/dspace/content/factory/ContentServiceFactory.java index 4010e14861..2335af007f 100644 --- a/dspace-api/src/main/java/org/dspace/content/factory/ContentServiceFactory.java +++ b/dspace-api/src/main/java/org/dspace/content/factory/ContentServiceFactory.java @@ -33,6 +33,7 @@ import org.dspace.content.service.RelationshipTypeService; import org.dspace.content.service.SiteService; import org.dspace.content.service.SupervisedItemService; import org.dspace.content.service.WorkspaceItemService; +import org.dspace.eperson.service.SubscribeService; import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.workflow.factory.WorkflowServiceFactory; @@ -75,6 +76,8 @@ public abstract class ContentServiceFactory { public abstract SiteService getSiteService(); + public abstract SubscribeService getSubscribeService(); + /** * Return the implementation of the RelationshipTypeService interface * diff --git a/dspace-api/src/main/java/org/dspace/content/factory/ContentServiceFactoryImpl.java b/dspace-api/src/main/java/org/dspace/content/factory/ContentServiceFactoryImpl.java index 6f123ae1ba..05eabcccdc 100644 --- a/dspace-api/src/main/java/org/dspace/content/factory/ContentServiceFactoryImpl.java +++ b/dspace-api/src/main/java/org/dspace/content/factory/ContentServiceFactoryImpl.java @@ -30,6 +30,7 @@ import org.dspace.content.service.RelationshipTypeService; import org.dspace.content.service.SiteService; import org.dspace.content.service.SupervisedItemService; import org.dspace.content.service.WorkspaceItemService; +import org.dspace.eperson.service.SubscribeService; import org.springframework.beans.factory.annotation.Autowired; /** @@ -71,7 +72,8 @@ public class ContentServiceFactoryImpl extends ContentServiceFactory { private SupervisedItemService supervisedItemService; @Autowired(required = true) private SiteService siteService; - + @Autowired(required = true) + private SubscribeService subscribeService; @Autowired(required = true) private RelationshipService relationshipService; @Autowired(required = true) @@ -158,6 +160,11 @@ public class ContentServiceFactoryImpl extends ContentServiceFactory { return siteService; } + @Override + public SubscribeService getSubscribeService() { + return subscribeService ; + } + @Override public RelationshipTypeService getRelationshipTypeService() { return relationshipTypeService; diff --git a/dspace-api/src/main/java/org/dspace/eperson/FrequencySubscriptionParameter.java b/dspace-api/src/main/java/org/dspace/eperson/FrequencySubscriptionParameter.java deleted file mode 100644 index e735c96948..0000000000 --- a/dspace-api/src/main/java/org/dspace/eperson/FrequencySubscriptionParameter.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.dspace.eperson; - -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -/** - * @author Alba Aliu (alba.aliu at alba.aliu@atis.al) - * - */ -@Entity -@DiscriminatorValue("FREQUENCY") -public class FrequencySubscriptionParameter extends SubscriptionParameter { -} diff --git a/dspace-api/src/main/java/org/dspace/eperson/SubscribeParameterServiceImpl.java b/dspace-api/src/main/java/org/dspace/eperson/SubscribeParameterServiceImpl.java index 88842ebfa9..870a95b7f7 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/SubscribeParameterServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/eperson/SubscribeParameterServiceImpl.java @@ -10,32 +10,23 @@ package org.dspace.eperson; import java.sql.SQLException; import java.util.List; -import org.apache.logging.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.eperson.dao.SubscriptionParameterDAO; import org.dspace.eperson.service.SubscriptionParameterService; import org.springframework.beans.factory.annotation.Autowired; - /** * Class implemennting method for service layer of SubscriptionParameter entity * * @author Alba Aliu at atis.al */ public class SubscribeParameterServiceImpl implements SubscriptionParameterService { - /** - * log4j logger - */ - private Logger log = org.apache.logging.log4j.LogManager.getLogger(SubscribeParameterServiceImpl.class); @Autowired(required = true) protected SubscriptionParameterDAO subscriptionParameterDAO; - - protected SubscribeParameterServiceImpl() { - - } + protected SubscribeParameterServiceImpl() {} @Override public List findAll(Context context) throws SQLException { @@ -82,4 +73,5 @@ public class SubscribeParameterServiceImpl implements SubscriptionParameterServi } } + } diff --git a/dspace-api/src/main/java/org/dspace/eperson/SubscribeServiceImpl.java b/dspace-api/src/main/java/org/dspace/eperson/SubscribeServiceImpl.java index 295944df00..817085cdda 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/SubscribeServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/eperson/SubscribeServiceImpl.java @@ -9,7 +9,9 @@ package org.dspace.eperson; import java.sql.SQLException; import java.util.List; +import java.util.Objects; +import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.service.AuthorizeService; @@ -30,27 +32,21 @@ import org.springframework.beans.factory.annotation.Autowired; * @version $Revision$ */ public class SubscribeServiceImpl implements SubscribeService { - /** - * log4j logger - */ - private Logger log = org.apache.logging.log4j.LogManager.getLogger(SubscribeServiceImpl.class); + + private Logger log = LogManager.getLogger(SubscribeServiceImpl.class); @Autowired(required = true) - protected SubscriptionDAO subscriptionDAO; + private SubscriptionDAO subscriptionDAO; @Autowired(required = true) - protected AuthorizeService authorizeService; + private AuthorizeService authorizeService; @Autowired(required = true) - protected CollectionService collectionService; - - protected SubscribeServiceImpl() { - - } + private CollectionService collectionService; @Override public List findAll(Context context, String resourceType, Integer limit, Integer offset) throws Exception { if (resourceType == null) { - return subscriptionDAO.findAllOrderedById(context, limit, offset); + return subscriptionDAO.findAllOrderedByDSO(context, limit, offset); } else { if (resourceType.equals("Item") || resourceType.equals("Collection") || resourceType.equals("Community")) { return subscriptionDAO.findAllOrderedByIDAndResourceType(context, resourceType, limit, offset); @@ -78,14 +74,13 @@ public class SubscribeServiceImpl implements SubscribeService { newSubscription.setType(type); return newSubscription; } else { - throw new AuthorizeException( - "Only admin or e-person themselves can subscribe"); + throw new AuthorizeException("Only admin or e-person themselves can subscribe"); } } @Override - public void unsubscribe(Context context, EPerson eperson, - DSpaceObject dSpaceObject) throws SQLException, AuthorizeException { + public void unsubscribe(Context context, EPerson eperson, DSpaceObject dSpaceObject) + throws SQLException, AuthorizeException { // Check authorisation. Must be administrator, or the eperson. if (authorizeService.isAdmin(context) || ((context.getCurrentUser() != null) && (context @@ -96,13 +91,12 @@ public class SubscribeServiceImpl implements SubscribeService { } else { subscriptionDAO.deleteByDSOAndEPerson(context, dSpaceObject, eperson); - log.info(LogManager.getHeader(context, "unsubscribe", - "eperson_id=" + eperson.getID() + ",collection_id=" - + dSpaceObject.getID())); + log.info(LogHelper.getHeader(context, "unsubscribe", + "eperson_id=" + eperson.getID() + ",collection_id=" + + dSpaceObject.getID())); } } else { - throw new AuthorizeException( - "Only admin or e-person themselves can unsubscribe"); + throw new AuthorizeException("Only admin or e-person themselves can unsubscribe"); } } @@ -113,33 +107,26 @@ public class SubscribeServiceImpl implements SubscribeService { } @Override - public List getSubscriptionsByEPersonAndDso(Context context, - EPerson eperson, DSpaceObject dSpaceObject, - Integer limit, Integer offset) - throws SQLException { + public List getSubscriptionsByEPersonAndDso(Context context,EPerson eperson,DSpaceObject dSpaceObject, + Integer limit, Integer offset) throws SQLException { return subscriptionDAO.findByEPersonAndDso(context, eperson, dSpaceObject, limit, offset); } @Override - public List getAvailableSubscriptions(Context context) - throws SQLException { + public List getAvailableSubscriptions(Context context) throws SQLException { return getAvailableSubscriptions(context, null); } @Override - public List getAvailableSubscriptions(Context context, EPerson eperson) - throws SQLException { - List collections; - if (eperson != null) { + public List getAvailableSubscriptions(Context context, EPerson eperson) throws SQLException { + if (Objects.nonNull(eperson)) { context.setCurrentUser(eperson); } - collections = collectionService.findAuthorized(context, null, Constants.ADD); - return collections; + return collectionService.findAuthorized(context, null, Constants.ADD); } @Override - public boolean isSubscribed(Context context, EPerson eperson, - DSpaceObject dSpaceObject) throws SQLException { + public boolean isSubscribed(Context context, EPerson eperson, DSpaceObject dSpaceObject) throws SQLException { return subscriptionDAO.findByEPersonAndDso(context, eperson, dSpaceObject, -1, -1) != null; } @@ -158,7 +145,7 @@ public class SubscribeServiceImpl implements SubscribeService { Subscription subscription = subscriptionDAO.findByID(context, Subscription.class, id); if (context.getCurrentUser().equals(subscription.getePerson()) || authorizeService.isAdmin(context, context.getCurrentUser())) { - return subscription; + return subscription; } throw new AuthorizeException("Only admin or e-person themselves can edit the subscription"); } @@ -187,7 +174,7 @@ public class SubscribeServiceImpl implements SubscribeService { @Override public Subscription addSubscriptionParameter(Context context, Integer id, - SubscriptionParameter subscriptionParameter) throws SQLException, AuthorizeException { + SubscriptionParameter subscriptionParameter) throws SQLException, AuthorizeException { // must be admin or the subscriber of the subscription Subscription subscriptionDB = subscriptionDAO.findByID(context, Subscription.class, id); if (authorizeService.isAdmin(context, context.getCurrentUser()) @@ -202,7 +189,7 @@ public class SubscribeServiceImpl implements SubscribeService { @Override public Subscription removeSubscriptionParameter(Context context, Integer id, - SubscriptionParameter subscriptionParameter) throws SQLException, AuthorizeException { + SubscriptionParameter subscriptionParameter) throws SQLException, AuthorizeException { // must be admin or the subscriber of the subscription Subscription subscriptionDB = subscriptionDAO.findByID(context, Subscription.class, id); if (authorizeService.isAdmin(context, context.getCurrentUser()) @@ -228,13 +215,34 @@ public class SubscribeServiceImpl implements SubscribeService { } catch (SQLException sqlException) { throw new SQLException(sqlException); } - } else { throw new AuthorizeException("Only admin or e-person themselves can delete the subscription"); } } else { - throw new IllegalArgumentException("Subscription with id" + id + "is not found"); + throw new IllegalArgumentException("Subscription with id " + id + " is not found"); } - } + + @Override + public List findAllSubscriptionsByTypeAndFrequency(Context context, + String type, String frequencyValue) throws SQLException { + return subscriptionDAO.findAllSubscriptionsByTypeAndFrequency(context, type, frequencyValue); + } + + @Override + public Long countAll(Context context) throws SQLException { + return subscriptionDAO.countAll(context); + } + + @Override + public Long countAllByEPerson(Context context, EPerson ePerson) throws SQLException { + return subscriptionDAO.countAllByEPerson(context, ePerson); + } + + @Override + public Long countAllByEPersonAndDSO(Context context, EPerson ePerson, DSpaceObject dSpaceObject) + throws SQLException { + return subscriptionDAO.countAllByEPersonAndDso(context, ePerson, dSpaceObject); + } + } diff --git a/dspace-api/src/main/java/org/dspace/eperson/Subscription.java b/dspace-api/src/main/java/org/dspace/eperson/Subscription.java index 48dd24cdd4..1f5ead4387 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/Subscription.java +++ b/dspace-api/src/main/java/org/dspace/eperson/Subscription.java @@ -26,8 +26,6 @@ import org.dspace.content.DSpaceObject; import org.dspace.core.Context; import org.dspace.core.ReloadableEntity; - - /** * Database entity representation of the subscription table * @@ -61,9 +59,7 @@ public class Subscription implements ReloadableEntity { * Protected constructor, create object using: * {@link org.dspace.eperson.service.SubscribeService#subscribe(Context, EPerson, DSpaceObject, List, String)} */ - protected Subscription() { - - } + protected Subscription() {} @Override public Integer getID() { diff --git a/dspace-api/src/main/java/org/dspace/eperson/SubscriptionParameter.java b/dspace-api/src/main/java/org/dspace/eperson/SubscriptionParameter.java index 0b69b36515..002b517032 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/SubscriptionParameter.java +++ b/dspace-api/src/main/java/org/dspace/eperson/SubscriptionParameter.java @@ -7,7 +7,6 @@ */ package org.dspace.eperson; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -23,25 +22,35 @@ import javax.persistence.Table; * * @author Alba Aliu at atis.al */ - @Entity @Table(name = "subscription_parameter") -@DiscriminatorColumn(name = "name") public class SubscriptionParameter { + @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "subscription_parameter_seq") - @SequenceGenerator(name = "subscription_parameter_seq", - sequenceName = "subscription_parameter_seq", allocationSize = 1) + @SequenceGenerator(name = "subscription_parameter_seq", sequenceName = "subscription_parameter_seq", + allocationSize = 1) @Column(name = "subscription_parameter_id", unique = true) private Integer id; + @ManyToOne - @JoinColumn(name = "subscription_id") + @JoinColumn(name = "subscription_id", nullable = false) private Subscription subscription; + @Column private String name; + @Column private String value; + public SubscriptionParameter() {} + + public SubscriptionParameter(Integer id, Subscription subscription, String name, String value) { + this.id = id; + this.subscription = subscription; + this.name = name; + this.value = value; + } public Subscription getSubscription() { return subscription; @@ -67,4 +76,12 @@ public class SubscriptionParameter { this.value = value; } + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + } diff --git a/dspace-api/src/main/java/org/dspace/eperson/dao/SubscriptionDAO.java b/dspace-api/src/main/java/org/dspace/eperson/dao/SubscriptionDAO.java index 4f4ed16a2e..011486622b 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/dao/SubscriptionDAO.java +++ b/dspace-api/src/main/java/org/dspace/eperson/dao/SubscriptionDAO.java @@ -28,11 +28,10 @@ public interface SubscriptionDAO extends GenericDAO { public void deleteByDspaceObject(Context context, DSpaceObject dSpaceObject) throws SQLException; - public List findByEPerson(Context context, - EPerson eperson, Integer limit, Integer offset) throws SQLException; + public List findByEPerson(Context context, EPerson eperson, Integer limit, Integer offset) + throws SQLException; - public List findByEPersonAndDso(Context context, - EPerson eperson, DSpaceObject dSpaceObject, + public List findByEPersonAndDso(Context context,EPerson eperson, DSpaceObject dSpaceObject, Integer limit, Integer offset) throws SQLException; public void deleteByEPerson(Context context, EPerson eperson) throws SQLException; @@ -41,7 +40,17 @@ public interface SubscriptionDAO extends GenericDAO { throws SQLException; public List findAllOrderedByIDAndResourceType(Context context, String resourceType, - Integer limit, Integer offset) throws SQLException; + Integer limit, Integer offset) throws SQLException; + + public List findAllOrderedByDSO(Context context, Integer limit, Integer offset) throws SQLException; + + public List findAllSubscriptionsByTypeAndFrequency(Context context, String type,String frequencyValue) + throws SQLException; + + public Long countAll(Context context) throws SQLException; + + public Long countAllByEPerson(Context context, EPerson ePerson) throws SQLException; + + public Long countAllByEPersonAndDso(Context context, EPerson ePerson,DSpaceObject dSpaceObject) throws SQLException; - public List findAllOrderedById(Context context, Integer limit, Integer offset) throws SQLException; } diff --git a/dspace-api/src/main/java/org/dspace/eperson/dao/impl/SubscriptionDAOImpl.java b/dspace-api/src/main/java/org/dspace/eperson/dao/impl/SubscriptionDAOImpl.java index 043fd70b57..71518c1fcf 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/dao/impl/SubscriptionDAOImpl.java +++ b/dspace-api/src/main/java/org/dspace/eperson/dao/impl/SubscriptionDAOImpl.java @@ -9,10 +9,12 @@ package org.dspace.eperson.dao.impl; import java.sql.SQLException; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import javax.persistence.Query; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Join; import javax.persistence.criteria.Root; import org.dspace.content.DSpaceObject; @@ -20,6 +22,8 @@ import org.dspace.core.AbstractHibernateDAO; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Subscription; +import org.dspace.eperson.SubscriptionParameter; +import org.dspace.eperson.SubscriptionParameter_; import org.dspace.eperson.Subscription_; import org.dspace.eperson.dao.SubscriptionDAO; @@ -31,6 +35,7 @@ import org.dspace.eperson.dao.SubscriptionDAO; * @author kevinvandevelde at atmire.com */ public class SubscriptionDAOImpl extends AbstractHibernateDAO implements SubscriptionDAO { + protected SubscriptionDAOImpl() { super(); } @@ -44,10 +49,9 @@ public class SubscriptionDAOImpl extends AbstractHibernateDAO impl criteriaQuery.select(subscriptionRoot); criteriaQuery.where(criteriaBuilder.equal(subscriptionRoot.get(Subscription_.ePerson), eperson)); List orderList = new LinkedList<>(); - orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.id))); + orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.dSpaceObject))); criteriaQuery.orderBy(orderList); return list(context, criteriaQuery, false, Subscription.class, limit, offset); - } @Override @@ -59,14 +63,12 @@ public class SubscriptionDAOImpl extends AbstractHibernateDAO impl getCriteriaQuery(criteriaBuilder, Subscription.class); Root subscriptionRoot = criteriaQuery.from(Subscription.class); criteriaQuery.select(subscriptionRoot); - criteriaQuery.where(criteriaBuilder.equal(subscriptionRoot.get(Subscription_.ePerson), eperson)); - criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal( - subscriptionRoot.get(Subscription_.ePerson), eperson), + subscriptionRoot.get(Subscription_.ePerson), eperson), criteriaBuilder.equal(subscriptionRoot.get(Subscription_.dSpaceObject), dSpaceObject) )); List orderList = new LinkedList<>(); - orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.id))); + orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.dSpaceObject))); criteriaQuery.orderBy(orderList); return list(context, criteriaQuery, false, Subscription.class, limit, offset); } @@ -100,7 +102,7 @@ public class SubscriptionDAOImpl extends AbstractHibernateDAO impl @Override public List findAllOrderedByIDAndResourceType(Context context, String resourceType, - Integer limit, Integer offset) throws SQLException { + Integer limit, Integer offset) throws SQLException { String hqlQuery = "select s from Subscription s join %s dso " + "ON dso.id = s.dSpaceObject ORDER BY subscription_id"; if (resourceType != null) { @@ -116,15 +118,69 @@ public class SubscriptionDAOImpl extends AbstractHibernateDAO impl query.setHint("org.hibernate.cacheable", false); return query.getResultList(); } + @Override - public List findAllOrderedById(Context context, Integer limit, Integer offset) throws SQLException { + public List findAllOrderedByDSO(Context context, Integer limit, Integer offset) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, Subscription.class); Root subscriptionRoot = criteriaQuery.from(Subscription.class); criteriaQuery.select(subscriptionRoot); List orderList = new LinkedList<>(); - orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.id))); + orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.dSpaceObject))); criteriaQuery.orderBy(orderList); return list(context, criteriaQuery, false, Subscription.class, limit, offset); } + + @Override + public List findAllSubscriptionsByTypeAndFrequency(Context context, + String type, String frequencyValue) throws SQLException { + CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); + CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, Subscription.class); + Root subscriptionRoot = criteriaQuery.from(Subscription.class); + criteriaQuery.select(subscriptionRoot); + Join childJoin = subscriptionRoot.join("subscriptionParameterList"); + criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(subscriptionRoot.get(Subscription_.TYPE), type), + criteriaBuilder.equal(childJoin.get(SubscriptionParameter_.name), "frequency"), + criteriaBuilder.equal(childJoin.get(SubscriptionParameter_.value), frequencyValue) + )); + List orderList = new ArrayList<>(1); + orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.ePerson))); + orderList.add(criteriaBuilder.asc(subscriptionRoot.get(Subscription_.id))); + criteriaQuery.orderBy(orderList); + return list(context, criteriaQuery, false, Subscription.class, 10000, -1); + } + + @Override + public Long countAll(Context context) throws SQLException { + CriteriaBuilder qb = getCriteriaBuilder(context); + CriteriaQuery cq = qb.createQuery(Long.class); + cq.select(qb.count(cq.from(Subscription.class))); + Query query = this.getHibernateSession(context).createQuery(cq); + return (Long) query.getSingleResult(); + } + + @Override + public Long countAllByEPerson(Context context, EPerson ePerson) throws SQLException { + CriteriaBuilder qb = getCriteriaBuilder(context); + CriteriaQuery cq = qb.createQuery(Long.class); + Root subscriptionRoot = cq.from(Subscription.class); + cq.select(qb.count(subscriptionRoot)); + cq.where(qb.equal(subscriptionRoot.get(Subscription_.ePerson), ePerson)); + Query query = this.getHibernateSession(context).createQuery(cq); + return (Long) query.getSingleResult(); + } + + @Override + public Long countAllByEPersonAndDso(Context context, + EPerson ePerson, DSpaceObject dSpaceObject) throws SQLException { + CriteriaBuilder qb = getCriteriaBuilder(context); + CriteriaQuery cq = qb.createQuery(Long.class); + Root subscriptionRoot = cq.from(Subscription.class); + cq.select(qb.count(subscriptionRoot)); + cq.where(qb.and(qb.equal(subscriptionRoot.get(Subscription_.ePerson) + , ePerson), qb.equal(subscriptionRoot.get(Subscription_.dSpaceObject), dSpaceObject))); + Query query = this.getHibernateSession(context).createQuery(cq); + return (Long) query.getSingleResult(); + } + } \ No newline at end of file diff --git a/dspace-api/src/main/java/org/dspace/eperson/dao/impl/SubscriptionParameterDAOImpl.java b/dspace-api/src/main/java/org/dspace/eperson/dao/impl/SubscriptionParameterDAOImpl.java index eee80a73a5..37af787ed3 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/dao/impl/SubscriptionParameterDAOImpl.java +++ b/dspace-api/src/main/java/org/dspace/eperson/dao/impl/SubscriptionParameterDAOImpl.java @@ -18,9 +18,11 @@ import org.dspace.eperson.dao.SubscriptionParameterDAO; * * @author Alba Aliu at atis.al */ -public class SubscriptionParameterDAOImpl extends AbstractHibernateDAO - implements SubscriptionParameterDAO { +public class SubscriptionParameterDAOImpl extends AbstractHibernateDAO + implements SubscriptionParameterDAO { + protected SubscriptionParameterDAOImpl() { super(); } + } \ No newline at end of file diff --git a/dspace-api/src/main/java/org/dspace/eperson/service/SubscribeService.java b/dspace-api/src/main/java/org/dspace/eperson/service/SubscribeService.java index 607118ce56..d06c23f1f0 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/service/SubscribeService.java +++ b/dspace-api/src/main/java/org/dspace/eperson/service/SubscribeService.java @@ -33,13 +33,13 @@ public interface SubscribeService { * new item appears in the collection. * * @param context DSpace context - * @param limit Number of subscriptions to return - * @param offset Offset number + * @param limit Number of subscriptions to return + * @param offset Offset number * @return list of Subscription objects * @throws SQLException An exception that provides information on a database access error or other errors. */ - public List findAll(Context context, String resourceType, - Integer limit, Integer offset) throws Exception; + public List findAll(Context context, String resourceType, Integer limit, Integer offset) + throws Exception; /** * Subscribe an e-person to a collection. An e-mail will be sent every day a @@ -67,21 +67,21 @@ public interface SubscribeService { * @throws AuthorizeException Exception indicating the current user of the context does not have permission * to perform a particular action. */ - public void unsubscribe(Context context, EPerson eperson, - DSpaceObject dSpaceObject) throws SQLException, AuthorizeException; + public void unsubscribe(Context context, EPerson eperson, DSpaceObject dSpaceObject) + throws SQLException, AuthorizeException; /** * Find out which collections an e-person is subscribed to * * @param context DSpace context * @param eperson EPerson - * @param limit Number of subscriptions to return - * @param offset Offset number + * @param limit Number of subscriptions to return + * @param offset Offset number * @return array of collections e-person is subscribed to * @throws SQLException An exception that provides information on a database access error or other errors. */ - public List getSubscriptionsByEPerson(Context context, EPerson eperson, - Integer limit, Integer offset) throws SQLException; + public List getSubscriptionsByEPerson(Context context, EPerson eperson, Integer limit, Integer offset) + throws SQLException; /** * Find out which collections an e-person is subscribed to and related with dso @@ -89,8 +89,8 @@ public interface SubscribeService { * @param context DSpace context * @param eperson EPerson * @param dSpaceObject DSpaceObject - * @param limit Number of subscriptions to return - * @param offset Offset number + * @param limit Number of subscriptions to return + * @param offset Offset number * @return array of collections e-person is subscribed to and related with dso * @throws SQLException An exception that provides information on a database access error or other errors. */ @@ -107,8 +107,7 @@ public interface SubscribeService { * @return array of collections the currently logged in e-person can subscribe to * @throws SQLException An exception that provides information on a database access error or other errors. */ - public List getAvailableSubscriptions(Context context) - throws SQLException; + public List getAvailableSubscriptions(Context context) throws SQLException; /** * Find out which collections an e-person can subscribe to @@ -118,8 +117,7 @@ public interface SubscribeService { * @return array of collections e-person can subscribe to * @throws SQLException An exception that provides information on a database access error or other errors. */ - public List getAvailableSubscriptions(Context context, EPerson eperson) - throws SQLException; + public List getAvailableSubscriptions(Context context, EPerson eperson) throws SQLException; /** * Is that e-person subscribed to that collection? @@ -130,8 +128,7 @@ public interface SubscribeService { * @return true if they are subscribed * @throws SQLException An exception that provides information on a database access error or other errors. */ - public boolean isSubscribed(Context context, EPerson eperson, - DSpaceObject dSpaceObject) throws SQLException; + public boolean isSubscribed(Context context, EPerson eperson, DSpaceObject dSpaceObject) throws SQLException; /** * Delete subscription by collection. @@ -155,7 +152,7 @@ public interface SubscribeService { * Finds a subscription by id * * @param context DSpace context - * @param id the id of subscription to be searched + * @param id the id of subscription to be searched * @throws SQLException An exception that provides information on a database access error or other errors. */ public Subscription findById(Context context, int id) throws SQLException, AuthorizeException; @@ -184,8 +181,7 @@ public interface SubscribeService { * @param subscriptionParameter SubscriptionParameter subscriptionParameter * @throws SQLException An exception that provides information on a database access error or other errors. */ - public Subscription addSubscriptionParameter(Context context, Integer id, - SubscriptionParameter subscriptionParameter) + public Subscription addSubscriptionParameter(Context context,Integer id,SubscriptionParameter subscriptionParameter) throws SQLException, AuthorizeException; /** @@ -197,13 +193,51 @@ public interface SubscribeService { * @throws SQLException An exception that provides information on a database access error or other errors. */ public Subscription removeSubscriptionParameter(Context context, Integer id, - SubscriptionParameter subscriptionParameter) throws SQLException, AuthorizeException; + SubscriptionParameter subscriptionParameter) throws SQLException, AuthorizeException; /** * Deletes a subscription * * @param context DSpace context + * @param id Integer id of subscription * @throws SQLException An exception that provides information on a database access error or other errors. */ public void deleteSubscription(Context context, Integer id) throws SQLException, AuthorizeException; -} + + /** + * Finds all subscriptions having given type and frequency + * + * @param context DSpace context + * @param type String type of subscription + * @param frequencyValue String frequency value of subscription + * @throws SQLException An exception that provides information on a database access error or other errors. + */ + public List findAllSubscriptionsByTypeAndFrequency(Context context, String type,String frequencyValue) + throws SQLException; + + /** + * Counts all subscriptions + * + * @param context DSpace context + */ + public Long countAll(Context context) throws SQLException, AuthorizeException; + + /** + * Counts all subscriptions by ePerson + * + * @param context DSpace context + * @param ePerson EPerson ePerson + */ + public Long countAllByEPerson(Context context, EPerson ePerson) throws SQLException, AuthorizeException; + + /** + * Counts all subscriptions by ePerson and DSO + * + * @param context DSpace context + * @param ePerson EPerson ePerson + * @param dSpaceObject DSpaceObject dSpaceObject + */ + public Long countAllByEPersonAndDSO(Context context, EPerson ePerson, DSpaceObject dSpaceObject) + throws SQLException, AuthorizeException; + +} \ No newline at end of file diff --git a/dspace-api/src/main/resources/org/dspace/storage/rdbms/sqlmigration/h2/V7.0_2021.07.30__add_table_subscriptionparamter_change_columns_subscription_table.sql b/dspace-api/src/main/resources/org/dspace/storage/rdbms/sqlmigration/h2/V7.0_2021.07.30__add_table_subscriptionparamter_change_columns_subscription_table.sql index e94ec3c504..ab20e35257 100644 --- a/dspace-api/src/main/resources/org/dspace/storage/rdbms/sqlmigration/h2/V7.0_2021.07.30__add_table_subscriptionparamter_change_columns_subscription_table.sql +++ b/dspace-api/src/main/resources/org/dspace/storage/rdbms/sqlmigration/h2/V7.0_2021.07.30__add_table_subscriptionparamter_change_columns_subscription_table.sql @@ -20,7 +20,7 @@ CREATE TABLE subscription_parameter ( subscription_parameter_id INTEGER NOT NULL, name CHARACTER VARYING(255), - value CHARACTER VARYING(255), + `value` CHARACTER VARYING(255), subscription_id INTEGER NOT NULL, CONSTRAINT subscription_parameter_pkey PRIMARY KEY (subscription_parameter_id), CONSTRAINT subscription_parameter_subscription_fkey FOREIGN KEY (subscription_id) REFERENCES subscription (subscription_id) ON DELETE CASCADE diff --git a/dspace-api/src/test/java/org/dspace/builder/AbstractBuilder.java b/dspace-api/src/test/java/org/dspace/builder/AbstractBuilder.java index 3306ced8f4..13122fe4a7 100644 --- a/dspace-api/src/test/java/org/dspace/builder/AbstractBuilder.java +++ b/dspace-api/src/test/java/org/dspace/builder/AbstractBuilder.java @@ -42,6 +42,7 @@ import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.GroupService; import org.dspace.eperson.service.RegistrationDataService; +import org.dspace.eperson.service.SubscribeService; import org.dspace.orcid.factory.OrcidServiceFactory; import org.dspace.orcid.service.OrcidHistoryService; import org.dspace.orcid.service.OrcidQueueService; @@ -102,6 +103,7 @@ public abstract class AbstractBuilder { static OrcidHistoryService orcidHistoryService; static OrcidQueueService orcidQueueService; static OrcidTokenService orcidTokenService; + static SubscribeService subscribeService; protected Context context; @@ -161,6 +163,7 @@ public abstract class AbstractBuilder { orcidHistoryService = OrcidServiceFactory.getInstance().getOrcidHistoryService(); orcidQueueService = OrcidServiceFactory.getInstance().getOrcidQueueService(); orcidTokenService = OrcidServiceFactory.getInstance().getOrcidTokenService(); + subscribeService = ContentServiceFactory.getInstance().getSubscribeService(); } @@ -194,7 +197,7 @@ public abstract class AbstractBuilder { requestItemService = null; versioningService = null; orcidTokenService = null; - + subscribeService = null; } public static void cleanupObjects() throws Exception { diff --git a/dspace-api/src/test/java/org/dspace/builder/SubscribeBuilder.java b/dspace-api/src/test/java/org/dspace/builder/SubscribeBuilder.java index 1d714b8567..9c1c778d56 100644 --- a/dspace-api/src/test/java/org/dspace/builder/SubscribeBuilder.java +++ b/dspace-api/src/test/java/org/dspace/builder/SubscribeBuilder.java @@ -7,6 +7,9 @@ */ package org.dspace.builder; +import java.sql.SQLException; +import java.util.List; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.dspace.authorize.AuthorizeException; @@ -18,9 +21,6 @@ import org.dspace.eperson.Subscription; import org.dspace.eperson.SubscriptionParameter; import org.dspace.eperson.service.SubscribeService; -import java.sql.SQLException; -import java.util.List; - public class SubscribeBuilder extends AbstractBuilder { /* Log4j logger*/ @@ -80,16 +80,17 @@ public class SubscribeBuilder extends AbstractBuilder subscriptionParameterList) { + public static SubscribeBuilder subscribeBuilder(final Context context, String type, DSpaceObject dSpaceObject, + EPerson ePerson, List subscriptionParameterList) { SubscribeBuilder builder = new SubscribeBuilder(context); return builder.create(context, type, dSpaceObject, ePerson, subscriptionParameterList); } - private SubscribeBuilder create(Context context, String type, DSpaceObject dSpaceObject, EPerson ePerson, List subscriptionParameterList) { + private SubscribeBuilder create(Context context, String type, DSpaceObject dSpaceObject, EPerson ePerson, + List subscriptionParameterList) { try { this.context = context; @@ -101,4 +102,5 @@ public class SubscribeBuilder extends AbstractBuilder { + @Autowired protected Utils utils; - @Autowired - private ConverterService converter; @Override public SubscriptionRest convert(Subscription subscription, Projection projection) { SubscriptionRest rest = new SubscriptionRest(); + rest.setProjection(projection); rest.setId(subscription.getID()); - rest.setSubscriptionParameterList(subscription.getSubscriptionParameterList()); + List subscriptionParameterRestList = new ArrayList<>(); + for (SubscriptionParameter subscriptionParameter : subscription.getSubscriptionParameterList()) { + SubscriptionParameterRest subscriptionParameterRest = new SubscriptionParameterRest(); + subscriptionParameterRest.setName(subscriptionParameter.getName()); + subscriptionParameterRest.setValue(subscriptionParameter.getValue()); + subscriptionParameterRest.setId(subscriptionParameter.getId()); + subscriptionParameterRestList.add(subscriptionParameterRest); + } + rest.setSubscriptionParameterList(subscriptionParameterRestList); rest.setType(subscription.getType()); return rest; } diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/SubscriptionRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/SubscriptionRest.java index d158d3ba91..394805a728 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/SubscriptionRest.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/SubscriptionRest.java @@ -13,12 +13,15 @@ import java.util.List; import org.dspace.app.rest.RestResourceController; -@LinksRest(links = {@LinkRest(name = SubscriptionRest.DSPACE_OBJECT, +@LinksRest(links = { @LinkRest(name = SubscriptionRest.DSPACE_OBJECT, method = "getDSpaceObject"), @LinkRest( name = SubscriptionRest.EPERSON, method = "getEPerson") }) public class SubscriptionRest extends BaseObjectRest { + + private static final long serialVersionUID = 1L; + public static final String NAME = "subscription"; public static final String NAME_PLURAL = "subscriptions"; public static final String CATEGORY = "core"; @@ -27,7 +30,7 @@ public class SubscriptionRest extends BaseObjectRest { private Integer id; private String type; - private List subscriptionParameterList = new ArrayList<>(); + private List subscriptionParameterList = new ArrayList<>(); @Override public String getCategory() { @@ -35,7 +38,7 @@ public class SubscriptionRest extends BaseObjectRest { } @Override - public Class getController() { + public Class getController() { return RestResourceController.class; } @@ -48,11 +51,11 @@ public class SubscriptionRest extends BaseObjectRest { this.type = type; } - public List getSubscriptionParameterList() { + public List getSubscriptionParameterList() { return subscriptionParameterList; } - public void setSubscriptionParameterList(List subscriptionParameterList) { + public void setSubscriptionParameterList(List subscriptionParameterList) { this.subscriptionParameterList = subscriptionParameterList; } @@ -69,4 +72,5 @@ public class SubscriptionRest extends BaseObjectRest { public void setId(Integer id) { this.id = id; } + } diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionDSpaceObjectLinkRepository.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionDSpaceObjectLinkRepository.java index ffd2d606dd..77215cdd50 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionDSpaceObjectLinkRepository.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionDSpaceObjectLinkRepository.java @@ -8,6 +8,7 @@ package org.dspace.app.rest.repository; import java.sql.SQLException; +import java.util.Objects; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; @@ -15,7 +16,9 @@ import org.dspace.app.rest.model.DSpaceObjectRest; import org.dspace.app.rest.model.SubscriptionRest; import org.dspace.app.rest.projection.Projection; import org.dspace.authorize.AuthorizeException; -import org.dspace.core.Context; +import org.dspace.content.Collection; +import org.dspace.content.Community; +import org.dspace.content.Item; import org.dspace.eperson.Subscription; import org.dspace.eperson.service.SubscribeService; import org.hibernate.proxy.HibernateProxy; @@ -29,31 +32,33 @@ import org.springframework.stereotype.Component; * Link repository for "dataSpaceObject" of subscription */ @Component(SubscriptionRest.CATEGORY + "." + SubscriptionRest.NAME + "." + SubscriptionRest.DSPACE_OBJECT) -@Transactional public class SubscriptionDSpaceObjectLinkRepository extends AbstractDSpaceRestRepository implements LinkRestRepository { @Autowired - SubscribeService subscribeService; - + private SubscribeService subscribeService; public DSpaceObjectRest getDSpaceObject(@Nullable HttpServletRequest request, - Integer subscriptionId, @Nullable Pageable optionalPageable, - Projection projection) throws AuthorizeException { + Integer subscriptionId, Projection projection) throws AuthorizeException { try { - Context context = obtainContext(); - Subscription subscription = subscribeService.findById(context, subscriptionId); - if (subscription == null) { + Subscription subscription = subscribeService.findById(obtainContext(), subscriptionId); + if (Objects.isNull(subscription)) { throw new ResourceNotFoundException("No such subscription: " + subscriptionId); } - HibernateProxy hibernateProxy = (HibernateProxy) subscription.getdSpaceObject(); - LazyInitializer initializer = hibernateProxy.getHibernateLazyInitializer(); - - return converter.toRest(initializer.getImplementation(), projection); + if (subscription.getdSpaceObject() instanceof Item || + subscription.getdSpaceObject() instanceof Community || + subscription.getdSpaceObject() instanceof Collection) { + return converter.toRest(subscription.getdSpaceObject(), projection); + } else { + HibernateProxy hibernateProxy = (HibernateProxy) subscription.getdSpaceObject(); + LazyInitializer initializer = hibernateProxy.getHibernateLazyInitializer(); + return converter.toRest(initializer.getImplementation(), projection); + } } catch (SQLException e) { throw new RuntimeException(e); } catch (AuthorizeException e) { throw new AuthorizeException(e.getMessage()); } } -} + +} \ No newline at end of file diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionEPersonLinkRepository.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionEPersonLinkRepository.java index b1cbc57135..4a7181f0da 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionEPersonLinkRepository.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionEPersonLinkRepository.java @@ -8,6 +8,7 @@ package org.dspace.app.rest.repository; import java.sql.SQLException; +import java.util.Objects; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; @@ -15,7 +16,6 @@ import org.dspace.app.rest.model.EPersonRest; import org.dspace.app.rest.model.SubscriptionRest; import org.dspace.app.rest.projection.Projection; import org.dspace.authorize.AuthorizeException; -import org.dspace.core.Context; import org.dspace.eperson.Subscription; import org.dspace.eperson.service.SubscribeService; import org.springframework.beans.factory.annotation.Autowired; @@ -30,25 +30,22 @@ import org.springframework.stereotype.Component; public class SubscriptionEPersonLinkRepository extends AbstractDSpaceRestRepository implements LinkRestRepository { @Autowired - SubscribeService subscribeService; + private SubscribeService subscribeService; - public EPersonRest getEPerson(@Nullable HttpServletRequest request, - Integer subscriptionId, + public EPersonRest getEPerson(@Nullable HttpServletRequest request, Integer subscriptionId, @Nullable Pageable optionalPageable, Projection projection) throws AuthorizeException { try { - Context context = obtainContext(); - Subscription subscription = subscribeService.findById(context, subscriptionId); - if (subscription == null) { + Subscription subscription = subscribeService.findById(obtainContext(), subscriptionId); + if (Objects.isNull(subscription)) { throw new ResourceNotFoundException("No such subscription: " + subscriptionId); } - return converter.toRest(subscription.getePerson(), projection); } catch (SQLException e) { throw new RuntimeException(e); - } - catch (AuthorizeException e) { + } catch (AuthorizeException e) { throw new AuthorizeException(e.getMessage()); } } -} + +} \ No newline at end of file diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionRestRepository.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionRestRepository.java index 6c2e49c022..e40caff8cd 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionRestRepository.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubscriptionRestRepository.java @@ -7,22 +7,23 @@ */ package org.dspace.app.rest.repository; - import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.UUID; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.BadRequestException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.dspace.app.rest.SearchRestMethod; import org.dspace.app.rest.converter.ConverterService; +import org.dspace.app.rest.exception.DSpaceBadRequestException; import org.dspace.app.rest.exception.UnprocessableEntityException; +import org.dspace.app.rest.model.SubscriptionParameterRest; import org.dspace.app.rest.model.SubscriptionRest; import org.dspace.app.rest.model.patch.Patch; import org.dspace.app.rest.repository.patch.ResourcePatch; @@ -30,12 +31,13 @@ import org.dspace.app.rest.utils.DSpaceObjectUtils; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.service.AuthorizeService; import org.dspace.content.DSpaceObject; +import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.Subscription; +import org.dspace.eperson.SubscriptionParameter; import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.SubscribeService; -import org.dspace.eperson.service.SubscriptionParameterService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -43,41 +45,34 @@ import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.sql.SQLException; -import java.util.List; - /** * This is the repository responsible to manage SubscriptionRest object * * @author Alba Aliu at atis.al */ - @Component(SubscriptionRest.CATEGORY + "." + SubscriptionRest.NAME) -public class SubscriptionRestRepository extends DSpaceRestRepository - implements LinkRestRepository { - private static final Logger log = LogManager.getLogger(); +public class SubscriptionRestRepository extends DSpaceRestRepository + implements LinkRestRepository { + @Autowired - AuthorizeService authorizeService; + private ConverterService converter; @Autowired - SubscribeService subscribeService; + private EPersonService personService; @Autowired - protected ConverterService converter; + private AuthorizeService authorizeService; @Autowired - protected EPersonService personService; + private SubscribeService subscribeService; @Autowired private DSpaceObjectUtils dspaceObjectUtil; @Autowired private ResourcePatch resourcePatch; - @Override @PreAuthorize("isAuthenticated()") public SubscriptionRest findOne(Context context, Integer id) { try { Subscription subscription = subscribeService.findById(context, id); - if (subscription == null) { + if (Objects.isNull(subscription)) { throw new ResourceNotFoundException("The subscription for ID: " + id + " could not be found"); } return converter.toRest(subscription, utils.obtainProjection()); @@ -96,14 +91,16 @@ public class SubscriptionRestRepository extends DSpaceRestRepository String resourceType = req.getParameter("resourceType"); List subscriptionList = subscribeService.findAll(context, resourceType, pageable.getPageSize(), Math.toIntExact(pageable.getOffset())); - return converter.toRestPage(subscriptionList, pageable, utils.obtainProjection()); + Long total = subscribeService.countAll(context); + return converter.toRestPage(subscriptionList, pageable, total, utils.obtainProjection()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } + @PreAuthorize("isAuthenticated()") @SearchRestMethod(name = "findByEPerson") - public Page findAllByEPerson(Context context, String id) { + public Page findAllSubscriptionsByEPerson(String id, Pageable pageable) throws Exception { try { Context context = obtainContext(); EPerson ePerson = personService.findByIdOrLegacyId(context, id); @@ -111,14 +108,19 @@ public class SubscriptionRestRepository extends DSpaceRestRepository || authorizeService.isAdmin(context, context.getCurrentUser())) { List subscriptionList = subscribeService.getSubscriptionsByEPerson(context, ePerson, pageable.getPageSize(), Math.toIntExact(pageable.getOffset())); - return converter.toRestPage(subscriptionList, pageable, utils.obtainProjection()); + Long total = subscribeService.countAllByEPerson(context, ePerson); + return converter.toRestPage(subscriptionList, pageable, total, utils.obtainProjection()); } else { throw new AuthorizeException("Only admin or e-person themselves can search for it's subscription"); } - } catch (SQLException | AuthorizeException sqlException) { - throw new RuntimeException(sqlException.getMessage(), sqlException); + } catch (SQLException sqlException) { + throw new SQLException(sqlException.getMessage(), sqlException); + + } catch (AuthorizeException authorizeException) { + throw new AuthorizeException(authorizeException.getMessage()); } } + @PreAuthorize("isAuthenticated()") @SearchRestMethod(name = "findByEPersonAndDso") public Page findByEPersonAndDso(Pageable pageable) throws Exception { @@ -138,7 +140,8 @@ public class SubscriptionRestRepository extends DSpaceRestRepository List subscriptionList = subscribeService.getSubscriptionsByEPersonAndDso(context, ePerson, dSpaceObject, pageable.getPageSize(), Math.toIntExact(pageable.getOffset())); - return converter.toRestPage(subscriptionList, pageable, subscriptionList.size(), + Long total = subscribeService.countAllByEPersonAndDSO(context, ePerson, dSpaceObject); + return converter.toRestPage(subscriptionList, pageable, total, utils.obtainProjection()); } else { throw new AuthorizeException("Only admin or e-person themselves can search for it's subscription"); @@ -150,22 +153,38 @@ public class SubscriptionRestRepository extends DSpaceRestRepository throw new AuthorizeException(authorizeException.getMessage()); } } + @Override @PreAuthorize("isAuthenticated()") - protected SubscriptionRest createAndReturn(Context context) { + protected SubscriptionRest createAndReturn(Context context) throws SQLException, AuthorizeException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); - ObjectMapper mapper = new ObjectMapper(); - SubscriptionRest subscriptionRest = null; - DSpaceObject dSpaceObject = null; - try { - subscriptionRest = mapper.readValue(req.getInputStream(), SubscriptionRest.class); - } catch (IOException e1) { + String epersonId = req.getParameter("eperson_id"); + String dsoId = req.getParameter("dspace_object_id"); + // dso must always be set + if (dsoId == null || epersonId == null) { throw new UnprocessableEntityException("error parsing the body"); } + ObjectMapper mapper = new ObjectMapper(); try { - Subscription subscription = null; DSpaceObject dSpaceObject = dspaceObjectUtil.findDSpaceObject(context, UUID.fromString(dsoId)); EPerson ePerson = personService.findByIdOrLegacyId(context, epersonId); + if (ePerson == null || dSpaceObject == null) { + throw new BadRequestException("Id of person or dspace object must represents reals ids"); + } + // user must have read permissions to dataspace object + if (!authorizeService.authorizeActionBoolean(context, ePerson, dSpaceObject, Constants.READ, true)) { + throw new AuthorizeException("The user has not READ rights on this DSO"); + } + // if user is admin do not make this control, + // otherwise make this control because normal user can only subscribe with their own ID of user. + if (!authorizeService.isAdmin(context)) { + if (!ePerson.equals(context.getCurrentUser())) { + throw new AuthorizeException("Only administrator can subscribe for other persons"); + } + } + ServletInputStream input = req.getInputStream(); + SubscriptionRest subscriptionRest = mapper.readValue(input, SubscriptionRest.class); + Subscription subscription = null; List subscriptionParameterList = subscriptionRest.getSubscriptionParameterList(); if (subscriptionParameterList != null) { List subscriptionParameters = new ArrayList<>(); @@ -178,12 +197,17 @@ public class SubscriptionRestRepository extends DSpaceRestRepository subscription = subscribeService.subscribe(context, ePerson, dSpaceObject, subscriptionParameters, - subscriptionRest.getType()); + subscriptionRest.getSubscriptionType()); } context.commit(); return converter.toRest(subscription, utils.obtainProjection()); - } catch (SQLException | AuthorizeException e) { - throw new RuntimeException(e.getMessage(), e); + } catch (SQLException sqlException) { + throw new SQLException(sqlException.getMessage(), sqlException); + + } catch (AuthorizeException authorizeException) { + throw new AuthorizeException(authorizeException.getMessage()); + } catch (IOException ioException) { + throw new UnprocessableEntityException("error parsing the body"); } } @@ -191,20 +215,30 @@ public class SubscriptionRestRepository extends DSpaceRestRepository @PreAuthorize("isAuthenticated()") protected SubscriptionRest put(Context context, HttpServletRequest request, String apiCategory, String model, Integer id, JsonNode jsonNode) throws SQLException, AuthorizeException { + HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); + String epersonId = req.getParameter("eperson_id"); + String dsoId = req.getParameter("dspace_object_id"); SubscriptionRest subscriptionRest = null; + DSpaceObject dSpaceObject = null; + EPerson ePerson = null; try { subscriptionRest = new ObjectMapper().readValue(jsonNode.toString(), SubscriptionRest.class); } catch (IOException e) { throw new UnprocessableEntityException("Error parsing subscription json: " + e.getMessage()); } - Subscription subscription = null; String notFoundException = "ResourceNotFoundException:" + apiCategory + "." + model + " with id: " + id + " not found"; + Subscription subscription; try { subscription = subscribeService.findById(context, id); if (subscription == null) { throw new ResourceNotFoundException(notFoundException); } + dSpaceObject = dspaceObjectUtil.findDSpaceObject(context, UUID.fromString(dsoId)); + ePerson = personService.findByIdOrLegacyId(context, epersonId); + if (dSpaceObject == null || ePerson == null) { + throw new ResourceNotFoundException(notFoundException); + } } catch (SQLException e) { throw new ResourceNotFoundException(notFoundException); } catch (AuthorizeException e) { @@ -227,20 +261,21 @@ public class SubscriptionRestRepository extends DSpaceRestRepository } else { throw new IllegalArgumentException("The id in the Json and the id in the url do not match: " + id + ", " - + subscriptionRest.getId()); + + subscription.getID()); } } @Override @PreAuthorize("isAuthenticated()") - public void patch(Context context, HttpServletRequest request, String apiCategory, - String model, Integer id, Patch patch) + public void patch(Context context,HttpServletRequest request,String category, String model, Integer id, Patch patch) throws UnprocessableEntityException, DSpaceBadRequestException, AuthorizeException { - Subscription subscription = null; try { - subscription = subscribeService.findById(context, id); + Subscription subscription = subscribeService.findById(context, id); if (subscription == null) { - throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found"); + throw new ResourceNotFoundException(category + "." + model + " with id: " + id + " not found"); + } + if (!authorizeService.isAdmin(context) || subscription.getePerson().equals(context.getCurrentUser())) { + throw new AuthorizeException("Only admin or e-person themselves can edit the subscription"); } resourcePatch.patch(context, subscription, patch.getOperations()); } catch (SQLException e) { @@ -254,11 +289,13 @@ public class SubscriptionRestRepository extends DSpaceRestRepository @Override @PreAuthorize("isAuthenticated()") - public void delete(Context context, Integer id) { + public void delete(Context context, Integer id) throws AuthorizeException { try { subscribeService.deleteSubscription(context, id); - } catch (SQLException | AuthorizeException sqlException) { + } catch (SQLException sqlException) { throw new RuntimeException(sqlException.getMessage(), sqlException); + } catch (AuthorizeException authorizeException) { + throw new AuthorizeException(authorizeException.getMessage()); } } @@ -267,4 +304,4 @@ public class SubscriptionRestRepository extends DSpaceRestRepository return SubscriptionRest.class; } -} +} \ No newline at end of file diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/patch/operation/SubscriptionParameterReplaceOperation.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/patch/operation/SubscriptionParameterReplaceOperation.java index b0f7c9a31c..c9149aa115 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/patch/operation/SubscriptionParameterReplaceOperation.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/patch/operation/SubscriptionParameterReplaceOperation.java @@ -16,10 +16,8 @@ import org.dspace.app.rest.exception.UnprocessableEntityException; import org.dspace.app.rest.model.SubscriptionParameterRest; import org.dspace.app.rest.model.patch.JsonValueEvaluator; import org.dspace.app.rest.model.patch.Operation; -import org.dspace.authorize.AuthorizeException; import org.dspace.core.Context; import org.dspace.eperson.Subscription; -import org.dspace.eperson.SubscriptionParameter; import org.dspace.eperson.service.SubscriptionParameterService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -38,7 +36,6 @@ public class SubscriptionParameterReplaceOperation extends PatchOperation { return subscriptionParameter.getId().equals(id); }).findFirst().orElseThrow(); - } + } \ No newline at end of file diff --git a/dspace-server-webapp/src/test/java/org/dspace/app/rest/SubscriptionRestRepositoryIT.java b/dspace-server-webapp/src/test/java/org/dspace/app/rest/SubscriptionRestRepositoryIT.java index 1422ec55a2..dc3519fe07 100644 --- a/dspace-server-webapp/src/test/java/org/dspace/app/rest/SubscriptionRestRepositoryIT.java +++ b/dspace-server-webapp/src/test/java/org/dspace/app/rest/SubscriptionRestRepositoryIT.java @@ -7,6 +7,21 @@ */ package org.dspace.app.rest; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import com.fasterxml.jackson.databind.ObjectMapper; import org.dspace.app.rest.model.SubscriptionParameterRest; import org.dspace.app.rest.model.SubscriptionRest; @@ -19,11 +34,9 @@ import org.dspace.builder.CollectionBuilder; import org.dspace.builder.CommunityBuilder; import org.dspace.builder.EPersonBuilder; import org.dspace.builder.ItemBuilder; +import org.dspace.builder.SubscribeBuilder; import org.dspace.content.Collection; -import org.dspace.content.Community; import org.dspace.content.Item; -import org.dspace.content.service.BitstreamService; -import org.dspace.content.service.SiteService; import org.dspace.eperson.EPerson; import org.dspace.eperson.Subscription; import org.dspace.eperson.SubscriptionParameter; @@ -31,71 +44,60 @@ import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.is; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * Integration test to test the /api/config/subscriptions endpoint * (Class has to start or end with IT to be picked up by the failsafe plugin) + * + * @author Mykhaylo Boychuk (mykhaylo.boychuk at 4science.com) */ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationTest { - private Collection collection; - private Item publicItem; - @Override + private Item publicItem; + private Collection collection; + @Before + @Override public void setUp() throws Exception { super.setUp(); context.turnOffAuthorisationSystem(); + parentCommunity = CommunityBuilder.createCommunity(context) - .withName("Parent Community") - .build(); - Community community = CommunityBuilder.createSubCommunity(context, parentCommunity) - .withName("Sub Community") - .build(); - collection = CollectionBuilder.createCollection(context, community).withName("Collection 1").build(); + .withName("Parent Community") + .build(); + collection = CollectionBuilder.createCollection(context, parentCommunity) + .withName("Collection 1") + .build(); // creation of the item which will be the DSO related with a subscription publicItem = ItemBuilder.createItem(context, collection) - .withTitle("Test") - .withIssueDate("2010-10-17") - .withAuthor("Smith, Donald") - .withSubject("ExtraEntry") - .build(); + .withTitle("Test") + .withIssueDate("2010-10-17") + .withAuthor("Smith, Donald") + .withSubject("ExtraEntry") + .build(); + context.restoreAuthSystemState(); } - // FIND ALL @Test public void findAll() throws Exception { context.turnOffAuthorisationSystem(); - String token = getAuthToken(admin.getEmail(), password); + List subscriptionParameterList = new ArrayList<>(); SubscriptionParameter subscriptionParameter = new SubscriptionParameter(); subscriptionParameter.setName("Frequency"); subscriptionParameter.setValue("Daily"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TypeTest", publicItem, admin, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "TypeTest", publicItem, admin, subscriptionParameterList).build(); subscriptionParameter.setSubscription(subscription); - //When we call the root endpoint + context.restoreAuthSystemState(); - getClient(token).perform(get("/api/core/subscriptions")) - //The status has to be 200 OK + + String tokenAdmin = getAuthToken(admin.getEmail(), password); + getClient(tokenAdmin).perform(get("/api/core/subscriptions")) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" .andExpect(content().contentType(contentType)) @@ -105,9 +107,12 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.page.totalPages", greaterThanOrEqualTo(1))) .andExpect(jsonPath("$.page.number", is(0))) .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionType", is("TypeTest"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", Matchers.endsWith("dSpaceObject"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", + Matchers.endsWith("dSpaceObject"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", Matchers.endsWith("ePerson"))) .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionParameterList[0].name", is("Frequency"))) .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionParameterList[0].value", is("Daily"))) @@ -116,42 +121,34 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT @Test public void findAllAnonymous() throws Exception { - //When we call the root endpoint as anonymous user getClient().perform(get("/api/core/subscriptions")) - //The status has to be 401 Not Authorized - .andExpect(status().isUnauthorized()); + .andExpect(status().isUnauthorized()); } @Test public void findAllAsUser() throws Exception { - context.turnOffAuthorisationSystem(); - String token = getAuthToken(eperson.getEmail(), password); - context.restoreAuthSystemState(); - //When we call the root endpoint as simple user - getClient(token).perform(get("/api/core/subscriptions")) - //The status has to be 403 Forbidden - .andExpect(status().isForbidden()); + String tokenEPerson = getAuthToken(eperson.getEmail(), password); + getClient(tokenEPerson).perform(get("/api/core/subscriptions")) + .andExpect(status().isForbidden()); } @Test public void findAllWithResourceType() throws Exception { context.turnOffAuthorisationSystem(); - //When we call the root endpoint as anonymous user - getClient().perform(get("/api/core/subscriptions")) - //The status has to be 401 Not Authorized - .andExpect(status().isUnauthorized()); - String token = getAuthToken(admin.getEmail(), password); + List subscriptionParameterList = new ArrayList<>(); SubscriptionParameter subscriptionParameter = new SubscriptionParameter(); subscriptionParameter.setName("Frequency"); subscriptionParameter.setValue("Daily"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TypeTest", publicItem, admin, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "TypeTest", publicItem, admin, subscriptionParameterList).build(); subscriptionParameter.setSubscription(subscription); - //When we call the root endpoint + context.restoreAuthSystemState(); - getClient(token).perform(get("/api/core/subscriptions?resourceType=Item")) - //The status has to be 200 OK + + String tokenAdmin = getAuthToken(admin.getEmail(), password); + getClient(tokenAdmin).perform(get("/api/core/subscriptions?resourceType=Item")) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" .andExpect(content().contentType(contentType)) @@ -161,16 +158,20 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.page.totalPages", greaterThanOrEqualTo(1))) .andExpect(jsonPath("$.page.number", is(0))) .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionType", is("TypeTest"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", Matchers.endsWith("dSpaceObject"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", + Matchers.endsWith("dSpaceObject"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", Matchers.endsWith("ePerson"))) .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionParameterList[0].name", is("Frequency"))) .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionParameterList[0].value", is("Daily"))) - .andExpect(jsonPath("$._links.self.href", Matchers.is(REST_SERVER_URL + "core/subscriptions?resourceType=Item"))); + .andExpect(jsonPath("$._links.self.href", + Matchers.is(REST_SERVER_URL + "core/subscriptions?resourceType=Item"))); + // search for subscriptions related with collections - getClient(token).perform(get("/api/core/subscriptions?resourceType=Collection")) - //The status has to be 200 OK + getClient(tokenAdmin).perform(get("/api/core/subscriptions?resourceType=Collection")) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" .andExpect(content().contentType(contentType)) @@ -179,24 +180,24 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.page.totalElements", greaterThanOrEqualTo(0))) .andExpect(jsonPath("$.page.totalPages", greaterThanOrEqualTo(0))) .andExpect(jsonPath("$.page.number", is(0))) - .andExpect(jsonPath("$._links.self.href", Matchers.is(REST_SERVER_URL + "core/subscriptions?resourceType=Collection"))); + .andExpect(jsonPath("$._links.self.href", + Matchers.is(REST_SERVER_URL + "core/subscriptions?resourceType=Collection"))); } - // FIND BY ID @Test public void findByIdAsAdministrator() throws Exception { context.turnOffAuthorisationSystem(); - String token = getAuthToken(admin.getEmail(), password); List subscriptionParameterList = new ArrayList<>(); SubscriptionParameter subscriptionParameter = new SubscriptionParameter(); subscriptionParameter.setName("Parameter"); subscriptionParameter.setValue("ValueParameter"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TestType", publicItem, admin, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "TestType", publicItem, admin, subscriptionParameterList).build(); context.restoreAuthSystemState(); - //When we call the root endpoint - getClient(token).perform(get("/api/core/subscriptions/" + subscription.getID())) - //The status has to be 200 OK + + String tokenAdmin = getAuthToken(admin.getEmail(), password); + getClient(tokenAdmin).perform(get("/api/core/subscriptions/" + subscription.getID())) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" .andExpect(content().contentType(contentType)) @@ -204,13 +205,14 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.subscriptionType", is("TestType"))) .andExpect(jsonPath("$.subscriptionParameterList[0].name", is("Parameter"))) .andExpect(jsonPath("$.subscriptionParameterList[0].value", is("ValueParameter"))) - .andExpect(jsonPath("$._links.self.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions/" + subscription.getID()))) - .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._links.self.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions/" + subscription.getID()))) + .andExpect(jsonPath("$._links.dSpaceObject.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.endsWith("/dSpaceObject"))) - .andExpect(jsonPath("$._links.ePerson.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._links.ePerson.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._links.ePerson.href", Matchers.endsWith("/ePerson"))); - - } @Test @@ -221,75 +223,73 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter.setName("Parameter"); subscriptionParameter.setValue("ValueParameter"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TestType", publicItem, admin, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "TestType", publicItem, admin, subscriptionParameterList).build(); context.restoreAuthSystemState(); - //When we call the root endpoint + getClient().perform(get("/api/core/subscriptions/" + subscription.getID())) - //The status has to be 401 - .andExpect(status().isUnauthorized()); + .andExpect(status().isUnauthorized()); } @Test + //TODO public void findByIdNotAsSubscriberNotAsAdmin() throws Exception { context.turnOffAuthorisationSystem(); - String token = getAuthToken(eperson.getEmail(), password); List subscriptionParameterList = new ArrayList<>(); SubscriptionParameter subscriptionParameter = new SubscriptionParameter(); subscriptionParameter.setName("Parameter"); subscriptionParameter.setValue("ValueParameter"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TestType", publicItem, admin, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "TestType", publicItem, admin, subscriptionParameterList).build(); context.restoreAuthSystemState(); - //When we call the root endpoint - getClient(token).perform(get("/api/core/subscriptions/" + subscription.getID())) - //The status has to be 500 + + String tokenEPerson = getAuthToken(eperson.getEmail(), password); + getClient(tokenEPerson).perform(get("/api/core/subscriptions/" + subscription.getID())) .andExpect(status().isInternalServerError()); } - // FIND ALL BY EPERSON/DSO @Test public void findAllSubscriptionsByEPerson() throws Exception { - //When we call the root endpoint as anonymous user -// getClient().perform(get("/api/core/subscriptions")) -// //The status has to be 403 Not Authorized -// .andExpect(status().isUnauthorized()); - String token = getAuthToken(eperson.getEmail(), password); context.turnOffAuthorisationSystem(); EPerson user = EPersonBuilder.createEPerson(context) - .withEmail("user@test.it") - .withPassword(password) - .build(); + .withEmail("user@test.it") + .withPassword(password) + .build(); List subscriptionParameterList = new ArrayList<>(); SubscriptionParameter subscriptionParameter = new SubscriptionParameter(); subscriptionParameter.setName("Parameter1"); subscriptionParameter.setValue("ValueParameter1"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TestType", publicItem, user, subscriptionParameterList).build(); + SubscribeBuilder.subscribeBuilder(context, "TestType", publicItem, user, subscriptionParameterList).build(); context.restoreAuthSystemState(); - //When we call the root endpoint - getClient(token).perform(get("/api/core/subscriptions/search/findByEPerson?id=" + eperson.getID())) - //The status has to be 200 OK + + String tokenEPerson = getAuthToken(eperson.getEmail(), password); + getClient(tokenEPerson).perform(get("/api/core/subscriptions/search/findByEPerson?id=" + eperson.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.page.size", is(20))) .andExpect(jsonPath("$.page.totalElements", greaterThanOrEqualTo(1))) .andExpect(jsonPath("$.page.totalPages", greaterThanOrEqualTo(1))) .andExpect(jsonPath("$.page.number", is(0))) .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionType", is("TestType"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", Matchers.endsWith("dSpaceObject"))) - .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.dSpaceObject.href", + Matchers.endsWith("dSpaceObject"))) + .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._embedded.subscriptions[0]._links.ePerson.href", Matchers.endsWith("ePerson"))) .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionParameterList[0].name", is("Parameter1"))) - .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionParameterList[0].value", is("ValueParameter1"))); + .andExpect(jsonPath("$._embedded.subscriptions[0].subscriptionParameterList[0].value", + is("ValueParameter1"))); + context.turnOffAuthorisationSystem(); + EPersonBuilder.createEPerson(context) + .withEmail("epersonIT@example.com") + .withPassword(password) + .withLanguage("al") + .build(); - EPerson epersonIT = EPersonBuilder.createEPerson(context) - .withEmail("epersonIT@example.com") - .withPassword(password) - .withLanguage("al") - .build(); - List subscriptionParameterList = new ArrayList<>(); - SubscriptionParameter subscriptionParameter = new SubscriptionParameter(); subscriptionParameter.setName("Parameter1"); subscriptionParameter.setValue("ValueParameter1"); subscriptionParameterList.add(subscriptionParameter); @@ -298,19 +298,20 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter1.setName("Parameter1"); subscriptionParameter1.setValue("ValueParameter1"); subscriptionParameterList1.add(subscriptionParameter1); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TestType", collection, user, subscriptionParameterList).build(); - Subscription subscription1 = SubscribeBuilder.subscribeBuilder(context, "Test", collection, user, subscriptionParameterList1).build(); + SubscribeBuilder.subscribeBuilder(context, "TestType", collection, user, subscriptionParameterList).build(); + SubscribeBuilder.subscribeBuilder(context, "Test", collection, user, subscriptionParameterList1).build(); context.restoreAuthSystemState(); - //When we call the root endpoint - String token = getAuthToken(admin.getEmail(), password); - getClient(token).perform(get("/api/core/subscriptions/search/findByEPersonAndDso?dspace_object_id=" + collection.getID() + "&eperson_id=" + user.getID())) - //The status has to be 200 OK - .andExpect(status().isUnauthorized()); + + String tokenAdmin = getAuthToken(admin.getEmail(), password); + getClient(tokenAdmin).perform(get("/api/core/subscriptions/search/findByEPersonAndDso") + .param("dspace_object_id", collection.getID().toString()) + .param("eperson_id", user.getID().toString())) + .andExpect(status().isUnauthorized()); } - // ADD @Test public void addSubscriptionNotLoggedIn() throws Exception { + context.turnOffAuthorisationSystem(); SubscriptionParameterRest subscriptionParameterRest = new SubscriptionParameterRest(); subscriptionParameterRest.setValue("nameTest"); subscriptionParameterRest.setName("valueTest"); @@ -321,17 +322,19 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT MultiValueMap params = new LinkedMultiValueMap(); params.add("dspace_object_id", publicItem.getID().toString()); params.add("eperson_id", eperson.getID().toString()); + context.restoreAuthSystemState(); + ObjectMapper objectMapper = new ObjectMapper(); - getClient().perform(post("/api/core/subscriptions?dspace_object_id=" + publicItem.getID() + "&eperson_id=" + eperson.getID()) - .content(objectMapper.writeValueAsString(subscriptionRest)) - .contentType(contentType)) - //The status has to be 401 Not Authorized - .andExpect(status().isUnauthorized()); + getClient().perform(post("/api/core/subscriptions") + .param("dspace_object_id", publicItem.getID().toString()) + .param("eperson_id", eperson.getID().toString()) + .content(objectMapper.writeValueAsString(subscriptionRest)) + .contentType(contentType)) + .andExpect(status().isUnauthorized()); } @Test public void addSubscriptionAsAdmin() throws Exception { - //When we call the root endpoint as anonymous user SubscriptionParameterRest subscriptionParameterRest = new SubscriptionParameterRest(); subscriptionParameterRest.setValue("nameTest"); subscriptionParameterRest.setName("valueTest"); @@ -339,9 +342,7 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameterRestList.add(subscriptionParameterRest); SubscriptionRest subscriptionRest = new SubscriptionRest(); subscriptionRest.setType("testType"); -// subscriptionRest.setSubscriptionParameterList(subscriptionParameterRestList); ObjectMapper objectMapper = new ObjectMapper(); - String token = getAuthToken(admin.getEmail(), password); Map map = new HashMap<>(); map.put("type", "test"); List> list = new ArrayList<>(); @@ -350,10 +351,13 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT sub_list.put("value", "daily"); list.add(sub_list); map.put("subscriptionParameterList", list); - getClient(token).perform(post("/api/core/subscriptions?dspace_object_id=" + publicItem.getID() + "&eperson_id=" + admin.getID()) - .content(objectMapper.writeValueAsString(map)) - .contentType(MediaType.APPLICATION_JSON_VALUE)) - //The status has to be 200 OK + + String tokenAdmin = getAuthToken(admin.getEmail(), password); + getClient(tokenAdmin).perform(post("/api/core/subscriptions") + .param("dspace_object_id", publicItem.getID().toString()) + .param("eperson_id", admin.getID().toString()) + .content(objectMapper.writeValueAsString(map)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" //By default we expect at least 1 submission forms so this to be reflected in the page object @@ -362,13 +366,14 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.subscriptionParameterList[0].name", is("nameTest"))) .andExpect(jsonPath("$.subscriptionParameterList[0].value", is("valueTest"))) .andExpect(jsonPath("$._links.self.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) - .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._links.dSpaceObject.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.endsWith("dSpaceObject"))) - .andExpect(jsonPath("$._links.ePerson.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._links.ePerson.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._links.ePerson.href", Matchers.endsWith("ePerson"))); } - // PUT @Test public void editSubscriptionAnonymous() throws Exception { context.turnOffAuthorisationSystem(); @@ -377,9 +382,9 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter.setName("Parameter1"); subscriptionParameter.setValue("ValueParameter1"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TestType", publicItem, admin, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "TestType", publicItem, admin, subscriptionParameterList).build(); ObjectMapper objectMapper = new ObjectMapper(); - String token = getAuthToken(admin.getEmail(), password); Map newSubscription = new HashMap<>(); newSubscription.put("type", "test"); List> list = new ArrayList<>(); @@ -389,15 +394,17 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT list.add(sub_list); newSubscription.put("subscriptionParameterList", list); context.restoreAuthSystemState(); - //When we call the root endpoint as anonymous user - getClient().perform(put("/api/core/subscriptions/" + subscription.getID() + "?dspace_object_id=" + publicItem.getID() + "&eperson_id=" + admin.getID()) - .content(objectMapper.writeValueAsString(newSubscription)) - .contentType(MediaType.APPLICATION_JSON_VALUE)) - //The status has to be 403 Not Authorized - .andExpect(status().isUnauthorized()); + + getClient().perform(put("/api/core/subscriptions/" + subscription.getID()) + .param("dspace_object_id", publicItem.getID().toString()) + .param("eperson_id", admin.getID().toString()) + .content(objectMapper.writeValueAsString(newSubscription)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isUnauthorized()); } @Test + //TODO public void editSubscriptionNotAsSubscriberNotAsAdmin() throws Exception { context.turnOffAuthorisationSystem(); EPerson epersonIT = EPersonBuilder.createEPerson(context) @@ -410,10 +417,10 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter.setName("Parameter1"); subscriptionParameter.setValue("ValueParameter1"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TestType", publicItem, eperson, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "TestType", publicItem, eperson, subscriptionParameterList).build(); context.restoreAuthSystemState(); ObjectMapper objectMapper = new ObjectMapper(); - String token = getAuthToken(epersonIT.getEmail(), password); Map newSubscription = new HashMap<>(); newSubscription.put("type", "test"); List> list = new ArrayList<>(); @@ -422,8 +429,11 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT sub_list.put("value", "daily"); list.add(sub_list); newSubscription.put("subscriptionParameterList", list); - //When we call the root endpoint as anonymous user - getClient(token).perform(put("/api/core/subscriptions/" + subscription.getID() + "?dspace_object_id=" + publicItem.getID() + "&eperson_id=" + admin.getID()) + + String token = getAuthToken(epersonIT.getEmail(), password); + getClient(token).perform(put("/api/core/subscriptions/" + subscription.getID()) + .param("dspace_object_id", publicItem.getID().toString()) + .param("eperson_id", admin.getID().toString()) .content(objectMapper.writeValueAsString(newSubscription)) .contentType(MediaType.APPLICATION_JSON_VALUE)) //The status has to be 500 Error @@ -432,15 +442,14 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT @Test public void editSubscriptionAsAdministratorOrSubscriber() throws Exception { - String tokenAdmin = getAuthToken(admin.getEmail(), password); - String tokenSubscriber = getAuthToken(eperson.getEmail(), password); context.turnOffAuthorisationSystem(); List subscriptionParameterList = new ArrayList<>(); SubscriptionParameter subscriptionParameter = new SubscriptionParameter(); subscriptionParameter.setName("Frequency"); subscriptionParameter.setValue("Daily"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "TestType", publicItem, eperson, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "TestType", publicItem, eperson, subscriptionParameterList).build(); context.restoreAuthSystemState(); ObjectMapper objectMapper = new ObjectMapper(); Map newSubscription = new HashMap<>(); @@ -451,11 +460,13 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT sub_list.put("value", "daily"); list.add(sub_list); newSubscription.put("subscriptionParameterList", list); + String tokenSubscriber = getAuthToken(eperson.getEmail(), password); - getClient(tokenSubscriber).perform(put("/api/core/subscriptions/" + subscription.getID() + "?dspace_object_id=" + publicItem.getID() + "&eperson_id=" + eperson.getID()) - //The status has to be 403 Not Authorized - .content(objectMapper.writeValueAsString(newSubscription)) - .contentType(MediaType.APPLICATION_JSON_VALUE)) + getClient(tokenSubscriber).perform(put("/api/core/subscriptions/" + subscription.getID()) + .param("dspace_object_id", publicItem.getID().toString()) + .param("eperson_id", eperson.getID().toString()) + .content(objectMapper.writeValueAsString(newSubscription)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" .andExpect(content().contentType(contentType)) @@ -464,32 +475,33 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.subscriptionParameterList[0].name", is("frequency"))) .andExpect(jsonPath("$.subscriptionParameterList[0].value", is("daily"))) .andExpect(jsonPath("$._links.self.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) - .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._links.dSpaceObject.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.endsWith("/dSpaceObject"))) - .andExpect(jsonPath("$._links.ePerson.href", Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) + .andExpect(jsonPath("$._links.ePerson.href", + Matchers.startsWith(REST_SERVER_URL + "core/subscriptions"))) .andExpect(jsonPath("$._links.ePerson.href", Matchers.endsWith("/ePerson"))); } - // DELETE @Test public void deleteSubscriptionNotAsSubscriberNotAsAdmin() throws Exception { context.turnOffAuthorisationSystem(); EPerson epersonIT = EPersonBuilder.createEPerson(context) - .withEmail("epersonIT@example.com") - .withPassword(password) - .withLanguage("al") - .build(); - String epersonITtoken = getAuthToken(epersonIT.getEmail(), password); + .withEmail("epersonIT@example.com") + .withPassword(password) + .withLanguage("al") + .build(); List subscriptionParameterList = new ArrayList<>(); SubscriptionParameter subscriptionParameter = new SubscriptionParameter(); subscriptionParameter.setName("Frequency"); subscriptionParameter.setValue("Daily"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "Test", publicItem, eperson, subscriptionParameterList).build(); + SubscribeBuilder.subscribeBuilder(context, "Test", publicItem, eperson, subscriptionParameterList).build(); context.restoreAuthSystemState(); + + String epersonITtoken = getAuthToken(epersonIT.getEmail(), password); getClient(epersonITtoken).perform(put("/api/core/subscriptions")) - //The status has to be 403 Not Authorized - .andExpect(status().isUnauthorized()); + .andExpect(status().isUnauthorized()); } @Test @@ -500,16 +512,14 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter.setName("Frequency"); subscriptionParameter.setValue("Daily"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "Test", publicItem, eperson, subscriptionParameterList).build(); - String token = getAuthToken(admin.getEmail(), password); + SubscribeBuilder.subscribeBuilder(context, "Test", publicItem, eperson, subscriptionParameterList).build(); context.restoreAuthSystemState(); - String token = getAuthToken(admin.getEmail(), password); - getClient(token).perform(put("/api/core/subscriptions")) - //The status has to be 403 Not Authorized - .andExpect(status().isOk()); + + String tokenAdmin = getAuthToken(admin.getEmail(), password); + getClient(tokenAdmin).perform(put("/api/core/subscriptions")) + .andExpect(status().isOk()); } - // PATCH @Test public void patchReplaceSubscriptionParameterAsAdmin() throws Exception { context.turnOffAuthorisationSystem(); @@ -518,19 +528,21 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter.setName("TestName"); subscriptionParameter.setValue("TestValue"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "Test", publicItem, eperson, subscriptionParameterList).build(); - String token = getAuthToken(admin.getEmail(), password); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "Test", publicItem, eperson, subscriptionParameterList).build(); List ops = new ArrayList(); Map value = new HashMap<>(); value.put("name", "frequency"); value.put("value", "monthly"); - ReplaceOperation replaceOperation = new ReplaceOperation("/subscriptionsParameter/" + subscription.getSubscriptionParameterList().get(0).getId(), value); + ReplaceOperation replaceOperation = new ReplaceOperation("/subscriptionsParameter/" + + subscription.getSubscriptionParameterList().get(0).getId(), value); ops.add(replaceOperation); String patchBody = getPatchContent(ops); - getClient(token).perform(patch("/api/core/subscriptions/" + subscription.getID()) - .content(patchBody) - ) - //The status has to be 403 Not Authorized + context.restoreAuthSystemState(); + + String tokenAdmin = getAuthToken(admin.getEmail(), password); + getClient(tokenAdmin).perform(patch("/api/core/subscriptions/" + subscription.getID()) + .content(patchBody)) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" .andExpect(content().contentType(contentType)) @@ -539,10 +551,14 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.id", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject"))) .andExpect(jsonPath("$.subscriptionParameterList[0].name", is("frequency"))) .andExpect(jsonPath("$.subscriptionParameterList[0].value", is("monthly"))) - .andExpect(jsonPath("$._links.self.href", Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) - .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) - .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject"))) - .andExpect(jsonPath("$._links.ePerson.href", Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) + .andExpect(jsonPath("$._links.self.href", + Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) + .andExpect(jsonPath("$._links.dSpaceObject.href", + Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) + .andExpect(jsonPath("$._links.dSpaceObject.href", + Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject"))) + .andExpect(jsonPath("$._links.ePerson.href", + Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) .andExpect(jsonPath("$._links.ePerson.href", Matchers.endsWith(REST_SERVER_URL + "/api/core/ePerson"))); } @@ -554,12 +570,14 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter.setName("TestName"); subscriptionParameter.setValue("TestValue"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "Test", publicItem, eperson, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "Test", publicItem, eperson, subscriptionParameterList).build(); List ops = new ArrayList(); Map value = new HashMap<>(); value.put("name", "frequency"); value.put("value", "monthly"); - ReplaceOperation replaceOperation = new ReplaceOperation("/subscriptionsParameter/" + subscription.getSubscriptionParameterList().get(0).getId(), value); + ReplaceOperation replaceOperation = new ReplaceOperation("/subscriptionsParameter/" + + subscription.getSubscriptionParameterList().get(0).getId(), value); ops.add(replaceOperation); String patchBody = getPatchContent(ops); EPerson epersonIT = EPersonBuilder.createEPerson(context) @@ -567,12 +585,12 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .withPassword(password) .withLanguage("al") .build(); + context.restoreAuthSystemState(); + String epersonITtoken = getAuthToken(epersonIT.getEmail(), password); getClient(epersonITtoken).perform(patch("/api/core/subscriptions/" + subscription.getID()) - .content(patchBody) - ) - //The status has to be 403 Forbidden - .andExpect(status().isForbidden()); + .content(patchBody)) + .andExpect(status().isForbidden()); } @Test @@ -583,19 +601,19 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter.setName("TestName"); subscriptionParameter.setValue("TestValue"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "Test", publicItem, eperson, subscriptionParameterList).build(); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "Test", publicItem, eperson, subscriptionParameterList).build(); String token = getAuthToken(admin.getEmail(), password); List ops = new ArrayList(); Map value = new HashMap<>(); value.put("name", "frequency"); value.put("value", "monthly"); - AddOperation addOperation = new AddOperation("/subscriptionsParameter/" + subscription.getSubscriptionParameterList().get(0).getId(), value); + AddOperation addOperation = new AddOperation("/subscriptionsParameter/" + + subscription.getSubscriptionParameterList().get(0).getId(), value); ops.add(addOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/core/subscriptions/" + subscription.getID()) - .content(patchBody) - ) - //The status has to be 403 Not Authorized + .content(patchBody)) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" .andExpect(content().contentType(contentType)) @@ -606,10 +624,14 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.subscriptionParameterList[0].value", is("TestValue"))) .andExpect(jsonPath("$.subscriptionParameterList[1].name", is("frequency"))) .andExpect(jsonPath("$.subscriptionParameterList[1].value", is("monthly"))) - .andExpect(jsonPath("$._links.self.href", Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) - .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) - .andExpect(jsonPath("$._links.dSpaceObject.href", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject"))) - .andExpect(jsonPath("$._links.ePerson.href", Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) + .andExpect(jsonPath("$._links.self.href", + Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) + .andExpect(jsonPath("$._links.dSpaceObject.href", + Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) + .andExpect(jsonPath("$._links.dSpaceObject.href", + Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject"))) + .andExpect(jsonPath("$._links.ePerson.href", + Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))) .andExpect(jsonPath("$._links.ePerson.href", Matchers.endsWith(REST_SERVER_URL + "/api/core/ePerson"))); } @@ -621,20 +643,21 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT subscriptionParameter.setName("TestName"); subscriptionParameter.setValue("TestValue"); subscriptionParameterList.add(subscriptionParameter); - Subscription subscription = SubscribeBuilder.subscribeBuilder(context, "Test", publicItem, eperson, subscriptionParameterList).build(); - String token = getAuthToken(admin.getEmail(), password); + Subscription subscription = SubscribeBuilder.subscribeBuilder(context, + "Test", publicItem, eperson, subscriptionParameterList).build(); List ops = new ArrayList(); Map value = new HashMap<>(); value.put("name", "frequency"); value.put("value", "monthly"); - RemoveOperation removeOperation = new RemoveOperation("/subscriptionsParameter/" + subscription.getSubscriptionParameterList().get(0).getId()); + RemoveOperation removeOperation = new RemoveOperation("/subscriptionsParameter/" + + subscription.getSubscriptionParameterList().get(0).getId()); ops.add(removeOperation); String patchBody = getPatchContent(ops); context.restoreAuthSystemState(); + + String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(patch("/api/core/subscriptions/" + subscription.getID()) - .content(patchBody) - ) - //The status has to be 403 Not Authorized + .content(patchBody)) .andExpect(status().isOk()) //We expect the content type to be "application/hal+json;charset=UTF-8" .andExpect(content().contentType(contentType)) @@ -642,6 +665,8 @@ public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationT .andExpect(jsonPath("$.type", is("Test"))) .andExpect(jsonPath("$.id", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject"))) .andExpect(jsonPath("$.subscriptionParameterList", Matchers.arrayWithSize(0))) - .andExpect(jsonPath("$._links.self.href", Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))); + .andExpect(jsonPath("$._links.self.href", + Matchers.startsWith(REST_SERVER_URL + "/api/core/subscriptions"))); } -} \ No newline at end of file + +} diff --git a/dspace/config/spring/api/core-dao-services.xml b/dspace/config/spring/api/core-dao-services.xml index ae4b5e6e3b..bb19ed21fc 100644 --- a/dspace/config/spring/api/core-dao-services.xml +++ b/dspace/config/spring/api/core-dao-services.xml @@ -39,6 +39,7 @@ + diff --git a/dspace/config/spring/api/core-services.xml b/dspace/config/spring/api/core-services.xml index a124ec830f..b949eef6e1 100644 --- a/dspace/config/spring/api/core-services.xml +++ b/dspace/config/spring/api/core-services.xml @@ -101,6 +101,7 @@ +