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:org.overlord.sramp.governance.shell.commands.Pkg2SrampCommand.java

/**
 * Uploads the BMRS package.//from  w  w w. j av a2  s  . c o  m
 * @param brmsBaseUrl
 * @param pkgName
 * @param tag
 * @param userId
 * @param password
 * @param client
 * @throws Exception
 */
public void uploadBrmsPackage(String brmsBaseUrl, String pkgName, String tag, String userId, String password,
        SrampAtomApiClient client) throws Exception {
    // http://localhost:8080/drools-guvnor/org.drools.guvnor.Guvnor/package/srampPackage/S_RAMP_0.0.3.0
    String urlStr = brmsBaseUrl + "/org.drools.guvnor.Guvnor/package/" + pkgName + "/" + tag; //$NON-NLS-1$ //$NON-NLS-2$

    Credentials credentials = new UsernamePasswordCredentials(userId, password);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
    fac = new ClientRequestFactory(clientExecutor, new URI(brmsBaseUrl));

    Map<String, Packages.Package> brmsPkgMap = getPkgsFromBrms(brmsBaseUrl);
    if (!brmsPkgMap.containsKey(pkgName)) {
        print("Brms contains the following BRMS Packages"); //$NON-NLS-1$
        for (String name : brmsPkgMap.keySet()) {
            print(" * " + name); //$NON-NLS-1$
        }
        throw new Exception("Could not find package with name " + pkgName + " in BRMS"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    Packages.Package brmsPkg = brmsPkgMap.get(pkgName);

    print("Located BRMS package '" + pkgName + "' :"); //$NON-NLS-1$ //$NON-NLS-2$
    print("   UUID ............: " + brmsPkg.getMetadata().getUuid()); //$NON-NLS-1$
    print("   Version .........: " + brmsPkg.getMetadata().getVersionNumber()); //$NON-NLS-1$
    print("   Author ..........: " + brmsPkg.getAuthor()); //$NON-NLS-1$
    print("   Last published ..: " + brmsPkg.getPublished()); //$NON-NLS-1$
    print("   Description .....: " + brmsPkg.getDescription()); //$NON-NLS-1$

    // now uploading this into s-ramp
    @SuppressWarnings("deprecation")
    ExtendedArtifactType extendedArtifactType = (ExtendedArtifactType) ArtifactType.fromFileExtension("pkg") //$NON-NLS-1$
            .newArtifactInstance();
    extendedArtifactType.setUuid(brmsPkg.getMetadata().getUuid());
    extendedArtifactType.setName(pkgName + ".pkg"); //$NON-NLS-1$

    Property assetsProperty = new Property();
    assetsProperty.setPropertyName(BrmsConstants.ASSET_INFO_XML);
    String assetsXml = getAssetsStringFromBrms(brmsBaseUrl, pkgName);
    //update the links
    String srampUrl = client.getEndpoint().substring(0, client.getEndpoint().lastIndexOf("/")); //$NON-NLS-1$
    assetsXml = assetsXml.replaceAll(brmsBaseUrl, srampUrl + "/brms"); //$NON-NLS-1$
    assetsProperty.setPropertyValue(assetsXml);
    extendedArtifactType.getProperty().add(assetsProperty);

    print("Reading " + pkgName + " from url " + urlStr); //$NON-NLS-1$ //$NON-NLS-2$
    ClientResponse<InputStream> pkgResponse = getInputStream(urlStr);
    InputStream content = pkgResponse.getEntity();

    BaseArtifactType artifact = client.uploadArtifact(extendedArtifactType, content);
    IOUtils.closeQuietly(content);
    print("Uploaded " + pkgName + " UUID=" + artifact.getUuid()); //$NON-NLS-1$ //$NON-NLS-2$

    // Now obtaining the assets in the this package, and upload those
    // TODO set relationship to parent pkg
    Assets assets = getAssetsFromBrms(brmsBaseUrl, pkgName);

    //Upload the process AND process-image, making sure the uuid is identical to the one mentioned
    for (Assets.Asset asset : assets.getAsset()) {
        if (!"package".equalsIgnoreCase(asset.getMetadata().getFormat())) { //$NON-NLS-1$
            //Upload the asset
            String fileName = asset.getTitle() + "." + asset.getMetadata().getFormat().toLowerCase(); //$NON-NLS-1$
            String uuid = asset.getMetadata().getUuid();
            //reading the asset from disk
            //http://localhost:8080/drools-guvnor/rest/packages/srampPackage/assets/
            String assetURLStr = brmsBaseUrl + "/rest/packages/" + pkgName + "/assets/" + asset.getTitle() //$NON-NLS-1$//$NON-NLS-2$
                    + "/binary"; //$NON-NLS-1$
            //print("Reading asset " + asset.getTitle() + " from url " + assetURLStr );
            ClientResponse<InputStream> assetResponse = getInputStream(assetURLStr);
            InputStream assetInputStream = assetResponse.getEntity();

            //upload the asset using the uuid
            @SuppressWarnings("deprecation")
            ArtifactType artifactType = ArtifactType.fromFileExtension(asset.getMetadata().getFormat());
            BaseArtifactType baseArtifactType = artifactType.newArtifactInstance();
            baseArtifactType.setName(fileName);
            baseArtifactType.setUuid(uuid);

            BaseArtifactType assetArtifact = client.uploadArtifact(baseArtifactType, assetInputStream);
            IOUtils.closeQuietly(assetInputStream);
            print("Uploaded asset " + assetArtifact.getUuid() + " " + assetArtifact.getName()); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    print("OK"); //$NON-NLS-1$

}

From source file:org.botlibre.util.Utils.java

public static String httpAuthPOST(String url, String user, String password, String type, String data)
        throws Exception {
    HttpPost request = new HttpPost(url);
    StringEntity params = new StringEntity(data, "utf-8");
    request.addHeader("content-type", type);
    request.setEntity(params);//from  w  w  w . ja v a  2 s  .  co m
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(user, password));
    HttpResponse response = client.execute(request);
    return fetchResponse(response);
}

From source file:org.fabrician.maven.plugins.GridlibUploadMojo.java

public void execute() throws MojoExecutionException {
    String username = brokerUsername;
    String password = brokerPassword;
    if (serverId != null && !"".equals(serverId)) {
        // TODO: implement server_id
        throw new MojoExecutionException("serverId is not yet supported");
    } else if (brokerUsername == null || "".equals(brokerUsername) || brokerPassword == null
            || "".equals(brokerPassword)) {
        throw new MojoExecutionException("serverId or brokerUsername and brokerPassword must be set");
    }/*from ww  w  .  j a  v a  2s.co  m*/

    DirectoryScanner ds = new DirectoryScanner();
    ds.setIncludes(mIncludes);
    ds.setExcludes(mExcludes);
    ds.setBasedir(".");
    ds.setCaseSensitive(true);
    ds.scan();

    String[] files = ds.getIncludedFiles();
    if (files == null) {
        getLog().info("No files found to upload");
    } else {
        getLog().info("Found " + files.length + " file to upload");

        for (String file : files) {
            File gridlibFilename = new File(file);
            getLog().info("Uploading " + gridlibFilename + " to " + brokerUrl);

            DefaultHttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            Credentials cred = new UsernamePasswordCredentials(username, password);
            httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, cred);

            try {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                entity.addPart("gridlibOverwrite",
                        new StringBody(String.valueOf(gridlibOverwrite), Charset.forName("UTF-8")));
                entity.addPart("gridlibArchive", new FileBody(gridlibFilename));

                HttpPost method = new HttpPost(brokerUrl);
                method.setEntity(entity);

                HttpResponse response = httpclient.execute(method);
                StatusLine status = response.getStatusLine();
                int code = status.getStatusCode();
                if (code >= 400 && code <= 500) {
                    throw new MojoExecutionException(
                            "Failed to upload " + gridlibFilename + " to " + brokerUrl + ": " + code);
                }
            } catch (Exception e) {
                throw new MojoExecutionException(e.getMessage());
            }
        }
    }
}

From source file:cloudMe.CloudMeAPI.java

private DefaultHttpClient getConnection() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
    HttpProtocolParams.setUserAgent(httpClient.getParams(), USER_AGENT_INFO);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, 80, "os@xcerion.com", "Digest"),
            new UsernamePasswordCredentials(userName, pass)); // Encrypts password & username
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                if (creds != null && scheme != null) {
                    authState.setAuthScheme(scheme);
                    authState.setCredentials(creds);
                } else {
                    scheme = authState.getAuthScheme();
                }//  ww w  .  j  av a 2s . c om
            }
        }
    };
    httpClient.addRequestInterceptor(preemptiveAuth, 0);
    return httpClient;

}

From source file:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected HttpClient createHTTPClient(String hostName, int port) {
    DefaultHttpClient cli = new DefaultHttpClient();
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);//from  w  w  w  . ja  va  2s. c  om
    cli.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    cli.getCredentialsProvider().setCredentials(new AuthScope(hostName, port), creds);
    ((DefaultHttpClient) cli).addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            //if (ssoToken != null)
            //request.addHeader("subjectid",ssoToken.getToken());
        }
    });
    return cli;
}

From source file:org.botlibre.util.Utils.java

public static String httpAuthPOST(String url, String user, String password, Map<String, String> formParams)
        throws Exception {
    HttpPost request = new HttpPost(url);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : formParams.entrySet()) {
        params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }/*from w w w  .j  ava  2s  . c  o  m*/
    request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(user, password));
    HttpResponse response = client.execute(request);
    return fetchResponse(response);
}

From source file:org.xwiki.contrib.authentication.http.XWikiHTTPAuthenticator.java

private boolean checkAuth(String username, String password, URI uri)
        throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "XWik");
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));

    HttpGet httpget = new HttpGet(uri);
    HttpResponse response = httpClient.execute(httpget);

    return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}

From source file:com.expressui.domain.RestClientService.java

/**
 * Create a REST client/*from w  ww.  j av a2  s  .  c om*/
 *
 * @param uri   uri of the service
 * @param clazz client class
 * @param <T>   class type
 * @return REST client
 * @throws Exception
 */
public <T> T create(String uri, Class<T> clazz) throws Exception {
    RestClientProxyFactoryBean restClientFactory = new RestClientProxyFactoryBean();
    restClientFactory.setBaseUri(new URI(uri));
    restClientFactory.setServiceInterface(clazz);
    if (applicationProperties.getHttpProxyHost() != null && applicationProperties.getHttpProxyPort() != null) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpHost proxy = new HttpHost(applicationProperties.getHttpProxyHost(),
                applicationProperties.getHttpProxyPort());

        if (applicationProperties.getHttpProxyUsername() != null
                && applicationProperties.getHttpProxyPassword() != null) {

            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(applicationProperties.getHttpProxyHost(),
                            applicationProperties.getHttpProxyPort()),
                    new UsernamePasswordCredentials(applicationProperties.getHttpProxyUsername(),
                            applicationProperties.getHttpProxyPassword()));
        }

        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        restClientFactory.setHttpClient(httpClient);
    }
    restClientFactory.afterPropertiesSet();
    return (T) restClientFactory.getObject();
}

From source file:uk.ac.ox.oucs.vle.TestPopulatorInput.java

public InputStream getInput(PopulatorContext context) {

    InputStream input;//w  ww.ja  v  a 2  s.c o  m
    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {
        URL xcri = new URL(context.getURI());
        if ("file".equals(xcri.getProtocol())) {
            input = xcri.openStream();

        } else {
            HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol());

            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                    new UsernamePasswordCredentials(context.getUser(), context.getPassword()));

            HttpGet httpget = new HttpGet(xcri.toURI());
            HttpResponse response = httpclient.execute(targetHost, httpget);
            HttpEntity entity = response.getEntity();

            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                throw new IllegalStateException(
                        "Invalid response [" + response.getStatusLine().getStatusCode() + "]");
            }

            input = entity.getContent();
        }
    } catch (MalformedURLException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IllegalStateException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IOException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (URISyntaxException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    }

    return input;
}

From source file:org.apache.hadoop.gateway.dispatch.AppCookieManager.java

/**
 * Fetches hadoop.auth cookie from hadoop service authenticating using SpNego
 * /*from  w  w  w  .  ja v a2s.  c om*/
 * @param outboundRequest
 *          out going request
 * @param refresh
 *          flag indicating whether to refresh the cached cookie
 * @return hadoop.auth cookie from hadoop service authenticating using SpNego
 * @throws IOException
 *           in case of errors
 */
public String getAppCookie(HttpUriRequest outboundRequest, boolean refresh) throws IOException {

    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    if (!refresh) {
        if (appCookie != null) {
            return appCookie;
        }
    }

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    clearAppCookie();
    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = createKerberosAuthenticationRequest(outboundRequest);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        EntityUtils.consume(httpResponse.getEntity());
        if (hadoopAuthCookie == null) {
            LOG.failedSPNegoAuthn(uri.toString());
            auditor.audit(Action.AUTHENTICATION, uri.toString(), ResourceType.URI, ActionOutcome.FAILURE);
            throw new IOException("SPNego authn failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }
    LOG.successfulSPNegoAuthn(uri.toString());
    auditor.audit(Action.AUTHENTICATION, uri.toString(), ResourceType.URI, ActionOutcome.SUCCESS);
    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(hadoopAuthCookie);
    return appCookie;
}