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.apache.ofbiz.order.order.OrderEvents.java

public static String downloadDigitalProduct(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    ServletContext application = session.getServletContext();
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    String dataResourceId = request.getParameter("dataResourceId");

    try {/*from  www. j a v a 2s.c om*/
        // has the userLogin.partyId ordered a product with DIGITAL_DOWNLOAD content associated for the given dataResourceId?
        GenericValue orderRoleAndProductContentInfo = EntityQuery.use(delegator)
                .from("OrderRoleAndProductContentInfo")
                .where("partyId", userLogin.get("partyId"), "dataResourceId", dataResourceId,
                        "productContentTypeId", "DIGITAL_DOWNLOAD", "statusId", "ITEM_COMPLETED")
                .queryFirst();

        if (orderRoleAndProductContentInfo == null) {
            request.setAttribute("_ERROR_MESSAGE_",
                    "No record of purchase for digital download found (dataResourceId=[" + dataResourceId
                            + "]).");
            return "error";
        }

        // TODO: check validity based on ProductContent fields: useCountLimit, useTime/useTimeUomId

        if (orderRoleAndProductContentInfo.getString("mimeTypeId") != null) {
            response.setContentType(orderRoleAndProductContentInfo.getString("mimeTypeId"));
        }
        OutputStream os = response.getOutputStream();
        GenericValue dataResource = EntityQuery.use(delegator).from("DataResource")
                .where("dataResourceId", dataResourceId).cache().queryOne();
        Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "",
                application.getInitParameter("webSiteId"), UtilHttp.getLocale(request),
                application.getRealPath("/"), false);
        os.write(IOUtils.toByteArray((ByteArrayInputStream) resourceData.get("stream")));
        os.flush();
    } catch (GenericEntityException e) {
        String errMsg = "Error downloading digital product content: " + e.toString();
        Debug.logError(e, errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    } catch (GeneralException e) {
        String errMsg = "Error downloading digital product content: " + e.toString();
        Debug.logError(e, errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    } catch (IOException e) {
        String errMsg = "Error downloading digital product content: " + e.toString();
        Debug.logError(e, errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    return "success";
}

From source file:edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties.java

public static ConfigurationProperties getBean(HttpSession session) {
    if (session == null) {
        throw new NullPointerException("session may not be null.");
    }//from  w w w  .  j  a va  2 s .com
    return getBean(session.getServletContext());
}

From source file:edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale.java

/**
 * Do we need to override the Locale in the current request? return the
 * first of these to be found://  w w  w . jav  a2s  .co m
 * <ul>
 * <li>The forced Locale in the servlet context</li>
 * <li>The selected Locale in the session</li>
 * <li>The first of the selectable Locales</li>
 * <li>null</li>
 * </ul>
 */
public static Locale getOverridingLocale(HttpServletRequest req) {
    HttpSession session = req.getSession();
    ServletContext ctx = session.getServletContext();

    Object ctxInfo = ctx.getAttribute(ATTRIBUTE_NAME);
    if (ctxInfo instanceof ContextSelectedLocale) {
        Locale forcedLocale = ((ContextSelectedLocale) ctxInfo).getForcedLocale();
        if (forcedLocale != null) {
            log.debug("Found forced locale in the context: " + forcedLocale);
            return forcedLocale;
        }
    }

    Object sessionInfo = session.getAttribute(ATTRIBUTE_NAME);
    if (sessionInfo instanceof SessionSelectedLocale) {
        Locale selectedLocale = ((SessionSelectedLocale) sessionInfo).getSelectedLocale();
        if (selectedLocale != null) {
            log.debug("Found selected locale in the session: " + selectedLocale);
            return selectedLocale;
        }
    }

    if (ctxInfo instanceof ContextSelectedLocale) {
        List<Locale> selectableLocales = ((ContextSelectedLocale) ctxInfo).getSelectableLocales();
        if (selectableLocales != null && !selectableLocales.isEmpty()) {
            Locale defaultLocale = selectableLocales.get(0);
            log.debug("Using first selectable locale as default: " + defaultLocale);
            return defaultLocale;
        }
    }

    return null;
}

From source file:de.sub.goobi.config.ConfigMain.java

/**
 * den absoluten Pfad fr die temporren Images zurckgeben ================================================================
 *///from  www . j  av a  2  s  . co  m
public static String getTempImagesPathAsCompleteDirectory() {
    FacesContext context = FacesContext.getCurrentInstance();
    String filename;
    if (imagesPath != null) {
        filename = imagesPath;
    } else {
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        filename = session.getServletContext().getRealPath("/pages/imagesTemp") + File.separator;

        /* den Ordner neu anlegen, wenn er nicht existiert */
        try {
            FilesystemHelper.createDirectory(filename);
        } catch (Exception ioe) {
            myLogger.error("IO error: " + ioe);
            Helper.setFehlerMeldung(Helper.getTranslation("couldNotCreateImageFolder"), ioe.getMessage());
        }
    }
    return filename;
}

From source file:com.icesoft.icefaces.tutorial.component.autocomplete.AutoCompleteDictionary.java

private static void init() {
    // Raw list of xml cities.
    List cityList = null;//w  w  w. j  ava 2  s  . c  om

    // load the city dictionary from the compressed xml file.

    // get the path of the compressed file
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    String basePath = session.getServletContext().getRealPath("/WEB-INF/resources");
    basePath += "/city.xml.zip";

    // extract the file
    ZipEntry zipEntry;
    ZipFile zipFile;
    try {
        zipFile = new ZipFile(basePath);
        zipEntry = zipFile.getEntry("city.xml");
    } catch (Exception e) {
        log.error("Error retrieving records", e);
        return;
    }

    // get the xml stream and decode it.
    if (zipFile.size() > 0 && zipEntry != null) {
        try {
            BufferedInputStream dictionaryStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));
            XMLDecoder xDecoder = new XMLDecoder(dictionaryStream);
            // get the city list.
            cityList = (List) xDecoder.readObject();
            dictionaryStream.close();
            zipFile.close();
            xDecoder.close();
        } catch (ArrayIndexOutOfBoundsException e) {
            log.error("Error getting city list, not city objects", e);
            return;
        } catch (IOException e) {
            log.error("Error getting city list", e);
            return;
        }
    }

    // Finally load the object from the xml file.
    if (cityList != null) {
        dictionary = new ArrayList(cityList.size());
        City tmpCity;
        for (int i = 0, max = cityList.size(); i < max; i++) {
            tmpCity = (City) cityList.get(i);
            if (tmpCity != null && tmpCity.getCity() != null) {
                dictionary.add(new SelectItem(tmpCity, tmpCity.getCity()));
            }
        }
        cityList.clear();
        // finally sort the list
        Collections.sort(dictionary, LABEL_COMPARATOR);
    }

}

From source file:edu.cornell.mannlib.vedit.beans.LoginStatusBean.java

/**
 * Get the current user, or null if not logged in.
 *//* ww w. j a  v a 2s. c  om*/
public static UserAccount getCurrentUser(HttpSession session) {
    if (session == null) {
        return null;
    }

    if (!getBean(session).isLoggedIn()) {
        return null;
    }

    ServletContext ctx = session.getServletContext();
    WebappDaoFactory wadf = ModelAccess.on(ctx).getWebappDaoFactory();
    UserAccountsDao userAccountsDao = wadf.getUserAccountsDao();
    if (userAccountsDao == null) {
        log.error("No UserAccountsDao");
        return null;
    }

    String userUri = getBean(session).getUserURI();
    return userAccountsDao.getUserAccountByUri(userUri);
}

From source file:org.kitodo.production.plugin.opac.pica.UGHUtils.java

/**
 * The function open() opens a file. In a user session context, the file is
 * taken from the web applications deployment directory
 * (/WEB-INF/classes), if not, it is taken from the CONFIG_DIR specified in
 * the CONFIG_FILE.//from w ww .j  a v a  2s  .  c om
 *
 * TODO: Community needs to decide: Is this behaviour really what we want?
 * Shouldnt it <em>always</em> be the configured directory?
 *
 * @param fileName
 *            File to open
 * @return a BufferedReader for reading the file
 * @throws FileNotFoundException
 *             if the file does not exist, is a directory rather than a
 *             regular file, or for some other reason cannot be opened for
 *             reading
 * @throws UnsupportedEncodingException
 *             If the named charset is not supported
 */
private static BufferedReader open(String fileName) throws IOException {
    String path = PicaPlugin.getConfigDir();
    FacesContext context = FacesContext.getCurrentInstance();
    if (context != null) {
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        path = FilenameUtils.concat(session.getServletContext().getRealPath("/WEB-INF"), "classes");
    }
    String file = FilenameUtils.concat(path, fileName);
    return new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
}

From source file:com.orchestra.portale.externalauth.FbAuthenticationManager.java

public static User fbLoginJs(HttpServletRequest request, HttpServletResponse response,
        UserRepository userRepository) {

    //Get access_token from request
    String access_token = request.getParameter("access_token");
    User user = null;//  www.j  a va  2  s  . c o  m

    if (StringUtils.isNotEmpty(access_token)) {

        try {

            Boolean validity = FacebookUtils.ifTokenValid(access_token);

            //if token is valid, retrieve userid and email from Facebook
            if (validity) {
                Map<String, String> userId_mail = FacebookUtils.getUserIDMail(access_token);
                String id = userId_mail.get("id");
                String email = userId_mail.get("email");

                try {
                    user = fbUserCheck(id, email, userRepository);
                } catch (UserNotFoundException ioex) {
                    /*Retrieve User Data to Registration*/
                    Map<String, String> userData = FacebookUtils.getUserData(access_token);

                    /*Create User*/
                    com.orchestra.portale.persistence.sql.entities.User new_user = new com.orchestra.portale.persistence.sql.entities.User();
                    new_user.setFbEmail(userData.get("email"));
                    new_user.setFbUser(userData.get("id"));
                    new_user.setUsername(userData.get("email"));
                    new_user.setFirstName(userData.get("firstName"));
                    new_user.setLastName(userData.get("lastName"));
                    new_user.setPassword(new BigInteger(130, new SecureRandom()).toString(32));

                    /*Create Role*/
                    com.orchestra.portale.persistence.sql.entities.Role new_user_role = new com.orchestra.portale.persistence.sql.entities.Role();
                    new_user_role.setRole("ROLE_USER");
                    new_user_role.setUser(new_user);
                    ArrayList<com.orchestra.portale.persistence.sql.entities.Role> new_user_roles = new ArrayList<com.orchestra.portale.persistence.sql.entities.Role>();
                    new_user_roles.add(new_user_role);
                    new_user.setRoles(new_user_roles);

                    /*Save User*/
                    userRepository.save(new_user);

                    //Save user image
                    try {
                        String img_url = userData.get("img");
                        String user_id_img = userRepository.findByUsername(new_user.getUsername()).getId()
                                .toString();

                        HttpSession session = request.getSession();
                        ServletContext sc = session.getServletContext();

                        String destination = sc.getRealPath("/") + "dist" + File.separator + "user"
                                + File.separator + "img" + File.separator + user_id_img + File.separator;

                        NetworkUtils.saveImageFromURL(img_url, destination, "avatar.jpg");

                    } catch (MalformedURLException ex) {
                        throw new FacebookException();
                    } catch (IOException ioexc) {
                        ioexc.getMessage();
                    }

                    /*Create Spring User*/
                    boolean enabled = true;
                    boolean accountNonExpired = true;
                    boolean credentialsNonExpired = true;
                    boolean accountNonLocked = true;

                    user = new User(new_user.getUsername(), new_user.getPassword().toLowerCase(), enabled,
                            accountNonExpired, credentialsNonExpired, accountNonLocked,
                            getAuthorities(new_user.getRoles()));

                }

            }

        } catch (FacebookException ioex) {
            ioex.printStackTrace();
        }

    }

    return user;
}

From source file:edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.java

public static RevisionInfoBean getBean(HttpSession session) {
    if (session == null) {
        log.warn("Tried to get revision info bean with a null session!");
        return DUMMY_BEAN;
    }/*from w  w  w  .  j av  a2 s . c  o m*/

    return getBean(session.getServletContext());
}

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

/**
 * Get the bean from the servlet context. If there is no bean, create one.
 * //from  w w w .  j a  v  a2  s .  c  o  m
 * Never returns null.
 */
public static ExternalAuthHelper getHelper(ServletRequest request) {
    if (!(request instanceof HttpServletRequest)) {
        log.trace("Not an HttpServletRequest: " + request);
        return DUMMY_HELPER;
    }

    HttpSession session = ((HttpServletRequest) request).getSession(false);
    if (session == null) {
        log.trace("No session; no need to create one.");
        return DUMMY_HELPER;
    }

    ServletContext ctx = session.getServletContext();

    Object attr = ctx.getAttribute(BEAN_ATTRIBUTE);
    if (attr instanceof ExternalAuthHelper) {
        log.trace("Found a bean: " + attr);
        return (ExternalAuthHelper) attr;
    }

    ExternalAuthHelper bean = buildBean(ctx);
    log.debug("Created a bean: " + bean);
    setBean(ctx, bean);
    return bean;
}