List of usage examples for org.apache.http.message BufferedHeader BufferedHeader
public BufferedHeader(CharArrayBuffer charArrayBuffer) throws ParseException
From source file:io.cloudslang.content.httpclient.build.HeadersBuilder.java
public List<Header> buildHeaders() { ArrayList<Header> headersArr = new ArrayList<>(); if (!StringUtils.isEmpty(headers)) { BufferedReader in = new BufferedReader(new StringReader(headers)); String str;/*from www .ja v a2 s . c o m*/ try { while ((str = in.readLine()) != null) { CharArrayBuffer charArrayBuffer = new CharArrayBuffer(str.length()); charArrayBuffer.append(str); headersArr.add(new BufferedHeader(charArrayBuffer)); } } catch (IOException e) { throw new IllegalArgumentException(e); } } if (entityContentType != null) { headersArr.add(entityContentType); } else if (contentType != null && !contentType.toString().isEmpty()) { headersArr.add(new BasicHeader("Content-Type", contentType.toString())); } return headersArr; }
From source file:org.apache.axis2.transport.http.server.ResponseSessionCookie.java
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); }/* ww w .j a va 2 s. c om*/ if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } String sessionCookie = null; MessageContext msgctx = (MessageContext) context.getAttribute(AxisParams.MESSAGE_CONTEXT); if (msgctx != null) { sessionCookie = (String) msgctx.getProperty(HTTPConstants.COOKIE_STRING); } if (sessionCookie == null) { sessionCookie = (String) context.getAttribute(HTTPConstants.COOKIE_STRING); } if (sessionCookie != null) { // Generate Netscape style cookie header CharArrayBuffer buffer1 = new CharArrayBuffer(sessionCookie.length() + 40); buffer1.append(HTTPConstants.HEADER_SET_COOKIE); buffer1.append(": "); buffer1.append(Constants.SESSION_COOKIE_JSESSIONID); buffer1.append("="); buffer1.append(sessionCookie); response.addHeader(new BufferedHeader(buffer1)); // Generate RFC2965 cookie2 header CharArrayBuffer buffer2 = new CharArrayBuffer(sessionCookie.length() + 50); buffer2.append(HTTPConstants.HEADER_SET_COOKIE2); buffer2.append(": "); buffer2.append(Constants.SESSION_COOKIE_JSESSIONID); buffer2.append("="); buffer2.append(sessionCookie); buffer2.append("; "); int port = response.getParams().getIntParameter(AxisParams.LISTENER_PORT, 0); if (port > 0) { buffer2.append("Port=\""); buffer2.append(Integer.toString(port)); buffer2.append("\"; "); } buffer2.append("Version=1"); response.addHeader(new BufferedHeader(buffer2)); } }
From source file:tv.arte.resteventapi.core.clients.RestEventApiRestClient.java
/** * Executes the REST request described by the {@link RestEvent} * //from ww w . j ava 2 s . c o m * @param restEvent The {@link RestEvent} to process * @return A result of the execution * @throws RestEventApiRuntimeException In case of non managed errors */ public static RestClientExecutionResult execute(final RestEvent restEvent) throws RestEventApiRuntimeException { RestClientExecutionResult result = new RestClientExecutionResult(); String url = restEvent.getUrl(); CloseableHttpClient client = null; HttpUriRequest request = null; Integer responseCode = null; try { //Request custom configs RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(restEvent.getTimeout()); requestBuilder = requestBuilder.setConnectionRequestTimeout(restEvent.getTimeout()); client = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()).build(); //Determine the method to execute switch (restEvent.getMethod()) { case GET: request = new HttpGet(url); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDelete(url); break; case PATCH: request = new HttpPatch(url); break; case HEAD: request = new HttpHead(url); break; default: throw new RestEventApiRuntimeException("RestEventAPI unsupported HTTP method"); } //Set the body for eligible methods if (restEvent.getBody() != null && request instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(restEvent.getBody())); } //Set headers if (CollectionUtils.isNotEmpty(restEvent.getHeaders())) { for (String strHeader : restEvent.getHeaders()) { CharArrayBuffer headerBuffer = new CharArrayBuffer(strHeader.length() + 1); headerBuffer.append(strHeader); request.addHeader(new BufferedHeader(headerBuffer)); } } HttpResponse response = client.execute(request); responseCode = response.getStatusLine().getStatusCode(); result.setState(RestClientCallState.OK); } catch (ConnectTimeoutException e) { result.setState(RestClientCallState.TIMEOUT); } catch (Exception e) { throw new RestEventApiRuntimeException("Un error occured while processing rest event", e); } finally { result.setResponseCode(responseCode); try { client.close(); } catch (Exception e2) { logger.warn("Unable to close HTTP client", e2); } } return result; }
From source file:com.androidquery.test.NTLMScheme.java
public Header authenticate(final Credentials credentials, final HttpRequest request) throws AuthenticationException { NTCredentials ntcredentials = null;//www .ja v a2 s . co m try { ntcredentials = (NTCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName()); } String response = null; if (this.state == State.CHALLENGE_RECEIVED || this.state == State.FAILED) { response = this.engine.generateType1Msg(ntcredentials.getDomain(), ntcredentials.getWorkstation()); this.state = State.MSG_TYPE1_GENERATED; } else if (this.state == State.MSG_TYPE2_RECEVIED) { response = this.engine.generateType3Msg(ntcredentials.getUserName(), ntcredentials.getPassword(), ntcredentials.getDomain(), ntcredentials.getWorkstation(), this.challenge); this.state = State.MSG_TYPE3_GENERATED; } else { throw new AuthenticationException("Unexpected state: " + this.state); } CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": NTLM "); buffer.append(response); return new BufferedHeader(buffer); }
From source file:freeipa.client.negotiation.JBossNegotiateScheme.java
/** * Produces Negotiate authorization Header 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 instead. * @param request The request being authenticated * * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure * * @return an Negotiate authorization Header */// ww w . java2 s .c o m @Override public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (state != State.CHALLENGE_RECEIVED) { throw new IllegalStateException("Negotiation authentication process has not been initiated"); } try { String key = null; if (isProxy()) { key = ExecutionContext.HTTP_PROXY_HOST; } else { key = ExecutionContext.HTTP_TARGET_HOST; } HttpHost host = (HttpHost) context.getAttribute(key); if (host == null) { throw new AuthenticationException("Authentication host is not set " + "in the execution context"); } String authServer; if (!this.stripPort && host.getPort() > 0) { authServer = host.toHostString(); } else { authServer = host.getHostName(); } System.out.println("init " + authServer); final Oid negotiationOid = new Oid(SPNEGO_OID); final GSSManager manager = GSSManager.getInstance(); final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); if (token == null) { token = new byte[0]; } token = gssContext.initSecContext(token, 0, token.length); if (token == null) { state = State.FAILED; throw new AuthenticationException("GSS security context initialization failed"); } state = State.TOKEN_GENERATED; String tokenstr = new String(base64codec.encode(token)); System.out.println("Sending response '" + tokenstr + "' back to the auth server"); CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Negotiate "); buffer.append(tokenstr); return new BufferedHeader(buffer); } catch (GSSException gsse) { state = 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 InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) throw new AuthenticationException(gsse.getMessage(), gsse); // other error throw new AuthenticationException(gsse.getMessage()); } }
From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitBrowserCompatCookieSpec.java
@Override public List<Header> formatCookies(final List<Cookie> cookies) { Collections.sort(cookies, COOKIE_COMPARATOR); final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); buffer.append(SM.COOKIE);/*from ww w. j a va 2 s .co m*/ buffer.append(": "); for (int i = 0; i < cookies.size(); i++) { final Cookie cookie = cookies.get(i); if (i > 0) { buffer.append("; "); } final String cookieName = cookie.getName(); final String cookieValue = cookie.getValue(); if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) { HtmlUnitBrowserCompatCookieHeaderValueFormatter.INSTANCE.formatHeaderElement(buffer, new BasicHeaderElement(cookieName, cookieValue), false); } else { // Netscape style cookies do not support quoted values buffer.append(cookieName); buffer.append("="); if (cookieValue != null) { buffer.append(cookieValue); } } } final List<Header> headers = new ArrayList<>(1); headers.add(new BufferedHeader(buffer)); return headers; }
From source file:org.odk.collect.android.utilities.EnhancedDigestScheme.java
/** * Creates digest-response header as defined in RFC2617. * /*from w w w . j a va 2s .c o m*/ * @param credentials * User credentials * * @return The digest-response as String. */ private Header createDigestHeader(final Credentials credentials) throws AuthenticationException { String uri = getParameter("uri"); String realm = getParameter("realm"); String nonce = getParameter("nonce"); String opaque = getParameter("opaque"); String method = getParameter("methodname"); String algorithm = getParameter("algorithm"); if (uri == null) { throw new IllegalStateException("URI may not be null"); } if (realm == null) { throw new IllegalStateException("Realm may not be null"); } if (nonce == null) { throw new IllegalStateException("Nonce may not be null"); } // TODO: add support for QOP_INT int qop = QOP_UNKNOWN; String qoplist = getParameter("qop"); if (qoplist != null) { StringTokenizer tok = new StringTokenizer(qoplist, ","); while (tok.hasMoreTokens()) { String variant = tok.nextToken().trim(); if (variant.equals("auth")) { qop = QOP_AUTH; break; } } } else { qop = QOP_MISSING; } if (qop == QOP_UNKNOWN) { throw new AuthenticationException("None of the qop methods is supported: " + qoplist); } // If an algorithm is not specified, default to MD5. if (algorithm == null) { algorithm = "MD5"; } // If an charset is not specified, default to ISO-8859-1. String charset = getParameter("charset"); if (charset == null) { charset = "ISO-8859-1"; } String digAlg = algorithm; if (digAlg.equalsIgnoreCase("MD5-sess")) { digAlg = "MD5"; } MessageDigest digester; try { digester = createMessageDigest(digAlg); } catch (UnsupportedDigestAlgorithmException ex) { throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg); } String uname = credentials.getUserPrincipal().getName(); String pwd = credentials.getPassword(); if (nonce.equals(this.lastNonce)) { nounceCount++; } else { nounceCount = 1; cnonce = null; lastNonce = nonce; } StringBuilder sb = new StringBuilder(256); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%08x", nounceCount); String nc = sb.toString(); if (cnonce == null) { cnonce = createCnonce(); } a1 = null; a2 = null; // 3.2.2.2: Calculating digest if (algorithm.equalsIgnoreCase("MD5-sess")) { // H( unq(username-value) ":" unq(realm-value) ":" passwd ) // ":" unq(nonce-value) // ":" unq(cnonce-value) // calculated one per session sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset))); sb.setLength(0); sb.append(checksum).append(':').append(nonce).append(':').append(cnonce); a1 = sb.toString(); } else { // unq(username-value) ":" unq(realm-value) ":" passwd sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); a1 = sb.toString(); } String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset))); if (qop == QOP_AUTH) { // Method ":" digest-uri-value a2 = method + ':' + uri; } else if (qop == QOP_AUTH_INT) { // Method ":" digest-uri-value ":" H(entity-body) // TODO: calculate entity hash if entity is repeatable throw new AuthenticationException("qop-int method is not suppported"); } else { a2 = method + ':' + uri; } String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset))); // 3.2.2.1 String digestValue; if (qop == QOP_MISSING) { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2); digestValue = sb.toString(); } else { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':').append(cnonce) .append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth").append(':').append(hasha2); digestValue = sb.toString(); } String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue))); CharArrayBuffer buffer = new CharArrayBuffer(128); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Digest "); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20); params.add(new BasicNameValuePair("username", uname)); params.add(new BasicNameValuePair("realm", realm)); params.add(new BasicNameValuePair("nonce", nonce)); params.add(new BasicNameValuePair("uri", uri)); params.add(new BasicNameValuePair("response", digest)); if (qop != QOP_MISSING) { params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth")); params.add(new BasicNameValuePair("nc", nc)); params.add(new BasicNameValuePair("cnonce", cnonce)); } if (algorithm != null) { params.add(new BasicNameValuePair("algorithm", algorithm)); } if (opaque != null) { params.add(new BasicNameValuePair("opaque", opaque)); } for (int i = 0; i < params.size(); i++) { BasicNameValuePair param = params.get(i); if (i > 0) { buffer.append(", "); } boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName()); BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes); } return new BufferedHeader(buffer); }
From source file:com.gargoylesoftware.htmlunit.WebClient.java
/** * Parses the given cookie and adds this to our cookie store. * @param cookieString the string to parse * @param pageUrl the url of the page that likes to set the cookie * @param origin the requester/*from w ww . j a v a2 s .c om*/ */ public void addCookie(final String cookieString, final URL pageUrl, final Object origin) { final CookieManager cookieManager = getCookieManager(); if (cookieManager.isCookiesEnabled()) { final CharArrayBuffer buffer = new CharArrayBuffer(cookieString.length() + 22); buffer.append("Set-Cookie: "); buffer.append(cookieString); final BrowserVersion browserVersion = getBrowserVersion(); final CookieSpec cookieSpec = new HtmlUnitBrowserCompatCookieSpec(browserVersion); try { final List<org.apache.http.cookie.Cookie> cookies = cookieSpec.parse(new BufferedHeader(buffer), cookieManager.buildCookieOrigin(pageUrl)); for (org.apache.http.cookie.Cookie cookie : cookies) { final Cookie htmlUnitCookie = new Cookie((ClientCookie) cookie); cookieManager.addCookie(htmlUnitCookie); if (LOG.isDebugEnabled()) { LOG.debug("Added cookie: '" + cookieString + "'"); } } } catch (final MalformedCookieException e) { getIncorrectnessListener().notify("set-cookie http-equiv meta tag: invalid cookie '" + cookieString + "'; reason: '" + e.getMessage() + "'.", origin); } } else if (LOG.isDebugEnabled()) { LOG.debug("Skipped adding cookie: '" + cookieString + "'"); } }
From source file:org.apache.http.impl.auth.BasicScheme.java
/** * Produces basic authorization header for the given set of {@link Credentials}. * * @param credentials The set of credentials to be used for authentication * @param request The request being authenticated * @throws org.apache.http.auth.InvalidCredentialsException if authentication * credentials are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a basic authorization string//from ww w . ja v a 2s . c om */ @Override public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { Args.notNull(credentials, "Credentials"); Args.notNull(request, "HTTP request"); final StringBuilder tmp = new StringBuilder(); tmp.append(credentials.getUserPrincipal().getName()); tmp.append(":"); tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); final byte[] base64password = base64codec .encode(EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request))); final CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Basic "); buffer.append(base64password, 0, base64password.length); return new BufferedHeader(buffer); }