Search in sources :

Example 46 with Filter

use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.

the class MCRMODSMetadataShareAgent method distributeMetadata.

/* (non-Javadoc)
     * @see org.mycore.datamodel.metadata.share.MCRMetadataShareAgent#inheritMetadata(org.mycore.datamodel.metadata.MCRObject)
     */
@Override
public void distributeMetadata(MCRObject holder) throws MCRPersistenceException, MCRAccessException {
    MCRMODSWrapper holderWrapper = new MCRMODSWrapper(holder);
    List<MCRMetaLinkID> children = holder.getStructure().getChildren();
    if (!children.isEmpty()) {
        LOGGER.info("Update inherited metadata");
        for (MCRMetaLinkID childIdRef : children) {
            MCRObjectID childId = childIdRef.getXLinkHrefID();
            if (MCRMODSWrapper.isSupported(childId)) {
                LOGGER.info("Update: {}", childIdRef);
                MCRObject child = MCRMetadataManager.retrieveMCRObject(childId);
                MCRMODSWrapper childWrapper = new MCRMODSWrapper(child);
                inheritToChild(holderWrapper, childWrapper);
                LOGGER.info("Saving: {}", childIdRef);
                try {
                    MCRMetadataManager.update(child);
                } catch (MCRPersistenceException | MCRAccessException e) {
                    throw new MCRPersistenceException("Error while updating inherited metadata", e);
                }
            }
        }
    }
    Collection<String> recipientIds = MCRLinkTableManager.instance().getSourceOf(holder.getId(), MCRLinkTableManager.ENTRY_TYPE_REFERENCE);
    for (String rId : recipientIds) {
        MCRObjectID recipientId = MCRObjectID.getInstance(rId);
        if (MCRMODSWrapper.isSupported(recipientId)) {
            LOGGER.info("distribute metadata to {}", rId);
            MCRObject recipient = MCRMetadataManager.retrieveMCRObject(recipientId);
            MCRMODSWrapper recipientWrapper = new MCRMODSWrapper(recipient);
            for (Element relatedItem : recipientWrapper.getLinkedRelatedItems()) {
                String holderId = relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE);
                if (holder.getId().toString().equals(holderId)) {
                    @SuppressWarnings("unchecked") Filter<Content> sharedMetadata = (Filter<Content>) Filters.element("part", MCRConstants.MODS_NAMESPACE).negate();
                    relatedItem.removeContent(sharedMetadata);
                    relatedItem.addContent(holderWrapper.getMODS().cloneContent());
                    LOGGER.info("Saving: {}", recipientId);
                    try {
                        MCRMetadataManager.update(recipient);
                    } catch (MCRPersistenceException | MCRAccessException e) {
                        throw new MCRPersistenceException("Error while updating shared metadata", e);
                    }
                }
            }
        }
    }
}
Also used : Element(org.jdom2.Element) MCRAccessException(org.mycore.access.MCRAccessException) MCRObject(org.mycore.datamodel.metadata.MCRObject) Filter(org.jdom2.filter.Filter) Content(org.jdom2.Content) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPersistenceException(org.mycore.common.MCRPersistenceException)

Example 47 with Filter

use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.

the class MCRMODSWrapper method setElement.

/**
 * Sets or adds an element with target name and value. The element name and attributes are used as xpath expression
 * to filter for an element. The attributes are used with and operation if present.
 */
public Optional<Element> setElement(String elementName, String elementValue, Map<String, String> attributes) {
    boolean isAttributeDataPresent = attributes != null && !attributes.isEmpty();
    boolean isValuePresent = elementValue != null && !elementValue.isEmpty();
    if (!isValuePresent && !isAttributeDataPresent) {
        return Optional.empty();
    }
    StringBuilder xPath = new StringBuilder("mods:");
    xPath.append(elementName);
    // add attributes to xpath with and operator
    if (isAttributeDataPresent) {
        xPath.append('[');
        Iterator<Map.Entry<String, String>> attributeIterator = attributes.entrySet().iterator();
        while (attributeIterator.hasNext()) {
            Map.Entry<String, String> attribute = attributeIterator.next();
            xPath.append('@').append(attribute.getKey()).append("='").append(attribute.getValue()).append('\'');
            if (attributeIterator.hasNext()) {
                xPath.append(" and ");
            }
        }
        xPath.append(']');
    }
    Element element = getElement(xPath.toString());
    if (element == null) {
        element = addElement(elementName);
        if (isAttributeDataPresent) {
            for (Map.Entry<String, String> entry : attributes.entrySet()) {
                element.setAttribute(entry.getKey(), entry.getValue());
            }
        }
    }
    if (isValuePresent) {
        element.setText(elementValue.trim());
    }
    return Optional.of(element);
}
Also used : MCRMetaElement(org.mycore.datamodel.metadata.MCRMetaElement) Element(org.jdom2.Element) HashMap(java.util.HashMap) Map(java.util.Map)

Example 48 with Filter

use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.

the class MCRClassificationMappingEventHandler method createMapping.

private void createMapping(MCRObject obj) {
    MCRMODSWrapper mcrmodsWrapper = new MCRMODSWrapper(obj);
    if (mcrmodsWrapper.getMODS() == null) {
        return;
    }
    // vorher alle mit generator *-mycore löschen
    mcrmodsWrapper.getElements("mods:classification[contains(@generator, '" + GENERATOR_SUFFIX + "')]").stream().forEach(Element::detach);
    LOGGER.info("check mappings {}", obj.getId());
    mcrmodsWrapper.getMcrCategoryIDs().stream().map(categoryId -> DAO.getCategory(categoryId, 0)).filter(Objects::nonNull).map(MCRClassificationMappingEventHandler::getMappings).flatMap(Collection::stream).distinct().forEach(mapping -> {
        String taskMessage = String.format(Locale.ROOT, "add mapping from '%s' to '%s'", mapping.getKey().toString(), mapping.getValue().toString());
        LOGGER.info(taskMessage);
        Element mappedClassification = mcrmodsWrapper.addElement("classification");
        String generator = getGenerator(mapping.getKey(), mapping.getValue());
        mappedClassification.setAttribute("generator", generator);
        MCRClassMapper.assignCategory(mappedClassification, mapping.getValue());
    });
    LOGGER.debug("mapping complete.");
}
Also used : Collection(java.util.Collection) MCREvent(org.mycore.common.events.MCREvent) MCRCategoryID(org.mycore.datamodel.classifications2.MCRCategoryID) MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) Collectors(java.util.stream.Collectors) MCREventHandlerBase(org.mycore.common.events.MCREventHandlerBase) MCRMODSWrapper(org.mycore.mods.MCRMODSWrapper) Objects(java.util.Objects) AbstractMap(java.util.AbstractMap) List(java.util.List) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) Locale(java.util.Locale) Map(java.util.Map) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRCategoryDAOFactory(org.mycore.datamodel.classifications2.MCRCategoryDAOFactory) Optional(java.util.Optional) MCRCategoryDAO(org.mycore.datamodel.classifications2.MCRCategoryDAO) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) MCRLabel(org.mycore.datamodel.classifications2.MCRLabel) Element(org.jdom2.Element) Element(org.jdom2.Element) Objects(java.util.Objects) Collection(java.util.Collection) MCRMODSWrapper(org.mycore.mods.MCRMODSWrapper)

Example 49 with Filter

use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.

the class MCRMODSURNPersistentIdentifierMetadataManager method getIdentifier.

@Override
public Optional<MCRPersistentIdentifier> getIdentifier(MCRBase obj, String additional) throws MCRPersistentIdentifierException {
    MCRObject object = checkObject(obj);
    MCRMODSWrapper wrapper = new MCRMODSWrapper(object);
    Element element = wrapper.getElement(MODS_IDENTIFIER_TYPE_URN);
    if (element == null) {
        return Optional.empty();
    }
    String urnText = element.getTextNormalize();
    return new MCRDNBURNParser().parse(urnText).filter(Objects::nonNull).map(MCRPersistentIdentifier.class::cast);
}
Also used : MCRObject(org.mycore.datamodel.metadata.MCRObject) Element(org.jdom2.Element) MCRMODSWrapper(org.mycore.mods.MCRMODSWrapper) MCRDNBURNParser(org.mycore.pi.urn.MCRDNBURNParser) MCRPersistentIdentifier(org.mycore.pi.MCRPersistentIdentifier)

Example 50 with Filter

use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.

the class MCRAccessCondition method lookupCategoryID.

/* (non-Javadoc)
     * @see org.mycore.mods.classification.MCRAuthorityInfo#lookupCategoryID()
     */
@Override
protected MCRCategoryID lookupCategoryID() {
    Collection<MCRCategory> categoryByURI = MCRAuthorityWithURI.getCategoryByURI(href);
    if (categoryByURI.size() > 1) {
        throw new MCRException(href + " is ambigous: " + categoryByURI.stream().map(MCRCategory::getId).collect(Collectors.toList()));
    }
    if (!categoryByURI.isEmpty()) {
        return categoryByURI.iterator().next().getId();
    }
    // maybe href is in form {authorityURI}#{categId}
    String categId, authorityURI = null;
    try {
        authorityURI = href.substring(0, href.lastIndexOf("#"));
        categId = href.substring(authorityURI.length() + 1);
    } catch (RuntimeException e) {
        LOGGER.warn("authorityURI:{}, valueURI:{}", authorityURI, href);
        return null;
    }
    int internalStylePos = authorityURI.indexOf(MCRAuthorityWithURI.CLASS_URI_PART);
    if (internalStylePos > 0) {
        String rootId = authorityURI.substring(internalStylePos + MCRAuthorityWithURI.CLASS_URI_PART.length());
        MCRCategoryID catId = new MCRCategoryID(rootId, categId);
        if (DAO.exist(catId)) {
            return catId;
        }
    }
    Collection<MCRCategory> classes = MCRAuthorityWithURI.getCategoryByURI(authorityURI);
    return classes.stream().map(cat -> new MCRCategoryID(cat.getId().getRootID(), categId)).filter(DAO::exist).findFirst().orElse(null);
}
Also used : Logger(org.apache.logging.log4j.Logger) Collection(java.util.Collection) MCRConstants(org.mycore.common.MCRConstants) MCRCategoryDAOFactory(org.mycore.datamodel.classifications2.MCRCategoryDAOFactory) MCRCategoryDAO(org.mycore.datamodel.classifications2.MCRCategoryDAO) MCRCategoryID(org.mycore.datamodel.classifications2.MCRCategoryID) MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) Collectors(java.util.stream.Collectors) LogManager(org.apache.logging.log4j.LogManager) MCRException(org.mycore.common.MCRException) Element(org.jdom2.Element) MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) MCRException(org.mycore.common.MCRException) MCRCategoryDAO(org.mycore.datamodel.classifications2.MCRCategoryDAO) MCRCategoryID(org.mycore.datamodel.classifications2.MCRCategoryID)

Aggregations

Element (org.jdom2.Element)43 Document (org.jdom2.Document)24 List (java.util.List)22 IOException (java.io.IOException)20 ArrayList (java.util.ArrayList)19 LogManager (org.apache.logging.log4j.LogManager)17 Logger (org.apache.logging.log4j.Logger)17 JDOMException (org.jdom2.JDOMException)17 Collectors (java.util.stream.Collectors)16 File (java.io.File)11 MCRException (org.mycore.common.MCRException)11 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)11 Collections (java.util.Collections)10 MCRObject (org.mycore.datamodel.metadata.MCRObject)10 Map (java.util.Map)9 MCRAccessException (org.mycore.access.MCRAccessException)9 MCRConstants (org.mycore.common.MCRConstants)9 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)9 MCRMetadataManager (org.mycore.datamodel.metadata.MCRMetadataManager)9 Files (java.nio.file.Files)8