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;
}
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();
}
}
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();
}
}
}
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/";
}
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();
}
}
Aggregations