Example usage for javax.servlet.http Cookie getValue

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

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private Cookies convertCookies(javax.servlet.http.Cookie[] servletCookies) {
    List<Cookie> cookies = new ArrayList<Cookie>();
    for (javax.servlet.http.Cookie servletCookie : servletCookies) {
        Cookie.Builder cookieBuilder = new Cookie.Builder(servletCookie.getName(), servletCookie.getValue());
        if (servletCookie.getComment() != null) {
            cookieBuilder.setComment(servletCookie.getComment());
        }//from   w  ww  .ja v  a  2 s  .  c om
        if (servletCookie.getDomain() != null) {
            cookieBuilder.setDomain(servletCookie.getDomain());
        }
        if (servletCookie.getPath() != null) {
            cookieBuilder.setPath(servletCookie.getPath());
        }
        cookieBuilder.setMaxAge(servletCookie.getMaxAge());
        cookieBuilder.setVersion(servletCookie.getVersion());
        cookieBuilder.setSecured(servletCookie.getSecure());
        cookies.add(cookieBuilder.build());
    }
    return new Cookies(cookies);
}

From source file:de.escidoc.core.aa.servlet.Login.java

/**
 * This method provides the logout of the user.<br> The following steps are performed:<br> <ul> <li>First, the
 * existence of a valid cookie containing an escidoc user handle is checked. If this cookie is not found, no logout
 * action is performed.</li> <li>The logout method of the UserManagementWrapper is called providing the extracted
 * userHandle. </ul>/*from  w  w  w  . j  a va 2 s .  com*/
 *
 * @param request  The {@link HttpServletRequest}.
 * @param response The {@link HttpServletResponse}.
 * @throws IOException      Thrown in case of an IO error.
 * @throws ServletException Thrown in case of any other error.
 */
private void doLogout(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html");
    // Try to identify the user by the cookie containing the
    // handle that identifies him/her.
    final Cookie escidocHandleCookie = EscidocServlet.getCookie(EscidocServlet.COOKIE_LOGIN, request);
    try {
        if (escidocHandleCookie != null) {
            final String handle = escidocHandleCookie.getValue();
            try {
                if (StringUtils.isNotEmpty(handle)) {
                    dao.deleteUserLoginData(handle);
                }
            } catch (final SystemException e) {
                throw new ServletException(e);
            }
        }

        sendLoggedOut(request, response);
    } catch (final WebserverSystemException e) {
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

/**
 * Handles the authorization grant response
 * //from   w ww . j a va 2s  .  c  o  m
 * @param authorizationGrant
 *            The Authorization grant code
 * @param request
 *            The request from which to extract parameters and perform the
 *            authentication
 * @return The authenticated user token, or null if authentication is
 *         incomplete.
 * @throws Exception 
 * @throws UnsupportedEncodingException
 */
protected Authentication handleAuthorizationGrantResponse(String authorizationGrant, HttpServletRequest request,
        OIDCServerConfiguration serverConfig) {

    final boolean debug = logger.isDebugEnabled();

    // Handle Token Endpoint interaction
    HttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout));

    //
    // TODO: basic auth is untested (it wasn't working last I
    // tested)
    // UsernamePasswordCredentials credentials = new
    // UsernamePasswordCredentials(serverConfig.getClientId(),
    // serverConfig.getClientSecret());
    // ((DefaultHttpClient)
    // httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY,
    // credentials);
    //

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

    RestTemplate restTemplate = new RestTemplate(factory);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add("grant_type", "authorization_code");
    form.add("code", authorizationGrant);
    form.add("redirect_uri", AbstractOIDCAuthenticationFilter.buildRedirectURI(request, null));

    // pass clientId and clientSecret in post of request
    form.add("client_id", serverConfig.getClientId());
    form.add("client_secret", serverConfig.getClientSecret());

    if (debug) {
        logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointURI());
        logger.debug("form = " + form);
    }
    ;
    String jsonString = null;

    try {
        jsonString = restTemplate.postForObject(serverConfig.getTokenEndpointURI(), form, String.class);
    } catch (HttpClientErrorException httpClientErrorException) {

        // Handle error

        logger.error("Token Endpoint error response:  " + httpClientErrorException.getStatusText() + " : "
                + httpClientErrorException.getMessage());

        throw new AuthenticationServiceException("Unable to obtain Access Token.");
    }

    logger.debug("from TokenEndpoint jsonString = " + jsonString);

    JsonElement jsonRoot = new JsonParser().parse(jsonString);

    if (jsonRoot.getAsJsonObject().get("error") != null) {

        // Handle error

        String error = jsonRoot.getAsJsonObject().get("error").getAsString();

        logger.error("Token Endpoint returned: " + error);

        throw new AuthenticationServiceException(
                "Unable to obtain Access Token.  Token Endpoint returned: " + error);

    } else {

        // Extract the id_token to insert into the
        // OpenIdConnectAuthenticationToken

        IdToken idToken = null;
        JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig);

        if (jsonRoot.getAsJsonObject().get("id_token") != null) {

            try {
                idToken = IdToken.parse(jsonRoot.getAsJsonObject().get("id_token").getAsString());

            } catch (AuthenticationServiceException e) {

                // I suspect this could happen

                logger.error("Problem parsing id_token:  " + e);
                // e.printStackTrace();

                throw new AuthenticationServiceException(
                        "Problem parsing id_token return from Token endpoint: " + e);
            }

            if (jwtValidator
                    .validateSignature(jsonRoot.getAsJsonObject().get("id_token").getAsString()) == false) {
                throw new AuthenticationServiceException("Signature not validated");
            }
            if (idToken.getClaims().getIssuer() == null) {
                throw new AuthenticationServiceException("Issuer is null");
            }
            if (!idToken.getClaims().getIssuer().equals(serverConfig.getIssuer())) {
                throw new AuthenticationServiceException("Issuers do not match");
            }
            if (jwtValidator.isJwtExpired(idToken)) {
                throw new AuthenticationServiceException("Id Token is expired");
            }
            if (jwtValidator.validateIssuedAt(idToken) == false) {
                throw new AuthenticationServiceException("Id Token issuedAt failed");
            }

        } else {

            // An error is unlikely, but it good security to check

            logger.error("Token Endpoint did not return an id_token");

            throw new AuthenticationServiceException("Token Endpoint did not return an id_token");
        }

        // Clients are required to compare nonce claim in ID token to 
        // the nonce sent in the Authorization request.  The client 
        // stores this value as a signed session cookie to detect a 
        // replay by third parties.
        //
        // See: OpenID Connect Messages Section 2.1.1 entitled "ID Token"
        //
        // http://openid.net/specs/openid-connect-messages-1_0.html#id_token
        //

        //String nonce = idToken.getClaims().getClaimAsString("nonce");

        String nonce = idToken.getClaims().getNonce();

        if (StringUtils.isBlank(nonce)) {

            logger.error("ID token did not contain a nonce claim.");

            throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
        }

        Cookie nonceSignatureCookie = WebUtils.getCookie(request, NONCE_SIGNATURE_COOKIE_NAME);

        if (nonceSignatureCookie != null) {

            String sigText = nonceSignatureCookie.getValue();

            if (sigText != null && !sigText.isEmpty()) {

                if (!verify(signer, publicKey, nonce, sigText)) {
                    logger.error("Possible replay attack detected! "
                            + "The comparison of the nonce in the returned " + "ID Token to the signed session "
                            + NONCE_SIGNATURE_COOKIE_NAME + " failed.");

                    throw new AuthenticationServiceException("Possible replay attack detected! "
                            + "The comparison of the nonce in the returned " + "ID Token to the signed session "
                            + NONCE_SIGNATURE_COOKIE_NAME + " failed.");
                }
            } else {
                logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty");
                throw new AuthenticationServiceException(
                        NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty");
            }

        } else {

            logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found.");

            throw new AuthenticationServiceException(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found.");
        }

        // pull the user_id out as a claim on the id_token

        String userId = idToken.getTokenClaims().getUserId();

        // construct an OpenIdConnectAuthenticationToken and return 
        // a Authentication object w/the userId and the idToken

        OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idToken);

        Authentication authentication = this.getAuthenticationManager().authenticate(token);

        return authentication;

    }
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

private HashMap<String, String> validateCookie(Cookie lcook, String name) {
    HashMap<String, String> attrs = null;
    String data = null;/*w  ww.ja  va2 s  . co  m*/
    String timeOut = "";
    if (name.equals("lcook"))
        timeOut = (String) this.config.getProperty("net.geant.edugain.filter.lcookTimeout");
    else
        timeOut = (String) this.config.getProperty("net.geant.edugain.filter.timeout");

    data = cipher.decode(name, lcook.getValue());
    String[] splittedValues = data.split(":");
    int length = splittedValues.length;
    String timeStampStr = (String) splittedValues[0];
    String location = (String) splittedValues[1];
    String serviceID = (String) splittedValues[2];

    long currentTime = System.currentTimeMillis();
    long timeStamp = Long.parseLong(timeStampStr) * 1000;
    boolean onTime = currentTime < (timeStamp + Long.parseLong(timeOut));
    String userData = "";

    if (onTime && serviceID.equals(this.serviceID)) {

        attrs = new HashMap<String, String>();
        for (int i = 3; i < length; i++) {
            userData = userData + (String) splittedValues[i] + ":";
        }
        userData = userData.substring(0, userData.length() - 1);

        String[] splittedAttrs = userData.split(",");
        length = splittedAttrs.length;
        for (int i = 0; i < length; i++) {
            String attValue = (String) splittedAttrs[i];
            int separatorIndex = attValue.indexOf("=");
            String key = attValue.substring(0, separatorIndex);
            String value = attValue.substring(separatorIndex + 1, attValue.length());
            attrs.put(key, value);
        }
    }

    return attrs;
}

From source file:com.jfinal.core.Controller.java

/**
 * Get cookie value by cookie name./*from   ww  w . j  a  va  2s .  co  m*/
 */
public String getCookie(String name, String defaultValue) {
    Cookie cookie = getCookieObject(name);
    return cookie != null ? cookie.getValue() : defaultValue;
}

From source file:fi.hoski.web.forms.RaceEntryServlet.java

/**
 * Handles the HTTP/*from   w ww.  jav a  2 s  . c o  m*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String raceFleetKeyStr = request.getParameter("RaceFleetKey");
        if (raceFleetKeyStr == null) {
            throw new ServletException("no RaceFleetKey");
        }
        Key raceFleetKey = KeyFactory.stringToKey(raceFleetKeyStr);
        Entity raceFleetEntity = datastore.get(raceFleetKey);
        Key raceSeriesKey = raceFleetKey.getParent();
        Entity raceseriesEntity = datastore.get(raceSeriesKey);
        RaceSeries raceSeries = (RaceSeries) entities.newInstance(raceseriesEntity);
        RaceFleet raceFleet = (RaceFleet) entities.newInstance(raceFleetEntity);
        RaceEntry raceEntry = new RaceEntry(raceFleet);
        raceEntry.populate(request.getParameterMap());

        String fn = request.getParameter(RaceEntry.FIRSTNAME);
        String ln = request.getParameter(RaceEntry.LASTNAME);
        raceEntry.set(RaceEntry.HELMNAME, fn + " " + ln);

        String sa = request.getParameter(RaceEntry.STREETADDRESS);
        String zc = request.getParameter(RaceEntry.ZIPCODE);
        String ct = request.getParameter(RaceEntry.CITY);
        String cn = request.getParameter(RaceEntry.COUNTRY);
        if (cn == null || cn.isEmpty()) {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct);
        } else {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct + ", " + cn);
        }

        Day closingDay = (Day) raceSeries.get(RaceSeries.ClosingDate);
        Number fee = 0.0;
        if (closingDay != null) {
            Day now = new Day();
            if (closingDay.before(now)) {
                fee = (Number) raceFleet.get(RaceFleet.Fee2);
            } else {
                fee = (Number) raceFleet.get(RaceFleet.Fee);
            }
        }
        Boolean clubDiscount = (Boolean) raceSeries.get(RaceSeries.CLUBDISCOUNT);
        String clubname = repositoryBundle.getString("Clubname");
        if (clubDiscount != null && clubDiscount
                && clubname.equalsIgnoreCase("" + raceEntry.get(RaceEntry.CLUB))) {
            fee = new Double(0);
        }
        raceEntry.set(RaceEntry.FEE, fee);
        raceEntry.set(RaceEntry.TIMESTAMP, new Date());

        entities.put(raceEntry);

        String payingInstructions = "";
        String payingInstructionsHtml = "";
        BankingBarcode bb = races.getBarcode(raceEntry);
        if (bb != null) {
            Day dueDay = new Day(bb.getDueDate());
            String payingFormat = EntityReferences.encode(msg(Messages.RACEENTRYPAYING), "UTF-8");
            String bic = EntityReferences.encode(msg(Messages.RACEBIC), "UTF-8");
            payingInstructions = String.format(payingFormat, bb.toString(), // 1 = barcode
                    bb.getAccount().getIBAN(), // 2 = account
                    bb.getReference().toFormattedRFString(), // 3 = ref
                    dueDay, // 4 = due date
                    String.format("%.2f", bb.getTotal()), // 5 = total
                    bic // 6 = bic
            );
            payingInstructionsHtml = String.format(payingFormat.replace("\n", "<br>"),
                    "<span id='barcode'>" + bb.toString() + "</span>", // 1 = barcode
                    "<span id='iban'>" + bb.getAccount().getIBAN() + "</span>", // 2 = account
                    "<span id='rf'>" + bb.getReference().toFormattedRFString() + "</span>", // 3 = ref
                    "<span id='due'>" + dueDay + "</span>", // 4 = due date
                    "<span id='fee'>" + String.format("%.2f", bb.getTotal()) + "</span>", // 5 = total
                    "<span id='bic'>" + bic + "</span>" // 6 = bic
            );
        }
        URL base = new URL(request.getRequestURL().toString());
        URL barcodeUrl = new URL(base, "/races/code128.html?ancestor=" + raceEntry.createKeyString());
        String name = (String) raceEntry.get(RaceEntry.HELMNAME);
        String email = (String) raceEntry.get(RaceEntry.HELMEMAIL);
        String confirmation = msg(Messages.RACEENTRYCONFIRMATION);
        String plainMessage = "";
        String htmlMessage = "<html><head></head><body>" + EntityReferences.encode(confirmation)
                + payingInstructionsHtml + raceEntry.getFieldsAsHtmlTable() + "<iframe src="
                + barcodeUrl.toString() + "/>" + "</body></html>";
        if (email != null) {
            InternetAddress recipient = new InternetAddress(email, name);
            String senderStr = msg(Messages.RACEENTRYFROMADDRESS);
            InternetAddress sender;
            try {
                sender = new InternetAddress(senderStr);
                plainMessage = confirmation + "\n" + payingInstructions + "\n" + raceEntry.getFields();

                String subject = msg(Messages.RACEENTRYSUBJECT);
                mailService.sendMail(sender, subject, plainMessage, htmlMessage, recipient);
            } catch (Exception ex) {
                log(senderStr, ex);
            }
        }
        Cookie cookie = null;
        Cookie[] cookies = null;
        if (useCookies) {
            cookies = request.getCookies();
        }
        if (cookies != null) {
            for (Cookie ck : cookies) {
                if (COOKIENAME.equals(ck.getName())) {
                    cookie = ck;
                }
            }
        }
        JSONObject json = null;
        if (useCookies && cookie != null) {
            Base64 decoder = new Base64();
            String str = new String(decoder.decode(cookie.getValue()));
            json = new JSONObject(str);
        } else {
            json = new JSONObject();
        }
        for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) request.getParameterMap())
                .entrySet()) {
            String property = entry.getKey();
            String[] values = entry.getValue();
            if (values.length == 1) {
                json.put(property, values[0]);
            }
        }
        Base64 encoder = new Base64();
        String base64 = encoder.encodeAsString(json.toString().getBytes("UTF-8"));
        if (useCookies) {
            if (cookie == null) {
                cookie = new Cookie(COOKIENAME, base64);
                cookie.setPath("/");
                cookie.setMaxAge(400 * 24 * 60 * 60);
            } else {
                cookie.setValue(base64);
            }
            response.addCookie(cookie);
        }
        sendError(response, HttpServletResponse.SC_OK,
                "<div id=\"" + raceEntry.createKeyString() + "\">Ok</div>");
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eJSON\">Internal error.</div>");
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eEntityNotFound\">Internal error.</div>");
    } catch (NumberFormatException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eNumberFormat\">Number error.</div>");
    }
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

protected boolean prepareForwardingCookies(HttpRequestBase method, HttpServletRequest request,
        DefaultHttpClient httpClient) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    Cookie[] cookies = request.getCookies();
    BasicCookieStore cs = new BasicCookieStore();
    httpClient.setCookieStore(cs);//from   ww  w . j a  v  a  2s. c  om
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie != null) {
                String cookiename = cookie.getName();
                if (StringUtil.isNotEmpty(cookiename)) {
                    String cookieval = cookie.getValue();
                    if (cookiename.startsWith(PASSTHRUID)) {
                        cookiename = cookiename.substring(PASSTHRUID.length());
                        if (isCookieAllowed(cookiename)) {
                            String[] parts = decodeCookieNameAndPath(cookiename);
                            if (parts != null && parts.length == 3) {
                                cookiename = parts[0];
                                String path = parts[1];
                                String domain = parts[2];

                                // Got stored domain now see if it matches destination
                                BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                                methodcookie.setDomain(domain);
                                methodcookie.setPath(path);
                                cs.addCookie(methodcookie);
                                if (getDebugHook() != null) {
                                    getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                            methodcookie.toString());
                                }
                            }
                        }
                    } else if (isCookieAllowed(cookiename)) {
                        BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                        String domain = cookie.getDomain();
                        if (domain == null) {
                            try {
                                domain = method.getURI().getHost();
                                domain = domain.substring(domain.indexOf('.'));
                            } catch (Exception e) {
                                domain = "";
                            }
                        }
                        methodcookie.setDomain(domain);
                        String path = cookie.getPath();
                        if (path == null) {
                            path = "/";
                        }
                        methodcookie.setPath(path);
                        cs.addCookie(methodcookie);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                    methodcookie.toString());
                        }
                    }
                }
            }
        }
    }
    ProxyProfiler.profileTimedRequest(timedObject, "perpareForwardingCookie");
    return true;
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.DumpHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    if (!isStarted())
        return;//  w w  w .j a  v a 2s .c o  m

    // Only handle GET, HEAD and POST
    if (!HttpRequest.__GET.equals(request.getMethod()) && !HttpRequest.__HEAD.equals(request.getMethod())
            && !HttpRequest.__POST.equals(request.getMethod()))
        return;

    log.debug("Dump");

    response.setField(HttpFields.__ContentType, HttpFields.__TextHtml);
    OutputStream out = response.getOutputStream();
    ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
    Writer writer = new OutputStreamWriter(buf, StringUtil.__ISO_8859_1);
    writer.write("<HTML><H1>Dump HttpHandler</H1>");
    writer.write("<PRE>\npath=" + request.getPath() + "\ncontextPath=" + getHttpContext().getContextPath()
            + "\npathInContext=" + pathInContext + "\n</PRE>\n");
    writer.write("<H3>Header:</H3><PRE>");
    writer.write(request.toString());
    writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>");
    Set names = request.getParameterNames();
    Iterator iter = names.iterator();
    while (iter.hasNext()) {
        String name = iter.next().toString();
        List values = request.getParameterValues(name);
        if (values == null || values.size() == 0) {
            writer.write(name);
            writer.write("=\n");
        } else if (values.size() == 1) {
            writer.write(name);
            writer.write("=");
            writer.write((String) values.get(0));
            writer.write("\n");
        } else {
            for (int i = 0; i < values.size(); i++) {
                writer.write(name);
                writer.write("[" + i + "]=");
                writer.write((String) values.get(i));
                writer.write("\n");
            }
        }
    }

    String cookie_name = request.getParameter("CookieName");
    if (cookie_name != null && cookie_name.trim().length() > 0) {
        String cookie_action = request.getParameter("Button");
        try {
            Cookie cookie = new Cookie(cookie_name.trim(), request.getParameter("CookieVal"));
            if ("Clear Cookie".equals(cookie_action))
                cookie.setMaxAge(0);
            response.addSetCookie(cookie);
        } catch (IllegalArgumentException e) {
            writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>");
            writer.write(e.toString());
            LogSupport.ignore(log, e);
        }
    }

    writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>");
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int c = 0; c < cookies.length; c++) {
            Cookie cookie = cookies[c];
            writer.write(cookie.getName());
            writer.write("=");
            writer.write(cookie.getValue());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>");
    Enumeration attributes = request.getAttributeNames();
    if (attributes != null && attributes.hasMoreElements()) {
        while (attributes.hasMoreElements()) {
            String attr = attributes.nextElement().toString();
            writer.write(attr);
            writer.write("=");
            writer.write(request.getAttribute(attr).toString());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>");
    byte[] content = new byte[4096];
    int len;
    try {
        InputStream in = request.getInputStream();
        while ((len = in.read(content)) >= 0)
            writer.write(new String(content, 0, len));
    } catch (IOException e) {
        LogSupport.ignore(log, e);
        writer.write(e.toString());
    }

    // You wouldn't normally set a trailer like this, but
    // we don't want to commit the output to force trailers as
    // it makes test harness messy
    request.getAcceptableTransferCodings();

    // commit now
    writer.flush();
    response.setIntField(HttpFields.__ContentLength, buf.size() + 1000);
    buf.writeTo(out);
    out.flush();

    // Now add the response
    buf.reset();
    writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>");
    writer.write(response.toString());
    writer.write("</PRE></HTML>");
    writer.flush();
    for (int pad = 998 - buf.size(); pad-- > 0;)
        writer.write(" ");
    writer.write("\015\012");
    writer.flush();
    buf.writeTo(out);

    request.setHandled(true);
}

From source file:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java

/**
 * @param request//from   ww w  .j  a v a2s. c  o  m
 * @param response
 * @param callbackUrl
 * @throws IOException
 * @throws Oops
 */
private void authorizeRequestToken(HttpServletRequest request, HttpServletResponse response, String username)
        throws Oops {

    String token = null, callbackUrl = null;

    Cookie[] cookies = request.getCookies();

    String shareId = null;

    if (null != request.getParameter("oauth_token")) {
        token = request.getParameter("oauth_token");
        callbackUrl = request.getParameter("oauth_callback");
    } else if (cookies != null) {
        OauthCookie parsedCookie = null;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(OauthCookie.COOKIE_NAME)) {
                // Remove the temporary 3rd party app cookie
                Cookie removeCookie = new Cookie(OauthCookie.COOKIE_NAME, "");
                removeCookie.setMaxAge(0);
                response.addCookie(removeCookie);
                try {
                    parsedCookie = OauthCookie.create(cookie);
                    shareId = parsedCookie.getShareId();
                    if (isBlank(parsedCookie.getRequestToken()))
                        throw new Oops(
                                "No request token present in oauth cookie (\"" + cookie.getValue() + "\").");
                    logger.debug("Parsed oauth cookie \"" + cookie.getValue() + "\" as \""
                            + parsedCookie.toString() + "\".");
                } catch (IOException e) {
                    logger.debug("Error parsing cookie. Just removing it.");
                }
            }
        }

        if (null != parsedCookie) {
            token = parsedCookie.getRequestToken();
            callbackUrl = parsedCookie.getCallbackUrl();
        }
    }

    if (null == token)
        throw new Oops("No request token found in request.");

    try {
        Token reqToken = MySQLOAuthProvider2.getRequestToken(token);
        if (null == reqToken)
            throw new PermissionDeniedException("401 Unauthorized");
        if (null != reqToken.getAttributes().getFirst("root_container")) { // pre-shared container accessor
            if (shareId != null) {//already created the share - user bound sharing
                List<String> groupUserLogins = MySQLOAuthProvider2.getShareUsers(shareId);
                if (!groupUserLogins.contains(username)) { // the username of the one authorized != user that share was created for
                    throw new PermissionDeniedException("401 Unauthorized");
                }
            } // else share is open for everyone
        }

        MySQLOAuthProvider2.markAsAuthorized(reqToken, username);

        if (null != callbackUrl && !callbackUrl.isEmpty()) {
            if (callbackUrl.indexOf('?') <= 0)
                callbackUrl += "?" + "oauth_token=" + reqToken.getToken();
            else
                callbackUrl += "&" + "oauth_token=" + reqToken.getToken();
            logger.debug("Redirecting user to " + callbackUrl);
            response.sendRedirect(callbackUrl);
        } else {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.println("You have successfully authorized "
                    + ".\nPlease close this browser window and click continue" + " in the client.");
            out.close();
        }
    } catch (IOException e) {
        logger.error("Error performing the token authorization " + e.getMessage());
        e.printStackTrace();
        throw new Oops(e.getMessage());
    }
}

From source file:com.sjc.cc.login.action.LoginAction.java

/**
 * CookieID//from  w  w w  . jav  a 2  s. c om
 * 
 * @param userId
 */
private void setCloudUserIdCookie(Long userId) {
    HttpServletResponse response = ServletActionContext.getResponse();
    Cookie loginInfo = new Cookie(COOKIE_CC_USER_ID, userId + "");
    loginInfo.setMaxAge(-1);
    if (logger.isDebugEnabled()) {
        logger.debug("The Cookie Cloud is :" + loginInfo + "," + loginInfo.getValue());
    }
    response.addCookie(loginInfo);
}