[DSC-183] Created Subscription_Parameter, Changed Subscription and created entry points components for Subscription

This commit is contained in:
Mykhaylo
2022-12-01 18:29:19 +01:00
parent c535de90f1
commit 40c0c9b7db
13 changed files with 1121 additions and 25 deletions

View File

@@ -0,0 +1,88 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.eperson;
import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.service.CollectionService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.eperson.dao.SubscriptionDAO;
import org.dspace.eperson.dao.SubscriptionParameterDAO;
import org.dspace.eperson.service.SubscribeService;
import org.dspace.eperson.service.SubscriptionParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.SQLException;
import java.util.List;
/**
* Class defining methods for sending new item e-mail alerts to users
*
* @author Robert Tansley
* @version $Revision$
*/
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() {
}
@Override
public List<SubscriptionParameter> findAll(Context context) throws SQLException {
return subscriptionParameterDAO.findAll(context, SubscriptionParameter.class);
}
@Override
public SubscriptionParameter add(Context context, String name, String value, Subscription subscription) throws SQLException, AuthorizeException {
SubscriptionParameter subscriptionParameter = subscriptionParameterDAO.create(context, new SubscriptionParameter());
subscriptionParameter.setName(name);
subscriptionParameter.setSubscription(subscription);
subscriptionParameter.setValue(value);
return subscriptionParameter;
}
@Override
public SubscriptionParameter edit(Context context,Integer id,String value, String name, Subscription subscription) throws SQLException, AuthorizeException {
SubscriptionParameter subscriptionParameter = subscriptionParameterDAO.findByID(context, SubscriptionParameter.class, id);
subscriptionParameter.setId(id);
subscriptionParameter.setName(name);
subscriptionParameter.setSubscription(subscription);
subscriptionParameter.setValue(value);
subscriptionParameterDAO.save(context, subscriptionParameter);
return subscriptionParameter;
}
@Override
public SubscriptionParameter findById(Context context, int id) throws SQLException {
return subscriptionParameterDAO.findByID(context, SubscriptionParameter.class, id);
}
@Override
public void deleteSubscriptionParameter(Context context, Integer id) throws SQLException, AuthorizeException {
SubscriptionParameter subscriptionParameter = subscriptionParameterDAO.findByID(context, SubscriptionParameter.class, id);
if (subscriptionParameter != null) {
subscriptionParameter.setSubscription(null);
subscriptionParameterDAO.delete(context, subscriptionParameter);
} else {
throw new SQLException("Subscription parameter with id" + id + "do not exists");
}
}
}

View File

@@ -152,18 +152,43 @@ public class SubscribeServiceImpl implements SubscribeService {
String type) throws SQLException, AuthorizeException { String type) throws SQLException, AuthorizeException {
// must be admin or the subscriber of the subscription // must be admin or the subscriber of the subscription
if (authorizeService.isAdmin(context, context.getCurrentUser()) || eperson.equals(context.getCurrentUser())) { if (authorizeService.isAdmin(context, context.getCurrentUser()) || eperson.equals(context.getCurrentUser())) {
Subscription subscription = subscriptionDAO.findByID(context, Subscription.class, id); Subscription subscriptionDB = subscriptionDAO.findByID(context, Subscription.class, id);
subscription.setType(type); subscriptionDB.removeParameterList();
subscription.setdSpaceObject(dSpaceObject); subscriptionDB.setType(type);
subscription.setSubscriptionParameterList(subscriptionParameterList); subscriptionDB.setdSpaceObject(dSpaceObject);
subscription.setePerson(eperson); subscriptionParameterList.forEach(subscriptionParameter -> subscriptionDB.addParameter(subscriptionParameter));
subscriptionDAO.save(context, subscription); subscriptionDB.setePerson(eperson);
return subscription; subscriptionDAO.save(context, subscriptionDB);
return subscriptionDB;
} else { } else {
throw new AuthorizeException("Only admin or e-person themselves can edit the subscription"); throw new AuthorizeException("Only admin or e-person themselves can edit the subscription");
} }
} }
@Override
public Subscription addSubscriptionParameter(Context context, Integer id, 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()) || subscriptionDB.getePerson().equals(context.getCurrentUser())) {
subscriptionDB.addParameter(subscriptionParameter);
subscriptionDAO.save(context, subscriptionDB);
return subscriptionDB;
} else {
throw new AuthorizeException("Only admin or e-person themselves can edit the subscription");
}
}
@Override
public Subscription removeSubscriptionParameter(Context context, Integer id, 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()) || subscriptionDB.getePerson().equals(context.getCurrentUser())) {
subscriptionDB.removeParameter(subscriptionParameter);
subscriptionDAO.save(context, subscriptionDB);
return subscriptionDB;
} else {
throw new AuthorizeException("Only admin or e-person themselves can edit the subscription");
}
}
@Override @Override
public void deleteSubscription(Context context, Integer id) throws SQLException, AuthorizeException { public void deleteSubscription(Context context, Integer id) throws SQLException, AuthorizeException {
// initially find the eperson associated with the subscription // initially find the eperson associated with the subscription

View File

@@ -55,8 +55,9 @@ public class Subscription implements ReloadableEntity<Integer> {
@Column(name = "type") @Column(name = "type")
private String type; private String type;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.ALL) @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.ALL, orphanRemoval = true)
private List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>(); private List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
/** /**
* Protected constructor, create object using: * Protected constructor, create object using:
* {@link org.dspace.eperson.service.SubscribeService#subscribe(Context, EPerson, DSpaceObject, List, String)} * {@link org.dspace.eperson.service.SubscribeService#subscribe(Context, EPerson, DSpaceObject, List, String)}
@@ -105,4 +106,17 @@ public class Subscription implements ReloadableEntity<Integer> {
public void setSubscriptionParameterList(List<SubscriptionParameter> subscriptionList) { public void setSubscriptionParameterList(List<SubscriptionParameter> subscriptionList) {
this.subscriptionParameterList = subscriptionList; this.subscriptionParameterList = subscriptionList;
} }
public void addParameter(SubscriptionParameter subscriptionParameter) {
subscriptionParameterList.add(subscriptionParameter);
subscriptionParameter.setSubscription(this);
}
public void removeParameterList() {
subscriptionParameterList.clear();
}
public void removeParameter(SubscriptionParameter subscriptionParameter) {
subscriptionParameterList.remove(subscriptionParameter);
}
} }

View File

@@ -148,6 +148,21 @@ public interface SubscribeService {
List<SubscriptionParameter> subscriptionParameterList, List<SubscriptionParameter> subscriptionParameterList,
String type) throws SQLException, AuthorizeException; String type) throws SQLException, AuthorizeException;
/**
* Deletes a subscription
*
* @param context DSpace context
* @throws SQLException An exception that provides information on a database access error or other errors.
*/
public Subscription addSubscriptionParameter(Context context, Integer id, SubscriptionParameter subscriptionParameter) throws SQLException, AuthorizeException;
/**
* Deletes a subscription
*
* @param context DSpace context
* @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;
/** /**
* Deletes a subscription * Deletes a subscription
* *

View File

@@ -15,20 +15,20 @@ CREATE SEQUENCE subscription_parameter_seq;
CREATE TABLE subscription_parameter CREATE TABLE subscription_parameter
( (
subscription_parameter_id INTEGER NOT NULL, subscription_parameter_id INTEGER NOT NULL,
parameter_name CHARACTER VARYING(255), name CHARACTER VARYING(255),
parameter_value CHARACTER VARYING(255), value CHARACTER VARYING(255),
subscription_id INTEGER NOT NULL, subscription_id INTEGER NOT NULL,
CONSTRAINT subscription_parameter_pkey PRIMARY KEY (subscription_parameter_id), CONSTRAINT subscription_parameter_pkey PRIMARY KEY (subscription_parameter_id),
CONSTRAINT subscription_parameter_subscription_fkey FOREIGN KEY (subscription_id) REFERENCES subscription (subscription_id) CONSTRAINT subscription_parameter_subscription_fkey FOREIGN KEY (subscription_id) REFERENCES subscription (subscription_id)
); );
-- -- -- --
--ALTER TABLE subscription DROP CONSTRAINT subscription_collection_id_fkey; --ALTER TABLE subscription DROP CONSTRAINT subscription_collection_id_fkey;
---- -- -- --
--ALTER TABLE subscription ALTER COLUMN collection_id RENAME TO dspace_object_id; ALTER TABLE subscription ALTER COLUMN collection_id RENAME TO dspace_object_id;
-- -- -- --
ALTER TABLE subscription ADD COLUMN type CHARACTER VARYING(255); ALTER TABLE subscription ADD COLUMN type CHARACTER VARYING(255);
---- -- ---- --
--ALTER TABLE subscription ADD CONSTRAINT subscription_dspaceobject_fkey FOREIGN KEY (dspace_object_id) REFERENCES dspaceobject(uuid); ALTER TABLE subscription ADD CONSTRAINT subscription_dspaceobject_fkey FOREIGN KEY (dspace_object_id) REFERENCES dspaceobject(uuid);

View File

@@ -25,12 +25,12 @@ CREATE TABLE subscription_parameter
-- -- -- --
--ALTER TABLE subscription DROP CONSTRAINT subscription_collection_id_fkey --ALTER TABLE subscription DROP CONSTRAINT subscription_collection_id_fkey
------ -- ---- --
--ALTER TABLE subscription ALTER COLUMN collection_id RENAME TO dspace_object_id; ALTER TABLE subscription ALTER COLUMN collection_id RENAME TO dspace_object_id;
---- -- ---- --
ALTER TABLE subscription ADD COL ALTER TABLE subscription ADD COL
---- -- ---- --
--ALTER TABLE subscription ADD CONSTRAINT subscription_dspaceobject_fkey FOREIGN KEY (dspace_object_id) REFERENCES dspaceobject (uuid); ALTER TABLE subscription ADD CONSTRAINT subscription_dspaceobject_fkey FOREIGN KEY (dspace_object_id) REFERENCES dspaceobject (uuid);
-- --

View File

@@ -21,15 +21,15 @@ CREATE TABLE subscription_parameter
CONSTRAINT subscription_parameter_pkey PRIMARY KEY (subscription_parameter_id), CONSTRAINT subscription_parameter_pkey PRIMARY KEY (subscription_parameter_id),
CONSTRAINT subscription_parameter_subscription_fkey FOREIGN KEY (subscription_id) REFERENCES subscription (subscription_id) CONSTRAINT subscription_parameter_subscription_fkey FOREIGN KEY (subscription_id) REFERENCES subscription (subscription_id)
); );
-- -- --
--ALTER TABLE subscription DROP CONSTRAINT subscription_collection_id_fkey; --ALTER TABLE subscription DROP CONSTRAINT subscription_collection_id_fkey;
---- -- -- --
--ALTER TABLE subscription RENAME COLUMN collection_id TO dspace_object_id; ALTER TABLE subscription RENAME COLUMN collection_id TO dspace_object_id;
---- -- -- --
ALTER TABLE subscription ADD COLUMN type CHARACTER VARYING(255); ALTER TABLE subscription ADD COLUMN type CHARACTER VARYING(255);
---- -- ---- --
--ALTER TABLE subscription ADD CONSTRAINT subscription_dspaceobject_fkey FOREIGN KEY (dspace_object_id) REFERENCES dspaceobject (uuid); ALTER TABLE subscription ADD CONSTRAINT subscription_dspaceobject_fkey FOREIGN KEY (dspace_object_id) REFERENCES dspaceobject (uuid);
--
--
-- --

View File

@@ -153,6 +153,21 @@ public class SubscriptionRestRepository extends DSpaceRestRepository<Subscriptio
} }
} }
@Override
@PreAuthorize("hasAuthority('ADMIN')")
public void patch(Context context, HttpServletRequest request, String apiCategory, String model, Integer id, Patch patch) throws UnprocessableEntityException, DSpaceBadRequestException {
Subscription subscription = null;
try {
subscription = subscribeService.findById(context, id);
if (subscription == null) {
throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found");
}
resourcePatch.patch(context, subscription, patch.getOperations());
} catch (SQLException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override @Override
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
public void delete(Context context, Integer id) { public void delete(Context context, Integer id) {

View File

@@ -21,7 +21,7 @@ import org.springframework.stereotype.Component;
/** /**
* Implementation for ResearcherProfile visibility patches. * Implementation for ResearcherProfile visibility patches.
* *SubscriptionParameterAddOperationpatches
* Example: * Example:
* <code> curl -X PATCH http://${dspace.server.url}/api/eperson/profiles/<:id-eperson> -H " * <code> curl -X PATCH http://${dspace.server.url}/api/eperson/profiles/<:id-eperson> -H "
* Content-Type: application/json" -d '[{ "op": "replace", "path": " * Content-Type: application/json" -d '[{ "op": "replace", "path": "

View File

@@ -0,0 +1,86 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.repository.patch.operation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.dspace.app.profile.ResearcherProfile;
import org.dspace.app.profile.service.ResearcherProfileService;
import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.exception.RESTAuthorizationException;
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.SubscribeService;
import org.dspace.eperson.service.SubscriptionParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Implementation for SubscriptionParameterAddOperation patches.
* <p>
* Example:
* <code> curl -X PATCH http://${dspace.server.url}api/core/subscriptions/<:id-subscription> -H "
* Content-Type: application/json" -d '[{ "op": "replace", "path": "
* </code>
*/
@Component
public class SubscriptionParameterAddOperation extends PatchOperation<Subscription> {
@Autowired
private SubscribeService subscribeService;
@Override
public Subscription perform(Context context, Subscription subscription, Operation operation)
throws SQLException {
if (supports(subscription, operation)) {
JsonNode value = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
if (operation.getValue() instanceof JsonValueEvaluator) {
value = ((JsonValueEvaluator) operation.getValue()).getValueNode();
} else {
value = objectMapper.readTree((String) operation.getValue());
}
SubscriptionParameterRest subscriptionParameterRest = objectMapper.readValue(value.toString(), SubscriptionParameterRest.class);
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setSubscription(subscription);
subscriptionParameter.setValue(subscriptionParameterRest.getValue());
subscriptionParameter.setName(subscriptionParameterRest.getName());
subscribeService.addSubscriptionParameter(context, subscription.getID(), subscriptionParameter);
} catch (UnprocessableEntityException e) {
throw new UnprocessableEntityException(e.getMessage(), e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
} else {
throw new DSpaceBadRequestException("Subscription does not support this operation");
}
return subscription;
}
@Override
public boolean supports(Object objectToMatch, Operation operation) {
return (objectToMatch instanceof Subscription
&& operation.getOp().trim().equalsIgnoreCase(OPERATION_ADD));
}
}

View File

@@ -0,0 +1,68 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.repository.patch.operation;
import org.dspace.app.profile.ResearcherProfile;
import org.dspace.app.profile.service.ResearcherProfileService;
import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.exception.RESTAuthorizationException;
import org.dspace.app.rest.exception.UnprocessableEntityException;
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.SubscribeService;
import org.dspace.eperson.service.SubscriptionParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
/**
* Implementation for SubscriptionParameterRemoveOperation patches.
* <p>
* Example:
* <code> curl -X PATCH http://${dspace.server.url}api/core/subscriptions/<:id-subscription> -H "
* Content-Type: application/json" -d '[{ "op": "replace", "path": "
* </code>
*/
@Component
public class SubscriptionParameterRemoveOperation extends PatchOperation<Subscription> {
@Autowired
private SubscriptionParameterService subscriptionParameterService;
@Autowired
private SubscribeService subscribeService;
@Override
public Subscription perform(Context context, Subscription subscription, Operation operation)
throws SQLException {
if (supports(subscription, operation)) {
Integer path = Integer.parseInt(operation.getPath().split("/")[2]);
try {
SubscriptionParameter subscriptionParameter = subscriptionParameterService.findById(context, path);
subscribeService.removeSubscriptionParameter(context, subscription.getID(), subscriptionParameter);
} catch (AuthorizeException e) {
throw new RESTAuthorizationException("Unauthorized user for removing subscription parameter");
}
} else {
throw new DSpaceBadRequestException("Subscription does not support this operation");
}
return subscription;
}
@Override
public boolean supports(Object objectToMatch, Operation operation) {
return (objectToMatch instanceof Subscription
&& operation.getOp().trim().equalsIgnoreCase(OPERATION_REMOVE));
}
}

View File

@@ -0,0 +1,108 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.repository.patch.operation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.jsonldjava.utils.Obj;
import javassist.NotFoundException;
import org.apache.xpath.operations.Bool;
import org.dspace.app.profile.ResearcherProfile;
import org.dspace.app.profile.service.ResearcherProfileService;
import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.exception.RESTAuthorizationException;
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.EPerson;
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;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation for SubscriptionParameterReplaceOperation patches.
* <p>
* Example:
* <code> curl -X PATCH http://${dspace.server.url}api/core/subscriptions/<:id-subscription> -H "
* Content-Type: application/json" -d '[{ "op": "replace", "path": "
* </code>
*/
@Component
public class SubscriptionParameterReplaceOperation extends PatchOperation<Subscription> {
@Autowired
private SubscriptionParameterService subscriptionParameterService;
@Override
public Subscription perform(Context context, Subscription subscription, Operation operation)
throws SQLException {
if (supports(subscription, operation)) {
Integer subscriptionParameterId = Integer.parseInt(operation.getPath().split("/", 3)[2]);
checkModelForExistingValue(subscription, subscriptionParameterId);
JsonNode value = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
if (operation.getValue() instanceof JsonValueEvaluator) {
value = ((JsonValueEvaluator) operation.getValue()).getValueNode();
} else {
value = objectMapper.readTree((String) operation.getValue());
}
SubscriptionParameterRest subscriptionParameterRest = objectMapper.readValue(value.toString(), SubscriptionParameterRest.class);
try {
SubscriptionParameter subscriptionParameter = subscriptionParameterService.edit(context, subscriptionParameterId, subscriptionParameterRest.getValue(),
subscriptionParameterRest.getName(),
subscription);
} catch (SQLException | AuthorizeException exception) {
throw new RuntimeException(exception);
}
} catch (UnprocessableEntityException e) {
throw new UnprocessableEntityException(e.getMessage(), e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
return subscription;
} else {
throw new DSpaceBadRequestException("Subscription does not support this operation");
}
}
@Override
public boolean supports(Object objectToMatch, Operation operation) {
return (objectToMatch instanceof Subscription
&& operation.getOp().trim().equalsIgnoreCase(OPERATION_REPLACE));
}
/**
* Checks whether the subscription
*
* @param subscription Object on which patch is being done
*/
private void checkModelForExistingValue(Subscription subscription, Integer id) {
subscription.getSubscriptionParameterList().stream().filter(subscriptionParameter -> {
return subscriptionParameter.getId().equals(id);
}).findFirst().orElseThrow();
}
public SubscriptionParameter generateObjectFromValue(Subscription subscription, String name) {
return subscription
.getSubscriptionParameterList().stream().filter(subscriptionParameter1 -> {
return subscriptionParameter1.getName().equals(name);
}).findFirst().orElseThrow();
}
}

View File

@@ -0,0 +1,677 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.app.rest;
import org.dspace.app.rest.model.patch.AddOperation;
import org.dspace.app.rest.model.patch.Operation;
import org.dspace.app.rest.model.patch.RemoveOperation;
import org.dspace.app.rest.model.patch.ReplaceOperation;
import org.dspace.app.rest.test.AbstractControllerIntegrationTest;
import org.dspace.builder.CollectionBuilder;
import org.dspace.builder.CommunityBuilder;
import org.dspace.builder.EPersonBuilder;
import org.dspace.builder.ItemBuilder;
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;
import org.dspace.eperson.service.SubscribeService;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
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.hasSize;
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/submissionforms endpoint
* (Class has to start or end with IT to be picked up by the failsafe plugin)
*/
public class SubscriptionRestRepositoryIT extends AbstractControllerIntegrationTest {
@Autowired
SubscribeService subscribeService;
@Autowired
SiteService siteService;
@Test
public void findAll() throws Exception {
context.turnOffAuthorisationSystem();
//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(admin.getEmail(), password);
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Test")
.withIssueDate("2010-10-17")
.withAuthor("Smith, Donald")
.withSubject("ExtraEntry")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Frequency");
subscriptionParameter.setValue("Daily");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, admin, col1, subscriptionParameterList, "TypeTest");
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
.andExpect(status().isOk())
//We expect the content type to be "application/hal+json;charset=UTF-8"
.andExpect(content().contentType(contentType))
//By default we expect at least 1 submission forms so this to be reflected in the page object
.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].type", is("TypeTest")))
.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")))
.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.startsWith(REST_SERVER_URL + "/api/core/subscriptions")));
}
@Test
public void findByIdAsAdministrator() 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(admin.getEmail(), password);
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Parameter");
subscriptionParameter.setValue("ValueParameter");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, admin, publicItem1, subscriptionParameterList, "TestType");
context.restoreAuthSystemState();
//When we call the root endpoint
getClient(token).perform(get("/api/core/subscriptions/" + subscription.getID()))
//The status has to be 200 OK
.andExpect(status().isOk())
//We expect the content type to be "application/hal+json;charset=UTF-8"
.andExpect(content().contentType(contentType))
//By default we expect at least 1 submission forms so this to be reflected in the page object
.andExpect(jsonPath("$.type", is("TestType")))
.andExpect(jsonPath("$.id", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject")))
.andExpect(jsonPath("$.subscriptionParameterList[0].name", is("Parameter")))
.andExpect(jsonPath("$.subscriptionParameterList[0].value", is("ValueParameter")))
.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")));
}
@Test
public void findByIdAsRandomUser() 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();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Parameter");
subscriptionParameter.setValue("ValueParameter");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, admin, publicItem1, subscriptionParameterList, "TestType");
context.restoreAuthSystemState();
//When we call the root endpoint
getClient(token).perform(get("/api/core/subscriptions/" + subscription.getID()))
//The status has to be 200 OK
.andExpect(status().isUnauthorized());
}
@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();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Parameter1");
subscriptionParameter.setValue("ValueParameter1");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "TestType");
context.restoreAuthSystemState();
//When we call the root endpoint
getClient(token).perform(get("/api/core/subscriptions/findByEPerson?id=" + eperson.getID()))
//The status has to be 200 OK
.andExpect(status().isOk())
//We expect the content type to be "application/hal+json;charset=UTF-8"
.andExpect(content().contentType(contentType))
//By default we expect at least 1 submission forms so this to be reflected in the page object
.andExpect(jsonPath("$.type", is("TestType")))
.andExpect(jsonPath("$.id", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject")))
.andExpect(jsonPath("$.subscriptionParameterList[0].name", is("Parameter1")))
.andExpect(jsonPath("$.subscriptionParameterList[0].value", is("ValueParameter1")))
.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")));
EPerson epersonIT = EPersonBuilder.createEPerson(context)
.withEmail("epersonIT@example.com")
.withPassword(password)
.withLanguage("al")
.build();
String epersonITtoken = getAuthToken(epersonIT.getEmail(), password);
getClient(epersonITtoken).perform(get("/api/core/subscriptions/" + subscription.getID()))
//The status has to be 200 OK
.andExpect(status().isUnauthorized());
}
@Test
public void addSubscriptionNotLoggedIn() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Parameter1");
subscriptionParameter.setValue("ValueParameter1");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "TestType");
context.restoreAuthSystemState();
//When we call the root endpoint as anonymous user
getClient().perform(post("/api/core/subscriptions"))
//The status has to be 403 Not Authorized
.andExpect(status().isUnauthorized());
}
@Test
public void addSubscriptionAsLoggedIn() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Test");
subscriptionParameter.setValue("Test");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "Type");
context.restoreAuthSystemState();
//When we call the root endpoint as anonymous user
getClient().perform(post("/api/core/subscriptions"))
//The status has to be 200 OK
.andExpect(status().isOk())
//We expect the content type to be "application/hal+json;charset=UTF-8"
.andExpect(content().contentType(contentType))
//By default we expect at least 1 submission forms so this to be reflected in the page object
.andExpect(jsonPath("$.type", is("Type")))
.andExpect(jsonPath("$.id", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject")))
.andExpect(jsonPath("$.subscriptionParameterList[0].name", is("Test")))
.andExpect(jsonPath("$.subscriptionParameterList[0].value", is("Test")))
.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")));
}
@Test
public void editSubscriptionAnonymous() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Parameter1");
subscriptionParameter.setValue("ValueParameter1");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "TestType");
context.restoreAuthSystemState();
//When we call the root endpoint as anonymous user
getClient().perform(put("/api/core/subscriptions"))
//The status has to be 403 Not Authorized
.andExpect(status().isUnauthorized());
}
@Test
public void editSubscriptionNotAsSubscriberNotAsAdmin() throws Exception {
context.turnOffAuthorisationSystem();
EPerson epersonIT = EPersonBuilder.createEPerson(context)
.withEmail("epersonIT@example.com")
.withPassword(password)
.withLanguage("al")
.build();
String epersonITtoken = getAuthToken(epersonIT.getEmail(), password);
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Parameter1");
subscriptionParameter.setValue("ValueParameter1");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "TestType");
context.restoreAuthSystemState();
//When we call the root endpoint as anonymous user
getClient(epersonITtoken).perform(put("/api/core/subscriptions"))
//The status has to be 403 Not Authorized
.andExpect(status().isUnauthorized());
}
@Test
public void editSubscriptionAsAdministratorOrSubscriber() throws Exception {
String tokenAdmin = getAuthToken(admin.getEmail(), password);
String tokenSubscriber = getAuthToken(eperson.getEmail(), password);
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Frequency");
subscriptionParameter.setValue("Daily");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "Test");
context.restoreAuthSystemState();
getClient(tokenSubscriber).perform(put("/api/core/subscriptions"))
//The status has to be 403 Not Authorized
.andExpect(status().isOk());
//When we call the root endpoint as anonymous user
getClient(tokenAdmin).perform(put("/api/core/subscriptions"))
//The status has to be 403 Not Authorized
.andExpect(status().isOk())
//We expect the content type to be "application/hal+json;charset=UTF-8"
.andExpect(content().contentType(contentType))
//By default we expect at least 1 submission forms so this to be reflected in the page object
.andExpect(jsonPath("$.type", is("Test")))
.andExpect(jsonPath("$.id", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject")))
.andExpect(jsonPath("$.subscriptionParameterList[0].name", is("Frequency")))
.andExpect(jsonPath("$.subscriptionParameterList[0].value", is("Daily")))
.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")));
}
@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);
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Frequency");
subscriptionParameter.setValue("Daily");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "Test");
context.restoreAuthSystemState();
getClient(epersonITtoken).perform(put("/api/core/subscriptions"))
//The status has to be 403 Not Authorized
.andExpect(status().isUnauthorized());
}
@Test
public void deleteSubscriptionAsAdmin() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("Frequency");
subscriptionParameter.setValue("Daily");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "Test");
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());
}
@Test
public void patchReplaceSubscriptionParameterAsAdmin() throws Exception {
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("TestName");
subscriptionParameter.setValue("TestValue");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "Test");
String token = getAuthToken(admin.getEmail(), password);
List<Operation> ops = new ArrayList<Operation>();
Map<String, String> value = new HashMap<>();
value.put("name", "frequency");
value.put("value", "monthly");
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
.andExpect(status().isOk())
//We expect the content type to be "application/hal+json;charset=UTF-8"
.andExpect(content().contentType(contentType))
//By default we expect at least 1 submission forms so this to be reflected in the page object
.andExpect(jsonPath("$.type", is("Test")))
.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.ePerson.href", Matchers.endsWith(REST_SERVER_URL + "/api/core/ePerson")));
}
@Test
public void patchSubscriptionParameterNotAsAdminNotAsSubscriber() throws Exception {
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("TestName");
subscriptionParameter.setValue("TestValue");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "Test");
List<Operation> ops = new ArrayList<Operation>();
Map<String, String> value = new HashMap<>();
value.put("name", "frequency");
value.put("value", "monthly");
ReplaceOperation replaceOperation = new ReplaceOperation("/subscriptionsParameter/"+subscription.getSubscriptionParameterList().get(0).getId(), value);
ops.add(replaceOperation);
String patchBody = getPatchContent(ops);
EPerson epersonIT = EPersonBuilder.createEPerson(context)
.withEmail("epersonIT@example.com")
.withPassword(password)
.withLanguage("al")
.build();
String epersonITtoken = getAuthToken(epersonIT.getEmail(), password);
getClient(epersonITtoken).perform(patch("/api/core/subscriptions/"+subscription.getID())
.content(patchBody)
)
//The status has to be 200 OK
.andExpect(status().isUnauthorized());
}
@Test
public void patchAddSubscriptionParameter() throws Exception {
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("TestName");
subscriptionParameter.setValue("TestValue");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "Test");
String token = getAuthToken(admin.getEmail(), password);
List<Operation> ops = new ArrayList<Operation>();
Map<String, String> value = new HashMap<>();
value.put("name", "frequency");
value.put("value", "monthly");
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
.andExpect(status().isOk())
//We expect the content type to be "application/hal+json;charset=UTF-8"
.andExpect(content().contentType(contentType))
//By default we expect at least 1 submission forms so this to be reflected in the page object
.andExpect(jsonPath("$.type", is("Test")))
.andExpect(jsonPath("$.id", Matchers.endsWith(REST_SERVER_URL + "/api/core/dSpaceObject")))
.andExpect(jsonPath("$.subscriptionParameterList[0].name", is("TestName")))
.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.ePerson.href", Matchers.endsWith(REST_SERVER_URL + "/api/core/ePerson")));
}
@Test
public void patchRemoveSubscriptionParameter() throws Exception {
context.turnOffAuthorisationSystem();
parentCommunity = CommunityBuilder.createCommunity(context)
.withName("Parent Community")
.build();
Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity)
.withName("Sub Community")
.build();
Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build();
// creation of the item which will be the DSO related with a subscription
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Item")
.withIssueDate("2020-10-17")
.withAuthor("John, Doe")
.withSubject("Test")
.build();
List<SubscriptionParameter> subscriptionParameterList = new ArrayList<>();
SubscriptionParameter subscriptionParameter = new SubscriptionParameter();
subscriptionParameter.setName("TestName");
subscriptionParameter.setValue("TestValue");
subscriptionParameterList.add(subscriptionParameter);
Subscription subscription = subscribeService.subscribe(context, eperson, publicItem1, subscriptionParameterList, "Test");
String token = getAuthToken(admin.getEmail(), password);
List<Operation> ops = new ArrayList<Operation>();
Map<String, String> value = new HashMap<>();
value.put("name", "frequency");
value.put("value", "monthly");
RemoveOperation removeOperation = new RemoveOperation("/subscriptionsParameter/"+subscription.getSubscriptionParameterList().get(0).getId());
ops.add(removeOperation);
String patchBody = getPatchContent(ops);
context.restoreAuthSystemState();
getClient(token).perform(patch("/api/core/subscriptions/"+subscription.getID())
.content(patchBody)
)
//The status has to be 403 Not Authorized
.andExpect(status().isOk())
//We expect the content type to be "application/hal+json;charset=UTF-8"
.andExpect(content().contentType(contentType))
//By default we expect at least 1 submission forms so this to be reflected in the page object
.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")));
}
}