Java Code Examples for io.reactivex.Completable#error()

The following examples show how to use io.reactivex.Completable#error() . 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: EntrypointServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private Completable validate(Entrypoint entrypoint, Entrypoint oldEntrypoint) {

        if (oldEntrypoint != null && oldEntrypoint.isDefaultEntrypoint()) {
            // Only the url of the default entrypoint can be updated.
            if (!entrypoint.getName().equals(oldEntrypoint.getName())
                    || !entrypoint.getDescription().equals(oldEntrypoint.getDescription())
                    || !entrypoint.getTags().equals(oldEntrypoint.getTags())) {
                return Completable.error(new InvalidEntrypointException("Only the url of the default entrypoint can be updated."));
            }
        }

        try {
            // Try to instantiate uri to check if it's a valid endpoint url.
            URL url = new URL(entrypoint.getUrl());
            if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) {
                throw new MalformedURLException();
            }

            return Completable.complete();
        } catch (MalformedURLException e) {
            return Completable.error(new InvalidEntrypointException("Entrypoint must have a valid url."));
        }
    }
 
Example 2
Source File: SaveContactsInteractor.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
public Completable execute() {
    Map<String, Contact> contacts = chatsStorage.getContacts();

    Transaction<TransactionStateAsset> contactListTransaction = null;
    try {
        contactListTransaction = kvsHelper.transformToTransaction(
                Constants.KVS_CONTACT_LIST,
                true,
                contacts
        );
    } catch (EncryptionException e) {
        return Completable.error(e);
    }

    return apiKvsProvider.put(contactListTransaction);
}
 
Example 3
Source File: AdamantApiWrapper.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
public Completable updateBalance(){
    try {
        return Flowable.defer(() -> api.authorize(keyPair.getPublicKeyString().toLowerCase()))
                .doOnNext((authorization -> {
                    if (authorization.getAccount() == null){return;}

                    if (this.account == null){
                        this.account = authorization.getAccount();
                        return;
                    }

                    this.account.setBalance(authorization.getAccount().getBalance());
                    this.account.setUnconfirmedBalance(authorization.getAccount().getUnconfirmedBalance());

                }))
                .compose(requestControl())
                .ignoreElements();
    } catch (Exception ex){
        return Completable.error(ex);
    }
}
 
Example 4
Source File: RxBleConnectionImpl.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
@RequiresApi(21 /* Build.VERSION_CODES.LOLLIPOP */)
public Completable requestConnectionPriority(int connectionPriority, long delay, @NonNull TimeUnit timeUnit) {
    if (connectionPriority != BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER
            && connectionPriority != BluetoothGatt.CONNECTION_PRIORITY_BALANCED
            && connectionPriority != BluetoothGatt.CONNECTION_PRIORITY_HIGH) {
        return Completable.error(
                new IllegalArgumentException(
                        "Connection priority must have valid value from BluetoothGatt (received "
                                + connectionPriority + ")"
                )
        );
    }

    if (delay <= 0) {
        return Completable.error(new IllegalArgumentException("Delay must be bigger than 0"));
    }

    return operationQueue
            .queue(operationsProvider.provideConnectionPriorityChangeOperation(connectionPriority, delay, timeUnit))
            .ignoreElements();
}
 
Example 5
Source File: FeatureRepository.java    From ground-android with Apache License 2.0 6 votes vote down vote up
private Completable updateLocalFeature(RemoteDataEvent<Feature> event) {
  switch (event.getEventType()) {
    case ENTITY_LOADED:
    case ENTITY_MODIFIED:
      return event.value().map(localDataStore::mergeFeature).orElse(Completable.complete());
    case ENTITY_REMOVED:
      // TODO: Delete features:
      // localDataStore.removeFeature(event.getEntityId());
      return Completable.complete();
    case ERROR:
      event.error().ifPresent(e -> Timber.d(e, "Invalid features in remote db ignored"));
      return Completable.complete();
    default:
      return Completable.error(
          new UnsupportedOperationException("Event type: " + event.getEventType()));
  }
}
 
Example 6
Source File: StorageManager.java    From ground-android with Apache License 2.0 5 votes vote down vote up
/** Save a copy of bitmap locally. */
public Completable savePhoto(Bitmap bitmap, String filename) {
  try {
    File file = fileUtil.saveBitmap(bitmap, filename);
    Timber.d("Photo saved %s : %b", filename, file.exists());
    return Completable.complete();
  } catch (IOException e) {
    return Completable.error(e);
  }
}
 
Example 7
Source File: UserValidator.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public static Completable validate(User user) {

        if (!isValid(user.getUsername(), USERNAME_PATTERN_COMPILED)) {
            return Completable.error(new InvalidUserException(String.format("Username [%s] is not a valid value", user.getUsername())));
        }

        if (!EmailValidator.isValid(user.getEmail())) {
            return Completable.error(new EmailFormatInvalidException(user.getEmail()));
        }

        if (!isValid(user.getFirstName(), NAME_STRICT_PATTERN_COMPILED)) {
            return Completable.error(new InvalidUserException(String.format("First name [%s] is not a valid value", user.getFirstName())));
        }

        if (!isValid(user.getLastName(), NAME_STRICT_PATTERN_COMPILED)) {
            return Completable.error(new InvalidUserException(String.format("Last name [%s] is not a valid value", user.getLastName())));
        }

        if (!isValid(user.getDisplayName(), NAME_LAX_PATTERN_COMPILED)) {
            return Completable.error(new InvalidUserException(String.format("Display name [%s] is not a valid value", user.getDisplayName())));
        }

        if (!isValid(user.getNickName(), NAME_LAX_PATTERN_COMPILED)) {
            return Completable.error(new InvalidUserException(String.format("Nick name [%s] is not a valid value", user.getNickName())));
        }

        if (user.getExternalId() != null && user.getExternalId().length() > DEFAULT_MAX_LENGTH) {
            return Completable.error(new InvalidUserException(String.format("External id [%s] is not a valid value", user.getExternalId())));
        }

        return Completable.complete();
    }
 
Example 8
Source File: NotificationAndIndicationManager.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@NonNull
static Completable writeClientCharacteristicConfig(
        final BluetoothGattCharacteristic bluetoothGattCharacteristic,
        final DescriptorWriter descriptorWriter,
        final byte[] value
) {
    final BluetoothGattDescriptor descriptor = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID);
    if (descriptor == null) {
        return Completable.error(new BleCannotSetCharacteristicNotificationException(
                bluetoothGattCharacteristic,
                BleCannotSetCharacteristicNotificationException.CANNOT_FIND_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR,
                null
        ));
    }

    return descriptorWriter.writeDescriptor(descriptor, value)
            .onErrorResumeNext(new Function<Throwable, CompletableSource>() {
                @Override
                public CompletableSource apply(Throwable throwable) {
                    return Completable.error(new BleCannotSetCharacteristicNotificationException(
                            bluetoothGattCharacteristic,
                            BleCannotSetCharacteristicNotificationException.CANNOT_WRITE_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR,
                            throwable
                    ));
                }
            });
}
 
Example 9
Source File: ConfigCase.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Set a new MetadataDownload configuration.
 * @param metadataIdsConfig Configuration with the metadata ids.
 * @return {@code Completable} that completes when the configuration is changed.
 */
public Completable setMetadataDownloadConfig(WebApiRepository.GetMetadataIdsConfig metadataIdsConfig) {
    if (metadataIdsConfig == null) {
        return Completable.error(new IllegalArgumentException("Received null config"));
    }
    return localDbRepository.setMetadataDownloadConfig(metadataIdsConfig);
}
 
Example 10
Source File: ConfigCase.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Set the gateway number to send the SMS. This is a required parameter before sending SMS.
 * @param gatewayNumber The gateway numberf
 * @return {@code Completable} that completes when the configuration is changed.
 */
public Completable setGatewayNumber(String gatewayNumber) {
    if (gatewayNumber == null || gatewayNumber.isEmpty()) {
        return Completable.error(new IllegalArgumentException("Gateway number can't be empty"));
    }
    return localDbRepository.setGatewayNumber(gatewayNumber);
}
 
Example 11
Source File: InterceptorsTest.java    From rx-jersey with MIT License 5 votes vote down vote up
@Override
public Completable intercept(ContainerRequestContext requestContext) {
    if (requestContext.getHeaders().containsKey("error")) {
        return Completable.error(new BadRequestException("Surprise!"));
    }
    return Completable.complete();
}
 
Example 12
Source File: SQLTestBase.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
protected Completable rxAssertEquals(Object expected, Object actual) {
  Completable completable;
  try {
    Assert.assertEquals(expected, actual);
    completable = Completable.complete();
  } catch (AssertionError error) {
    completable = Completable.error(error);
  }
  return completable;
}
 
Example 13
Source File: RoomLocalDataStore.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Transaction
@Override
public Completable applyAndEnqueue(ObservationMutation mutation) {
  try {
    return apply(mutation).andThen(enqueue(mutation));
  } catch (LocalDataStoreException e) {
    return Completable.error(e);
  }
}
 
Example 14
Source File: OngoingSubmissionsStore.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Completable removeOngoingSubmission(Integer id) {
    if (id == null) {
        return Completable.error(new IllegalArgumentException("Wrong submission id"));
    }
    return getOngoingSubmissions().flatMapCompletable(submissions -> {
        submissions.remove(id);
        return saveOngoingSubmissions(ongoingSubmissions);
    });
}
 
Example 15
Source File: FCMNotificationServiceFacade.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Completable unsubscribe() {
    String unsubscribeTransactionJson = settings.getUnsubscribeFcmTransaction();
    if (unsubscribeTransactionJson == null || unsubscribeTransactionJson.isEmpty()) {
        //TODO: Обязательно проверь в тестах кейс с выходом
        return Completable.complete();
    }

    try {

        Transaction<TransactionChatAsset> transaction = gson.fromJson(
                unsubscribeTransactionJson,
                new TypeToken<Transaction<TransactionChatAsset>>() {}.getType()
        );

        AdamantPushSubscriptionMessageFactory subscribeFactory = (AdamantPushSubscriptionMessageFactory)messageFactoryProvider
                .getFactoryByType(SupportedMessageListContentType.ADAMANT_SUBSCRIBE_ON_NOTIFICATION);
        MessageProcessor<AdamantPushSubscriptionMessage> messageProcessor = subscribeFactory.getMessageProcessor();

        return messageProcessor
                .sendTransaction(Single.just(transaction))
                .ignoreElement()
                .doOnComplete(() -> {
                    settings.setNotificationToken("");
                    settings.setUnsubscribeFcmTransaction("");
                });
    } catch (Exception ex) {
        return Completable.error(ex);
    }

}
 
Example 16
Source File: SwitchPushNotificationServiceInteractor.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
public Completable changeNotificationFacade(SupportedPushNotificationFacadeType newFacadeType) {
    SupportedPushNotificationFacadeType pushNotificationFacadeType = settings.getPushNotificationFacadeType();
    PushNotificationServiceFacade currentFacade = facades.get(pushNotificationFacadeType);
    PushNotificationServiceFacade newFacade = facades.get(newFacadeType);

    if ((currentFacade != null) && (newFacade != null)) {
        return currentFacade
                .unsubscribe()
                .andThen(newFacade.subscribe())
                .doOnComplete(() -> settings.setPushNotificationFacadeType(newFacadeType))
                .timeout(BuildConfig.DEFAULT_OPERATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } else {
        return Completable.error(new NotSupportedPushNotificationFacade("Not Supported facade: " + pushNotificationFacadeType));
    }
}
 
Example 17
Source File: PgXianDatasource.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public Completable destroy() {
    try {
        pgDatasource.close();
        return Completable.complete();
    } catch (Throwable e) {
        return Completable.error(e);
    }
}
 
Example 18
Source File: CompletableToCompletionStageTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 4 votes vote down vote up
@Override
protected Completable createInstanceFailingImmediately(RuntimeException e) {
    return Completable.error(e);
}
 
Example 19
Source File: NullWhorlwind.java    From whorlwind with Apache License 2.0 4 votes vote down vote up
@Override public Completable write(String name, ByteString value) {
  return Completable.error(new UnsupportedOperationException());
}
 
Example 20
Source File: VerticleTest.java    From vertx-rx with Apache License 2.0 4 votes vote down vote up
@Override
public Completable rxStop() {
  return Completable.error(err);
}