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:edu.wpi.cs.wpisuitetng.LoginServletTest.java

@Test
@Ignore/*from  w ww .  j ava2 s  .  c om*/
/**
 * Acceptence Test 3: User with valid credentials attempts to login.
 *  Preconditions:      (1) There must be a user with the username "twack" and 
 *                    a password "abcde" in the database
 *                    
 *    Expected Results:    (1) 200 OK Response Code
 *                   (2) WPI Suite Cookie Returned
 *                   (3) Cookie header match
 *                   (4) Cookie body contains loginTime & valid username (will be tightened soon)
 * @throws ClientProtocolException
 * @throws IOException
 */
public void testLoginSuccess() throws ClientProtocolException, IOException {

    HttpPost httpPost = new HttpPost("http://localhost:8080/WPISuite/API/login/");
    String token = BasicAuth.generateBasicAuth("twack", "abcde");
    httpPost.setHeader("Authorization", token);
    HttpResponse response = httpclient.execute(httpPost);

    try {
        // Stat Code is OK
        StatusLine responseStatus = response.getStatusLine();
        assertEquals(200, responseStatus.getStatusCode());

        // Cookie exists?
        List<Cookie> cookies = this.httpclient.getCookieStore().getCookies();
        assertEquals(1, cookies.size());

        // Cookie Header validation
        Cookie wpiSuite = cookies.get(0);
        String expectedHeader = "WPISUITE-twack";
        assertTrue(expectedHeader.equals(wpiSuite.getName()));

        // Cookie Body validation
        String cookieBody = wpiSuite.getValue();

        assertTrue(cookieBody.contains("loginTime"));
        assertTrue(cookieBody.contains("twack"));
        // TODO: compare against actual serialized Session
    } finally {
        httpPost.releaseConnection();
    }
}

From source file:de.damdi.fitness.activity.settings.sync.RestClient.java

/**
 * Get the first occurrence of a cookie named like this
 * /*  w  w w.  j  av  a  2s. c o m*/
 * @return the value if the cookie exists, otherwise null
 */
public String getCookie(String name) {
    List<Cookie> cookies = mClient.getCookieStore().getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(name)) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:com.partnet.automation.http.ApacheHttpAdapter.java

private List<CookieAdapter> convertCookieToAdapter(List<Cookie> cookies) {
    List<CookieAdapter> adapt = new ArrayList<>();

    for (Cookie cookie : cookies) {
        adapt.add(new CookieAdapter.Builder().setDomain(cookie.getDomain()).setName(cookie.getName())
                .setExpiryDate(cookie.getExpiryDate()).setPath(cookie.getPath()).setValue(cookie.getValue())
                .setVersion(cookie.getVersion()).build());
    }// w  w  w .  ja  va2  s.  co  m
    return adapt;
}

From source file:net.fizzl.redditengine.impl.SerializableCookie.java

public SerializableCookie(Cookie cookie) {
    this.comment = cookie.getComment();
    this.commentURL = cookie.getCommentURL();
    this.domain = cookie.getDomain();
    this.expiryDate = cookie.getExpiryDate();
    this.name = cookie.getName();
    this.path = cookie.getPath();
    this.ports = cookie.getPorts();
    this.value = cookie.getValue();
    this.version = cookie.getVersion();
    this.secure = cookie.isSecure();
}

From source file:com.liato.bankdroid.WebViewActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);/*ww  w . jav  a  2s .  com*/
    this.addTitleButton(R.drawable.title_icon_back, "back", this);
    this.addTitleButton(R.drawable.title_icon_forward, "forward", this);
    this.addTitleButton(R.drawable.title_icon_refresh, "refresh", this);
    this.setTitleButtonEnabled("forward", false);
    this.setTitleButtonEnabled("back", false);
    this.setTitleButtonEnabled("refresh", false);

    final CookieSyncManager csm = CookieSyncManager.createInstance(this);
    mWebView = (WebView) findViewById(R.id.wvBank);
    mWebView.setBackgroundColor(0);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setUserAgentString(Urllib.DEFAULT_USER_AGENT);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgressBar(progress);
            if (progress == 100) {
                Handler handler = new Handler();
                Runnable runnable = new Runnable() {
                    public void run() {
                        activity.hideProgressBar();
                    }
                };
                // Let the progress bar hit 100% before we hide it.
                handler.postDelayed(runnable, 100);

            } else if (mFirstPageLoaded) {
                activity.showProgressBar();
            }
        }
    });
    mWebView.setWebViewClient(new BankWebViewClient());
    String preloader = "Error...";
    try {
        preloader = IOUtils.toString(getResources().openRawResource(R.raw.loading));
        preloader = String.format(preloader, "", // Javascript function
                "" // HTML
        );
    } catch (NotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mWebView.loadDataWithBaseURL("what://is/this/i/dont/even", preloader, "text/html", "utf-8", null);

    Bundle extras = getIntent().getExtras();
    final long bankId = extras.getLong("bankid", -1);
    //final long bankId = -1;
    if (bankId >= 0) {
        Runnable generateLoginPage = new Runnable() {
            public void run() {
                Bank bank = BankFactory.bankFromDb(bankId, WebViewActivity.this, false);
                SessionPackage loginPackage = bank.getSessionPackage(WebViewActivity.this);
                CookieStore cookieStore = loginPackage.getCookiestore();
                if ((cookieStore != null) && !cookieStore.getCookies().isEmpty()) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    String cookieString;
                    for (Cookie cookie : cookieStore.getCookies()) {
                        cookieString = String.format("%s=%s;%spath=%s; domain=%s;", cookie.getName(),
                                cookie.getValue(),
                                cookie.getExpiryDate() == null ? ""
                                        : "expires=" + cookie.getExpiryDate() + "; ",
                                cookie.getPath() == null ? "/" : cookie.getPath(), cookie.getDomain());
                        cookieManager.setCookie(cookie.getDomain(), cookieString);
                    }
                    csm.sync();
                }
                mWebView.loadDataWithBaseURL("what://is/this/i/dont/even", loginPackage.getHtml(), "text/html",
                        "utf-8", null);
            }
        };
        new Thread(generateLoginPage).start();
    }
}

From source file:com.jaspersoft.android.jaspermobile.network.cookie.CookieMapperTest.java

@Test
public void testToApacheCookie() throws Exception {
    Cookie cookie = cookieMapper.toApacheCookie(fakeCookie);
    assertThat("Failed to map cookie path", cookie.getPath(), is(fakeCookie.getPath()));
    assertThat("Failed to map cookie domain", cookie.getDomain(), is(fakeCookie.getDomain()));
    assertThat("Failed to map cookie version", cookie.getVersion(), is(fakeCookie.getVersion()));
    assertThat("Failed to map cookie value", cookie.getValue(), is(fakeCookie.getValue()));
    assertThat("Failed to map cookie name", cookie.getName(), is(fakeCookie.getName()));
    assertThat("Failed to map cookie expiry date", cookie.getExpiryDate(), is(notNullValue()));
}

From source file:sft.LoginAndBookSFT.java

public void startBooking() throws URISyntaxException, MalformedURLException, ProtocolException, IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    try {//from  w  ww  .  ja  v a2s.  c  o m
        // get cookie
        final HttpGet httpget = new HttpGet("https://sft.ticketack.com");
        final CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            final HttpEntity entity = response1.getEntity();

            System.out.println("Login form get: " + response1.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            final List<Cookie> _cookies = cookieStore.getCookies();
            if (_cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < _cookies.size(); i++) {
                    System.out.println("- " + _cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        // login
        final HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("https://sft.ticketack.com/ticket/view/"))
                .addParameter("ticket_number", username).addParameter("ticket_key", password).build();
        final CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            final HttpEntity entity = response2.getEntity();

            System.out.println("Login form get: " + response2.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Post logon cookies:");
            final List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    // System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }

    final Cookie _cookie = cookieStore.getCookies().get(0);
    final String mightyCooke = "PHPSESSID=" + _cookie.getValue();

    for (final String _booking : bookings) {

        // get free seatings
        // json https://sft.ticketack.com/screening/infos_json/02c101f9-c62a-445e-ad72-19fb32db34c0
        final String _json = doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/infos_json/");

        final Gson gson = new Gson();
        final Example _allInfos = gson.fromJson(_json, Example.class);

        if (_allInfos.getCinemaHall().getMap() != null) {

            final String _mySeat = getMeAFreeSeat(_json);

            // book on seating
            // 02c101f9-c62a-445e-ad72-19fb32db34c0?format=json&overbook=false&seat=Parkett%20Rechts:1:16
            try {
                if (_mySeat != null)
                    doGet(mightyCooke,
                            _booking + "?format=json&overbook=true&seat=" + URLEncoder.encode(_mySeat, "UTF-8"),
                            "https://sft.ticketack.com/screening/book_on_ticket/");
            } catch (final MalformedURLException exception) {
                System.err.println("Error: " + exception.getMessage());
            } catch (final ProtocolException exception) {
                System.err.println("Error: " + exception.getMessage());
            } catch (final UnsupportedEncodingException exception) {
                System.err.println("Error: " + exception.getMessage());
            } catch (final IOException exception) {
                System.err.println("Error: " + exception.getMessage());
            }
            System.out.println("booking (seat) done for: " + _booking);

        } else {

            // book
            // https://sft.ticketack.com/screening/book_on_ticket/76c039cc-d1d5-40a1-9a5d-2b1cd4c47799
            // Cookie:PHPSESSID=s1a6a8casfhidfq68tqn2cb565
            doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/book_on_ticket/");
            System.out.println("booking done for: " + _booking);
        }

    }

    System.out.println("All done!");

}

From source file:com.github.tmyroadctfig.icloud4j.json.SerializableClientCookie.java

public SerializableClientCookie(Cookie cookie) {
    this.name = cookie.getName();
    this.value = cookie.getValue();
    this.cookieComment = cookie.getComment();
    this.cookieDomain = cookie.getDomain();
    this.cookieExpiryDate = cookie.getExpiryDate() != null ? cookie.getExpiryDate().getTime() : null;
    this.cookiePath = cookie.getPath();
    this.isSecure = cookie.isSecure();
    this.cookieVersion = cookie.getVersion();

    if (cookie instanceof ClientCookie) {
        ClientCookie c = (ClientCookie) cookie;
        copyAttribute(ClientCookie.COMMENT_ATTR, c);
        copyAttribute(ClientCookie.COMMENTURL_ATTR, c);
        copyAttribute(ClientCookie.DISCARD_ATTR, c);
        copyAttribute(ClientCookie.DOMAIN_ATTR, c);
        copyAttribute(ClientCookie.EXPIRES_ATTR, c);
        copyAttribute(ClientCookie.MAX_AGE_ATTR, c);
        copyAttribute(ClientCookie.PATH_ATTR, c);
        copyAttribute(ClientCookie.PORT_ATTR, c);
        copyAttribute(ClientCookie.SECURE_ATTR, c);
        copyAttribute(ClientCookie.DOMAIN_ATTR, c);
    }/*from  ww  w  .  j av  a 2 s  .com*/
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitBrowserCompatCookieSpec.java

@Override
public List<Header> formatCookies(final List<Cookie> cookies) {
    Collections.sort(cookies, COOKIE_COMPARATOR);

    final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
    buffer.append(SM.COOKIE);//from www.j  a  va 2  s . c  om
    buffer.append(": ");
    for (int i = 0; i < cookies.size(); i++) {
        final Cookie cookie = cookies.get(i);
        if (i > 0) {
            buffer.append("; ");
        }
        final String cookieName = cookie.getName();
        final String cookieValue = cookie.getValue();
        if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) {
            HtmlUnitBrowserCompatCookieHeaderValueFormatter.INSTANCE.formatHeaderElement(buffer,
                    new BasicHeaderElement(cookieName, cookieValue), false);
        } else {
            // Netscape style cookies do not support quoted values
            buffer.append(cookieName);
            buffer.append("=");
            if (cookieValue != null) {
                buffer.append(cookieValue);
            }
        }
    }
    final List<Header> headers = new ArrayList<>(1);
    headers.add(new BufferedHeader(buffer));
    return headers;
}

From source file:nya.miku.wishmaster.http.cloudflare.InterceptingAntiDDOS.java

/**  anti-DDOS , ? ? ??  webview  httpclient (? ?? ? ?-?  API >= 11) */
Cookie check(final CloudflareException exception, final ExtendedHttpClient httpClient,
        final CancellableTask task, final Activity activity) {
    synchronized (lock) {
        if (processing)
            return null;
        processing = true;//from w  ww.j av a 2  s. co  m
    }
    processing2 = true;
    currentCookie = null;

    final HttpRequestModel rqModel = HttpRequestModel.builder().setGET().build();
    final CookieStore cookieStore = httpClient.getCookieStore();
    CloudflareChecker.removeCookie(cookieStore, exception.getRequiredCookieName());
    final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView();
    final WebViewClient client = new WebViewClient() {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            HttpResponseModel responseModel = null;
            try {
                responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
                for (int i = 0; i < 3 && responseModel.statusCode == 400; ++i) {
                    Logger.d(TAG, "HTTP 400");
                    responseModel.release();
                    responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
                }
                for (Cookie cookie : cookieStore.getCookies()) {
                    if (CloudflareChecker.isClearanceCookie(cookie, url, exception.getRequiredCookieName())) {
                        Logger.d(TAG, "Cookie found: " + cookie.getValue());
                        currentCookie = cookie;
                        processing2 = false;
                        return new WebResourceResponse("text/html", "UTF-8",
                                new ByteArrayInputStream("cookie received".getBytes()));
                    }
                }
                BufOutputStream output = new BufOutputStream();
                IOUtils.copyStream(responseModel.stream, output);
                return new WebResourceResponse(null, null, output.toInputStream());
            } catch (Exception e) {
                Logger.e(TAG, e);
            } finally {
                if (responseModel != null)
                    responseModel.release();
            }
            return new WebResourceResponse("text/html", "UTF-8",
                    new ByteArrayInputStream("something wrong".getBytes()));
        }
    };

    activity.runOnUiThread(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            webView = new WebView(activity);
            webView.setVisibility(View.GONE);
            layout.addView(webView);
            webView.setWebViewClient(client);
            webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl(exception.getCheckUrl());
        }
    });

    long startTime = System.currentTimeMillis();
    while (processing2) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > CloudflareChecker.TIMEOUT) {
            processing2 = false;
        }
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                layout.removeView(webView);
                webView.stopLoading();
                webView.clearCache(true);
                webView.destroy();
                webView = null;
            } finally {
                processing = false;
            }
        }
    });
    return currentCookie;
}