Search in sources :

Example 16 with MetadataValue

use of org.dspace.content.MetadataValue in project DSpace by DSpace.

the class DescribeStep method readField.

private void readField(InProgressSubmission obj, SubmissionStepConfig config, DataDescribe data, DCInputSet inputConfig) throws DCInputsReaderException {
    String documentTypeValue = "";
    List<MetadataValue> documentType = itemService.getMetadataByMetadataString(obj.getItem(), configurationService.getProperty("submit.type-bind.field", "dc.type"));
    if (documentType.size() > 0) {
        documentTypeValue = documentType.get(0).getValue();
    }
    // Get list of all field names (including qualdrop names) allowed for this dc.type
    List<String> allowedFieldNames = inputConfig.populateAllowedFieldNames(documentTypeValue);
    // Loop input rows and process submitted metadata
    for (DCInput[] row : inputConfig.getFields()) {
        for (DCInput input : row) {
            List<String> fieldsName = new ArrayList<String>();
            if (input.isQualdropValue()) {
                for (Object qualifier : input.getPairs()) {
                    fieldsName.add(input.getFieldName() + "." + (String) qualifier);
                }
            } else {
                fieldsName.add(input.getFieldName());
            }
            for (String fieldName : fieldsName) {
                List<MetadataValue> mdv = itemService.getMetadataByMetadataString(obj.getItem(), fieldName);
                for (MetadataValue md : mdv) {
                    MetadataValueRest dto = new MetadataValueRest();
                    dto.setAuthority(md.getAuthority());
                    dto.setConfidence(md.getConfidence());
                    dto.setLanguage(md.getLanguage());
                    dto.setPlace(md.getPlace());
                    dto.setValue(md.getValue());
                    String[] metadataToCheck = Utils.tokenize(md.getMetadataField().toString());
                    if (data.getMetadata().containsKey(Utils.standardize(metadataToCheck[0], metadataToCheck[1], metadataToCheck[2], "."))) {
                        // all values for this field
                        if (allowedFieldNames.contains(fieldName)) {
                            data.getMetadata().get(Utils.standardize(md.getMetadataField().getMetadataSchema().getName(), md.getMetadataField().getElement(), md.getMetadataField().getQualifier(), ".")).add(dto);
                        } else {
                            data.getMetadata().remove(Utils.standardize(metadataToCheck[0], metadataToCheck[1], metadataToCheck[2], "."));
                        }
                    } else {
                        // Add values only if allowed by type bind
                        if (allowedFieldNames.contains(fieldName)) {
                            List<MetadataValueRest> listDto = new ArrayList<>();
                            listDto.add(dto);
                            data.getMetadata().put(Utils.standardize(md.getMetadataField().getMetadataSchema().getName(), md.getMetadataField().getElement(), md.getMetadataField().getQualifier(), "."), listDto);
                        }
                    }
                }
            }
        }
    }
}
Also used : MetadataValue(org.dspace.content.MetadataValue) ArrayList(java.util.ArrayList) MetadataValueRest(org.dspace.app.rest.model.MetadataValueRest) DCInput(org.dspace.app.util.DCInput)

Example 17 with MetadataValue

use of org.dspace.content.MetadataValue in project DSpace by DSpace.

the class ExtractMetadataStep method doPostProcessing.

@Override
public void doPostProcessing(Context context, InProgressSubmission wsi) {
    Map<String, List<MetadataValue>> metadataMapValue = metadataMap.get();
    Set<String> changedMetadata = getChangedMetadata(wsi.getItem(), listener.getMetadataToListen(), metadataMapValue);
    // are listened metadata changed?
    try {
        if (!changedMetadata.isEmpty()) {
            ExternalDataObject obj = listener.getExternalDataObject(context, wsi.getItem(), changedMetadata);
            if (obj != null) {
                // add metadata to the item if no values are already here
                Set<String> alreadyFilledMetadata = new HashSet();
                for (MetadataValue mv : wsi.getItem().getMetadata()) {
                    alreadyFilledMetadata.add(mv.getMetadataField().toString('.'));
                }
                for (MetadataValueDTO metadataValue : obj.getMetadata()) {
                    StringJoiner joiner = new StringJoiner(".");
                    joiner.add(metadataValue.getSchema());
                    joiner.add(metadataValue.getElement());
                    if (StringUtils.isNoneBlank(metadataValue.getQualifier())) {
                        joiner.add(metadataValue.getQualifier());
                    }
                    if (!alreadyFilledMetadata.contains(joiner.toString())) {
                        itemService.addMetadata(context, wsi.getItem(), metadataValue.getSchema(), metadataValue.getElement(), metadataValue.getQualifier(), null, metadataValue.getValue());
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : MetadataValue(org.dspace.content.MetadataValue) ExternalDataObject(org.dspace.external.model.ExternalDataObject) ArrayList(java.util.ArrayList) List(java.util.List) MetadataValueDTO(org.dspace.content.dto.MetadataValueDTO) StringJoiner(java.util.StringJoiner) IOException(java.io.IOException) HashSet(java.util.HashSet)

Example 18 with MetadataValue

use of org.dspace.content.MetadataValue in project DSpace by DSpace.

the class MetadataValidation method validate.

@Override
public List<ErrorRest> validate(SubmissionService submissionService, InProgressSubmission obj, SubmissionStepConfig config) throws DCInputsReaderException, SQLException {
    List<ErrorRest> errors = new ArrayList<>();
    String documentTypeValue = "";
    DCInputSet inputConfig = getInputReader().getInputsByFormName(config.getId());
    List<MetadataValue> documentType = itemService.getMetadataByMetadataString(obj.getItem(), configurationService.getProperty("submit.type-bind.field", "dc.type"));
    if (documentType.size() > 0) {
        documentTypeValue = documentType.get(0).getValue();
    }
    // Get list of all field names (including qualdrop names) allowed for this dc.type
    List<String> allowedFieldNames = inputConfig.populateAllowedFieldNames(documentTypeValue);
    // Begin the actual validation loop
    for (DCInput[] row : inputConfig.getFields()) {
        for (DCInput input : row) {
            String fieldKey = metadataAuthorityService.makeFieldKey(input.getSchema(), input.getElement(), input.getQualifier());
            boolean isAuthorityControlled = metadataAuthorityService.isAuthorityControlled(fieldKey);
            List<String> fieldsName = new ArrayList<String>();
            if (input.isQualdropValue()) {
                boolean foundResult = false;
                List<Object> inputPairs = input.getPairs();
                // values are also in the list and before the stored values.
                for (int i = 1; i < inputPairs.size(); i += 2) {
                    String fullFieldname = input.getFieldName() + "." + (String) inputPairs.get(i);
                    List<MetadataValue> mdv = itemService.getMetadataByMetadataString(obj.getItem(), fullFieldname);
                    // then remove. This includes field name without qualifier.
                    if (!input.isAllowedFor(documentTypeValue) && (!allowedFieldNames.contains(fullFieldname) && !allowedFieldNames.contains(input.getFieldName()))) {
                        itemService.removeMetadataValues(ContextUtil.obtainCurrentRequestContext(), obj.getItem(), mdv);
                    } else {
                        validateMetadataValues(mdv, input, config, isAuthorityControlled, fieldKey, errors);
                        if (mdv.size() > 0 && input.isVisible(DCInput.SUBMISSION_SCOPE)) {
                            foundResult = true;
                        }
                    }
                }
                if (input.isRequired() && !foundResult) {
                    // for this required qualdrop no value was found, add to the list of error fields
                    addError(errors, ERROR_VALIDATION_REQUIRED, "/" + WorkspaceItemRestRepository.OPERATION_PATH_SECTIONS + "/" + config.getId() + "/" + input.getFieldName());
                }
            } else {
                fieldsName.add(input.getFieldName());
            }
            for (String fieldName : fieldsName) {
                boolean valuesRemoved = false;
                List<MetadataValue> mdv = itemService.getMetadataByMetadataString(obj.getItem(), fieldName);
                if (!input.isAllowedFor(documentTypeValue)) {
                    // then remove. Otherwise, do not
                    if (!(allowedFieldNames.contains(fieldName))) {
                        itemService.removeMetadataValues(ContextUtil.obtainCurrentRequestContext(), obj.getItem(), mdv);
                        valuesRemoved = true;
                        log.debug("Stripping metadata values for " + input.getFieldName() + " on type " + documentTypeValue + " as it is allowed by another input of the same field " + "name");
                    } else {
                        log.debug("Not removing unallowed metadata values for " + input.getFieldName() + " on type " + documentTypeValue + " as it is allowed by another input of the same field " + "name");
                    }
                }
                validateMetadataValues(mdv, input, config, isAuthorityControlled, fieldKey, errors);
                if ((input.isRequired() && mdv.size() == 0) && input.isVisible(DCInput.SUBMISSION_SCOPE) && !valuesRemoved) {
                    // input that is also allowed for this document type
                    if (input.isAllowedFor(documentTypeValue)) {
                        // since this field is missing add to list of error
                        // fields
                        addError(errors, ERROR_VALIDATION_REQUIRED, "/" + WorkspaceItemRestRepository.OPERATION_PATH_SECTIONS + "/" + config.getId() + "/" + input.getFieldName());
                    }
                }
            }
        }
    }
    return errors;
}
Also used : MetadataValue(org.dspace.content.MetadataValue) DCInputSet(org.dspace.app.util.DCInputSet) ArrayList(java.util.ArrayList) ErrorRest(org.dspace.app.rest.model.ErrorRest) DCInput(org.dspace.app.util.DCInput)

Example 19 with MetadataValue

use of org.dspace.content.MetadataValue in project DSpace by DSpace.

the class ItemMetadataValueAddPatchOperation method add.

@Override
void add(Context context, HttpServletRequest currentRequest, InProgressSubmission source, String path, Object value) throws SQLException {
    String[] split = getAbsolutePath(path).split("/");
    // if split size is one so we have a call to initialize or replace
    if (split.length == 1) {
        List<MetadataValueRest> list = evaluateArrayObject((LateObjectEvaluator) value);
        replaceValue(context, source.getItem(), split[0], list);
    } else {
        // call with "-" or "index-based" we should receive only single
        // object member
        MetadataValueRest object = evaluateSingleObject((LateObjectEvaluator) value);
        // check if is not empty
        List<MetadataValue> metadataByMetadataString = itemService.getMetadataByMetadataString(source.getItem(), split[0]);
        Assert.notEmpty(metadataByMetadataString);
        if (split.length > 1) {
            String controlChar = split[1];
            switch(controlChar) {
                case "-":
                    addValue(context, source.getItem(), split[0], object, -1);
                    break;
                default:
                    // index based
                    int index = Integer.parseInt(controlChar);
                    if (index > metadataByMetadataString.size()) {
                        throw new IllegalArgumentException("The specified index MUST NOT be greater than the number of elements in the array");
                    }
                    addValue(context, source.getItem(), split[0], object, index);
                    break;
            }
        }
    }
}
Also used : RelationshipMetadataValue(org.dspace.content.RelationshipMetadataValue) MetadataValue(org.dspace.content.MetadataValue) MetadataValueRest(org.dspace.app.rest.model.MetadataValueRest)

Example 20 with MetadataValue

use of org.dspace.content.MetadataValue in project DSpace by DSpace.

the class ItemMetadataValueAddPatchOperation method replaceValue.

protected void replaceValue(Context context, Item source, String target, List<MetadataValueRest> list) throws SQLException {
    String[] metadata = Utils.tokenize(target);
    // fetch pre-existent metadata
    List<MetadataValue> preExistentMetadata = getDSpaceObjectService().getMetadata(source, metadata[0], metadata[1], metadata[2], Item.ANY);
    // fetch pre-existent relationships
    Map<Integer, Relationship> preExistentRelationships = preExistentRelationships(context, preExistentMetadata);
    // clear all plain metadata
    getDSpaceObjectService().clearMetadata(context, source, metadata[0], metadata[1], metadata[2], Item.ANY);
    // remove all deleted relationships
    for (Relationship rel : preExistentRelationships.values()) {
        try {
            Optional<MetadataValueRest> stillPresent = list.stream().filter(ll -> ll.getAuthority() != null && rel.getID().equals(getRelId(ll.getAuthority()))).findAny();
            if (stillPresent.isEmpty()) {
                relationshipService.delete(context, rel);
            }
        } catch (AuthorizeException e) {
            e.printStackTrace();
            throw new RuntimeException("Authorize Exception during relationship deletion.");
        }
    }
    // create plain metadata / move relationships in the list order
    // if a virtual value is present in the list, it must be present in preExistentRelationships too.
    // (with this operator virtual value can only be moved or deleted).
    int idx = 0;
    for (MetadataValueRest ll : list) {
        if (StringUtils.startsWith(ll.getAuthority(), Constants.VIRTUAL_AUTHORITY_PREFIX)) {
            Optional<MetadataValue> preExistentMv = preExistentMetadata.stream().filter(mvr -> StringUtils.equals(ll.getAuthority(), mvr.getAuthority())).findFirst();
            if (!preExistentMv.isPresent()) {
                throw new UnprocessableEntityException("Relationship with authority=" + ll.getAuthority() + " not found");
            }
            final RelationshipMetadataValue rmv = (RelationshipMetadataValue) preExistentMv.get();
            final Relationship rel = preExistentRelationships.get(rmv.getRelationshipId());
            this.updateRelationshipPlace(context, source, idx, rel);
        } else {
            getDSpaceObjectService().addMetadata(context, source, metadata[0], metadata[1], metadata[2], ll.getLanguage(), ll.getValue(), ll.getAuthority(), ll.getConfidence(), idx);
        }
        idx++;
    }
}
Also used : MetadataValueRest(org.dspace.app.rest.model.MetadataValueRest) RelationshipMetadataValue(org.dspace.content.RelationshipMetadataValue) Item(org.dspace.content.Item) MetadataValue(org.dspace.content.MetadataValue) ItemService(org.dspace.content.service.ItemService) AuthorizeException(org.dspace.authorize.AuthorizeException) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Relationship(org.dspace.content.Relationship) StringUtils(org.apache.commons.lang3.StringUtils) UnprocessableEntityException(org.dspace.app.rest.exception.UnprocessableEntityException) InProgressSubmission(org.dspace.content.InProgressSubmission) LateObjectEvaluator(org.dspace.app.rest.model.patch.LateObjectEvaluator) Constants(org.dspace.core.Constants) SQLException(java.sql.SQLException) List(java.util.List) HttpServletRequest(javax.servlet.http.HttpServletRequest) Logger(org.apache.logging.log4j.Logger) Context(org.dspace.core.Context) Map(java.util.Map) Utils(org.dspace.core.Utils) Optional(java.util.Optional) RelationshipService(org.dspace.content.service.RelationshipService) Assert(org.springframework.util.Assert) RelationshipMetadataValue(org.dspace.content.RelationshipMetadataValue) MetadataValue(org.dspace.content.MetadataValue) UnprocessableEntityException(org.dspace.app.rest.exception.UnprocessableEntityException) RelationshipMetadataValue(org.dspace.content.RelationshipMetadataValue) AuthorizeException(org.dspace.authorize.AuthorizeException) MetadataValueRest(org.dspace.app.rest.model.MetadataValueRest) Relationship(org.dspace.content.Relationship)

Aggregations

MetadataValue (org.dspace.content.MetadataValue)140 Item (org.dspace.content.Item)45 ArrayList (java.util.ArrayList)39 SQLException (java.sql.SQLException)29 MetadataField (org.dspace.content.MetadataField)22 Test (org.junit.Test)21 Date (java.util.Date)16 Collection (org.dspace.content.Collection)16 IOException (java.io.IOException)15 AuthorizeException (org.dspace.authorize.AuthorizeException)13 List (java.util.List)11 Community (org.dspace.content.Community)11 WorkspaceItem (org.dspace.content.WorkspaceItem)11 MetadataValueRest (org.dspace.app.rest.model.MetadataValueRest)10 DCDate (org.dspace.content.DCDate)9 MetadataSchema (org.dspace.content.MetadataSchema)9 EPerson (org.dspace.eperson.EPerson)9 WorkflowItem (org.dspace.workflow.WorkflowItem)9 AbstractUnitTest (org.dspace.AbstractUnitTest)8 AbstractEntityIntegrationTest (org.dspace.app.rest.test.AbstractEntityIntegrationTest)8