Example usage for org.apache.commons.httpclient.auth AuthScope AuthScope

List of usage examples for org.apache.commons.httpclient.auth AuthScope AuthScope

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.auth AuthScope AuthScope.

Prototype

public AuthScope(String paramString, int paramInt) 

Source Link

Usage

From source file:hr.fer.zemris.vhdllab.platform.remoting.HttpClientRequestExecutor.java

@SuppressWarnings("null")
@Override//  w w  w .j  a  v  a 2s .c o m
protected void executePostMethod(HttpInvokerClientConfiguration config, HttpClient httpClient,
        PostMethod postMethod) throws IOException {
    AuthScope scope = new AuthScope(config.getCodebaseUrl(), AuthScope.ANY_PORT);
    super.executePostMethod(config, httpClient, postMethod);
    switch (postMethod.getStatusCode()) {
    case HttpStatus.SC_UNAUTHORIZED:
        UsernamePasswordCredentials credentials;
        if (Environment.isDevelopment() && !showRetryMessage) {
            credentials = new UsernamePasswordCredentials("test", "test");
            //              credentials = new UsernamePasswordCredentials("admin", "admin");
            showRetryMessage = true;
        } else {
            CommandManager manager = Application.instance().getActiveWindow().getCommandManager();
            LoginCommand command = (LoginCommand) manager.getCommand("loginCommand");
            command.execute();
            credentials = command.getCredentials();
        }
        if (credentials == null) {
            System.exit(1);
        }
        ApplicationContextHolder.getContext().setUserId(credentials.getUserName());
        showRetryMessage = true;
        getHttpClient().getState().setCredentials(scope, credentials);
        executePostMethod(config, httpClient, postMethod);
        break;
    }
}

From source file:com.intellij.tasks.impl.BaseRepositoryImpl.java

protected void configureHttpClient(HttpClient client) {
    client.getParams().setConnectionManagerTimeout(3000);
    client.getParams().setSoTimeout(TaskSettings.getInstance().CONNECTION_TIMEOUT);
    if (isUseProxy()) {
        HttpConfigurable proxy = HttpConfigurable.getInstance();
        client.getHostConfiguration().setProxy(proxy.PROXY_HOST, proxy.PROXY_PORT);
        if (proxy.PROXY_AUTHENTICATION) {
            AuthScope authScope = new AuthScope(proxy.PROXY_HOST, proxy.PROXY_PORT);
            Credentials credentials = getCredentials(proxy.getProxyLogin(), proxy.getPlainProxyPassword(),
                    proxy.PROXY_HOST);//w w  w.j  av  a  2 s.  c  o m
            client.getState().setProxyCredentials(authScope, credentials);
        }
    }
    if (isUseHttpAuthentication()) {
        client.getParams().setCredentialCharset("UTF-8");
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(getUsername(), getPassword()));
    } else {
        client.getState().clearCredentials();
        client.getParams().setAuthenticationPreemptive(false);
    }
}

From source file:gr.upatras.ece.nam.fci.panlab.RepoClient.java

/**
 * Make a GET call towards the repository. The BASIC Authentication is handled automatically
 * @param tgwaddr// w w  w.  j av a  2s .  c o  m
 */
public void execute(String tgwaddr) {

    String reqRepoURL = repoHostAddress + tgwaddr;
    HttpClient client = new HttpClient();

    // pass our credentials to HttpClient, they will only be used for
    // authenticating to servers with realm "realm" on the host
    // "www.verisign.com", to authenticate against an arbitrary realm 
    // or host change the appropriate argument to null.
    client.getState().setCredentials(new AuthScope(null, 8080),
            new UsernamePasswordCredentials(username, password));

    // create a GET method that reads a file over HTTPS, 
    // we're assuming that this file requires basic 
    // authentication using the realm above.
    GetMethod get = new GetMethod(reqRepoURL);
    System.out.println("Request: " + reqRepoURL);
    get.setRequestHeader("User-Agent", "RepoM2M-1.00");
    //get.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Tell the GET method to automatically handle authentication. The
    // method will use any appropriate credentials to handle basic
    // authentication requests.  Setting this value to false will cause
    // any request for authentication to return with a status of 401.
    // It will then be up to the client to handle the authentication.
    get.setDoAuthentication(true);

    try {
        // execute the GET
        client.executeMethod(get);

        // print the status and response
        InputStream responseBody = get.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();
        //return theinputstream;

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        get.releaseConnection();
    }
    //return null;       

}

From source file:fedora.common.http.WebClient.java

public HttpClient getHttpClient(String hostOrURL, UsernamePasswordCredentials creds) throws IOException {

    String host = null;/*  w  w w  .  j a v  a  2 s. co  m*/

    if (hostOrURL != null) {
        if (hostOrURL.indexOf("/") != -1) {
            URL url = new URL(hostOrURL);
            host = url.getHost();
        } else {
            host = hostOrURL;
        }
    }

    HttpClient client = new HttpClient(m_cManager);
    if (host != null && creds != null) {
        client.getState().setCredentials(new AuthScope(host, AuthScope.ANY_PORT), creds);
        client.getParams().setAuthenticationPreemptive(true);
    }

    if (proxy.isHostProxyable(host)) {
        client.getHostConfiguration().setProxy(proxy.getProxyHost(), proxy.getProxyPort());
        if (proxy.hasValidCredentials()) {
            client.getState().setProxyCredentials(
                    new AuthScope(proxy.getProxyHost(), proxy.getProxyPort(), null),
                    new UsernamePasswordCredentials(proxy.getProxyUser(), proxy.getProxyPassword()));
        }
    }
    return client;
}

From source file:com.lp.client.frame.component.phone.HttpPhoneDialerAuth.java

@Override
protected void prepareClient(HttpClient client, GetMethod method) {
    super.prepareClient(client, method);

    if (authUser != null && authPassword != null) {
        client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                //               new UsernamePasswordCredentials("admin", "0000")) ;
                new UsernamePasswordCredentials(authUser, authPassword));
        method.setDoAuthentication(true);
    }// w  w w  .  ja  v a2s. co  m
}

From source file:com.pureinfo.force.net.impl.HttpUtilImpl.java

/**
 * @see com.pureinfo.force.net.IHttpUtil#getContent(String, NameValuePair[],
 *      String, String)/*w  ww  .j a  v  a  2 s  .  c  o  m*/
 */
public String getContent(String _sUrl, NameValuePair[] _args, String _sRequestCharset, String _sResponseCharset)
        throws IOTransferException {
    if (_sRequestCharset == null) {
        _sRequestCharset = "utf-8";
    }

    //1. to create http client and set proxy
    HttpClient client = new HttpClient();
    if (m_proxyHost != null) {
        client.getHostConfiguration().setProxyHost(m_proxyHost);
        if (m_sProxyUser != null & m_sProxyPassword != null) {
            client.getState().setProxyCredentials(//
                    new AuthScope(m_proxyHost.getHostName(), m_proxyHost.getPort()),
                    new UsernamePasswordCredentials(m_sProxyUser, m_sProxyPassword));
        }
    }

    //2. to create post
    PostMethod method = new PostMethod(_sUrl);
    if (m_nRetryCount > 0) {
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, //
                new DefaultHttpMethodRetryHandler(m_nRetryCount, false));
    }
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + _sRequestCharset);
    for (int i = 0; _args != null && i < _args.length; i++) {
        method.addParameter(_args[i]);
    }

    //3. to send request and read response
    String sResponse;
    try {
        client.executeMethod(method);
        sResponse = method.getResponseBodyAsString();
        if (!method.getRequestCharSet().equals(_sRequestCharset)) {
            sResponse = new String(sResponse.getBytes(), _sResponseCharset);
        }
        return sResponse;
    } catch (Exception ex) {
        throw new IOTransferException(_sUrl, ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.inbravo.scribe.rest.service.crm.zd.auth.basic.ZDBasicAuthManager.java

@Override
public final String getSessionId(final String userId, final String password, final String crmURL,
        final String crmProtocol, final String port) throws Exception {
    logger.debug("----Inside login userId: " + userId + " & password: " + password + " & crmURL: " + crmURL
            + " & crmProtocol: " + crmProtocol + " & crmPort: " + port);

    /* Validate protocol */
    if (crmProtocol == null || "".equalsIgnoreCase(crmProtocol)) {

        /* Send user error */
        throw new ScribeException(
                ScribeResponseCodes._1003 + "Invalid protocol to communicate with ZD: " + crmProtocol);
    }//from  w w  w.  j a v  a 2 s . c  om

    /* Trick: Check all live users on CRM currently */
    final GetMethod getMethod = new GetMethod(crmProtocol + "://" + crmURL + "/users/current.xml");

    getMethod.addRequestHeader("Content-Type", "application/xml");
    final HttpClient httpclient = new HttpClient();

    /* Set credentials */
    httpclient.getState().setCredentials(new AuthScope(crmURL, this.validateCrmPort(port)),
            new UsernamePasswordCredentials(userId, password));

    try {
        int result = httpclient.executeMethod(getMethod);
        logger.debug("----Inside getSessionId response code: " + result + " & body: "
                + getMethod.getResponseBodyAsString());

        /* Check for authentication */
        if (result == HttpStatus.SC_UNAUTHORIZED) {
            logger.debug("----Inside getSessionId found unauthorized user");
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else {
            final String sessionId = getMethod.getResponseHeader("Set-Cookie").getValue();
            logger.debug("----Inside getSessionId sessionId: " + sessionId);
            return sessionId;
        }
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
}

From source file:edu.unc.lib.dl.cdr.sword.server.managers.MediaResourceManagerImpl.java

@Override
public MediaResource getMediaResourceRepresentation(String uri, Map<String, String> accept,
        AuthCredentials auth, SwordConfiguration config)
        throws SwordError, SwordServerException, SwordAuthException {

    log.debug("Retrieving media resource representation for " + uri);

    DatastreamPID targetPID = (DatastreamPID) extractPID(uri, SwordConfigurationImpl.EDIT_MEDIA_PATH + "/");

    Datastream datastream = Datastream.getDatastream(targetPID.getDatastream());
    if (datastream == null)
        datastream = virtualDatastreamMap.get(targetPID.getDatastream());

    if (datastream == null)
        throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404,
                "Media representations other than those of datastreams are not currently supported");

    HttpClient client = new HttpClient();

    UsernamePasswordCredentials cred = new UsernamePasswordCredentials(accessClient.getUsername(),
            accessClient.getPassword());
    client.getState().setCredentials(new AuthScope(null, 443), cred);
    client.getState().setCredentials(new AuthScope(null, 80), cred);

    GetMethod method = new GetMethod(fedoraPath + "/objects/" + targetPID.getPid() + "/datastreams/"
            + datastream.getName() + "/content");

    InputStream inputStream = null;
    String mimeType = null;//from  ww w. j a  v  a  2 s.co m
    String lastModified = null;

    try {
        method.setDoAuthentication(true);
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            StringBuffer query = new StringBuffer();
            query.append("select $mimeType $lastModified from <%1$s>")
                    .append(" where <%2$s> <%3$s> $mimeType and <%2$s> <%4$s> $lastModified").append(";");
            String formatted = String.format(query.toString(),
                    tripleStoreQueryService.getResourceIndexModelUri(),
                    targetPID.getURI() + "/" + datastream.getName(),
                    ContentModelHelper.FedoraProperty.mimeType.getURI().toString(),
                    ContentModelHelper.FedoraProperty.lastModifiedDate.getURI().toString());
            List<List<String>> datastreamResults = tripleStoreQueryService.queryResourceIndex(formatted);
            if (datastreamResults.size() > 0) {
                mimeType = datastreamResults.get(0).get(0);
                lastModified = datastreamResults.get(0).get(1);
            }
            inputStream = new MethodAwareInputStream(method);
        } else if (method.getStatusCode() >= 500) {
            throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, method.getStatusCode(),
                    "Failed to retrieve " + targetPID.getPid() + ": " + method.getStatusLine().toString());
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404,
                    "Object " + targetPID.getPid() + " could not be found.");
        }
    } catch (HttpException e) {
        throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                "An exception occurred while attempting to retrieve " + targetPID.getPid());
    } catch (IOException e) {
        throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                "An exception occurred while attempting to retrieve " + targetPID.getPid());
    }

    // For the ACL virtual datastream, transform RELS-EXT into accessControl tag
    if ("ACL".equals(targetPID.getDatastream())) {
        try {
            log.debug("Converting response XML to ACL format");
            SAXBuilder saxBuilder = new SAXBuilder();
            Document relsExt = saxBuilder.build(inputStream);
            XMLOutputter outputter = new XMLOutputter();
            Element accessElement = AccessControlTransformationUtil.rdfToACL(relsExt.getRootElement());
            inputStream.close();
            inputStream = new ByteArrayInputStream(outputter.outputString(accessElement).getBytes());
        } catch (Exception e) {
            log.debug("Failed to parse response from " + targetPID.getDatastreamURI() + " into ACL format", e);
            throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                    "An exception occurred while attempting to retrieve " + targetPID.getPid());
        }
    }

    MediaResource resource = new MediaResource(inputStream, mimeType, null, true);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Date lastModifiedDate;
    try {
        lastModifiedDate = formatter.parse(lastModified);
        resource.setLastModified(lastModifiedDate);
    } catch (ParseException e) {
        log.error("Unable to set last modified date for " + uri, e);
    }

    return resource;
}

From source file:com.datos.vfs.provider.http.HttpClientFactory.java

/**
 * Creates a new connection to the server.
 * @param builder The HttpFileSystemConfigBuilder.
 * @param scheme The protocol.//from  w ww.ja v  a2  s.c  om
 * @param hostname The hostname.
 * @param port The port number.
 * @param username The username.
 * @param password The password
 * @param fileSystemOptions The file system options.
 * @return a new HttpClient connection.
 * @throws FileSystemException if an error occurs.
 * @since 2.0
 */
public static HttpClient createConnection(final HttpFileSystemConfigBuilder builder, final String scheme,
        final String hostname, final int port, final String username, final String password,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    HttpClient client;
    try {
        final HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
        final HttpConnectionManagerParams connectionMgrParams = mgr.getParams();

        client = new HttpClient(mgr);

        final HostConfiguration config = new HostConfiguration();
        config.setHost(hostname, port, scheme);

        if (fileSystemOptions != null) {
            final String proxyHost = builder.getProxyHost(fileSystemOptions);
            final int proxyPort = builder.getProxyPort(fileSystemOptions);

            if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
                config.setProxy(proxyHost, proxyPort);
            }

            final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
            if (proxyAuth != null) {
                final UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
                        new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME,
                                UserAuthenticationData.PASSWORD });

                if (authData != null) {
                    final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(
                            UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                                    UserAuthenticationData.USERNAME, null)),
                            UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                                    UserAuthenticationData.PASSWORD, null)));

                    final AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
                    client.getState().setProxyCredentials(scope, proxyCreds);
                }

                if (builder.isPreemptiveAuth(fileSystemOptions)) {
                    final HttpClientParams httpClientParams = new HttpClientParams();
                    httpClientParams.setAuthenticationPreemptive(true);
                    client.setParams(httpClientParams);
                }
            }

            final Cookie[] cookies = builder.getCookies(fileSystemOptions);
            if (cookies != null) {
                client.getState().addCookies(cookies);
            }
        }
        /**
         * ConnectionManager set methods must be called after the host & port and proxy host & port
         * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
         * tries to locate the host configuration.
         */
        connectionMgrParams.setMaxConnectionsPerHost(config,
                builder.getMaxConnectionsPerHost(fileSystemOptions));
        connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));

        connectionMgrParams.setConnectionTimeout(builder.getConnectionTimeout(fileSystemOptions));
        connectionMgrParams.setSoTimeout(builder.getSoTimeout(fileSystemOptions));

        client.setHostConfiguration(config);

        if (username != null) {
            final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
            final AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
            client.getState().setCredentials(scope, creds);
        }
    } catch (final Exception exc) {
        throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname);
    }

    return client;
}

From source file:com.rometools.fetcher.impl.HttpClientFeedFetcher.java

@Override
public SyndFeed retrieveFeed(final String userAgent, final URL feedUrl)
        throws IllegalArgumentException, IOException, FeedException, FetcherException {

    if (feedUrl == null) {
        throw new IllegalArgumentException("null is not a valid URL");
    }/*from  w  w w  .  j  av a  2 s  . c om*/

    final HttpClient client = new HttpClient(httpClientParams);

    if (credentialSupplier != null) {

        final HttpClientParams params = client.getParams();
        params.setAuthenticationPreemptive(true);

        final String host = feedUrl.getHost();
        final Credentials credentials = credentialSupplier.getCredentials(null, host);
        if (credentials != null) {
            final AuthScope authScope = new AuthScope(host, -1);
            final HttpState state = client.getState();
            state.setCredentials(authScope, credentials);
        }

    }

    System.setProperty("httpclient.useragent", userAgent);

    final String urlStr = feedUrl.toString();
    final HttpMethod method = new GetMethod(urlStr);

    if (customRequestHeaders == null) {
        method.addRequestHeader("Accept-Encoding", "gzip");
        method.addRequestHeader("User-Agent", userAgent);

    } else {
        for (final Map.Entry<String, String> entry : customRequestHeaders.entrySet()) {
            method.addRequestHeader(entry.getKey(), entry.getValue());
        }
        if (!customRequestHeaders.containsKey("Accept-Encoding")) {
            method.addRequestHeader("Accept-Encoding", "gzip");
        }
        if (!customRequestHeaders.containsKey("User-Agent")) {
            method.addRequestHeader("User-Agent", userAgent);
        }
    }

    method.setFollowRedirects(true);

    if (httpClientMethodCallback != null) {
        synchronized (httpClientMethodCallback) {
            httpClientMethodCallback.afterHttpClientMethodCreate(method);
        }
    }

    final FeedFetcherCache cache = getFeedInfoCache();

    if (cache != null) {
        // retrieve feed
        try {

            if (isUsingDeltaEncoding()) {
                method.setRequestHeader("A-IM", "feed");
            }

            // try to get the feed info from the cache
            SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl);

            if (syndFeedInfo != null) {

                method.setRequestHeader("If-None-Match", syndFeedInfo.getETag());

                final Object lastModifiedHeader = syndFeedInfo.getLastModified();
                if (lastModifiedHeader instanceof String) {
                    method.setRequestHeader("If-Modified-Since", (String) lastModifiedHeader);
                }

            }

            final int statusCode = client.executeMethod(method);
            fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr);
            handleErrorCodes(statusCode);

            SyndFeed feed = getFeed(syndFeedInfo, urlStr, method, statusCode);

            syndFeedInfo = buildSyndFeedInfo(feedUrl, urlStr, method, feed, statusCode);

            cache.setFeedInfo(feedUrl, syndFeedInfo);

            // the feed may have been modified to pick up cached values
            // (eg - for delta encoding)
            feed = syndFeedInfo.getSyndFeed();

            return feed;

        } finally {

            method.releaseConnection();

        }

    } else {

        // cache is not in use
        try {

            final int statusCode = client.executeMethod(method);
            fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr);
            handleErrorCodes(statusCode);

            return getFeed(null, urlStr, method, statusCode);

        } finally {

            method.releaseConnection();

        }

    }

}