类org.apache.commons.httpclient.Credentials源码实例Demo

下面列出了怎么用org.apache.commons.httpclient.Credentials的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cloudstack   文件: HttpTemplateDownloader.java
private void checkCredentials(String user, String password) {
    try {
        Pair<String, Integer> hostAndPort = UriUtils.validateUrl(downloadUrl);
        if ((user != null) && (password != null)) {
            client.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
            client.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
            s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
        } else {
            s_logger.info("No credentials configured for host=" + hostAndPort.first() + ":" + hostAndPort.second());
        }
    } catch (IllegalArgumentException iae) {
        errorString = iae.getMessage();
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        inited = false;
    }
}
 
源代码2 项目: cosmic   文件: UriUtils.java
public static InputStream getInputStreamFromUrl(final String url, final String user, final String password) {

        try {
            final Pair<String, Integer> hostAndPort = validateUrl(url);
            final HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
            if ((user != null) && (password != null)) {
                httpclient.getParams().setAuthenticationPreemptive(true);
                final Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
                httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
                s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
            }
            // Execute the method.
            final GetMethod method = new GetMethod(url);
            final int statusCode = httpclient.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                s_logger.error("Failed to read from URL: " + url);
                return null;
            }

            return method.getResponseBodyAsStream();
        } catch (final Exception ex) {
            s_logger.error("Failed to read from URL: " + url);
            return null;
        }
    }
 
源代码3 项目: development   文件: PortFactory.java
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 * @param username
 * @param password
 * @return
 * @throws IOException
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}
 
源代码4 项目: development   文件: RORClientTest.java
@Test
public void createClient() throws Exception {
	// given
	System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
	System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);
	System.setProperty(HTTPS_PROXY_USER, HTTPS_PROXY_USER_VALUE);
	System.setProperty(HTTPS_PROXY_PASSWORD, HTTPS_PROXY_PASSWORD_VALUE);
	Credentials proxyCredentials = new UsernamePasswordCredentials(
			HTTPS_PROXY_USER_VALUE, HTTPS_PROXY_PASSWORD_VALUE);
	AuthScope authScope = new AuthScope(HTTPS_PROXY_HOST_VALUE,
			Integer.parseInt(HTTPS_PROXY_PORT_VALUE));

	// when
	HttpClient client = vdcClient.createHttpClient();

	// then
	assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
			.getProxyHost());
	assertEquals(HTTPS_PROXY_PORT_VALUE,
			String.valueOf(client.getHostConfiguration().getProxyPort()));
	assertEquals(proxyCredentials,
			client.getState().getProxyCredentials(authScope));

}
 
源代码5 项目: development   文件: BasicAuthLoader.java
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 *            the URL to read
 * @param username
 * @param password
 * @return the read content.
 * @throws IOException
 *             if an I/O exception occurs.
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}
 
源代码6 项目: olat   文件: HttpClientFactory.java
/**
 * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
 * 
 * @param user
 *            can be NULL
 * @param password
 *            can be NULL
 * @return HttpClient
 */
public static HttpClient getHttpClientInstance(String user, String password) {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionParams params = connectionManager.getParams();
    // wait max 10 seconds to establish connection
    params.setConnectionTimeout(10000);
    // a read() call on the InputStream associated with this Socket
    // will block for only this amount
    params.setSoTimeout(10000);
    HttpClient c = new HttpClient(connectionManager);

    // use basic authentication if available
    if (user != null && user.length() > 0) {
        AuthScope authScope = new AuthScope(null, -1, null);
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        c.getState().setCredentials(authScope, credentials);
    }
    return c;
}
 
源代码7 项目: olat   文件: HttpClientFactory.java
/**
 * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
 * 
 * @param user
 *            can be NULL
 * @param password
 *            can be NULL
 * @return HttpClient
 */
public static HttpClient getHttpClientInstance(String user, String password) {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionParams params = connectionManager.getParams();
    // wait max 10 seconds to establish connection
    params.setConnectionTimeout(10000);
    // a read() call on the InputStream associated with this Socket
    // will block for only this amount
    params.setSoTimeout(10000);
    HttpClient c = new HttpClient(connectionManager);

    // use basic authentication if available
    if (user != null && user.length() > 0) {
        AuthScope authScope = new AuthScope(null, -1, null);
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        c.getState().setCredentials(authScope, credentials);
    }
    return c;
}
 
源代码8 项目: cloudstack   文件: UriUtils.java
public static InputStream getInputStreamFromUrl(String url, String user, String password) {

        try {
            Pair<String, Integer> hostAndPort = validateUrl(url);
            HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
            if ((user != null) && (password != null)) {
                httpclient.getParams().setAuthenticationPreemptive(true);
                Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
                httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
                s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
            }
            // Execute the method.
            GetMethod method = new GetMethod(url);
            int statusCode = httpclient.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                s_logger.error("Failed to read from URL: " + url);
                return null;
            }

            return method.getResponseBodyAsStream();
        } catch (Exception ex) {
            s_logger.error("Failed to read from URL: " + url);
            return null;
        }
    }
 
源代码9 项目: elasticsearch-hadoop   文件: EsApiKeyAuthScheme.java
/**
 * Implementation method for authentication
 */
private String authenticate(Credentials credentials) throws AuthenticationException {
    if (!(credentials instanceof EsApiKeyCredentials)) {
        throw new AuthenticationException("Incorrect credentials type provided. Expected [" + EsApiKeyCredentials.class.getName()
                + "] but got [" + credentials.getClass().getName() + "]");
    }

    EsApiKeyCredentials esApiKeyCredentials = ((EsApiKeyCredentials) credentials);
    String authString = null;

    if (esApiKeyCredentials.getToken() != null && StringUtils.hasText(esApiKeyCredentials.getToken().getName())) {
        EsToken token = esApiKeyCredentials.getToken();
        String keyComponents = token.getId() + ":" + token.getApiKey();
        byte[] base64Encoded = Base64.encodeBase64(keyComponents.getBytes(StringUtils.UTF_8));
        String tokenText = new String(base64Encoded, StringUtils.UTF_8);
        authString = EsHadoopAuthPolicies.APIKEY + " " + tokenText;
    }

    return authString;
}
 
源代码10 项目: openhab1-addons   文件: HttpUtil.java
/**
 * Extracts username and password from the given <code>url</code>. A valid
 * url to extract {@link Credentials} from looks like:
 *
 * <pre>
 * http://username:[email protected]
 * </pre>
 *
 * @param url the URL to extract {@link Credentials} from
 *
 * @return the exracted Credentials or <code>null</code> if the given
 *         <code>url</code> does not contain credentials
 */
protected static Credentials extractCredentials(String url) {

    Matcher matcher = URL_CREDENTIALS_PATTERN.matcher(url);

    if (matcher.matches()) {

        matcher.reset();

        String username = "";
        String password = "";

        while (matcher.find()) {
            username = matcher.group(1);
            password = matcher.group(2);
        }

        Credentials credentials = new UsernamePasswordCredentials(username, password);
        return credentials;
    }

    return null;
}
 
源代码11 项目: httpsig-java   文件: SignerCredentialsProvider.java
public Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
        throws CredentialsNotAvailableException {

    if (Constants.SCHEME.equals(scheme.getSchemeName())) {
        if (signer == null) {
            throw new CredentialsNotAvailableException("SSHKey Signer not available");
        } else {
            return new SignerCredentials(signer);
        }
    } else {
        if (this.delegatee != null) {
            return this.delegatee.getCredentials(scheme, host, port, proxy);
        }
    }
    return null;
}
 
/**
 * Returns the Ticket in the form used for HTTP Basic Authentication. 
 * This should be added as the value to a HTTP Request Header with 
 *  key Authorization
 */
public String getAsHTTPAuthorization()
{
    // Build from the Username and Password
    Pair<String,String> userPass = getAsUsernameAndPassword();
    Credentials credentials = new UsernamePasswordCredentials(userPass.getFirst(), userPass.getSecond());

    // Encode it into the required format
    String credentialsEncoded = Base64.encodeBytes(
            credentials.toString().getBytes(utf8), Base64.DONT_BREAK_LINES );
    
    // Mark it as Basic, and we're done
    return "Basic " + credentialsEncoded;
}
 
源代码13 项目: scim2-compliance-test-suite   文件: CSP.java
@SuppressWarnings("deprecation")
public String getAccessToken() {
    if (this.oAuth2AccessToken != null) {
        return this.oAuth2AccessToken;
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(this.getUsername(), this.getPassword());
        client.getState().setCredentials(AuthScope.ANY, defaultcreds);

        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestBody("grant_type=client_credentials");
        int responseCode = client.executeMethod(method);
        if (responseCode != 200) {

            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }
        String responseBody = method.getResponseBodyAsString();
        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
源代码14 项目: development   文件: RORClient.java
public HttpClient createHttpClient() {
	HttpClient client = new HttpClient();

	String proxyHost = System.getProperty(HTTPS_PROXY_HOST);
	String proxyPort = System.getProperty(HTTPS_PROXY_PORT);
	String proxyUser = System.getProperty(HTTPS_PROXY_USER);
	String proxyPassword = System.getProperty(HTTPS_PROXY_PASSWORD);
	int proxyPortInt = 0;

	try {
		proxyPortInt = Integer.parseInt(proxyPort);
	} catch (NumberFormatException e) {
		// ignore
	}
	if (!useProxyByPass(this.apiUrl)) {
		if (proxyHost != null && proxyPortInt > 0) {
			client.getHostConfiguration().setProxy(proxyHost, proxyPortInt);

			if (proxyUser != null && proxyUser.length() > 0
					&& proxyPassword != null && proxyPassword.length() > 0) {
				HttpState state = new HttpState();
				Credentials proxyCredentials = new UsernamePasswordCredentials(
						proxyUser, proxyPassword);
				state.setProxyCredentials(new AuthScope(proxyHost,
						proxyPortInt), proxyCredentials);
				client.setState(state);
			}
		}
	}
	return client;
}
 
源代码15 项目: maven-confluence-plugin   文件: Confluence.java
protected Confluence(String endpoint, ConfluenceProxy proxyInfo ) throws URISyntaxException, MalformedURLException {
       this(new XmlRpcClient());
if (endpoint.endsWith("/")) {
           endpoint = endpoint.substring(0, endpoint.length() - 1);
       }

       endpoint = ConfluenceService.Protocol.XMLRPC.addTo(endpoint);
   
       final java.net.URI serviceURI = new java.net.URI(endpoint);

       XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl();
       clientConfig.setServerURL(serviceURI.toURL() );

       clientConfig.setEnabledForExtensions(true); // add this to support attachment upload

       client.setConfig( clientConfig );

       if( isProxyEnabled(proxyInfo, serviceURI) ) {
           
           final XmlRpcCommonsTransportFactory transportFactory = new XmlRpcCommonsTransportFactory( client );

           final HttpClient httpClient = new HttpClient();
           final HostConfiguration hostConfiguration = httpClient.getHostConfiguration();
           hostConfiguration.setProxy( proxyInfo.host, proxyInfo.port );
           hostConfiguration.setHost(serviceURI.getHost(), serviceURI.getPort(), serviceURI.toURL().getProtocol());

           if( !isNullOrEmpty(proxyInfo.userName) && !isNullOrEmpty(proxyInfo.password) ) {
               Credentials cred = new UsernamePasswordCredentials(proxyInfo.userName,proxyInfo.password);
               httpClient.getState().setProxyCredentials(AuthScope.ANY, cred);
           }

           transportFactory.setHttpClient( httpClient );
           client.setTransportFactory( transportFactory );
       }
   }
 
源代码16 项目: knopflerfish.org   文件: HttpAuthenticator.java
private static boolean doAuthenticateDefault(
    HttpMethod method, 
    HttpConnection conn,
    HttpState state, 
    boolean proxy)
  throws AuthenticationException {
    if (method == null) {
        throw new IllegalArgumentException("HTTP method may not be null");
    }
    if (state == null) {
        throw new IllegalArgumentException("HTTP state may not be null");
    }
    String host = null;
    if (conn != null) {
        host = proxy ? conn.getProxyHost() : conn.getHost();
    }
    Credentials credentials = proxy 
        ? state.getProxyCredentials(null, host) : state.getCredentials(null, host);
    if (credentials == null) {
        return false;
    }
    if (!(credentials instanceof UsernamePasswordCredentials)) {
        throw new InvalidCredentialsException(
         "Credentials cannot be used for basic authentication: " 
          + credentials.toString());
    }
    String auth = BasicScheme.authenticate(
        (UsernamePasswordCredentials) credentials,
        method.getParams().getCredentialCharset());
    if (auth != null) {
        String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP;
        Header header = new Header(s, auth, true);
        method.addRequestHeader(header);
        return true;
    } else {
        return false;
    }
}
 
源代码17 项目: Kylin   文件: RestClient.java
private void init(String host, int port, String userName, String password) {
    this.host = host;
    this.port = port;
    this.userName = userName;
    this.password = password;
    this.baseUrl = "http://" + host + ":" + port + "/kylin/api";

    client = new HttpClient();

    if (userName != null && password != null) {
        client.getParams().setAuthenticationPreemptive(true);
        Credentials creds = new UsernamePasswordCredentials(userName, password);
        client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), creds);
    }
}
 
源代码18 项目: geofence   文件: InstancesManagerServiceImpl.java
private void setAuth(HttpClient client, String url, String username, String pw) throws MalformedURLException {
    URL u = new URL(url);
    if(username != null && pw != null) {
        Credentials defaultcreds = new UsernamePasswordCredentials(username, pw);
        client.getState().setCredentials(new AuthScope(u.getHost(), u.getPort()), defaultcreds);
        client.getParams().setAuthenticationPreemptive(true); // GS2 by default always requires authentication
    } else {
        if(logger.isDebugEnabled()) {
            logger.debug("Not setting credentials to access to " + url);
        }
    }
}
 
源代码19 项目: fenixedu-academic   文件: PhoneValidationUtils.java
private void initCIISTSMSGateway() {
    final String CIIST_SMS_USERNAME = FenixEduAcademicConfiguration.getConfiguration().getCIISTSMSUsername();
    final String CIIST_SMS_PASSWORD = FenixEduAcademicConfiguration.getConfiguration().getCIISTSMSPassword();
    CIIST_SMS_GATEWAY_URL = FenixEduAcademicConfiguration.getConfiguration().getCIISTSMSGatewayUrl();
    if (!StringUtils.isEmpty(CIIST_SMS_USERNAME) && !StringUtils.isEmpty(CIIST_SMS_PASSWORD)) {
        CIIST_CLIENT = new HttpClient();
        Credentials credentials = new UsernamePasswordCredentials(CIIST_SMS_USERNAME, CIIST_SMS_PASSWORD);
        CIIST_CLIENT.getState().setCredentials(AuthScope.ANY, credentials);
    }
}
 
源代码20 项目: cloudstack   文件: HttpTemplateDownloader.java
private void checkProxy(Proxy proxy) {
    if (proxy != null) {
        client.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());
        if (proxy.getUserName() != null) {
            Credentials proxyCreds = new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword());
            client.getState().setProxyCredentials(AuthScope.ANY, proxyCreds);
        }
    }
}
 
源代码21 项目: elasticsearch-hadoop   文件: SpnegoAuthScheme.java
/**
 * Returns the text to send via the Authenticate header on the next request.
 */
@Override
public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
    try {
        return authenticate(credentials, URI.create(method.getURI().getURI()));
    } catch (URIException e) {
        throw new AuthenticationException("Could not determine request URI", e);
    }
}
 
源代码22 项目: rome   文件: HttpClientFeedFetcherTest.java
/**
 * @see com.rometools.rome.fetcher.impl.AbstractJettyTest#getAuthenticatedFeedFetcher()
 */
@Override
public FeedFetcher getAuthenticatedFeedFetcher() {
    return new HttpClientFeedFetcher(null, new HttpClientFeedFetcher.CredentialSupplier() {
        @Override
        public Credentials getCredentials(final String realm, final String host) {
            if ("localhost".equals(host)) {
                return new UsernamePasswordCredentials("username", "password");
            } else {
                return null;
            }
        }
    });
}
 
源代码23 项目: jrpip   文件: AuthenticatedUrl.java
public AuthenticatedUrl(URL url, Credentials credentials, Cookie[] cookies)
{
    this.url = url;
    this.credentials = credentials;
    this.cookies = cookies;
}
 
源代码24 项目: jrpip   文件: AuthenticatedUrl.java
public AuthenticatedUrl(String url, Credentials credentials) throws MalformedURLException
{
    this(new URL(url), credentials, null);
}
 
源代码25 项目: jrpip   文件: AuthenticatedUrl.java
public AuthenticatedUrl(String url, Credentials credentials, Cookie[] cookies) throws MalformedURLException
{
    this(new URL(url), credentials, cookies);
}
 
源代码26 项目: dacapobench   文件: AuthenticatedSession.java
@Override
protected void setClientState(HttpState state) {
  super.setClientState(state);
  Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
  state.setCredentials(new AuthScope("localhost", port, AuthScope.ANY_REALM), defaultcreds);
}
 
源代码27 项目: cosmic   文件: HttpTemplateDownloader.java
public HttpTemplateDownloader(final StorageLayer storageLayer, final String downloadUrl, final String toDir, final DownloadCompleteCallback callback,
                              final long maxTemplateSizeInBytes, final String user, final String password, final Proxy proxy, final ResourceType resourceType) {
    this._storage = storageLayer;
    this.downloadUrl = downloadUrl;
    setToDir(toDir);
    this.status = TemplateDownloadStatus.NOT_STARTED;
    this.resourceType = resourceType;
    this.maxTemplateSizeInBytes = maxTemplateSizeInBytes;

    this.totalBytes = 0;
    this.client = new HttpClient(s_httpClientManager);

    this.myretryhandler = (method, exception, executionCount) -> {
        if (executionCount >= 2) {
            // Do not retry if over max retry count
            return false;
        }
        if (exception instanceof NoHttpResponseException) {
            // Retry if the server dropped connection on us
            return true;
        }
        if (!method.isRequestSent()) {
            // Retry if the request has not been sent fully or
            // if it's OK to retry methods that have been sent
            return true;
        }
        // otherwise do not retry
        return false;
    };

    try {
        this.request = new GetMethod(downloadUrl);
        this.request.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, this.myretryhandler);
        this.completionCallback = callback;
        this.request.setFollowRedirects(true);

        final File f = File.createTempFile("dnld", "tmp_", new File(toDir));

        if (this._storage != null) {
            this._storage.setWorldReadableAndWriteable(f);
        }

        this.toFile = f.getAbsolutePath();
        final Pair<String, Integer> hostAndPort = UriUtils.validateUrl(downloadUrl);

        if (proxy != null) {
            this.client.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());
            if (proxy.getUserName() != null) {
                final Credentials proxyCreds = new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword());
                this.client.getState().setProxyCredentials(AuthScope.ANY, proxyCreds);
            }
        }
        if (user != null && password != null) {
            this.client.getParams().setAuthenticationPreemptive(true);
            final Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
            this.client.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
            s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
        } else {
            s_logger.info("No credentials configured for host=" + hostAndPort.first() + ":" + hostAndPort.second());
        }
    } catch (final IllegalArgumentException iae) {
        this.errorString = iae.getMessage();
        this.status = TemplateDownloadStatus.UNRECOVERABLE_ERROR;
        this.inited = false;
    } catch (final Exception ex) {
        this.errorString = "Unable to start download -- check url? ";
        this.status = TemplateDownloadStatus.UNRECOVERABLE_ERROR;
        s_logger.warn("Exception in constructor -- " + ex.toString());
    }
}
 
源代码28 项目: development   文件: BasicAuthWSDLLocator.java
private InputSource createInputSource(String url) throws IOException {
    final HttpClient client = new HttpClient();
    final String proxyHost = System.getProperty("http.proxyHost");
    final String proxyPort = System.getProperty("http.proxyPort", "80");
    if (proxyHost != null && proxyHost.trim().length() > 0) {
        try {
            client.getHostConfiguration().setProxy(proxyHost.trim(),
                    Integer.parseInt(proxyPort));
        } catch (NumberFormatException e) {
            logger.logError(Log4jLogger.SYSTEM_LOG, e,
                    LogMessageIdentifier.ERROR_USE_PROXY_DEFINITION_FAILED);
        }
    }

    // Set credentials if specified:
    URL targetURL = new URL(url);
    if (userName != null && userName.length() > 0) {
        client.getParams().setAuthenticationPreemptive(true);
        final Credentials credentials = new UsernamePasswordCredentials(
                userName, password);
        client.getState().setCredentials(
                new AuthScope(targetURL.getHost(), targetURL.getPort(),
                        AuthScope.ANY_REALM), credentials);
    }

    // Retrieve content:
    // opening a local resource isn't supported by apache
    // instead open stream directly
    if (targetURL.getProtocol().startsWith("file")) {
        in = targetURL.openStream();
        return new InputSource(in);
    }
    final GetMethod method = new GetMethod(url);
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    in = method.getResponseBodyAsStream();
    return new InputSource(in);
}
 
/**
 * Produces Negotiate authorization string based on token created by
 * processChallenge.
 *
 * @param credentials Never used be the Negotiate scheme but must be provided to
 * satisfy common-httpclient API. Credentials from JAAS will be used insted.
 * @param method The method being authenticated
 *
 * @throws org.apache.commons.httpclient.auth.AuthenticationException if authorization string cannot
 *   be generated due to an authentication failure
 *
 * @return an Negotiate authorization string
 *
 * @since 3.0
 */
public synchronized String authenticate(
        Credentials credentials,
        HttpMethod method
) throws AuthenticationException {
    LOG.info("enter CustomNegotiateScheme.authenticate(Credentials, HttpMethod)");

    if (state == UNINITIATED) {
        throw new IllegalStateException(
                "Negotiation authentication process has not been initiated");
    }

    try {
        try {
            if (context == null) {
                LOG.info("host: " + method.getURI().getHost());
                init(method.getURI().getHost(), (UsernamePasswordCredentials) credentials);
            }
        } catch (org.apache.commons.httpclient.URIException urie) {
            LOG.severe(urie.getMessage());
            state = FAILED;
            throw new AuthenticationException(urie.getMessage());
        }

        // HTTP 1.1 issue:
        // Mutual auth will never complete do to 200 insted of 401 in
        // return from server. "state" will never reach ESTABLISHED
        // but it works anyway

        //            token = context.initSecContext(token, 0, token.length);
        LOG.info("got token, sending " + token.length + " to server");
    } catch (GSSException gsse) {
        LOG.severe(gsse.getMessage());
        state = FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) {
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        }
        if (gsse.getMajor() == GSSException.NO_CRED) {
            throw new CredentialsNotAvailableException(gsse.getMessage(), gsse);
        }
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
                || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                || gsse.getMajor() == GSSException.OLD_TOKEN) {
            throw new AuthChallengeException(gsse.getMessage(), gsse);
        }
        // other error
        throw new AuthenticationException(gsse.getMessage());
    }
    return "Negotiate " + new String(new Base64(-1).encode(token));
}
 
源代码30 项目: elasticsearch-hadoop   文件: EsApiKeyAuthScheme.java
/**
 * Returns the text to send via the Authenticate header on the next request.
 */
@Override
public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
    return authenticate(credentials);
}
 
 类方法
 同包方法