use of com.microsoft.graph.options.HeaderOption in project msgraph-sdk-java by microsoftgraph.
the class DefaultHttpProvider method sendRequestInternal.
/**
* Sends the HTTP request
*
* @param request the request description
* @param resultClass the class of the response from the service
* @param serializable the object to send to the service in the body of the request
* @param progress the progress callback for the request
* @param handler the handler for stateful response
* @param <Result> the type of the response object
* @param <Body> the type of the object to send to the service in the body of the request
* @param <DeserializeType> the response handler for stateful response
* @return the result from the request
* @throws ClientException an exception occurs if the request was unable to complete for any reason
*/
@SuppressWarnings("unchecked")
private <Result, Body, DeserializeType> Result sendRequestInternal(final IHttpRequest request, final Class<Result> resultClass, final Body serializable, final IProgressCallback<Result> progress, final IStatefulResponseHandler<Result, DeserializeType> handler) throws ClientException {
final int defaultBufferSize = 4096;
final String binaryContentType = "application/octet-stream";
try {
if (authenticationProvider != null) {
authenticationProvider.authenticateRequest(request);
}
OutputStream out = null;
InputStream in = null;
boolean isBinaryStreamInput = false;
final URL requestUrl = request.getRequestUrl();
logger.logDebug("Starting to send request, URL " + requestUrl.toString());
final IConnection connection = connectionFactory.createFromRequest(request);
try {
logger.logDebug("Request Method " + request.getHttpMethod().toString());
List<HeaderOption> requestHeaders = request.getHeaders();
final byte[] bytesToWrite;
connection.addRequestHeader("Accept", "*/*");
if (serializable == null) {
// This ensures that the Content-Length header is properly set
if (request.getHttpMethod() == HttpMethod.POST) {
bytesToWrite = new byte[0];
} else {
bytesToWrite = null;
}
} else if (serializable instanceof byte[]) {
logger.logDebug("Sending byte[] as request body");
bytesToWrite = (byte[]) serializable;
// If the user hasn't specified a Content-Type for the request
if (!hasHeader(requestHeaders, CONTENT_TYPE_HEADER_NAME)) {
connection.addRequestHeader(CONTENT_TYPE_HEADER_NAME, binaryContentType);
}
connection.setContentLength(bytesToWrite.length);
} else {
logger.logDebug("Sending " + serializable.getClass().getName() + " as request body");
final String serializeObject = serializer.serializeObject(serializable);
bytesToWrite = serializeObject.getBytes();
// If the user hasn't specified a Content-Type for the request
if (!hasHeader(requestHeaders, CONTENT_TYPE_HEADER_NAME)) {
connection.addRequestHeader(CONTENT_TYPE_HEADER_NAME, JSON_CONTENT_TYPE);
}
connection.setContentLength(bytesToWrite.length);
}
// Handle cases where we've got a body to process.
if (bytesToWrite != null) {
out = connection.getOutputStream();
int writtenSoFar = 0;
BufferedOutputStream bos = new BufferedOutputStream(out);
int toWrite;
do {
toWrite = Math.min(defaultBufferSize, bytesToWrite.length - writtenSoFar);
bos.write(bytesToWrite, writtenSoFar, toWrite);
writtenSoFar = writtenSoFar + toWrite;
if (progress != null) {
executors.performOnForeground(writtenSoFar, bytesToWrite.length, progress);
}
} while (toWrite > 0);
bos.close();
}
if (handler != null) {
handler.configConnection(connection);
}
logger.logDebug(String.format("Response code %d, %s", connection.getResponseCode(), connection.getResponseMessage()));
if (handler != null) {
logger.logDebug("StatefulResponse is handling the HTTP response.");
return handler.generateResult(request, connection, this.getSerializer(), this.logger);
}
if (connection.getResponseCode() >= HttpResponseCode.HTTP_CLIENT_ERROR) {
logger.logDebug("Handling error response");
in = connection.getInputStream();
handleErrorResponse(request, serializable, connection);
}
if (connection.getResponseCode() == HttpResponseCode.HTTP_NOBODY || connection.getResponseCode() == HttpResponseCode.HTTP_NOT_MODIFIED) {
logger.logDebug("Handling response with no body");
return handleEmptyResponse(connection.getResponseHeaders(), resultClass);
}
if (connection.getResponseCode() == HttpResponseCode.HTTP_ACCEPTED) {
logger.logDebug("Handling accepted response");
return handleEmptyResponse(connection.getResponseHeaders(), resultClass);
}
in = new BufferedInputStream(connection.getInputStream());
final Map<String, String> headers = connection.getHeaders();
final String contentType = headers.get(CONTENT_TYPE_HEADER_NAME);
if (contentType.contains(JSON_CONTENT_TYPE)) {
logger.logDebug("Response json");
return handleJsonResponse(in, connection.getResponseHeaders(), resultClass);
} else {
logger.logDebug("Response binary");
isBinaryStreamInput = true;
// no inspection unchecked
return (Result) handleBinaryStream(in);
}
} finally {
if (out != null) {
out.close();
}
if (!isBinaryStreamInput && in != null) {
in.close();
connection.close();
}
}
} catch (final GraphServiceException ex) {
final boolean shouldLogVerbosely = logger.getLoggingLevel() == LoggerLevel.DEBUG;
logger.logError("Graph service exception " + ex.getMessage(shouldLogVerbosely), ex);
throw ex;
} catch (final Exception ex) {
final ClientException clientException = new ClientException("Error during http request", ex);
logger.logError("Error during http request", clientException);
throw clientException;
}
}
use of com.microsoft.graph.options.HeaderOption in project msgraph-sdk-java by microsoftgraph.
the class GraphServiceException method createFromConnection.
/**
* Creates a Graph service exception from a given failed HTTP request
*
* @param request the request that resulted in this failure
* @param serializable the serialized object that was sent with this request
* @param serializer the serializer to re-create the option in its over the wire state
* @param connection the connection that was used to extract the response information from
* @param logger the logger to log exception information to
* @param <T> the type of the serializable object
* @return the new GraphServiceException instance
* @throws IOException an exception occurs if there were any problems processing the connection
*/
public static <T> GraphServiceException createFromConnection(final IHttpRequest request, final T serializable, final ISerializer serializer, final IConnection connection, final ILogger logger) throws IOException {
final String method = connection.getRequestMethod();
final String url = request.getRequestUrl().toString();
final List<String> requestHeaders = new LinkedList<>();
for (final HeaderOption option : request.getHeaders()) {
requestHeaders.add(option.getName() + " : " + option.getValue());
}
boolean isVerbose = logger.getLoggingLevel() == LoggerLevel.DEBUG;
final String requestBody;
if (serializable instanceof byte[]) {
final byte[] bytes = (byte[]) serializable;
StringBuilder sb = new StringBuilder();
sb.append("byte[").append(bytes.length).append("]");
sb.append(" {");
if (isVerbose) {
sb.append(bytes);
} else {
for (int i = 0; i < MAX_BYTE_COUNT_BEFORE_TRUNCATION && i < bytes.length; i++) {
sb.append(bytes[i]).append(", ");
}
if (bytes.length > MAX_BYTE_COUNT_BEFORE_TRUNCATION) {
sb.append(TRUNCATION_MARKER).append("}");
}
}
requestBody = sb.toString();
} else if (serializable != null) {
requestBody = serializer.serializeObject(serializable);
} else {
requestBody = null;
}
final int responseCode = connection.getResponseCode();
final List<String> responseHeaders = new LinkedList<>();
final Map<String, String> headers = connection.getHeaders();
for (final String key : headers.keySet()) {
final String fieldPrefix;
if (key == null) {
fieldPrefix = "";
} else {
fieldPrefix = key + " : ";
}
responseHeaders.add(fieldPrefix + headers.get(key));
}
final String responseMessage = connection.getResponseMessage();
final String rawOutput = DefaultHttpProvider.streamToString(connection.getInputStream());
GraphErrorResponse error;
try {
error = serializer.deserializeObject(rawOutput, GraphErrorResponse.class, connection.getResponseHeaders());
} catch (final Exception ex) {
error = new GraphErrorResponse();
error.error = new GraphError();
error.error.code = "Unable to parse error response message";
error.error.message = "Raw error: " + rawOutput;
error.error.innererror = new GraphInnerError();
error.error.innererror.code = ex.getMessage();
}
if (responseCode >= INTERNAL_SERVER_ERROR) {
return new GraphFatalServiceException(method, url, requestHeaders, requestBody, responseCode, responseMessage, responseHeaders, error, isVerbose);
}
return new GraphServiceException(method, url, requestHeaders, requestBody, responseCode, responseMessage, responseHeaders, error, isVerbose);
}
use of com.microsoft.graph.options.HeaderOption in project msgraph-sdk-java by microsoftgraph.
the class DefaultHttpProviderTests method testHasHeaderReturnsFalse.
@Test
public void testHasHeaderReturnsFalse() {
HeaderOption h = new HeaderOption("name", "value");
assertFalse(DefaultHttpProvider.hasHeader(Arrays.asList(h), "blah"));
}
use of com.microsoft.graph.options.HeaderOption in project msgraph-sdk-java by microsoftgraph.
the class DefaultHttpProviderTests method testHasHeaderReturnsTrue.
@Test
public void testHasHeaderReturnsTrue() {
HeaderOption h = new HeaderOption("name", "value");
assertTrue(DefaultHttpProvider.hasHeader(Arrays.asList(h), "name"));
}
use of com.microsoft.graph.options.HeaderOption in project msgraph-sdk-java by microsoftgraph.
the class DefaultHttpProviderTests method testHasHeaderReturnsTrueWhenDifferentCase.
@Test
public void testHasHeaderReturnsTrueWhenDifferentCase() {
HeaderOption h = new HeaderOption("name", "value");
assertTrue(DefaultHttpProvider.hasHeader(Arrays.asList(h), "NAME"));
}
Aggregations