Search in sources :

Example 1 with ClientException

use of com.microsoft.graph.core.ClientException in project android-java-snippets-sample by microsoftgraph.

the class EventsSnippets method getEventsSnippets.

static EventsSnippets[] getEventsSnippets() {
    return new EventsSnippets[] { // Marker element
    new EventsSnippets(null) {

        @Override
        public void request(ICallback callback) {
        // No implementation
        }
    }, /*
                 * Get all events for the signed in user.
                 * GET https://graph.microsoft.com/{version}/me/events
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/user_list_events
                 */
    new EventsSnippets<JsonObject>(get_user_events) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            mGraphServiceClient.getMe().getEvents().buildRequest().get(new ICallback<IEventCollectionPage>() {

                @Override
                public void success(IEventCollectionPage iEventCollectionPage) {
                    callback.success(iEventCollectionPage.getRawObject());
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /*
                 * Adds an event to the signed-in user\'s calendar.
                 * POST https://graph.microsoft.com/{version}/me/events
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/user_post_events
                 */
    new EventsSnippets<JsonObject>(create_event) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            Event event = createEventObject();
            mGraphServiceClient.getMe().getEvents().buildRequest().post(event, new ICallback<Event>() {

                @Override
                public void success(Event event) {
                    callback.success(event.getRawObject());
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /*
                 * Update an event
                 * PATCH https://graph.microsoft.com/{version}/me/events/{Event.Id}
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/event_update
                 */
    new EventsSnippets<JsonObject>(update_event) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            Event event = createEventObject();
            mGraphServiceClient.getMe().getEvents().buildRequest().post(event, new ICallback<Event>() {

                @Override
                public void success(Event event) {
                    // Update the event object
                    event.subject = "Updated event";
                    mGraphServiceClient.getMe().getEvents().byId(event.id).buildRequest().patch(event, new ICallback<Event>() {

                        @Override
                        public void success(Event event) {
                            callback.success(event.getRawObject());
                        }

                        @Override
                        public void failure(ClientException ex) {
                            callback.failure(ex);
                        }
                    });
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /*
                 * Delete an event
                 * DELETE https://graph.microsoft.com/{version}/me/events/{Event.Id}
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/event_delete
                 */
    new EventsSnippets<JsonObject>(delete_event) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            Event event = createEventObject();
            mGraphServiceClient.getMe().getEvents().buildRequest().post(event, new ICallback<Event>() {

                @Override
                public void success(Event event) {
                    // Update the event object
                    event.subject = "Updated event";
                    mGraphServiceClient.getMe().getEvents().byId(event.id).buildRequest().delete(new ICallback<Void>() {

                        @Override
                        public void success(Void aVoid) {
                            callback.success(null);
                        }

                        @Override
                        public void failure(ClientException ex) {
                            callback.failure(ex);
                        }
                    });
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    } };
}
Also used : IEventCollectionPage(com.microsoft.graph.extensions.IEventCollectionPage) ICallback(com.microsoft.graph.concurrency.ICallback) Event(com.microsoft.graph.extensions.Event) ClientException(com.microsoft.graph.core.ClientException)

Example 2 with ClientException

use of com.microsoft.graph.core.ClientException in project android-java-snippets-sample by microsoftgraph.

the class GroupsSnippets method getGroupsSnippets.

static GroupsSnippets[] getGroupsSnippets() {
    return new GroupsSnippets[] { // Marker element
    new GroupsSnippets(null) {

        @Override
        public void request(ICallback callback) {
        // Not implemented
        }
    }, /*
                 * Get a group by id
                 * GET https://graph.microsoft.com/{version}/myOrganization/groups/{Group.objectId}
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/group_get
                 */
    new GroupsSnippets<JsonObject>(get_a_group) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            // create a group then query it
            Group group = createGroupObject();
            mGraphServiceClient.getGroups().buildRequest().post(group, new ICallback<Group>() {

                @Override
                public void success(Group group) {
                    mGraphServiceClient.getGroups().byId(group.id).buildRequest().get(new ICallback<Group>() {

                        @Override
                        public void success(Group group) {
                            callback.success(group.getRawObject());
                        }

                        @Override
                        public void failure(ClientException ex) {
                            callback.failure(ex);
                        }
                    });
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /* Get all of the members of a newly created organization group
                 * GET https://graph.microsoft.com/{version}/myOrganization/groups/{Group.objectId}/members
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/group_list_members
                 */
    new GroupsSnippets<JsonObject>(get_group_members) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            // create a group then ask for its members
            Group group = createGroupObject();
            mGraphServiceClient.getGroups().buildRequest().post(group, new ICallback<Group>() {

                @Override
                public void success(Group group) {
                    mGraphServiceClient.getGroups().byId(group.id).getMembers().buildRequest().get(new ICallback<IDirectoryObjectCollectionWithReferencesPage>() {

                        @Override
                        public void success(IDirectoryObjectCollectionWithReferencesPage iDirectoryObjectCollectionWithReferencesPage) {
                            callback.success(iDirectoryObjectCollectionWithReferencesPage.getRawObject());
                        }

                        @Override
                        public void failure(ClientException ex) {
                            callback.failure(ex);
                        }
                    });
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /* Get all of a group's owners
                 * GET https://graph.microsoft.com/{version}/myOrganization/groups/{Group.objectId}/owners
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/group_list_owners
                 */
    new GroupsSnippets<JsonObject>(get_group_owners) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            // create a group and then request its owner
            Group group = createGroupObject();
            mGraphServiceClient.getGroups().buildRequest().post(group, new ICallback<Group>() {

                @Override
                public void success(Group group) {
                    mGraphServiceClient.getGroups().byId(group.id).getOwners().buildRequest().get(new ICallback<IDirectoryObjectCollectionWithReferencesPage>() {

                        @Override
                        public void success(IDirectoryObjectCollectionWithReferencesPage iDirectoryObjectCollectionWithReferencesPage) {
                            callback.success(iDirectoryObjectCollectionWithReferencesPage.getRawObject());
                        }

                        @Override
                        public void failure(ClientException ex) {
                            callback.failure(ex);
                        }
                    });
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /* List all organization groups
                 * GET https://graph.microsoft.com/v1.0/groups
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/group_list
                 */
    new GroupsSnippets<JsonObject>(get_all_groups) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            mGraphServiceClient.getGroups().buildRequest().get(new ICallback<IGroupCollectionPage>() {

                @Override
                public void success(IGroupCollectionPage iGroupCollectionPage) {
                    callback.success(iGroupCollectionPage.getRawObject());
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /* Create a new group with a random name
                 * POST https://graph.microsoft.com/{version}/myOrganization/groups
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/resources/group
                 */
    new GroupsSnippets<JsonObject>(insert_a_group) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            // create a new group
            Group group = createGroupObject();
            mGraphServiceClient.getGroups().buildRequest().post(group, new ICallback<Group>() {

                @Override
                public void success(Group group) {
                    callback.success(group.getRawObject());
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /* Delete a group
                 * DELETE https://graph.microsoft.com/{version}/myOrganization/groups/{Group.objectId}
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/group_delete
                 */
    new GroupsSnippets<JsonObject>(delete_a_group) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            // Create a group that we will delete
            // create a group and then request its owner
            Group group = createGroupObject();
            mGraphServiceClient.getGroups().buildRequest().post(group, new ICallback<Group>() {

                @Override
                public void success(Group group) {
                    mGraphServiceClient.getGroups().byId(group.id).buildRequest().delete(new ICallback<Void>() {

                        @Override
                        public void success(Void aVoid) {
                            callback.success(null);
                        }

                        @Override
                        public void failure(ClientException ex) {
                            callback.failure(ex);
                        }
                    });
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    } };
}
Also used : Group(com.microsoft.graph.extensions.Group) ICallback(com.microsoft.graph.concurrency.ICallback) IGroupCollectionPage(com.microsoft.graph.extensions.IGroupCollectionPage) IDirectoryObjectCollectionWithReferencesPage(com.microsoft.graph.extensions.IDirectoryObjectCollectionWithReferencesPage) ClientException(com.microsoft.graph.core.ClientException)

Example 3 with ClientException

use of com.microsoft.graph.core.ClientException in project android-java-snippets-sample by microsoftgraph.

the class MessageSnippets method getMessageSnippets.

static MessageSnippets[] getMessageSnippets() {
    return new MessageSnippets[] { // Marker element
    new MessageSnippets(null) {

        @Override
        public void request(ICallback callback) {
        // Not implemented
        }
    }, /* Get messages from mailbox for signed in user
                 * HTTP GET https://graph.microsoft.com/{version}/me/messages
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/user_list_messages
                 */
    new MessageSnippets<JsonObject>(get_user_messages) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            mGraphServiceClient.getMe().getMessages().buildRequest().get(new ICallback<IMessageCollectionPage>() {

                @Override
                public void success(IMessageCollectionPage iMessageCollectionPage) {
                    callback.success(iMessageCollectionPage.getRawObject());
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    }, /* Sends an email message on behalf of the signed in user
                 * HTTP POST https://graph.microsoft.com/{version}/me/messages/sendMail
                 * @see https://graph.microsoft.io/docs/api-reference/v1.0/api/user_post_messages
                 */
    new MessageSnippets<JsonObject>(send_an_email_message) {

        @Override
        public void request(final ICallback<JsonObject> callback) {
            Message message = createMessageObject();
            mGraphServiceClient.getMe().getSendMail(message, true).buildRequest().post(new ICallback<Void>() {

                @Override
                public void success(Void aVoid) {
                    callback.success(null);
                }

                @Override
                public void failure(ClientException ex) {
                    callback.failure(ex);
                }
            });
        }
    } };
}
Also used : ICallback(com.microsoft.graph.concurrency.ICallback) Message(com.microsoft.graph.extensions.Message) IMessageCollectionPage(com.microsoft.graph.extensions.IMessageCollectionPage) ClientException(com.microsoft.graph.core.ClientException)

Example 4 with ClientException

use of com.microsoft.graph.core.ClientException in project msgraph-sdk-java by microsoftgraph.

the class BaseRequestTests method testSendWithCallback.

@Test
public void testSendWithCallback() {
    final AtomicBoolean success = new AtomicBoolean(false);
    final AtomicBoolean failure = new AtomicBoolean(false);
    ICallback<Object> callback = new ICallback<Object>() {

        @Override
        public void success(Object o) {
            success.set(true);
            callbackJsonObject = (JsonObject) o;
        }

        @Override
        public void failure(ClientException ex) {
            failure.set(true);
        }
    };
    request.send(HttpMethod.GET, callback, null);
    assertTrue(success.get());
    assertFalse(failure.get());
    assertNotNull(callbackJsonObject);
    assertEquals("zzz", callbackJsonObject.get("id").getAsString());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ICallback(com.microsoft.graph.concurrency.ICallback) JsonObject(com.google.gson.JsonObject) ClientException(com.microsoft.graph.core.ClientException) Test(org.junit.Test)

Example 5 with ClientException

use of com.microsoft.graph.core.ClientException 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;
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) BufferedOutputStream(java.io.BufferedOutputStream) URL(java.net.URL) HeaderOption(com.microsoft.graph.options.HeaderOption) IOException(java.io.IOException) ClientException(com.microsoft.graph.core.ClientException) BufferedInputStream(java.io.BufferedInputStream) ClientException(com.microsoft.graph.core.ClientException) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

ClientException (com.microsoft.graph.core.ClientException)16 ICallback (com.microsoft.graph.concurrency.ICallback)10 Test (org.junit.Test)6 InputStream (java.io.InputStream)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 JsonObject (com.google.gson.JsonObject)3 QueryOption (com.microsoft.graph.options.QueryOption)3 HashMap (java.util.HashMap)3 IProgressCallback (com.microsoft.graph.concurrency.IProgressCallback)2 MockExecutors (com.microsoft.graph.concurrency.MockExecutors)2 IDirectoryObjectCollectionWithReferencesPage (com.microsoft.graph.extensions.IDirectoryObjectCollectionWithReferencesPage)2 User (com.microsoft.graph.extensions.User)2 MockLogger (com.microsoft.graph.logger.MockLogger)2 Option (com.microsoft.graph.options.Option)2 MockSerializer (com.microsoft.graph.serializer.MockSerializer)2 BufferedInputStream (java.io.BufferedInputStream)2 IOException (java.io.IOException)2 URL (java.net.URL)2 LinkedList (java.util.LinkedList)2 SharedPreferences (android.content.SharedPreferences)1