Example usage for javax.servlet.http Cookie setPath

List of usage examples for javax.servlet.http Cookie setPath

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setPath.

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

From source file:org.madsonic.service.PlayerService.java

/**
 * Returns the player associated with the given HTTP request.  If no such player exists, a new
 * one is created.//from  w w  w . ja va2 s. co  m
 *
 * @param request              The HTTP request.
 * @param response             The HTTP response.
 * @param remoteControlEnabled Whether this method should return a remote-controlled player.
 * @param isStreamRequest      Whether the HTTP request is a request for streaming data.
 * @return The player associated with the given HTTP request.
 */
public synchronized Player getPlayer(HttpServletRequest request, HttpServletResponse response,
        boolean remoteControlEnabled, boolean isStreamRequest) {

    // Find by 'player' request parameter.
    Player player = getPlayerById(request.getParameter("player"));

    // Find in session context.
    if (player == null && remoteControlEnabled) {
        String playerId = (String) request.getSession().getAttribute("player");
        if (playerId != null) {
            player = getPlayerById(playerId);
        }
    }

    // Find by cookie.
    String username = securityService.getCurrentUsername(request);
    if (player == null && remoteControlEnabled) {
        player = getPlayerById(getPlayerIdFromCookie(request, username));
    }

    // Make sure we're not hijacking the player of another user.
    if (player != null && player.getUsername() != null && username != null
            && !player.getUsername().equals(username)) {
        player = null;
    }

    // Look for player with same IP address and user name.
    if (player == null) {
        player = getNonRestPlayerByIpAddressAndUsername(request.getRemoteAddr(), username);
    }

    // If no player was found, create it.
    if (player == null) {
        player = new Player();
        createPlayer(player);
        LOG.debug("Created player " + player.getId() + " (remoteControlEnabled: " + remoteControlEnabled
                + ", isStreamRequest: " + isStreamRequest + ", username: " + username + ", ip: "
                + request.getRemoteAddr() + ").");
    }

    // Update player data.
    boolean isUpdate = false;
    if (username != null && player.getUsername() == null) {
        player.setUsername(username);
        isUpdate = true;
    }
    if (player.getIpAddress() == null || isStreamRequest || (!isPlayerConnected(player) && player.isDynamicIp()
            && !request.getRemoteAddr().equals(player.getIpAddress()))) {
        player.setIpAddress(request.getRemoteAddr());
        isUpdate = true;
    }
    String userAgent = request.getHeader("user-agent");
    if (isStreamRequest) {
        player.setType(userAgent);
        player.setLastSeen(new Date());
        isUpdate = true;
    }

    if (isUpdate) {
        updatePlayer(player);
    }

    // Set cookie in response.
    if (response != null) {
        String cookieName = COOKIE_NAME + "-" + StringUtil.utf8HexEncode(username);
        Cookie cookie = new Cookie(cookieName, player.getId());
        cookie.setMaxAge(COOKIE_EXPIRY);
        String path = request.getContextPath();
        if (StringUtils.isEmpty(path)) {
            path = "/";
        }
        cookie.setPath(path);
        response.addCookie(cookie);
    }

    // Save player in session context.
    if (remoteControlEnabled) {
        request.getSession().setAttribute("player", player.getId());
    }

    return player;
}

From source file:com.vmm.storefront.controllers.pages.ProductPageController.java

@RequestMapping(value = PRODUCT_CODE_PATH_VARIABLE_PATTERN, method = RequestMethod.GET)
public String productDetail(@PathVariable("productCode") final String productCode, final Model model,
        final HttpServletRequest request, final HttpServletResponse response,
        @CookieValue(value = "lastBrowsedProducts", defaultValue = "") String lastBrowsedProducts)
        throws CMSItemNotFoundException, UnsupportedEncodingException {

    // Count of products to be maintained in Cookie
    final int countOfProducts = 20;

    System.out.println("praveen cookie value======" + lastBrowsedProducts);

    if (lastBrowsedProducts.equalsIgnoreCase("")) {
        lastBrowsedProducts = productCode;
    } else {//from   w w w. jav  a  2 s  . c om
        lastBrowsedProducts = listLatestBrowsedProducts(lastBrowsedProducts, productCode, countOfProducts);
    }
    final Cookie foo = new Cookie("lastBrowsedProducts", lastBrowsedProducts);
    foo.setMaxAge(9999999);
    foo.setPath("/");
    response.addCookie(foo);

    System.out.println("praveen cookie added value------------------" + lastBrowsedProducts);

    final List<ProductOption> extraOptions = Arrays.asList(ProductOption.VARIANT_MATRIX_BASE,
            ProductOption.VARIANT_MATRIX_URL, ProductOption.VARIANT_MATRIX_MEDIA);

    final ProductData productData = productFacade.getProductForCodeAndOptions(productCode, extraOptions);

    final String redirection = checkRequestUrl(request, response, productDataUrlResolver.resolve(productData));
    if (StringUtils.isNotEmpty(redirection)) {
        return redirection;
    }

    updatePageTitle(productCode, model);

    populateProductDetailForDisplay(productCode, model, request, extraOptions);

    model.addAttribute(new ReviewForm());
    model.addAttribute("pageType", PageType.PRODUCT.name());
    model.addAttribute("futureStockEnabled", Boolean.valueOf(Config.getBoolean(FUTURE_STOCK_ENABLED, false)));

    final String metaKeywords = MetaSanitizerUtil.sanitizeKeywords(productData.getKeywords());
    final String metaDescription = MetaSanitizerUtil.sanitizeDescription(productData.getDescription());
    setUpMetaData(model, metaKeywords, metaDescription);
    return getViewForPage(model);
}

From source file:de.hska.ld.etherpad.controller.DocumentEtherpadController.java

@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.GET, value = "/edit/{documentId}")
//@Transactional(readOnly = true)
public Callable editDocumentContent(HttpServletResponse response, @PathVariable Long documentId) {
    return () -> {
        Document document = documentService.findById(documentId);
        boolean readOnly = false;

        // check if the User is allowed to access the current Document
        if (document != null) {
            documentService.checkPermission(document, Access.Permission.READ);
            try {
                documentService.checkPermission(document, Access.Permission.WRITE);
            } catch (Exception e) {
                readOnly = true;//from  w  w w .  j a va  2s .  co m
            }
        } else {
            throw new NotFoundException("id");
        }

        // for the given User check whether there is an AuthorId registered in Etherpad
        UserEtherpadInfo firstUserEtherPadInfoCheck = userEtherpadInfoService
                .getUserEtherpadInfoForCurrentUser();
        String authorId = null;
        if (firstUserEtherPadInfoCheck != null) {
            authorId = firstUserEtherPadInfoCheck.getAuthorId();
        }

        //  look up if there is an existing AuthorId associated with the current user
        if (authorId == null) {

            // if there is no AuthorId present register an AuthorId for the current User
            authorId = etherpadClient.createAuthor(Core.currentUser().getFullName());
            userEtherpadInfoService.storeAuthorIdForCurrentUser(authorId);
        }

        // is the GroupPad available for the Document :
        String groupPadId = documentEtherpadInfoService.getGroupPadIdForDocument(document);
        if (groupPadId == null && !"".equals(groupPadId)) {
            //  otherwise create a GroupPad
            String groupId = etherpadClient.createGroup();
            Attachment mainContent = document.getAttachmentList().get(0);
            byte[] mainSource = mainContent.getSource();
            try {
                //String urlEncodedDocumentTitle = URLEncoder.encode(URLEncoder.encode(document.getTitle(), "UTF-8"), "UTF-8");
                String groupPadTitle = UUID.randomUUID().toString();//StringUtils.left(urlEncodedDocumentTitle, 50);
                while (groupPadTitle.endsWith("%")) {
                    groupPadTitle = groupPadTitle.substring(0, groupPadTitle.length() - 1);
                }
                if (mainSource != null) {
                    String discussionText = new String(mainSource, "UTF-8");
                    if (!"".equals(discussionText)) {
                        groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle);
                        //groupPadId = etherpadClient.createGroupPad(groupId, document.getTitle(), discussionText);
                        etherpadClient.setGroupPadContent(groupPadId, discussionText);
                        //setHTML(padID, html)
                    } else {
                        groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle);
                    }
                } else {
                    groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle);
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            //  groupPad is available associate GroupPadId for the Document
            documentEtherpadInfoService.storeGroupPadIdForDocument(groupPadId, document);
        }

        String readOnlyId = null;
        if (readOnly) {
            readOnlyId = documentEtherpadInfoService.getReadOnlyIdForDocument(document);
            if (readOnlyId == null) {
                readOnlyId = etherpadClient.getReadOnlyID(groupPadId);
                if (readOnlyId == null) {
                    throw new ValidationException("Read only id is null"); // TODO change exception type
                } else {
                    documentEtherpadInfoService.storeReadOnlyIdForDocument(readOnlyId, document);
                }
            }
        }

        // create a session between Author and GroupPad
        String groupId = groupPadId.split("\\$")[0];
        long currentTime = System.currentTimeMillis() / 1000L; // current time
        long validUntil = currentTime + 86400L;

        String sessionId = null;
        UserEtherpadInfo userEtherpadInfo = userEtherpadInfoService.getUserEtherpadInfoForCurrentUser();
        sessionId = userEtherpadInfo.getSessionId();
        Long currentValidUntil = userEtherpadInfo.getValidUntil();

        // retrieve sessionID from db if available
        boolean newSessionRequired = false;
        if (sessionId == null) {
            newSessionRequired = true;
        } else {
            boolean isStillValid = false;
            // check if valid until is still valid for more than 3h
            // check if sessionID is still valid (valid for more than 3h)
            /*boolean sameGroupId = userEtherpadInfo.getGroupId().equals(groupId);
            if (sameGroupId && userEtherpadInfo.getGroupId().equals(groupId) && currentValidUntil - currentTime >= 10800) {
            // if sessionID is still valid longer than 3h
            // then send the sessionID to the client
            isStillValid = true;
            } else if (currentValidUntil - currentTime < 10800) {
            newSessionRequired = true;
            } else if (isStillValid) {*/
            // check if the session still exists on the etherpad server (GET)
            isStillValid = etherpadClient.checkIfSessionStillValid(currentTime, sessionId, groupId);
            if (!isStillValid) {
                newSessionRequired = true;
            }
            //}
        }
        if (newSessionRequired) {
            sessionId = etherpadClient.createSession(groupId, authorId, validUntil);

            // store the sessionID into UserEtherpadInfo object
            // store the validUntil value also
            User currentUser = Core.currentUser();
            User dbUser = userService.findById(currentUser.getId());
            userEtherpadInfoService.storeSessionForUser(sessionId, groupId, validUntil, userEtherpadInfo);
        }

        // we need return types, cookie with sessionId and the URL of Etherpads Pad
        javax.servlet.http.Cookie myCookie = new javax.servlet.http.Cookie("sessionID", sessionId);
        myCookie.setPath("/");
        if (!"localhost".equals(env.getProperty("module.core.oidc.server.endpoint.main.domain"))) {
            myCookie.setDomain(env.getProperty("module.core.oidc.server.endpoint.main.domain"));
        }
        response.addCookie(myCookie);
        // return Etherpad URL path
        String padURL = null;
        if (readOnly) {
            padURL = etherpadEndpointExternal + "/p/" + readOnlyId;
        } else {
            padURL = etherpadEndpointExternal + "/p/" + groupPadId;
        }

        return new ResponseEntity<>(padURL, HttpStatus.CREATED);
    };
}

From source file:com.skilrock.lms.embedded.roleMgmt.common.PrivsInterceptor.java

public void createCookie() {
    boolean found = false;
    Cookie userSessionId = null;
    Cookie[] cookies = request.getCookies();
    for (Cookie element : cookies) {
        userSessionId = element;//ww w. java 2  s  . c  o  m
        if (userSessionId.getName().equals("LMSCookie")) {
            found = true;
            break;
        }
        if (!found) {
            userSessionId = new Cookie("LMSCookie", "");
            userSessionId.setMaxAge(24 * 60 * 60);
            userSessionId.setPath("/");
            response.addCookie(userSessionId);
        } else {
            userSessionId.setMaxAge(24 * 60 * 60);
            userSessionId.setPath("/");
            response.addCookie(userSessionId);
        }

    }

}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private String addCookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse,
        final String cookieName, final String cookieValue) {
    if (httpRequest == null || httpResponse == null || cookieName == null || cookieValue == null) {
        throw new PreconditionException("Required parameter is null");
    }//ww  w  .ja v  a2s .  c  o  m
    final Cookie cookie = new Cookie(cookieName, "");
    cookie.setValue(cookieValue);
    cookie.setMaxAge(-1);
    cookie.setSecure(true);
    cookie.setDomain(httpRequest.getServerName());
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    httpResponse.addCookie(cookie);
    return cookie.getValue();
}

From source file:com.xwiki.authentication.trustedldap.TrustedLDAPAuthServiceImpl.java

public XWikiUser checkAuthSSO(String username, String password, XWikiContext context) throws XWikiException {
    Cookie cookie;//  ww w.j  a va  2  s. c  om

    LOG.debug("checkAuth");

    LOG.debug("Action: " + context.getAction());
    if (context.getAction().startsWith("logout")) {
        cookie = getCookie("XWIKISSOAUTHINFO", context);
        if (cookie != null) {
            cookie.setMaxAge(0);
            context.getResponse().addCookie(cookie);
        }

        return null;
    }

    Principal principal = null;

    if (LOG.isDebugEnabled()) {
        Cookie[] cookies = context.getRequest().getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                LOG.debug("CookieList: " + c.getName() + " => " + c.getValue());
            }
        }
    }

    cookie = getCookie("XWIKISSOAUTHINFO", context);
    if (cookie != null) {
        LOG.debug("Found Cookie");
        String uname = decryptText(cookie.getValue(), context);
        if (uname != null) {
            principal = new SimplePrincipal(uname);
        }
    }

    XWikiUser user;

    // Authenticate
    if (principal == null) {
        principal = authenticate(username, password, context);
        if (principal == null) {
            return null;
        }

        LOG.debug("Saving auth cookie");
        String encuname = encryptText(principal.getName().contains(":") ? principal.getName()
                : context.getDatabase() + ":" + principal.getName(), context);
        Cookie usernameCookie = new Cookie("XWIKISSOAUTHINFO", encuname);
        usernameCookie.setMaxAge(-1);
        usernameCookie.setPath("/");
        context.getResponse().addCookie(usernameCookie);

        user = new XWikiUser(principal.getName());
    } else {
        user = new XWikiUser(principal.getName().startsWith(context.getDatabase())
                ? principal.getName().substring(context.getDatabase().length() + 1)
                : principal.getName());
    }

    LOG.debug("XWikiUser=" + user);

    return user;
}

From source file:com.skilrock.lms.web.roleMgmt.common.PrivsInterceptor.java

public void createCookie() {
    boolean found = false;
    Cookie userSessionId = null;
    Cookie[] cookies = request.getCookies();
    for (Cookie element : cookies) {
        userSessionId = element;//from  w w  w  .  ja  va 2s . com
        if (userSessionId.getName().equals("LMSCookie")) {
            found = true;
            break;
        }
    }
    if (!found) {
        userSessionId = new Cookie("LMSCookie", "");
        userSessionId.setMaxAge(24 * 60 * 60);
        userSessionId.setPath("/");
        response.addCookie(userSessionId);
    } else {
        userSessionId.setMaxAge(24 * 60 * 60);
        userSessionId.setPath("/");
        response.addCookie(userSessionId);
    }

}

From source file:de.innovationgate.wga.server.api.Call.java

/**
 * Creates a new completely initialized HTTP cookie, which is not yet assigned to the call.
 * Use {@link #addCookie(Cookie)} to do so and send it to the client.
 * The cookie is initialized with path (the OpenWGA context path), type/maxage (transient),
 * domain (either request host or host from configured server base url) and security
 * flag (true if the current call is HTTPS).
 * @param name Name of the cookie/*from  ww w . j ava  2 s .c  o  m*/
 * @param value Value of the cookie
 * @return
 * @throws WGException
 */
public Cookie createCookie(String name, String value) throws WGException {

    URLBuilder baseURL = _wga.urlBuilder(_wga.server().getBaseURL());
    URLBuilder requestURL = _wga.urlBuilder(getURL());

    Cookie c = new Cookie();
    c.setName(name);
    c.setValue(value);
    c.setMaxAge(-1);
    c.setPath(baseURL.build(false));
    if (_wga.isRequestAvailable()) {
        c.setDomain(requestURL.getHost());
    } else {
        c.setDomain(baseURL.getHost());
    }
    c.setSecure(requestURL.getProtocol().equals("https"));

    return c;

}

From source file:nl.strohalm.cyclos.utils.LoginHelper.java

/**
 * Perform the login itself//from w  w  w.j  av  a2  s  .  c  o  m
 */
public User login(final Class<? extends User> requiredUserClass, final String principalTypeString,
        final String memberUsername, final String principal, final String password, final String channel,
        final HttpServletRequest request, final HttpServletResponse response) throws LoginException {
    final String remoteAddress = request.getRemoteAddr();

    final PrincipalType principalType = channelService.resolvePrincipalType(channel, principalTypeString);

    // Validate the user
    String usernameToVerify = principal;
    if (principalType.getPrincipal() != Principal.USER) {
        try {
            Member member;
            member = elementService.loadByPrincipal(principalType, principal, Element.Relationships.USER,
                    Element.Relationships.GROUP);
            usernameToVerify = member.getUsername();
        } catch (final EntityNotFoundException e) {
            usernameToVerify = "";
        }
    }
    final User user = accessService.verifyLogin(memberUsername, usernameToVerify, remoteAddress);
    if (!requiredUserClass.isInstance(user)) {
        throw new AccessDeniedException();
    }

    // Find the user nature
    final Group group = user.getElement().getGroup();
    final boolean isAdmin = group instanceof AdminGroup;
    final boolean isMember = group instanceof MemberGroup;
    final boolean isBroker = group instanceof BrokerGroup;
    final boolean isOperator = group instanceof OperatorGroup;
    final boolean isPosWeb = RequestHelper.isPosWeb(request);

    final AccessSettings accessSettings = settingsService.getAccessSettings();

    // Check if the administrator is allowed to login
    if (isAdmin && !accessSettings.getAdministrationWhitelistValidator().isAllowed(request.getRemoteHost(),
            request.getRemoteAddr())) {
        throw new AccessDeniedException();
    }

    // According to the cyclos.properties flag, create a new session or use the current one
    HttpSession session;
    if (newSessionAfterLogin) {
        session = createNewSessionForlogin(request);
    } else {
        session = request.getSession();
    }

    // Login the user
    accessService.login(user, password, channel, isPosWeb, remoteAddress, session.getId());

    // Apply the session timeout
    final TimePeriod timeout = isPosWeb ? accessSettings.getPoswebTimeout()
            : isMember ? accessSettings.getMemberTimeout() : accessSettings.getAdminTimeout();
    int timeoutSeconds = (int) timeout.getValueIn(TimePeriod.Field.SECONDS);
    if (timeoutSeconds <= 0) {
        timeoutSeconds = -1;
    }
    session.setMaxInactiveInterval(timeoutSeconds);

    // If is a member, determine if the member has accounts, documents, loan groups and memberPos
    boolean hasAccounts = false;
    boolean singleAccount = false;
    boolean hasDocuments = false;
    boolean hasLoanGroups = false;
    boolean hasGeneralReferences = false;
    boolean hasTransactionFeedbacks = false;
    boolean hasPin = false;
    boolean hasExternalChannels = false;
    boolean hasCards = false;
    boolean hasPos = false;
    boolean hasCommissionContracts = false;
    if (isMember || isOperator) {
        Member member;
        if (isMember) {
            member = ((MemberUser) user).getMember();

            // Get the accessible channels
            final MemberGroup memberGroup = groupService.load(member.getMemberGroup().getId(),
                    MemberGroup.Relationships.CHANNELS);
            hasPin = groupService.usesPin(memberGroup);
            for (final Channel current : memberGroup.getChannels()) {
                if (!Channel.WEB.equals(current.getInternalName())) {
                    hasExternalChannels = true;
                    break;
                }
            }

            if (!member.getPosDevices().isEmpty()) {
                hasPos = true;
                if (member.getPosDevices().size() == 1) {
                    final Collection<MemberPos> memberPos = member.getPosDevices();
                    for (final MemberPos mpos : memberPos) {
                        session.setAttribute("uniqueMemberPosId ", mpos.getPos().getId());
                    }
                }
            }

        } else {
            member = ((OperatorUser) user).getOperator().getMember();
        }
        // Fetch broker
        member = elementService.load(member.getId(), Member.Relationships.BROKER);
        final MemberGroup memberGroup = member.getMemberGroup();

        // Check if the member has accounts
        final List<? extends Account> accounts = accountService.getAccounts(member);
        hasAccounts = !accounts.isEmpty();
        singleAccount = accounts.size() == 1;
        if (isMember) {
            // Check if the member has documents
            if (permissionService.hasPermission(MemberPermission.DOCUMENTS_VIEW)) {
                hasDocuments = true;
            } else {
                final DocumentQuery documentQuery = new DocumentQuery();
                documentQuery.setNatures(Collections.singleton(Document.Nature.MEMBER));
                documentQuery.setMember(member);
                documentQuery.setPageForCount();
                hasDocuments = PageHelper.hasResults(documentService.search(documentQuery));
            }
            // Check if the member has loan groups
            final LoanGroupQuery lgq = new LoanGroupQuery();
            lgq.setPageForCount();
            lgq.setMember(member);
            hasLoanGroups = PageHelper.hasResults(loanGroupService.search(lgq));

            // Check if the member has commission contracts
            hasCommissionContracts = commissionService.hasBrokerCommissionContracts();
        }
        // Check if the user has references
        final Collection<Nature> referenceNatures = referenceService.getNaturesByGroup(memberGroup);
        hasGeneralReferences = referenceNatures.contains(Nature.GENERAL);
        hasTransactionFeedbacks = referenceNatures.contains(Nature.TRANSACTION);

        // Check if the user can have guarantees
        try {
            final Collection<GuaranteeType.Model> guaranteeModels = guaranteeService
                    .getRelatedGuaranteeModels();
            session.setAttribute("loggedMemberHasGuarantees", guaranteeModels.size() > 0);
        } catch (final Exception e) {
            // Ignore
        }

        // Check if the user has cards
        hasCards = member.getCards().isEmpty() ? false : true;
    }

    if (isAdmin || isBroker) {
        // Retrieve the member record types the logged user can see on the menu
        final MemberRecordTypeQuery query = new MemberRecordTypeQuery();
        if (isAdmin) {
            query.setViewableByAdminGroup((AdminGroup) group);
        } else {
            query.setViewableByBrokerGroup((BrokerGroup) group);
        }
        query.setShowMenuItem(true);
        final List<MemberRecordType> types = memberRecordTypeService.search(query);
        session.setAttribute("memberRecordTypesInMenu", types);
    }

    // When a receipt printer cookie is set, and the printer no longer exists, or belongs to someone else, clear the cookie
    final String receiptPrinterId = RequestHelper.getCookieValue(request, "receiptPrinterId");
    if (StringUtils.isNotEmpty(receiptPrinterId)) {
        final Long id = IdConverter.instance().valueOf(receiptPrinterId);
        if (!receiptPrinterSettingsService.belongsToTheLoggedUser(id)) {
            final Cookie cookie = new Cookie("receiptPrinterId", "");
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }
    }

    final String actionPrefix = "/" + (isAdmin ? "admin" : isMember ? "member" : "operator");

    // Set the request attributes
    request.setAttribute("loggedUser", user);
    request.setAttribute("loggedElement", user.getElement());

    // Set the session attributes
    session.setAttribute("loggedUserId", user.getId());
    session.setAttribute("isAdmin", isAdmin);
    session.setAttribute("isMember", isMember);
    session.setAttribute("isBroker", isBroker);
    session.setAttribute("isOperator", isOperator);
    session.setAttribute("isBuyer", guaranteeService.isBuyer());
    session.setAttribute("isSeller", guaranteeService.isSeller());
    session.setAttribute("isIssuer", guaranteeService.isIssuer());
    session.setAttribute("loggedMemberHasAccounts", hasAccounts);
    session.setAttribute("loggedMemberHasSingleAccount", singleAccount);
    session.setAttribute("loggedMemberHasDocuments", hasDocuments);
    session.setAttribute("loggedMemberHasLoanGroups", hasLoanGroups);
    session.setAttribute("loggedMemberHasGeneralReferences", hasGeneralReferences);
    session.setAttribute("loggedMemberHasTransactionFeedbacks", hasTransactionFeedbacks);
    session.setAttribute("hasPin", hasPin);
    session.setAttribute("hasCards", hasCards);
    session.setAttribute("hasPos", hasPos);
    session.setAttribute("hasCommissionContracts", hasCommissionContracts);
    session.setAttribute("hasExternalChannels", hasExternalChannels);
    session.setAttribute("actionPrefix", actionPrefix);
    session.setAttribute("pathPrefix", "/do" + actionPrefix);
    session.setAttribute("navigation", Navigation.get(session));

    // Return the logged user
    return user;
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

public void sendImageDownloadResponse(ImageUtil image, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (image == null)
        return;/*www . j  a va 2  s.com*/

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(image.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(image.getLength());

    }

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(image.getBytes());
    os.close();
}