Example usage for javax.servlet.http HttpSession getServletContext

List of usage examples for javax.servlet.http HttpSession getServletContext

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns the ServletContext to which this session belongs.

Usage

From source file:org.kitodo.serviceloader.KitodoServiceLoader.java

/**
 * Loads bean classes and registers them to the FacesContext. Afterwards
 * they can be used in all frontend files
 *//*from   ww w  . j a  v a 2s .com*/
private void loadBeans() {
    Path moduleFolder = FileSystems.getDefault().getPath(modulePath);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, JAR)) {

        for (Path f : stream) {
            try (JarFile jarFile = new JarFile(f.toString())) {

                if (hasFrontendFiles(jarFile)) {

                    Enumeration<JarEntry> e = jarFile.entries();

                    URL[] urls = { new URL("jar:file:" + f.toString() + "!/") };
                    try (URLClassLoader cl = URLClassLoader.newInstance(urls)) {
                        while (e.hasMoreElements()) {
                            JarEntry je = e.nextElement();

                            /*
                             * IMPORTANT: Naming convention: the name of the
                             * java class has to be in upper camel case or
                             * "pascal case" and must be equal to the file
                             * name of the corresponding facelet file
                             * concatenated with the word "Form".
                             *
                             * Example: template filename "sample.xhtml" =>
                             * "SampleForm.java"
                             *
                             * That is the reason for the following check
                             * (e.g. whether the JarEntry name ends with
                             * "Form.class")
                             */
                            if (je.isDirectory() || !je.getName().endsWith("Form.class")) {
                                continue;
                            }

                            String className = je.getName().substring(0, je.getName().length() - 6);
                            className = className.replace('/', '.');
                            Class c = cl.loadClass(className);

                            String beanName = className.substring(className.lastIndexOf('.') + 1).trim();

                            FacesContext facesContext = FacesContext.getCurrentInstance();
                            HttpSession session = (HttpSession) facesContext.getExternalContext()
                                    .getSession(false);

                            session.getServletContext().setAttribute(beanName, c.newInstance());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(ERROR, e.getMessage());
    }
}

From source file:it.scoppelletti.programmerpower.web.spring.ApplicationContextListener.java

/**
 * Inizializzazione di una sessione.//  w  w w  .jav a  2 s .  c  o  m
 * 
 * @param event Evento.
 */
public void sessionCreated(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    EventContext eventCtx = null;

    if (mySessionListeners == null) {
        return;
    }

    try {
        eventCtx = new EventContext(ApplicationContextListener.THREAD_SESSION_CREATE,
                session.getServletContext());

        for (Map.Entry<String, HttpSessionListener> entry : mySessionListeners.entrySet()) {
            myLogger.trace("Calling method sessionCreated({}) of " + "HttpSessionListener {}.", session.getId(),
                    entry.getKey());
            try {
                entry.getValue().sessionCreated(event);
            } catch (Exception ex) {
                myLogger.error(entry.getKey(), ex);
            }
        }
    } finally {
        if (eventCtx != null) {
            eventCtx.dispose();
            eventCtx = null;
        }
    }
}

From source file:it.scoppelletti.programmerpower.web.spring.ApplicationContextListener.java

/**
 * Termine di una sessione./*  www.  j a  v a  2  s. c  om*/
 * 
 * @param event Evento.
 */
public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    EventContext eventCtx = null;

    if (mySessionListeners == null) {
        return;
    }

    try {
        eventCtx = new EventContext(ApplicationContextListener.THREAD_SESSION_DESTROY,
                session.getServletContext());

        for (Map.Entry<String, HttpSessionListener> entry : mySessionListeners.entrySet()) {
            myLogger.trace("Calling method sessionDestroyed({}) of " + "HttpSessionListener {}.",
                    session.getId(), entry.getKey());
            try {
                entry.getValue().sessionDestroyed(event);
            } catch (Exception ex) {
                myLogger.error(entry.getKey(), ex);
            }
        }
    } finally {
        if (eventCtx != null) {
            eventCtx.dispose();
            eventCtx = null;
        }
    }
}

From source file:com.portfolio.security.LTIv2Servlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuffer outTrace = new StringBuffer();
    String logFName = null;//from   w ww .j av  a  2s. c om
    HttpSession session = request.getSession(true);
    String ppath = session.getServletContext().getRealPath("/");
    String outsideDir = ppath.substring(0, ppath.lastIndexOf("/")) + "_files/";

    ServletContext application = getServletConfig().getServletContext();

    //super.doPost(request, response);
    logFName = outsideDir + "logs/logLTI2.txt";
    outTraceFormattedMessage(outTrace, "doPost() - " + logFName);

    String toolProxyPath = outsideDir + "tool_proxy.txt";

    try {
        //         wadbackend.WadUtilities.setApplicationAttributes(application, session);
        doRequest(request, response, session, application, toolProxyPath, outTrace);
    } catch (Exception e) {
        String ipAddress = request.getRemoteAddr();
        String uri = request.getRequestURI();
        M_log.warn("General LTI2 Failure URI=" + uri + " IP=" + ipAddress);
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        doErrorJSON(request, response, null, "General failure", e);
    } finally {
        outTraceFormattedMessage(outTrace, "In finally()");
        if (LTIServletUtils.isTrace(application)) {
            outTraceFormattedMessage(outTrace, "In finally() with trace");
            //            wadbackend.WadUtilities.appendlogfile(logFName, "POSTlti:" + outTrace.toString());
        }
    }
}

From source file:com.starr.smartbuilds.controller.BuildController.java

@RequestMapping(method = { RequestMethod.GET })
public String getBuild(Model model, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ParseException {
    resp.setHeader("Access-Control-Allow-Origin", "*");
    Build build = new Build();
    Long buildId = 0L;/*from  w w  w  .  j  a  v  a 2  s  .  com*/
    String p = req.getParameter("id");
    if (p != null || !p.equals("")) {
        buildId = Long.parseLong(p);
        try {
            HttpSession session = req.getSession();

            build = buildDAO.getBuild(buildId);
            model.addAttribute("author", build.getUser());
            model.addAttribute("build", build);
            model.addAttribute("champion", build.getChampion().getKeyChamp());
            model.addAttribute("blocks", buildService.parseBlocks(build.getBlocks()));
            model.addAttribute("download", fileService.getFile(build, session.getServletContext()));

            User user = (User) session.getAttribute("user");
            if (user == null) {
                model.addAttribute("authMsg", "<a href='./auth'>Log in</a>");
                model.addAttribute("exitReg", "<a href='./reg'>Register</a>");
            } else {
                model.addAttribute("authMsg", "Hello," + user.getSummonerName() + "!");
                model.addAttribute("exitReg", "<a href='./auth/exit'>Exit</a>");
                model.addAttribute("createbuild",
                        "<li><a href='./add' style='color: #deff00;'>Create Build</a></li>");
            }
        } catch (NullPointerException ex) {
            resp.sendRedirect("/");
        }

        return "build";
    } else {
        System.out.println("param--" + p);
        resp.sendRedirect("./");

    }

    return "build";
}

From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java

private ServerManager getServerManager(HttpServletRequest request) {

    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    ServerManager serverManager = (ServerManager) servletContext.getAttribute(getServiceManagerAttribute());
    if (null != serverManager) {
        return serverManager;
    }/*  ww  w  . ja va 2s. c o m*/
    LOG.debug("creating an OpenID server manager");
    serverManager = new ServerManager();
    /*
     * Important that the shared association store and the private
     * association store are different. See also:
     * http://code.google.com/p/openid4java/source/detail?r=738
     */
    serverManager.setSharedAssociations(new InMemoryServerAssociationStore());
    serverManager.setPrivateAssociations(new InMemoryServerAssociationStore());
    String location = "https://" + request.getServerName();
    if (request.getServerPort() != 443) {
        location += ":" + request.getServerPort();
    }
    location += "/eid-idp";
    String opEndpointUrl = location + "/protocol/" + getPath();
    LOG.debug("OP endpoint URL: " + opEndpointUrl);
    serverManager.setOPEndpointUrl(opEndpointUrl);
    servletContext.setAttribute(getServiceManagerAttribute(), serverManager);
    return serverManager;
}

From source file:com.company.project.core.connector.AadController.java

@Override
protected void doGet(final SlingHttpServletRequest httpRequest, final SlingHttpServletResponse resp)
        throws ServletException, IOException {
    final Resource resource = httpRequest.getResource();
    resp.getOutputStream().println(resource.toString());
    resp.getOutputStream().println("This content is generated by the new SimpleServlet");

    HttpSession session = httpRequest.getSession();
    AuthenticationResult result = (AuthenticationResult) session
            .getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
    if (result == null) {
        resp.getOutputStream().println("AuthenticationResult not found in session.");
    } else {/*from   ww  w.  j a v a  2s.  c o m*/
        String data;
        try {
            data = this.getUsernamesFromGraph(result.getAccessToken(),
                    session.getServletContext().getInitParameter("tenant"));
            // model.addAttribute("users", data);
            resp.getOutputStream().println("Data looks like: " + data);
        } catch (Exception e) {
            // model.addAttribute("error", e);
            //  return "/error";
        }
    }
    // return "/secure/aad";       
}

From source file:org.intermine.web.struts.PortalQueryAction.java

/**
 * Link-ins from other sites end up here (after some redirection).
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return an ActionForward object defining where control goes next
 *
 * @exception Exception if the application business logic throws
 *  an exception/*from w w w  .  j  a  v a2s.com*/
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    ServletContext servletContext = session.getServletContext();

    String origin = request.getParameter("origin");
    String className = request.getParameter("class");
    String extId = request.getParameter("externalid");
    if (StringUtils.isBlank(extId)) {
        extId = request.getParameter("externalids");
    }

    // Add a message to welcome the user
    Properties properties = SessionMethods.getWebProperties(servletContext);
    String welcomeMsg = properties.getProperty("portal.welcome." + origin);
    if (StringUtils.isEmpty(welcomeMsg)) {
        welcomeMsg = properties.getProperty("portal.welcome");
    }
    if (!StringUtils.isBlank(welcomeMsg)) {
        SessionMethods.recordMessage(welcomeMsg, session);
    }

    if (StringUtils.isBlank(extId)) {
        recordError(new ActionMessage("errors.badportalidentifiers"), request);
        return mapping.findForward("failure");
    }

    String[] idList = extId.split(",");

    // Use the old way = quicksearch template in case some people used to link in
    // without class name
    if ((idList.length == 1) && (className == null || className.length() == 0)) {
        String defaultClass = properties.getProperty("webapp.portal.defaultClass");
        BagQueryRunner bagRunner = im.getBagQueryRunner();
        BagQueryResult bqr = bagRunner.searchForBag(defaultClass, Arrays.asList(idList), null, false);

        Map<Integer, List> matches = bqr.getMatches();
        Map<String, Map<String, Map<String, List>>> issues = bqr.getIssues();
        if (matches.isEmpty() && issues.isEmpty()) {
            return new ForwardParameters(mapping.findForward("noResults")).forward();
        }

        // check the matches first...
        for (Map.Entry<Integer, List> entry : matches.entrySet()) {
            String id = entry.getKey().toString();
            return new ForwardParameters(mapping.findForward("report")).addParameter("id", id).forward();
        }

        // and if there are none check the issues
        for (Entry<String, Map<String, Map<String, List>>> issue : issues.entrySet()) {

            Set<String> queryType = issue.getValue().keySet();
            for (String qt : queryType) {
                Object obj = issue.getValue().get(qt).get(idList[0]).get(0);

                // parse the string representation of the object
                String ob = obj.toString().substring(obj.toString().indexOf('[') + 1);
                String id = null;
                String[] result = ob.split(", ");
                for (String token : result) {
                    String[] pair = token.split("=");
                    if ("id".equalsIgnoreCase(pair[0])) {
                        id = pair[1].replaceAll("\"", "").replaceAll("]", "");
                        return new ForwardParameters(mapping.findForward("report")).addParameter("id", id)
                                .forward();
                    }
                    continue;
                }
            }
        }
    }

    Model model = im.getModel();
    WebConfig webConfig = SessionMethods.getWebConfig(request);
    BagQueryConfig bagQueryConfig = im.getBagQueryConfig();

    // If the class is not in the model, we can't continue
    className = StringUtil.capitalise(className);
    if (model.getClassDescriptorByName(className) == null) {
        recordError(new ActionMessage("errors.badportalclass"), request);
        return goToNoResults(mapping, session);
    }

    PathQuery pathQuery = new PathQuery(model);
    pathQuery.addViews(PathQueryResultHelper.getDefaultViewForClass(className, model, webConfig, null));
    pathQuery.addConstraint(Constraints.lookup(className, extId, null));

    Map<String, BagQueryResult> returnBagQueryResults = new HashMap<String, BagQueryResult>();
    Profile profile = SessionMethods.getProfile(session);
    WebResultsExecutor executor = im.getWebResultsExecutor(profile);
    WebResults webResults = executor.execute(pathQuery, returnBagQueryResults);

    String bagName = NameUtil.generateNewName(profile.getSavedBags().keySet(), "link");
    List<Integer> bagList = new ArrayList<Integer>();

    // There's only one node, get the first value
    BagQueryResult bagQueryResult = returnBagQueryResults.values().iterator().next();
    bagList.addAll(bagQueryResult.getMatchAndIssueIds());

    DisplayLookupMessageHandler.handleMessages(bagQueryResult, session, properties, className, null);

    ActionMessages actionMessages = new ActionMessages();

    // Use custom converters
    Set<AdditionalConverter> additionalConverters = bagQueryConfig.getAdditionalConverters(className);
    if (additionalConverters != null) {
        for (AdditionalConverter additionalConverter : additionalConverters) {

            // constraint value, eg. organism name
            String extraValue = PortalHelper.getAdditionalParameter(request, additionalConverter.getUrlField());

            if (StringUtils.isNotEmpty(extraValue)) {
                BagConverter bagConverter = PortalHelper.getBagConverter(im, webConfig,
                        additionalConverter.getClassName());
                List<Integer> converted = bagConverter.getConvertedObjectIds(profile, className, bagList,
                        extraValue);
                // No matches
                if (converted.size() <= 0) {
                    actionMessages.add(Constants.PORTAL_MSG,
                            new ActionMessage("portal.noorthologues", extraValue, extId));
                    session.setAttribute(Constants.PORTAL_MSG, actionMessages);
                    return goToResults(mapping, session, webResults);
                }
                actionMessages.add(Constants.PORTAL_MSG,
                        bagConverter.getActionMessage(extId, converted.size(), className, extraValue));
                session.setAttribute(Constants.PORTAL_MSG, actionMessages);

                if (converted.size() == 1) {
                    return goToReport(mapping, converted.get(0).toString());
                }
                InterMineBag imBag = profile.createBag(bagName, className, "", im.getClassKeys());
                return createBagAndGoToBagDetails(mapping, imBag, converted);
            }
        }
    }

    attachMessages(actionMessages, className, bagQueryResult.getMatches().size(), bagList.size(), extId);

    session.setAttribute(Constants.PORTAL_MSG, actionMessages);

    // more than one result but only one ID
    if ((bagList.size() > 1) && (idList.length == 1)) {
        return goToResults(mapping, session, webResults);
        // one ID searched for one ID found
    } else if ((bagList.size() == 1) && (idList.length == 1)) {
        return goToReport(mapping, bagList.get(0).toString());
        // lots of results, make a list
    } else if (bagList.size() >= 1) {
        InterMineBag imBag = profile.createBag(bagName, className, "", im.getClassKeys());
        return createBagAndGoToBagDetails(mapping, imBag, bagList);
        // No matches
    } else {
        return goToResults(mapping, session, webResults);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.DefaultAddMissingIndividualFormGenerator.java

private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
    //Here, retrieve model from 
    OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
    //if object property
    if (EditConfigurationUtils.isObjectProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)) {
        Individual objectIndividual = EditConfigurationUtils.getObjectIndividual(vreq);
        if (!isReplaceWithNew(vreq) && (isForwardToCreateButEdit(vreq) || objectIndividual != null)) {
            editConfiguration.prepareForObjPropUpdate(model);
        } else {//from ww  w.j  a  v  a 2 s  .  co m
            //new object to be created
            editConfiguration.prepareForNonUpdate(model);
        }
    } else {
        log.error("Data property not object property so update can't be done correctly");

    }
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.ui.SSOAssertionConsumerService.java

private void handleFederatedSAMLRequest(HttpServletRequest req, HttpServletResponse resp, String ssoTokenID,
        String samlRequest, String relayState, String authMode, Subject subject, String rpSessionId)
        throws IOException, ServletException, SAML2SSOUIAuthenticatorException {
    // Instantiate the service client.
    HttpSession session = req.getSession();
    String serverURL = CarbonUIUtil.getServerURL(session.getServletContext(), session);
    ConfigurationContext configContext = (ConfigurationContext) session.getServletContext()
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    SAMLSSOServiceClient ssoServiceClient = new SAMLSSOServiceClient(serverURL, configContext);

    String method = req.getMethod();
    boolean isPost = false;

    if ("post".equalsIgnoreCase(method)) {
        isPost = true;/*from   w w  w .  j av a  2  s . co  m*/
    }

    SAMLSSOReqValidationResponseDTO signInRespDTO = ssoServiceClient.validate(samlRequest, null, ssoTokenID,
            rpSessionId, authMode, isPost);
    if (signInRespDTO.getValid()) {
        handleRequestFromLoginPage(req, resp, ssoTokenID, signInRespDTO.getAssertionConsumerURL(),
                signInRespDTO.getId(), signInRespDTO.getIssuer(), subject.getNameID().getValue(),
                subject.getNameID().getValue(), signInRespDTO.getRpSessionId(),
                signInRespDTO.getRequestMessageString(), relayState);
    }
}