Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider.

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:com.lgallardo.youtorrentcontroller.JSONParser.java

public void postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String boundary = null;/*from www . ja  va  2s . c  o  m*/

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    //        Log.d("Debug", "JSONParser - command: " + command);

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = url + "gui/?action=start&hash=" + hash;
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = url + "gui/?action=pause&hash=" + hash;
    }

    if ("stop".equals(command) || "stopSelected".equals(command)) {
        url = url + "gui/?action=stop&hash=" + hash;
        Log.d("Debug", "Stoping torrent " + hash);
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {

        URI hash_uri = null;

        try {
            hash_uri = new URI(hash);
            hash = hash_uri.toString();

            //                Log.d("Debug","Torrent URL: "+ hash);

        } catch (URISyntaxException e) {
            Log.e("Debug", "URISyntaxException: " + e.toString());
        }

        url = url + "gui/?action=add-url&s=" + hash;
        //            key = "urls";
    }

    if ("addTorrentFile".equals(command)) {
        url = url + "gui/?action=add-file";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;
        //            urlContentType = "multipart/form-data";

    }

    //        if ("pauseall".equals(command)) {
    //            url = "command/pauseall";
    //        }
    //
    //        if ("pauseAll".equals(command)) {
    //            url = "command/pauseAll";
    //        }
    //
    //
    //        if ("resumeall".equals(command)) {
    //            url = "command/resumeall";
    //        }
    //
    //        if ("resumeAll".equals(command)) {
    //            url = "command/resumeAll";
    //        }

    if ("increasePrio".equals(command)) {
        url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("recheckSelected".equals(command)) {
        url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash=");
    }

    //        if ("toggleFirstLastPiecePrio".equals(command)) {
    //            url = "command/toggleFirstLastPiecePrio";
    //            key = "hashes";
    //
    //        }
    //
    //        if ("toggleSequentialDownload".equals(command)) {
    //            url = "command/toggleSequentialDownload";
    //            key = "hashes";
    //
    //        }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token;

        //            Log.d("Debug", "JSONParser - url: " + url);

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {
            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        // In order to pass the has we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // Set content type and urls
        if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);

        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            //                Log.d("Debug", "JSONParser - urlContentType: " +  urlContentType);
            //                Log.d("Debug", "JSONParser - hash: " +  Uri.decode(URLEncoder.encode(hash, "UTF-8")));
            //                Log.d("Debug", "JSONParser - hash: " +  hash);

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null);
            //                builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.lgallardo.qbittorrentclient.JSONParser.java

public String postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String limit = "";
    String tracker = "";

    String boundary = null;//  w  ww  . j  a v a2 s. c  om

    String fileId = "";

    String filePriority = "";

    String result = "";

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    String label = "";

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = "command/resume";
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = "command/pause";
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = "command/delete";
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = "command/deletePerm";
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {
        url = "command/download";
        key = "urls";
    }

    if ("addTracker".equals(command)) {
        url = "command/addTrackers";
        key = "hash";

    }

    if ("addTorrentFile".equals(command)) {
        url = "command/upload";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;

    }

    if ("pauseall".equals(command)) {
        url = "command/pauseall";
    }

    if ("pauseAll".equals(command)) {
        url = "command/pauseAll";
    }

    if ("resumeall".equals(command)) {
        url = "command/resumeall";
    }

    if ("resumeAll".equals(command)) {
        url = "command/resumeAll";
    }

    if ("increasePrio".equals(command)) {
        url = "command/increasePrio";
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = "command/decreasePrio";
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = "command/topPrio";
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = "command/bottomPrio";
        key = "hashes";

    }

    if ("setFilePrio".equals(command)) {
        url = "command/setFilePrio";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];
        fileId = tmpString[1];
        filePriority = tmpString[2];

        //            Log.d("Debug", "hash: " + hash);
        //            Log.d("Debug", "fileId: " + fileId);
        //            Log.d("Debug", "filePriority: " + filePriority);
    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("setUploadRateLimit".equals(command)) {

        url = "command/setTorrentsUpLimit";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            limit = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            limit = "-1";
        }
    }

    if ("setDownloadRateLimit".equals(command)) {
        url = "command/setTorrentsDlLimit";
        key = "hashes";

        Log.d("Debug", "Hash before: " + hash);

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            limit = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            limit = "-1";
        }

        //            Log.d("Debug", "url: " + url);
        //            Log.d("Debug", "Hashes: " + hash + " | limit: " + limit);

    }

    if ("recheckSelected".equals(command)) {
        url = "command/recheck";
    }

    if ("toggleFirstLastPiecePrio".equals(command)) {
        url = "command/toggleFirstLastPiecePrio";
        key = "hashes";

    }

    if ("toggleSequentialDownload".equals(command)) {
        url = "command/toggleSequentialDownload";
        key = "hashes";

    }

    if ("toggleAlternativeSpeedLimits".equals(command)) {

        //            Log.d("Debug", "Toggling alternative rates");

        url = "command/toggleAlternativeSpeedLimits";
        key = "hashes";

    }

    if ("setLabel".equals(command)) {
        url = "command/setLabel";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            label = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            label = "";
        }

        //            Log.d("Debug", "Hash2: " + hash + "| label2: " + label);

    }

    if ("setCategory".equals(command)) {
        url = "command/setCategory";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            label = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            label = "";
        }

        //            Log.d("Debug", "Hash2: " + hash + "| label2: " + label);

    }

    if ("alternativeSpeedLimitsEnabled".equals(command)) {

        //            Log.d("Debug", "Getting alternativeSpeedLimitsEnabled");

        url = "command/alternativeSpeedLimitsEnabled";

        key = "hashes";
    }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {

            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        if ("addTracker".equals(command)) {

            String[] tmpString = hash.split("&");
            hash = tmpString[0];

            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();

            try {
                tracker = tmpString[1];
            } catch (ArrayIndexOutOfBoundsException e) {
                tracker = "";
            }

            //                Log.d("Debug", "addTracker - hash: " + hash);
            //                Log.d("Debug", "addTracker - tracker: " + tracker);

        }

        // In order to pass the hash we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        // Add limit
        if (!limit.equals("")) {
            Log.d("Debug", "JSONParser - Limit: " + limit);
            nvps.add(new BasicNameValuePair("limit", limit));
        }

        // Set values for setting file priority
        if ("setFilePrio".equals(command)) {

            nvps.add(new BasicNameValuePair("id", fileId));
            nvps.add(new BasicNameValuePair("priority", filePriority));
        }

        // Add label
        if (label != null && !label.equals("")) {

            label = Uri.decode(label);

            if ("setLabel".equals(command)) {

                nvps.add(new BasicNameValuePair("label", label));
            } else {

                nvps.add(new BasicNameValuePair("category", label));
            }

            //                Log.d("Debug", "Hash3: " + hash + "| label3: >" + label + "<");
        }

        // Add tracker
        if (tracker != null && !tracker.equals("")) {

            nvps.add(new BasicNameValuePair("urls", tracker));

            //                Log.d("Debug", ">Tracker: " + key + " | " + hash + " | " + tracker + "<");

        }

        String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8);

        // This replaces encoded char "+" for "%20" so spaces can be passed as parameter
        entityValue = entityValue.replaceAll("\\+", "%20");

        StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
        stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);

        httpget.setEntity(stringEntity);

        // Set content type and urls
        if ("addTorrent".equals(command) || "increasePrio".equals(command) || "decreasePrio".equals(command)
                || "maxPrio".equals(command) || "setFilePrio".equals(command)
                || "toggleAlternativeSpeedLimits".equals(command)
                || "alternativeSpeedLimitsEnabled".equals(command) || "setLabel".equals(command)
                || "setCategory".equals(command) || "addTracker".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);
        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        //            Log.d("Debug", "JSONPArser - mStatusCode: " + mStatusCode);

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        result = EntityUtils.toString(httpEntity);

        //            Log.d("Debug", "JSONPArser - command result: " + result);

        return result;

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (SSLPeerUnverifiedException e) {
        Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString());
        throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE);
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return null;

}

From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java

public String oozieSubmitJob(String user, String password, String request, int status)
        throws IOException, URISyntaxException {
    getMock("OOZIE").expect().method("POST").pathInfo("/v1/jobs").respond().status(HttpStatus.SC_CREATED)
            .content(getResourceBytes("oozie-jobs-submit-response.json")).contentType("application/json");
    //System.out.println( "REQUEST LENGTH = " + request.length() );

    URL url = new URL(getUrl("OOZIE") + "/v1/jobs?action=start" + (isUseGateway() ? "" : "&user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(user, password));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost(url.toURI());
    //    post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity(request, ContentType.create("application/xml", "UTF-8"));
    post.setEntity(entity);//  www . j  av  a 2  s .com
    post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds");
    HttpResponse response = client.execute(targetHost, post, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());

    //    String json = given()
    //        .log().all()
    //        .auth().preemptive().basic( user, password )
    //        .queryParam( "action", "start" )
    //        .contentType( "application/xml;charset=UTF-8" )
    //        .content( request )
    //        .expect()
    //        .log().all()
    //        .statusCode( status )
    //        .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
    //System.out.println( "JSON=" + json );
    String id = from(json).getString("id");
    return id;
}

From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java

public String oozieQueryJobStatus(String user, String password, String id, int status) throws Exception {
    getMock("OOZIE").expect().method("GET").pathInfo("/v1/job/" + id).respond().status(HttpStatus.SC_OK)
            .content(getResourceBytes("oozie-job-show-info.json")).contentType("application/json");

    //NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
    URL url = new URL(getUrl("OOZIE") + "/v1/job/" + id + (isUseGateway() ? "" : "?user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(user, password));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet request = new HttpGet(url.toURI());
    request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
    HttpResponse response = client.execute(targetHost, request, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());
    String jobStatus = from(json).getString("status");
    return jobStatus;
}

From source file:org.apache.hive.ptest.execution.JIRAService.java

void publishComments(String comments) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {//from w ww  . ja v  a2  s . c  o  m
        String url = String.format("%s/rest/api/2/issue/%s/comment", mUrl, mName);
        URL apiURL = new URL(mUrl);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(apiURL.getHost(), apiURL.getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(mUser, mPassword));
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute("preemptive-auth", new BasicScheme());
        httpClient.addRequestInterceptor(new PreemptiveAuth(), 0);
        HttpPost request = new HttpPost(url);
        ObjectMapper mapper = new ObjectMapper();
        StringEntity params = new StringEntity(mapper.writeValueAsString(new Body(comments)));
        request.addHeader("Content-Type", "application/json");
        request.setEntity(params);
        HttpResponse httpResponse = httpClient.execute(request, localcontext);
        StatusLine statusLine = httpResponse.getStatusLine();
        if (statusLine.getStatusCode() != 201) {
            throw new RuntimeException(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        }
        mLogger.info("JIRA Response Metadata: " + httpResponse);
    } catch (Exception e) {
        mLogger.error("Encountered error attempting to post comment to " + mName, e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.eobjects.datacleaner.user.UserPreferencesImpl.java

@Override
public HttpClient createHttpClient() {
    final ClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

    if (isProxyEnabled()) {
        // set up HTTP proxy
        final String proxyHostname = getProxyHostname();
        final int proxyPort = getProxyPort();

        try {//from ww w  .  ja v a2 s  .c  o  m
            final HttpHost proxy = new HttpHost(proxyHostname, proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (isProxyAuthenticationEnabled()) {
                final AuthScope authScope = new AuthScope(proxyHostname, proxyPort);
                final String proxyUsername = getProxyUsername();
                final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername,
                        getProxyPassword());
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);

                final int backslashIndex = proxyUsername.lastIndexOf('\\');
                final String ntUsername;
                final String ntDomain;
                if (backslashIndex != -1) {
                    ntUsername = proxyUsername.substring(backslashIndex + 1);
                    ntDomain = proxyUsername.substring(0, backslashIndex);
                } else {
                    ntUsername = proxyUsername;
                    ntDomain = System.getProperty("datacleaner.proxy.domain");
                }

                String workstation = System.getProperty("datacleaner.proxy.workstation");
                if (Strings.isNullOrEmpty(workstation)) {
                    String computername = InetAddress.getLocalHost().getHostName();
                    workstation = computername;
                }

                NTCredentials ntCredentials = new NTCredentials(ntUsername, getProxyPassword(), workstation,
                        ntDomain);
                AuthScope ntAuthScope = new AuthScope(proxyHostname, proxyPort, AuthScope.ANY_REALM, "ntlm");
                httpClient.getCredentialsProvider().setCredentials(ntAuthScope, ntCredentials);
            }
        } catch (Exception e) {
            // ignore proxy creation and return http client without it
            logger.error("Unexpected error occurred while initializing HTTP proxy", e);
        }
    }

    return httpClient;
}

From source file:org.eobjects.datacleaner.user.UserPreferencesImplTest.java

public void testCreateHttpClientWithoutNtCredentials() throws Exception {
    UserPreferencesImpl up = new UserPreferencesImpl(null);
    up.setProxyHostname("host");
    up.setProxyPort(1234);/*w w  w.j a  v a2s.c  o m*/
    up.setProxyUsername("bar");
    up.setProxyPassword("baz");
    up.setProxyEnabled(true);
    up.setProxyAuthenticationEnabled(true);

    DefaultHttpClient httpClient = (DefaultHttpClient) up.createHttpClient();

    String computername = InetAddress.getLocalHost().getHostName();
    assertNotNull(computername);
    assertTrue(computername.length() > 1);

    AuthScope authScope;
    Credentials credentials;

    authScope = new AuthScope("host", 1234, AuthScope.ANY_REALM, "ntlm");
    credentials = httpClient.getCredentialsProvider().getCredentials(authScope);
    assertEquals("[principal: bar][workstation: " + computername.toUpperCase() + "]", credentials.toString());

    authScope = new AuthScope("host", 1234);
    credentials = httpClient.getCredentialsProvider().getCredentials(authScope);
    assertEquals("[principal: bar]", credentials.toString());

    authScope = new AuthScope("anotherhost", AuthScope.ANY_PORT);
    credentials = httpClient.getCredentialsProvider().getCredentials(authScope);
    assertNull(credentials);
}

From source file:org.eobjects.datacleaner.user.UserPreferencesImplTest.java

public void testCreateHttpClientWithNtCredentials() throws Exception {
    UserPreferencesImpl up = new UserPreferencesImpl(null);
    up.setProxyHostname("host");
    up.setProxyPort(1234);//from  w w  w.ja va  2s. c  o  m
    up.setProxyUsername("FOO\\bar");
    up.setProxyPassword("baz");
    up.setProxyEnabled(true);
    up.setProxyAuthenticationEnabled(true);

    DefaultHttpClient httpClient = (DefaultHttpClient) up.createHttpClient();

    String computername = InetAddress.getLocalHost().getHostName();
    assertNotNull(computername);
    assertTrue(computername.length() > 1);

    AuthScope authScope;
    Credentials credentials;

    authScope = new AuthScope("host", 1234, AuthScope.ANY_REALM, "ntlm");
    credentials = httpClient.getCredentialsProvider().getCredentials(authScope);
    assertEquals("[principal: FOO/bar][workstation: " + computername.toUpperCase() + "]",
            credentials.toString());

    authScope = new AuthScope("host", 1234);
    credentials = httpClient.getCredentialsProvider().getCredentials(authScope);
    assertEquals("[principal: FOO\\bar]", credentials.toString());

    authScope = new AuthScope("anotherhost", AuthScope.ANY_PORT);
    credentials = httpClient.getCredentialsProvider().getCredentials(authScope);
    assertNull(credentials);
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private <T> T runMethod(HttpRequestBase method, String uri, ResponseHandler<T> responseHandler)
        throws IOException {
    String protocol = _isSecure ? "https" : "http";
    ServiceError error;/*from  w  w w.  ja va  2s.c o m*/
    URL url = new URL(protocol, _host, _port, uri);

    try {
        method.setURI(url.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("The syntax of request url [" + uri + "] is invalid", e);
    }

    _log.debug("Setting URI: " + url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (_isSecure) {
        // To allow for self signed certificates
        configureSSL(client);
    }

    // Validate user & password inputs
    if (_user == null || _user.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("User name cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    if (_password == null || _password.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("Password cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    // Set Basic auth creds
    UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(_user, _password);

    client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);

    // Preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost host = new HttpHost(_host, _port, protocol);

    authCache.put(host, basicAuth);

    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    method.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);

    // Disable re-tries
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, true));

    HttpResponse response = client.execute(method, localContext);

    return responseHandler.handleResponse(response);
}

From source file:org.rhq.maven.plugins.UploadMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skipUpload) {
        getLog().info("Skipped execution");
        return;/*from  w w  w. jav  a  2 s . com*/
    }
    File agentPluginArchive = getAgentPluginArchiveFile(buildDirectory, finalName);
    if (!agentPluginArchive.exists() && agentPluginArchive.isFile()) {
        throw new MojoExecutionException("Agent plugin archive does not exist: " + agentPluginArchive);
    }

    // Prepare HttpClient
    ClientConnectionManager httpConnectionManager = new BasicClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager);
    HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, socketConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, socketReadTimeout);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));

    HttpPost uploadContentRequest = null;
    HttpPut moveContentToPluginsDirRequest = null;
    HttpPost pluginScanRequest = null;
    HttpPost pluginDeployRequest = null;
    HttpGet pluginDeployCheckCompleteRequest = null;
    try {

        // Upload plugin content
        URI uploadContentUri = buildUploadContentUri();
        uploadContentRequest = new HttpPost(uploadContentUri);
        uploadContentRequest.setEntity(new FileEntity(agentPluginArchive, APPLICATION_OCTET_STREAM));
        uploadContentRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
        HttpResponse uploadContentResponse = httpClient.execute(uploadContentRequest);

        if (uploadContentResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            handleProblem(uploadContentResponse.getStatusLine().toString());
            return;
        }

        getLog().info("Uploaded " + agentPluginArchive);
        // Read the content handle value in JSON response
        JSONObject uploadContentResponseJsonObject = new JSONObject(
                EntityUtils.toString(uploadContentResponse.getEntity()));
        String contentHandle = (String) uploadContentResponseJsonObject.get("value");
        uploadContentRequest.abort();

        if (!startScan && !updatePluginsOnAllAgents) {

            // Request uploaded content to be moved to the plugins directory but do not trigger a plugin scan
            URI moveContentToPluginsDirUri = buildMoveContentToPluginsDirUri(contentHandle);
            moveContentToPluginsDirRequest = new HttpPut(moveContentToPluginsDirUri);
            moveContentToPluginsDirRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
            HttpResponse moveContentToPluginsDirResponse = httpClient.execute(moveContentToPluginsDirRequest);

            if (moveContentToPluginsDirResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                handleProblem(moveContentToPluginsDirResponse.getStatusLine().toString());
                return;
            }

            moveContentToPluginsDirRequest.abort();
            getLog().info("Moved uploaded content to plugins directory");
            return;
        }

        // Request uploaded content to be moved to the plugins directory and trigger a plugin scan
        URI pluginScanUri = buildPluginScanUri(contentHandle);
        pluginScanRequest = new HttpPost(pluginScanUri);
        pluginScanRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
        getLog().info("Moving uploaded content to plugins directory and requesting a plugin scan");
        HttpResponse pluginScanResponse = httpClient.execute(pluginScanRequest);

        if (pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED //
                && pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            handleProblem(pluginScanResponse.getStatusLine().toString());
            return;
        }

        pluginScanRequest.abort();
        getLog().info("Plugin scan complete");

        if (updatePluginsOnAllAgents) {

            URI pluginDeployUri = buildPluginDeployUri();
            pluginDeployRequest = new HttpPost(pluginDeployUri);
            pluginDeployRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
            getLog().info("Requesting agents to update their plugins");
            HttpResponse pluginDeployResponse = httpClient.execute(pluginDeployRequest);

            if (pluginDeployResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                handleProblem(pluginDeployResponse.getStatusLine().toString());
                return;
            }

            getLog().info("Plugins update requests sent");
            // Read the agent plugins update handle value in JSON response
            JSONObject pluginDeployResponseJsonObject = new JSONObject(
                    EntityUtils.toString(pluginDeployResponse.getEntity()));
            String pluginsUpdateHandle = (String) pluginDeployResponseJsonObject.get("value");
            pluginDeployRequest.abort();

            if (waitForPluginsUpdateOnAllAgents) {

                getLog().info("Waiting for plugins update requests to complete");

                long start = System.currentTimeMillis();
                for (;;) {

                    URI pluginDeployCheckCompleteUri = buildPluginDeployCheckCompleteUri(pluginsUpdateHandle);
                    pluginDeployCheckCompleteRequest = new HttpGet(pluginDeployCheckCompleteUri);
                    pluginDeployCheckCompleteRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
                    HttpResponse pluginDeployCheckCompleteResponse = httpClient
                            .execute(pluginDeployCheckCompleteRequest);

                    if (pluginDeployCheckCompleteResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        handleProblem(pluginDeployCheckCompleteResponse.getStatusLine().toString());
                        return;
                    }

                    // Read the agent plugins update handle value in JSON response
                    JSONObject pluginDeployCheckCompleteResponseJsonObject = new JSONObject(
                            EntityUtils.toString(pluginDeployCheckCompleteResponse.getEntity()));
                    Boolean pluginDeployCheckCompleteHandle = (Boolean) pluginDeployCheckCompleteResponseJsonObject
                            .get("value");
                    pluginDeployCheckCompleteRequest.abort();

                    if (pluginDeployCheckCompleteHandle == TRUE) {
                        getLog().info("All agents updated their plugins");
                        return;
                    }

                    if (SECONDS.toMillis(
                            maxWaitForPluginsUpdateOnAllAgents) < (System.currentTimeMillis() - start)) {
                        handleProblem("Not all agents updated their plugins but wait limit has been reached ("
                                + maxWaitForPluginsUpdateOnAllAgents + " ms)");
                        return;
                    }

                    Thread.sleep(SECONDS.toMillis(5));
                    getLog().info("Checking plugins update requests status again");
                }
            }
        }
    } catch (IOException e) {
        handleException(e);
    } catch (JSONException e) {
        handleException(e);
    } catch (URISyntaxException e) {
        handleException(e);
    } catch (InterruptedException e) {
        handleException(e);
    } finally {
        abortQuietly(uploadContentRequest);
        abortQuietly(moveContentToPluginsDirRequest);
        abortQuietly(pluginScanRequest);
        abortQuietly(pluginDeployRequest);
        abortQuietly(pluginDeployCheckCompleteRequest);
        httpConnectionManager.shutdown();
    }
}