Search in sources :

Example 6 with MCRUsageException

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

the class MCRFileImportExport method exportFiles.

/**
 * Exports all contents of the given MCRDirectory to the local filesystem, including all subdirectories and stored files. If the local object is a file, the
 * parent directory of that file will be used for exporting.
 *
 * @param local
 *            the local directory where to export the contents to
 * @param dir
 *            the directory thats contents should be exported
 */
public static void exportFiles(MCRDirectory dir, File local) throws MCRException {
    Objects.requireNonNull(dir, "internal directory is null");
    Objects.requireNonNull(local, "local file is null");
    String path = local.getPath();
    if (!local.canWrite()) {
        throw new MCRUsageException("Not writeable: " + path);
    }
    // If local is file, use its parent instead
    if (local.isFile()) {
        local = local.getParentFile();
    }
    MCRFilesystemNode[] children = dir.getChildren();
    for (MCRFilesystemNode element : children) {
        if (element instanceof MCRFile) {
            MCRFile internalFile = (MCRFile) element;
            String name = internalFile.getName();
            File localFile = new File(local, name);
            try {
                internalFile.getContentTo(localFile);
            } catch (Exception ex) {
                throw new MCRException("Can't get file content.", ex);
            }
        } else {
            MCRDirectory internalDir = (MCRDirectory) element;
            String name = internalDir.getName();
            File localDir = new File(local, name);
            if (!localDir.exists()) {
                localDir.mkdir();
            }
            exportFiles(internalDir, localDir);
        }
    }
}
Also used : MCRUsageException(org.mycore.common.MCRUsageException) MCRException(org.mycore.common.MCRException) File(java.io.File) MCRUsageException(org.mycore.common.MCRUsageException) IOException(java.io.IOException) MCRException(org.mycore.common.MCRException) FileNotFoundException(java.io.FileNotFoundException)

Example 7 with MCRUsageException

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

the class MCRFileImportExport method importFiles.

/**
 * Imports the contents of a local file or directory into the MyCoRe Internal Filesystem. If the local object is a file, a MCRFile with the same name will
 * be created or updated in the given MCRDirectory. If the local object is a directory, all contained subdirectories and files will be imported into the
 * given MCRDirectory. That means that after finishing this method, the complete directory structure will have been imported and mapped from the local
 * filesystem's structure. The method checks the contents of each local file to be imported. If the file's content has not changed for existing files, the
 * internal MCRFile will not be updated. If an internal directory is updated from a local directory, new files will be added, existing files will be updated
 * if necessary, but files that already exist in the given MCRDirectory but not in the local filesystem will be kept and will not be deleted.
 *
 * @param local
 *            the local file or directory
 * @param dir
 *            an existing MCRDirectory where to store the imported contents of the local filesystem.
 */
public static void importFiles(File local, MCRDirectory dir) throws IOException {
    Objects.requireNonNull(local, "local file is null");
    String path = local.getPath();
    String name = local.getName();
    if (!local.exists()) {
        throw new MCRUsageException("Not found: " + path);
    }
    if (!local.canRead()) {
        throw new MCRUsageException("Not readable: " + path);
    }
    // Import a local file
    if (local.isFile()) {
        MCRFilesystemNode existing = dir.getChild(name);
        MCRFile file = null;
        // If internal directory with same name exists
        if (existing instanceof MCRDirectory) {
            // delete it
            existing.delete();
            existing = null;
        }
        if (existing == null) {
            // Create new, empty MCRFile
            file = new MCRFile(name, dir, false);
        } else {
            // Update existing MCRFile
            file = (MCRFile) existing;
            // Determine MD5 checksum of local file
            try (FileInputStream fin = new FileInputStream(local);
                MCRMD5InputStream cis = new MCRMD5InputStream(fin)) {
                IOUtils.copy(cis, new MCRDevNull());
                String local_md5 = cis.getMD5String();
                // If file content of local file has not changed, do not load it again
                if (file.getMD5().equals(local_md5)) {
                    return;
                }
            }
        }
        // Store file content
        file.setContentFrom(local);
    } else {
        File[] files = local.listFiles();
        // For each local child node
        for (File file : files) {
            local = file;
            name = local.getName();
            MCRDirectory internalDir = dir;
            if (local.isDirectory()) {
                MCRFilesystemNode existing = dir.getChild(name);
                if (existing instanceof MCRFile) {
                    // If there is an
                    // existing MCRFile with
                    // same name
                    // delete that existing MCRFile
                    existing.delete();
                    existing = null;
                }
                if (existing == null) {
                    // Create new directory
                    internalDir = new MCRDirectory(name, dir, false);
                } else {
                    internalDir = (MCRDirectory) existing;
                }
            }
            // Recursively import
            importFiles(local, internalDir);
        }
    }
}
Also used : MCRUsageException(org.mycore.common.MCRUsageException) MCRDevNull(org.mycore.common.content.streams.MCRDevNull) MCRMD5InputStream(org.mycore.common.content.streams.MCRMD5InputStream) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 8 with MCRUsageException

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

the class MCRLDAPClient method updateUserProperties.

public boolean updateUserProperties(MCRUser user) throws NamingException {
    String userName = user.getUserName();
    boolean userChanged = false;
    if ((defaultGroup != null) && (!user.isUserInRole((defaultGroup.getName())))) {
        LOGGER.info("User {} add to group {}", userName, defaultGroup);
        userChanged = true;
        user.assignRole(defaultGroup.getName());
    }
    // Get user properties from LDAP server
    DirContext ctx = new InitialDirContext(ldapEnv);
    try {
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration<SearchResult> results = ctx.search(baseDN, String.format(Locale.ROOT, uidFilter, userName), controls);
        while (results.hasMore()) {
            SearchResult searchResult = results.next();
            Attributes attributes = searchResult.getAttributes();
            for (NamingEnumeration<String> attributeIDs = attributes.getIDs(); attributeIDs.hasMore(); ) {
                String attributeID = attributeIDs.next();
                Attribute attribute = attributes.get(attributeID);
                for (NamingEnumeration<?> values = attribute.getAll(); values.hasMore(); ) {
                    String attributeValue = values.next().toString();
                    LOGGER.debug("{}={}", attributeID, attributeValue);
                    if (attributeID.equals(mapName) && (user.getRealName() == null)) {
                        attributeValue = formatName(attributeValue);
                        LOGGER.info("User {} name = {}", userName, attributeValue);
                        user.setRealName(attributeValue);
                        userChanged = true;
                    }
                    if (attributeID.equals(mapEMail) && (user.getEMailAddress() == null)) {
                        LOGGER.info("User {} e-mail = {}", userName, attributeValue);
                        user.setEMail(attributeValue);
                        userChanged = true;
                    }
                    String groupMapping = "MCR.user2.LDAP.Mapping.Group." + attributeID + "." + attributeValue;
                    String group = MCRConfiguration.instance().getString(groupMapping, null);
                    if ((group != null) && (!user.isUserInRole((group)))) {
                        LOGGER.info("User {} add to group {}", userName, group);
                        user.assignRole(group);
                        userChanged = true;
                    }
                }
            }
        }
    } catch (NameNotFoundException ex) {
        String msg = "LDAP base name not found: " + ex.getMessage() + " " + ex.getExplanation();
        throw new MCRConfigurationException(msg, ex);
    } catch (NamingException ex) {
        String msg = "Exception accessing LDAP server";
        throw new MCRUsageException(msg, ex);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception ignored) {
            }
        }
    }
    return userChanged;
}
Also used : Attribute(javax.naming.directory.Attribute) NameNotFoundException(javax.naming.NameNotFoundException) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) MCRConfigurationException(org.mycore.common.config.MCRConfigurationException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) MCRUsageException(org.mycore.common.MCRUsageException) NamingException(javax.naming.NamingException) MCRConfigurationException(org.mycore.common.config.MCRConfigurationException) NameNotFoundException(javax.naming.NameNotFoundException) MCRUsageException(org.mycore.common.MCRUsageException) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException)

Example 9 with MCRUsageException

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

the class MCRTransferPackage method resolveChildrenAndLinks.

/**
 * Fills the given objectMap with all children and links of the object. The object
 * itself is also added.
 *
 * @param object the source object
 * @param objectMap the map which will be created
 */
protected void resolveChildrenAndLinks(MCRObject object, LinkedHashMap<MCRObjectID, MCRObject> objectMap, Set<MCRCategoryID> categories) {
    // add links
    for (MCRObject entityLink : MCRObjectUtils.getLinkedObjects(object)) {
        if (!objectMap.containsKey(entityLink.getId())) {
            objectMap.put(entityLink.getId(), entityLink);
        }
    }
    // add classifications
    categories.addAll(MCRObjectUtils.getCategories(object));
    // add the object to the objectMap
    objectMap.put(object.getId(), object);
    // resolve children
    for (MCRMetaLinkID metaLinkId : object.getStructure().getChildren()) {
        MCRObjectID childId = MCRObjectID.getInstance(metaLinkId.toString());
        if (!MCRMetadataManager.exists(childId)) {
            throw new MCRUsageException("Requested object '" + childId + "' does not exist. Thus a transfer package cannot be created.");
        }
        MCRObject child = MCRMetadataManager.retrieveMCRObject(childId);
        resolveChildrenAndLinks(child, objectMap, categories);
    }
}
Also used : MCRUsageException(org.mycore.common.MCRUsageException) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID)

Example 10 with MCRUsageException

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

the class MCRTransferPackagePacker method getSource.

/**
 * Returns the source object.
 *
 * @return mycore object which should be packed
 * @throws MCRUsageException something went wrong
 */
protected MCRObject getSource() throws MCRUsageException {
    String sourceId = getSourceId();
    MCRObjectID mcrId = MCRObjectID.getInstance(sourceId);
    if (!MCRMetadataManager.exists(mcrId)) {
        throw new MCRUsageException("Requested object '" + sourceId + "' does not exist. Thus a transfer package cannot be created.");
    }
    return MCRMetadataManager.retrieveMCRObject(mcrId);
}
Also used : MCRUsageException(org.mycore.common.MCRUsageException) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID)

Aggregations

MCRUsageException (org.mycore.common.MCRUsageException)11 IOException (java.io.IOException)3 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)2 BufferedInputStream (java.io.BufferedInputStream)1 NameNotFoundException (javax.naming.NameNotFoundException)1 NamingException (javax.naming.NamingException)1 Attribute (javax.naming.directory.Attribute)1 Attributes (javax.naming.directory.Attributes)1 DirContext (javax.naming.directory.DirContext)1 InitialDirContext (javax.naming.directory.InitialDirContext)1 SearchControls (javax.naming.directory.SearchControls)1 SearchResult (javax.naming.directory.SearchResult)1 Document (org.jdom2.Document)1 Element (org.jdom2.Element)1 Test (org.junit.Test)1 MCRAccessException (org.mycore.access.MCRAccessException)1 MCRException (org.mycore.common.MCRException)1