Example usage for java.util.function Supplier get

List of usage examples for java.util.function Supplier get

Introduction

In this page you can find the example usage for java.util.function Supplier get.

Prototype

T get();

Source Link

Document

Gets a result.

Usage

From source file:es.upv.grycap.coreutils.fiber.http.Http2Client.java

/**
 * Puts the content of a buffer of bytes to a server via a HTTP PUT request.
 * @param url - URL target of this request
 * @param mediaType - Content-Type header for this request
 * @param supplier - supplies the content of this request
 * @param callback - is called back when the response is readable
 *///w w w.  j a  v  a2  s .  co  m
public void asyncPutBytes(final String url, final String mediaType, final Supplier<byte[]> supplier,
        final Callback callback) {
    final String url2 = requireNonNull(trimToNull(url), "A non-empty URL expected");
    final String mediaType2 = requireNonNull(trimToNull(mediaType), "A non-empty media type expected");
    requireNonNull(supplier, "A valid supplier expected");
    requireNonNull(callback, "A valid callback expected");
    // prepare request
    final Request request = new Request.Builder().url(url2).put(new RequestBody() {
        @Override
        public MediaType contentType() {
            return MediaType.parse(mediaType2 + "; charset=utf-8");
        }

        @Override
        public void writeTo(final BufferedSink sink) throws IOException {
            sink.write(supplier.get());
        }
    }).build();
    // submit request
    client.newCall(request).enqueue(callback);
}

From source file:es.upv.grycap.coreutils.fiber.http.Http2Client.java

/**
 * Posts the content of a buffer of bytes to a server via a HTTP POST request.
 * @param url - URL target of this request
 * @param mediaType - Content-Type header for this request
 * @param supplier - supplies the content of this request
 * @param callback - is called back when the response is readable
 *//*from  w w w  . j  ava  2s . com*/
public void asyncPostBytes(final String url, final String mediaType, final Supplier<byte[]> supplier,
        final Callback callback) {
    final String url2 = requireNonNull(trimToNull(url), "A non-empty URL expected");
    final String mediaType2 = requireNonNull(trimToNull(mediaType), "A non-empty media type expected");
    requireNonNull(supplier, "A valid supplier expected");
    requireNonNull(callback, "A valid callback expected");
    // prepare request
    final Request request = new Request.Builder().url(url2).post(new RequestBody() {
        @Override
        public MediaType contentType() {
            return MediaType.parse(mediaType2 + "; charset=utf-8");
        }

        @Override
        public void writeTo(final BufferedSink sink) throws IOException {
            sink.write(supplier.get());
        }
    }).build();
    // submit request
    client.newCall(request).enqueue(callback);
}

From source file:com.example.app.profile.model.company.CompanyDAO.java

/**
 * New membership type membership type.//from  w  ww. j  a  va 2 s  .  co m
 *
 * @param pt the pt
 * @param info the info
 * @param operations the operations
 *
 * @return the membership type
 */
public MembershipType createMembershipType(ProfileType pt, MembershipTypeInfo info,
        Supplier<List<MembershipOperation>> operations) {
    MembershipType mt = new MembershipType();
    TransientLocalizedObjectKey tlok = info.getNewNameLocalizedObjectKey();
    TransientLocalizedObjectKey dtlok = info.getNewNameLocalizedObjectKey();

    mt.setName(tlok);
    mt.setDescription(dtlok);
    mt.setProgrammaticIdentifier(info.getProgId());
    mt.setDefaultOperations(operations.get());
    mt.setProfileType(pt);

    return mt;
}

From source file:io.github.jeddict.jpa.modeler.properties.PropertiesHandler.java

private static EmbeddedPropertySupport getConvertPropertySupport(String id, String name, String description,
        String keyAttribute, JPAModelerScene scene, final java.util.function.Supplier<Convert> convertProucer) { //Producer is used to get Convert and call getConvert/getMapKeyConvert everytime to clear unused converter list  
    GenericEmbedded entity = new GenericEmbedded(id, name, description);
    entity.setEntityEditor(new ConvertPanel(scene.getModelerFile()));
    entity.setDataListener(new EmbeddedDataListener<Convert>() {
        private Convert convert;

        @Override/*from   w  w  w  .j  ava  2 s.  c o  m*/
        public void init() {
            convert = convertProucer.get();
        }

        @Override
        public Convert getData() {
            return convert;
        }

        @Override
        public void setData(Convert convert) {
            if (keyAttribute != null) {
                convert.setAttributeName(keyAttribute);
            }
            convertProucer.get();//remove all unused converter item from list except at index 0
            //skip
        }

        @Override
        public String getDisplay() {
            if (ConvertValidator.isEmpty(convert)) {
                return NONE_TYPE;
            } else {
                return isNotBlank(convert.getConverter()) ? convert.getConverter() : "Disable Conversion";
            }
        }

    });
    return new EmbeddedPropertySupport(scene.getModelerFile(), entity);
}

From source file:com.ikanow.aleph2.analytics.services.DeduplicationEnrichmentContext.java

/** Common emit logic
 * @param json//www. j  a  v a  2s. co  m
 * @param supplier
 * @return
 */
public Validation<BasicMessageBean, JsonNode> emitObjectCommon(final JsonNode json,
        final Supplier<Validation<BasicMessageBean, JsonNode>> supplier) {
    return checkObjectLogic(json).bind(j -> {
        final boolean is_manual_delete = (1 == json.size());
        final JsonNode _id = (_delete_unhandled_duplicates || is_manual_delete) ? json.get(AnnotationBean._ID)
                : null;
        if (is_manual_delete && (null != _id)) {
            _mutable_state._manual_ids_to_delete.add(_id);
            return Validation.success(json);
        } else {
            if (_delete_unhandled_duplicates || (CustomPolicy.very_strict == _custom_policy))
                _mutable_state._id_set.remove(_id);
            _mutable_state._num_emitted++;
            return supplier.get();
        }
    });

}

From source file:jp.classmethod.aws.dynamodb.DynamoDbRepository.java

/**
 * Translates low level database exceptions to application level exceptions
 *
 * @param e the low level amazon client exception
 * @param action crud action name//from w w w.j a v  a2s. c om
 * @param conditionalSupplier creates condition failed exception (context dependent)
 * @return a translation of the AWS/DynamoDB exception
 */
DataAccessException convertDynamoDBException(AmazonClientException e, String action,
        Supplier<? extends DataAccessException> conditionalSupplier) {

    final String format = "unable to %s entity due to %s.";
    if (e instanceof ConditionalCheckFailedException) {
        return conditionalSupplier.get();
    } else if (e instanceof ProvisionedThroughputExceededException) {
        return new QueryTimeoutException(String.format(Locale.ENGLISH, format, action, "throttling"), e);
    } else if (e instanceof ResourceNotFoundException) {
        return new NonTransientDataAccessResourceException(
                String.format(Locale.ENGLISH, format, action, "table does not exist"), e);
    } else if (e instanceof AmazonServiceException) {
        AmazonServiceException ase = (AmazonServiceException) e;
        if (VALIDATION_EXCEPTION.equals(((AmazonServiceException) e).getErrorCode())) {
            return new InvalidDataAccessResourceUsageException(
                    String.format(Locale.ENGLISH, format, action, "client error"), e);
        } else {
            return new DynamoDbServiceException(
                    String.format(Locale.ENGLISH, format, action, "DynamoDB service error"), ase);
        }
    } else {
        return new InvalidDataAccessResourceUsageException(
                String.format(Locale.ENGLISH, format, action, "client error"), e);
    }
}

From source file:com.example.app.communication.service.NotificationService.java

/**
 *   Send email//from  ww w.  jav  a  2  s. com
 * @param emailTemplate the email template
 * @param context the context
 * @param defaultFromNameSupplier the supplier for the name of the default sender.
 */
public void sendEmail(EmailTemplate emailTemplate, EmailTemplateContext context,
        @Nullable Supplier<String> defaultFromNameSupplier) {
    try {
        final FileEntityMailDataHandler mdh = _emailTemplateProcessor.process(context, emailTemplate);
        try (MailMessage mm = new MailMessage(mdh)) {
            if (mm.getToRecipients().isEmpty()) {
                final EmailTemplateRecipient recipientAttribute = context.getRecipientAttribute();
                if (recipientAttribute != null)
                    mm.addTo(recipientAttribute.getEmailAddress());
            }
            if (mm.getFrom().isEmpty()) {
                UnparsedAddress from = new UnparsedAddress(_systemSender,
                        defaultFromNameSupplier != null ? defaultFromNameSupplier.get() : null);
                mm.addFrom(from);
            }
            sendEmail(mm);
        }
    } catch (EmailTemplateException | MailDataHandlerException e) {
        _logger.error("Unable to send message.", e);
    }
}

From source file:org.elasticsearch.xpack.test.rest.XPackRestIT.java

/**
 * Executes an API call using the admin context, waiting for it to succeed.
 *///www  .  j  ava2  s .c om
private void awaitCallApi(String apiName, Map<String, String> params, List<Map<String, Object>> bodies,
        CheckedFunction<ClientYamlTestResponse, Boolean, IOException> success, Supplier<String> error)
        throws Exception {

    AtomicReference<IOException> exceptionHolder = new AtomicReference<>();
    awaitBusy(() -> {
        try {
            ClientYamlTestResponse response = callApi(apiName, params, bodies, getApiCallHeaders());
            if (response.getStatusCode() == HttpStatus.SC_OK) {
                exceptionHolder.set(null);
                return success.apply(response);
            }
            return false;
        } catch (IOException e) {
            exceptionHolder.set(e);
        }
        return false;
    });

    IOException exception = exceptionHolder.get();
    if (exception != null) {
        throw new IllegalStateException(error.get(), exception);
    }
}

From source file:com.haulmont.cuba.client.sys.FileLoaderClientImpl.java

protected void saveStreamWithServlet(FileDescriptor fd, Supplier<InputStream> inputStreamSupplier,
        @Nullable StreamingProgressListener streamingListener)
        throws FileStorageException, InterruptedException {

    Object context = serverSelector.initContext();
    String selectedUrl = serverSelector.getUrl(context);
    if (selectedUrl == null) {
        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName());
    }//from  www. j  a v  a  2 s .  c om

    ClientConfig clientConfig = configuration.getConfig(ClientConfig.class);
    String fileUploadContext = clientConfig.getFileUploadContext();

    while (true) {
        String url = selectedUrl + fileUploadContext + "?s=" + userSessionSource.getUserSession().getId()
                + "&f=" + fd.toUrlParam();

        try (InputStream inputStream = inputStreamSupplier.get()) {
            InputStreamProgressEntity.UploadProgressListener progressListener = null;
            if (streamingListener != null) {
                progressListener = streamingListener::onStreamingProgressChanged;
            }

            HttpPost method = new HttpPost(url);
            method.setEntity(new InputStreamProgressEntity(inputStream, ContentType.APPLICATION_OCTET_STREAM,
                    progressListener));

            HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
            HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
            try {
                HttpResponse response = client.execute(method);

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    break;
                } else {
                    log.debug("Unable to upload file to {}\n{}", url, response.getStatusLine());
                    selectedUrl = failAndGetNextUrl(context);
                    if (selectedUrl == null) {
                        throw new FileStorageException(FileStorageException.Type.fromHttpStatus(statusCode),
                                fd.getName());
                    }
                }
            } catch (InterruptedIOException e) {
                log.trace("Uploading has been interrupted");
                throw new InterruptedException("File uploading is interrupted");
            } catch (IOException e) {
                log.debug("Unable to upload file to {}\n{}", url, e);
                selectedUrl = failAndGetNextUrl(context);
                if (selectedUrl == null) {
                    throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
                }
            } finally {
                connectionManager.shutdown();
            }
        } catch (IOException | RetryUnsupportedException e) {
            throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
        }
    }
}