Search in sources :

Example 41 with MCRObjectID

use of org.mycore.datamodel.metadata.MCRObjectID in project mycore by MyCoRe-Org.

the class MCRUploadHandlerIFS method getOrCreateDerivateID.

private MCRObjectID getOrCreateDerivateID() {
    if (derivateID == null) {
        String projectID = MCRObjectID.getInstance(this.documentID).getProjectId();
        MCRObjectID oid = MCRObjectID.getNextFreeId(projectID + '_' + ID_TYPE);
        this.derivateID = oid.toString();
        return oid;
    } else
        return MCRObjectID.getInstance(derivateID);
}
Also used : MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID)

Example 42 with MCRObjectID

use of org.mycore.datamodel.metadata.MCRObjectID in project mycore by MyCoRe-Org.

the class MCRBasketServlet method doGetPost.

public void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest req = job.getRequest();
    HttpServletResponse res = job.getResponse();
    String type = req.getParameter("type");
    String action = req.getParameter("action");
    String[] uris = req.getParameterValues("uri");
    String[] ids = req.getParameterValues("id");
    String redirect = getProperty(req, "redirect");
    URL referer = getReferer(req);
    boolean resolveContent = "true".equals(req.getParameter("resolve"));
    LOGGER.info("{} {} {}", action, type, ids == null ? "" : ids);
    MCRBasket basket = MCRBasketManager.getOrCreateBasketInSession(type);
    if ("add".equals(action)) {
        if (uris.length != ids.length) {
            throw new MCRException("Amount of URIs must match amount of IDs");
        }
        for (int i = 0; i < uris.length; i++) {
            MCRBasketEntry entry = new MCRBasketEntry(ids[i], uris[i]);
            basket.add(entry);
            if (resolveContent) {
                entry.resolveContent();
            }
        }
    } else if ("remove".equals(action)) {
        for (String id : ids) {
            basket.removeEntry(id);
        }
    } else if ("up".equals(action)) {
        for (String id : ids) {
            basket.up(basket.get(id));
        }
    } else if ("down".equals(action)) {
        for (String id : ids) {
            basket.down(basket.get(id));
        }
    } else if ("clear".equals(action)) {
        basket.clear();
    } else if ("create".equals(action)) {
        String ownerID = req.getParameter("ownerID");
        MCRObjectID ownerOID = MCRObjectID.getInstance(ownerID);
        MCRBasketPersistence.createDerivateWithBasket(basket, ownerOID);
    } else if ("update".equals(action)) {
        MCRBasketPersistence.updateBasket(basket);
    } else if ("retrieve".equals(action)) {
        String derivateID = req.getParameter("derivateID");
        basket = MCRBasketPersistence.retrieveBasket(derivateID);
        type = basket.getType();
        MCRBasketManager.setBasketInSession(basket);
    } else if ("comment".equals(action)) {
        Document sub = (Document) (job.getRequest().getAttribute("MCRXEditorSubmission"));
        String comment = sub.getRootElement().getChildTextTrim("comment");
        for (String id : ids) {
            basket.get(id).setComment(comment);
        }
    } else if ("show".equals(action)) {
        req.setAttribute("XSL.Style", type);
        Document xml = new MCRBasketXMLBuilder(true).buildXML(basket);
        getLayoutService().doLayout(req, res, new MCRJDOMContent(xml));
        return;
    }
    if (referer != null && "referer".equals(redirect)) {
        res.sendRedirect(res.encodeRedirectURL(referer.toExternalForm()));
    } else if (redirect != null) {
        res.sendRedirect(res.encodeRedirectURL(redirect));
    } else {
        res.sendRedirect(res.encodeRedirectURL(getServletBaseURL() + "MCRBasketServlet?action=show&type=" + type));
    }
}
Also used : MCRException(org.mycore.common.MCRException) MCRJDOMContent(org.mycore.common.content.MCRJDOMContent) HttpServletResponse(javax.servlet.http.HttpServletResponse) Document(org.jdom2.Document) URL(java.net.URL) HttpServletRequest(javax.servlet.http.HttpServletRequest) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID)

Example 43 with MCRObjectID

use of org.mycore.datamodel.metadata.MCRObjectID in project mycore by MyCoRe-Org.

the class MCRIFSCommands method checkDerivatesWithProjectIDInMCRFSNODES.

@MCRCommand(syntax = "check mcrfsnodes of derivates with project id {0}", help = "check the entries of MCRFSNODES with project ID {0} that the derivate exists")
public static void checkDerivatesWithProjectIDInMCRFSNODES(String project_id) {
    LOGGER.info("Start check of MCRFSNODES for derivates with project ID {}", project_id);
    if (project_id == null || project_id.length() == 0) {
        LOGGER.error("Project ID missed for check MCRFSNODES entries of derivates with project ID {0}");
        return;
    }
    MCRXMLMetadataManager mgr = MCRXMLMetadataManager.instance();
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<String> query = cb.createQuery(String.class);
    Root<MCRFSNODES> nodes = query.from(MCRFSNODES.class);
    AtomicInteger counter = new AtomicInteger();
    em.createQuery(query.distinct(true).select(nodes.get(MCRFSNODES_.owner)).where(cb.like(nodes.get(MCRFSNODES_.owner), project_id + "\\_%"))).getResultList().stream().peek(ignore -> counter.incrementAndGet()).map(MCRObjectID::getInstance).filter(derID -> {
        try {
            return !mgr.exists(derID);
        } catch (IOException e) {
            LOGGER.error("Error while checking existence of {}", derID, e);
            return true;
        }
    }).forEach(missingDerivate -> LOGGER.error("   !!!! Can't find MCRFSNODES entry {} as existing derivate", missingDerivate));
    LOGGER.info("Check done for {} entries", counter.get());
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Transformer(javax.xml.transform.Transformer) Arrays(java.util.Arrays) Date(java.util.Date) StreamResult(javax.xml.transform.stream.StreamResult) FileTime(java.nio.file.attribute.FileTime) MCRStreamQuery(org.mycore.backend.jpa.MCRStreamQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Map(java.util.Map) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) MCRXMLMetadataManager(org.mycore.datamodel.common.MCRXMLMetadataManager) MCRFSNODES(org.mycore.backend.hibernate.tables.MCRFSNODES) URI(java.net.URI) Method(java.lang.reflect.Method) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) ParameterExpression(javax.persistence.criteria.ParameterExpression) GregorianCalendar(java.util.GregorianCalendar) TimeZone(java.util.TimeZone) StandardOpenOption(java.nio.file.StandardOpenOption) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Objects(java.util.Objects) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) MCRUtils(org.mycore.common.MCRUtils) List(java.util.List) Attributes2Impl(org.xml.sax.ext.Attributes2Impl) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRFilesystemNode(org.mycore.datamodel.ifs.MCRFilesystemNode) SAXException(org.xml.sax.SAXException) MCRContentStoreFactory(org.mycore.datamodel.ifs.MCRContentStoreFactory) Session(org.hibernate.Session) MCRConfiguration(org.mycore.common.config.MCRConfiguration) TypedQuery(javax.persistence.TypedQuery) MCRException(org.mycore.common.MCRException) MessageFormat(java.text.MessageFormat) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) MCRFSNODES_(org.mycore.backend.hibernate.tables.MCRFSNODES_) Charset(java.nio.charset.Charset) MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory) MCRContentStore(org.mycore.datamodel.ifs.MCRContentStore) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) MCRCommandGroup(org.mycore.frontend.cli.annotation.MCRCommandGroup) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) Root(javax.persistence.criteria.Root) MCRFile(org.mycore.datamodel.ifs.MCRFile) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) NotDirectoryException(java.nio.file.NotDirectoryException) MCRHIBConnection(org.mycore.backend.hibernate.MCRHIBConnection) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) EntityManager(javax.persistence.EntityManager) OutputKeys(javax.xml.transform.OutputKeys) Field(java.lang.reflect.Field) File(java.io.File) NameFileComparator(org.apache.commons.io.comparator.NameFileComparator) TransformerHandler(javax.xml.transform.sax.TransformerHandler) LogManager(org.apache.logging.log4j.LogManager) EntityManager(javax.persistence.EntityManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MCRXMLMetadataManager(org.mycore.datamodel.common.MCRXMLMetadataManager) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) IOException(java.io.IOException) MCRFSNODES(org.mycore.backend.hibernate.tables.MCRFSNODES) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 44 with MCRObjectID

use of org.mycore.datamodel.metadata.MCRObjectID in project mycore by MyCoRe-Org.

the class MCRDOICommands method synchronizeDatabase.

@MCRCommand(syntax = "repair registered dois {0}", help = "Contacts the Registration Service and inserts all registered DOIs to the Database. It also updates all media files. The Service ID{0} is the id from the configuration.", order = 10)
public static void synchronizeDatabase(String serviceID) {
    MCRDOIRegistrationService registrationService = new MCRDOIRegistrationService(serviceID);
    try {
        MCRDataciteClient dataciteClient = registrationService.getDataciteClient();
        List<MCRDigitalObjectIdentifier> doiList = dataciteClient.getDOIList();
        doiList.stream().filter(doi -> {
            boolean isTestDOI = doi.getPrefix().equals(MCRDigitalObjectIdentifier.TEST_DOI_PREFIX);
            return !isTestDOI || registrationService.usesTestPrefix();
        }).forEach(doi -> {
            try {
                URI uri = dataciteClient.resolveDOI(doi);
                if (uri.toString().startsWith(registrationService.getRegisterURL())) {
                    LOGGER.info("Checking DOI: {}", doi.asString());
                    MCRObjectID objectID = getObjectID(uri);
                    if (MCRMetadataManager.exists(objectID)) {
                        if (!registrationService.isRegistered(objectID, "")) {
                            LOGGER.info("DOI is not registered in MyCoRe. Add to Database: {}", doi.asString());
                            MCRPI databaseEntry = new MCRPI(doi.asString(), registrationService.getType(), objectID.toString(), "", serviceID, new Date());
                            MCRHIBConnection.instance().getSession().save(databaseEntry);
                        }
                        // Update main files
                        MCRObject obj = MCRMetadataManager.retrieveMCRObject(objectID);
                        List<Map.Entry<String, URI>> entryList = registrationService.getMediaList(obj);
                        dataciteClient.setMediaList(doi, entryList);
                    } else {
                        LOGGER.info("Could not find Object : {}", objectID);
                    }
                } else {
                    LOGGER.info("DOI/URL is not from this application: {}/{}", doi.asString(), uri);
                }
            } catch (MCRPersistentIdentifierException e) {
                LOGGER.error("Error occurred for DOI: {}", doi, e);
            }
        });
    } catch (MCRPersistentIdentifierException e) {
        LOGGER.error("Error while receiving DOI list from Registration-Service!", e);
    }
}
Also used : MCRDOIParser(org.mycore.pi.doi.MCRDOIParser) Date(java.util.Date) HashMap(java.util.HashMap) MCRException(org.mycore.common.MCRException) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) MCRPI(org.mycore.pi.backend.MCRPI) MCRIdentifierUnresolvableException(org.mycore.pi.exceptions.MCRIdentifierUnresolvableException) Map(java.util.Map) URI(java.net.URI) MCRCommandGroup(org.mycore.frontend.cli.annotation.MCRCommandGroup) MCRAccessException(org.mycore.access.MCRAccessException) MCRDataciteClient(org.mycore.pi.doi.MCRDataciteClient) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) MCRHIBConnection(org.mycore.backend.hibernate.MCRHIBConnection) Collectors(java.util.stream.Collectors) MCRDOIRegistrationService(org.mycore.pi.doi.MCRDOIRegistrationService) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRDigitalObjectIdentifier(org.mycore.pi.doi.MCRDigitalObjectIdentifier) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRActiveLinkException(org.mycore.datamodel.common.MCRActiveLinkException) MCRPersistentIdentifierMetadataManager(org.mycore.pi.MCRPersistentIdentifierMetadataManager) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) MCRPI(org.mycore.pi.backend.MCRPI) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) URI(java.net.URI) Date(java.util.Date) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRDigitalObjectIdentifier(org.mycore.pi.doi.MCRDigitalObjectIdentifier) MCRDOIRegistrationService(org.mycore.pi.doi.MCRDOIRegistrationService) MCRDataciteClient(org.mycore.pi.doi.MCRDataciteClient) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 45 with MCRObjectID

use of org.mycore.datamodel.metadata.MCRObjectID in project mycore by MyCoRe-Org.

the class MCRPersistentIdentifierRegistrationResource method register.

@POST
@Path("service/{serviceName}/{mycoreId}")
@Produces(MediaType.APPLICATION_JSON)
public Response register(@PathParam("serviceName") String serviceName, @PathParam("mycoreId") String mycoreId, @DefaultValue("") @QueryParam("additional") String additional) {
    if (!MCRPIRegistrationServiceManager.getInstance().getServiceIDList().contains(serviceName)) {
        return Response.status(Response.Status.BAD_REQUEST).entity(buildErrorJSON("No Registration Service found for " + serviceName)).build();
    }
    MCRPIRegistrationService<MCRPersistentIdentifier> registrationService = MCRPIRegistrationServiceManager.getInstance().getRegistrationService(serviceName);
    MCRObjectID mycoreIDObject;
    try {
        mycoreIDObject = MCRObjectID.getInstance(mycoreId);
    } catch (MCRException e) {
        LOGGER.error(e);
        return Response.status(Response.Status.BAD_REQUEST).entity(buildErrorJSON("The provided id " + mycoreId + " seems to be invalid!", e)).build();
    }
    MCRPersistentIdentifier identifier;
    MCRBase object = MCRMetadataManager.retrieve(mycoreIDObject);
    try {
        identifier = registrationService.register(object, additional, true);
    } catch (MCRPersistentIdentifierException | MCRActiveLinkException e) {
        LOGGER.error(e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(buildErrorJSON("Error while register new identifier!", e)).build();
    } catch (MCRAccessException e) {
        LOGGER.error(e);
        return Response.status(Response.Status.FORBIDDEN).entity(buildErrorJSON("Error while register new identifier!", e)).build();
    }
    return Response.status(Response.Status.CREATED).entity(buildIdentifierObject(identifier)).build();
}
Also used : MCRException(org.mycore.common.MCRException) MCRActiveLinkException(org.mycore.datamodel.common.MCRActiveLinkException) MCRAccessException(org.mycore.access.MCRAccessException) MCRBase(org.mycore.datamodel.metadata.MCRBase) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPersistentIdentifier(org.mycore.pi.MCRPersistentIdentifier) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Aggregations

MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)144 IOException (java.io.IOException)37 MCRObject (org.mycore.datamodel.metadata.MCRObject)32 MCRException (org.mycore.common.MCRException)30 MCRCommand (org.mycore.frontend.cli.annotation.MCRCommand)30 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)29 MCRPath (org.mycore.datamodel.niofs.MCRPath)25 MCRAccessException (org.mycore.access.MCRAccessException)22 Document (org.jdom2.Document)20 MCRPersistenceException (org.mycore.common.MCRPersistenceException)18 MCRMetaLinkID (org.mycore.datamodel.metadata.MCRMetaLinkID)16 JDOMException (org.jdom2.JDOMException)15 MCRBase (org.mycore.datamodel.metadata.MCRBase)15 SAXException (org.xml.sax.SAXException)15 Date (java.util.Date)14 MCRActiveLinkException (org.mycore.datamodel.common.MCRActiveLinkException)13 MCRSession (org.mycore.common.MCRSession)11 MCRContent (org.mycore.common.content.MCRContent)11 MCRPersistentIdentifierException (org.mycore.pi.exceptions.MCRPersistentIdentifierException)11 URISyntaxException (java.net.URISyntaxException)10