Search in sources :

Example 26 with MCRException

use of org.mycore.common.MCRException 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 27 with MCRException

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

the class MCRAccessCommands method createPermissionsFromFile.

/**
 * This method sets the new permissions given in a certain file
 *
 * @param filename
 *            the filename of the file that contains the mcrpermissions
 */
public static void createPermissionsFromFile(String filename) throws Exception {
    MCRAccessInterface AI = MCRAccessManager.getAccessImpl();
    if (!checkFilename(filename)) {
        return;
    }
    LOGGER.info("Reading file {} ...", filename);
    org.jdom2.Document doc = MCRXMLParserFactory.getValidatingParser().parseXML(new MCRFileContent(filename));
    org.jdom2.Element rootelm = doc.getRootElement();
    if (!rootelm.getName().equals("mcrpermissions")) {
        throw new MCRException("The data are not for mcrpermissions.");
    }
    List<Element> listelm = rootelm.getChildren("mcrpermission");
    for (Element mcrpermission : listelm) {
        String permissionName = mcrpermission.getAttributeValue("name").trim();
        String ruleDescription = mcrpermission.getAttributeValue("ruledescription");
        if (ruleDescription == null) {
            ruleDescription = "";
        }
        Element rule = mcrpermission.getChild("condition").clone();
        String objectid = mcrpermission.getAttributeValue("objectid");
        if (objectid == null) {
            AI.addRule(permissionName, rule, ruleDescription);
        } else {
            AI.addRule(objectid, permissionName, rule, ruleDescription);
        }
    }
}
Also used : Document(org.jdom2.Document) MCRException(org.mycore.common.MCRException) MCRAccessInterface(org.mycore.access.MCRAccessInterface) MCRFileContent(org.mycore.common.content.MCRFileContent) Element(org.jdom2.Element) Element(org.jdom2.Element)

Example 28 with MCRException

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

the class MCRIFS2Commands method repairUnicodeInContentStores.

@MCRCommand(syntax = "repair unicode in content stores {0}", help = "this fixes consequences of MCR-1423 in content" + " stores . If {0} is false then nothing will be done (dry run).")
public static void repairUnicodeInContentStores(String execute) {
    boolean dry = execute.toLowerCase(Locale.ROOT).equals(Boolean.FALSE.toString().toLowerCase(Locale.ROOT));
    MCRContentStoreFactory.getAvailableStores().forEach((name, cs) -> {
        LOGGER.info("{} store: {} ", dry ? "would fix" : "fixing", name);
        try {
            Path path = cs.getBaseDir().toPath();
            LOGGER.info("Starting with path : {}", path);
            java.nio.file.Files.walkFileTree(path, new MCRUnicodeFilenameNormalizer(dry));
        } catch (IOException e) {
            throw new MCRException("Error while get basedir of content store " + name, e);
        }
    });
}
Also used : Path(java.nio.file.Path) MCRException(org.mycore.common.MCRException) IOException(java.io.IOException) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 29 with MCRException

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

the class MCRIFS2Commands method fixFileEntry.

private static void fixFileEntry(File node, String content_store, String derivate_id, String storage_base, boolean check_only) {
    LOGGER.debug("fixFileEntry : name = {}", node.getName());
    String storageid = node.getAbsolutePath().substring(storage_base.length()).replace("\\", "/");
    LOGGER.debug("fixFileEntry : storageid = {}", storageid);
    String id = "";
    String md5_old = "";
    long size_old = 0;
    boolean foundEntry = false;
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    boolean transactionActive = mcrSession.isTransactionActive();
    if (!transactionActive) {
        mcrSession.beginTransaction();
    }
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<MCRFSNODES> query = cb.createQuery(MCRFSNODES.class);
        Root<MCRFSNODES> nodes = query.from(MCRFSNODES.class);
        try {
            MCRFSNODES fsNode = em.createQuery(query.where(cb.equal(nodes.get(MCRFSNODES_.owner), derivate_id), cb.equal(nodes.get(MCRFSNODES_.storeid), content_store), cb.equal(nodes.get(MCRFSNODES_.storageid), storageid), cb.equal(nodes.get(MCRFSNODES_.type), "F"))).getSingleResult();
            LOGGER.debug("Found file entry for {}", storageid);
            foundEntry = true;
            id = fsNode.getId();
            md5_old = fsNode.getMd5();
            size_old = fsNode.getSize();
            em.detach(fsNode);
        } catch (NoResultException e) {
            LOGGER.error("Can't find file entry for {}", storageid);
            if (check_only)
                return;
        } catch (NonUniqueResultException e) {
            LOGGER.error("Non unique file entry for {}", storageid);
            return;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // check fctid, size and MD5 of the file
    String fctid = "";
    String md5 = "";
    try (MCRContentInputStream cis = new MCRContentInputStream(new FileInputStream(node))) {
        byte[] header = cis.getHeader();
        fctid = MCRFileContentTypeFactory.detectType(node.getName(), header).getID();
        ByteStreams.copy(cis, ByteStreams.nullOutputStream());
        md5 = cis.getMD5String();
    } catch (MCRException | IOException e1) {
        e1.printStackTrace();
        return;
    }
    long size = node.length();
    LOGGER.debug("size old : {} <--> size : {}", Long.toString(size_old), Long.toString(size));
    LOGGER.debug("MD5 old : {} <--> MD5 : {}", md5_old, md5);
    if (size_old == size && md5_old.equals(md5)) {
        return;
    }
    if (foundEntry && size_old != size) {
        LOGGER.warn("Wrong file size for {} : {} <-> {}", storageid, size_old, size);
    }
    if (foundEntry && !md5.equals(md5_old)) {
        LOGGER.warn("Wrong file md5 for {} : {} <-> {}", storageid, md5_old, md5);
    }
    if (check_only)
        return;
    // fix entry
    LOGGER.info("Fix entry for file {}", storageid);
    if (!foundEntry) {
        MCRFileMetadataManager fmmgr = MCRFileMetadataManager.instance();
        id = fmmgr.createNodeID();
    }
    String pid = null;
    try {
        pid = getParentID(node, derivate_id);
    } catch (NoResultException e1) {
        LOGGER.error("Can't find parent id of directory for file {}", storageid);
    } catch (NonUniqueResultException e1) {
        LOGGER.error("The directory entry for {} and {} is not unique!", derivate_id, node.getParentFile().getName());
        return;
    }
    try {
        MCRFSNODES mcrfsnodes = new MCRFSNODES();
        mcrfsnodes.setId(id);
        mcrfsnodes.setPid(pid);
        mcrfsnodes.setType("F");
        mcrfsnodes.setOwner(derivate_id);
        mcrfsnodes.setName(node.getName());
        mcrfsnodes.setSize(size);
        mcrfsnodes.setDate(new Date(node.lastModified()));
        mcrfsnodes.setStoreid(content_store);
        mcrfsnodes.setStorageid(storageid);
        mcrfsnodes.setFctid(fctid);
        mcrfsnodes.setMd5(md5);
        em.merge(mcrfsnodes);
        mcrSession.commitTransaction();
        LOGGER.debug("Entry {} fixed.", node.getName());
    } catch (PersistenceException pe) {
        mcrSession.rollbackTransaction();
        pe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) NonUniqueResultException(javax.persistence.NonUniqueResultException) MCRException(org.mycore.common.MCRException) NoResultException(javax.persistence.NoResultException) IOException(java.io.IOException) MCRFSNODES(org.mycore.backend.hibernate.tables.MCRFSNODES) NoResultException(javax.persistence.NoResultException) MCRException(org.mycore.common.MCRException) NonUniqueResultException(javax.persistence.NonUniqueResultException) IOException(java.io.IOException) PersistenceException(javax.persistence.PersistenceException) HibernateException(org.hibernate.HibernateException) FileInputStream(java.io.FileInputStream) MCRFileMetadataManager(org.mycore.datamodel.ifs.MCRFileMetadataManager) Date(java.util.Date) EntityManager(javax.persistence.EntityManager) MCRSession(org.mycore.common.MCRSession) MCRContentInputStream(org.mycore.datamodel.ifs.MCRContentInputStream) PersistenceException(javax.persistence.PersistenceException)

Example 30 with MCRException

use of org.mycore.common.MCRException 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)

Aggregations

MCRException (org.mycore.common.MCRException)131 IOException (java.io.IOException)39 Element (org.jdom2.Element)26 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)19 Document (org.jdom2.Document)18 MCRCommand (org.mycore.frontend.cli.annotation.MCRCommand)18 File (java.io.File)15 MCRConfigurationException (org.mycore.common.config.MCRConfigurationException)12 MCRObject (org.mycore.datamodel.metadata.MCRObject)12 ArrayList (java.util.ArrayList)11 JDOMException (org.jdom2.JDOMException)11 MCRAccessException (org.mycore.access.MCRAccessException)11 MCRPath (org.mycore.datamodel.niofs.MCRPath)10 SAXException (org.xml.sax.SAXException)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 List (java.util.List)7 MCRActiveLinkException (org.mycore.datamodel.common.MCRActiveLinkException)7 SAXParseException (org.xml.sax.SAXParseException)7 URI (java.net.URI)6 Path (java.nio.file.Path)6