io.reactivex.Maybe Java Examples

The following examples show how to use io.reactivex.Maybe. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ImpressionStorageClientTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void storeImpression_noErrors_storesAppendedCampaigns() {
  when(storageClient.read(any(CampaignImpressionsParser.class)))
      .thenReturn(
          Maybe.just(
              CampaignImpressionList.newBuilder()
                  .addAlreadySeenCampaigns(campaignImpression)
                  .build()));
  ArgumentCaptor<CampaignImpressionList> campaignImpressionListArgumentCaptor =
      ArgumentCaptor.forClass(CampaignImpressionList.class);
  impressionStorageClient.storeImpression(campaignImpression).subscribe();
  verify(storageClient).write(campaignImpressionListArgumentCaptor.capture());

  assertThat(campaignImpressionListArgumentCaptor.getValue().getAlreadySeenCampaignsList())
      .containsExactly(campaignImpression, campaignImpression);
}
 
Example #2
Source File: UserConsentEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRevokeConsent() throws Exception {
    when(userService.findById(anyString())).thenReturn(Maybe.just(new User()));
    when(userService.revokeConsent(anyString(), anyString(), any())).thenReturn(Completable.complete());

    router.route("/users/:userId/consents/:consentId")
            .handler(rc -> {
                JWT token = new JWT();
                token.setSub("sub");
                rc.put(OAuth2AuthHandler.TOKEN_CONTEXT_KEY, token);
                rc.next();
            })
            .handler(userConsentEndpointHandler::revoke)
            .failureHandler(new ErrorHandler());

    testRequest(
            HttpMethod.DELETE, "/users/user-id/consents/consent-id",
            req -> req.putHeader(HttpHeaders.AUTHORIZATION.toString(), "Bearer token"),
            204,
            "No Content", null);
}
 
Example #3
Source File: RxJavaTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void multiExportToRx() {
    Multi<String> multi = Multi.createFrom().items("hello", "bonjour");
    // tag::multi-export[]
    Completable completable = multi.convert().with(MultiRxConverters.toCompletable());
    Single<Optional<String>> single = multi.convert().with(MultiRxConverters.toSingle());
    Single<String> single2 = multi.convert().with(MultiRxConverters
            .toSingle().onEmptyThrow(() -> new Exception("D'oh!")));
    Maybe<String> maybe = multi.convert().with(MultiRxConverters.toMaybe());
    Observable<String> observable = multi.convert().with(MultiRxConverters.toObservable());
    Flowable<String> flowable = multi.convert().with(MultiRxConverters.toFlowable());
    // end::multi-export[]

    completable.test().assertComplete();
    single.test().assertValue(o -> o.isPresent() && o.get().equals("hello"));
    single2.test().assertValue("hello");
    maybe.test().assertValue("hello");
    observable.test().assertValues("hello", "bonjour").assertComplete();
    flowable.test().assertValues("hello", "bonjour").assertComplete();
}
 
Example #4
Source File: ScopeServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotUpdate_malformedIconUri() {
    UpdateScope updateScope = new UpdateScope();
    updateScope.setIconUri("malformedIconUri");

    when(scopeRepository.findById("toUpdateId")).thenReturn(Maybe.just(new Scope()));

    TestObserver testObserver = new TestObserver();
    scopeService.update(DOMAIN, "toUpdateId",updateScope).subscribe(testObserver);

    testObserver.assertError(MalformedIconUriException.class);
    testObserver.assertNotComplete();

    verify(scopeRepository, times(1)).findById("toUpdateId");
    verify(scopeRepository, never()).update(any(Scope.class));
}
 
Example #5
Source File: DemoMaybe.java    From Reactive-Programming-With-Java-9 with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub

	Maybe<List<String>> month_maybe = Maybe.create(emitter -> {
		try {
			String[] monthArray = { "Jan", "Feb", "Mar", "Apl", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov",
					"Dec" };

			List<String> months = Arrays.asList(monthArray);
			if (months != null && !months.isEmpty()) {
				emitter.onSuccess(months);
			} else {
				emitter.onComplete();
			}
		} catch (Exception e) {
			emitter.onError(e);
		}
	});
	month_maybe.subscribe(s->System.out.println(s));
	
}
 
Example #6
Source File: ManagementAuthenticationProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAuthenticate_secondAuthProvider() {
    AuthenticationProvider authenticationProvider = mock(AuthenticationProvider.class);
    when(authenticationProvider.loadUserByUsername(any(io.gravitee.am.identityprovider.api.Authentication.class))).thenReturn(Maybe.error(new BadCredentialsException()));
    AuthenticationProvider authenticationProvider2 = mock(AuthenticationProvider.class);
    when(authenticationProvider2.loadUserByUsername(any(io.gravitee.am.identityprovider.api.Authentication.class))).thenReturn(Maybe.just(new DefaultUser("username")));
    when(identityProviderManager.getIdentityProvider("idp1")).thenReturn(new IdentityProvider());
    when(identityProviderManager.getIdentityProvider("idp2")).thenReturn(new IdentityProvider());
    when(identityProviderManager.get("idp1")).thenReturn(authenticationProvider);
    when(identityProviderManager.get("idp2")).thenReturn(authenticationProvider2);

    Authentication authentication = managementAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken("username", "password"));

    Assert.assertNotNull(authentication);
    verify(identityProviderManager, times(1)).get("idp1");
    verify(identityProviderManager, times(1)).get("idp2");
}
 
Example #7
Source File: RecorderControllerTest.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Test
public void snapshotWithNoSensors() {
  final RecorderControllerImpl rc =
      new RecorderControllerImpl(
          getContext(),
          getAppAccount(),
          environment,
          new RecorderListenerRegistry(),
          null,
          dataController,
          scheduler,
          Delay.ZERO,
          new FakeUnitAppearanceProvider());

  Maybe<String> snapshot =
      rc.generateSnapshotText(Lists.<String>newArrayList(sensorId), sensorRegistry);
  assertEquals("[No sensors observed]", snapshot.test().values().toString());
}
 
Example #8
Source File: ApplicationServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void update_clientCredentials_ok() {
    when(applicationRepository.findById(any())).thenReturn(Maybe.just(new Application()));
    when(applicationRepository.update(any(Application.class))).thenReturn(Single.just(new Application()));
    when(domainService.findById(any())).thenReturn(Maybe.just(new Domain()));
    when(eventService.create(any())).thenReturn(Single.just(new Event()));
    when(scopeService.validateScope(any(),any())).thenReturn(Single.just(true));

    Application toPatch = new Application();
    toPatch.setDomain(DOMAIN);
    ApplicationSettings settings = new ApplicationSettings();
    ApplicationOAuthSettings oAuthSettings = new ApplicationOAuthSettings();
    oAuthSettings.setGrantTypes(Arrays.asList("client_credentials"));
    oAuthSettings.setResponseTypes(Arrays.asList());
    settings.setOauth(oAuthSettings);
    toPatch.setSettings(settings);

    TestObserver testObserver = applicationService.update(toPatch).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();

    verify(applicationRepository, times(1)).findById(any());
    verify(applicationRepository, times(1)).update(any(Application.class));
}
 
Example #9
Source File: HttpEntityArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unused")
void handle(
		String string,
		Mono<String> monoString,
		HttpEntity<String> httpEntity,
		HttpEntity<Mono<String>> monoBody,
		HttpEntity<Flux<String>> fluxBody,
		HttpEntity<Single<String>> singleBody,
		HttpEntity<io.reactivex.Single<String>> rxJava2SingleBody,
		HttpEntity<Maybe<String>> rxJava2MaybeBody,
		HttpEntity<Observable<String>> observableBody,
		HttpEntity<io.reactivex.Observable<String>> rxJava2ObservableBody,
		HttpEntity<Flowable<String>> flowableBody,
		HttpEntity<CompletableFuture<String>> completableFutureBody,
		RequestEntity<String> requestEntity,
		Mono<HttpEntity<String>> httpEntityMono) {}
 
Example #10
Source File: ClientServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPatch_mobileApplication_googleCase() {
    Application client = new Application();
    client.setDomain(DOMAIN);

    PatchClient patchClient = new PatchClient();
    patchClient.setAuthorizedGrantTypes(Optional.of(Arrays.asList("authorization_code")));
    patchClient.setRedirectUris(Optional.of(Arrays.asList("com.google.app:/callback")));

    when(applicationService.findById("my-client")).thenReturn(Maybe.just(client));
    when(applicationService.update(any(Application.class))).thenReturn(Single.just(new Application()));

    TestObserver testObserver = clientService.patch(DOMAIN, "my-client", patchClient).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();

    verify(applicationService, times(1)).findById(anyString());
    verify(applicationService, times(1)).update(any(Application.class));
}
 
Example #11
Source File: MemberResource.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@DELETE
@ApiOperation(value = "Remove a membership",
        notes = "User must have the DOMAIN_MEMBER[DELETE] permission on the specified domain " +
                "or DOMAIN_MEMBER[DELETE] permission on the specified environment " +
                "or DOMAIN_MEMBER[DELETE] permission on the specified organization")
@ApiResponses({
        @ApiResponse(code = 204, message = "Membership successfully deleted"),
        @ApiResponse(code = 500, message = "Internal server error")})
public void removeMember(
        @PathParam("organizationId") String organizationId,
        @PathParam("environmentId") String environmentId,
        @PathParam("domain") String domain,
        @PathParam("member") String membershipId,
        @Suspended final AsyncResponse response) {

    final io.gravitee.am.identityprovider.api.User authenticatedUser = getAuthenticatedUser();

    checkAnyPermission(organizationId, environmentId, domain, Permission.DOMAIN_MEMBER, Acl.DELETE)
            .andThen(domainService.findById(domain)
                    .switchIfEmpty(Maybe.error(new DomainNotFoundException(domain)))
                    .flatMapCompletable(irrelevant -> membershipService.delete(membershipId, authenticatedUser)))
            .subscribe(() -> response.resume(Response.noContent().build()), response::resume);
}
 
Example #12
Source File: ApplicationsResourceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreate() {
    final String domainId = "domain-1";
    final Domain mockDomain = new Domain();
    mockDomain.setId(domainId);

    NewApplication newApplication = new NewApplication();
    newApplication.setName("name");
    newApplication.setType(ApplicationType.SERVICE);

    Application application = new Application();
    application.setId("app-id");
    application.setName("name");
    application.setType(ApplicationType.SERVICE);

    doReturn(Maybe.just(mockDomain)).when(domainService).findById(domainId);
    doReturn(Single.just(application)).when(applicationService).create(eq(domainId), any(NewApplication.class), any());

    final Response response = target("domains")
            .path(domainId)
            .path("applications")
            .request().post(Entity.json(newApplication));
    assertEquals(HttpStatusCode.CREATED_201, response.getStatus());
}
 
Example #13
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotInvokeUserEndpoint_userNotFound() throws Exception {
    JWT jwt = new JWT();
    jwt.setJti("id-token");
    jwt.setAud("client-id");
    jwt.setSub("id-subject");
    jwt.setScope("openid");

    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");

    router.route().order(-1).handler(createOAuth2AuthHandler(oAuth2AuthProvider(jwt, client)));

    when(userService.findById(anyString())).thenReturn(Maybe.empty());

    testRequest(
            HttpMethod.GET, "/userinfo", req -> req.putHeader(HttpHeaders.AUTHORIZATION, "Bearer test-token"),
            HttpStatusCode.UNAUTHORIZED_401, "Unauthorized", null);
}
 
Example #14
Source File: FormServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public Completable delete(ReferenceType referenceType, String referenceId, String formId, User principal) {
    LOGGER.debug("Delete form {}", formId);
    return formRepository.findById(referenceType, referenceId, formId)
            .switchIfEmpty(Maybe.error(new FormNotFoundException(formId)))
            .flatMapCompletable(page -> {
                // create event for sync process
                Event event = new Event(Type.FORM, new Payload(page.getId(), page.getReferenceType(), page.getReferenceId(), Action.DELETE));

                return formRepository.delete(formId)
                        .andThen(eventService.create(event)).toCompletable()
                        .doOnComplete(() -> auditService.report(AuditBuilder.builder(FormTemplateAuditBuilder.class).principal(principal).type(EventType.FORM_TEMPLATE_DELETED).form(page)))
                        .doOnError(throwable -> auditService.report(AuditBuilder.builder(FormTemplateAuditBuilder.class).principal(principal).type(EventType.FORM_TEMPLATE_DELETED).throwable(throwable)));
            })
            .onErrorResumeNext(ex -> {
                if (ex instanceof AbstractManagementException) {
                    return Completable.error(ex);
                }

                LOGGER.error("An error occurs while trying to delete form: {}", formId, ex);
                return Completable.error(new TechnicalManagementException(
                        String.format("An error occurs while trying to delete form: %s", formId), ex));
            });
}
 
Example #15
Source File: RequestBodyArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void emptyBodyWithMaybe() throws Exception {

	MethodParameter param = this.testMethod.annot(requestBody()).arg(Maybe.class, String.class);
	Maybe<String> maybe = resolveValueWithEmptyBody(param);
	StepVerifier.create(maybe.toFlowable())
			.expectNextCount(0)
			.expectError(ServerWebInputException.class)
			.verify();

	param = this.testMethod.annot(requestBody().notRequired()).arg(Maybe.class, String.class);
	maybe = resolveValueWithEmptyBody(param);
	StepVerifier.create(maybe.toFlowable())
			.expectNextCount(0)
			.expectComplete()
			.verify();
}
 
Example #16
Source File: ScopeServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Maybe<Scope> findByDomainAndKey(String domain, String scopeKey) {
    LOGGER.debug("Find scopes by domain: {} and scope key: {}", domain, scopeKey);
    return scopeRepository.findByDomainAndKey(domain, scopeKey)
            .onErrorResumeNext(ex -> {
                LOGGER.error("An error occurs while trying to find scopes by domain: {} and scope key: {}", domain, scopeKey, ex);
                return Maybe.error(new TechnicalManagementException(
                        String.format("An error occurs while trying to find scopes by domain: %s and scope key: %s", domain, scopeKey), ex));
            });
}
 
Example #17
Source File: AuthorizationEndpointTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotInvokeAuthorizationEndpoint_invalidClient() throws Exception {
    when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.empty());

    testRequest(
            HttpMethod.GET,
            "/oauth/authorize?response_type=code&client_id=client-id",
            null,
            resp -> {
                String location = resp.headers().get("location");
                assertNotNull(location);
                assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=invalid_request&error_description=No+client+found+for+client_id+client-id"));
            },
            HttpStatusCode.FOUND_302, "Found", null);
}
 
Example #18
Source File: PermissionTicketServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void remove() {
    when(repository.findById("id")).thenReturn(Maybe.just(new PermissionTicket().setId("id")));
    when(repository.delete("id")).thenReturn(Completable.complete());
    TestObserver<PermissionTicket> testObserver = service.remove("id").test();
    testObserver.assertComplete().assertNoErrors().assertValue(Objects::nonNull);
}
 
Example #19
Source File: UserResourceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetUser_notFound() {
    final String domainId = "domain-id";
    doReturn(Maybe.empty()).when(domainService).findById(domainId);

    final Response response = target("domains/" + domainId).request().get();
    assertEquals(HttpStatusCode.NOT_FOUND_404, response.getStatus());
}
 
Example #20
Source File: EnvironmentServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreate_updateError() {

    Environment existingEnvironment = new Environment();
    existingEnvironment.setId(ENVIRONMENT_ID);
    existingEnvironment.setOrganizationId(ORGANIZATION_ID);

    when(environmentRepository.findById(ENVIRONMENT_ID, ORGANIZATION_ID)).thenReturn(Maybe.just(existingEnvironment));
    when(environmentRepository.update(argThat(environment -> environment.getId().equals(ENVIRONMENT_ID)))).thenReturn(Single.error(new TechnicalManagementException()));

    NewEnvironment newEnvironment = new NewEnvironment();
    newEnvironment.setName("TestName");
    newEnvironment.setDescription("TestDescription");
    newEnvironment.setDomainRestrictions(Collections.singletonList("TestDomainRestriction"));

    DefaultUser createdBy = new DefaultUser("test");
    createdBy.setId(USER_ID);

    TestObserver<Environment> obs = cut.createOrUpdate(ORGANIZATION_ID, ENVIRONMENT_ID, newEnvironment, createdBy).test();

    obs.awaitTerminalEvent();
    obs.assertError(TechnicalManagementException.class);

    verify(auditService, times(1)).report(argThat(builder -> {
        Audit audit = builder.build(new ObjectMapper());
        assertEquals(ReferenceType.ORGANIZATION, audit.getReferenceType());
        assertEquals(ORGANIZATION_ID, audit.getReferenceId());
        assertEquals(createdBy.getId(), audit.getActor().getId());
        assertEquals(EventType.ENVIRONMENT_UPDATED, audit.getType());
        assertEquals(Status.FAILURE, audit.getOutcome().getStatus());

        return true;
    }));
}
 
Example #21
Source File: CurrentTraceContextAssemblyTrackingMatrixTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void callable_maybe_conditional_assembleInScope_subscribeInScope() {
  Maybe<Integer> source, errorSource;
  try (Scope scope = currentTraceContext.newScope(assemblyContext)) {
    source = callableMaybe(subscribeContext)
      .filter(lessThanThreeInAssemblyContext)
      .doOnSuccess(e -> assertInAssemblyContext())
      .doOnComplete(this::assertInAssemblyContext);
    errorSource = callableMaybe(subscribeContext, new IllegalStateException())
      .filter(lessThanThreeInAssemblyContext)
      .doOnError(t -> assertInAssemblyContext())
      .doOnComplete(this::assertInAssemblyContext);
  }

  subscribeInDifferentContext(source.toObservable(), errorSource.toObservable()).assertResult(1);
}
 
Example #22
Source File: TimeLimiterTransformerMaybeTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void otherError() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ZERO));
    TestObserver<?> observer = Maybe.error(new RuntimeException())
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    observer.assertError(RuntimeException.class);
    then(timeLimiter).should()
        .onError(any(RuntimeException.class));
}
 
Example #23
Source File: ImpressionStorageClientTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void isImpressed_ifExperimentImpressed_isTrue() {
  when(storageClient.read(any(CampaignImpressionsParser.class)))
      .thenReturn(Maybe.fromCallable(() -> experimentImpressionList));
  TestSubscriber<Boolean> subscriber =
      impressionStorageClient.isImpressed(experimentalCampaign).toFlowable().test();

  assertThat(subscriber.getEvents().get(0)).containsExactly(true);
}
 
Example #24
Source File: ClientFormsResource.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create a form for a client",
        notes = "User must have APPLICATION_FORM[READ] permission on the specified client " +
                "or APPLICATION_FORM[READ] permission on the specified domain " +
                "or APPLICATION_FORM[READ] permission on the specified environment " +
                "or APPLICATION_FORM[READ] permission on the specified organization")
@ApiResponses({
        @ApiResponse(code = 201, message = "Form successfully created"),
        @ApiResponse(code = 500, message = "Internal server error")})
public void create(
        @PathParam("organizationId") String organizationId,
        @PathParam("environmentId") String environmentId,
        @PathParam("domain") String domain,
        @PathParam("client") String client,
        @ApiParam(name = "email", required = true)
        @Valid @NotNull final NewForm newForm,
        @Suspended final AsyncResponse response) {

    final User authenticatedUser = getAuthenticatedUser();

    checkAnyPermission(organizationId, environmentId, domain, client, Permission.APPLICATION_FORM, Acl.DELETE)
            .andThen(domainService.findById(domain)
                    .switchIfEmpty(Maybe.error(new DomainNotFoundException(domain)))
                    .flatMap(irrelevant -> clientService.findById(client))
                    .switchIfEmpty(Maybe.error(new ClientNotFoundException(client)))
                    .flatMapSingle(irrelevant -> formService.create(domain, client, newForm, authenticatedUser))
                    .map(form -> Response
                            .created(URI.create("/organizations/" + organizationId + "/environments/" + environmentId + "/domains/" + domain + "/clients/" + client + "/forms/" + form.getId()))
                            .entity(form)
                            .build()))
            .subscribe(response::resume, response::resume);
}
 
Example #25
Source File: ExtensionGrantResourceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetExtensionGrant_domainNotFound() {
    final String domainId = "domain-id";
    final String extensionGrantId = "extensionGrant-id";

    doReturn(Maybe.empty()).when(domainService).findById(domainId);

    final Response response = target("domains").path(domainId).path("extensionGrants").path(extensionGrantId).request().get();
    assertEquals(HttpStatusCode.NOT_FOUND_404, response.getStatus());
}
 
Example #26
Source File: PreparedGetObjectTest.java    From storio with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetObjectByQueryWithoutTypeMappingAsMaybe() {
    final GetObjectStub getStub = GetObjectStub.newInstanceWithoutTypeMapping();

    final Maybe<TestItem> testItemMaybe = getStub.storIOSQLite
            .get()
            .object(TestItem.class)
            .withQuery(getStub.query)
            .withGetResolver(getStub.getResolver)
            .prepare()
            .asRxMaybe();

    getStub.verifyQueryBehavior(testItemMaybe);
}
 
Example #27
Source File: MembershipServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotCreate_memberNotFound() {

    Membership membership = new Membership();
    membership.setReferenceId(DOMAIN_ID);
    membership.setReferenceType(ReferenceType.DOMAIN);
    membership.setMemberId("user-id");
    membership.setMemberType(MemberType.USER);
    membership.setRoleId("role-id");

    Role role = new Role();
    role.setId("role-id");
    role.setReferenceId(DOMAIN_ID);
    role.setReferenceType(ReferenceType.DOMAIN);
    role.setAssignableType(ReferenceType.DOMAIN);

    when(userService.findById(ReferenceType.ORGANIZATION, ORGANIZATION_ID, membership.getMemberId())).thenReturn(Single.error(new UserNotFoundException("user-id")));
    when(roleService.findById(role.getId())).thenReturn(Maybe.just(role));
    when(membershipRepository.findByReferenceAndMember(membership.getReferenceType(), membership.getReferenceId(), membership.getMemberType(), membership.getMemberId())).thenReturn(Maybe.empty());

    TestObserver testObserver = membershipService.addOrUpdate(ORGANIZATION_ID, membership).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertNotComplete();
    testObserver.assertError(UserNotFoundException.class);

    verify(membershipRepository, never()).create(any());
}
 
Example #28
Source File: ModuleManager.java    From android-arch-mvvm with Apache License 2.0 5 votes vote down vote up
private static void checkReturnType(Method method1, Method method2) {
    Class<?> returnType;
    Type returnType1, returnType2;
    if (ModuleCall.class.equals(method1.getReturnType())) { // 异步回调的方法
        returnType = method2.getReturnType();
        if (returnType.equals(Observable.class) || returnType.equals(Single.class) || returnType.equals(Flowable.class) || returnType.equals(Maybe.class)) {

            returnType1 = method1.getGenericReturnType();
            returnType2 = method2.getGenericReturnType();

            if (returnType1 instanceof ParameterizedType && returnType2 instanceof ParameterizedType) { // 都带泛型
                // 检查泛型的类型是否一样
                if (!((ParameterizedType) returnType1).getActualTypeArguments()[0].equals(((ParameterizedType) returnType2).getActualTypeArguments()[0])) {
                    throw new IllegalArgumentException(method1.getName() + "方法的返回值类型的泛型的须一样");
                }
            } else if (!(returnType1 instanceof Class && returnType2 instanceof Class)) {
                throw new IllegalArgumentException(method1.getName() + "方法的返回值类型的泛型的须一样");
            }
        } else {
            throw new IllegalArgumentException(String.format("%s::%s的返回值类型必须是Observable,Single,Flowable,Maybe之一", method2.getDeclaringClass().getSimpleName(), method2.getName()));
        }
    } else {
        if (!method1.getGenericReturnType().equals(method2.getGenericReturnType())) { //同步调用的返回值必须一样
            throw new IllegalArgumentException(method1.getName() + "方法的返回值类型不一样");
        }
    }
}
 
Example #29
Source File: ApplicationMembersResource.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@POST
@ApiOperation(value = "Add or update an application member",
        notes = "User must have APPLICATION_MEMBER[CREATE] permission on the specified application " +
                "or APPLICATION_MEMBER[CREATE] permission on the specified domain " +
                "or APPLICATION_MEMBER[CREATE] permission on the specified environment " +
                "or APPLICATION_MEMBER[CREATE] permission on the specified organization")
@ApiResponses({
        @ApiResponse(code = 201, message = "Member has been added or updated successfully"),
        @ApiResponse(code = 400, message = "Membership parameter is not valid"),
        @ApiResponse(code = 500, message = "Internal server error")})
public void addOrUpdateMember(
        @PathParam("organizationId") String organizationId,
        @PathParam("environmentId") String environmentId,
        @PathParam("domain") String domain,
        @PathParam("application") String application,
        @Valid @NotNull NewMembership newMembership,
        @Suspended final AsyncResponse response) {

    final User authenticatedUser = getAuthenticatedUser();

    final Membership membership = convert(newMembership);
    membership.setDomain(domain);
    membership.setReferenceId(application);
    membership.setReferenceType(ReferenceType.APPLICATION);

    checkAnyPermission(organizationId, environmentId, domain, application, Permission.APPLICATION_MEMBER, Acl.CREATE)
            .andThen(domainService.findById(domain)
                    .switchIfEmpty(Maybe.error(new DomainNotFoundException(domain)))
                    .flatMap(__ -> applicationService.findById(application))
                    .switchIfEmpty(Maybe.error(new ApplicationNotFoundException(application)))
                    .flatMapSingle(__ -> membershipService.addOrUpdate(organizationId, membership, authenticatedUser))
                    .flatMap(membership1 -> addDomainUserRoleIfNecessary(organizationId, domain, newMembership, authenticatedUser)
                            .andThen(Single.just(Response
                                    .created(URI.create("/organizations/" + organizationId + "/environments/" + environmentId + "/domains/" + domain + "/applications/" + application + "/members/" + membership1.getId()))
                                    .entity(membership1)
                                    .build()))))
            .subscribe(response::resume, response::resume);
}
 
Example #30
Source File: ApplicationServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdate_clientNotFound() {
    PatchApplication patchClient = Mockito.mock(PatchApplication.class);
    when(applicationRepository.findById("my-client")).thenReturn(Maybe.empty());

    TestObserver testObserver = applicationService.patch(DOMAIN, "my-client", patchClient).test();

    testObserver.assertError(ApplicationNotFoundException.class);
    testObserver.assertNotComplete();

    verify(applicationRepository, times(1)).findById(anyString());
    verify(applicationRepository, never()).update(any(Application.class));
}