org.apache.http.impl.conn.SingleClientConnManager Java Examples

The following examples show how to use org.apache.http.impl.conn.SingleClientConnManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpAndroidClientFactory.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public HttpClient createHttpClient(ClientConfiguration clientconfiguration)
{
    BasicHttpParams basichttpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(basichttpparams, clientconfiguration.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(basichttpparams, clientconfiguration.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(basichttpparams, true);
    HttpConnectionParams.setTcpNoDelay(basichttpparams, true);
    int i = clientconfiguration.getSocketBufferSizeHints()[0];
    int j = clientconfiguration.getSocketBufferSizeHints()[1];
    if (i > 0 || j > 0)
    {
        HttpConnectionParams.setSocketBufferSize(basichttpparams, Math.max(i, j));
    }
    SchemeRegistry schemeregistry = new SchemeRegistry();
    schemeregistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (clientconfiguration.getProtocol() == Protocol.HTTPS)
    {
        schemeregistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }
    return new DefaultHttpClient(new SingleClientConnManager(basichttpparams, schemeregistry), basichttpparams);
}
 
Example #2
Source File: Curl.java    From UAF with Apache License 2.0 5 votes vote down vote up
private static HttpClient createHttpsClient() {
	HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
	SchemeRegistry registry = new SchemeRegistry();
	SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
	socketFactory
			.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
	registry.register(new Scheme("https", socketFactory, 443));
	HttpClient client = new DefaultHttpClient();
	SingleClientConnManager mgr = new SingleClientConnManager(
			client.getParams(), registry);
	DefaultHttpClient httpClient = new DefaultHttpClient(mgr,
			client.getParams());
	return httpClient;
}
 
Example #3
Source File: HttpClientFactory.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * HTTPClientオブジェクトを作成.
 * @param type 通信タイプ
 * @return 作成したHttpClientクラスインスタンス
 */
public static HttpClient create(final String type) {
    if (TYPE_DEFAULT.equalsIgnoreCase(type)) {
        return new DefaultHttpClient();
    }

    SSLSocketFactory sf = null;
    try {
        if (TYPE_INSECURE.equalsIgnoreCase(type)) {
            sf = createInsecureSSLSocketFactory();
        }
    } catch (Exception e) {
        return null;
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", PORTHTTPS, sf));
    schemeRegistry.register(new Scheme("http", PORTHTTP, PlainSocketFactory.getSocketFactory()));
    HttpParams params = new BasicHttpParams();
    ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
    // ClientConnectionManager cm = new
    // ThreadSafeClientConnManager(schemeRegistry);
    HttpClient hc = new DefaultHttpClient(cm, params);

    HttpParams params2 = hc.getParams();
    int timeout = TIMEOUT;
    HttpConnectionParams.setConnectionTimeout(params2, timeout); // 接続のタイムアウト
    HttpConnectionParams.setSoTimeout(params2, timeout); // データ取得のタイムアウト
    return hc;
}
 
Example #4
Source File: HttpClientFactory.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * HTTPClientオブジェクトを作成.
 * @param type 通信タイプ
 * @param connectionTimeout タイムアウト値(ミリ秒)。0の場合はデフォルト値を利用する。
 * @return 作成したHttpClientクラスインスタンス
 */
public static HttpClient create(final String type, final int connectionTimeout) {
    if (TYPE_DEFAULT.equalsIgnoreCase(type)) {
        return new DefaultHttpClient();
    }

    SSLSocketFactory sf = null;
    try {
        if (TYPE_INSECURE.equalsIgnoreCase(type)) {
            sf = createInsecureSSLSocketFactory();
        }
    } catch (Exception e) {
        return null;
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", PORTHTTPS, sf));
    schemeRegistry.register(new Scheme("http", PORTHTTP, PlainSocketFactory.getSocketFactory()));
    HttpParams params = new BasicHttpParams();
    ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
    // ClientConnectionManager cm = new
    // ThreadSafeClientConnManager(schemeRegistry);
    HttpClient hc = new DefaultHttpClient(cm, params);

    HttpParams params2 = hc.getParams();
    int timeout = TIMEOUT;
    if (connectionTimeout != 0) {
        timeout = connectionTimeout;
    }
    HttpConnectionParams.setConnectionTimeout(params2, timeout); // 接続のタイムアウト
    HttpConnectionParams.setSoTimeout(params2, timeout); // データ取得のタイムアウト
    return hc;
}
 
Example #5
Source File: MyHttpClient.java    From vocefiscal-android with Apache License 2.0 5 votes vote down vote up
@Override
protected ClientConnectionManager createClientConnectionManager() 
{
	SchemeRegistry registry = new SchemeRegistry();
	registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
	// Register for port 443 our SSLSocketFactory with our keystore
	// to the ConnectionManager
	//TODO registry.register(new Scheme("https", newSslSocketFactory(), 443));
	return new SingleClientConnManager(getParams(), registry);
}
 
Example #6
Source File: DispatchHttpClient.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(
            new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", newSslSocketFactory(), 443));
    return new SingleClientConnManager(getParams(), registry);
}
 
Example #7
Source File: BuddycloudHTTPHelper.java    From buddycloud-android with Apache License 2.0 5 votes vote down vote up
public static HttpClient createSecureHttpClient() {
	try {
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("https", createSecureSocketFactory(),
				443));
		ClientConnectionManager ccm = new SingleClientConnManager(
				new DefaultHttpClient().getParams(), registry);
		return new DefaultHttpClient(ccm, null);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #8
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void login() throws EndpointNotFoundException, UnauthorizedException, UnexpectedStatusCodeException,
        IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    try {
        HttpPost request = new HttpPost(authUrl);

        String body = String
                .format("{\"auth\": {\"passwordCredentials\": {\"username\": \"%s\", \"password\": \"%s\"}, \"tenantName\":\"%s\"}}",
                user, password, tenant);
        StringEntity entity = new StringEntity(body);
        entity.setContentType("application/json");
        request.setEntity(entity);
        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

        String responseBody = swiftResponse.getResponseBodyAsString();

        Gson gson = new Gson();
        LoginResponseObject loginResponse = gson.fromJson(responseBody, LoginResponseObject.class);

        this.authToken = loginResponse.getAccess().getToken().getId();

        Boolean endpointFound = false;

        for (ServiceObject service : loginResponse.getAccess().getServiceCatalog()) {

            if (service.getType().equals("object-store")) {
                this.storageUrl = service.getEndpoints().get(0).getPublicURL();
                endpointFound = true;
                break;
            }
        }

        // get the token issue swift date
        DateTimeZone.setDefault(DateTimeZone.UTC);
        DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
        DateTime issuedAt = dateStringFormat.parseDateTime(loginResponse.getAccess().getToken().getIssuedAt());

        // get the token expiration swift date
        dateStringFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
        DateTime expiresAt = dateStringFormat.parseDateTime(loginResponse.getAccess().getToken().getExpires());

        // calculate the period between these two dates and add it to our
        // current time because datetime can differ from Swift and this
        // device
        Period period = new Period(issuedAt, expiresAt);
        expirationDate = DateTime.now().plus(period);

        if (!endpointFound) {
            throw new EndpointNotFoundException();
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example #9
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void createNewWorkspace(Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }



    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example #10
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void removeUserToWorkspace(User owner, User user, Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    String permissions = getWorkspacePermissions(owner, workspace);

    String tenantUser = Config.getSwiftTenant() + ":" + user.getSwiftUser();

    if (permissions.contains("," + tenantUser)) {
        permissions.replace("," + tenantUser, "");
    } else if (permissions.contains(tenantUser)) {
        permissions.replace(tenantUser, "");
    } else {
        return;
    }

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);
    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_CONTAINER_READ, permissions);
        request.setHeader(SwiftResponse.X_CONTAINER_WRITE, permissions);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example #11
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void grantUserToWorkspace(User owner, User user, Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    String permissions = getWorkspacePermissions(owner, workspace);

    String tenantUser = Config.getSwiftTenant() + ":" + user.getSwiftUser();

    if (permissions.contains(tenantUser)) {
        return;
    }

    permissions += "," + tenantUser;

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);
    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_CONTAINER_READ, permissions);
        request.setHeader(SwiftResponse.X_CONTAINER_WRITE, permissions);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example #12
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void copyChunk(Workspace sourceWorkspace, Workspace destinationWorkspace, String chunkName) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    chunkName = "chk-" + chunkName;

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    String url = this.storageUrl + "/" + destinationWorkspace.getSwiftContainer() + "/"
            + chunkName;

    String copyFrom = "/" + sourceWorkspace.getSwiftContainer() + "/" + chunkName;

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_COPY_FROM, copyFrom);
        //request.setHeader("Content-Length", "0");                        

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new ObjectNotFoundException("404 Not Found");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example #13
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void deleteWorkspace(Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpDelete request = new HttpDelete(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example #14
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
private String getWorkspacePermissions(User user, Workspace workspace) throws Exception {

        if (!isTokenActive()) {
            login();
        }

        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] certificate, String authType) {
                return true;
            }
        };

        SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 5000, sf));
        ClientConnectionManager ccm = new SingleClientConnManager(registry);

        HttpClient httpClient = new DefaultHttpClient(ccm);

        String url = this.storageUrl + "/" + workspace.getSwiftContainer();

        try {

            HttpHead request = new HttpHead(url);
            request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

            HttpResponse response = httpClient.execute(request);

            SwiftResponse swiftResponse = new SwiftResponse(response);

            if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                throw new UnauthorizedException("404 User unauthorized");
            }

            if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
                throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
            }

            // We suppose there are the same permissions for read and write
            Header containerWriteHeader = swiftResponse.getResponseHeader(SwiftResponse.X_CONTAINER_WRITE);

            if (containerWriteHeader == null) {
                return "";
            }

            return containerWriteHeader.getValue();

        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }