Example usage for org.apache.http.client CookieStore addCookie

List of usage examples for org.apache.http.client CookieStore addCookie

Introduction

In this page you can find the example usage for org.apache.http.client CookieStore addCookie.

Prototype

void addCookie(Cookie cookie);

Source Link

Document

Adds an Cookie , replacing any existing equivalent cookies.

Usage

From source file:com.gsma.mobileconnect.utils.RestClient.java

/**
 * Build a cookie store that contains the specified cookies.
 * <p>/*from  w  ww . ja v a 2s.  c o  m*/
 * The domain of the cookies is set to the specified host.
 *
 * @param host The domain of the cookies.
 * @param cookiesToProxy The cookies to add to the store.
 * @return The cookie store.
 */
private CookieStore buildCookieStore(String host, List<KeyValuePair> cookiesToProxy) {
    CookieStore cookieStore = new BasicCookieStore();

    if (null == cookiesToProxy) {
        return cookieStore;
    }

    for (KeyValuePair cookieToProxy : cookiesToProxy) {
        BasicClientCookie cookie = new BasicClientCookie(cookieToProxy.getKey(), cookieToProxy.getValue());
        cookie.setDomain(host);
        cookieStore.addCookie(cookie);
    }

    return cookieStore;
}

From source file:com.mockey.ClientExecuteProxy.java

/**
 * // ww  w  .  ja v  a  2s.  c  om
 * @param twistInfo
 * @param proxyServer
 * @param realServiceUrl
 * @param httpMethod
 * @param request
 * @return
 * @throws ClientExecuteProxyException
 */
public ResponseFromService execute(TwistInfo twistInfo, ProxyServerModel proxyServer, Url realServiceUrl,
        boolean allowRedirectFollow, RequestFromClient request) throws ClientExecuteProxyException {
    log.info("Request: " + String.valueOf(realServiceUrl));

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.ISO_8859_1);
    HttpProtocolParams.setUseExpectContinue(params, false);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(supportedSchemes);
    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    if (!allowRedirectFollow) {
        // Do NOT allow for 302 REDIRECT
        httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
            public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
                boolean isRedirect = false;
                try {
                    isRedirect = super.isRedirected(request, response, context);
                } catch (ProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (!isRedirect) {
                    int responseCode = response.getStatusLine().getStatusCode();
                    if (responseCode == 301 || responseCode == 302) {
                        return true;
                    }
                }
                return isRedirect;
            }
        });
    } else {
        // Yes, allow for 302 REDIRECT
        // Nothing needed here.
    }

    // Prevent CACHE, 304 not modified
    //      httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
    //         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    //            
    //            request.setHeader("If-modified-Since", "Fri, 13 May 2006 23:54:18 GMT");
    //
    //         }
    //      });

    CookieStore cookieStore = httpclient.getCookieStore();
    for (Cookie httpClientCookie : request.getHttpClientCookies()) {
        // HACK:
        // httpClientCookie.getValue();
        cookieStore.addCookie(httpClientCookie);
    }
    // httpclient.setCookieStore(cookieStore);

    if (ClientExecuteProxy.cookieStore == null) {
        ClientExecuteProxy.cookieStore = httpclient.getCookieStore();

    } else {
        httpclient.setCookieStore(ClientExecuteProxy.cookieStore);
    }

    StringBuffer requestCookieInfo = new StringBuffer();
    // Show what cookies are in the store .
    for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
        log.debug("Cookie in the cookie STORE: " + cookie.toString());
        requestCookieInfo.append(cookie.toString() + "\n\n\n");

    }

    if (proxyServer.isProxyEnabled()) {
        // make sure to use a proxy that supports CONNECT
        httpclient.getCredentialsProvider().setCredentials(proxyServer.getAuthScope(),
                proxyServer.getCredentials());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer.getHttpHost());
    }

    // TWISTING
    Url originalRequestUrlBeforeTwisting = null;
    if (twistInfo != null) {
        String fullurl = realServiceUrl.getFullUrl();
        String twistedUrl = twistInfo.getTwistedValue(fullurl);
        if (twistedUrl != null) {
            originalRequestUrlBeforeTwisting = realServiceUrl;
            realServiceUrl = new Url(twistedUrl);
        }
    }

    ResponseFromService responseMessage = null;
    try {
        HttpHost htttphost = new HttpHost(realServiceUrl.getHost(), realServiceUrl.getPort(),
                realServiceUrl.getScheme());

        HttpResponse response = httpclient.execute(htttphost, request.postToRealServer(realServiceUrl));
        if (response.getStatusLine().getStatusCode() == 302) {
            log.debug("FYI: 302 redirect occuring from " + realServiceUrl.getFullUrl());
        }
        responseMessage = new ResponseFromService(response);
        responseMessage.setOriginalRequestUrlBeforeTwisting(originalRequestUrlBeforeTwisting);
        responseMessage.setRequestUrl(realServiceUrl);
    } catch (Exception e) {
        log.error(e);
        throw new ClientExecuteProxyException("Unable to retrieve a response. ", realServiceUrl, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // Parse out the response information we're looking for
    // StringBuffer responseCookieInfo = new StringBuffer();
    // // Show what cookies are in the store .
    // for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
    // log.info("Cookie in the cookie STORE: " + cookie.toString());
    // responseCookieInfo.append(cookie.toString() + "\n\n\n");
    //
    // }
    // responseMessage.setRequestCookies(requestCookieInfo.toString());
    // responseMessage.setResponseCookies(responseCookieInfo.toString());
    return responseMessage;
}

From source file:com.hp.mqm.client.AbstractMqmRestClient.java

/**
 * Invokes {@link org.apache.http.client.HttpClient#execute(org.apache.http.client.methods.HttpUriRequest)}
 * with given request and it does login if it is necessary.
 *
 * Method does not support request with non-repeatable entity (see {@link HttpEntity#isRepeatable()}).
 *
 * @param request which should be executed
 * @return response for given request// w ww .  j a v a  2s .co  m
 * @throws IllegalArgumentException when request entity is not repeatable
 */
protected HttpResponse execute(HttpUriRequest request) throws IOException {
    HttpResponse response;

    if (LWSSO_TOKEN == null) {
        login();
    }
    HttpContext localContext = new BasicHttpContext();
    CookieStore localCookies = new BasicCookieStore();
    localCookies.addCookie(LWSSO_TOKEN);
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);

    addRequestHeaders(request);
    response = httpClient.execute(request, localContext);
    if (response.getStatusLine().getStatusCode() == 401) {
        HttpClientUtils.closeQuietly(response);
        login();
        localCookies.clear();
        localCookies.addCookie(LWSSO_TOKEN);
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);
        addRequestHeaders(request);
        response = httpClient.execute(request, localContext);
    }
    return response;
}

From source file:com.num.mobiperf.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *///  w  w w  .  j a  v a2s .com
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        HttpConnectionParams.setConnectionTimeout(params, POST_TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(params, POST_TIMEOUT_MILLISEC);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        // Logger.w("Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}

From source file:edu.mit.scratch.ScratchCloudSession.java

public String get(final String key) throws ScratchProjectException {
    try {//from w  w  w  .j  av  a  2  s  .  c o  m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/varserver/" + this.getProjectID())
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*//*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = ((JSONArray) jsonOBJ.get("variables")).iterator();

        while (keys.hasNext()) {
            final JSONObject o = new JSONObject(StringEscapeUtils.unescapeJson("" + keys.next()));
            final String k = o.get("name") + "";

            if (k.equals(key))
                return o.get("value") + "";
        }
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return null;
}

From source file:edu.mit.scratch.ScratchCloudSession.java

public List<String> getVariables() throws ScratchProjectException {
    final List<String> list = new ArrayList<>();

    try {//from www . j a v a  2  s.co m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/varserver/" + this.getProjectID())
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*//*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = ((JSONArray) jsonOBJ.get("variables")).iterator();

        while (keys.hasNext()) {
            final JSONObject o = new JSONObject(StringEscapeUtils.unescapeJson("" + keys.next()));
            final String k = o.get("name") + "";
            list.add(k);
        }
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return list;
}

From source file:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClient.java

/**
 * This method creates a cookie for every {@link HeaderElement} of the {@link Header} given as parameter.
 * Then, it adds this newly created cookie into the {@link CookieStore} provided as parameter.
 *///from   ww  w  .j  a v  a  2 s .c o  m
protected void createAndAddCookiesOnStoreForHeader(CookieStore cookieStore, Header header) {
    for (HeaderElement element : header.getElements()) {
        BasicClientCookie cookie = createCookieForHeaderElement(element);
        cookieStore.addCookie(cookie);
    }
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side contacts. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account//from   w ww .  ja v  a  2 s.c  o m
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyContacts A list of the contacts to send to the server
 * @return A list of contacts that we need to update locally
 */
public static void syncCalendar(Context context, Account account, String authtoken, long serverSyncState)
        throws JSONException, ParseException, IOException, AuthenticationException {
    ArrayList<SerializableCookie> myCookies;
    CookieStore cookieStore = new BasicCookieStore();
    DefaultHttpClient hClient = getHttpClient(context);
    mContentResolver = context.getContentResolver();
    final String[] weeknames = { "rota_this_week", "rota_next_week" };

    long calendar_id = getCalendar(account);
    if (calendar_id == -1) {
        Log.e("CalendarSyncAdapter", "Unable to create HutSync event calendar");
        return;
    }

    try {
        myCookies = (ArrayList<SerializableCookie>) fromString(authtoken);
    } catch (final IOException e) {
        Log.e(TAG, "IOException when expanding authtoken", e);
        return;
    } catch (final ClassNotFoundException e) {
        Log.e(TAG, "ClassNotFoundException when expanding authtoken", e);
        return;
    }

    for (SerializableCookie cur_cookie : myCookies) {
        cookieStore.addCookie(cur_cookie.getCookie());
    }

    hClient.setCookieStore(cookieStore);
    Log.i(TAG, "Syncing to: " + SYNC_CONTACTS_URI);
    HttpGet httpget = new HttpGet(SYNC_CONTACTS_URI);
    final HttpResponse resp = hClient.execute(httpget);
    final String response = EntityUtils.toString(resp.getEntity());
    HashMap<Long, SyncEntry> localEvents = new HashMap<Long, SyncEntry>();
    ArrayList<Event> events = new ArrayList<Event>();
    Pattern p = Pattern.compile("background-color:(#[[a-f][A-F][0-9]]{6})");
    Pattern ps = Pattern
            .compile(".calendar-key span.(\\S+) \\{ background-color:(#[[a-f][A-F][0-9]]{6}); color:#fff; \\}");

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        //check we are still logged in
        //if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        //    Log.e(TAG, "Authentication exception in sending dirty contacts");
        //    throw new AuthenticationException();
        //}

        //if we are logged in
        Map<String, String> shift_types = new HashMap<String, String>();
        int length = weeknames.length;
        Document doc = Jsoup.parse(response);
        String full_name = doc.select("a[href*=" + account.name + "/profile]").first().text();

        AccountManager mAccountManager = AccountManager.get(context);
        Account[] the_accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
        boolean multiple_accounts = (the_accounts.length > 1);

        Elements the_styles = doc.select("style");
        for (Element the_style : the_styles) {
            String st_txt = the_style.html();
            Matcher ms = ps.matcher(st_txt);
            while (ms.find()) { // Find each match in turn; String can't do this.
                String cname = ms.group(1); // Access a submatch group; String can't do this.
                String ccol = ms.group(2);
                String rname = doc.select("span." + cname).first().text();
                Log.i(TAG, "LOOK: " + cname + ", " + ccol + ", " + rname);
                shift_types.put(ccol, rname);
            }
        }

        for (int w = 0; w < weeknames.length; w++) {

            Elements the_dates = doc.select("div.homepage div.accord-content table[id=" + weeknames[w]
                    + "] tr.heading th:not(.skipStyles)");
            //for (Element hidden : the_dates) { //0 is Mon, 6 is Sun
            Element the_date = the_dates.first(); //figure out the year for the Monday.
            String str_v = the_date.text();
            String[] str_sub = str_v.split(" ");
            str_sub[1] = str_sub[1].trim();
            String[] date_split = str_sub[1].split("/");
            Calendar c = Calendar.getInstance();
            int this_month = c.get(Calendar.MONTH) + 1;
            int monday_month = Integer.parseInt(date_split[1]);
            int this_year = c.get(Calendar.YEAR);
            int monday_year = this_year;
            if (this_month > monday_month) {
                monday_year++;
            } else if (this_month < monday_month) {
                monday_year--;
            }

            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
            Date date = new Date();
            if (str_v != null && !str_v.isEmpty()) {
                String this_date = str_sub[1] + "/" + monday_year; //we need to figure out the year - sometimes its next year

                try {
                    date = format.parse(this_date);
                } catch (Exception e) {
                    // TODO Auto-generated catch block  
                    e.printStackTrace();
                }
                Log.i(TAG, "Dates: " + this_date + " - " + date);
            }
            //}

            for (int i = 1; i < 8; ++i) { //1 is monday, 7 is sunday
                Elements hiddens = doc.select("div.homepage div.accord-content table[id=" + weeknames[w]
                        + "] td:eq(" + Integer.toString(i) + "):not(.skipStyles) div.timeElem");
                int add_days = i - 1;
                for (Element hidden : hiddens) {
                    String str = hidden.text();
                    if (str != null && !str.isEmpty()) {
                        String style = hidden.attr("style");
                        String bg_col = "";
                        Matcher m = p.matcher(style);
                        if (m.find()) {
                            bg_col = m.group(1); // Access a submatch group; String can't do this.
                        }

                        Log.i(TAG, "Time: " + str + "(" + bg_col + ")");
                        String ev_description = ""; //Location too?
                        if (multiple_accounts)
                            ev_description += full_name + "\n\n";
                        String[] times = str.split(" - ");
                        String[] start_time = times[0].split(":");
                        String[] end_time = times[1].split(":");
                        int add_start_hours = Integer.parseInt(start_time[0]);
                        int add_start_minutes = Integer.parseInt(start_time[1]);
                        int add_finish_hours = Integer.parseInt(end_time[0]);
                        int add_finish_minutes = Integer.parseInt(end_time[1]);
                        String ev_shiftType = "";
                        if (bg_col != null && !bg_col.isEmpty()) {
                            ev_shiftType = (String) shift_types.get(bg_col);
                        } else {
                            ev_shiftType = "Other";
                        }
                        String ev_title = ev_shiftType + " Shift";

                        c.setTime(date);
                        c.add(Calendar.DATE, add_days);
                        c.add(Calendar.HOUR_OF_DAY, add_start_hours);
                        c.add(Calendar.MINUTE, add_start_minutes);
                        Date startDate = c.getTime();
                        long ev_id = startDate.getTime();

                        c.setTime(date);
                        c.add(Calendar.DATE, add_days);
                        if (add_finish_hours < add_start_hours) { //shift rolls to next day
                            c.add(Calendar.HOUR_OF_DAY, 24);
                            ev_description += "Shift finishes at " + times[1] + " on the next day\n\n";
                        } else {
                            c.add(Calendar.HOUR_OF_DAY, add_finish_hours);
                            c.add(Calendar.MINUTE, add_finish_minutes);
                        }
                        Date endDate = c.getTime();

                        Event ev = new Event(ev_id, ev_title, startDate, endDate, ev_description, ev_shiftType);
                        events.add(ev);
                        Log.i(TAG, "Event: " + ev);
                    }
                }
            }
        }

        //next merge adjacent shifts
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        Event prev_event = null;
        for (Iterator<Event> it = events.iterator(); it.hasNext();) {
            Event cur_event = it.next();
            if (prev_event != null) {
                if (prev_event.getEndDate().compareTo(cur_event.getStartDate()) == 0) {
                    prev_event.setDescription(prev_event.getDescription() + "Merged consecutive shifts:\n"
                            + timeFormat.format(prev_event.getStartDate()) + " to "
                            + timeFormat.format(prev_event.getEndDate()) + " (" + prev_event.getShiftType()
                            + ")\n" + timeFormat.format(cur_event.getStartDate()) + " to "
                            + timeFormat.format(cur_event.getEndDate()) + " (" + cur_event.getShiftType()
                            + ")\n\n");
                    prev_event.setEndDate(cur_event.getEndDate()); //TODO: only merge if other + FOH/BOH, note times in new description
                    it.remove();
                }
            }
            prev_event = cur_event;
        }

        //next, load local events
        Cursor c1 = mContentResolver.query(
                Events.CONTENT_URI.buildUpon().appendQueryParameter(Events.ACCOUNT_NAME, account.name)
                        .appendQueryParameter(Events.ACCOUNT_TYPE, account.type).build(),
                new String[] { Events._ID, Events._SYNC_ID }, Events.CALENDAR_ID + "=?",
                new String[] { String.valueOf(calendar_id) }, null);
        while (c1 != null && c1.moveToNext()) {
            //if(is_full_sync) {
            //   deleteEvent(context, account, c1.getLong(0));
            //} else {
            SyncEntry entry = new SyncEntry();
            entry.raw_id = c1.getLong(0);
            localEvents.put(c1.getLong(1), entry);
            //}
        }
        c1.close();
        try {
            ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
            for (Event event : events) {

                if (localEvents.containsKey(Long.valueOf(event.getId()))) {
                    SyncEntry entry = localEvents.get(Long.valueOf(event.getId()));
                    operationList.add(updateEvent(calendar_id, account, event, entry.raw_id));
                } else {
                    operationList.add(updateEvent(calendar_id, account, event, -1));
                }

                if (operationList.size() >= 50) {
                    try {
                        mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    operationList.clear();
                }
            }

            if (operationList.size() > 0) {
                try {
                    mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return;
        }

    } else {
        Log.e(TAG, "Server error in sending dirty contacts: " + resp.getStatusLine());
        throw new IOException();
    }
}

From source file:edu.mit.scratch.ScratchProject.java

public ScratchProject update() throws ScratchProjectException {
    try {//  www.j  a  v  a 2s. c  o m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)"
                        + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36")
                .setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/api/v1/project/" + this.getProjectID() + "/?format=json")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
            System.out.println(resp.getStatusLine().toString());
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println("projdata:" + result.toString());
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = jsonOBJ.keys();

        while (keys.hasNext()) {
            final String key = "" + keys.next();
            final Object o = jsonOBJ.get(key);
            if (o instanceof JSONObject)
                this.creator = "" + ((JSONObject) o).get("username");
            else {
                final String val = "" + o;

                switch (key) {
                case "creator":
                    this.creator = val;
                    break;
                case "datetime_shared":
                    this.share_date = val;
                    break;
                case "description":
                    this.description = val;
                    break;
                case "favorite_count":
                    this.favorite_count = val;
                    break;
                case "id":
                    this.ID = Integer.parseInt(val);
                    break;
                case "love_count":
                    this.love_count = val;
                    break;
                case "resource_uri":
                    this.resource_uri = val;
                    break;
                case "thumbnail":
                    this.thumbnail = val;
                    break;
                case "title":
                    this.title = val;
                    break;
                case "view_count":
                    this.view_count = val;
                    break;
                default:
                    System.out.println("Missing reference:" + key);
                    break;
                }
            }
        }
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return this;
}

From source file:org.sigmond.net.AsyncHttpTask.java

protected HttpRequestInfo doInBackground(HttpRequestInfo... params) {
    HttpRequestInfo rinfo = params[0];//from w w w .  j ava  2  s.co  m
    try {
        client.setCookieStore(rinfo.getCookieStore()); //cookie handling
        HttpResponse resp = client.execute(rinfo.getRequest()); //execute request

        //store any new cookies recieved
        CookieStore store = rinfo.getCookieStore();
        Header[] allHeaders = resp.getAllHeaders();
        CookieSpecBase base = new BrowserCompatSpec();
        URI uri = rinfo.getRequest().getURI();
        int port = uri.getPort();
        if (port <= 0)
            port = 80;
        CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri.getPath(), false);
        for (Header header : allHeaders) {
            List<Cookie> parse = base.parse(header, origin);
            for (Cookie cookie : parse) {
                if (cookie.getValue() != null && cookie.getValue() != "")
                    store.addCookie(cookie);
            }
        }
        rinfo.setCookieStore(store);
        //store the response
        rinfo.setResponse(resp);
        //process the response string. This is required in newer Android versions.
        //newer versions will not allow reading from a network response input stream in the main thread.
        rinfo.setResponseString(HttpUtils.responseToString(resp));
    } catch (Exception e) {
        rinfo.setException(e);
    }
    return rinfo;
}