Search in sources :

Example 16 with MCRSession

use of org.mycore.common.MCRSession 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 17 with MCRSession

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

the class MCRHttpSessionListener method sessionDestroyed.

/*
     * (non-Javadoc)
     * 
     * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
     */
public void sessionDestroyed(HttpSessionEvent hse) {
    // clear MCRSessions
    HttpSession httpSession = hse.getSession();
    LOGGER.debug(() -> "HttpSession " + httpSession.getId() + " is beeing destroyed by " + hse.getSource() + ", clearing up.");
    LOGGER.debug("Removing any MCRSessions from HttpSession");
    for (Enumeration<String> e = httpSession.getAttributeNames(); e.hasMoreElements(); ) {
        String key = e.nextElement();
        if (key.equals(MCRServlet.ATTR_MYCORE_SESSION)) {
            MCRSession mcrSession = MCRSessionMgr.getSession((String) httpSession.getAttribute(key));
            if (mcrSession != null) {
                LOGGER.debug("Clean up MCRSession {}", mcrSession);
                mcrSession.close();
            }
            // remove reference in httpSession
            httpSession.removeAttribute(key);
        }
    }
    LOGGER.debug("Clearing up done");
}
Also used : MCRSession(org.mycore.common.MCRSession) HttpSession(javax.servlet.http.HttpSession)

Example 18 with MCRSession

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

the class MCRParameterCollector method getInstanceFromUserSession.

public static MCRParameterCollector getInstanceFromUserSession() {
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    MCRServletJob job = (MCRServletJob) mcrSession.get("MCRServletJob");
    return job == null ? new MCRParameterCollector() : new MCRParameterCollector(job.getRequest());
}
Also used : MCRSession(org.mycore.common.MCRSession) MCRServletJob(org.mycore.frontend.servlets.MCRServletJob)

Example 19 with MCRSession

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

the class MCRErrorServlet method generateErrorPage.

protected void generateErrorPage(HttpServletRequest request, HttpServletResponse response, String msg, Throwable ex, Integer statusCode, Class<? extends Throwable> exceptionType, String requestURI, String servletName) throws IOException, TransformerException, SAXException {
    boolean exceptionThrown = ex != null;
    LOGGER.log(exceptionThrown ? Level.ERROR : Level.WARN, MessageFormat.format("{0}: Error {1} occured. The following message was given: {2}", requestURI, statusCode, msg), ex);
    String style = MCRFrontendUtil.getProperty(request, "XSL.Style").filter("xml"::equals).orElse("default");
    request.setAttribute("XSL.Style", style);
    Document errorDoc = buildErrorPage(msg, statusCode, requestURI, exceptionType, servletName, ex);
    final String requestAttr = "MCRErrorServlet.generateErrorPage";
    if (!response.isCommitted() && request.getAttribute(requestAttr) == null) {
        if (statusCode != null) {
            response.setStatus(statusCode);
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        request.setAttribute(requestAttr, msg);
        boolean currentSessionActive = MCRSessionMgr.hasCurrentSession();
        boolean sessionFromRequest = setCurrentSession(request);
        MCRSession session = null;
        try {
            session = MCRSessionMgr.getCurrentSession();
            boolean openTransaction = session.isTransactionActive();
            if (!openTransaction) {
                session.beginTransaction();
            }
            try {
                setWebAppBaseURL(session, request);
                LAYOUT_SERVICE.doLayout(request, response, new MCRJDOMContent(errorDoc));
            } finally {
                if (!openTransaction)
                    session.commitTransaction();
            }
        } finally {
            if (exceptionThrown || !currentSessionActive) {
                MCRSessionMgr.releaseCurrentSession();
            }
            if (!sessionFromRequest) {
                // new session created for transaction
                session.close();
            }
        }
    } else {
        if (request.getAttribute(requestAttr) != null) {
            LOGGER.warn("Could not send error page. Generating error page failed. The original message:\n{}", request.getAttribute(requestAttr));
        } else {
            LOGGER.warn("Could not send error page. Response allready commited. The following message was given:\n{}", msg);
        }
    }
}
Also used : MCRSession(org.mycore.common.MCRSession) MCRJDOMContent(org.mycore.common.content.MCRJDOMContent) Document(org.jdom2.Document)

Example 20 with MCRSession

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

the class MCRObjectServlet method getContent.

@Override
public MCRContent getContent(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final MCRObjectID mcrid = getMCRObjectID(req, resp);
    if (mcrid == null) {
        return null;
    }
    if (!MCRAccessManager.checkPermission(mcrid, PERMISSION_READ)) {
        // check read permission for ID
        final MCRSession currentSession = MCRSessionMgr.getCurrentSession();
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, getErrorI18N(I18N_ERROR_PREFIX, "accessDenied", mcrid.toString(), currentSession.getUserInformation().getUserID(), currentSession.getCurrentIP()));
        return null;
    }
    long rev = REV_CURRENT;
    final String revision = getProperty(req, "r");
    if (revision != null) {
        rev = Long.parseLong(revision);
    }
    MCRContent localObject = (rev == REV_CURRENT) ? requestLocalObject(mcrid, resp) : requestVersionedObject(mcrid, resp, rev);
    if (localObject == null) {
        return null;
    }
    try {
        return getLayoutService().getTransformedContent(req, resp, localObject);
    } catch (TransformerException | SAXException e) {
        throw new IOException(e);
    }
}
Also used : MCRSession(org.mycore.common.MCRSession) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) IOException(java.io.IOException) MCRContent(org.mycore.common.content.MCRContent) TransformerException(javax.xml.transform.TransformerException) SAXException(org.xml.sax.SAXException)

Aggregations

MCRSession (org.mycore.common.MCRSession)63 IOException (java.io.IOException)15 MCRUserInformation (org.mycore.common.MCRUserInformation)10 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)10 MCRPath (org.mycore.datamodel.niofs.MCRPath)6 SignedJWT (com.nimbusds.jwt.SignedJWT)5 Date (java.util.Date)5 EntityManager (javax.persistence.EntityManager)5 Path (java.nio.file.Path)4 Response (javax.ws.rs.core.Response)4 Test (org.junit.Test)4 MCRRestAPIException (org.mycore.restapi.v1.errors.MCRRestAPIException)4 SAXException (org.xml.sax.SAXException)4 UnknownHostException (java.net.UnknownHostException)3 Document (org.jdom2.Document)3 MCRAccessException (org.mycore.access.MCRAccessException)3 MCRException (org.mycore.common.MCRException)3 MCRPersistenceException (org.mycore.common.MCRPersistenceException)3 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)3 MCRRestAPIError (org.mycore.restapi.v1.errors.MCRRestAPIError)3