List of usage examples for org.apache.http.util CharArrayBuffer CharArrayBuffer
public CharArrayBuffer(int i)
From source file:com.gistlabs.mechanize.util.apache.URLEncodedUtils.java
/** * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string * using the given character encoding./*from w ww . j a va2s . c o m*/ * * @param s * text to parse. * @param charset * Encoding to use when decoding the parameters. * * @since 4.2 */ public static List<NameValuePair> parse(final String s, final Charset charset) { if (s == null) return Collections.emptyList(); BasicHeaderValueParser parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(s.length()); buffer.append(s); ParserCursor cursor = new ParserCursor(0, buffer.length()); List<NameValuePair> list = new ArrayList<NameValuePair>(); while (!cursor.atEnd()) { NameValuePair nvp = parser.parseNameValuePair(buffer, cursor, DELIM); if (nvp.getName().length() > 0) list.add(new BasicNameValuePair(decodeFormFields(nvp.getName(), charset), decodeFormFields(nvp.getValue(), charset))); } return list; }
From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitBrowserCompatCookieSpec.java
/** * {@inheritDoc}/*from ww w.j av a 2s . com*/ */ @Override public List<Cookie> parse(Header header, final CookieOrigin origin) throws MalformedCookieException { // first a hack to support empty headers final String text = header.getValue(); int endPos = text.indexOf(';'); if (endPos < 0) { endPos = text.indexOf('='); } else { final int pos = text.indexOf('='); if (pos > endPos) { endPos = -1; } else { endPos = pos; } } if (endPos < 0) { header = new BasicHeader(header.getName(), EMPTY_COOKIE_NAME + "=" + header.getValue()); } else if (endPos == 0 || StringUtils.isBlank(text.substring(0, endPos))) { header = new BasicHeader(header.getName(), EMPTY_COOKIE_NAME + header.getValue()); } final List<Cookie> cookies; final String headername = header.getName(); if (!headername.equalsIgnoreCase(SM.SET_COOKIE)) { throw new MalformedCookieException("Unrecognized cookie header '" + header.toString() + "'"); } final HeaderElement[] helems = header.getElements(); boolean versioned = false; boolean netscape = false; for (final HeaderElement helem : helems) { if (helem.getParameterByName("version") != null) { versioned = true; } if (helem.getParameterByName("expires") != null) { netscape = true; } } if (netscape || !versioned) { // Need to parse the header again, because Netscape style cookies do not correctly // support multiple header elements (comma cannot be treated as an element separator) final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT; final CharArrayBuffer buffer; final ParserCursor cursor; if (header instanceof FormattedHeader) { buffer = ((FormattedHeader) header).getBuffer(); cursor = new ParserCursor(((FormattedHeader) header).getValuePos(), buffer.length()); } else { final String s = header.getValue(); if (s == null) { throw new MalformedCookieException("Header value is null"); } buffer = new CharArrayBuffer(s.length()); buffer.append(s); cursor = new ParserCursor(0, buffer.length()); } final HeaderElement elem = parser.parseHeader(buffer, cursor); final String name = elem.getName(); final String value = elem.getValue(); if (name == null || name.isEmpty()) { throw new MalformedCookieException("Cookie name may not be empty"); } final BasicClientCookie cookie = new BasicClientCookie(name, value); cookie.setPath(getDefaultPath(origin)); cookie.setDomain(getDefaultDomain(origin)); // cycle through the parameters final NameValuePair[] attribs = elem.getParameters(); for (int j = attribs.length - 1; j >= 0; j--) { final NameValuePair attrib = attribs[j]; final String s = attrib.getName().toLowerCase(Locale.ROOT); cookie.setAttribute(s, attrib.getValue()); final CookieAttributeHandler handler = findAttribHandler(s); if (handler != null) { handler.parse(cookie, attrib.getValue()); } } // Override version for Netscape style cookies if (netscape) { cookie.setVersion(0); } cookies = Collections.<Cookie>singletonList(cookie); } else { cookies = parse(helems, origin); } for (final Cookie c : cookies) { // re-add quotes around value if parsing as incorrectly trimmed them if (header.getValue().contains(c.getName() + "=\"" + c.getValue())) { ((BasicClientCookie) c).setValue('"' + c.getValue() + '"'); } } return cookies; }
From source file:com.mcxiaoke.next.http.entity.ContentType.java
/** * Parses textual representation of <code>Content-Type</code> value. * * @param s text// ww w . j a v a 2s .c om * @return content type * @throws org.apache.http.ParseException if the given text does not represent a valid * <code>Content-Type</code> value. * @throws java.nio.charset.UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public static ContentType parse(final String s) throws ParseException, UnsupportedCharsetException { AssertUtils.notNull(s, "Content type"); final CharArrayBuffer buf = new CharArrayBuffer(s.length()); buf.append(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(buf, cursor); if (elements.length > 0) { return create(elements[0]); } else { throw new ParseException("Invalid content type: " + s); } }
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 *///from w w w .ja va2s . 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.mcxiaoke.next.http.entity.BasicHeaderValueFormatter.java
public CharArrayBuffer formatHeaderElement(final CharArrayBuffer charBuffer, final HeaderElement elem, final boolean quote) { AssertUtils.notNull(elem, "Header element"); final int len = estimateHeaderElementLen(elem); CharArrayBuffer buffer = charBuffer; if (buffer == null) { buffer = new CharArrayBuffer(len); } else {//from w ww . j a va 2s . c o m buffer.ensureCapacity(len); } buffer.append(elem.getName()); final String value = elem.getValue(); if (value != null) { buffer.append('='); doFormatValue(buffer, value, quote); } final int parcnt = elem.getParameterCount(); if (parcnt > 0) { for (int i = 0; i < parcnt; i++) { buffer.append("; "); formatNameValuePair(buffer, elem.getParameter(i), quote); } } return buffer; }
From source file:cn.aage.robot.http.entity.ContentType.java
/** * Parses textual representation of <code>Content-Type</code> value. * * @param s text//from www .j a v a 2s . c om * @return content type * @throws ParseException if the given text does not represent a valid * <code>Content-Type</code> value. * @throws UnsupportedCharsetException Thrown when the named charset is not available in * this instance of the Java virtual machine */ public static ContentType parse(final String s) throws ParseException, UnsupportedCharsetException { Args.notNull(s, "Content type"); final CharArrayBuffer buf = new CharArrayBuffer(s.length()); buf.append(s); final ParserCursor cursor = new ParserCursor(0, s.length()); final HeaderElement[] elements = BasicHeaderValueParser.DEFAULT.parseElements(buf, cursor); if (elements.length > 0) { return create(elements[0]); } else { throw new ParseException("Invalid content type: " + s); } }
From source file:com.mcxiaoke.next.http.entity.BasicHeaderValueFormatter.java
public CharArrayBuffer formatParameters(final CharArrayBuffer charBuffer, final NameValuePair[] nvps, final boolean quote) { AssertUtils.notNull(nvps, "Header parameter array"); final int len = estimateParametersLen(nvps); CharArrayBuffer buffer = charBuffer; if (buffer == null) { buffer = new CharArrayBuffer(len); } else {/*from ww w.j ava 2s . com*/ buffer.ensureCapacity(len); } for (int i = 0; i < nvps.length; i++) { if (i > 0) { buffer.append("; "); } formatNameValuePair(buffer, nvps[i], quote); } return buffer; }
From source file:at.general.solutions.android.ical.remote.HttpDownloadThread.java
@Override public void run() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 100); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(params, USER_AGENT); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient client = new DefaultHttpClient(cm, params); if (useAuthentication) { client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(remoteUsername, remotePassword)); }/*from w ww.j a v a 2s .c o m*/ HttpGet get = new HttpGet(remoteUrl); try { super.sendInitMessage(R.string.downloading); HttpResponse response = client.execute(get); Log.d(LOG_TAG, response.getStatusLine().getReasonPhrase() + " " + isGoodResponse(response.getStatusLine().getStatusCode())); if (isGoodResponse(response.getStatusLine().getStatusCode())) { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); if (instream == null) { super.sendErrorMessage(R.string.couldnotConnectToRemoteserver); return; } if (entity.getContentLength() > Integer.MAX_VALUE) { super.sendErrorMessage(R.string.remoteFileTooLarge); return; } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = encoding; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); super.sendMaximumMessage(i); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); super.sendProgressMessage(buffer.length()); } } finally { reader.close(); } super.sendFinishedMessage(buffer.toString()); } else { int errorMsg = R.string.couldnotConnectToRemoteserver; if (isAccessDenied(response.getStatusLine().getStatusCode())) { errorMsg = R.string.accessDenied; } else if (isFileNotFound(response.getStatusLine().getStatusCode())) { errorMsg = R.string.remoteFileNotFound; } super.sendErrorMessage(errorMsg); } } catch (UnknownHostException e) { super.sendErrorMessage(R.string.unknownHostException, e); Log.e(LOG_TAG, "Error occured", e); } catch (Throwable e) { super.sendErrorMessage(R.string.couldnotConnectToRemoteserver, e); Log.e(LOG_TAG, "Error occured", e); } finally { client.getConnectionManager().shutdown(); } }
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);// ww w . j a va2s. c o 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; }