Search in sources :

Example 1 with MCRDirectory

use of org.mycore.datamodel.ifs.MCRDirectory 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 2 with MCRDirectory

use of org.mycore.datamodel.ifs.MCRDirectory in project mycore by MyCoRe-Org.

the class MCRIFSCommands method fixDirectorySize.

private static long fixDirectorySize(MCRDirectory directory) {
    long directorySize = 0;
    for (MCRFilesystemNode child : directory.getChildren()) {
        if (child instanceof MCRDirectory) {
            directorySize += fixDirectorySize((MCRDirectory) child);
        } else if (child instanceof MCRFile) {
            MCRFile file = (MCRFile) child;
            directorySize += file.getSize();
        }
    }
    /*
            There is no setSize method on MCRFileSystemNode and there should not be one.
            But in this repair command we need to set the size, so we use reflection.
         */
    try {
        Field privateLongField = MCRFilesystemNode.class.getDeclaredField(MCRFILESYSTEMNODE_SIZE_FIELD_NAME);
        privateLongField.setAccessible(true);
        privateLongField.set(directory, directorySize);
    } catch (NoSuchFieldException e) {
        String message = MessageFormat.format("There is no field named {0} in MCRFileSystemNode!", MCRFILESYSTEMNODE_SIZE_FIELD_NAME);
        throw new MCRException(message, e);
    } catch (IllegalAccessException e) {
        String message = MessageFormat.format("Could not acces filed {0} in {1}!", MCRFILESYSTEMNODE_SIZE_FIELD_NAME, directory.toString());
        throw new MCRException(message, e);
    }
    // now call touch with the old date of MCRFSN to apply the changes to the DB
    GregorianCalendar lastModified = directory.getLastModified();
    FileTime LastModifiedFileTime = FileTime.fromMillis(lastModified.getTimeInMillis());
    try {
        Method touchMethod = MCRFilesystemNode.class.getDeclaredMethod(MCRFILESYSTEMNODE_TOUCH_METHOD_NAME, FileTime.class, boolean.class);
        touchMethod.setAccessible(true);
        touchMethod.invoke(directory, LastModifiedFileTime, false);
    } catch (NoSuchMethodException e) {
        throw new MCRException(MessageFormat.format("There is no {0}-method..", MCRFILESYSTEMNODE_TOUCH_METHOD_NAME));
    } catch (InvocationTargetException | IllegalAccessException e) {
        throw new MCRException(MessageFormat.format("Error while calling {0}-method..", MCRFILESYSTEMNODE_TOUCH_METHOD_NAME));
    }
    LOGGER.info(MessageFormat.format("Changed size of directory {0} to {1} Bytes", directory.getName(), directorySize));
    return directorySize;
}
Also used : MCRFile(org.mycore.datamodel.ifs.MCRFile) MCRException(org.mycore.common.MCRException) MCRFilesystemNode(org.mycore.datamodel.ifs.MCRFilesystemNode) GregorianCalendar(java.util.GregorianCalendar) FileTime(java.nio.file.attribute.FileTime) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) Field(java.lang.reflect.Field) MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory)

Example 3 with MCRDirectory

use of org.mycore.datamodel.ifs.MCRDirectory in project mycore by MyCoRe-Org.

the class MCRIFSCommands method fixDirectorysOfDerivate.

@MCRCommand(syntax = "repair directory sizes of derivate {0}", help = "Fixes the directory sizes of a derivate.")
public static void fixDirectorysOfDerivate(String id) {
    MCRDirectory mcrDirectory = (MCRDirectory) MCRFilesystemNode.getRootNode(id);
    if (mcrDirectory == null) {
        throw new IllegalArgumentException(MessageFormat.format("Could not get root node for {0}", id));
    }
    fixDirectorySize(mcrDirectory);
}
Also used : MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 4 with MCRDirectory

use of org.mycore.datamodel.ifs.MCRDirectory in project mycore by MyCoRe-Org.

the class MCRBasicFileAttributeViewImpl method setTimes.

@Override
public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime) throws IOException {
    MCRFilesystemNode node = resolveNode();
    if (node instanceof MCRFile) {
        MCRFile file = (MCRFile) node;
        file.adjustMetadata(lastModifiedTime, file.getMD5(), file.getSize());
        Files.getFileAttributeView(file.getLocalFile().toPath(), BasicFileAttributeView.class).setTimes(lastModifiedTime, lastAccessTime, createTime);
    } else if (node instanceof MCRDirectory) {
        LOGGER.warn("Setting times on directories is not supported: {}", node.toPath());
    }
}
Also used : BasicFileAttributeView(java.nio.file.attribute.BasicFileAttributeView) MCRFile(org.mycore.datamodel.ifs.MCRFile) MCRFilesystemNode(org.mycore.datamodel.ifs.MCRFilesystemNode) MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory)

Example 5 with MCRDirectory

use of org.mycore.datamodel.ifs.MCRDirectory in project mycore by MyCoRe-Org.

the class MCRFileSystemProvider method delete.

/* (non-Javadoc)
     * @see java.nio.file.spi.FileSystemProvider#delete(java.nio.file.Path)
     */
@Override
public void delete(Path path) throws IOException {
    MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path);
    MCRFilesystemNode child = resolvePath(mcrPath);
    if (child instanceof MCRDirectory) {
        if (((MCRDirectory) child).hasChildren()) {
            throw new DirectoryNotEmptyException(mcrPath.toString());
        }
    }
    try {
        child.delete();
    } catch (RuntimeException e) {
        throw new IOException("Could not delete: " + mcrPath, e);
    }
}
Also used : MCRFilesystemNode(org.mycore.datamodel.ifs.MCRFilesystemNode) MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) IOException(java.io.IOException) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Aggregations

MCRDirectory (org.mycore.datamodel.ifs.MCRDirectory)21 MCRFilesystemNode (org.mycore.datamodel.ifs.MCRFilesystemNode)13 MCRPath (org.mycore.datamodel.niofs.MCRPath)13 MCRFile (org.mycore.datamodel.ifs.MCRFile)10 NoSuchFileException (java.nio.file.NoSuchFileException)9 IOException (java.io.IOException)7 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)5 NotDirectoryException (java.nio.file.NotDirectoryException)4 DirectoryNotEmptyException (java.nio.file.DirectoryNotEmptyException)3 Path (java.nio.file.Path)3 CopyOption (java.nio.file.CopyOption)2 FileSystemException (java.nio.file.FileSystemException)2 InvalidPathException (java.nio.file.InvalidPathException)2 ProviderMismatchException (java.nio.file.ProviderMismatchException)2 StandardCopyOption (java.nio.file.StandardCopyOption)2 BasicFileAttributeView (java.nio.file.attribute.BasicFileAttributeView)2 GregorianCalendar (java.util.GregorianCalendar)2 MCRException (org.mycore.common.MCRException)2 MCRPersistenceException (org.mycore.common.MCRPersistenceException)2 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)2