Example usage for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE

List of usage examples for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE

Introduction

In this page you can find the example usage for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE.

Prototype

String USE_EXPECT_CONTINUE

To view the source code for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE.

Click Source Link

Usage

From source file:com.github.lpezet.antiope.dao.DefaultHttpRequestFactory.java

@Override
public HttpRequestBase createHttpRequest(Request<?> pRequest, APIConfiguration pConfiguration,
        HttpContext pHttpContext, ExecutionContext pExecutionContext) {
    // Signing request is any signer.
    if (pExecutionContext.getSigner() != null && pExecutionContext.getCredentials() != null) {
        pExecutionContext.getMetrics().startEvent(APIRequestMetrics.RequestSigningTime);
        try {/*  w  w w.ja  v a  2s  . c  o  m*/
            pExecutionContext.getSigner().sign(pRequest, pExecutionContext.getCredentials());
        } finally {
            pExecutionContext.getMetrics().endEvent(APIRequestMetrics.RequestSigningTime);
        }
    }

    URI oEndpoint = pRequest.getEndpoint();
    /*
     * HttpClient cannot handle url in pattern of "http://host//path", so we
     * have to escape the double-slash between endpoint and resource-path
     * into "/%2F"
     */
    String oUri = HttpUtils.appendUri(oEndpoint.toString(), pRequest.getResourcePath(), true);
    String oEncodedParams = HttpUtils.encodeParameters(pRequest);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean oRequestHasNoPayload = pRequest.getContent() == null;
    boolean oRequestIsPost = pRequest.getHttpMethod() == HttpMethodName.POST;
    boolean oPutParamsInUri = !oRequestIsPost || oRequestHasNoPayload;
    if (oEncodedParams != null && oPutParamsInUri) {
        oUri += QMARK + oEncodedParams;
    }

    HttpRequestBase oHttpRequest;
    if (pRequest.getHttpMethod() == HttpMethodName.POST) {
        HttpPost oPostMethod = new HttpPost(oUri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all API Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (pRequest.getContent() == null && oEncodedParams != null) {
            oPostMethod.setEntity(newStringEntity(oEncodedParams));
        } else if (pRequest.getContent() != null) {
            oPostMethod.setEntity(new RepeatableInputStreamRequestEntity(pRequest));
        }
        oHttpRequest = oPostMethod;
    } else if (pRequest.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(oUri);

        /*
         * Enable 100-continue support for PUT operations, since this is
         * where we're potentially uploading large amounts of data and want
         * to find out as early as possible if an operation will fail. We
         * don't want to do this for all operations since it will cause
         * extra latency in the network interaction.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        //if (pPreviousEntity != null) {
        //   putMethod.setEntity(pPreviousEntity);
        //} else 
        if (pRequest.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(pRequest);
            if (pRequest.getHeaders().get(CONTENT_LENGTH) == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }

        oHttpRequest = putMethod;
    } else if (pRequest.getHttpMethod() == HttpMethodName.GET) {
        oHttpRequest = new HttpGet(oUri);
    } else if (pRequest.getHttpMethod() == HttpMethodName.DELETE) {
        oHttpRequest = new HttpDelete(oUri);
    } else if (pRequest.getHttpMethod() == HttpMethodName.HEAD) {
        oHttpRequest = new HttpHead(oUri);
    } else {
        throw new APIClientException("Unknown HTTP method name: " + pRequest.getHttpMethod());
    }

    configureHeaders(oHttpRequest, pRequest, pExecutionContext, pConfiguration);

    return oHttpRequest;
}

From source file:org.hk.jt.client.core.Request.java

private HttpResponse execPost() throws URISyntaxException, InvalidKeyException, UnsupportedEncodingException,
        NoSuchAlgorithmException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
    HttpPost httpPost = new HttpPost();
    httpPost.setURI(new URI(requestIf.getUrl()));
    httpPost.setHeader("Authorization", createAuthorizationValue());

    if (postParameter != null && !postParameter.isEmpty()) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : postParameter.keySet()) {
            params.add(new BasicNameValuePair(key, postParameter.get(key)));
        }/*from  w  ww  .ja  v a2s.  c o m*/
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    }

    if (requestIf.getFiles() != null) {
        final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        List<NameValuePair> fileList = requestIf.getFiles();
        if (fileList != null && !fileList.isEmpty()) {
            for (NameValuePair val : fileList) {
                File file = new File(val.getValue());
                entity.addPart(val.getName(), new FileBody(file, CONTENTTYPE_BINARY));
            }
        }
        httpPost.setEntity(entity);
    }
    httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    return client.execute(httpPost);
}

From source file:org.sonatype.nexus.testsuite.deploy.nexus176.Nexus176DeployToInvalidRepoIT.java

@Test
public void wagonSnapshotDeployTest() throws Exception {

    Gav gav = new Gav(this.getTestId(), "simpleArtifact", "1.0.0-SNAPSHOT", null, "xml", 0,
            new Date().getTime(), "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    // the method we are calling
    HttpPost filePost = new HttpPost(uploadURL);
    filePost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

    int status = getDeployUtils().deployUsingGavWithRest(uploadURL, TEST_RELEASE_REPO, gav, fileToDeploy);

    if (status != HttpStatus.SC_NOT_FOUND) {
        Assert.fail("Upload attempt should have returned a 400, it returned:  " + status);
    }// w  ww  .  j av a 2 s . c om

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);

}

From source file:kriswuollett.sandbox.twitter.api.streaming.gson.GsonTwitterStreamingRequest.java

@Override
public TwitterStreamingResponse call() throws Exception {
    if (listener == null)
        throw new IllegalStateException("The listener was null");

    final InputStream in;

    if (inputStream == null) {
        if (consumer == null)
            throw new IllegalStateException("The consumer was null");

        if (track == null)
            throw new IllegalStateException("The track was null");

        final HttpPost post = new HttpPost("https://stream.twitter.com/1/statuses/filter.json");

        final List<NameValuePair> nvps = new LinkedList<NameValuePair>();

        // nvps.add( new BasicNameValuePair( "track", "twitter" ) );
        // nvps.add( new BasicNameValuePair( "locations", "-74,40,-73,41" ) );
        //nvps.add( new BasicNameValuePair( "track", "'nyc','ny','new york','new york city'" ) );
        nvps.add(new BasicNameValuePair("track", track));
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        consumer.sign(post);// www . ja  v a2s  .  c  o  m

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpResponse response = httpClient.execute(post);

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK)
            return new Response(false, response.getStatusLine().getReasonPhrase());

        in = response.getEntity().getContent();
    } else {
        if (consumer != null)
            throw new IllegalStateException("The consumer parameter cannot be used with inputStream");

        if (track != null)
            throw new IllegalStateException("The track parameter cannot be used with inputStream");

        in = inputStream;
    }

    reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    reader.setLenient(true);

    try {
        stack1.clear();

        ParseState state = new ParseState(State.BEGIN, null, null);

        stack1.push(state);

        while (true) {
            final JsonToken token = reader.peek();

            switch (token) {
            case BEGIN_ARRAY:
                reader.beginArray();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sBEGIN_ARRAY STATE=%s STACK_SIZE=%d", padding(stack1.size()),
                            state, stack1.size()));
                onBeginArray();
                break;
            case END_ARRAY:
                reader.endArray();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sEND_ARRAY STATE=%s STACK_SIZE=%d", padding(stack1.size()),
                            state, stack1.size()));
                onEndArray();
                break;
            case BEGIN_OBJECT:
                reader.beginObject();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sBEGIN_OBJECT STATE=%s STACK_SIZE=%d", padding(stack1.size()),
                            state, stack1.size()));
                onBeginObject();
                break;
            case END_OBJECT:
                reader.endObject();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sEND_OBJECT STATE=%s STACK_SIZE=%d", padding(stack1.size()),
                            state, stack1.size()));
                onEndObject();
                break;
            case NAME:
                String name = reader.nextName();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sNAME - %s", padding(stack1.size()), name));
                onName(name);
                break;
            case STRING:
                String s = reader.nextString();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sSTRING - %s", padding(stack1.size()), s));
                onString(s);
                break;
            case NUMBER:
                String n = reader.nextString();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sNUMBER - %s", padding(stack1.size()), n));
                onNumber(n);
                break;
            case BOOLEAN:
                boolean b = reader.nextBoolean();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sBOOLEAN - %b", padding(stack1.size()), b));
                onBoolean(b);
                break;
            case NULL:
                reader.nextNull();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sNULL", padding(stack1.size())));
                onNull();
                break;
            case END_DOCUMENT:
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sEND_DOCUMENT", padding(stack1.size())));
                return new Response(true, "OK");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

@Override
public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException {
    final HostAddressResolver resolver = FactoryUtils.getHostAddressResolver(conf);
    final String urlString = req.getURL();
    final URI urlOrig = ParseUtils.parseURI(urlString);
    final String host = urlOrig.getHost(), authority = urlOrig.getAuthority();
    try {//w w w . j a va  2 s. com
        HttpRequestBaseHC4 commonsRequest;
        final String resolvedHost = resolver != null ? resolver.resolve(host) : null;
        final String resolvedUrl = !isEmpty(resolvedHost)
                ? urlString.replace("://" + host, "://" + resolvedHost)
                : urlString;
        final RequestMethod method = req.getMethod();
        if (method == RequestMethod.GET) {
            commonsRequest = new HttpGetHC4(resolvedUrl);
        } else if (method == RequestMethod.POST) {
            final HttpPostHC4 post = new HttpPostHC4(resolvedUrl);
            post.setEntity(getAsEntity(req.getParameters()));
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (method == RequestMethod.DELETE) {
            commonsRequest = new HttpDeleteHC4(resolvedUrl);
        } else if (method == RequestMethod.HEAD) {
            commonsRequest = new HttpHeadHC4(resolvedUrl);
        } else if (method == RequestMethod.PUT) {
            final HttpPutHC4 put = new HttpPutHC4(resolvedUrl);
            put.setEntity(getAsEntity(req.getParameters()));
            commonsRequest = put;
        } else
            throw new TwitterException("Unsupported request method " + method);
        final HttpParams httpParams = commonsRequest.getParams();
        HttpClientParams.setRedirecting(httpParams, false);
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        final Authorization authorization = req.getAuthorization();
        final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req)
                : null;
        if (authorizationHeader != null) {
            commonsRequest.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);
        }
        if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) {
            commonsRequest.addHeader(HttpHeaders.HOST, authority);
        }

        final ApacheHttpClientHttpResponseImpl res;
        try {
            final HttpContext httpContext = new BasicHttpContextHC4();
            httpContext.setAttribute(HostResolvedSSLConnectionSocketFactory.HTTP_CONTEXT_KEY_ORIGINAL_HOST,
                    host);
            res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest, httpContext), conf);
        } catch (final IllegalStateException e) {
            throw new TwitterException("Please check your API settings.", e);
        } catch (final NullPointerException e) {
            // Bug http://code.google.com/p/android/issues/detail?id=5255
            throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e);
        } catch (final OutOfMemoryError e) {
            // I don't know why OOM thown, but it should be catched.
            System.gc();
            throw new TwitterException("Unknown error", e);
        }
        final int statusCode = res.getStatusCode();
        if (statusCode < OK || statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), req, res);
        return res;
    } catch (final IOException e) {
        // TODO
        if (resolver instanceof TwidereHostAddressResolver) {
            final TwidereHostAddressResolver twidereResolver = (TwidereHostAddressResolver) resolver;
            twidereResolver.removeCachedHost(host);
        }
        throw new TwitterException(e);
    }
}

From source file:com.mfizz.observer.core.ServiceObserver.java

public ServiceObserver(ServiceObserverConfiguration serviceConfig, ExecutorService executor, Class<D> dataClass,
        Class<A> aggregateClass, Class<S> summaryClass, ContentParser<D> contentParser,
        ObserverNamingStrategy ons) {/* www  .j  ava 2  s  .  co m*/
    this.serviceConfig = serviceConfig;
    this.executor = executor;
    this.observers = new ConcurrentHashMap<String, Observer<D>>();
    this.dataClass = dataClass;
    this.aggregateClass = aggregateClass;
    this.summaryClass = summaryClass;
    this.contentParser = contentParser;
    if (ons == null) {
        this.ons = ObserverNamingStrategy.DEFAULT;
    } else {
        this.ons = ons;
    }
    this.snapshotAllTimer = Metrics.newTimer(
            new MetricName("com.mfizz.observer.ServiceObservers", serviceConfig.getName(), "snapshot-all-time"),
            TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS);
    this.snapshotAllAttemptedCounter = new AtomicLong();
    this.snapshotAllCompletedCounter = new AtomicLong();
    this.lastSnapshotAllResult = new AtomicReference<SnapshotAllResult>();

    //this.lastSnapshotAllTimestamp = new AtomicLong(0);
    //this.lastSnapshotsCompletedCounter = new AtomicInteger();
    //this.lastSnapshotsFailedCounter = new AtomicInteger();

    this.groups = new TreeSet<String>();
    this.summary = new ConcurrentHashMap<String, SummaryGroup<S>>();
    this.snapshots = new ConcurrentHashMap<String, TimeSeries<ObserveAggregateSnapshot<A>>>();

    // always make sure "current" is added to set of vars to track
    // "current" always tracked for all
    this.serviceConfig.getPeriods().add(SummaryPeriod.parse("current"));

    //
    // create high performance http client that can be reused by all observers
    //
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // increase max total connection to 200
    cm.setMaxTotal(200);
    // increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);

    this.httpclient = new DefaultHttpClient(cm);
    this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            // always return false -- we never want a request retried
            return false;
        }
    });
    this.httpclient.getParams()
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                    new Integer((int) serviceConfig.getSocketTimeout()))
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                    new Integer((int) serviceConfig.getConnectionTimeout()))
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
}

From source file:com.ichi2.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;/* w  w  w .  ja  v  a2s.co  m*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // compression flag and session key as post vars
        buf.write(bdry + "\r\n");
        buf.write("Content-Disposition: form-data; name=\"c\"\r\n\r\n" + (comp != 0 ? 1 : 0) + "\r\n");
        if (hkey) {
            buf.write(bdry + "\r\n");
            buf.write("Content-Disposition: form-data; name=\"k\"\r\n\r\n" + mHKey + "\r\n");
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersion());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:com.unboundid.scim.sdk.examples.ClientExample.java

/**
 * Create an SSL-enabled Wink client config from the provided information.
 * The returned client config may be used to create a SCIM service object.
 * IMPORTANT: This should not be used in production because no validation
 * is performed on the server certificate returned by the SCIM service.
 *
 * @param userName    The HTTP Basic Auth user name.
 * @param password    The HTTP Basic Auth password.
 *
 * @return  An Apache Wink client config.
 *///from   w  ww . j  a v a  2s .  c  o m
public static ClientConfig createHttpBasicClientConfig(final String userName, final String password) {
    SSLSocketFactory sslSocketFactory;
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLS");

        // Do not use these settings in production.
        sslContext.init(null, new TrustManager[] { new BlindTrustManager() }, new SecureRandom());
        sslSocketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e.getLocalizedMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getLocalizedMessage());
    }

    final HttpParams params = new BasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true);
    params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry);
    mgr.setMaxTotal(200);
    mgr.setDefaultMaxPerRoute(20);

    final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);

    final Credentials credentials = new UsernamePasswordCredentials(userName, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient);
    clientConfig.setBypassHostnameVerification(true);

    return clientConfig;
}

From source file:org.sonatype.nexus.testsuite.deploy.nexus176.Nexus176DeployToInvalidRepoIT.java

@Test
public void deploySnapshotWithGavUsingRest() throws Exception {

    Gav gav = new Gav(this.getTestId(), "uploadWithGav", "1.0.0-SNAPSHOT", null, "xml", 0, new Date().getTime(),
            "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    // the method we are calling
    HttpPost filePost = new HttpPost(uploadURL);
    filePost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

    int status = getDeployUtils().deployUsingGavWithRest(uploadURL, TEST_RELEASE_REPO, gav, fileToDeploy);

    if (status != HttpStatus.SC_NOT_FOUND) {
        Assert.fail("Upload attempt should have returned a 400, it returned:  " + status);
    }/*from  w  w w  .j a va2  s.c  om*/

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);

}

From source file:com.hichinaschool.flashcards.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;//  w ww . j  ava 2 s  .  c o m
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        HashMap<String, Object> vars = new HashMap<String, Object>();
        // compression flag and session key as post vars
        vars.put("c", comp != 0 ? 1 : 0);
        if (hkey) {
            vars.put("k", mHKey);
            vars.put("s", mSKey);
        }
        for (String key : vars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    vars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}