diff --git a/entity-management-common/src/main/java/eu/europeana/entitymanagement/common/config/EntityManagementConfiguration.java b/entity-management-common/src/main/java/eu/europeana/entitymanagement/common/config/EntityManagementConfiguration.java index b564aee3..316906c0 100644 --- a/entity-management-common/src/main/java/eu/europeana/entitymanagement/common/config/EntityManagementConfiguration.java +++ b/entity-management-common/src/main/java/eu/europeana/entitymanagement/common/config/EntityManagementConfiguration.java @@ -76,6 +76,9 @@ public class EntityManagementConfiguration { @Value("${auth.enabled: true}") private boolean authEnabled; + @Value("${enrichmentMigrationPassword}") + private String enrichmentsMigrationPassword; + public EntityManagementConfiguration() { LOG.info("Initializing EntityManagementConfiguration bean as: configuration"); @@ -167,4 +170,8 @@ public boolean shouldComputeMetrics() { public boolean isAuthEnabled() { return authEnabled; } + + public String getEnrichmentsMigrationPassword() { + return enrichmentsMigrationPassword; + } } diff --git a/entity-management-web/src/integration-test/java/eu/europeana/entitymanagement/web/BaseMvcTestUtils.java b/entity-management-web/src/integration-test/java/eu/europeana/entitymanagement/web/BaseMvcTestUtils.java index f17bbbdd..a1068a3e 100644 --- a/entity-management-web/src/integration-test/java/eu/europeana/entitymanagement/web/BaseMvcTestUtils.java +++ b/entity-management-web/src/integration-test/java/eu/europeana/entitymanagement/web/BaseMvcTestUtils.java @@ -19,6 +19,8 @@ public class BaseMvcTestUtils { public static final String CONCEPT_DATA_RECONCELIATION_XML = "/metis-deref/concept-data-reconceliation.xml"; public static final String CONCEPT_METIS_BATHTUB = "/metis-deref/concept-metis-bathtub.xml"; public static final String CONCEPT_XML = "/metis-deref/concept.xml"; + public static final String VALID_MIGRATION_ID = "http://www.wikidata.org/entity/testing"; + public static final String INVALID_MIGRATION_ID = "http://www.testing.org/entity/testing"; public static String getEntityIdentifier(String result) throws JSONException { String id = getEntityId(result); diff --git a/entity-management-web/src/integration-test/java/eu/europeana/entitymanagement/web/EntityAdminControllerIT.java b/entity-management-web/src/integration-test/java/eu/europeana/entitymanagement/web/EntityAdminControllerIT.java index 026b2d52..4778e2d0 100644 --- a/entity-management-web/src/integration-test/java/eu/europeana/entitymanagement/web/EntityAdminControllerIT.java +++ b/entity-management-web/src/integration-test/java/eu/europeana/entitymanagement/web/EntityAdminControllerIT.java @@ -5,6 +5,7 @@ import eu.europeana.entitymanagement.common.config.AppConfigConstants; import eu.europeana.entitymanagement.definitions.model.Concept; import eu.europeana.entitymanagement.definitions.model.EntityRecord; +import eu.europeana.entitymanagement.vocabulary.EntityTypes; import eu.europeana.entitymanagement.web.service.EntityRecordService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -17,6 +18,7 @@ import org.springframework.http.MediaType; import org.springframework.mock.web.MockServletContext; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @@ -25,7 +27,11 @@ import static eu.europeana.entitymanagement.testutils.BaseMvcTestUtils.*; import static eu.europeana.entitymanagement.testutils.BaseMvcTestUtils.BASE_SERVICE_URL; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** @@ -79,7 +85,7 @@ void permanentDeletionShouldBeSuccessful() throws Exception { String requestPath = getEntityRequestPath(record.getEntityId()); - mockMvc.perform(post(BASE_SERVICE_URL + "/" + requestPath + BASE_ADMIN_URL) + mockMvc.perform(delete(BASE_SERVICE_URL + "/" + requestPath + BASE_ADMIN_URL) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); @@ -87,4 +93,68 @@ void permanentDeletionShouldBeSuccessful() throws Exception { Optional dbRecordOptional = entityRecordService.retrieveEntityRecordByUri(record.getEntityId()); Assertions.assertTrue(dbRecordOptional.isEmpty()); } + + @Test + void migrationExistingEntityShouldBeSuccessful() throws Exception { + String requestBody = "{\"id\" : \"" + BaseMvcTestUtils.VALID_MIGRATION_ID + "\"}"; + String entityId = EntityRecordUtils.buildEntityIdUri("concept", "1"); + ResultActions results = mockMvc.perform(post(BASE_SERVICE_URL + "/{type}/{identifier}" + BASE_ADMIN_URL, "concept", "1") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isAccepted()); + + results.andExpect(jsonPath("$.id", any(String.class))) + .andExpect(jsonPath("$.type", is(EntityTypes.Concept.name()))) + .andExpect(jsonPath("$.isAggregatedBy").isNotEmpty()) + .andExpect(jsonPath("$.isAggregatedBy.aggregates", hasSize(2))) + // should have Europeana and Datasource proxies + .andExpect(jsonPath("$.proxies", hasSize(2))); + + // check that record is present + Optional dbRecordOptional = entityRecordService.retrieveEntityRecordByUri(entityId); + Assertions.assertFalse(dbRecordOptional.isEmpty()); + + entityRecordService.delete(entityId); + } + + @Test + void migrationExistingEntityInvalidEntityType() throws Exception { + String requestBody = "{\"id\" : \"" + BaseMvcTestUtils.VALID_MIGRATION_ID + "\"}"; + mockMvc.perform(post(BASE_SERVICE_URL + "/{type}/{identifier}" + BASE_ADMIN_URL, "testing", "1") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isInternalServerError()); + } + + @Test + void migrationExistingEntityInvalidDataSource() throws Exception { + String requestBody = "{\"id\" : \"" + BaseMvcTestUtils.INVALID_MIGRATION_ID + "\"}"; + mockMvc.perform(post(BASE_SERVICE_URL + "/{type}/{identifier}" + BASE_ADMIN_URL, "concept", "1") + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()); + } + + @Test + void migrationExistingEntityAlreadyExist() throws Exception { + String requestBody = "{\"id\" : \"" + BaseMvcTestUtils.VALID_MIGRATION_ID + "\"}"; + // create entity already + Concept concept = objectMapper.readValue(loadFile(CONCEPT_JSON), Concept.class); + EntityRecord entityRecord = new EntityRecord(); + entityRecord.setEntity(concept); + entityRecord.setEntityId(concept.getEntityId()); + EntityRecord record = entityRecordService.saveEntityRecord(entityRecord); + + System.out.println(record.getEntityId()); + String requestPath = getEntityRequestPath(record.getEntityId()); + System.out.println(requestPath); + + mockMvc.perform(post(BASE_SERVICE_URL + requestPath + BASE_ADMIN_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()); + + entityRecordService.delete(record.getEntityId()); + + } } diff --git a/entity-management-web/src/main/java/eu/europeana/entitymanagement/exception/EntityAlreadyExistsException.java b/entity-management-web/src/main/java/eu/europeana/entitymanagement/exception/EntityAlreadyExistsException.java new file mode 100644 index 00000000..d80b8fc3 --- /dev/null +++ b/entity-management-web/src/main/java/eu/europeana/entitymanagement/exception/EntityAlreadyExistsException.java @@ -0,0 +1,34 @@ +package eu.europeana.entitymanagement.exception; + + +import eu.europeana.api.commons.error.EuropeanaApiException; +import org.springframework.http.HttpStatus; + +/** + * Exception thrown when a entity already exists + */ +public class EntityAlreadyExistsException extends EuropeanaApiException { + + private static final long serialVersionUID = -2506967519765835153L; + + public EntityAlreadyExistsException(String entityUri) { + super("Entity already exists for '" + entityUri + "' found"); + } + + @Override + public boolean doLog() { + return false; + } + + + @Override + public HttpStatus getResponseStatus() { + return HttpStatus.BAD_REQUEST; + } + + + @Override + public boolean doLogStacktrace() { + return false; + } +} diff --git a/entity-management-web/src/main/java/eu/europeana/entitymanagement/exception/EntityCreationException.java b/entity-management-web/src/main/java/eu/europeana/entitymanagement/exception/EntityCreationException.java index a6de26c8..83297f26 100644 --- a/entity-management-web/src/main/java/eu/europeana/entitymanagement/exception/EntityCreationException.java +++ b/entity-management-web/src/main/java/eu/europeana/entitymanagement/exception/EntityCreationException.java @@ -1,6 +1,7 @@ package eu.europeana.entitymanagement.exception; import eu.europeana.api.commons.error.EuropeanaApiException; +import org.springframework.http.HttpStatus; /** * Exception thrown for all errors that occur while creating or saving an entity to the database @@ -18,4 +19,21 @@ public EntityCreationException(String msg) { public EntityCreationException(String msg, Throwable th) { super(msg); } + + /** + * @return boolean indicating whether this type of exception should be logged or not + */ + @Override + public boolean doLog() { + return true; + } + + public boolean logStacktrace() { + return false; + } + + @Override + public HttpStatus getResponseStatus() { + return HttpStatus.BAD_REQUEST; + } } diff --git a/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/BaseRest.java b/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/BaseRest.java index 35bd1278..dc711df3 100644 --- a/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/BaseRest.java +++ b/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/BaseRest.java @@ -1,11 +1,14 @@ package eu.europeana.entitymanagement.web; +import eu.europeana.api.commons.web.http.HttpHeaders; +import eu.europeana.entitymanagement.definitions.model.Aggregation; import eu.europeana.entitymanagement.exception.EntityCreationException; import eu.europeana.entitymanagement.web.service.EntityObjectFactory; import eu.europeana.entitymanagement.web.xml.model.RdfBaseWrapper; import eu.europeana.entitymanagement.web.xml.model.XmlBaseEntityImpl; import javax.annotation.Resource; +import org.apache.commons.codec.digest.DigestUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -19,6 +22,10 @@ import eu.europeana.entitymanagement.serialization.EntityXmlSerializer; import eu.europeana.entitymanagement.vocabulary.FormatTypes; import eu.europeana.entitymanagement.web.service.AuthorizationService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.Date; public abstract class BaseRest extends BaseRestController { @@ -83,4 +90,51 @@ protected String serialize(EntityRecord entityRecord, FormatTypes format, String return responseBody; } + /** + * Generates serialised EntityRecord Response entity along with + * Http status and headers + * + * @param profile + * @param outFormat + * @param contentType + * @param entityRecord + * @param status + * @return + * @throws EntityCreationException + */ + public ResponseEntity generateResponseEntity(String profile, FormatTypes outFormat, + String contentType, EntityRecord entityRecord, HttpStatus status) + throws EntityCreationException { + + Aggregation isAggregatedBy = entityRecord.getEntity().getIsAggregatedBy(); + + long timestamp = isAggregatedBy != null ? + isAggregatedBy.getModified().getTime() : + 0L; + + String etag = computeEtag(timestamp, outFormat.name(), getApiVersion()); + + org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders(); + headers.add(HttpHeaders.ALLOW, HttpHeaders.ALLOW_GET); + if (!outFormat.equals(FormatTypes.schema)) { + headers.add(HttpHeaders.VARY, HttpHeaders.ACCEPT); + headers.add(HttpHeaders.LINK, HttpHeaders.VALUE_LDP_RESOURCE); + } + if (contentType != null && !contentType.isEmpty()) + headers.add(HttpHeaders.CONTENT_TYPE, contentType); + + String body = serialize(entityRecord, outFormat, profile); + return ResponseEntity.status(status).headers(headers).eTag(etag).body(body); + } + + + /** + * Generates a unique hex string based on the input params + * TODO: move logic to {@link eu.europeana.api.commons.web.controller.BaseRestController#generateETag(Date, String, String)} + */ + public String computeEtag(long timestamp, String format, String version){ + return DigestUtils.md5Hex(String.format("%s:%s:%s", timestamp, format, version)); + } + + } diff --git a/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/EMController.java b/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/EMController.java index e63b57e5..e31968d4 100644 --- a/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/EMController.java +++ b/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/EMController.java @@ -289,31 +289,6 @@ private ResponseEntity createResponse(String profile, String type, Strin return generateResponseEntity(profile, outFormat, contentType, entityRecord, HttpStatus.OK); } - private ResponseEntity generateResponseEntity(String profile, FormatTypes outFormat, - String contentType, EntityRecord entityRecord, HttpStatus status) - throws EntityCreationException { - - Aggregation isAggregatedBy = entityRecord.getEntity().getIsAggregatedBy(); - - long timestamp = isAggregatedBy != null ? - isAggregatedBy.getModified().getTime() : - 0L; - - String etag = computeEtag(timestamp, outFormat.name(), getApiVersion()); - - org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders(); - headers.add(HttpHeaders.ALLOW, HttpHeaders.ALLOW_GET); - if (!outFormat.equals(FormatTypes.schema)) { - headers.add(HttpHeaders.VARY, HttpHeaders.ACCEPT); - headers.add(HttpHeaders.LINK, HttpHeaders.VALUE_LDP_RESOURCE); - } - if (contentType != null && !contentType.isEmpty()) - headers.add(HttpHeaders.CONTENT_TYPE, contentType); - - String body = serialize(entityRecord, outFormat, profile); - return ResponseEntity.status(status).headers(headers).eTag(etag).body(body); - } - private ResponseEntity launchTaskAndRetrieveEntity(String type, String identifier, EntityRecord entityRecord, String profile) throws Exception { // launch synchronous update, then retrieve entity from DB afterwards @@ -360,12 +335,4 @@ private String getDatabaseIdentifier(String entityId) { //entity id is "http://data.europeana.eu/{type}/{identifier}" return entityId.substring(entityId.lastIndexOf("/") + 1); } - - /** - * Generates a unique hex string based on the input params - * TODO: move logic to {@link eu.europeana.api.commons.web.controller.BaseRestController#generateETag(Date, String, String)} - */ - private String computeEtag(long timestamp, String format, String version){ - return DigestUtils.md5Hex(String.format("%s:%s:%s", timestamp, format, version)); - } } diff --git a/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/EntityAdminController.java b/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/EntityAdminController.java index 9d0c6037..6d3fd007 100644 --- a/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/EntityAdminController.java +++ b/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/EntityAdminController.java @@ -2,18 +2,25 @@ import eu.europeana.api.commons.definitions.vocabulary.CommonApiConstants; import eu.europeana.api.commons.error.EuropeanaApiException; +import eu.europeana.api.commons.web.exception.ApplicationAuthenticationException; import eu.europeana.api.commons.web.exception.HttpException; +import eu.europeana.api.commons.web.http.HttpHeaders; import eu.europeana.api.commons.web.model.vocabulary.Operations; import eu.europeana.entitymanagement.common.config.EntityManagementConfiguration; import eu.europeana.entitymanagement.definitions.model.EntityRecord; +import eu.europeana.entitymanagement.vocabulary.EntityProfile; +import eu.europeana.entitymanagement.vocabulary.FormatTypes; import eu.europeana.entitymanagement.vocabulary.WebEntityConstants; +import eu.europeana.entitymanagement.web.model.EntityPreview; import eu.europeana.entitymanagement.web.service.EntityRecordService; import io.swagger.annotations.ApiOperation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.util.StringUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @@ -57,4 +64,58 @@ public ResponseEntity deleteEntity( entityRecordService.delete(entityRecord.getEntityId()); return ResponseEntity.noContent().build(); } + + /** + * Migrate existing Entity + * + * @param wskey + * @param type type of entity + * @param identifier entity id + * @param request + * @return + * @throws HttpException + */ + @ApiOperation(value = "Migrate existing Entity", nickname = "migrateExistingEntity", response = java.lang.Void.class) + @PostMapping(value = "/{type}/{identifier}/management",produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity migrateExistingEntity( + @RequestParam(value = CommonApiConstants.PARAM_WSKEY, required = false) String wskey, + @PathVariable(value = WebEntityConstants.PATH_PARAM_TYPE) String type, + @PathVariable(value = WebEntityConstants.PATH_PARAM_IDENTIFIER) String identifier, + @RequestBody EntityPreview entityCreationRequest, + HttpServletRequest request) throws HttpException, EuropeanaApiException { + if (emConfig.isAuthEnabled()) { + //TODO later change the verification method once DB migration is done + // verifyWriteAccess(Operations.CREATE, request); + verifyMigrationAccess(request); + } + // camel case the type to match enum Constants + type = StringUtils.capitalize(type); + LOG.debug("Migrating existing entity: {}", entityCreationRequest.getId()); + + EntityRecord savedEntityRecord = entityRecordService + .createEntityFromMigrationRequest(entityCreationRequest, type, identifier); + LOG.debug("Created Entity record for {}; entityId={}", entityCreationRequest.getId(), savedEntityRecord.getEntityId()); + return generateResponseEntity(EntityProfile.internal.toString(), FormatTypes.jsonld, null, savedEntityRecord, HttpStatus.ACCEPTED); + } + + /** + * Method will authenticate Migration requests. + * This is done to avoid the expiration of tokens + * + * TODO remove after DB migration + * + * @param request + * @throws ApplicationAuthenticationException + */ + private void verifyMigrationAccess(HttpServletRequest request) throws ApplicationAuthenticationException { + String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); + if (!StringUtils.hasLength(authorization) || !authorization.startsWith("Bearer")) { + throw new ApplicationAuthenticationException("User is not authorised to perform this action", null); + } + + // Authorization header is "Bearer " + if (!authorization.substring(7).equals(emConfig.getEnrichmentsMigrationPassword())) { + throw new ApplicationAuthenticationException("Invalid token for migrating existing entity", null, null, HttpStatus.FORBIDDEN); + } + } } diff --git a/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/service/EntityRecordService.java b/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/service/EntityRecordService.java index a3357a06..f4bdf654 100644 --- a/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/service/EntityRecordService.java +++ b/entity-management-web/src/main/java/eu/europeana/entitymanagement/web/service/EntityRecordService.java @@ -10,19 +10,14 @@ import static eu.europeana.entitymanagement.web.EntityRecordUtils.getIsAggregatedById; import eu.europeana.api.commons.error.EuropeanaApiException; +import eu.europeana.enrichment.utils.EntityType; +import eu.europeana.entitymanagement.definitions.exceptions.UnsupportedEntityTypeException; +import eu.europeana.entitymanagement.exception.EntityAlreadyExistsException; import eu.europeana.entitymanagement.exception.EntityNotFoundException; import eu.europeana.entitymanagement.exception.EntityRemovedException; import eu.europeana.entitymanagement.web.EntityRecordUtils; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; @@ -147,7 +142,55 @@ public long delete(String entityId) { return entityRecordRepository.deleteForGood(entityId); } - /** + /** + * Creates an {@link EntityRecord} from an {@link EntityPreview}, which is then + * persisted. + * Note : This method is used for creating Entity for Migration requests + * + * @param entityCreationRequest + * @param type type of entity + * @param identifier id of entity + * @return Saved Entity record + * @throws EntityCreationException if an error occurs + */ + public EntityRecord createEntityFromMigrationRequest(EntityPreview entityCreationRequest, String type, String identifier) + throws EntityCreationException, EntityAlreadyExistsException { + // Fail quick if no datasource is configured + Optional externalDatasourceOptional = datasources.getDatasource(entityCreationRequest.getId()); + if (externalDatasourceOptional.isEmpty()) { + throw new EntityCreationException("No configured datasource for entity " + entityCreationRequest.getId()); + } + + Date timestamp = new Date(); + Entity entity = EntityObjectFactory.createEntityObject(type); + EntityRecord entityRecord = new EntityRecord(); + String entityId = generateEntityId(entity.getType(), identifier); + // check if entity already exists + // this is avoid MongoDb exception for duplicate key + checkIfEntityAlreadyExists(entityId); + + entityRecord.setEntityId(entityId); + entity.setEntityId(entityId); + entityRecord.setEntity(entity); + + Entity europeanaProxyMetadata = EntityObjectFactory.createEntityObject(type); + // copy metadata from request into entity + europeanaProxyMetadata.setEntityId(entityId); + europeanaProxyMetadata.setType(type); + copyPreviewMetadata(europeanaProxyMetadata, entityCreationRequest); + setEuropeanaMetadata(europeanaProxyMetadata, entityId, entityRecord, timestamp); + + // create metis Entity + Entity metisEntity = EntityObjectFactory.createEntityObject(type); + + DataSource externalDatasource = externalDatasourceOptional.get(); + setExternalProxyMetadata(metisEntity, entityCreationRequest, entityId, externalDatasource, entityRecord, timestamp); + + setEntityAggregation(entityRecord, entityId, timestamp); + return entityRecordRepository.save(entityRecord); + } + + /** * Creates an {@link EntityRecord} from an {@link EntityPreview}, which is then * persisted. * @@ -161,14 +204,14 @@ public EntityRecord createEntityFromRequest(EntityPreview entityCreationRequest, // Fail quick if no datasource is configured Optional externalDatasourceOptional = datasources.getDatasource(entityCreationRequest.getId()); if (externalDatasourceOptional.isEmpty()) { - throw new EntityCreationException("No configured datasource for entity " + entityCreationRequest.getId()); + throw new EntityCreationException("No configured datasource for entity " + entityCreationRequest.getId()); } Date timestamp = new Date(); Entity entity = EntityObjectFactory.createEntityObject(metisResponse.getType()); EntityRecord entityRecord = new EntityRecord(); - String entityId = generateEntityId(entity.getType()); + String entityId = generateEntityId(entity.getType(), null); entityRecord.setEntityId(entityId); entity.setEntityId(entityId); entityRecord.setEntity(entity); @@ -190,6 +233,18 @@ public EntityRecord createEntityFromRequest(EntityPreview entityCreationRequest, } + /** + * Checks if Entity already exists + * @param entityId + * @throws EntityAlreadyExistsException + */ + private void checkIfEntityAlreadyExists(String entityId) throws EntityAlreadyExistsException { + Optional entityRecordOptional = retrieveEntityRecordByUri(entityId); + if (!entityRecordOptional.isEmpty()) { + throw new EntityAlreadyExistsException(entityId); + } + } + /** * Copies metadata provided during Entity creation, into the created Entity * @param entity entity @@ -202,9 +257,24 @@ private void copyPreviewMetadata(Entity entity, EntityPreview entityCreationRequ entity.setDepiction(entityCreationRequest.getDepiction()); } - private String generateEntityId(String entityType) { - long dbId = entityRecordRepository.generateAutoIncrement(entityType); - return EntityRecordUtils.buildEntityIdUri(entityType, String.valueOf(dbId)); + /** + * generates the EntityId + * If entityId is present, generate entity id uri with entityId + * else generates a auto increment id + * ex: http://data.europeana.eu// + * OR http://data.europeana.eu// + * + * @param entityType + * @param entityId + * @return + */ + private String generateEntityId(String entityType, String entityId) { + if (entityId != null) { + return EntityRecordUtils.buildEntityIdUri(entityType, entityId); + } else { + long dbId = entityRecordRepository.generateAutoIncrement(entityType); + return EntityRecordUtils.buildEntityIdUri(entityType, String.valueOf(dbId)); + } } /** diff --git a/entity-management-web/src/main/resources/entitymanagement.properties b/entity-management-web/src/main/resources/entitymanagement.properties index b09d2603..7bc26fd8 100644 --- a/entity-management-web/src/main/resources/entitymanagement.properties +++ b/entity-management-web/src/main/resources/entitymanagement.properties @@ -63,4 +63,7 @@ mongo.enrichment.database = enrichment europeana.apikey.serviceurl= # Useful for local development. If false, unauthenticated requests can be sent to API -auth.enabled=false \ No newline at end of file +auth.enabled=false + +#token for migration +enrichmentMigrationPassword = \ No newline at end of file