Search in sources :

Example 6 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRObjectUtils method restore.

/**
 * Restores a MyCoRe Object to the selected revision. Please note that children and derivates
 * are not deleted or reverted!
 *
 * @param mcrId the mycore object identifier
 * @param revision The revision to restore to. If this is lower than zero, the last revision is used.
 * @return the new {@link MCRObject}
 *
 * @throws IOException An error occurred while retrieving the revision information. This is most
 *          likely due an svn error.
 * @throws MCRPersistenceException There is no such object with the given id and revision.
 * @throws ClassCastException The returning type must be the same as the type of the restored object
 */
public static <T extends MCRBase> T restore(MCRObjectID mcrId, Long revision) throws IOException, MCRPersistenceException {
    @SuppressWarnings("unchecked") T mcrBase = (T) (mcrId.getTypeId().equals("derivate") ? new MCRDerivate() : new MCRObject());
    // get content
    MCRXMLMetadataManager xmlMetadataManager = MCRXMLMetadataManager.instance();
    MCRContent content = xmlMetadataManager.retrieveContent(mcrId, revision);
    if (content == null) {
        throw new MCRPersistenceException("No such object " + mcrId + " with revision " + revision + ".");
    }
    // store it
    try {
        mcrBase.setFromJDOM(content.asXML());
        if (MCRMetadataManager.exists(mcrId)) {
            MCRMetadataManager.update(mcrBase);
        } else {
            if (mcrBase instanceof MCRObject) {
                MCRMetadataManager.create((MCRObject) mcrBase);
            } else {
                MCRMetadataManager.create((MCRDerivate) mcrBase);
            }
        }
        return mcrBase;
    } catch (Exception exc) {
        throw new MCRException("Unable to get object " + mcrId + " with revision " + revision + ".", exc);
    }
}
Also used : MCRException(org.mycore.common.MCRException) MCRXMLMetadataManager(org.mycore.datamodel.common.MCRXMLMetadataManager) MCRContent(org.mycore.common.content.MCRContent) MCRPersistenceException(org.mycore.common.MCRPersistenceException) MCRPersistenceException(org.mycore.common.MCRPersistenceException) IOException(java.io.IOException) MCRException(org.mycore.common.MCRException)

Example 7 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRFileMetaEventHandler method handlePathDeleted.

@Override
protected void handlePathDeleted(MCREvent evt, Path path, BasicFileAttributes attrs) {
    if (attrs.isDirectory()) {
        return;
    }
    MCRPath mcrPath = MCRPath.toMCRPath(path);
    MCRObjectID derivateID = MCRObjectID.getInstance(mcrPath.getOwner());
    if (!MCRMetadataManager.exists(derivateID)) {
        LOGGER.warn("Derivate {} from file '{}' does not exist.", derivateID, path);
        return;
    }
    MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
    MCRObjectDerivate objectDerivate = derivate.getDerivate();
    if (objectDerivate.deleteFileMetaData('/' + path.subpath(0, path.getNameCount()).toString())) {
        try {
            MCRMetadataManager.update(derivate);
        } catch (MCRPersistenceException | MCRAccessException e) {
            throw new MCRPersistenceException("Could not update derivate: " + derivateID, e);
        }
    }
}
Also used : MCRAccessException(org.mycore.access.MCRAccessException) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRPersistenceException(org.mycore.common.MCRPersistenceException)

Example 8 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRVersioningMetadataStore method verify.

/**
 * Checks to local SVN repository for errors
 * @throws MCRPersistenceException if 'svn verify' fails
 */
public void verify() throws MCRPersistenceException {
    String replURLStr = repURL.toString();
    if (!repURL.getProtocol().equals("file")) {
        LOGGER.warn("Cannot verify non local SVN repository '{}'.", replURLStr);
        return;
    }
    try {
        SVNRepository repository = getRepository();
        long latestRevision = repository.getLatestRevision();
        if (latestRevision == 0) {
            LOGGER.warn("Cannot verify SVN repository '{}' with no revisions.", replURLStr);
        }
        ISVNAuthenticationManager authenticationManager = repository.getAuthenticationManager();
        SVNAdminClient adminClient = new SVNAdminClient(authenticationManager, null);
        File repositoryRoot = new File(URI.create(replURLStr));
        adminClient.setEventHandler(new ISVNAdminEventHandler() {

            // if more than batchSize revisions print progress
            int batchSize = 100;

            @Override
            public void checkCancelled() throws SVNCancelException {
            }

            @Override
            public void handleEvent(SVNEvent event, double progress) throws SVNException {
            }

            @Override
            public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException {
                if (event.getMessage() != null) {
                    if (event.getRevision() % batchSize != 0 || event.getRevision() == 0) {
                        LOGGER.debug(event::getMessage);
                    } else {
                        LOGGER.info("{} ({}% done)", event.getMessage(), (int) (event.getRevision() * 100.0 / latestRevision));
                    }
                }
            }
        });
        adminClient.doVerify(repositoryRoot);
        LOGGER.info("Verified SVN repository '{}'.", replURLStr);
    } catch (Exception e) {
        throw new MCRPersistenceException("SVN repository contains errors and could not be verified: " + replURLStr, e);
    }
}
Also used : ISVNAuthenticationManager(org.tmatesoft.svn.core.auth.ISVNAuthenticationManager) SVNAdminEvent(org.tmatesoft.svn.core.wc.admin.SVNAdminEvent) SVNException(org.tmatesoft.svn.core.SVNException) URISyntaxException(java.net.URISyntaxException) MCRConfigurationException(org.mycore.common.config.MCRConfigurationException) JDOMException(org.jdom2.JDOMException) SVNCancelException(org.tmatesoft.svn.core.SVNCancelException) SVNException(org.tmatesoft.svn.core.SVNException) MCRPersistenceException(org.mycore.common.MCRPersistenceException) IOException(java.io.IOException) ISVNAdminEventHandler(org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler) SVNCancelException(org.tmatesoft.svn.core.SVNCancelException) SVNEvent(org.tmatesoft.svn.core.wc.SVNEvent) SVNRepository(org.tmatesoft.svn.core.io.SVNRepository) SVNAdminClient(org.tmatesoft.svn.core.wc.admin.SVNAdminClient) File(java.io.File) MCRPersistenceException(org.mycore.common.MCRPersistenceException)

Example 9 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRRestAPIUploadHelper method uploadFile.

/**
 * uploads a file into a given derivate
 * @param info - the Jersey UriInfo object
 * @param request - the HTTPServletRequest object
 * @param pathParamMcrObjID - a MyCoRe Object ID
 * @param pathParamMcrDerID - a MyCoRe Derivate ID
 * @param uploadedInputStream - the inputstream from HTTP Post request
 * @param fileDetails - the file information from HTTP Post request
 * @param formParamPath - the path of the file inside the derivate
 * @param formParamMaindoc - true, if this file should be marked as maindoc
 * @param formParamUnzip - true, if the upload is zip file that should be unzipped inside the derivate
 * @param formParamMD5 - the MD5 sum of the uploaded file
 * @param formParamSize - the size of the uploaded file
 * @return a Jersey Response object
 * @throws MCRRestAPIException
 */
public static Response uploadFile(UriInfo info, HttpServletRequest request, String pathParamMcrObjID, String pathParamMcrDerID, InputStream uploadedInputStream, FormDataContentDisposition fileDetails, String formParamPath, boolean formParamMaindoc, boolean formParamUnzip, String formParamMD5, Long formParamSize) throws MCRRestAPIException {
    SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
    SortedMap<String, String> parameter = new TreeMap<>();
    parameter.put("mcrObjectID", pathParamMcrObjID);
    parameter.put("mcrDerivateID", pathParamMcrDerID);
    parameter.put("path", formParamPath);
    parameter.put("maindoc", Boolean.toString(formParamMaindoc));
    parameter.put("unzip", Boolean.toString(formParamUnzip));
    parameter.put("md5", formParamMD5);
    parameter.put("size", Long.toString(formParamSize));
    String base64Signature = request.getHeader("X-MyCoRe-RestAPI-Signature");
    if (base64Signature == null) {
        throw new MCRRestAPIException(Status.UNAUTHORIZED, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION, "The submitted data could not be validated.", "Please provide a signature as HTTP header 'X-MyCoRe-RestAPI-Signature'."));
    }
    if (verifyPropertiesWithSignature(parameter, base64Signature, MCRJSONWebTokenUtil.retrievePublicKeyFromAuthenticationToken(signedJWT))) {
        try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
            // MCRSession session = MCRServlet.getSession(request);
            MCRSession session = MCRSessionMgr.getCurrentSession();
            MCRUserInformation currentUser = session.getUserInformation();
            MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
            session.setUserInformation(apiUser);
            MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
            MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
            MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
            if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
                MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
                java.nio.file.Path derDir = null;
                String path = null;
                if (der.getOwnerID().equals(objID)) {
                    try {
                        derDir = UPLOAD_DIR.resolve(derID.toString());
                        if (Files.exists(derDir)) {
                            Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
                        }
                        path = formParamPath.replace("\\", "/").replace("../", "");
                        while (path.startsWith("/")) {
                            path = path.substring(1);
                        }
                        MCRDirectory difs = MCRDirectory.getRootDirectory(derID.toString());
                        if (difs == null) {
                            difs = new MCRDirectory(derID.toString());
                        }
                        der.getDerivate().getInternals().setIFSID(difs.getID());
                        der.getDerivate().getInternals().setSourcePath(derDir.toString());
                        if (formParamUnzip) {
                            String maindoc = null;
                            try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(uploadedInputStream))) {
                                ZipEntry entry;
                                while ((entry = zis.getNextEntry()) != null) {
                                    LOGGER.debug("Unzipping: {}", entry.getName());
                                    java.nio.file.Path target = derDir.resolve(entry.getName());
                                    Files.createDirectories(target.getParent());
                                    Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
                                    if (maindoc == null && !entry.isDirectory()) {
                                        maindoc = entry.getName();
                                    }
                                }
                            } catch (IOException e) {
                                LOGGER.error(e);
                            }
                            MCRFileImportExport.importFiles(derDir.toFile(), difs);
                            if (formParamMaindoc) {
                                der.getDerivate().getInternals().setMainDoc(maindoc);
                            }
                        } else {
                            java.nio.file.Path saveFile = derDir.resolve(path);
                            Files.createDirectories(saveFile.getParent());
                            Files.copy(uploadedInputStream, saveFile, StandardCopyOption.REPLACE_EXISTING);
                            // delete old file
                            MCRFileImportExport.importFiles(derDir.toFile(), difs);
                            if (formParamMaindoc) {
                                der.getDerivate().getInternals().setMainDoc(path);
                            }
                        }
                        MCRMetadataManager.update(der);
                        Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
                    } catch (IOException | MCRPersistenceException | MCRAccessException e) {
                        LOGGER.error(e);
                        throw new MCRRestAPIException(Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Internal error", e.getMessage()));
                    }
                }
                session.setUserInformation(currentUser);
                return Response.created(info.getBaseUriBuilder().path("v1/objects/" + objID + "/derivates/" + derID + "/contents").build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
            }
        }
    }
    throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_DATA, "File upload failed.", "The submitted data could not be validated."));
}
Also used : MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) ZipEntry(java.util.zip.ZipEntry) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) MCRAccessException(org.mycore.access.MCRAccessException) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) TreeMap(java.util.TreeMap) ZipInputStream(java.util.zip.ZipInputStream) MCRSession(org.mycore.common.MCRSession) MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory) BufferedInputStream(java.io.BufferedInputStream) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRUserInformation(org.mycore.common.MCRUserInformation) MCRPersistenceException(org.mycore.common.MCRPersistenceException)

Example 10 with MCRPersistenceException

use of org.mycore.common.MCRPersistenceException in project mycore by MyCoRe-Org.

the class MCRSolrPathDocumentFactory method getDocument.

/**
 * Generates a {@link SolrInputDocument} from a {@link MCRPath} instance.
 *
 * @see MCRSolrFileIndexHandler
 * @see MCRSolrFilesIndexHandler
 * @see MCRSolrIndexHandlerFactory
 */
public SolrInputDocument getDocument(Path input, BasicFileAttributes attr) throws IOException, MCRPersistenceException {
    SolrInputDocument doc = new SolrInputDocument();
    Consumer<? super MCRSolrFileIndexAccumulator> accumulate = (accumulator) -> {
        LOGGER.debug("{} accumulates {}", accumulator, input);
        try {
            accumulator.accumulate(doc, input, attr);
        } catch (IOException e) {
            LOGGER.error("Error in Accumulator!", e);
        }
    };
    ACCUMULATOR_LIST.forEach(accumulate);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("MCRFile {} transformed to:\n{}", input, doc);
    }
    return doc;
}
Also used : MCRSolrFilesIndexHandler(org.mycore.solr.index.handlers.stream.MCRSolrFilesIndexHandler) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRPersistenceException(org.mycore.common.MCRPersistenceException) IOException(java.io.IOException) MCRConfiguration(org.mycore.common.config.MCRConfiguration) MCRSolrFileIndexHandler(org.mycore.solr.index.handlers.stream.MCRSolrFileIndexHandler) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) MCRConfigurationException(org.mycore.common.config.MCRConfigurationException) Consumer(java.util.function.Consumer) List(java.util.List) Logger(org.apache.logging.log4j.Logger) CONFIG_PREFIX(org.mycore.solr.MCRSolrConstants.CONFIG_PREFIX) MCRSolrIndexHandlerFactory(org.mycore.solr.index.handlers.MCRSolrIndexHandlerFactory) Path(java.nio.file.Path) LogManager(org.apache.logging.log4j.LogManager) SolrInputDocument(org.apache.solr.common.SolrInputDocument) SolrInputDocument(org.apache.solr.common.SolrInputDocument) IOException(java.io.IOException)

Aggregations

MCRPersistenceException (org.mycore.common.MCRPersistenceException)36 IOException (java.io.IOException)18 MCRAccessException (org.mycore.access.MCRAccessException)13 JDOMException (org.jdom2.JDOMException)9 MCRActiveLinkException (org.mycore.datamodel.common.MCRActiveLinkException)8 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)8 MCRPath (org.mycore.datamodel.niofs.MCRPath)8 MCRException (org.mycore.common.MCRException)7 SAXException (org.xml.sax.SAXException)6 File (java.io.File)5 PersistenceException (javax.persistence.PersistenceException)5 Path (java.nio.file.Path)4 UncheckedIOException (java.io.UncheckedIOException)3 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)3 Date (java.util.Date)3 EntityManager (javax.persistence.EntityManager)3 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)3 MCRMetaLinkID (org.mycore.datamodel.metadata.MCRMetaLinkID)3 SignedJWT (com.nimbusds.jwt.SignedJWT)2 PrintWriter (java.io.PrintWriter)2