List of usage examples for org.apache.http.auth UsernamePasswordCredentials getUserName
public String getUserName()
From source file:com.vuze.android.remote.rpc.RestJsonClient.java
public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers, UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException { long readTime = 0; long connSetupTime = 0; long connTime = 0; int bytesRead = 0; if (DEBUG_DETAILED) { Log.d(TAG, id + "] Execute " + url); }//from www .ja va2s . c o m long now = System.currentTimeMillis(); long then; Map<?, ?> json = Collections.EMPTY_MAP; try { URI uri = new URI(url); int port = uri.getPort(); BasicHttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote"); DefaultHttpClient httpclient; if ("https".equals(uri.getScheme())) { httpclient = MySSLSocketFactory.getNewHttpClient(port); } else { httpclient = new DefaultHttpClient(basicHttpParams); } //AndroidHttpClient.newInstance("Vuze Android Remote"); // This doesn't set the "Authorization" header!? httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds); // Prepare a request object HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException if (creds != null) { byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes(); String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length); httpRequest.setHeader("Authorization", "Basic " + encoding); } if (jsonPost != null) { HttpPost post = (HttpPost) httpRequest; String postString = JSONUtils.encodeToJSON(jsonPost); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "] Post: " + postString); } AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getCompressedEntity(postString) : new StringEntity(postString); post.setEntity(entity); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { setupRequestFroyo(httpRequest); } if (headers != null) { for (Header header : headers) { httpRequest.setHeader(header); } } // Execute the request HttpResponse response; then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connSetupTime = (then - now); now = then; } httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException e, int i, HttpContext httpContext) { if (i < 2) { return true; } return false; } }); response = httpclient.execute(httpRequest); then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connTime = (then - now); now = then; } HttpEntity entity = response.getEntity(); // XXX STATUSCODE! StatusLine statusLine = response.getStatusLine(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "StatusCode: " + statusLine.getStatusCode()); } if (entity != null) { long contentLength = entity.getContentLength(); if (contentLength >= Integer.MAX_VALUE - 2) { throw new RPCException("JSON response too large"); } // A Simple JSON Response Read InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getUngzippedContent(entity) : entity.getContent(); InputStreamReader isr = new InputStreamReader(instream, "utf8"); StringBuilder sb = null; BufferedReader br = null; // JSONReader is 10x slower, plus I get more OOM errors.. :( // final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false // : DEFAULT_USE_STRINGBUFFER; final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER; if (useStringBuffer) { // Setting capacity saves StringBuffer from going through many // enlargeBuffers, and hopefully allows toString to not make a copy sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512); } else { if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "Using BR. ContentLength = " + contentLength); } br = new BufferedReader(isr, 8192); br.mark(32767); } try { // 9775 files on Nexus 7 (~2,258,731 bytes) // fastjson 1.1.46 (String) : 527- 624ms // fastjson 1.1.39 (String) : 924-1054ms // fastjson 1.1.39 (StringBuilder): 1227-1463ms // fastjson 1.1.39 (BR) : 2233-2260ms // fastjson 1.1.39 (isr) : 2312ms // GSON 2.2.4 (String) : 1539-1760ms // GSON 2.2.4 (BufferedReader) : 2646-3060ms // JSON-SMART 1.3.1 (String) : 572- 744ms (OOMs more often than fastjson) if (useStringBuffer) { char c[] = new char[8192]; while (true) { int read = isr.read(c); if (read < 0) { break; } sb.append(c, 0, read); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); if (DEBUG_DETAILED) { if (sb.length() > 2000) { Log.d(TAG, id + "] " + sb.substring(0, 2000) + "..."); } else { Log.d(TAG, id + "] " + sb.toString()); } } bytesRead = sb.length(); readTime = (then - now); now = then; } json = JSONUtils.decodeJSON(sb.toString()); //json = JSONUtilsGSON.decodeJSON(sb.toString()); } else { //json = JSONUtils.decodeJSON(isr); json = JSONUtils.decodeJSON(br); //json = JSONUtilsGSON.decodeJSON(br); } } catch (Exception pe) { // StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 409) { throw new RPCException(response, "409"); } try { String line; if (useStringBuffer) { line = sb.subSequence(0, Math.min(128, sb.length())).toString(); } else { br.reset(); line = br.readLine().trim(); } isr.close(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "]line: " + line); } Header contentType = entity.getContentType(); if (line.startsWith("<") || line.contains("<html") || (contentType != null && contentType.getValue().startsWith("text/html"))) { // TODO: use android strings.xml throw new RPCException(response, "Could not retrieve remote client location information. The most common cause is being on a guest wifi that requires login before using the internet."); } } catch (IOException ignore) { } Log.e(TAG, id, pe); if (statusLine != null) { String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n" + pe.getMessage(); throw new RPCException(msg, pe); } throw new RPCException(pe); } finally { closeOnNewThread(useStringBuffer ? isr : br); } if (AndroidUtils.DEBUG_RPC) { // Log.d(TAG, id + "]JSON Result: " + json); } } } catch (RPCException e) { throw e; } catch (Throwable e) { Log.e(TAG, id, e); throw new RPCException(e); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime + "ms, parsed in " + (then - now) + "ms"); } return json; }
From source file:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java
/** * This method allows to propagate the authentication information from the current object. * * @param commonsDataLoader//from ww w . j a v a 2 s. c o m * {@code CommonsDataLoader} to be initialized with authentication information */ public void propagateAuthentication(final CommonsDataLoader commonsDataLoader) { for (final Map.Entry<HttpHost, UsernamePasswordCredentials> credentialsEntry : authenticationMap .entrySet()) { final HttpHost httpHost = credentialsEntry.getKey(); final UsernamePasswordCredentials credentials = credentialsEntry.getValue(); commonsDataLoader.addAuthentication(httpHost.getHostName(), httpHost.getPort(), httpHost.getSchemeName(), credentials.getUserName(), credentials.getPassword()); } }
From source file:com.mnxfst.testing.activities.http.AbstractHTTPRequestActivity.java
/** * @see com.mnxfst.testing.activities.TSPlanActivity#initialize(com.mnxfst.testing.plan.config.TSPlanConfigOption) *//* w w w . jav a2s . com*/ public void initialize(TSPlanConfigOption cfg) throws TSPlanActivityExecutionException { if (cfg == null) throw new TSPlanActivityExecutionException("Failed to initialize activity '" + this.getClass().getName() + "' due to missing configuration options"); ///////////////////////////////////////////////////////////////////////////////////////// // fetch scheme, host, port and path this.scheme = (String) cfg.getOption(CFG_OPT_SCHEME); if (this.scheme == null || this.scheme.isEmpty()) throw new TSPlanActivityExecutionException( "Required config option '" + CFG_OPT_SCHEME + "' missing for activity '" + getName() + "'"); this.host = (String) cfg.getOption(CFG_OPT_HOST); if (this.host == null || this.host.isEmpty()) throw new TSPlanActivityExecutionException( "Requied config option '" + CFG_OPT_HOST + "' missing for activity '" + getName() + "'"); String portStr = (String) cfg.getOption(CFG_OPT_PORT); if (portStr != null && !portStr.isEmpty()) { try { this.port = Integer.parseInt(portStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_PORT + "' for activity '" + getName() + "'"); } } // fetch username and password this.basicAuthUsername = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_USERNAME); this.basicAuthPassword = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PASSWORD); this.basicAuthHostScope = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_HOST_SCOPE); String authPortScopeStr = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PORT_SCOPE); if (authPortScopeStr != null && !authPortScopeStr.trim().isEmpty()) { try { this.basicAuthPortScope = Integer.parseInt(authPortScopeStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_BASIC_AUTH_PORT_SCOPE + "' for activity '" + getName() + "'"); } } if (this.port <= 0) this.port = 80; this.path = (String) cfg.getOption(CFG_OPT_PATH); if (this.path == null || this.path.isEmpty()) this.path = "/"; String maxConnStr = (String) cfg.getOption(CFG_OPT_MAX_CONNECTIONS); if (maxConnStr != null && !maxConnStr.isEmpty()) { try { this.maxConnections = Integer.parseInt(maxConnStr); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_MAX_CONNECTIONS + "' for activity '" + getName() + "'"); } } // initialize http host and context this.httpHost = new HttpHost(this.host, this.port); // URI builder try { // query parameters List<NameValuePair> qParams = new ArrayList<NameValuePair>(); for (String key : cfg.getOptions().keySet()) { if (key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) { String value = (String) cfg.getOption(key); String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length()); qParams.add(new BasicNameValuePair(requestParameterName, value)); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", requestParameter=" + requestParameterName + ", value=" + value + "]"); } } this.destinationURI = URIUtils.createURI(this.scheme, this.host, this.port, this.path, URLEncodedUtils.format(qParams, this.contentChartset), null); // TODO handle post values } catch (URISyntaxException e) { throw new TSPlanActivityExecutionException("Failed to initialize uri for [scheme=" + this.scheme + ", host=" + this.host + ", port=" + this.port + ", path=" + this.path + "]"); } httpRequestContext.setAttribute(ExecutionContext.HTTP_CONNECTION, clientConnection); httpRequestContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", maxConnections=" + maxConnections + ", scheme=" + scheme + ", host=" + host + ", port=" + port + ", path=" + path + "]"); ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // protocol settings this.userAgent = (String) cfg.getOption(CFG_OPT_USER_AGENT); if (this.userAgent == null || this.userAgent.isEmpty()) this.userAgent = "ptest-server"; String protocolVersion = (String) cfg.getOption(CFG_OPT_HTTP_PROTOCOL_VERSION); if (protocolVersion != null && !protocolVersion.isEmpty()) { if (protocolVersion.equalsIgnoreCase("0.9")) this.httpVersion = HttpVersion.HTTP_0_9; else if (protocolVersion.equalsIgnoreCase("1.0")) this.httpVersion = HttpVersion.HTTP_1_0; else if (protocolVersion.equalsIgnoreCase("1.1")) this.httpVersion = HttpVersion.HTTP_1_1; else throw new TSPlanActivityExecutionException("Failed to parse http protocol version '" + protocolVersion + "'. Valid value: 0.9, 1.0 and 1.1"); } this.contentChartset = (String) cfg.getOption(CFG_OPT_CONTENT_CHARSET); if (this.contentChartset == null || this.contentChartset.isEmpty()) this.contentChartset = "UTF-8"; String expectContStr = (String) cfg.getOption(CFG_OPT_EXPECT_CONTINUE); if (expectContStr != null && !expectContStr.isEmpty()) { this.expectContinue = Boolean.parseBoolean(expectContStr.trim()); } HttpProtocolParams.setUserAgent(httpParameters, userAgent); HttpProtocolParams.setVersion(httpParameters, httpVersion); HttpProtocolParams.setContentCharset(httpParameters, contentChartset); HttpProtocolParams.setUseExpectContinue(httpParameters, expectContinue); String httpProcStr = (String) cfg.getOption(CFG_OPT_HTTP_REQUEST_PROCESSORS); if (httpProcStr != null && !httpProcStr.isEmpty()) { List<HttpRequestInterceptor> interceptors = new ArrayList<HttpRequestInterceptor>(); String[] procClasses = httpProcStr.split(","); if (procClasses != null && procClasses.length > 0) { for (int i = 0; i < procClasses.length; i++) { try { Class<?> clazz = Class.forName(procClasses[i]); interceptors.add((HttpRequestInterceptor) clazz.newInstance()); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", httpRequestInterceptor=" + procClasses[i] + "]"); } catch (Exception e) { throw new TSPlanActivityExecutionException("Failed to instantiate http interceptor '" + procClasses[i] + "' for activity '" + getName() + "'. Error: " + e.getMessage()); } } } this.httpRequestResponseProcessor = new ImmutableHttpProcessor( (HttpRequestInterceptor[]) interceptors.toArray(EMPTY_HTTP_REQUEST_INTERCEPTOR_ARRAY)); this.hasRequestResponseProcessors = true; } this.method = (String) cfg.getOption(CFG_OPT_METHOD); if (method == null || method.isEmpty()) this.method = "GET"; if (!method.equalsIgnoreCase("get") && !method.equalsIgnoreCase("post")) throw new TSPlanActivityExecutionException( "Invalid method '" + method + "' found for activity '" + getName() + "'"); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", method=" + method + ", user-agent=" + userAgent + ", httpVersion=" + httpVersion + ", contentCharset=" + contentChartset + ", expectContinue=" + expectContinue + "]"); ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // fetch proxy settings this.proxyUrl = (String) cfg.getOption(CFG_OPT_PROXY_URL); String proxyPortStr = (String) cfg.getOption(CFG_OPT_PROXY_PORT); if (proxyPortStr != null && !proxyPortStr.isEmpty()) { try { this.proxyPort = Integer.parseInt(proxyPortStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_PROXY_PORT + "' for activity '" + getName() + "'"); } } this.proxyUser = (String) cfg.getOption(CFG_OPT_PROXY_USER); this.proxyPassword = (String) cfg.getOption(CFG_OPT_PROXY_PASSWORD); if (proxyUrl != null && !proxyUrl.isEmpty()) { if (proxyPort > 0) this.proxyHost = new HttpHost(proxyUrl, proxyPort); else this.proxyHost = new HttpHost(proxyUrl); } if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", proxyUrl=" + proxyUrl + ", proxyPort=" + proxyPort + ", proxyUser=" + proxyUser + "]"); ///////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////// // // fetch request parameters // // // unfortunately we must step through the whole set of keys ... // for(String key : cfg.getOptions().keySet()) { // if(key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) { // String value = (String)cfg.getOption(key); // String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length()); // httpParameters.setParameter(requestParameterName, value); // if(logger.isDebugEnabled()) // logger.debug("activity[name="+getName()+", id="+getId()+", requestParameter="+requestParameterName+", value="+value+"]"); // } // } // // ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // configure scheme registry and initialize http client SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", registeredSchemes={http, https}]"); ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager( schemeRegistry); threadSafeClientConnectionManager.setMaxTotal(maxConnections); threadSafeClientConnectionManager.setDefaultMaxPerRoute(maxConnections); this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager); if (this.basicAuthUsername != null && !this.basicAuthUsername.trim().isEmpty() && this.basicAuthPassword != null && !this.basicAuthPassword.trim().isEmpty()) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.basicAuthUsername, this.basicAuthPassword); AuthScope authScope = null; if (basicAuthHostScope != null && !basicAuthHostScope.isEmpty() && basicAuthPortScope > 0) { authScope = new AuthScope(basicAuthHostScope, basicAuthPortScope); } else { authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); } this.httpClient.getCredentialsProvider().setCredentials(authScope, creds); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", credentials=(" + creds.getUserName() + ", " + creds.getPassword() + "), authScope=(" + authScope.getHost() + ":" + authScope.getPort() + ")]"); } if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", threadSafeClientConnectionManager=initialized]"); }
From source file:org.artifactory.bintray.BintrayServiceImpl.java
@Override public List<Repo> getReposToDeploy(@Nullable Map<String, String> headersMap) throws IOException, BintrayException { UsernamePasswordCredentials creds = getCurrentUserBintrayCreds(); String requestUrl = getBaseBintrayApiUrl() + PATH_REPOS + "/" + creds.getUserName(); InputStream responseStream = null; try {//from w w w .j a v a 2s . c o m responseStream = executeGet(requestUrl, creds, headersMap); if (responseStream != null) { return JacksonReader.streamAsValueTypeReference(responseStream, new TypeReference<List<Repo>>() { }); } } finally { IOUtils.closeQuietly(responseStream); } return null; }