Search in sources :

Example 1 with GraphServiceException

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

the class BatchResponseContentTest method doesNotIncludeVerboseInformation.

@Test
public void doesNotIncludeVerboseInformation() {
    String responsebody = "{\"responses\":[{\"id\":\"1\",\"status\":400,\"headers\":{\"Cache-Control\":\"no-cache\",\"x-ms-resource-unit\":\"1\",\"Content-Type\":\"application/json\"},\"body\":{\"error\":{\"code\":\"Request_BadRequest\",\"message\":\"Avalueisrequiredforproperty'displayName'ofresource'User'.\",\"innerError\":{\"date\":\"2021-02-02T19:19:38\",\"request-id\":\"408b8e64-4047-4c97-95b6-46e9f212ab48\",\"client-request-id\":\"102910da-260c-3028-0fb3-7d6903a02622\"}}}}]}";
    ISerializer serializer = new DefaultSerializer(new DefaultLogger() {

        {
            setLoggingLevel(LoggerLevel.ERROR);
        }
    });
    BatchResponseContent batchresponse = serializer.deserializeObject(responsebody, BatchResponseContent.class);
    if (batchresponse != null) {
        if (// this is done by the batch request in the fluent API
        batchresponse.responses != null)
            for (final BatchResponseStep<?> step : batchresponse.responses) {
                step.serializer = serializer;
            }
        try {
            batchresponse.getResponseById("1").getDeserializedBody(BatchRequestContent.class);
        } catch (GraphServiceException ex) {
            final GraphErrorResponse response = ex.getError();
            assertNotNull(response);
            assertNotNull(response.error);
            assertNotNull(response.error.message);
            assertEquals(ex.getMessage(false), ex.getMessage());
        }
    } else
        fail("batch response was null");
}
Also used : DefaultSerializer(com.microsoft.graph.serializer.DefaultSerializer) GraphErrorResponse(com.microsoft.graph.http.GraphErrorResponse) GraphServiceException(com.microsoft.graph.http.GraphServiceException) DefaultLogger(com.microsoft.graph.logger.DefaultLogger) ISerializer(com.microsoft.graph.serializer.ISerializer) Test(org.junit.jupiter.api.Test)

Example 2 with GraphServiceException

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

the class BatchResponseContentTest method includeVerboseInformation.

@Test
public void includeVerboseInformation() {
    String responsebody = "{\"responses\":[{\"id\":\"1\",\"status\":400,\"headers\":{\"Cache-Control\":\"no-cache\",\"x-ms-resource-unit\":\"1\",\"Content-Type\":\"application/json\"},\"body\":{\"error\":{\"code\":\"Request_BadRequest\",\"message\":\"Avalueisrequiredforproperty'displayName'ofresource'User'.\",\"innerError\":{\"date\":\"2021-02-02T19:19:38\",\"request-id\":\"408b8e64-4047-4c97-95b6-46e9f212ab48\",\"client-request-id\":\"102910da-260c-3028-0fb3-7d6903a02622\"}}}}]}";
    ISerializer serializer = new DefaultSerializer(new DefaultLogger() {

        {
            setLoggingLevel(LoggerLevel.DEBUG);
        }
    });
    BatchResponseContent batchresponse = serializer.deserializeObject(responsebody, BatchResponseContent.class);
    if (batchresponse != null) {
        if (// this is done by the batch request in the fluent API
        batchresponse.responses != null)
            for (final BatchResponseStep<?> step : batchresponse.responses) {
                step.serializer = serializer;
            }
        try {
            batchresponse.getResponseById("1").getDeserializedBody(BatchRequestContent.class);
        } catch (GraphServiceException ex) {
            final GraphErrorResponse response = ex.getError();
            assertNotNull(response);
            assertNotNull(response.error);
            assertNotNull(response.error.message);
            assertEquals(ex.getMessage(true), ex.getMessage());
        }
    } else
        fail("batch response was null");
}
Also used : DefaultSerializer(com.microsoft.graph.serializer.DefaultSerializer) GraphErrorResponse(com.microsoft.graph.http.GraphErrorResponse) GraphServiceException(com.microsoft.graph.http.GraphServiceException) DefaultLogger(com.microsoft.graph.logger.DefaultLogger) ISerializer(com.microsoft.graph.serializer.ISerializer) Test(org.junit.jupiter.api.Test)

Example 3 with GraphServiceException

use of com.microsoft.graph.http.GraphServiceException in project opencga by opencb.

the class AzureADAuthenticationManager method getUsersFromRemoteGroup.

@Override
public List<User> getUsersFromRemoteGroup(String groupId) throws CatalogException {
    IDirectoryObjectCollectionWithReferencesPage membersPage;
    try {
        membersPage = graphServiceClient.groups(groupId).members().buildRequest().get();
    } catch (GraphServiceException e) {
        logger.error("Group '{}' not found.", groupId);
        throw new CatalogException("Group '" + groupId + "' not found");
    } catch (ClientException e) {
        logger.error("Graph query could not be performed: {}", e.getMessage());
        throw e;
    }
    List<com.microsoft.graph.models.extensions.User> graphUserList = new ArrayList<>();
    ObjectMapper jsonObjectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    boolean moreElems = true;
    while (membersPage.getCurrentPage() != null && moreElems) {
        for (DirectoryObject directoryObject : membersPage.getCurrentPage()) {
            com.microsoft.graph.models.extensions.User graphUser;
            if ("#microsoft.graph.user".equals(directoryObject.oDataType)) {
                try {
                    graphUser = jsonObjectMapper.readValue(String.valueOf(directoryObject.getRawObject()), com.microsoft.graph.models.extensions.User.class);
                    graphUserList.add(graphUser);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (membersPage.getNextPage() != null) {
            membersPage = membersPage.getNextPage().buildRequest().get();
        } else {
            moreElems = false;
        }
    }
    return extractUserInformation(graphUserList);
}
Also used : GraphServiceException(com.microsoft.graph.http.GraphServiceException) CatalogException(org.opencb.opencga.catalog.exceptions.CatalogException) IOException(java.io.IOException) IDirectoryObjectCollectionWithReferencesPage(com.microsoft.graph.requests.extensions.IDirectoryObjectCollectionWithReferencesPage) ClientException(com.microsoft.graph.core.ClientException) DirectoryObject(com.microsoft.graph.models.extensions.DirectoryObject) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 4 with GraphServiceException

use of com.microsoft.graph.http.GraphServiceException in project azure-ad-plugin by jenkinsci.

the class AzureSecurityRealm method createSecurityComponents.

@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents((AuthenticationManager) authentication -> {
        if (authentication instanceof AzureAuthenticationToken) {
            return authentication;
        }
        throw new BadCredentialsException("Unexpected authentication type: " + authentication);
    }, username -> {
        if (username == null) {
            throw new UserMayOrMayNotExistException2("Can't find a user with no username");
        }
        if (isDisableGraphIntegration()) {
            throw new UserMayOrMayNotExistException2("Can't lookup a user if graph integration is disabled");
        }
        AzureAdUser azureAdUser = caches.get(username, (cacheKey) -> {
            GraphServiceClient<Request> azureClient = getAzureClient();
            String userId = ObjId2FullSidMap.extractObjectId(username);
            if (userId == null) {
                userId = username;
            }
            // as we look up by object id we don't know if it's a user or a group :(
            try {
                com.microsoft.graph.models.User activeDirectoryUser = azureClient.users(userId).buildRequest().get();
                if (activeDirectoryUser != null & activeDirectoryUser.id == null) {
                    // known to happen when subject is a group with display name only and starts with a #
                    return null;
                }
                AzureAdUser user = requireNonNull(AzureAdUser.createFromActiveDirectoryUser(activeDirectoryUser));
                List<AzureAdGroup> groups = AzureCachePool.get(azureClient).getBelongingGroupsByOid(user.getObjectID());
                user.setAuthorities(groups);
                return user;
            } catch (GraphServiceException e) {
                if (e.getResponseCode() == NOT_FOUND) {
                    return null;
                } else if (e.getResponseCode() == BAD_REQUEST) {
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.log(Level.FINE, "Failed to lookup user with userid '" + userId, e);
                    } else {
                        LOGGER.log(Level.WARNING, "Failed to lookup user with userid '" + userId + "'." + " Enable 'Fine' Logging for more information.");
                    }
                    return null;
                }
                throw e;
            }
        });
        if (azureAdUser == null) {
            throw new UsernameNotFoundException("Cannot find user: " + username);
        }
        return azureAdUser;
    });
}
Also used : HierarchicalStreamWriter(com.thoughtworks.xstream.io.HierarchicalStreamWriter) FilterChain(javax.servlet.FilterChain) ServiceBuilder(com.github.scribejava.core.builder.ServiceBuilder) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AccessToken(com.azure.core.credential.AccessToken) UUIDValidator(com.microsoft.jenkins.azuread.utils.UUIDValidator) Mailer(hudson.tasks.Mailer) DataBoundConstructor(org.kohsuke.stapler.DataBoundConstructor) ServletException(javax.servlet.ServletException) HttpRedirect(org.kohsuke.stapler.HttpRedirect) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service) StringUtils(org.apache.commons.lang3.StringUtils) Collections.singletonList(java.util.Collections.singletonList) HttpClients(com.microsoft.graph.httpcore.HttpClients) SecurityRealm(hudson.security.SecurityRealm) Proxy(java.net.Proxy) Group(com.microsoft.graph.models.Group) NonNull(edu.umd.cs.findbugs.annotations.NonNull) Map(java.util.Map) ClientSecretCredentialBuilder(com.azure.identity.ClientSecretCredentialBuilder) GroupDetails(hudson.security.GroupDetails) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) TokenCredentialAuthProvider(com.microsoft.graph.authentication.TokenCredentialAuthProvider) InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) Converter(com.thoughtworks.xstream.converters.Converter) Request(okhttp3.Request) ListBoxModel(hudson.util.ListBoxModel) HttpResponse(org.kohsuke.stapler.HttpResponse) Collections.emptyList(java.util.Collections.emptyList) Jenkins(jenkins.model.Jenkins) MarshallingContext(com.thoughtworks.xstream.converters.MarshallingContext) JenkinsJVM(jenkins.util.JenkinsJVM) Credentials(okhttp3.Credentials) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Header(org.kohsuke.stapler.Header) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) List(java.util.List) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) UserMayOrMayNotExistException2(hudson.security.UserMayOrMayNotExistException2) RandomStringUtils(org.apache.commons.lang3.RandomStringUtils) HeaderOption(com.microsoft.graph.options.HeaderOption) Authentication(org.springframework.security.core.Authentication) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GroupCollectionPage(com.microsoft.graph.requests.GroupCollectionPage) GraphServiceClient(com.microsoft.graph.requests.GraphServiceClient) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) QueryParameter(org.kohsuke.stapler.QueryParameter) StaplerRequest(org.kohsuke.stapler.StaplerRequest) Supplier(com.google.common.base.Supplier) HashMap(java.util.HashMap) ClientSecretCredential(com.azure.identity.ClientSecretCredential) Cache(com.github.benmanes.caffeine.cache.Cache) CrumbExclusion(hudson.security.csrf.CrumbExclusion) UserProperty(hudson.tasks.Mailer.UserProperty) AZURE_CHINA(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_CHINA) AzureEnvironment.getServiceRoot(com.microsoft.jenkins.azuread.AzureEnvironment.getServiceRoot) TokenRequestContext(com.azure.core.credential.TokenRequestContext) Level(java.util.logging.Level) HttpServletRequest(javax.servlet.http.HttpServletRequest) Objects.requireNonNull(java.util.Objects.requireNonNull) Suppliers(com.google.common.base.Suppliers) Extension(hudson.Extension) User(hudson.model.User) LinkedList(java.util.LinkedList) Util(hudson.Util) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) UnmarshallingContext(com.thoughtworks.xstream.converters.UnmarshallingContext) QueryOption(com.microsoft.graph.options.QueryOption) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) ProxyConfiguration(hudson.ProxyConfiguration) FormValidation(hudson.util.FormValidation) HttpResponses(org.kohsuke.stapler.HttpResponses) Descriptor(hudson.model.Descriptor) DataBoundSetter(org.kohsuke.stapler.DataBoundSetter) HttpClientRetriever(io.jenkins.plugins.azuresdk.HttpClientRetriever) HttpServletResponse(javax.servlet.http.HttpServletResponse) GraphServiceException(com.microsoft.graph.http.GraphServiceException) IOException(java.io.IOException) AZURE_US_GOVERNMENT_L4(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_US_GOVERNMENT_L4) AZURE_GERMANY(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_GERMANY) AZURE_US_GOVERNMENT_L5(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_US_GOVERNMENT_L5) AzureAdApi(com.microsoft.jenkins.azuread.scribe.AzureAdApi) SecurityListener(jenkins.security.SecurityListener) AzureEnvironment.getAuthorityHost(com.microsoft.jenkins.azuread.AzureEnvironment.getAuthorityHost) TimeUnit(java.util.concurrent.TimeUnit) Option(com.microsoft.graph.options.Option) URLEncoder(java.net.URLEncoder) OkHttpClient(okhttp3.OkHttpClient) JwtClaims(org.jose4j.jwt.JwtClaims) AZURE_PUBLIC_CLOUD(com.microsoft.jenkins.azuread.AzureEnvironment.AZURE_PUBLIC_CLOUD) Secret(hudson.util.Secret) CheckForNull(edu.umd.cs.findbugs.annotations.CheckForNull) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) GraphServiceException(com.microsoft.graph.http.GraphServiceException) Request(okhttp3.Request) StaplerRequest(org.kohsuke.stapler.StaplerRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UserMayOrMayNotExistException2(hudson.security.UserMayOrMayNotExistException2)

Example 5 with GraphServiceException

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

the class BatchResponseContentTest method deserializesErrorsProperly.

@Test
public void deserializesErrorsProperly() {
    String responsebody = "{\"responses\":[{\"id\":\"1\",\"status\":400,\"headers\":{\"Cache-Control\":\"no-cache\",\"x-ms-resource-unit\":\"1\",\"Content-Type\":\"application/json\"},\"body\":{\"error\":{\"code\":\"Request_BadRequest\",\"message\":\"Avalueisrequiredforproperty'displayName'ofresource'User'.\",\"innerError\":{\"date\":\"2021-02-02T19:19:38\",\"request-id\":\"408b8e64-4047-4c97-95b6-46e9f212ab48\",\"client-request-id\":\"102910da-260c-3028-0fb3-7d6903a02622\"}}}}]}";
    ISerializer serializer = new DefaultSerializer(mock(ILogger.class));
    BatchResponseContent batchresponse = serializer.deserializeObject(responsebody, BatchResponseContent.class);
    if (batchresponse != null) {
        if (// this is done by the batch request in the fluent API
        batchresponse.responses != null)
            for (final BatchResponseStep<?> step : batchresponse.responses) {
                step.serializer = serializer;
            }
        assertThrows(GraphServiceException.class, () -> {
            batchresponse.getResponseById("1").getDeserializedBody(BatchRequestContent.class);
        });
        try {
            batchresponse.getResponseById("1").getDeserializedBody(BatchRequestContent.class);
        } catch (GraphServiceException ex) {
            final GraphErrorResponse response = ex.getError();
            assertNotNull(response);
            assertNotNull(response.error);
            assertNotNull(response.error.message);
        }
    } else
        fail("batch response was null");
}
Also used : DefaultSerializer(com.microsoft.graph.serializer.DefaultSerializer) GraphErrorResponse(com.microsoft.graph.http.GraphErrorResponse) GraphServiceException(com.microsoft.graph.http.GraphServiceException) ILogger(com.microsoft.graph.logger.ILogger) ISerializer(com.microsoft.graph.serializer.ISerializer) Test(org.junit.jupiter.api.Test)

Aggregations

GraphServiceException (com.microsoft.graph.http.GraphServiceException)6 GraphErrorResponse (com.microsoft.graph.http.GraphErrorResponse)3 DefaultSerializer (com.microsoft.graph.serializer.DefaultSerializer)3 ISerializer (com.microsoft.graph.serializer.ISerializer)3 ClientException (com.microsoft.graph.core.ClientException)2 DefaultLogger (com.microsoft.graph.logger.DefaultLogger)2 Test (org.junit.jupiter.api.Test)2 AccessToken (com.azure.core.credential.AccessToken)1 TokenRequestContext (com.azure.core.credential.TokenRequestContext)1 ClientSecretCredential (com.azure.identity.ClientSecretCredential)1 ClientSecretCredentialBuilder (com.azure.identity.ClientSecretCredentialBuilder)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Cache (com.github.benmanes.caffeine.cache.Cache)1 Caffeine (com.github.benmanes.caffeine.cache.Caffeine)1 ServiceBuilder (com.github.scribejava.core.builder.ServiceBuilder)1 OAuth20Service (com.github.scribejava.core.oauth.OAuth20Service)1 Supplier (com.google.common.base.Supplier)1 Suppliers (com.google.common.base.Suppliers)1 TokenCredentialAuthProvider (com.microsoft.graph.authentication.TokenCredentialAuthProvider)1 HttpClients (com.microsoft.graph.httpcore.HttpClients)1