Search in sources :

Example 6 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRRestAPIObjectsHelper method listDerivateContentAsXML.

private static Document listDerivateContentAsXML(MCRDerivate derObj, String path, int depth, UriInfo info) throws IOException {
    Document doc = new Document();
    MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
    root = MCRPath.toMCRPath(root.resolve(path));
    if (depth == -1) {
        depth = Integer.MAX_VALUE;
    }
    if (root != null) {
        Element eContents = new Element("contents");
        eContents.setAttribute("mycoreobject", derObj.getOwnerID().toString());
        eContents.setAttribute("mycorederivate", derObj.getId().toString());
        doc.addContent(eContents);
        if (!path.endsWith("/")) {
            path += "/";
        }
        MCRPath p = MCRPath.getPath(derObj.getId().toString(), path);
        if (p != null && Files.exists(p)) {
            Element eRoot = MCRPathXML.getDirectoryXML(p).getRootElement();
            eContents.addContent(eRoot.detach());
            createXMLForSubdirectories(p, eRoot, 1, depth);
        }
        // add href Attributes
        String baseURL = MCRJerseyUtil.getBaseURL(info) + MCRConfiguration.instance().getString("MCR.RestAPI.v1.Files.URL.path");
        baseURL = baseURL.replace("${mcrid}", derObj.getOwnerID().toString()).replace("${derid}", derObj.getId().toString());
        XPathExpression<Element> xp = XPathFactory.instance().compile(".//child[@type='file']", Filters.element());
        for (Element e : xp.evaluate(eContents)) {
            String uri = e.getChildText("uri");
            if (uri != null) {
                int pos = uri.lastIndexOf(":/");
                String subPath = uri.substring(pos + 2);
                while (subPath.startsWith("/")) {
                    subPath = path.substring(1);
                }
                e.setAttribute("href", baseURL + subPath);
            }
        }
    }
    return doc;
}
Also used : Element(org.jdom2.Element) Document(org.jdom2.Document) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 7 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRRestAPIUploadHelper method deleteAllFiles.

/**
 * deletes all files inside a given derivate
 * @param info - the Jersey UriInfo object
 * @param request - the HTTPServletRequest object
 * @param pathParamMcrObjID - the MyCoRe Object ID
 * @param pathParamMcrDerID - the MyCoRe Derivate ID
 * @return a Jersey Response Object
 * @throws MCRRestAPIException
 */
public static Response deleteAllFiles(UriInfo info, HttpServletRequest request, String pathParamMcrObjID, String pathParamMcrDerID) throws MCRRestAPIException {
    Response response = Response.status(Status.INTERNAL_SERVER_ERROR).build();
    SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
    SortedMap<String, String> parameter = new TreeMap<>();
    parameter.put("mcrObjectID", pathParamMcrObjID);
    parameter.put("mcrDerivateID", pathParamMcrDerID);
    String base64Signature = request.getHeader("X-MyCoRe-RestAPI-Signature");
    if (base64Signature == null) {
    // ToDo error handling
    }
    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.checkPermission uses CACHE, which seems to be dirty from other calls
            MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
            if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
                MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
                final MCRPath rootPath = MCRPath.getPath(der.getId().toString(), "/");
                try {
                    Files.walkFileTree(rootPath, MCRRecursiveDeleter.instance());
                    Files.createDirectory(rootPath);
                } catch (IOException e) {
                    LOGGER.error(e);
                }
            }
            session.setUserInformation(currentUser);
            response = 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();
        }
    } else {
        throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_DATA, "Delete failed.", "The submitted data could not be validated."));
    }
    return response;
}
Also used : MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) TreeMap(java.util.TreeMap) Response(javax.ws.rs.core.Response) MCRSession(org.mycore.common.MCRSession) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRUserInformation(org.mycore.common.MCRUserInformation)

Example 8 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRJSONFileVisitor method writePathInfo.

private void writePathInfo(Path path, BasicFileAttributes attrs) throws IOException {
    MCRPath mcrPath = MCRPath.toMCRPath(path);
    MCRPath relativePath = mcrPath.getRoot().relativize(mcrPath);
    boolean isRoot = mcrPath.getNameCount() == 0;
    jw.name("type").value(attrs.isDirectory() ? "directory" : "file");
    if (isRoot) {
        jw.name("mycoreobject").value(objId);
        jw.name("mycorederivate").value(mcrPath.getOwner());
    }
    jw.name("name").value(isRoot ? "" : mcrPath.getFileName().toString());
    jw.name("path").value(attrs.isDirectory() ? toStringValue(relativePath) : SEPARATOR_STRING + relativePath);
    if (!isRoot) {
        jw.name("parentPath").value(toStringValue(relativePath.getParent()));
    }
    addBasicAttributes(path, attrs);
}
Also used : MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 9 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRJSONFileVisitor method visitFile.

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    MCRPath mcrPath = MCRPath.toMCRPath(file);
    MCRPath relativePath = mcrPath.getRoot().relativize(mcrPath);
    jw.beginObject();
    writePathInfo(file, attrs);
    jw.name("extension").value(getFileExtension(file.getFileName().toString()));
    jw.name("href").value(MCRSecureTokenV2FilterConfig.getFileNodeServletSecured(MCRObjectID.getInstance(derId), relativePath.toString(), this.baseURL));
    jw.endObject();
    return super.visitFile(file, attrs);
}
Also used : MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 10 with MCRPath

use of org.mycore.datamodel.niofs.MCRPath in project mycore by MyCoRe-Org.

the class MCRSolrFileIndexBaseAccumulator method accumulate.

@Override
public void accumulate(SolrInputDocument doc, Path input, BasicFileAttributes attr) throws IOException {
    doc.setField("id", input.toUri().toString());
    String absolutePath = '/' + input.subpath(0, input.getNameCount()).toString();
    try {
        // check if this is an MCRPath -> more metadata
        MCRPath mcrPath = MCRPath.toMCRPath(input);
        MCRObjectID mcrObjID = MCRMetadataManager.getObjectId(MCRObjectID.getInstance(mcrPath.getOwner()), 10, TimeUnit.SECONDS);
        if (mcrObjID == null) {
            LOGGER.warn("Could not determine MCRObject for file {}", absolutePath);
            doc.setField("returnId", mcrPath.getOwner());
        } else {
            doc.setField("returnId", mcrObjID.toString());
            doc.setField("objectProject", mcrObjID.getProjectId());
        }
        String ownerID = mcrPath.getOwner();
        doc.setField("derivateID", ownerID);
        doc.setField("derivateModified", getDerivateModified(ownerID));
        Collection<MCRCategoryID> linksFromReference = MCRCategLinkServiceFactory.getInstance().getLinksFromReference(new MCRCategLinkReference(mcrPath));
        HashSet<MCRCategoryID> linkedCategories = new HashSet<>(linksFromReference);
        for (MCRCategoryID category : linksFromReference) {
            for (MCRCategory parent : CATEGORY_DAO.getParents(category)) {
                linkedCategories.add(parent.getId());
            }
        }
        for (MCRCategoryID category : linkedCategories) {
            doc.addField("fileCategory", category.toString());
        }
    } catch (ProviderMismatchException e) {
        LOGGER.warn("Cannot build all fields as input is not an instance of MCRPath: {}", input);
    }
    doc.setField("objectType", "data_file");
    doc.setField("fileName", input.getFileName().toString());
    doc.setField("filePath", absolutePath);
    doc.setField("stream_size", attr.size());
    doc.setField("stream_name", absolutePath);
    doc.setField("stream_source_info", input.toString());
    doc.setField("stream_content_type", MCRContentTypes.probeContentType(input));
    doc.setField("extension", Files.getFileExtension(input.getFileName().toString()));
    MCRISO8601Date iDate = new MCRISO8601Date();
    iDate.setDate(new Date(attr.lastModifiedTime().toMillis()));
    doc.setField("modified", iDate.getISOString());
}
Also used : MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) MCRCategoryID(org.mycore.datamodel.classifications2.MCRCategoryID) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) ProviderMismatchException(java.nio.file.ProviderMismatchException) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRISO8601Date(org.mycore.datamodel.common.MCRISO8601Date) MCRCategLinkReference(org.mycore.datamodel.classifications2.MCRCategLinkReference) MCRISO8601Date(org.mycore.datamodel.common.MCRISO8601Date) Date(java.util.Date) HashSet(java.util.HashSet)

Aggregations

MCRPath (org.mycore.datamodel.niofs.MCRPath)96 IOException (java.io.IOException)49 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)26 Path (java.nio.file.Path)25 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)22 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)22 Document (org.jdom2.Document)15 JDOMException (org.jdom2.JDOMException)15 MCRPersistenceException (org.mycore.common.MCRPersistenceException)14 MCRException (org.mycore.common.MCRException)13 MCRDirectory (org.mycore.datamodel.ifs.MCRDirectory)13 MCRAccessException (org.mycore.access.MCRAccessException)12 Files (java.nio.file.Files)11 Collectors (java.util.stream.Collectors)11 LogManager (org.apache.logging.log4j.LogManager)11 Logger (org.apache.logging.log4j.Logger)11 FileVisitResult (java.nio.file.FileVisitResult)10 NoSuchFileException (java.nio.file.NoSuchFileException)10 Date (java.util.Date)10 List (java.util.List)10