Search in sources :

Example 21 with MCRSession

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

the class MCRServlet method getSession.

public static MCRSession getSession(HttpServletRequest req) {
    boolean reusedSession = req.isRequestedSessionIdValid();
    HttpSession theSession = req.getSession(true);
    if (reusedSession) {
        LOGGER.debug(() -> "Reused HTTP session: " + theSession.getId() + ", created: " + LocalDateTime.ofInstant(Instant.ofEpochMilli(theSession.getCreationTime()), ZoneId.systemDefault()));
    } else {
        LOGGER.info(() -> "Created new HTTP session: " + theSession.getId());
    }
    MCRSession session = null;
    MCRSession fromHttpSession = Optional.ofNullable((String) theSession.getAttribute(ATTR_MYCORE_SESSION)).map(MCRSessionMgr::getSession).orElse(null);
    if (fromHttpSession != null && fromHttpSession.getID() != null) {
        // Take session from HttpSession with servlets
        session = fromHttpSession;
        String lastIP = session.getCurrentIP();
        if (lastIP.length() != 0) {
            // check if request IP equals last known IP
            String newip = MCRFrontendUtil.getRemoteAddr(req);
            if (!lastIP.equals(newip) && !newip.equals(MCRFrontendUtil.getHostIP())) {
                LOGGER.warn("Session steal attempt from IP {}, previous IP was {}. Session: {}", newip, lastIP, session);
                MCRSessionMgr.releaseCurrentSession();
                // MCR-1409 do not leak old session
                session.close();
                session = MCRSessionMgr.getCurrentSession();
                session.setCurrentIP(newip);
            }
        }
    } else {
        // Create a new session
        session = MCRSessionMgr.getCurrentSession();
    }
    // Store current session in HttpSession
    theSession.setAttribute(ATTR_MYCORE_SESSION, session.getID());
    LOGGER.debug("Bound MCRSession {} to HTTPSession {}", session.toString(), theSession.getId());
    // store the HttpSession ID in MCRSession
    if (session.put("http.session", theSession.getId()) == null) {
        // first request
        MCRStreamUtils.asStream(req.getLocales()).map(Locale::toString).filter(MCRTranslation.getAvailableLanguages()::contains).findFirst().ifPresent(session::setCurrentLanguage);
    }
    // Forward MCRSessionID to XSL Stylesheets
    req.setAttribute("XSL.MCRSessionID", session.getID());
    return session;
}
Also used : MCRSession(org.mycore.common.MCRSession) HttpSession(javax.servlet.http.HttpSession)

Example 22 with MCRSession

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

the class MCRServlet method processRenderingPhase.

private void processRenderingPhase(MCRServletJob job, Exception thinkException) throws Exception {
    if (allowCrossDomainRequests() && !job.getResponse().containsHeader(ACCESS_CONTROL_ALLOW_ORIGIN)) {
        job.getResponse().setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    }
    MCRSession session = MCRSessionMgr.getCurrentSession();
    if (getProperty(job.getRequest(), INITIAL_SERVLET_NAME_KEY).equals(getServletName())) {
        // current Servlet not called via RequestDispatcher
        session.beginTransaction();
    }
    render(job, thinkException);
    if (getProperty(job.getRequest(), INITIAL_SERVLET_NAME_KEY).equals(getServletName())) {
        // current Servlet not called via RequestDispatcher
        session.commitTransaction();
    }
}
Also used : MCRSession(org.mycore.common.MCRSession)

Example 23 with MCRSession

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

the class MCRServlet method doGetPost.

/**
 * This private method handles both GET and POST requests and is invoked by doGet() and doPost().
 *
 * @param req
 *            the HTTP request instance
 * @param res
 *            the HTTP response instance
 * @exception IOException
 *                for java I/O errors.
 * @exception ServletException
 *                for errors from the servlet engine.
 */
private void doGetPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, SAXException, TransformerException {
    if (MCRConfiguration.instance() == null) {
        // removes NullPointerException below, if somehow Servlet is not yet
        // intialized
        init();
    }
    // Try to set encoding of form values
    String ReqCharEncoding = req.getCharacterEncoding();
    if (ReqCharEncoding == null) {
        // Set default to UTF-8
        ReqCharEncoding = MCRConfiguration.instance().getString("MCR.Request.CharEncoding", "UTF-8");
        req.setCharacterEncoding(ReqCharEncoding);
        LOGGER.debug("Setting ReqCharEncoding to: {}", ReqCharEncoding);
    }
    if ("true".equals(req.getParameter("reload.properties"))) {
        MCRConfigurationDirSetup setup = new MCRConfigurationDirSetup();
        setup.startUp(getServletContext());
    }
    if (SERVLET_URL == null) {
        prepareBaseURLs(getServletContext(), req);
    }
    MCRServletJob job = new MCRServletJob(req, res);
    MCRSession session = getSession(job.getRequest());
    bindSessionToRequest(req, getServletName(), session);
    try {
        // transaction around 1st phase of request
        Exception thinkException = processThinkPhase(job);
        // first phase completed, start rendering phase
        processRenderingPhase(job, thinkException);
    } catch (Exception ex) {
        if (getProperty(req, INITIAL_SERVLET_NAME_KEY).equals(getServletName())) {
            // current Servlet not called via RequestDispatcher
            session.rollbackTransaction();
        }
        if (isBrokenPipe(ex)) {
            LOGGER.info("Ignore broken pipe.");
            return;
        }
        if (ex.getMessage() == null) {
            LOGGER.error("Exception while in rendering phase.", ex);
        } else {
            LOGGER.error("Exception while in rendering phase: {}", ex.getMessage());
        }
        if (ex instanceof ServletException) {
            throw (ServletException) ex;
        } else if (ex instanceof IOException) {
            throw (IOException) ex;
        } else if (ex instanceof SAXException) {
            throw (SAXException) ex;
        } else if (ex instanceof TransformerException) {
            throw (TransformerException) ex;
        } else if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException(ex);
        }
    } finally {
        // in case that Thread pooling will be used by servlet engine
        if (getProperty(req, INITIAL_SERVLET_NAME_KEY).equals(getServletName())) {
            // current Servlet not called via RequestDispatcher
            MCRSessionMgr.releaseCurrentSession();
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) MCRSession(org.mycore.common.MCRSession) IOException(java.io.IOException) MCRConfigurationDirSetup(org.mycore.common.config.MCRConfigurationDirSetup) TransformerException(javax.xml.transform.TransformerException) ServletException(javax.servlet.ServletException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TransformerException(javax.xml.transform.TransformerException) SAXException(org.xml.sax.SAXException)

Example 24 with MCRSession

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

the class MCRServlet method getServletBaseURL.

/**
 * Returns the servlet base URL of the mycore system
 */
public static String getServletBaseURL() {
    MCRSession session = MCRSessionMgr.getCurrentSession();
    Object value = session.get(BASE_URL_ATTRIBUTE);
    if (value != null) {
        LOGGER.debug("Returning BaseURL {}servlets/ from user session.", value);
        return value + "servlets/";
    }
    return SERVLET_URL != null ? SERVLET_URL : MCRFrontendUtil.getBaseURL() + "servlets/";
}
Also used : MCRSession(org.mycore.common.MCRSession)

Example 25 with MCRSession

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

the class MCRJobThread method run.

public void run() {
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    mcrSession.setUserInformation(MCRSystemUserInformation.getSystemUserInstance());
    EntityManager em = MCREntityManagerProvider.getEntityManagerFactory().createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    try {
        Class<? extends MCRJobAction> actionClass = job.getAction();
        Constructor<? extends MCRJobAction> actionConstructor = actionClass.getConstructor(MCRJob.class);
        MCRJobAction action = actionConstructor.newInstance(job);
        transaction.begin();
        try {
            setStatus(MCRProcessableStatus.processing);
            job.setStart(new Date());
            action.execute();
            job.setFinished(new Date());
            job.setStatus(MCRJobStatus.FINISHED);
            setStatus(MCRProcessableStatus.successful);
        } catch (ExecutionException ex) {
            LOGGER.error("Exception occured while try to start job. Perform rollback.", ex);
            setError(ex);
            action.rollback();
        } catch (Exception ex) {
            LOGGER.error("Exception occured while try to start job.", ex);
            setError(ex);
        }
        em.merge(job);
        transaction.commit();
        // notify the queue we have processed the job
        synchronized (queue) {
            queue.notifyAll();
        }
    } catch (Exception e) {
        LOGGER.error("Error while getting next job.", e);
        if (transaction != null) {
            transaction.rollback();
        }
    } finally {
        em.close();
        MCRSessionMgr.releaseCurrentSession();
        mcrSession.close();
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) MCRSession(org.mycore.common.MCRSession) ExecutionException(java.util.concurrent.ExecutionException) Date(java.util.Date) ExecutionException(java.util.concurrent.ExecutionException)

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