Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getParams.

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:org.sonatype.nexus.internal.httpclient.HttpClientFactoryImplTest.java

@Test
@Ignore("DefaultHttpClient is not in use anymore")
public void sharedInstanceConfigurationTest() {
    setParameters();// w  w  w.j  a  va  2 s .c om
    try {
        testSubject = new HttpClientFactoryImpl(Providers.of(systemStatus),
                Providers.of(globalRemoteStorageContext), eventBus, jmxInstaller, null);

        final HttpClient client = testSubject.create();
        // Note: shared instance is shared across Nexus instance. It does not features connection pooling as
        // connections are
        // never reused intentionally

        // shared client does not reuse connections (no pool)
        Assert.assertTrue(
                ((DefaultHttpClient) client).getConnectionReuseStrategy() instanceof NoConnectionReuseStrategy);
        Assert.assertTrue(
                ((DefaultHttpClient) client).getConnectionManager() instanceof PoolingClientConnectionManager);

        // check is all set as needed: retries
        Assert.assertTrue(((DefaultHttpClient) client)
                .getHttpRequestRetryHandler() instanceof StandardHttpRequestRetryHandler);
        Assert.assertEquals(globalRemoteStorageContext.getRemoteConnectionSettings().getRetrievalRetryCount(),
                ((StandardHttpRequestRetryHandler) ((DefaultHttpClient) client).getHttpRequestRetryHandler())
                        .getRetryCount());
        Assert.assertEquals(false,
                ((StandardHttpRequestRetryHandler) ((DefaultHttpClient) client).getHttpRequestRetryHandler())
                        .isRequestSentRetryEnabled());

        // check is all set as needed: everything else
        Assert.assertEquals(1234L, client.getParams().getLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 0));
        Assert.assertEquals(1234,
                client.getParams().getIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 0));
        Assert.assertEquals(1234, client.getParams().getIntParameter(HttpConnectionParams.SO_TIMEOUT, 0));
        Assert.assertEquals(1234,
                ((PoolingClientConnectionManager) client.getConnectionManager()).getMaxTotal());
        Assert.assertEquals(1234,
                ((PoolingClientConnectionManager) client.getConnectionManager()).getDefaultMaxPerRoute());
    } finally {
        testSubject.shutdown();
        unsetParameters();
    }
}

From source file:org.sonatype.nexus.apachehttpclient.Hc4ProviderImplTest.java

@Test
@Ignore("DefaultHttpClient is not in use anymore")
public void sharedInstanceConfigurationTest() {
    setParameters();/*  w  ww.ja  v a2s.co m*/
    try {
        testSubject = new Hc4ProviderImpl(applicationConfiguration, userAgentBuilder, eventBus, jmxInstaller,
                null);

        final HttpClient client = testSubject.createHttpClient();
        // Note: shared instance is shared across Nexus instance. It does not features connection pooling as
        // connections are
        // never reused intentionally

        // shared client does not reuse connections (no pool)
        Assert.assertTrue(
                ((DefaultHttpClient) client).getConnectionReuseStrategy() instanceof NoConnectionReuseStrategy);
        Assert.assertTrue(
                ((DefaultHttpClient) client).getConnectionManager() instanceof PoolingClientConnectionManager);

        // check is all set as needed: retries
        Assert.assertTrue(((DefaultHttpClient) client)
                .getHttpRequestRetryHandler() instanceof StandardHttpRequestRetryHandler);
        Assert.assertEquals(globalRemoteStorageContext.getRemoteConnectionSettings().getRetrievalRetryCount(),
                ((StandardHttpRequestRetryHandler) ((DefaultHttpClient) client).getHttpRequestRetryHandler())
                        .getRetryCount());
        Assert.assertEquals(false,
                ((StandardHttpRequestRetryHandler) ((DefaultHttpClient) client).getHttpRequestRetryHandler())
                        .isRequestSentRetryEnabled());

        // check is all set as needed: everything else
        Assert.assertEquals(1234L, client.getParams().getLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 0));
        Assert.assertEquals(1234,
                client.getParams().getIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 0));
        Assert.assertEquals(1234, client.getParams().getIntParameter(HttpConnectionParams.SO_TIMEOUT, 0));
        Assert.assertEquals(1234,
                ((PoolingClientConnectionManager) client.getConnectionManager()).getMaxTotal());
        Assert.assertEquals(1234,
                ((PoolingClientConnectionManager) client.getConnectionManager()).getDefaultMaxPerRoute());
    } finally {
        testSubject.shutdown();
        unsetParameters();
    }
}

From source file:fr.natoine.html.HTMLPage.java

@SuppressWarnings("finally")
public String extractFullContentResource(String _url, int _time_to_respond) {
    String response_content = null;
    HttpClient httpclient = new DefaultHttpClient();
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET , "UTF-8");
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-16");
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "ISO-8859-1");
    //US-ASCII/* ww w.  j av  a 2  s . co m*/
    //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "US-ASCII");
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
    //HttpParams params = 
    //HttpClient httpclient = new DefaultHttpClient(params);
    HttpGet httpget = new HttpGet(_url);
    try {
        //Timer pour mettre un dlai sur le temps d'excution de la requte
        //Timer timer = new Timer();
        //timer.schedule(new TimerTaskTooLong(httpget , _url) , _time_to_respond);
        //HttpResponse response = httpclient.execute(httpget);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        if (responseBody != null) {
            response_content = responseBody;
            //      valid = true ;
        }
    } catch (ClientProtocolException e) {
        //   valid = false ;
        System.out.println(
                "[HTMLPage.extractFullContentCssLink] url : " + _url + " doesn't support GET requests !!! ");
        e.printStackTrace();
    } catch (IOException e) {
        //   valid = false ;
        System.out.println(
                "[HTMLPage.extractFullContentCssLink] url : " + _url + " send no data !!! Not responding ... ");
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
        return response_content;
    }
}

From source file:com.gimranov.zandy.app.task.APIRequest.java

/**
 * Issues the specified request, calling its specified handler as appropriate
 *
 * This should not be run from a UI thread
 *
 * @return//from   www.ja va2s . c o  m
 * @throws APIException
 */
public void issue(Database db, ServerCredentials cred) throws APIException {

    URI uri;

    // Add the API key, if missing and we have it
    if (!query.contains("key=") && key != null) {
        String suffix = (query.contains("?")) ? "&key=" + key : "?key=" + key;
        query = query + suffix;
    }

    // Force lower-case
    method = method.toLowerCase();

    Log.i(TAG, "Request " + method + ": " + query);

    try {
        uri = new URI(query);
    } catch (URISyntaxException e1) {
        throw new APIException(APIException.INVALID_URI, "Invalid URI: " + query, this);
    }

    HttpClient client = new DefaultHttpClient();
    // The default implementation includes an Expect: header, which
    // confuses the Zotero servers.
    client.getParams().setParameter("http.protocol.expect-continue", false);
    // We also need to send our data nice and raw.
    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

    HttpGet get = new HttpGet(uri);
    HttpPost post = new HttpPost(uri);
    HttpPut put = new HttpPut(uri);
    HttpDelete delete = new HttpDelete(uri);

    for (HttpRequest request : Arrays.asList(get, post, put, delete)) {
        request.setHeader("Zotero-API-Version", "1");
    }

    // There are several shared initialization routines for POST and PUT
    if ("post".equals(method) || "put".equals(method)) {
        if (ifMatch != null) {
            post.setHeader("If-Match", ifMatch);
            put.setHeader("If-Match", ifMatch);
        }
        if (contentType != null) {
            post.setHeader("Content-Type", contentType);
            put.setHeader("Content-Type", contentType);
        }
        if (body != null) {
            Log.d(TAG, "Request body: " + body);
            // Force the encoding to UTF-8
            StringEntity entity;
            try {
                entity = new StringEntity(body, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new APIException(APIException.INVALID_UUID,
                        "UnsupportedEncodingException. This shouldn't "
                                + "be possible-- UTF-8 is certainly supported",
                        this);
            }
            post.setEntity(entity);
            put.setEntity(entity);
        }
    }

    if ("get".equals(method)) {
        if (contentType != null) {
            get.setHeader("Content-Type", contentType);
        }
    }

    /* For requests that return Atom feeds or entries (XML):
     *       ITEMS_ALL            ]
     *       ITEMS_FOR_COLLECTION   ]- Except format=keys
     *       ITEMS_CHILDREN         ]
     * 
     *       ITEM_BY_KEY
     *       COLLECTIONS_ALL
     *       ITEM_NEW
     *       ITEM_UPDATE
     *       ITEM_ATTACHMENT_NEW
     *       ITEM_ATTACHMENT_UPDATE
     */
    if ("xml".equals(disposition)) {
        XMLResponseParser parse = new XMLResponseParser(this);
        // These types will always have a temporary key that we've
        // been using locally, and which should be replaced by the
        // incoming item key.
        if (type == ITEM_NEW || type == ITEM_ATTACHMENT_NEW) {
            parse.update(updateType, updateKey);
        }

        try {
            HttpResponse hr;
            if ("post".equals(method)) {
                hr = client.execute(post);
            } else if ("put".equals(method)) {
                hr = client.execute(put);
            } else {
                // We fall back on GET here, but there really
                // shouldn't be anything else, so we throw in that case
                // for good measure
                if (!"get".equals(method)) {
                    throw new APIException(APIException.INVALID_METHOD, "Unexpected method: " + method, this);
                }
                hr = client.execute(get);
            }

            // Record the response code
            status = hr.getStatusLine().getStatusCode();
            Log.d(TAG, status + " : " + hr.getStatusLine().getReasonPhrase());

            if (status < 400) {
                HttpEntity he = hr.getEntity();
                InputStream in = he.getContent();
                parse.setInputStream(in);
                // Entry mode if the request is an update (PUT) or if it is a request
                // for a single item by key (ITEM_BY_KEY)
                int mode = ("put".equals(method) || type == APIRequest.ITEM_BY_KEY)
                        ? XMLResponseParser.MODE_ENTRY
                        : XMLResponseParser.MODE_FEED;
                try {
                    parse.parse(mode, uri.toString(), db);
                } catch (RuntimeException e) {
                    throw new RuntimeException("Parser threw exception on request: " + method + " " + query, e);
                }
            } else {
                ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                hr.getEntity().writeTo(ostream);
                Log.e(TAG, "Error Body: " + ostream.toString());
                Log.e(TAG, "Request Body:" + body);

                if (status == 412) {
                    // This is: "Precondition Failed", meaning that we provided
                    // the wrong etag to update the item. That should mean that
                    // there is a conflict between what we're sending (PUT) and
                    // the server. We mark that ourselves and save the request
                    // to the database, and also notify our handler.
                    getHandler().onError(this, APIRequest.HTTP_ERROR_CONFLICT);
                } else {
                    Log.e(TAG, "Response status " + status + " : " + ostream.toString());
                    getHandler().onError(this, APIRequest.HTTP_ERROR_UNSPECIFIED);
                }
                status = getHttpStatus() + REQ_FAILING;
                recordAttempt(db);

                // I'm not sure whether we should throw here
                throw new APIException(APIException.HTTP_ERROR, ostream.toString(), this);
            }
        } catch (Exception e) {
            StringBuilder sb = new StringBuilder();
            for (StackTraceElement el : e.getStackTrace()) {
                sb.append(el.toString() + "\n");
            }
            recordAttempt(db);
            throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(),
                    this);
        }
    } // end if ("xml".equals(disposition)) {..}
    /* For requests that return non-XML data:
     *       ITEMS_ALL            ]
     *       ITEMS_FOR_COLLECTION   ]- For format=keys
     *       ITEMS_CHILDREN         ]
     * 
     * No server response:
     *       ITEM_DELETE
     *       ITEM_MEMBERSHIP_ADD
     *       ITEM_MEMBERSHIP_REMOVE
     *       ITEM_ATTACHMENT_DELETE
     * 
     * Currently not supported; return JSON:
     *       ITEM_FIELDS
     *       CREATOR_TYPES
     *       ITEM_FIELDS_L10N
     *       CREATOR_TYPES_L10N
     * 
     * These ones use BasicResponseHandler, which gives us
     * the response as a basic string. This is only appropriate
     * for smaller responses, since it means we have to wait until
     * the entire response is received before parsing it, so we
     * don't use it for the XML responses.
     * 
     * The disposition here is "none" or "raw".
     * 
     * The JSON-returning requests, such as ITEM_FIELDS, are not currently
     * supported; they should have a disposition of their own.
     */
    else {
        BasicResponseHandler brh = new BasicResponseHandler();
        String resp;

        try {
            if ("post".equals(method)) {
                resp = client.execute(post, brh);
            } else if ("put".equals(method)) {
                resp = client.execute(put, brh);
            } else if ("delete".equals(method)) {
                resp = client.execute(delete, brh);
            } else {
                // We fall back on GET here, but there really
                // shouldn't be anything else, so we throw in that case
                // for good measure
                if (!"get".equals(method)) {
                    throw new APIException(APIException.INVALID_METHOD, "Unexpected method: " + method, this);
                }
                resp = client.execute(get, brh);
            }
        } catch (IOException e) {
            StringBuilder sb = new StringBuilder();
            for (StackTraceElement el : e.getStackTrace()) {
                sb.append(el.toString() + "\n");
            }
            recordAttempt(db);
            throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(),
                    this);
        }

        if ("raw".equals(disposition)) {
            /* 
             * The output should be a newline-delimited set of alphanumeric
             * keys.
             */

            String[] keys = resp.split("\n");

            ArrayList<String> missing = new ArrayList<String>();

            if (type == ITEMS_ALL || type == ITEMS_FOR_COLLECTION) {

                // Try to get a parent collection
                // Our query looks like this:
                // /users/5770/collections/2AJUSIU9/items
                int colloc = query.indexOf("/collections/");
                int itemloc = query.indexOf("/items");
                // The string "/collections/" is thirteen characters long
                ItemCollection coll = ItemCollection.load(query.substring(colloc + 13, itemloc), db);

                if (coll != null) {
                    coll.loadChildren(db);

                    // If this is a collection's key listing, we first look
                    // for any synced keys we have that aren't in the list
                    ArrayList<String> keyAL = new ArrayList<String>(Arrays.asList(keys));
                    ArrayList<Item> notThere = coll.notInKeys(keyAL);
                    // We should then remove those memberships
                    for (Item i : notThere) {
                        coll.remove(i, true, db);
                    }
                }

                ArrayList<Item> recd = new ArrayList<Item>();
                for (int j = 0; j < keys.length; j++) {
                    Item got = Item.load(keys[j], db);
                    if (got == null) {
                        missing.add(keys[j]);
                    } else {
                        // We can update the collection membership immediately
                        if (coll != null)
                            coll.add(got, true, db);
                        recd.add(got);
                    }
                }

                if (coll != null) {
                    coll.saveChildren(db);
                    coll.save(db);
                }

                Log.d(TAG, "Received " + keys.length + " keys, " + missing.size() + " missing ones");
                Log.d(TAG, "Have " + (double) recd.size() / keys.length + " of list");

                if (recd.size() == keys.length) {
                    Log.d(TAG, "No new items");
                    succeeded(db);
                } else if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) {
                    Log.d(TAG, "Requesting full list");
                    APIRequest mReq;
                    if (type == ITEMS_FOR_COLLECTION) {
                        mReq = fetchItems(coll, false, cred);
                    } else {
                        mReq = fetchItems(false, cred);
                    }

                    mReq.status = REQ_NEW;
                    mReq.save(db);
                } else {
                    Log.d(TAG, "Requesting " + missing.size() + " items one by one");
                    APIRequest mReq;
                    for (String key : missing) {
                        // Queue request for the missing key
                        mReq = fetchItem(key, cred);
                        mReq.status = REQ_NEW;
                        mReq.save(db);
                    }
                    // Queue request for the collection again, by key
                    // XXX This is not the best way to make sure these
                    // items are put in the correct collection.
                    if (type == ITEMS_FOR_COLLECTION) {
                        fetchItems(coll, true, cred).save(db);
                    }
                }
            } else if (type == ITEMS_CHILDREN) {
                // Try to get a parent item
                // Our query looks like this:
                // /users/5770/items/2AJUSIU9/children
                int itemloc = query.indexOf("/items/");
                int childloc = query.indexOf("/children");
                // The string "/items/" is seven characters long
                Item item = Item.load(query.substring(itemloc + 7, childloc), db);

                ArrayList<Attachment> recd = new ArrayList<Attachment>();
                for (int j = 0; j < keys.length; j++) {
                    Attachment got = Attachment.load(keys[j], db);
                    if (got == null)
                        missing.add(keys[j]);
                    else
                        recd.add(got);
                }

                if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) {
                    APIRequest mReq;
                    mReq = cred.prep(children(item));
                    mReq.status = REQ_NEW;
                    mReq.save(db);
                } else {
                    APIRequest mReq;
                    for (String key : missing) {
                        // Queue request for the missing key
                        mReq = fetchItem(key, cred);
                        mReq.status = REQ_NEW;
                        mReq.save(db);
                    }
                }
            }
        } else if ("json".equals(disposition)) {
            // TODO
        } else {
            /* Here, disposition should be "none" */
            // Nothing to be done.
        }

        getHandler().onComplete(this);
    }
}

From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java

/**
 * Wrap a basic HttpClient object in an all trusting SSL enabled
 * HttpClient object.//from   ww w.  j  av  a 2 s.  c  o  m
 * 
 * @param base The HttpClient to wrap.
 * @return The SSL wrapped HttpClient.
 * @throws GeneralSecurityException
 * @throws IOException
 */
private HttpClient trustAllSslEnable(HttpClient base) throws GeneralSecurityException {
    // Get an initialized SSL context
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    // set up the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL"); //$NON-NLS-1$
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
    sr.register(https);
    return new DefaultHttpClient(ccm, base.getParams());
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();

            if (useProxy) {
                HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT_HTTP);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }/*from   w  ww.j  a  v a2  s  .c  om*/

            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            CustomMultiPartEntity entity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                    new ProgressListener() {
                        int lastPercent = 0;

                        @Override
                        public void transferred(long num) {

                            percentUploaded = (int) (((float) num) / ((float) totalLength) * 99f);
                            //Log.d(TAG, "percent uploaded: " + percentUploaded + " - " + num + " / " + totalLength);
                            if (lastPercent != percentUploaded) {
                                ((SSCXferActivity) activity).showProgress("uploading...", percentUploaded);
                                lastPercent = percentUploaded;
                            }
                        }

                    });

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            totalLength = entity.getContentLength();

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((SSCXferActivity) activity).finishedUploading(false);

                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            Log.d(TAG, " video bin got back " + response);

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(true);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

From source file:dev.memento.MementoBrowser.java

/**
 * Make http requests using the Memento protocol to obtain a Memento or list
 * of Mementos. /*from   ww w. j  a va2s .com*/
 */
private void makeHttpRequests(String initUrl) {

    // Contact Memento proxy with chosen Accept-Datetime:
    // http://mementoproxy.lanl.gov/aggr/timegate/http://example.com/
    // Accept-Datetime: Tue, 24 Jul 2001 15:45:04 GMT             

    HttpClient httpclient = new DefaultHttpClient();

    // Disable automatic redirect handling so we can process the 302 ourself 
    httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);

    String url = mDefaultTimegateUri + initUrl;
    HttpGet httpget = new HttpGet(url);

    // Change the request date to 23:00:00 if this is the first memento.
    // Otherwise we'll be out of range.

    String acceptDatetime;

    if (mFirstMemento != null && mFirstMemento.getDateTime().equals(mDateChosen)) {
        Log.d(LOG_TAG, "Changing chosen time to 23:59 since datetime matches first Memento.");
        SimpleDateTime dt = new SimpleDateTime(mDateChosen);
        dt.setToLastHour();
        acceptDatetime = dt.longDateFormatted();
    } else {
        acceptDatetime = mDateChosen.longDateFormatted();
    }

    httpget.setHeader("Accept-Datetime", acceptDatetime);
    httpget.setHeader("User-Agent", mUserAgent);

    //Log.d(LOG_TAG, getHeadersAsString(response.getAllHeaders()));

    Log.d(LOG_TAG, "Accessing: " + httpget.getURI());
    Log.d(LOG_TAG, "Accept-Datetime: " + acceptDatetime);

    HttpResponse response = null;
    try {
        response = httpclient.execute(httpget);

        Log.d(LOG_TAG, "Response code = " + response.getStatusLine());

        //Log.d(LOG_TAG, getHeadersAsString(response.getAllHeaders()));
    } catch (ClientProtocolException e) {
        mErrorMessage = "Unable to contact proxy server. ClientProtocolException exception.";
        Log.e(LOG_TAG, getExceptionStackTraceAsString(e));
        return;
    } catch (IOException e) {
        mErrorMessage = "Unable to contact proxy server. IOException exception.";
        Log.e(LOG_TAG, getExceptionStackTraceAsString(e));
        return;
    } finally {
        // Deallocate all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // Get back:
    // 300 (TCN: list with multiple Mementos to choose from)
    // or 302 (TCN: choice) 
    // or 404 (no Mementos for this URL)
    // or 406 (TCN: list with only first and last Mementos)

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 300) {
        // TODO: Implement.  Right now the lanl proxy doesn't appear to be returning this
        // code, so let's just ignore it for now.
        Log.d(LOG_TAG, "Pick a URL from list");
    } else if (statusCode == 302) {
        // Send browser to Location URL
        // Note that the date/time of this memento is not given in the Location.

        Header[] headers = response.getHeaders("Location");
        if (headers.length == 0) {
            mErrorMessage = "Sorry, but there was an unexpected error that will "
                    + "prevent the Memento from being displayed. Try again in 5 minutes.";
            Log.e(LOG_TAG, "Error: Location header not found in response headers.");
        } else {
            String redirectUrl = headers[0].getValue();

            // Find out the datetime of this resource
            /*SimpleDateTime d = getResourceDatetime(redirectUrl);
            if (d != null)
               mDateDisplayed = d;
               */

            Log.d(LOG_TAG, "Sending browser to " + redirectUrl);
            mWebview.loadUrl(redirectUrl);

            // We can't update the view directly since we're running
            // in a thread, so use mUpdateResults to show a toast message
            // if accessing a different date than what was requested.

            //mHandler.post(mUpdateResults);

            // Parse various Links
            headers = response.getHeaders("Link");
            if (headers.length == 0) {
                Log.e(LOG_TAG, "Error: Link header not found in response headers.");
                mErrorMessage = "Sorry, but the Memento could not be accessed. Try again in 5 minutes.";
            } else {
                String linkValue = headers[0].getValue();

                mTimeMap = null;
                mTimeBundle = null;

                // Get the datetime of this mememnto which should be supplied in the
                // Link: headers
                mDateDisplayed = parseCsvLinks(linkValue);

                // Now that we know the date, update the UI to reflect it
                mHandler.post(mUpdateResults);

                if (mTimeMap != null)
                    if (!accessTimeMap())
                        mErrorMessage = "There were problems accessing the Memento's TimeMap.";
            }
        }
    } else if (statusCode == 404) {
        mErrorMessage = "Sorry, but there are no Mementos for this URL.";
    } else if (statusCode == 406) {

        // Parse various Links
        Header[] headers = response.getHeaders("Link");

        if (headers.length == 0) {
            Log.d(LOG_TAG, "Error: Link header not found in 406 response headers.");
            //mErrorMessage = "Sorry, but there was an error in retreiving this Memento.";

            // The lanl proxy has it wrong.  It should return 404 when the URL is not
            // present, so we'll just pretend this is a 404.
            mErrorMessage = "Sorry, but there are no Mementos for this URL.";

            //Log.d(LOG_TAG, "BODY: " + EntityUtils.toString(response.getEntity());                     
        } else {
            String linkValue = headers[0].getValue();

            mTimeMap = null;
            mTimeBundle = null;

            parseCsvLinks(linkValue);

            if (mTimeMap != null)
                accessTimeMap();

            if (mFirstMemento == null || mLastMemento == null) {
                Log.e(LOG_TAG, "Could not find first or last Memento in 406 response for " + url);
                mErrorMessage = "Sorry, but there was an error in retreiving this Memento.";
            } else {
                Log.d(LOG_TAG, "Not available in this date range (" + mFirstMemento.getDateTimeSimple() + " to "
                        + mLastMemento.getDateTimeSimple() + ")");

                // According to Rob Sanderson (LANL), we will only get 406 when the date is too
                // early, so redirect to first Memento

                mDateDisplayed = new SimpleDateTime(mFirstMemento.getDateTime());
                String redirectUrl = mFirstMemento.getUrl();
                Log.d(LOG_TAG, "Sending browser to " + redirectUrl);
                mWebview.loadUrl(redirectUrl);

                mHandler.post(mUpdateResults);
            }
        }
    } else {
        mErrorMessage = "Sorry, but there was an unexpected error that will "
                + "prevent the Memento from being displayed. Try again in 5 minutes.";
        Log.e(LOG_TAG, "Unexpected response code in makeHttpRequests = " + statusCode);
    }
}

From source file:wsattacker.plugin.dos.dosExtension.requestSender.RequestSenderImpl.java

private String sendRequestHttpClient(RequestObject requestObject) {

    // get Post Request
    HttpPost post = this.createHttpPostMethod(requestObject);

    // set afterReceive to default value to handle missing responses
    afterReceive = 0;/*from  w w w .ja va  2s  .c om*/

    // Get HTTP client and execute request
    try {
        URL url = new URL(requestObject.getEndpoint());
        String protocol = url.getProtocol();

        HttpClient httpClient;
        if (protocol.equalsIgnoreCase("https")) {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String string)
                        throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String string)
                        throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);

            SSLSocketFactory sf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme httpsScheme = new Scheme("https", url.getPort(), sf);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(httpsScheme);

            // apache HttpClient version >4.2 should use
            // BasicClientConnectionManager
            ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);

            httpClient = new DefaultHttpClient(cm);
        } else {
            httpClient = new DefaultHttpClient();
        }

        httpClient.getParams().setParameter("http.socket.timeout", TIMEOUT);
        httpClient.getParams().setParameter("http.connection.timeout", TIMEOUT);
        httpClient.getParams().setParameter("http.connection-manager.max-per-host", TIMEOUT);
        httpClient.getParams().setParameter("http.connection-manager.max-total", new Integer(3000));
        // > params.setDefaultMaxConnectionsPerHost(3000);
        // > params.setMaxTotalConnections(3000);

        beforeSend = System.nanoTime();

        HttpResponse response = httpClient.execute(post);
        StringWriter writer = new StringWriter();
        IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8");
        responseString = writer.toString();

        afterReceive = System.nanoTime();
        // System.out.println("Response status code: " + result);
        // System.out.println("Response body: " + responseString);
    } catch (IOException ex) {
        // Logger.getLogger(RequestSender.class.getName()).log(Level.SEVERE,
        // null, ex);
        System.out.println("--RequestSender - IO Exception: " + ex.getMessage());

        // ex.printStackTrace();
    } catch (Exception e) {
        // Request timed out!?
        System.out.println("--RequestSender - unexpected Exception: " + e.getMessage());
    } finally {
        // Release current connection to the connection pool
        // post.releaseConnection();

        if (responseString == null) {
            responseString = "";
        }

        // Set afterReceive to beforeSend if afterReceive is 0 so that there 
        // is no huge negative response time when the web service doesn't answer
        if (afterReceive == 0) {
            afterReceive = beforeSend;
        }
    }

    return responseString;
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_VB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;/*from  ww w .j  a  va 2  s  . co m*/
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            // CHECK RESPONSE FOR SUCCESS!!
            if (!failed && response != null
                    && response.matches(res.getString(R.string.video_bin_API_good_re))) {
                // We got back HTTP response with valid URL
                Log.d(TAG, " video bin got back URL " + response);

            } else {
                Log.d(TAG, " video bin got eror back:\n" + response);
                failed = true;
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);

                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(true);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}