Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ufal/be-collection2item-table-is-not-migrated #439

Merged
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
package org.dspace.app.rest.repository;

import static org.dspace.app.rest.utils.ContextUtil.obtainContext;
import static org.dspace.app.rest.utils.RegexUtils.REGEX_REQUESTMAPPING_IDENTIFIER_AS_UUID;
import static org.dspace.core.Constants.COLLECTION;

import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
Expand All @@ -27,10 +30,12 @@
import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.model.ItemRest;
import org.dspace.app.rest.model.WorkspaceItemRest;
import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils;
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.Item;
import org.dspace.content.MetadataValue;
import org.dspace.content.WorkspaceItem;
Expand All @@ -51,6 +56,8 @@
import org.dspace.workflow.WorkflowException;
import org.dspace.xmlworkflow.service.XmlWorkflowService;
import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -366,6 +373,75 @@ public ItemRest importItem(HttpServletRequest request) throws SQLException, Auth
return itemRest;
}

/**
* Endpoint for importing item's mapped collection.
* The mapping for requested endpoint, for example
* <pre>
* {@code
* https://<dspace.server.url>/api/clarin/import/item/{ITEM_UUID}/mappedCollections
* }
* </pre>
* @param request request
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
*/
@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(method = RequestMethod.POST, value = "/item" + REGEX_REQUESTMAPPING_IDENTIFIER_AS_UUID +
"/mappedCollections")
public void importItemCollections(@PathVariable UUID uuid, HttpServletRequest request) throws SQLException,
AuthorizeException, IOException {
Context context = ContextUtil.obtainContext(request);
if (Objects.isNull(context)) {
throw new RuntimeException("Context is null - cannot import item's mapped collections.");
}

// Load List of collection self links
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you mean single collection? If not, use collections

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not I think more collections, not one

List<String> requestAsStringList = new ArrayList<>();
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new InputStreamReader(request.getInputStream()));

for (Object entity : (JSONArray) obj) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe I will add some control if obj is JSONArray

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check added

String collectionSelfLink = entity.toString();
requestAsStringList.add(collectionSelfLink);
}
} catch (Exception e) {
throw new RuntimeException("Cannot import item's mapped collections because parsing of the request JSON" +
"throws this error: " + e.getMessage());
}

// Find Collections following its self link
List<DSpaceObject> listDsoFoundInRequest
= utils.constructDSpaceObjectList(context, requestAsStringList);

if (listDsoFoundInRequest.size() < 1) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe use const for 1, but as you want

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Used CollectionUtils.isEmpty(listDsoFoundInRequest) instead

throw new UnprocessableEntityException("Not a valid collection uuid.");
}

for (DSpaceObject dso : listDsoFoundInRequest) {

Item item = itemService.find(context, uuid);
if (dso != null && dso.getType() == COLLECTION && item != null) {
milanmajchrak marked this conversation as resolved.
Show resolved Hide resolved
if (this.checkIfItemIsTemplate(item)) {
continue;
}

Collection collectionToMapTo = (Collection) dso;
if (this.checkIfOwningCollection(item, collectionToMapTo.getID())) {
continue;
}

collectionService.addItem(context, collectionToMapTo, item);
collectionService.update(context, collectionToMapTo);
itemService.update(context, item);
} else {
throw new UnprocessableEntityException("Not a valid collection or item uuid.");
}
}

context.commit();
}

/**
* Convert String input value to boolean.
* @param value input value
Expand All @@ -391,4 +467,12 @@ private Integer getIntegerFromString(String value) {
}
return output;
}
}

private boolean checkIfItemIsTemplate(Item item) {
return item.getTemplateItemOf() != null;
}

private boolean checkIfOwningCollection(Item item, UUID collectionID) {
return item.getOwningCollection().getID().equals(collectionID);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are you sure that item has collection?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a check

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
Expand All @@ -33,6 +34,7 @@
import org.dspace.builder.WorkflowItemBuilder;
import org.dspace.builder.WorkspaceItemBuilder;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.content.MetadataValue;
import org.dspace.content.WorkspaceItem;
Expand Down Expand Up @@ -470,4 +472,53 @@ public void testImportAuthorityAndConfidenceInMetadata() throws Exception {
assertEquals(dcRelationValue.getAuthority(), String.valueOf(AUTHORITY));
assertEquals(dcRelationValue.getConfidence(), CONFIDENCE);
}

@Test
public void importItemsMappedCollections() throws Exception {
context.turnOffAuthorisationSystem();
//** GIVEN **
//1. A community-collection structure with one parent community with sub-community and two collections.
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();
Collection col2 = CollectionBuilder.createCollection(context, child1).withName("Collection 2").build();
Collection col3 = CollectionBuilder.createCollection(context, child1).withName("Collection 3").build();

//2. Public item that is readable by Anonymous with different subjects
Item publicItem1 = ItemBuilder.createItem(context, col1)
.withTitle("Public item 1")
.withIssueDate("2017-10-17")
.withAuthor("Smith, Donald").withAuthor("Doe, John")
.withSubject("ExtraEntry")
.build();
context.restoreAuthSystemState();

// It is owning collection
String col1SelfLink = "https://localhost:8080/spring-rest/api/core/collections/" + col1.getID();
String col2SelfLink = "https://localhost:8080/spring-rest/api/core/collections/" + col2.getID();
String col3SelfLink = "https://localhost:8080/spring-rest/api/core/collections/" + col3.getID();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use const for common parts of links

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

List<String> collectionSelfLinksList = new ArrayList<>();
collectionSelfLinksList.add(col1SelfLink);
collectionSelfLinksList.add(col2SelfLink);
collectionSelfLinksList.add(col3SelfLink);

ObjectMapper mapper = new ObjectMapper();
String token = getAuthToken(admin.getEmail(), password);

getClient(token).perform(post("/api/clarin/import/item/" +
milanmajchrak marked this conversation as resolved.
Show resolved Hide resolved
publicItem1.getID() + "/mappedCollections")
.content(mapper.writeValueAsBytes(collectionSelfLinksList))
.contentType(org.springframework.http.MediaType.APPLICATION_JSON))
.andExpect(status().isOk());

Item updatedItem = itemService.find(context, publicItem1.getID());
assertEquals(updatedItem.getCollections().size(), 3);
milanmajchrak marked this conversation as resolved.
Show resolved Hide resolved
assertTrue(updatedItem.getCollections().contains(col1));
assertTrue(updatedItem.getCollections().contains(col2));
assertTrue(updatedItem.getCollections().contains(col3));
}
}