List of usage examples for org.apache.http.protocol HttpContext getAttribute
Object getAttribute(String str);
From source file:com.adrup.saldo.bank.lf.LfBankManager.java
@Override public Map<AccountHashKey, RemoteAccount> getAccounts(Map<AccountHashKey, RemoteAccount> accounts) throws BankException { Log.d(TAG, "getAccounts()"); HttpClient httpClient = new SaldoHttpClient(mContext); try {/*from www . ja v a 2s .c om*/ // get login page Log.d(TAG, "getting login page"); HttpContext httpContext = new BasicHttpContext(); String res = HttpHelper.get(httpClient, LOGIN_URL, httpContext); HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String action = currentHost.toURI() + currentReq.getURI(); Log.e(TAG, "action=" + action); Matcher matcher = Pattern.compile(VIEWSTATE_REGEX).matcher(res); if (!matcher.find()) { Log.e(TAG, "No viewstate match."); Log.d(TAG, res); throw new LfBankException("No viewState match."); } String viewState = matcher.group(1); Log.d(TAG, "viewState= " + viewState); matcher = Pattern.compile(EVENTVALIDATION_REGEX).matcher(res); if (!matcher.find()) { Log.e(TAG, "No eventvalidation match."); Log.d(TAG, res); throw new LfBankException("No eventValidation match."); } String eventValidation = matcher.group(1); Log.d(TAG, "eventValidation= " + eventValidation); // do login post List<NameValuePair> parameters = new ArrayList<NameValuePair>(3); parameters.add(new BasicNameValuePair("__LASTFOCUS", "")); parameters.add(new BasicNameValuePair("__EVENTTARGET", "")); parameters.add(new BasicNameValuePair("__EVENTARGUMENT", "")); parameters.add(new BasicNameValuePair(VIEWSTATE_PARAM, viewState)); parameters.add(new BasicNameValuePair("selMechanism", "PIN-kod")); parameters.add(new BasicNameValuePair(USER_PARAM, mBankLogin.getUsername())); parameters.add(new BasicNameValuePair(PASS_PARAM, mBankLogin.getPassword())); parameters.add(new BasicNameValuePair("btnLogIn.x", "39")); parameters.add(new BasicNameValuePair("btnLogIn.y", "11")); parameters.add(new BasicNameValuePair(EVENTVALIDATION_PARAM, eventValidation)); Log.d(TAG, "logging in..."); res = HttpHelper.post(httpClient, action, parameters); if (res.contains("Felaktig inloggning")) { Log.d(TAG, "auth fail"); throw new AuthenticationException("auth fail"); } Log.d(TAG, "getting accountsUrl"); // token matcher = Pattern.compile(TOKEN_REGEX).matcher(res); if (!matcher.find()) { Log.e(TAG, "No token match."); Log.d(TAG, res); throw new LfBankException("No token match."); } String token = matcher.group(1); Log.d(TAG, "token= " + token); // accountsUrl matcher = Pattern.compile(ACCOUNTS_URL_REGEX).matcher(res); if (!matcher.find()) { Log.e(TAG, "No accountsUrl match."); Log.d(TAG, res); throw new LfBankException("No accountsUrl match."); } String accountsUrl = Html.fromHtml(matcher.group(1)).toString(); accountsUrl += "&_token=" + token; Log.d(TAG, "tokenized accountsUrl= " + accountsUrl); // get accounts page Log.d(TAG, "fetching accounts"); res = HttpHelper.get(httpClient, accountsUrl); matcher = Pattern.compile(ACCOUNTS_REGEX).matcher(res); int remoteId = 1; int count = 0; while (matcher.find()) { count++; int groupCount = matcher.groupCount(); for (int i = 1; i <= groupCount; i++) { Log.d(TAG, i + ":" + matcher.group(i)); } if (groupCount < 2) { throw new BankException("Pattern match issue: groupCount < 2"); } int ordinal = remoteId; String name = Html.fromHtml(matcher.group(1)).toString(); long balance = Long.parseLong(matcher.group(2).replaceAll("\\,|\\.| ", "")) / 100; accounts.put(new AccountHashKey(String.valueOf(remoteId), mBankLogin.getId()), new Account(String.valueOf(remoteId), mBankLogin.getId(), ordinal, name, balance)); remoteId++; } if (count == 0) { Log.d(TAG, "no accounts added"); Log.d(TAG, res); } } catch (IOException e) { Log.e(TAG, e.getMessage(), e); throw new LfBankException(e.getMessage(), e); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); throw new LfBankException(e.getMessage(), e); } finally { httpClient.getConnectionManager().shutdown(); } return accounts; }
From source file:org.pepstock.jem.node.https.SubmitHandler.java
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { // extracts the host String host = context.getAttribute(JOB_SUBMIT_IP_ADDRESS_KEY).toString(); // gets HTTP method (uses locale ENGLISH to be sure to have POST) String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); // if NOT post, exception! if (!method.equals(POST)) { LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host); throw new MethodNotSupportedException( NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host)); }/*from www .ja v a2s .c o m*/ // gets the URI or the request String target = request.getRequestLine().getUri(); // if is not the same , accepts, exception! if (!target.equalsIgnoreCase(DEFAULT_ACTION)) { LogAppl.getInstance().emit(NodeMessage.JEMC285W, target, host); throw new MethodNotSupportedException( NodeMessage.JEMC285W.toMessage().getFormattedMessage(target, host)); } // checks the HTTP request if (request instanceof HttpEntityEnclosingRequest) { // gets the entity of the request HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); // gets the body in string format String result = EntityUtils.toString(entity, CharSet.DEFAULT); // reads the first line, // with all URL encoded variables String vars = StringUtils.substringBefore(result, DELIMITER); // loads a map with all parms Map<String, String> parms = loadParametersMap(URLEncodedUtils.parse(vars, CharSet.DEFAULT)); // gets the USER String user = parms.get(SubmitParameters.USER.getName()); // if JEM is configured to have the Socket Interceptor on HC // the client MUST provide a SIGNATURE (using own private key) with // the user crypted inside if (Main.getHazelcastConfig().getNetworkConfig().getSocketInterceptorConfig().isEnabled()) { // checks if there is the signature if (parms.containsKey(USER_SIGNATURE_KEY)) { // gets the signature in HEX format String cryptedUserString = parms.get(USER_SIGNATURE_KEY); // gets keys stores KeyStoresInfo keyStoresInfo = KeyStoreUtil.getKeyStoresInfo(); try { // extracts from the USER key store the PUBLIC KEY (upload by UI) for the user PublicKey publicKey = KeysUtil.getPublicKeyByAlias(keyStoresInfo.getUserKeystoreInfo(), user); // creates tne SIGNATURE verifying steps Signature signature = Signature.getInstance("SHA256withRSA"); // sets public key signature.initVerify(publicKey); // sets content to check. It uses USER signature.update(user.getBytes(CharSet.DEFAULT_CHARSET_NAME)); // checks if is verified if (!signature.verify(Hex.decodeHex(cryptedUserString.toCharArray()))) { // if not, log and EXCEPTION LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host); throw new HttpException( NodeMessage.JEMC286W.toMessage().getFormattedMessage(user, host)); } } catch (MessageException e) { LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host); throw new ProtocolException(e.getMessage(), e); } catch (KeyException e) { throw new ProtocolException(e.getMessage(), e); } catch (DecoderException e) { throw new ProtocolException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new ProtocolException(e.getMessage(), e); } catch (SignatureException e) { throw new ProtocolException(e.getMessage(), e); } } else { LogAppl.getInstance().emit(NodeMessage.JEMC287W, user, host); // if here, the signature is missing throw new HttpException(NodeMessage.JEMC287W.toMessage().getFormattedMessage(user, host)); } } // gets JEM environemnt name and its passwrod String env = parms.get(SubmitParameters.ENV.getName()); String password = parms.get(SubmitParameters.PASSWORD.getName()); // checks if password and env are same, // comparing with the HC configuration if (!Main.getHazelcastConfig().getGroupConfig().getName().equalsIgnoreCase(env) || !Main.getHazelcastConfig().getGroupConfig().getPassword().equalsIgnoreCase(password)) { // if not equals, exception LogAppl.getInstance().emit(NodeMessage.JEMC288W, host); throw new HttpException(NodeMessage.JEMC288W.toMessage().getFormattedMessage(host)); } // reads teh second row of the body, with the JCL String jcl = StringUtils.substringAfter(result, DELIMITER); // sets the entity to send back, submitting the job. // it returns the JOBID StringEntity resultEntity = new StringEntity(submit(jcl, user, host, parms), ContentType.create(RESPONSE_MIME_TYPE, CharSet.DEFAULT_CHARSET_NAME)); // sets STATUS code and entity response.setStatusCode(HttpStatus.SC_OK); response.setEntity(resultEntity); } else { // if here, the request is not correct LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host); throw new MethodNotSupportedException( NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host)); } }
From source file:com.manning.androidhacks.hack023.net.FollowPostRedirectHandler.java
/** * HttpClient is compliant with the requirements of the HTTP specification * (RFC 2616) and does not automatically redirect other methods than GET and * HEAD. We have to override this method to automatically follow redirects * when using the POST method.// w ww.j a v a 2 s . c o m */ @Override public boolean isRedirectRequested(final HttpResponse response, final HttpContext context) { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); String method = request.getRequestLine().getMethod(); return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME) || method.equalsIgnoreCase(HttpPost.METHOD_NAME); case HttpStatus.SC_SEE_OTHER: return true; default: return false; } }
From source file:com.normalexception.app.rx8club.httpclient.RetryHandler.java
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // retry a max of MAX_RETRY times if (executionCount >= MAX_RETRY) { Log.d(TAG, "Max Retries Exceeded"); return false; }//from w ww . j a va 2 s . co m if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us Log.d(TAG, "Server dropped request, retrying"); return true; } Boolean b = (Boolean) context.getAttribute(HttpCoreContext.HTTP_REQ_SENT); boolean sent = (b != null && b.booleanValue()); if (!sent) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent Log.d(TAG, "Request not fully sent, retrying"); return true; } // otherwise do not retry return false; }
From source file:pl.llp.aircasting.util.http.HttpBuilder.java
private HttpRequestInterceptor preemptiveAuth() { return new HttpRequestInterceptor() { @Override//from w ww . ja v a 2 s . c o m public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { AuthState authState = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE); Credentials credentials; if (useLogin) { credentials = new UsernamePasswordCredentials(login, password); } else { credentials = new UsernamePasswordCredentials(settingsHelper.getAuthToken(), "X"); } authState.setAuthScope(AuthScope.ANY); authState.setAuthScheme(new BasicScheme()); authState.setCredentials(credentials); } }; }
From source file:com.googlecode.noweco.webmail.httpclient.UnsecureResponseProcessCookies.java
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP request may not be null"); }/*from w ww.j a va2 s . c o m*/ if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } // Obtain actual CookieSpec instance CookieSpec cookieSpec = (CookieSpec) context.getAttribute(ClientContext.COOKIE_SPEC); if (cookieSpec == null) { this.log.debug("Cookie spec not specified in HTTP context"); return; } // Obtain cookie store CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE); if (cookieStore == null) { this.log.debug("Cookie store not specified in HTTP context"); return; } // Obtain actual CookieOrigin instance CookieOrigin cookieOrigin = (CookieOrigin) context.getAttribute(ClientContext.COOKIE_ORIGIN); if (cookieOrigin == null) { this.log.debug("Cookie origin not specified in HTTP context"); return; } HeaderIterator it = response.headerIterator(SM.SET_COOKIE); processCookies(it, cookieSpec, cookieOrigin, cookieStore); // see if the cookie spec supports cookie versioning. if (cookieSpec.getVersion() > 0) { // process set-cookie2 headers. // Cookie2 will replace equivalent Cookie instances it = response.headerIterator(SM.SET_COOKIE2); processCookies(it, cookieSpec, cookieOrigin, cookieStore); } }
From source file:org.xwiki.android.test.utils.xmlrpc.RestClient.java
/** * set user credentials with manually developed preemtive Auth *///from w ww . j av a2s.co m private void setCredentials() { // Setting preemtiveAuth manually since org.apache.http does not support it HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; client.addRequestInterceptor(preemptiveAuth, 0); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds); }
From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java
/** * Set up http client with credentials/*from ww w . j a va2 s. c o m*/ * @return Http client * @throws MojoExecutionException Mojo execution exception */ protected final CloseableHttpClient getHttpClient() throws MojoExecutionException { try { URI crxUri = new URI(getCrxPackageManagerUrl()); final AuthScope authScope = new AuthScope(crxUri.getHost(), crxUri.getPort()); final Credentials credentials = new UsernamePasswordCredentials(this.userId, this.password); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(authScope, credentials); HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { // enable preemptive authentication AuthState authState = (AuthState) context .getAttribute(HttpClientContext.TARGET_AUTH_STATE); authState.update(new BasicScheme(), credentials); } }); if (this.relaxedSSLCheck) { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); } catch (URISyntaxException ex) { throw new MojoExecutionException("Invalid url: " + getCrxPackageManagerUrl(), ex); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex) { throw new MojoExecutionException("Could not set relaxedSSLCheck", ex); } }
From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java
/** {@inheritDoc} */ public void closed(final NHttpClientConnection conn) { System.out.println(conn + " [proxy->origin] conn closed"); HttpContext context = conn.getContext(); ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB); if (proxyTask != null) { // TODO: change it to ReentrantLock synchronized (proxyTask) { proxyTask.setOriginState(ConnState.CLOSED); if (!proxyTask.getResponse().isCommitted()) { proxyTask.getCompletion().run(); }/* w w w .j a v a 2s.c o m*/ } } }