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

The following examples show how to use io.reactivex.Single#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: DynamicClientRegistrationServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private Single<Client> sanitizeTemplate(Client template) {
    if(!template.isTemplate()) {
        return Single.error(new InvalidClientMetadataException("Client behind software_id is not a template"));
    }
    //Erase potential confidential values.
    template.setClientId(SecureRandomString.generate());
    template.setDomain(domain.getId());
    template.setId(null);
    template.setClientSecret(null);
    template.setClientName(ClientServiceImpl.DEFAULT_CLIENT_NAME);
    template.setRedirectUris(null);
    template.setSectorIdentifierUri(null);
    template.setJwks(null);
    template.setJwksUri(null);
    //Set it as non template
    template.setTemplate(false);

    return Single.just(template);
}
 
Example 2
Source File: RemoteSearchSource.java    From Melophile with Apache License 2.0 6 votes vote down vote up
@Override
public Single<List<TrackEntity>> moreTracks() {
  Page<?> page = queryMap.get(Type.TRACK);
  if (page != null) {
    if (page.isLast) {
      return Single.just(new ArrayList<>());
    }
    return service.searchTracksPage(TrackEntity.Filter.start()
            .nextPage(page).limit(100).createOptions())
            .map(result -> {
              if (result != null) {
                queryMap.put(Type.TRACK, result);
                return result.collection;
              }
              return null;
            }).map(filter::filterTracks);
  }
  return Single.error(new IllegalArgumentException("You haven't made a query!"));
}
 
Example 3
Source File: DynamicClientRegistrationServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private Single<DynamicClientRegistrationRequest> validateIdTokenEncryptionAlgorithm(DynamicClientRegistrationRequest request) {
    if(request.getIdTokenEncryptedResponseEnc()!=null && request.getIdTokenEncryptedResponseAlg()==null) {
        return Single.error(new InvalidClientMetadataException("When id_token_encrypted_response_enc is included, id_token_encrypted_response_alg MUST also be provided"));
    }
    //if id_token_encrypted_response_alg is provided, it must be valid.
    if(request.getIdTokenEncryptedResponseAlg()!=null && request.getIdTokenEncryptedResponseAlg().isPresent()) {
        if(!JWAlgorithmUtils.isValidIdTokenResponseAlg(request.getIdTokenEncryptedResponseAlg().get())) {
            return Single.error(new InvalidClientMetadataException("Unsupported id_token_encrypted_response_alg value"));
        }
        if(request.getIdTokenEncryptedResponseEnc()!=null && request.getIdTokenEncryptedResponseEnc().isPresent()) {
            if(!JWAlgorithmUtils.isValidIdTokenResponseEnc(request.getIdTokenEncryptedResponseEnc().get())) {
                return Single.error(new InvalidClientMetadataException("Unsupported id_token_encrypted_response_enc value"));
            }
        }
        else {
            //Apply default value if id_token_encrypted_response_alg is informed and not id_token_encrypted_response_enc.
            request.setIdTokenEncryptedResponseEnc(Optional.of(JWAlgorithmUtils.getDefaultIdTokenResponseEnc()));
        }
    }
    return Single.just(request);
}
 
Example 4
Source File: PermissionTicketServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
/**
 * Validate if all requested resources are known and contains the requested scopes.
 * Resources must belong to the same resource owner.
 * @param requestedPermissions Requested resources and associated scopes.
 * @param registeredResources Current registered resource sets.
 * @param requestedResourcesIds List of current requested resource set ids.
 * @return Permission requests input parameter if ok, else an error.
 */
private Single<List<PermissionRequest>> validatePermissionRequest(List<PermissionRequest> requestedPermissions, List<Resource> registeredResources, List<String> requestedResourcesIds) {
    //Check fetched resources is not empty
    if(registeredResources==null || registeredResources.isEmpty()) {
        return Single.error(InvalidPermissionRequestException.INVALID_RESOURCE_ID);
    }

    //Resources must belong to the same resource owner
    if (registeredResources.size() > 1 && registeredResources.stream().map(Resource::getUserId).distinct().count() > 1) {
        return Single.error(InvalidPermissionRequestException.INVALID_RESOURCE_OWNER);
    }

    //Build map with resource ID as key.
    Map<String, Resource> resourceSetMap = registeredResources.stream().collect(Collectors.toMap(Resource::getId, resource -> resource));

    //If the fetched resources does not contains all the requested ids, then return an invalid resource id error.
    if(!resourceSetMap.keySet().containsAll(requestedResourcesIds)) {
        return Single.error(InvalidPermissionRequestException.INVALID_RESOURCE_ID);
    }

    //If current resource set does not contains all the requested scopes, then return an invalid scope error.
    for(PermissionRequest requestResourceScope:requestedPermissions) {
        Resource fetchedResource = resourceSetMap.get(requestResourceScope.getResourceId());
        if(!fetchedResource.getResourceScopes().containsAll(requestResourceScope.getResourceScopes())) {
            return Single.error(InvalidPermissionRequestException.INVALID_SCOPE_RESOURCE);
        }
    }

    //If there is some duplicated resource ids request, merge them.
    if(resourceSetMap.entrySet().size() < requestedPermissions.size()) {
        requestedPermissions = mergeSameResourceRequest(requestedPermissions);
    }

    //Everything is matching.
    return Single.just(requestedPermissions);
}
 
Example 5
Source File: RequestObjectServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Single<JWT> readRequestObjectFromURI(String requestUri, Client client) {
    try {
        if (requestUri.startsWith(RESOURCE_OBJECT_URN_PREFIX)) {
            // Extract the identifier
            String identifier = requestUri.substring(RESOURCE_OBJECT_URN_PREFIX.length());

            return requestObjectRepository.findById(identifier)
                    .switchIfEmpty(Single.error(new InvalidRequestObjectException()))
                    .flatMap((Function<RequestObject, Single<JWT>>) req -> {
                        if (req.getExpireAt().after(new Date())) {
                            return readRequestObject(req.getPayload(), client);
                        }

                        return Single.error(new InvalidRequestObjectException());
                    });
        } else {
            return webClient.getAbs(UriBuilder.fromHttpUrl(requestUri).build().toString())
                    .rxSend()
                    .map(HttpResponse::bodyAsString)
                    .flatMap((Function<String, Single<JWT>>) s -> readRequestObject(s, client));
        }
    }
    catch (IllegalArgumentException | URISyntaxException ex) {
        return Single.error(new InvalidRequestObjectException(requestUri+" is not valid."));
    }
}
 
Example 6
Source File: MongoAuditReporter.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Single<Map<Object, Object>> aggregate(ReferenceType referenceType, String referenceId, AuditReportableCriteria criteria, Type analyticsType) {
    // build query
    Bson query = query(referenceType, referenceId, criteria);
    switch (analyticsType) {
        case DATE_HISTO:
            return executeHistogram(criteria, query);
        case GROUP_BY:
            return executeGroupBy(criteria, query);
        case COUNT:
            return executeCount(query);
        default:
            return Single.error(new IllegalArgumentException("Analytics [" + analyticsType + "] cannot be calculated"));
    }
}
 
Example 7
Source File: GetPlaylists.java    From Melophile with Apache License 2.0 5 votes vote down vote up
@Override
public Single<PlaylistSet> buildUseCase(MelophileTheme theme) {
  if (theme != null) {
    return repository.getPlaylistsBy(theme)
            .map(list -> new PlaylistSet(theme, list));
  }
  return Single.error(new IllegalArgumentException("Melophile theme is null!"));
}
 
Example 8
Source File: AbstractMessageProcessor.java    From adamant-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Single<Transaction<? extends TransactionAsset>> buildNormalizedTransaction(T message) {
    //TODO: Rewrite the error handling so that any error is displayed under the message.
    if (!api.isAuthorized()){return Single.error(new NotAuthorizedException("Not authorized"));}

    KeyPair keyPair = api.getKeyPair();
    Account account = api.getAccount();

    long currentMessageCost = this.calculateMessageCostInAdamant(message);
    if (currentMessageCost > account.getBalance()){
        return Single.error(
                new NotEnoughAdamantBalanceException(
                        "Not enough adamant. Cost:" + currentMessageCost + ". Balance:" + account.getBalance()
                )
        );
    }

    try {
        return publicKeyStorage.findPublicKey(message.getCompanionId())
                .singleOrError()
                .observeOn(Schedulers.computation())
                .flatMap(publicKey -> buildTransactionMessage(message, publicKey))
                .flatMap((unnormalizedTransactionMessage -> Single.fromPublisher(
                        api.getNormalizedTransaction(unnormalizedTransactionMessage)
                                .subscribeOn(Schedulers.io())
                                .observeOn(Schedulers.computation())
                )))
                .flatMap((transactionWasNormalized -> {
                    if (transactionWasNormalized.isSuccess()) {
                        Transaction<? extends TransactionAsset> transaction = transactionWasNormalized.getTransaction();
                        transaction.setSenderId(account.getAddress());

                        transaction.setSignature(
                                encryptor.createTransactionSignature(
                                        transaction,
                                        keyPair
                                )
                        );

                        return Single.just(transaction);
                    } else {
                        return Single.error(new Exception(transactionWasNormalized.getError()));
                    }
                }));
    } catch (Exception ex) {
        ex.printStackTrace();
        return Single.error(ex);
    }
}
 
Example 9
Source File: StoreApiImpl.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public Single<ApiResponse<Order>> getOrderById(Long orderId) {
    return Single.error(new ApiException("Not Implemented").setStatusCode(501));
}
 
Example 10
Source File: UserApiImpl.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public Single<ApiResponse<Void>> createUsersWithListInput(List<User> user) {
    return Single.error(new ApiException("Not Implemented").setStatusCode(501));
}
 
Example 11
Source File: GrpcBurstNodeService.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
@Override
public Single<byte[]> generateSubscriptionCancelTransaction(byte[] senderPublicKey, BurstID subscription, BurstValue fee, int deadline) {
    return Single.error(new UnsupportedOperationException("GRPC Client does not support this API call yet")); // TODO
}
 
Example 12
Source File: PetApiImpl.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public Single<ApiResponse<ModelApiResponse>> uploadFile(Long petId,String additionalMetadata,FileUpload file) {
    return Single.error(new ApiException("Not Implemented").setStatusCode(501));
}
 
Example 13
Source File: GrantTypeUtils.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
/**
 * <pre>
 * Check:
 *  - grant types are null or empty, or contains unknown grant types.
 *  - refresh_token does not come with authorization_code, password or client_credentials grant.
 *  - client_credentials grant come with another grant that require user authentication.
 * </pre>
 * @param application Application with grant_type to validate.
 * @return Single client or error
 */
public static Single<Application> validateGrantTypes(Application application) {
    // no application to check, continue
    if (application==null) {
        return Single.error(new InvalidClientMetadataException("No application to validate grant"));
    }

    // no application settings to check, continue
    if (application.getSettings() == null) {
        return Single.just(application);
    }

    // no application oauth settings to check, continue
    if (application.getSettings().getOauth() == null) {
        return Single.just(application);
    }

    // Each security domain can have multiple extension grant with the same grant_type
    // we must split the client authorized grant types to get the real grant_type value
    ApplicationOAuthSettings oAuthSettings = application.getSettings().getOauth();
    List<String> formattedClientGrantTypes = oAuthSettings.getGrantTypes() == null ? null : oAuthSettings.getGrantTypes().stream().map(str -> str.split(EXTENSION_GRANT_SEPARATOR)[0]).collect(Collectors.toList());
    if(!isSupportedGrantType(formattedClientGrantTypes)) {
        return Single.error(new InvalidClientMetadataException("Missing or invalid grant type."));
    }

    //Ensure correspondance between response & grant types.
    completeGrantTypeCorrespondance(application);

    //refresh_token are not allowed for all grant types...
    Set<String> grantTypeSet = Collections.unmodifiableSet(new HashSet<>(oAuthSettings.getGrantTypes()));
    if(grantTypeSet.contains(REFRESH_TOKEN)) {
        //Hybrid is not managed yet and AM does not support refresh token for client_credentials for now...
        List<String> allowedRefreshTokenGrant = Arrays.asList(AUTHORIZATION_CODE, PASSWORD, JWT_BEARER);//, CLIENT_CREDENTIALS, HYBRID);
        //return true if there is no element in common
        if(Collections.disjoint(formattedClientGrantTypes, allowedRefreshTokenGrant)) {
            return Single.error(new InvalidClientMetadataException(
                    REFRESH_TOKEN+" grant type must be associated with one of "+String.join(", ",allowedRefreshTokenGrant)
            ));
        }
    }

    /*
     * Uncomment when ready to setup a "non expert mode" on the AM user interface"
     * It is not recommended to mix client and user authentication within the same application.
     * (Aka client_credentials and authorization_code, implicit or password...)
    if(grantTypeSet.contains(CLIENT_CREDENTIALS)) {
        //If client_credentials come with at least one of belows grant
        if(!Collections.disjoint(client.getAuthorizedGrantTypes(),Arrays.asList(AUTHORIZATION_CODE, IMPLICIT, PASSWORD, HYBRID, DEVIDE_CODE))) {
            return Single.error(new InvalidClientMetadataException(
                    CLIENT_CREDENTIALS+" must not be associated with another grant that imply user authentication"
            ));
        }
    }
    */

    return Single.just(application);
}
 
Example 14
Source File: JWEServiceImpl.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public Single<JWT> decrypt(String jwt, Client client) {
    try {
        // Parse a first time to check if the JWT is encrypted
        JWT parsedJwt = JWTParser.parse(jwt);

        if (parsedJwt instanceof EncryptedJWT) {

            JWEObject jweObject = JWEObject.parse(jwt);

            JWEAlgorithm algorithm = jweObject.getHeader().getAlgorithm();

            //RSA decryption
            if (RSACryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.RSA_KEY_ENCRYPTION(), jwk ->
                        new RSADecrypter(JWKConverter.convert((RSAKey) jwk))
                );
            }
            //Curve decryption (Elliptic "EC" & Edward "OKP")
            else if (ECDHCryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.CURVE_KEY_ENCRYPTION(), jwk -> {
                    if (KeyType.EC.getValue().equals(jwk.getKty())) {
                        return new ECDHDecrypter(JWKConverter.convert((ECKey) jwk));
                    }
                    return new X25519Decrypter(JWKConverter.convert((OKPKey) jwk));
                });
            }
            //AES decryption ("OCT" keys)
            else if (AESCryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.OCT_KEY_ENCRYPTION(algorithm), jwk ->
                        new AESDecrypter(JWKConverter.convert((OCTKey) jwk))
                );
            }
            //Direct decryption ("OCT" keys)
            else if (DirectCryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.OCT_KEY_ENCRYPTION(jweObject.getHeader().getEncryptionMethod()), jwk ->
                        new DirectDecrypter(JWKConverter.convert((OCTKey) jwk))
                );
            }
            //Password Base decryption ("OCT" keys)
            else if (PasswordBasedCryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.OCT_KEY_ENCRYPTION(), jwk -> {
                    OctetSequenceKey octKey = JWKConverter.convert((OCTKey) jwk);
                    return new PasswordBasedDecrypter(octKey.getKeyValue().decode());
                });
            }

            return Single.error(new ServerErrorException("Unable to perform Json Web Decryption, unsupported algorithm: " + algorithm.getName()));
        } else {
            return Single.just(parsedJwt);
        }
    } catch (Exception ex) {
        return Single.error(ex);
    }
}
 
Example 15
Source File: ApiClient.java    From andela-crypto-app with Apache License 2.0 4 votes vote down vote up
public static Single<Country> loadRate(Country oldCountry) {
    long minutesBefore = System.currentTimeMillis() - (10 * 60 * 1000);
    if (oldCountry.refreshedAt > minutesBefore)
        return Single.error(new Throwable("No refresh needed!"));

    return getApi().getPrice(oldCountry.code, BTC_ETH)
            .map(response -> {
                HttpUrl url = response.raw().request().url();
                String from = url.queryParameter(Api.FROM_SYMBOL);

                if (TextUtils.isEmpty(from)) {
                    return null;
                }

                Exchange exchange = response.body();
                if (exchange == null) {
                    return null;
                }

                if (ObjectsCompat.equals(oldCountry.code, from)) {
                    int btcStatus = Country.SAME;
                    if (oldCountry.btc != -1) {
                        if (exchange.bitcoin > oldCountry.btc) {
                            btcStatus = Country.RISE;
                        } else if (exchange.bitcoin < oldCountry.btc) {
                            btcStatus = Country.DROP;
                        }
                    }

                    int ethStatus = Country.SAME;
                    if (oldCountry.eth != -1) {
                        if (exchange.bitcoin > oldCountry.btc) {
                            ethStatus = Country.RISE;
                        } else if (exchange.bitcoin < oldCountry.btc) {
                            ethStatus = Country.DROP;
                        }
                    }
                    oldCountry.btcStatus = btcStatus;
                    oldCountry.ethStatus = ethStatus;

                    oldCountry.eth = exchange.ethereum;
                    oldCountry.btc = exchange.bitcoin;
                    oldCountry.refreshedAt = System.currentTimeMillis();
                    return oldCountry;
                }
                return null;
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example 16
Source File: GrpcBurstNodeService.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
@Override
public Single<byte[]> generateTransferAssetTransaction(byte[] senderPublicKey, BurstAddress recipient, BurstID assetId, BurstValue quantity, BurstValue fee, int deadline) {
    return Single.error(new UnsupportedOperationException("GRPC Client does not support this API call yet")); // TODO
}
 
Example 17
Source File: SingleReturnValueHandlerTest.java    From rxjava-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/throw")
public Single<Object> error() {
    return Single.error(new RuntimeException("Unexpected"));
}
 
Example 18
Source File: GrpcBurstNodeService.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
@Override
public Single<byte[]> generateTransactionWithEncryptedMessage(BurstAddress recipient, byte[] senderPublicKey, BurstValue fee, int deadline, BurstEncryptedMessage message) {
    return Single.error(new UnsupportedOperationException("GRPC Client does not support this API call yet")); // TODO

}
 
Example 19
Source File: GrpcBurstNodeService.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
@Override
public Single<byte[]> generateTransactionWithMessage(BurstAddress recipientAddress, byte[] recipientPublicKey, byte[] senderPublicKey, BurstValue fee, int deadline, String message) {
    return Single.error(new UnsupportedOperationException("GRPC Client does not support this API call yet")); // TODO
}
 
Example 20
Source File: SingleDeferredResultTest.java    From Java-9-Spring-Webflux with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/throw")
public Single<Object> error() {
    return Single.error(new RuntimeException("Unexpected"));
}