Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addCookie.

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

@RequestMapping(value = { "/{userParam}/loggedout", "{userParam}/j_spring_security_logout" })
public String loggedout(@PathVariable String userParam, ModelMap map, HttpSession session,
        HttpServletResponse response, HttpServletRequest request) {
    logger.debug("###Entering in loggedout(response) method");
    String showSuffixControl = "false";
    String suffixControlType = "textbox";
    List<String> suffixList = null;
    if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
        showSuffixControl = "true";
        if (config.getValue(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled).equals("true")) {
            suffixControlType = "dropdown";
            suffixList = tenantService.getSuffixList();
        }//from w  ww  .j a v  a2 s.c  o  m
    }
    map.addAttribute("showSuffixControl", showSuffixControl);
    map.addAttribute("suffixControlType", suffixControlType);
    map.addAttribute("suffixList", suffixList);
    if (config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)
            && config.getValue(Names.com_citrix_cpbm_directory_mode).equals("pull")) {
        map.addAttribute("directoryServiceAuthenticationEnabled", "true");
    }
    if (config.getValue(Names.com_citrix_cpbm_public_catalog_display).equals("true")
            && channelService.getDefaultServiceProviderChannel() != null) {
        map.addAttribute("showAnonymousCatalogBrowsing", "true");
    }
    map.addAttribute("showLanguageSelection", "true");
    map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
    map.addAttribute("logout", true);
    String redirect = null;
    Enumeration<String> en = session.getAttributeNames();
    while (en.hasMoreElements()) {
        String attr = en.nextElement();
        session.removeAttribute(attr);
    }
    Cookie cookie = new Cookie("JforumSSO", "");
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
    if (request.getRequestedSessionId() != null && request.isRequestedSessionIdValid()) {
        // create logout notification begins
        User user = userService.get(userParam);
        String message = "logged.out";
        String messageArgs = user.getUsername();
        eventService.createEvent(new Date(), user, message, messageArgs, Source.PORTAL, Scope.USER,
                Category.ACCOUNT, Severity.INFORMATION, true);
    }
    session.invalidate();
    if (config.getAuthenticationService().compareToIgnoreCase(CAS) == 0) {
        try {
            redirect = StringUtils.isEmpty(config.getCasLogoutUrl()) ? null
                    : config.getCasLogoutUrl() + "?service="
                            + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("Exception encoding: " + redirect, e);
        }
        if (redirect == null) {
            throw new InternalError("CAS authentication required, but login url not set");
        }
    }

    SecurityContextHolder.getContext().setAuthentication(null);
    // ends
    logger.debug("###Exiting loggedout(response) method");
    return redirect == null ? "redirect:/j_spring_security_logout" : "redirect:" + redirect;
}

From source file:org.bpmscript.web.BpmScriptCookieController.java

@SuppressWarnings("unchecked")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    response.setContentType(contentType);

    String requestUri = request.getRequestURI();
    String definitionName = null;
    String methodName = null;// w  ww .j av a 2 s .c  om
    String split[] = request.getRequestURI().split("/");
    if (requestUri.endsWith("/")) {
        definitionName = split[split.length - 1];
        methodName = defaultIndexName;
    } else {
        definitionName = split[split.length - 2];
        methodName = split[split.length - 1].split("\\.")[0];
    }

    String correlationIdParam = null;

    String cookieName = cookiePrefix + StringUtils.capitalize(definitionName)
            + StringUtils.capitalize(methodName);

    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        String name = cookie.getName();
        if (cookieName.equals(name)) {
            correlationIdParam = cookie.getValue();
        }
    }

    String timeoutParam = request.getParameter("timeout");
    long timeout = defaultTimeout;
    if (timeoutParam != null) {
        try {
            timeout = Integer.parseInt(timeoutParam);
        } catch (NumberFormatException e) {
            log.debug(e);
        }
    }
    try {
        SerializableHttpServletRequest serializableHttpServletRequest = new SerializableHttpServletRequest(
                request);
        if (correlationIdParam == null) {
            Object result = null;
            String conversationId = null;
            Object message = bpmScriptFacade.call(definitionName, methodName, timeout,
                    serializableHttpServletRequest);
            if (message instanceof IInvocationMessage) {
                IInvocationMessage conversationMessage = (IInvocationMessage) message;
                result = conversationMessage.getArgs()[0];
                conversationId = conversationMessage.getCorrelationId();
            } else {
                result = message;
            }
            if (result instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) result;
                if (conversationId != null) {
                    map.put("conversationId", conversationId);
                    response.addCookie(new Cookie(cookieName, conversationId));
                }
                ModelAndView modelAndView = new ModelAndView((String) map.get("view"), map);
                return modelAndView;
            } else {
                throw new Exception("result must be a map or a conversation");
            }
        } else {

            IInvocationMessage conversationMessage = null;

            conversationMessage = (IInvocationMessage) conversationCorrelator.call(correlationIdParam, timeout,
                    serializableHttpServletRequest);

            if (conversationMessage != null) {
                Map<String, Object> result = (Map<String, Object>) conversationMessage.getArgs()[0];
                String conversationId = conversationMessage.getCorrelationId();
                result.put("conversationId", conversationId);
                String replyTo = conversationMessage.getReplyTo();
                Cookie cookie = new Cookie(cookieName, conversationId);
                if (replyTo == null) {
                    cookie.setMaxAge(0);
                }
                response.addCookie(cookie);
                ModelAndView modelAndView = new ModelAndView((String) result.get("view"), result);
                return modelAndView;
            } else {
                Cookie cookie = new Cookie(cookieName, "");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                throw new Exception("Did not get a response for message " + correlationIdParam);
            }
        }
    } catch (Throwable e) {
        if (e instanceof Exception) {
            throw (Exception) e;
        } else {
            throw new Exception(e);
        }
    }
}

From source file:com.enonic.vertical.userservices.UserHandlerController.java

private void processLogout(SiteContext siteContext, HttpServletRequest request, HttpServletResponse response,
        HttpSession session, ExtendedMap formItems, UserServicesService userServices)
        throws VerticalUserServicesException, RemoteException {

    UserStoreKey userStoreKey = parseUserStoreKeyFromUidAndUserstore(formItems);

    if (session != null) {
        // Create log entry:
        User user = securityService.getOldUserObject();
        if (user != null && !user.isAnonymous()) {
            if (siteContext.isAuthenticationLoggingEnabled()) {
                createLogEntry(siteContext, user, userServices, request.getRemoteAddr(),
                        LogType.LOGOUT.asInteger(), userStoreKey);
            }/*from w  ww .j  av  a  2 s.c o  m*/
        } else {
            String message = "User is not logged in.";
            VerticalUserServicesLogger.warn(this.getClass(), 0, message, null);
            redirectToErrorPage(request, response, formItems, ERR_USER_NOT_LOGGED_IN, null);
            return;
        }

        // Remove GUID cookie if present
        String cookieName = "guid-" + siteContext.getSiteKey();
        Cookie cookie = CookieUtil.getCookie(request, cookieName);
        if (cookie != null) {
            cookie.setValue(null);
            response.addCookie(cookie);
        }

        removeGuidCookie(response, DeploymentPathResolver.getSiteDeploymentPath(request), siteContext);
        securityService.logoutPortalUser();

        redirectToPage(request, response, formItems);
    }
}

From source file:demo.oauth.client.controllers.TemporaryCredentialsController.java

@RequestMapping("/handleTemporaryCredentials")
public ModelAndView handleRequest(@ModelAttribute(value = "oAuthParams") OAuthParams oAuthParams,
        HttpServletResponse response) {

    OAuthServiceProvider provider;//from w w w .j a  va  2  s .  c  o m
    OAuthConsumer consumer;
    OAuthAccessor accessor;

    OAuthClient client = new OAuthClient(new URLConnectionClient());

    oAuthParams.setErrorMessage(null);
    String temporaryCredentialsEndpointUrl = oAuthParams.getTemporaryCredentialsEndpoint();
    if (temporaryCredentialsEndpointUrl == null || "".equals(temporaryCredentialsEndpointUrl)) {
        oAuthParams.setErrorMessage("Missing temporary credentials endpoint url");
    }
    String clientId = oAuthParams.getClientID();
    if (clientId == null || "".equals(clientId)) {
        oAuthParams.setErrorMessage("Missing client identifier");
    }
    String secret = oAuthParams.getClientSecret();
    if (secret == null || "".equals(secret)) {
        oAuthParams.setErrorMessage("Missing client shared-secret");
    }

    if (oAuthParams.getErrorMessage() == null) {
        provider = new OAuthServiceProvider(temporaryCredentialsEndpointUrl,
                oAuthParams.getResourceOwnerAuthorizationEndpoint(), oAuthParams.getTokenRequestEndpoint());
        consumer = new OAuthConsumer(null, clientId, secret, provider);
        accessor = new OAuthAccessor(consumer);

        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, oAuthParams.getSignatureMethod());
        parameters.put(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
        parameters.put(OAuth.OAUTH_TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));
        parameters.put(OAuth.OAUTH_CALLBACK, oAuthParams.getCallbackURL());
        parameters.put("realm", "private");
        parameters.put("scope", "read_info modify_info");

        try {
            accessor.consumer.setProperty(OAuthClient.PARAMETER_STYLE, ParameterStyle.AUTHORIZATION_HEADER);
            client.getRequestToken(accessor, OAuthMessage.POST, parameters.entrySet());
        } catch (Exception e) {
            oAuthParams.setErrorMessage(e.toString());
        }

        oAuthParams.setOauthToken(accessor.requestToken);
        oAuthParams.setOauthTokenSecret(accessor.tokenSecret);
        Cookie cId = new Cookie("clientID", oAuthParams.getClientID());
        Cookie cSec = new Cookie("clientSecret", oAuthParams.getClientSecret());
        Cookie tokenSec = new Cookie("tokenSec", accessor.tokenSecret);
        response.addCookie(cId);
        response.addCookie(cSec);
        response.addCookie(tokenSec);
    }

    ModelAndView modelAndView = new ModelAndView();
    if (oAuthParams.getErrorMessage() != null) {
        modelAndView.setViewName("temporaryCredentials");
    } else {
        modelAndView.setViewName("authorizeResourceOwner");
    }

    return modelAndView;
}

From source file:com.haulmont.idp.controllers.IdpController.java

@GetMapping(value = "/")
public String checkIdpSession(@RequestParam(value = "sp", defaultValue = "") String serviceProviderUrl,
        @RequestParam(value = "response_type", defaultValue = "server-ticket") String responseType,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {
    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;//from   www  .j a  v  a  2s.c  om
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        String serviceProviderTicket = idpService.createServiceProviderTicket(idpSessionCookie);
        if (serviceProviderTicket != null) {
            String serviceProviderRedirectUrl;
            try {
                URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

                if (ResponseType.CLIENT_TICKET.getCode().equals(responseType)) {
                    uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + serviceProviderTicket);
                } else {
                    uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, serviceProviderTicket);
                }

                serviceProviderRedirectUrl = uriBuilder.build().toString();
            } catch (URISyntaxException e) {
                log.warn("Unable to compose redirect URL", e);

                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return null;
            }

            try {
                response.sendRedirect(serviceProviderRedirectUrl);
            } catch (IOException e) {
                // do not log stacktrace here
                log.warn("Unable to send redirect to service provider URL", e.getMessage());
            }

            log.debug("New ticket {} created for already logged in user", serviceProviderTicket);

            return null;
        } else {
            log.debug("IDP session {} not found, login required", idpSessionCookie);
        }
    }

    // remove auth cookie
    Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);

    if (ResponseType.CLIENT_TICKET.getCode().equals(responseType)) {
        return "redirect:login.html" + "?response_type=" + ResponseType.CLIENT_TICKET.getCode() + "&sp="
                + URLEncodeUtils.encodeUtf8(serviceProviderUrl);
    }

    return "redirect:login.html?sp=" + URLEncodeUtils.encodeUtf8(serviceProviderUrl);
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException      Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 *//*from   w  w w.  j  a  va 2s.c o  m*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void finalizeAuthBean(Object bean, HttpServletRequest request, HttpServletResponse response) {
    executePreDestroy(bean);//from ww w .ja va  2  s  .  c om
    AuthBean authBean = bean.getClass().getAnnotation(AuthBean.class);
    try {
        for (Field field : HELPER.getBeanFields(bean.getClass())) {
            if (field.getAnnotations().length > 0) {
                field.setAccessible(true);

                if (field.isAnnotationPresent(AuthField.class)) {
                    AuthField authField = field.getAnnotation(AuthField.class);

                    Object value = field.get(bean);
                    if (value != null) {
                        // Return encrypted auth fields as cookies to check if customer is still
                        // logged on next request
                        String cookieValue = AuthEncrypter.encrypt(request, authBean.secretKey(), value);

                        Cookie cookie = getAuthenticationCookie(request, authField.value(), cookieValue, -1);
                        response.addCookie(cookie);
                    } else {
                        // Case value is null we force Cookie deletion on client side
                        Cookie cookie = getAuthenticationCookie(request, authField.value(), null, 0);
                        response.addCookie(cookie);
                    }
                }
                field.set(bean, null);
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Finalize injection on AuthBean [" + bean + "] failed: " + ex.getMessage());
    }
    request.removeAttribute(HELPER.getClassName(authBean, bean.getClass()));
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @param httpServletRequest Request object pertaining to the proxied HTTP request
 * @throws IOException      Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *//* w w  w.jav a  2s.  co  m*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    getCredential(httpServletRequest.getParameter("servername"));
    if (credentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    httpMethodProxyRequest.setFollowRedirects(true);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    String response = httpMethodProxyRequest.getResponseBodyAsString();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(stringLocation
                    .replace(getProxyHostAndPort(httpServletRequest) + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, response);
        } else {
            response = new String(ungzip(httpMethodProxyRequest.getResponseBody()));
        }
        httpServletResponse.setContentLength(response.length());
    }

    // Send the content to the client
    if (intProxyResponseCode == 200)
        httpServletResponse.getWriter().write(response);
    else
        httpServletResponse.getWriter().write(intProxyResponseCode);
}

From source file:it.cnr.isti.hpc.dexter.annotate.controller.SuccessController.java

@RequestMapping(value = "/authSuccess")
public ModelAndView getRedirectURL(final HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
    AuthProvider provider = manager.getCurrentAuthProvider();

    HttpSession session = request.getSession();

    System.out.println("session-id = " + session.getId());
    if (provider == null) {
        logger.error("cannot find provider");
        RedirectView view = new RedirectView("index.html");
        ModelAndView mv = new ModelAndView(view);
        return mv;

    }//w w w . j  a  v  a2s  .  co  m
    Profile profile = provider.getUserProfile();
    System.out.println("profile: \n" + profile);
    User user = new User();
    String mail = profile.getEmail();
    if (mail == null) {
        mail = profile.getValidatedId() + "@" + profile.getProviderId() + ".app";
    }
    user.setEmail(mail);
    String first = profile.getFirstName();
    String last = profile.getLastName();
    String display = profile.getDisplayName();

    user.setFirstName((first == null) ? "" : first);

    user.setLastName((last == null || last.isEmpty()) ? mail : last);

    user.setDisplayName(display);
    if (display == null) {
        user.setDisplayName(mail);

    }
    String pwd = pswGenerator.nextSessionId();
    user.setPassword(pwd);

    User u = dao.getUserByMail(user.getEmail());
    System.out.println("------------success---------------");
    if (u != null)
        System.out.println(u.toString());
    System.out.println("----------------------------------");
    if (u != null) {
        logger.info("user ", user.getEmail() + " logged in");
        user = u;
    } else {
        logger.info("add user {}", user.getEmail());
        dao.addUser(user);
    }
    // String type = null;
    // if (session.getAttribute(Constants.REQUEST_TYPE) != null) {
    // type = (String) session.getAttribute(Constants.REQUEST_TYPE);
    // }
    // if (type != null) {
    // if (Constants.REGISTRATION.equals(type)) {
    // return registration(provider);
    // } else if (Constants.IMPORT_CONTACTS.equals(type)) {
    // return importContacts(provider);
    // } else if (Constants.SHARE.equals(type)) {
    // return new ModelAndView("shareForm", "connectedProvidersIds",
    // manager.getConnectedProvidersIds());
    // }
    // }

    RedirectView view = new RedirectView("index.html");
    ModelAndView mv = new ModelAndView(view);

    Cookie cookie = new Cookie("mail", user.getEmail());
    response.addCookie(cookie);
    cookie = new Cookie("psw", user.getPassword());
    response.addCookie(cookie);
    cookie = new Cookie("uid", String.valueOf(user.getId()));
    response.addCookie(cookie);

    // mv.addObject("uid", user.getId());
    // mv.addObject("pwd", user.getPassword());
    return mv;

}