Example usage for org.apache.http.cookie Cookie getValue

List of usage examples for org.apache.http.cookie Cookie getValue

Introduction

In this page you can find the example usage for org.apache.http.cookie Cookie getValue.

Prototype

String getValue();

Source Link

Document

Returns the value.

Usage

From source file:org.jboss.as.test.integration.web.cookie.CookieUnitTestCase.java

@Test
public void testCookieRetrievedCorrectly() throws Exception {
    log.info("testCookieRetrievedCorrectly()");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieServlet"));

    // assert that we are able to hit servlet successfully
    int postStatusCode = response.getStatusLine().getStatusCode();
    Header[] postErrorHeaders = response.getHeaders("X-Exception");
    assertTrue("Wrong response code: " + postStatusCode, postStatusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-Exception(" + Arrays.toString(postErrorHeaders) + ") is null", postErrorHeaders.length == 0);

    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    assertTrue("Sever did not set expired cookie on client", checkNoExpiredCookie(cookies));

    for (Cookie cookie : cookies) {
        log.info("Cookie : " + cookie);
        String cookieName = cookie.getName();
        String cookieValue = cookie.getValue();

        if (cookieName.equals("simpleCookie")) {
            assertTrue("cookie value should be jboss", cookieValue.equals("jboss"));
            assertEquals("cookie path", "/jbosstest-cookie", cookie.getPath());
            assertEquals("cookie persistence", false, cookie.isPersistent());
        } else if (cookieName.equals("withSpace")) {
            assertEquals("should be no quote in cookie with space", cookieValue.indexOf("\""), -1);
        } else if (cookieName.equals("comment")) {
            log.info("comment in cookie: " + cookie.getComment());
            // RFC2109:Note that there is no Comment attribute in the Cookie request header
            // corresponding to the one in the Set-Cookie response header. The user
            // agent does not return the comment information to the origin server.

            assertTrue(cookie.getComment() == null);
        } else if (cookieName.equals("withComma")) {
            assertTrue("should contain a comma", cookieValue.indexOf(",") != -1);
        } else if (cookieName.equals("expireIn10Sec")) {
            Date now = new Date();
            log.info("will sleep for 5 seconds to see if cookie expires");
            assertTrue("cookies should not be expired by now",
                    !cookie.isExpired(new Date(now.getTime() + fiveSeconds)));
            log.info("will sleep for 5 more secs and it should expire");
            assertTrue("cookies should be expired by now",
                    cookie.isExpired(new Date(now.getTime() + 2 * fiveSeconds)));
        }/*from  w  w w  .jav  a 2  s. c o  m*/
    }
}

From source file:com.github.jrrdev.mantisbtsync.core.common.auth.PortalAuthManager.java

/**
 * EGet the authenfication by executing the defined requests sequence.
 *
 * @throws IOException/*from w w  w  . j a va  2s . c  o  m*/
 * @throws ClientProtocolException
 */
public ExitStatus authentificate() throws ClientProtocolException, IOException {
    authCookie = null;

    if (firstRequest != null) {

        final CookieStore cookieStore = new BasicCookieStore();
        client = HttpClients.custom().setDefaultCookieStore(cookieStore)
                .setRedirectStrategy(new LaxRedirectStrategy()).useSystemProperties().build();

        lastResponse = firstRequest.executeSequence(client);

        final List<Cookie> cookies = cookieStore.getCookies();
        final StringBuilder strBuff = new StringBuilder();
        for (final Cookie cookie : cookies) {
            strBuff.append(cookie.getName());
            strBuff.append("=");
            strBuff.append(cookie.getValue());
            strBuff.append(";");
        }

        authCookie = strBuff.toString();
    }

    return ExitStatus.COMPLETED;
}

From source file:net.bither.http.BaseHttpResponse.java

private BasicCookieStore getCookieStore(String domain) {
    BasicCookieStore cookieStore = null;
    if (cookieCache.containsKey(domain)) {
        cookieStore = cookieCache.get(domain);
    } else {//from w ww  .j  a  va 2  s. c om
        PersistentCookieStore persistentCookieStore = PersistentCookieStore.getInstance();
        cookieStore = new BasicCookieStore();
        for (Cookie cookie : persistentCookieStore.getCookies()) {
            BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
            basicClientCookie.setDomain(domain);
            basicClientCookie.setExpiryDate(cookie.getExpiryDate());
            basicClientCookie.setVersion(cookie.getVersion());
            basicClientCookie.setPath(cookie.getPath());
            cookieStore.addCookie(basicClientCookie);
        }
        cookieCache.put(domain, cookieStore);
    }
    return cookieStore;
}

From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java

public static Cookie copyCookie(Cookie toCopy, String targetServer) {
    // Parse the target server down to a domain name
    int index = targetServer.indexOf("://");
    if (index > -1) {
        targetServer = targetServer.substring(index + 3);
    }//from w w  w . j  av  a 2s.  c o m
    // JBAS-8540
    // need to be able to parse IPv6 URLs which have enclosing brackets
    // HttpClient 3.1 creates cookies which oinclude the square brackets
    // index = targetServer.indexOf(":");
    index = targetServer.lastIndexOf(":");
    if (index > -1) {
        targetServer = targetServer.substring(0, index);
    }
    index = targetServer.indexOf("/");
    if (index > -1) {
        targetServer = targetServer.substring(0, index);
    }

    // Cookie copy = new Cookie(targetServer, toCopy.getName(), toCopy.getValue(), "/", null, false);
    BasicClientCookie copy = new BasicClientCookie(toCopy.getName(), toCopy.getValue());
    copy.setDomain(targetServer);
    return copy;
}

From source file:com.janoz.usenet.processors.impl.NZBGetProcessor.java

@Override
public void validateResponse(InputStream responseStream) throws RetrieveException {
    Cookie uploadStatus = super.getCookie("upload_status");
    if (uploadStatus != null) {
        try {/*  w  w w .  j  av a2s .co  m*/
            String status = stripTags(URLDecoder.decode(uploadStatus.getValue(), "UTF8"));
            if (status.startsWith("Error")) {
                throw new RetrieveException("NzbGetWeb " + status.replace('\n', ' '));
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error("UTF8 encoding not available. This should have been impossible");
            throw new RuntimeException("UTF8 encoding not available. This should have been impossible");
        }
    } else {
        if (isLoginResponse(responseStream)) {
            throw new RetrieveException("Authorization required.");
        }
        throw new RetrieveException("Unknown response from NzbGetWeb.");
    }

}

From source file:com.kynetx.api.java

protected void storeCookies(CookieStore toStore) throws IOException {
    if (isWritable()) {
        File path = new File(context.getExternalFilesDir(null), "cookies");

        OutputStream output = new FileOutputStream(path);
        ObjectOutputStream oos = new ObjectOutputStream(output);

        List<Cookie> cookies = toStore.getCookies();

        oos.writeInt(cookies.size());//w  ww  . j a  v  a2s .  co  m

        for (int i = 0; i < cookies.size(); i++) {
            Cookie cookie = cookies.get(i);
            oos.writeObject(cookie.getName());
            oos.writeObject(cookie.getValue());
            oos.writeObject(cookie.getDomain());
            oos.writeObject(cookie.getPath());
            oos.writeInt(cookie.getVersion());
        }

        oos.close();
    } else {
        throw new IOException();
    }
}

From source file:mobi.dlys.android.core.net.http.request.PersistentCookieStore.java

public StringBuffer getCookieHeader(String url) {

    String domain = UrlUtil.getDomain(url);
    List<Cookie> list = getCookies();
    StringBuffer buffer = new StringBuffer();
    for (Cookie c : list) {
        if (c.getDomain().equalsIgnoreCase(domain)) {
            buffer.append(c.getName()).append("=").append(c.getValue()).append(";");
        }/* w  w  w .  j  av a2 s. c om*/
    }
    return buffer;
}

From source file:org.tellervo.desktop.wsi.util.WSCookieWrapper.java

@Override
public boolean equals(Object o) {
    if (o instanceof WSCookieWrapper) {
        WSCookieWrapper w = (WSCookieWrapper) o;

        return (iseq(name, w.name) && iseq(attribs, w.attribs) && iseq(value, w.value)
                && iseq(cookieComment, w.cookieComment) && iseq(cookieDomain, w.cookieDomain)
                && iseq(cookiePath, w.cookiePath) && iseq(isSecure, w.isSecure)
                && iseq(cookieVersion, w.cookieVersion) && iseq(commentURL, w.commentURL)
                && iseq(ports, w.ports));
    }/*from  w ww . j  a  va 2s . co m*/

    if (o instanceof Cookie) {
        Cookie c = (Cookie) o;
        boolean match;

        match = iseq(name, c.getName()) && iseq(value, c.getValue()) && iseq(cookieComment, c.getComment())
                && iseq(cookieDomain, c.getDomain()) && iseq(cookiePath, c.getPath())
                && iseq(isSecure, c.isSecure()) && iseq(cookieVersion, c.getVersion())
                && iseq(commentURL, c.getCommentURL()) && iseq(ports, c.getPorts());

        if (!match)
            return false;

        /*
        if(c instanceof ClientCookie) {
           ClientCookie cc = (ClientCookie) c;
                   
           for(String attr : ATTR_LIST) {
              if(!iseq(attribs.get(attr), cc.getAttribute(attr)))
          return false;
           }
        }
        */

        return true;
    }

    return false;
}

From source file:org.xwiki.wysiwyg.internal.plugin.alfresco.server.SiteMinderAuthenticator.java

/**
 * @return the list of SiteMinder cookies that have to be added to the HTTP request in order to authenticate it.
 *///from   w  ww  . j av a  2s.  com
private List<Cookie> getSiteMinderCookies() {
    javax.servlet.http.Cookie[] receivedCookies = ((ServletRequest) container.getRequest())
            .getHttpServletRequest().getCookies();
    List<Cookie> cookies = new ArrayList<Cookie>();
    // Look for the SMSESSION cookie.
    for (int i = 0; i < receivedCookies.length; i++) {
        javax.servlet.http.Cookie receivedCookie = receivedCookies[i];
        if (SITE_MINDER_COOKIES.contains(receivedCookie.getName())) {
            BasicClientCookie cookie = new BasicClientCookie(receivedCookie.getName(),
                    receivedCookie.getValue());
            cookie.setVersion(receivedCookie.getVersion());
            cookie.setDomain(receivedCookie.getDomain());
            cookie.setPath(receivedCookie.getPath());
            cookie.setSecure(receivedCookie.getSecure());
            // Set attributes EXACTLY as sent by the browser.
            cookie.setAttribute(ClientCookie.VERSION_ATTR, String.valueOf(receivedCookie.getVersion()));
            cookie.setAttribute(ClientCookie.DOMAIN_ATTR, receivedCookie.getDomain());
            cookies.add(cookie);
        }
    }
    return cookies;
}

From source file:org.exoplatform.shareextension.service.UploadAction.java

@Override
protected boolean doExecute() {
    String id = uploadInfo.uploadId;
    String boundary = "----------------------------" + id;
    String CRLF = "\r\n";
    int status = -1;
    OutputStream output = null;//from   w ww  .  j av a  2s.c  om
    PrintWriter writer = null;
    try {
        // Open a connection to the upload web service
        StringBuffer stringUrl = new StringBuffer(postInfo.ownerAccount.serverUrl).append("/portal")
                .append(ExoConstants.DOCUMENT_UPLOAD_PATH_REST).append("?uploadId=").append(id);
        URL uploadUrl = new URL(stringUrl.toString());
        HttpURLConnection uploadReq = (HttpURLConnection) uploadUrl.openConnection();
        uploadReq.setDoOutput(true);
        uploadReq.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        // Pass the session cookies for authentication
        CookieStore store = ExoConnectionUtils.cookiesStore;
        if (store != null) {
            StringBuffer cookieString = new StringBuffer();
            for (Cookie cookie : store.getCookies()) {
                cookieString.append(cookie.getName()).append("=").append(cookie.getValue()).append("; ");
            }
            uploadReq.addRequestProperty("Cookie", cookieString.toString());
        }
        ExoConnectionUtils.setUserAgent(uploadReq);
        // Write the form data
        output = uploadReq.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                + uploadInfo.fileToUpload.documentName + "\"").append(CRLF);
        writer.append("Content-Type: " + uploadInfo.fileToUpload.documentMimeType).append(CRLF);
        writer.append(CRLF).flush();
        byte[] buf = new byte[1024];
        while (uploadInfo.fileToUpload.documentData.read(buf) != -1) {
            output.write(buf);
        }
        output.flush();
        writer.append(CRLF).flush();
        writer.append("--" + boundary + "--").append(CRLF).flush();
        // Execute the connection and retrieve the status code
        status = uploadReq.getResponseCode();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error while uploading " + uploadInfo.fileToUpload, e);
    } finally {
        if (uploadInfo != null && uploadInfo.fileToUpload != null
                && uploadInfo.fileToUpload.documentData != null)
            try {
                uploadInfo.fileToUpload.documentData.close();
            } catch (IOException e1) {
                Log.e(LOG_TAG, "Error while closing the upload stream", e1);
            }
        if (output != null)
            try {
                output.close();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error while closing the connection", e);
            }
        if (writer != null)
            writer.close();
    }
    if (status < HttpURLConnection.HTTP_OK || status >= HttpURLConnection.HTTP_MULT_CHOICE) {
        // Exit if the upload went wrong
        return listener.onError("Could not upload the file " + uploadInfo.fileToUpload.documentName);
    }
    status = -1;
    try {
        // Prepare the request to save the file in JCR
        String stringUrl = postInfo.ownerAccount.serverUrl + "/portal"
                + ExoConstants.DOCUMENT_CONTROL_PATH_REST;
        Uri moveUri = Uri.parse(stringUrl);
        moveUri = moveUri.buildUpon().appendQueryParameter("uploadId", id)
                .appendQueryParameter("action", "save")
                .appendQueryParameter("workspaceName", DocumentHelper.getInstance().workspace)
                .appendQueryParameter("driveName", uploadInfo.drive)
                .appendQueryParameter("currentFolder", uploadInfo.folder)
                .appendQueryParameter("fileName", uploadInfo.fileToUpload.documentName).build();
        HttpGet moveReq = new HttpGet(moveUri.toString());
        // Execute the request and retrieve the status code
        HttpResponse move = ExoConnectionUtils.httpClient.execute(moveReq);
        status = move.getStatusLine().getStatusCode();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error while saving " + uploadInfo.fileToUpload + " in JCR", e);
    }
    boolean ret = false;
    if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
        ret = listener.onSuccess("File " + uploadInfo.fileToUpload.documentName + "uploaded successfully");
    } else {
        ret = listener.onError("Could not save the file " + uploadInfo.fileToUpload.documentName);
    }
    return ret;
}