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:com.orchestra.portale.controller.ColellaController.java

@RequestMapping(value = "/colellaImport")
public @ResponseBody String colellaImport(HttpServletRequest request) {

    HttpSession session = request.getSession();
    ServletContext sc = session.getServletContext();
    String folder = sc.getRealPath("/") + "dist" + File.separator + "colella";

    List<Produttore> pList = XMLParser.parseCartellaProduttori(folder);

    for (Produttore prod : pList) {
        System.out.println("*******************************");

        //Dati obbligatori
        CompletePOI p = new CompletePOI();
        String den = prod.getDenominazione().replace("'", "&#039;");
        den = den.replace("\"", "&quot;").replace("\n", "").replace("\r", "");
        p.setName(den);/*from   w  w  w .j  a v a  2s  .c  om*/

        System.out.println("Name: " + p.getName());

        p.setVisibility("1");
        p.setLocation(
                new double[] { Double.parseDouble(prod.getSedeLat()), Double.parseDouble(prod.getSedeLon()) });
        p.setAddress(prod.getSedeVia());
        if (prod.getDescrizione() != null && !prod.getDescrizione().trim().equals("")) {
            if (prod.getDescrizione().length() <= 100) {
                String desc = prod.getDescrizione().replace("'", "&#039;");
                desc = desc.replace("\"", "&quot;").replace("\n", "").replace("\r", "");
                p.setShortDescription(desc.substring(0, desc.length()));
            } else {
                String desc = prod.getDescrizione().replace("'", "&#039;");
                desc = desc.replace("\"", "&quot;").replace("\n", "").replace("\r", "");
                p.setShortDescription(desc.substring(0, 100));
            }

            System.out.println(p.getShortDescription());
        }

        ArrayList<String> l = new ArrayList<String>();
        l.add("food");
        p.setCategories(l);

        //componenti
        ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();

        //componente cover
        if (true) {
            CoverImgComponent coverimg = new CoverImgComponent();
            coverimg.setLink("cover.jpg");
            listComponent.add(coverimg);
        }

        //componente contatti
        ContactsComponent contacts_component = new ContactsComponent();
        boolean contacts = false;

        ArrayList<PhoneContact> phoneList = new ArrayList<PhoneContact>();

        //Recapiti telefonici
        if (prod.getTelFissoList() != null && prod.getTelFissoList().size() > 0) {

            for (String t : prod.getTelFissoList()) {

                if (!t.trim().equals("")) {

                    PhoneContact phone = new PhoneContact();
                    phone.setLabel("Fisso");

                    phone.setNumber(t);
                    phoneList.add(phone);

                    System.out.println("Tel: " + phone.getLabel() + " " + phone.getNumber());
                }

            }
            contacts = true;
            contacts_component.setPhoneList(phoneList);
            for (PhoneContact ph : contacts_component.getPhoneList()) {
                System.out.println("Tel****: " + ph.getLabel() + " " + ph.getNumber());
            }
        }
        if (prod.getTelMobList() != null && prod.getTelMobList().size() > 0) {

            for (String t : prod.getTelMobList()) {

                if (!t.trim().equals("")) {
                    PhoneContact phone = new PhoneContact();
                    phone.setLabel("Mobile");

                    phone.setNumber(t);
                    phoneList.add(phone);

                    System.out.println("Tel M: " + phone.getLabel() + " " + phone.getNumber());
                }
            }
            contacts = true;
            contacts_component.setPhoneList(phoneList);
        }
        if (prod.getEmailList() != null && prod.getEmailList().size() > 0) {

            ArrayList<EmailContact> emailList = new ArrayList<EmailContact>();

            for (String t : prod.getEmailList()) {

                if (!t.trim().equals("")) {
                    EmailContact email = new EmailContact();
                    email.setEmail(t);
                    emailList.add(email);

                    System.out.println("Email: " + email.getLabel() + " " + email.getEmail());
                }
            }
            contacts = true;
            contacts_component.setEmailsList(emailList);
        }

        if (prod.getFacebook() != null && !prod.getFacebook().trim().equals("")) {

            contacts_component.setFacebook(prod.getFacebook());
            System.out.println("Face: " + prod.getFacebook());
        }

        if (prod.getTwitter() != null && !prod.getTwitter().trim().equals("")) {

            contacts_component.setTwitter(prod.getTwitter());
            System.out.println("Twit: " + prod.getTwitter());
        }

        if (prod.getWebSite() != null && !prod.getWebSite().trim().equals("")) {
            ArrayList<GenericSocial> customsocial = new ArrayList<GenericSocial>();
            GenericSocial social = new GenericSocial();
            contacts = true;
            social.setLabel("Website");
            social.setSocial(prod.getWebSite());
            customsocial.add(social);
            contacts_component.setSocialList(customsocial);

            System.out.println("Social: " + social.getLabel() + " " + social.getSocial());
        }
        if (contacts) {
            System.out.println("### INSERT CONTACTS ###### SIZE: " + contacts_component.getPhoneList().size());

            listComponent.add(contacts_component);
        }

        //DESCRIPTION COMPONENT
        if (prod.getDescrizione() != null && !prod.getDescrizione().trim().equals("")) {
            ArrayList<Section> list = new ArrayList<Section>();

            //descrizione
            Section section = new Section();
            section.setDescription(prod.getDescrizione());
            list.add(section);
            System.out.println("Desc: " + section.getDescription());

            //dati storici
            if (prod.getDatiStorici() != null && !prod.getDatiStorici().trim().equals("")) {
                Section section_d = new Section();
                section_d.setTitle("Dati Storici");
                section_d.setDescription(prod.getDatiStorici());
                list.add(section_d);
                System.out.println("Dati Sto: " + section_d.getDescription());
            }

            //curiosit
            if (prod.getCuriosita() != null && !prod.getCuriosita().trim().equals("")) {
                Section section_c = new Section();
                section_c.setTitle("Curiosit");
                section_c.setDescription(prod.getCuriosita());
                list.add(section_c);
                System.out.println("Curiosita: " + section_c.getDescription());
            }

            //note
            if (prod.getNoteList() != null && prod.getNoteList().size() > 0) {

                for (String n : prod.getNoteList()) {

                    if (!n.trim().equals("")) {

                        Section section_n = new Section();
                        section_n.setTitle("Note");
                        section_n.setDescription(n);
                        list.add(section_n);

                        System.out.println("Note: " + section_n.getDescription());
                    }
                }

            }

            DescriptionComponent description_component = new DescriptionComponent();
            description_component.setSectionsList(list);
            listComponent.add(description_component);
        }

        p.setComponents(listComponent);

        pm.savePoi(p);

        System.out.println(prod.getDenominazione());
    }

    return "ok";

}

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

/**
 * If the found jar files have frontend files, they will be extracted and
 * copied into the frontend folder of the core module. Before copying,
 * existing frontend files of the same module will be deleted from the core
 * module. Afterwards the created temporary folder will be deleted as well.
 *///w  w w  .j a  v  a2s . c  om
private void loadFrontendFilesIntoCore() {

    Path moduleFolder = FileSystems.getDefault().getPath(modulePath);

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, JAR)) {

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

                if (hasFrontendFiles(jarFile)) {

                    Path temporaryFolder = Files.createTempDirectory(SYSTEM_TEMP_FOLDER, TEMP_DIR_PREFIX);

                    File tempDir = new File(Paths.get(temporaryFolder.toUri()).toAbsolutePath().toString());

                    extractFrontEndFiles(loc.getAbsolutePath(), tempDir);

                    String moduleName = extractModuleName(tempDir);
                    if (!moduleName.isEmpty()) {
                        FacesContext facesContext = FacesContext.getCurrentInstance();
                        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);

                        String filePath = session.getServletContext().getRealPath(File.separator + PAGES_FOLDER)
                                + File.separator + moduleName;
                        FileUtils.deleteDirectory(new File(filePath));

                        String resourceFolder = String.join(File.separator,
                                Arrays.asList(tempDir.getAbsolutePath(), META_INF_FOLDER, RESOURCES_FOLDER));
                        copyFrontEndFiles(resourceFolder, filePath);
                    } else {
                        logger.info("No module found in JarFile '" + jarFile.getName() + "'.");
                    }
                    FileUtils.deleteDirectory(tempDir);
                }
            }
        }
    } catch (Exception e) {
        logger.error(ERROR, e.getMessage());
    }
}

From source file:com.orchestra.portale.controller.EditDeepeningPageController.java

@RequestMapping(value = "/updatedpage", method = RequestMethod.POST)
public ModelAndView updatePoi(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam(value = "file", required = false) MultipartFile[] files,
        @RequestParam(value = "cover", required = false) MultipartFile cover,
        @RequestParam(value = "fileprec", required = false) String[] fileprec,
        @RequestParam(value = "imgdel", required = false) String[] imgdel) throws InterruptedException {

    DeepeningPage poi = pm.findDeepeningPage(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }/*from ww w . ja  va 2s. c om*/
    }
    ModelAndView model = new ModelAndView("okpageadmin");
    model.addObject("mess", "PAGINA MODIFICATA CORRETTAMENTE!");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    poi.setName(params.get("name"));

    int i = 1;
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 0) {
        while (i < files.length) {
            ImgGallery img = new ImgGallery();
            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("newcredit" + (i + 1)))
                img.setCredit(params.get("newcredit" + (i + 1)));
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1)))
                img.setCredit(params.get("credit" + (iximg + 1)));
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {

        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    poi.setComponents(listComponent);

    pm.saveDeepeningPage(poi);

    DeepeningPage poi2 = pm.findDeepeningPageByName(poi.getName());

    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            System.out.println("FILE CREATO IN POSIZIONE:" + serverFile.getAbsolutePath().toString());

        } catch (Exception e) {
            e.printStackTrace();
            return model;
        }
    }
    if (!cover.isEmpty()) {
        MultipartFile file = cover;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE

    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }

    return model;
}

From source file:com.wyp.module.controller.LicenseController.java

public String generateCitrixLicense(HttpSession session, License license) {
    Properties properties = new Properties();
    String responseJson = "";
    try {//from   w w  w  .ja  v a2  s .  c  o m
        properties.load(
                session.getServletContext().getResourceAsStream("/WEB-INF/classes/citrixInfo.properties"));
    } catch (IOException e) {
        return "?citrixInfo.properties";
    }
    initProperties(properties);
    String address = map.get("address");
    String version = map.get("version");
    String oemKey = map.get("oem_key");
    String secret = map.get("secret");
    if (null == address || "".equals(address.trim())) {
        return "citrix webservice?";
    }
    if (null == version || "".equals(version.trim())) {
        return "version";
    }
    if (null == oemKey || "".equals(oemKey.trim())) {
        return "oem_key";
    }
    if (null == secret || "".equals(secret.trim())) {
        return "secret";
    }
    license.setName("inspur");
    license.setAddress1("");
    license.setAddress2("?");
    license.setCity("");
    license.setState("inspur");
    license.setPostalcode("");
    license.setCompany("");
    license.setCountry("");
    license.setEditon("premium");// premium
    license.setSockets("56");
    license.setRequestUUID(UUID.randomUUID().toString());

    // ?json
    String requestJson = assembRequestJson(license);
    // ?license
    String licenses = getCitrixLicense(requestJson);
    if ("TIMEOUT".equals(licenses)) {
        licenses = getCitrixLicense(requestJson);
    }

    return responseJson;
}

From source file:eu.impact_project.wsclient.SOAPresults.java

/**
 * Loads the user values/files and sends them to the web service. Files are
 * encoded to Base64. Stores the resulting message in the session and the
 * resulting files on the server./*from  w ww  .  ja  va 2s  .com*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream outStream = null;
    BufferedInputStream bis = null;
    user = request.getParameter("user");
    pass = request.getParameter("pass");

    try {

        HttpSession session = request.getSession(true);

        String folder = session.getServletContext().getRealPath("/");
        if (!folder.endsWith("/")) {
            folder = folder + "/";
        }

        Properties props = new Properties();
        InputStream stream = new URL("file:" + folder + "config.properties").openStream();

        props.load(stream);
        stream.close();

        boolean loadDefault = Boolean.parseBoolean(props.getProperty("loadDefaultWebService"));
        boolean supportFileUpload = Boolean.parseBoolean(props.getProperty("supportFileUpload"));
        boolean oneResultFile = Boolean.parseBoolean(props.getProperty("oneResultFile"));
        String defaultFilePrefix = props.getProperty("defaultFilePrefix");

        SoapService serviceObject = (SoapService) session.getAttribute("serviceObject");
        SoapOperation operation = null;
        if (supportFileUpload) {

            // stores all the strings and encoded files from the html form
            Map<String, String> htmlFormItems = new HashMap<String, String>();

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                // a normal string field
                if (item.isFormField()) {
                    htmlFormItems.put(item.getFieldName(), item.getString());

                    // uploaded file
                } else {

                    // encode the uploaded file to base64
                    String currentAttachment = new String(Base64.encode(item.get()));

                    htmlFormItems.put(item.getFieldName(), currentAttachment);
                }
            }

            // get the chosen WSDL operation
            String operationName = htmlFormItems.get("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                input.setValue(htmlFormItems.get(input.getName()));
            }

        } else {
            // get the chosen WSDL operation
            String operationName = request.getParameter("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                String[] soapInputValues = request.getParameterValues(input.getName());
                input.clearValues();
                for (String value : soapInputValues) {
                    input.addValue(value);
                }
            }

        }

        List<SoapOutput> outs = operation.execute(user, pass);
        String soapResponse = operation.getResponse();

        String htmlResponse = useXslt(soapResponse, "/SoapToHtml.xsl");

        session.setAttribute("htmlResponse", htmlResponse);
        session.setAttribute("soapResponse", soapResponse);

        // for giving the file names back to the JSP
        List<String> fileNames = new ArrayList<String>();

        // process possible attachments in the response
        List<SoapAttachment> attachments = operation.getReceivedAttachments();
        int i = 0;
        for (SoapAttachment attachment : attachments) {

            // path to the server directory
            String serverPath = getServletContext().getRealPath("/");
            if (!serverPath.endsWith("/")) {
                serverPath = folder + "/";
            }

            // construct the file name for the attachment
            String fileEnding = "";
            String contentType = attachment.getContentType();
            System.out.println("content type: " + contentType);
            if (contentType.equals("image/gif")) {
                fileEnding = ".gif";
            } else if (contentType.equals("image/jpeg")) {
                fileEnding = ".jpg";
            } else if (contentType.equals("image/tiff")) {
                fileEnding = ".tif";
            } else if (contentType.equals("application/vnd.ms-excel")) {
                fileEnding = ".xlsx";
            }

            String fileName = loadDefault ? defaultFilePrefix : "attachedFile";

            String counter = oneResultFile ? "" : i + "";

            String attachedFileName = fileName + counter + fileEnding;

            // store the attachment into the file
            File file = new File(serverPath + attachedFileName);
            outStream = new FileOutputStream(file);

            InputStream inStream = attachment.getInputStream();

            bis = new BufferedInputStream(inStream);

            int bufSize = 1024 * 8;

            byte[] bytes = new byte[bufSize];

            int count = bis.read(bytes);
            while (count != -1 && count <= bufSize) {
                outStream.write(bytes, 0, count);
                count = bis.read(bytes);
            }
            if (count != -1) {
                outStream.write(bytes, 0, count);
            }
            outStream.close();
            bis.close();

            fileNames.add(attachedFileName);
            i++;
        }

        // pass the file names to JSP
        request.setAttribute("fileNames", fileNames);

        request.setAttribute("round3", "round3");
        // get back to JSP
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/interface.jsp");
        rd.forward(request, response);

    } catch (Exception e) {
        logger.error("Exception", e);
        e.printStackTrace();
    } finally {
        if (outStream != null) {
            outStream.close();
        }
        if (bis != null) {
            bis.close();
        }
    }

}

From source file:com.adito.core.GlobalWarningManager.java

@SuppressWarnings("unchecked")
public void coreEvent(CoreEvent evt) {
    if (evt.getId() == CoreEventConstants.LOGON) {
        SessionInfo sessionInfo = evt.getSessionInfo();
        if (sessionInfo != null && sessionInfo.getHttpSession() != null) {
            // Only add warnings to web sessions
            HttpSession session = sessionInfo.getHttpSession();
            User user = sessionInfo.getUser();
            List<GlobalWarning> globalWarnings = (List<GlobalWarning>) session.getServletContext()
                    .getAttribute(Constants.CONTEXT_GLOBAL_WARNINGS);
            if (globalWarnings != null) {
                for (GlobalWarning gw : globalWarnings) {
                    List<User> dismissedByUsers = dismissedWarnings.get(gw.getMessage().getKey());
                    if (dismissedByUsers == null || !dismissedByUsers.contains(user)) {
                        try {
                            if (gw.getType() == GlobalWarning.SUPER_USER
                                    && LogonControllerFactory.getInstance().isAdministrator(user)) {
                                populateSession(session, gw);
                            } else if (gw.getType() == GlobalWarning.MANAGEMENT_USERS && PolicyDatabaseFactory
                                    .getInstance().isAnyAccessRightAllowed(user, true, true, false)) {
                                populateSession(session, gw);
                            } else if (gw.getType() == GlobalWarning.USERS_WITH_PERMISSIONS
                                    && PolicyDatabaseFactory.getInstance().isPermitted(
                                            gw.getRequiredResourceType(), gw.getRequiredPermissions(), user,
                                            false)) {
                                populateSession(session, gw);
                            } else if (gw.getType() == GlobalWarning.ALL_USERS) {
                                populateSession(session, gw);
                            }/*from   w  ww . j a  va 2  s.c  o m*/
                        } catch (Exception e) {
                            log.error("Failed to add global message. ", e);
                        }
                    }
                }
            }
        }
    }

}

From source file:com.silverpeas.authentication.AuthenticationServlet.java

/**
 * Write session cookie.//  ww  w.j a va  2 s  .com
 *
 * @return
 */
private void writeSessionCookie(HttpServletResponse response, HttpSession session, boolean secured) {
    Cookie cookie = new Cookie("JSESSIONID", session.getId());
    cookie.setMaxAge(-1);
    cookie.setPath(session.getServletContext().getContextPath());
    cookie.setHttpOnly(true);
    if (secured) {
        cookie.setSecure(secured);
    }
    response.addCookie(cookie);
}

From source file:org.snaker.framework.form.web.FormController.java

/**
 * ?// w  ww.  j av  a  2s .  co m
 * @param id
 * @param html
 * @return
 */
@RequestMapping(value = "designer/save", method = RequestMethod.POST)
@ResponseBody
public String designerSave(Long id, String html, HttpSession session) {
    Form form = formManager.get(id);
    String newHtml = htmlProcessor.processHtml(html);
    newHtml = newHtml.replaceAll("selvalue=\"", "");
    newHtml = newHtml.replaceAll("##\"", "");
    form.setHtml(newHtml);
    System.out.println(form.getHtml());
    String templatePath = session.getServletContext().getRealPath("/") + "/workflow/templates/flow/forms/";
    formManager.save(form, templatePath);
    return "success";
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.authenticate.BasicAuthenticator.java

private void notifyOtherUsersOfLogout(HttpSession session) {
    String userUri = LoginStatusBean.getBean(session).getUserURI();
    if ((userUri == null) || userUri.isEmpty()) {
        return;/* w ww.  j  a  va  2s .c om*/
    }

    Authenticate.sendLoginNotifyEvent(new LogoutEvent(userUri), session.getServletContext(), session);
}

From source file:com.flexive.war.listener.SessionTimeoutListener.java

@Override
public void sessionDestroyed(HttpSessionEvent event) {
    final HttpSession session = event.getSession();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Session destroyed: " + session.getId());
    }// w ww . ja v  a  2 s. c om
    // set parameters needed for logout
    final FxContext ctx = FxContext.get();

    try {
        ctx.setSessionID(session.getId());

        // retrieve context path
        final ServletContext servletContext = session.getServletContext();
        if (servletContext != null) {
            ctx.setContextPath(servletContext.getContextPath());
        }

        // get division ID from session
        final String divisionIdKey = FxSessionWrapper.encodeAttributeName(FxContext.SESSION_DIVISIONID);
        if (session.getAttribute(divisionIdKey) != null) {
            ctx.setDivisionId((Integer) session.getAttribute(divisionIdKey));
        }

        if (ctx.getDivisionId() == -1 || !CacheAdmin.isEnvironmentLoaded()) {
            // probably during undeploy
            return;
        }

        ctx.setTicket(FxContext.getTicketFromEJB(session));
        if (!ctx.getTicket().isGuest()) {
            // perform logout only when the user is logged in
            if (LOG.isDebugEnabled()) {
                LOG.debug("Performing logout for user of destroyed session (possible session timeout): "
                        + session.getId());
            }

            onLogout(ctx.getTicket());

            ctx.logout();
        }
    } catch (FxLogoutFailedException e) {
        LOG.error("Failed to logout user after session timeout: " + e.getMessage(), e);
    } finally {
        FxContext.cleanup();
    }
}