use of com.github.davidmoten.odata.client.ClientException in project odata-client by davidmoten.
the class DefaultHttpService method getResponse.
private HttpResponse getResponse(String url, List<RequestHeader> requestHeaders, HttpMethod method, boolean doInput, InputStream content, int length) {
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setInstanceFollowRedirects(true);
c.setRequestMethod(method.toString());
for (RequestHeader header : requestHeadersModifier.apply(requestHeaders)) {
c.setRequestProperty(header.name(), header.value());
}
if (length != HttpService.LENGTH_UNKNOWN) {
c.setRequestProperty("Content-Length", length + "");
}
c.setDoInput(doInput);
c.setDoOutput(content != null);
// apply just before connection established so further configuration can take
// place like timeouts
consumer.accept(c);
if (content != null) {
try (OutputStream out = c.getOutputStream()) {
byte[] b = new byte[8192];
int len;
while ((len = content.read(b)) != -1) {
out.write(b, 0, len);
}
}
}
final byte[] bytes;
if (doInput) {
bytes = Util.read(c.getInputStream());
} else {
bytes = null;
}
return new HttpResponse(c.getResponseCode(), bytes);
} catch (ProtocolException e) {
throw new ProtocolRuntimeException(e);
} catch (IOException e) {
throw new ClientException(e);
}
}
use of com.github.davidmoten.odata.client.ClientException in project odata-client by davidmoten.
the class RequestHelper method patchOrPut.
@SuppressWarnings("unused")
private static <T extends ODataEntityType> T patchOrPut(T entity, ContextPath contextPath, RequestOptions options, HttpMethod method) {
Preconditions.checkArgument(method == HttpMethod.PUT || method == HttpMethod.PATCH);
final String json;
if (method == HttpMethod.PATCH) {
json = Serializer.INSTANCE.serializeChangesOnly(entity);
} else {
json = Serializer.INSTANCE.serialize(entity);
}
// build the url
ContextPath cp = contextPath.addQueries(options.getQueries());
List<RequestHeader> h = cleanAndSupplementRequestHeaders(options, "minimal", true);
final String url;
String editLink = (String) entity.getUnmappedFields().get("@odata.editLink");
// TODO get patch working when editLink present (does not work with MsGraph)
if (editLink != null && false) {
if (editLink.startsWith(HTTPS) || editLink.startsWith("http://")) {
url = editLink;
} else {
// TOOD unit test relative url in editLink
// from
// http://docs.oasis-open.org/odata/odata-json-format/v4.01/cs01/odata-json-format-v4.01-cs01.html#_Toc499720582
String context = (String) entity.getUnmappedFields().get("@odata.context");
if (context != null) {
try {
URL u = new URL(context);
String p = u.getPath();
String basePath = p.substring(0, p.lastIndexOf('/'));
url = basePath + "/" + editLink;
} catch (MalformedURLException e) {
throw new ClientException(e);
}
} else {
url = cp.context().service().getBasePath().toUrl() + "/" + editLink;
}
}
} else {
url = cp.toUrl();
}
// get the response
HttpService service = cp.context().service();
final HttpResponse response = service.submit(method, url, h, json, options);
checkResponseCodeOk(cp, response);
// original?
return entity;
}
use of com.github.davidmoten.odata.client.ClientException in project odata-client by davidmoten.
the class ClientCredentialsAccessTokenProvider method refreshAccessToken.
private String refreshAccessToken() {
// need to refresh the token
try {
log.debug("refreshing access token");
URL url = new URL(authenticationEndpoint + tenantName + OAUTH2_TOKEN_URL_SUFFIX);
final HttpsURLConnection con;
if (proxyHost.isPresent()) {
InetSocketAddress proxyInet = new InetSocketAddress(proxyHost.get(), proxyPort.get());
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyInet);
con = (HttpsURLConnection) url.openConnection(proxy);
if (proxyUsername.isPresent()) {
String usernameAndPassword = proxyUsername.get() + ":" + proxyPassword.get();
String authString = "Basic " + Base64.getEncoder().encodeToString(usernameAndPassword.getBytes(StandardCharsets.UTF_8));
con.setRequestProperty("Proxy-Authorization", authString);
}
// TODO support NTLM?
} else {
con = (HttpsURLConnection) url.openConnection();
}
con.setConnectTimeout((int) connectTimeoutMs);
con.setReadTimeout((int) readTimeoutMs);
con.setRequestMethod(POST);
con.setRequestProperty(REQUEST_HEADER, APPLICATION_JSON);
StringBuilder params = new StringBuilder();
add(params, PARAMETER_RESOURCE, resource);
add(params, PARAMETER_CLIENT_ID, clientId);
add(params, PARAMETER_GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS);
add(params, PARAMETER_CLIENT_SECRET, clientSecret);
for (String scope : scopes) {
add(params, PARAMETER_SCOPE, scope);
}
con.setDoOutput(true);
try (DataOutputStream dos = new DataOutputStream(con.getOutputStream())) {
dos.writeBytes(params.toString());
}
int responseCode = con.getResponseCode();
String json = Util.readString(con.getInputStream(), StandardCharsets.UTF_8);
if (responseCode != OK) {
throw new ClientException(responseCode, json);
} else {
ObjectMapper om = new ObjectMapper();
JsonNode o = om.readTree(json);
// update the cached values
expiryTime = o.get("expires_on").asLong() * 1000;
accessToken = o.get("access_token").asText();
log.debug("refreshed access token, expires on " + new Date(expiryTime));
return accessToken;
}
} catch (IOException e) {
// reset stuff
expiryTime = 0;
accessToken = null;
Optional<Integer> code = extractStatusCode(e.getMessage());
if (code.isPresent()) {
throw new ClientException(code.get(), e);
} else {
throw new ClientException(e);
}
}
}
use of com.github.davidmoten.odata.client.ClientException in project odata-client by davidmoten.
the class ApacheHttpClientHttpService method getResponse.
private HttpResponse getResponse(List<RequestHeader> requestHeaders, HttpRequestBase request, InputStream content, int length, HttpRequestOptions options) {
Preconditions.checkNotNull(options);
log.debug("{} from url {}", request.getMethod(), request.getURI());
log.debug("requestHeaders={}", requestHeaders);
for (RequestHeader header : requestHeadersModifier.apply(toUrl(request), requestHeaders)) {
request.addHeader(header.name(), header.value());
}
try {
if (content != null && request instanceof HttpEntityEnclosingRequest) {
((HttpEntityEnclosingRequest) request).setEntity(new InputStreamEntity(content, length));
log.debug("content={}", content);
}
RequestConfig config = com.github.davidmoten.odata.client.Util.nvl(request.getConfig(), RequestConfig.DEFAULT);
Builder builder = //
RequestConfig.copy(config);
options.requestConnectTimeoutMs().ifPresent(x -> builder.setConnectTimeout(x.intValue()));
options.requestReadTimeoutMs().ifPresent(x -> builder.setSocketTimeout(x.intValue()));
config = builder.build();
request.setConfig(config);
log.debug("executing request");
try (CloseableHttpResponse response = client.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
log.debug("executed request, code={}", statusCode);
HttpEntity entity = response.getEntity();
final byte[] bytes;
if (entity == null) {
bytes = null;
} else {
bytes = Util.read(entity.getContent());
}
if (log.isDebugEnabled()) {
log.debug("response text=\n{}", bytes == null ? "null" : new String(bytes, StandardCharsets.UTF_8));
}
return new HttpResponse(statusCode, bytes);
}
} catch (IOException e) {
throw new ClientException(e);
}
}
Aggregations