use of org.apache.http.HttpRequest in project XobotOS by xamarin.
the class ResponseConnControl method process.
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Always drop connection after certain type of responses
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_BAD_REQUEST || status == HttpStatus.SC_REQUEST_TIMEOUT || status == HttpStatus.SC_LENGTH_REQUIRED || status == HttpStatus.SC_REQUEST_TOO_LONG || status == HttpStatus.SC_REQUEST_URI_TOO_LONG || status == HttpStatus.SC_SERVICE_UNAVAILABLE || status == HttpStatus.SC_NOT_IMPLEMENTED) {
response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
return;
}
// Always drop connection for HTTP/1.0 responses and below
// if the content body cannot be correctly delimited
HttpEntity entity = response.getEntity();
if (entity != null) {
ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
if (entity.getContentLength() < 0 && (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) {
response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
return;
}
}
// Drop connection if requested by the client
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
if (request != null) {
Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE);
if (header != null) {
response.setHeader(HTTP.CONN_DIRECTIVE, header.getValue());
}
}
}
use of org.apache.http.HttpRequest in project robovm by robovm.
the class DefaultRedirectHandler method getLocationURI.
public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
//get the location header to find out where to redirect to
Header locationHeader = response.getFirstHeader("location");
if (locationHeader == null) {
// got a redirect response, but no location header
throw new ProtocolException("Received redirect response " + response.getStatusLine() + " but no location header");
}
String location = locationHeader.getValue();
if (this.log.isDebugEnabled()) {
this.log.debug("Redirect requested to location '" + location + "'");
}
URI uri;
try {
uri = new URI(location);
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid redirect URI: " + location, ex);
}
HttpParams params = response.getParams();
// Location = "Location" ":" absoluteURI
if (!uri.isAbsolute()) {
if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
}
// Adjust location URI
HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
throw new IllegalStateException("Target host not available " + "in the HTTP context");
}
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
try {
URI requestURI = new URI(request.getRequestLine().getUri());
URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
uri = URIUtils.resolve(absoluteRequestURI, uri);
} catch (URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
}
if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {
RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);
if (redirectLocations == null) {
redirectLocations = new RedirectLocations();
context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
}
URI redirectURI;
if (uri.getFragment() != null) {
try {
HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
redirectURI = URIUtils.rewriteURI(uri, target, true);
} catch (URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
} else {
redirectURI = uri;
}
if (redirectLocations.contains(redirectURI)) {
throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
} else {
redirectLocations.add(redirectURI);
}
}
return uri;
}
use of org.apache.http.HttpRequest in project robovm by robovm.
the class DefaultRequestDirector method createConnectRequest.
/**
* Creates the CONNECT request for tunnelling.
* Called by {@link #createTunnelToTarget createTunnelToTarget}.
*
* @param route the route to establish
* @param context the context for request execution
*
* @return the CONNECT request for tunnelling
*/
protected HttpRequest createConnectRequest(HttpRoute route, HttpContext context) {
// see RFC 2817, section 5.2 and
// INTERNET-DRAFT: Tunneling TCP based protocols through
// Web proxy servers
HttpHost target = route.getTargetHost();
String host = target.getHostName();
int port = target.getPort();
if (port < 0) {
Scheme scheme = connManager.getSchemeRegistry().getScheme(target.getSchemeName());
port = scheme.getDefaultPort();
}
StringBuilder buffer = new StringBuilder(host.length() + 6);
buffer.append(host);
buffer.append(':');
buffer.append(Integer.toString(port));
String authority = buffer.toString();
ProtocolVersion ver = HttpProtocolParams.getVersion(params);
HttpRequest req = new BasicHttpRequest("CONNECT", authority, ver);
return req;
}
use of org.apache.http.HttpRequest in project robovm by robovm.
the class DefaultRequestDirector method handleResponse.
/**
* Analyzes a response to check need for a followup.
*
* @param roureq the request and route.
* @param response the response to analayze
* @param context the context used for the current request execution
*
* @return the followup request and route if there is a followup, or
* <code>null</code> if the response should be returned as is
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context) throws HttpException, IOException {
HttpRoute route = roureq.getRoute();
HttpHost proxy = route.getProxyHost();
RequestWrapper request = roureq.getRequest();
HttpParams params = request.getParams();
if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) {
if (redirectCount >= maxRedirects) {
throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
}
redirectCount++;
URI uri = this.redirectHandler.getLocationURI(response, context);
HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
HttpGet redirect = new HttpGet(uri);
HttpRequest orig = request.getOriginal();
redirect.setHeaders(orig.getAllHeaders());
RequestWrapper wrapper = new RequestWrapper(redirect);
wrapper.setParams(params);
HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
if (this.log.isDebugEnabled()) {
this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
}
return newRequest;
}
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {
HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
target = route.getTargetHost();
}
this.log.debug("Target requested authentication");
Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
return null;
}
}
updateAuthState(this.targetAuthState, target, credsProvider);
if (this.targetAuthState.getCredentials() != null) {
// Re-try the same request via the same route
return roureq;
} else {
return null;
}
} else {
// Reset target auth scope
this.targetAuthState.setAuthScope(null);
}
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
return null;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
// Re-try the same request via the same route
return roureq;
} else {
return null;
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
return null;
}
use of org.apache.http.HttpRequest in project acceptance-test-harness by jenkinsci.
the class MockUpdateCenter method ensureRunning.
public void ensureRunning() {
if (original != null) {
return;
}
// TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController
Jenkins jenkins = injector.getInstance(Jenkins.class);
List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url");
if (sites.size() != 1) {
// TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies
LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites);
return;
}
UpdateCenterMetadata ucm;
try {
ucm = ucmd.get(jenkins);
} catch (IOException x) {
LOGGER.log(Level.WARNING, "cannot load data for mock update center", x);
return;
}
JSONObject all;
try {
all = new JSONObject(ucm.originalJSON);
all.remove("signature");
JSONObject plugins = all.getJSONObject("plugins");
LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size() + " possible overrides");
for (PluginMetadata meta : ucm.plugins.values()) {
String name = meta.getName();
String version = meta.getVersion();
JSONObject plugin = plugins.optJSONObject(name);
if (plugin == null) {
LOGGER.log(Level.INFO, "adding plugin {0}", name);
plugin = new JSONObject().accumulate("name", name);
plugins.put(name, plugin);
}
plugin.put("url", name + ".hpi");
updating(plugin, "version", version);
updating(plugin, "gav", meta.gav);
updating(plugin, "requiredCore", meta.requiredCore().toString());
updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> {
try {
return new JSONObject().accumulate("name", d.name).accumulate("version", d.version).accumulate("optional", d.optional);
} catch (JSONException x) {
throw new AssertionError(x);
}
}).collect(Collectors.toList())));
plugin.remove("sha1");
}
} catch (JSONException x) {
LOGGER.log(Level.WARNING, "cannot prepare mock update center", x);
return;
}
HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter")).add(new ResponseContent()).add(new RequestConnControl()).build();
UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
String json = "updateCenter.post(\n" + all + "\n);";
handlerMapper.register("/update-center.json", (HttpRequest request, HttpResponse response, HttpContext context) -> {
response.setStatusCode(HttpStatus.SC_OK);
response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
});
handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> {
String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1");
PluginMetadata meta = ucm.plugins.get(plugin);
if (meta == null) {
LOGGER.log(Level.WARNING, "no such plugin {0}", plugin);
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
return;
}
File local = meta.resolve(injector, meta.getVersion());
LOGGER.log(Level.INFO, "serving {0}", local);
response.setStatusCode(HttpStatus.SC_OK);
response.setEntity(new FileEntity(local));
});
handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> {
String location = original.replace("/update-center.json", request.getRequestLine().getUri());
LOGGER.log(Level.INFO, "redirect to {0}", location);
/* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true):
response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY);
response.setHeader("Location", location);
*/
HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection();
uc.setInstanceFollowRedirects(true);
// TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json
byte[] data = IOUtils.toByteArray(uc);
String contentType = uc.getContentType();
response.setStatusCode(HttpStatus.SC_OK);
response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType)));
});
server = ServerBootstrap.bootstrap().setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler()).create();
try {
server.start();
} catch (IOException x) {
LOGGER.log(Level.WARNING, "cannot start mock update center", x);
return;
}
original = sites.get(0);
// TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host
String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort() + "/update-center.json";
LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override });
jenkins.runScript("DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])", override);
}
Aggregations