Example usage for java.util Objects requireNonNull

List of usage examples for java.util Objects requireNonNull

Introduction

In this page you can find the example usage for java.util Objects requireNonNull.

Prototype

public static <T> T requireNonNull(T obj) 

Source Link

Document

Checks that the specified object reference is not null .

Usage

From source file:it.reply.orchestrator.utils.EnumUtils.java

/**
 * <p>/*from  ww  w.j a v a 2s  .c  om*/
 * Retrieve a enum value from its name and its class.
 * </p>
 * 
 * <p>
 * The enum must extends {@link Named}, and the name value should be the one that would be
 * returned from {@link Named#getName()}.
 * </p>
 * 
 * @param enumClass
 *          the class of the enum
 * @param name
 *          the enum name
 * @return the enum value, can be null
 */
@Nullable
public static <T extends Enum<T> & Named> T fromName(Class<T> enumClass, String name) {
    Objects.requireNonNull(enumClass);
    Objects.requireNonNull(name);
    for (T enumItem : org.apache.commons.lang3.EnumUtils.getEnumList(enumClass)) {
        if (name.equals(enumItem.getName())) {
            return enumItem;
        }
    }
    return null;
}

From source file:Main.java

/**
 * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested
 * {@code numElements} elements are not available, it will wait for them up to the specified
 * timeout.//from w  w w  . j  ava2 s .c  o  m
 *
 * Taken from Google Guava 18.0 Queues
 *
 * @param q the blocking queue to be drained
 * @param buffer where to add the transferred elements
 * @param numElements the number of elements to be waited for
 * @param timeout how long to wait before giving up, in units of {@code unit}
 * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
 * @param <E> the type of the queue
 * @return the number of elements transferred
 * @throws InterruptedException if interrupted while waiting
 */
public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout,
        TimeUnit unit) throws InterruptedException {
    buffer = Objects.requireNonNull(buffer);
    /*
     * This code performs one System.nanoTime() more than necessary, and in return, the time to
     * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
     * the timeout arbitrarily inaccurate, given a queue that is slow to drain).
     */
    long deadline = System.nanoTime() + unit.toNanos(timeout);
    int added = 0;
    while (added < numElements) {
        // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
        // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
        added += q.drainTo(buffer, numElements - added);
        if (added < numElements) { // not enough elements immediately available; will have to poll
            E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
            if (e == null) {
                break; // we already waited enough, and there are no more elements in sight
            }
            buffer.add(e);
            added++;
        }
    }
    return added;
}

From source file:me.ferrybig.javacoding.webmapper.EndpointResult.java

public EndpointResult(Result result, T data, ContentType<T> contentType) {
    this.result = Objects.requireNonNull(result);
    this.data = Objects.requireNonNull(data);
    this.contentType = Objects.requireNonNull(contentType);
}

From source file:onl.area51.httpd.util.ContentTypeResolver.java

public static void register(String suffix, ContentType ct) {
    Objects.requireNonNull(suffix);
    Objects.requireNonNull(ct);/*from   ww  w .  ja va  2  s. c o m*/
    String s = suffix.trim().toLowerCase();
    int i = suffix.lastIndexOf('.');
    if (i > 0) {
        throw new IllegalArgumentException("Invalid suffix " + suffix);
    }
    CONTENT_TYPES.putIfAbsent(i == 0 ? s : ("." + s), ct);
}

From source file:org.elasticsearch.packaging.util.ServerUtils.java

public static void waitForElasticsearch(String status, String index) throws IOException {

    Objects.requireNonNull(status);

    // we loop here rather than letting httpclient handle retries so we can measure the entire waiting time
    final long startTime = System.currentTimeMillis();
    long timeElapsed = 0;
    boolean started = false;
    while (started == false && timeElapsed < waitTime) {
        try {/*w  ww.j  a v a  2 s.  c  om*/

            final HttpResponse response = Request.Get("http://localhost:9200/_cluster/health")
                    .connectTimeout((int) timeoutLength).socketTimeout((int) timeoutLength).execute()
                    .returnResponse();

            if (response.getStatusLine().getStatusCode() >= 300) {
                final String statusLine = response.getStatusLine().toString();
                final String body = EntityUtils.toString(response.getEntity());
                throw new RuntimeException(
                        "Connecting to elasticsearch cluster health API failed:\n" + statusLine + "\n" + body);
            }

            started = true;

        } catch (HttpHostConnectException e) {
            // we want to retry if the connection is refused
            LOG.debug("Got connection refused when waiting for cluster health", e);
        }

        timeElapsed = System.currentTimeMillis() - startTime;
    }

    if (started == false) {
        throw new RuntimeException("Elasticsearch did not start");
    }

    final String url;
    if (index == null) {
        url = "http://localhost:9200/_cluster/health?wait_for_status=" + status + "&timeout=60s&pretty";
    } else {
        url = "http://localhost:9200/_cluster/health/" + index + "?wait_for_status=" + status
                + "&timeout=60s&pretty";

    }

    final String body = makeRequest(Request.Get(url));
    assertThat("cluster health response must contain desired status", body, containsString(status));
}

From source file:jgnash.convert.exportantur.csv.CsvExport.java

public static void exportAccount(final Account account, final LocalDate startDate, final LocalDate endDate,
        final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);

    // force a correct file extension
    final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".csv";

    final CSVFormat csvFormat = CSVFormat.EXCEL.withQuoteMode(QuoteMode.ALL);

    try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
            Files.newOutputStream(Paths.get(fileName)), StandardCharsets.UTF_8);
            final CSVPrinter writer = new CSVPrinter(new BufferedWriter(outputStreamWriter), csvFormat)) {

        outputStreamWriter.write('\ufeff'); // write UTF-8 byte order mark to the file for easier imports

        writer.printRecord("Account", "Number", "Debit", "Credit", "Balance", "Date", "Timestamp", "Memo",
                "Payee", "Reconciled");

        // write the transactions
        final List<Transaction> transactions = account.getTransactions(startDate, endDate);

        final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2).toFormatter();

        final DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendLiteral('-').appendValue(MONTH_OF_YEAR, 2).appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2).appendLiteral(' ').appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2)
                .toFormatter();//from www.  j a  v  a 2  s.  c  o  m

        for (final Transaction transaction : transactions) {
            final String date = dateTimeFormatter.format(transaction.getLocalDate());

            final String timeStamp = timestampFormatter.format(transaction.getTimestamp());

            final String credit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) < 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String debit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) > 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String balance = account.getBalanceAt(transaction).toPlainString();

            final String reconciled = transaction.getReconciled(account) == ReconciledState.NOT_RECONCILED
                    ? Boolean.FALSE.toString()
                    : Boolean.TRUE.toString();

            writer.printRecord(account.getName(), transaction.getNumber(), debit, credit, balance, date,
                    timeStamp, transaction.getMemo(), transaction.getPayee(), reconciled);
        }
    } catch (final IOException e) {
        Logger.getLogger(CsvExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:org.eclipse.hono.service.auth.TenantApiTrustOptions.java

private TenantApiTrustOptions(final HonoTrustManagerFactory factory) {
    this.factory = Objects.requireNonNull(factory);
}

From source file:eu.itesla_project.iidm.datasource.Bzip2FileDataSource.java

public Bzip2FileDataSource(Path directory, String baseName, DataSourceObserver observer) {
    this.directory = Objects.requireNonNull(directory);
    this.baseName = Objects.requireNonNull(baseName);
    this.observer = observer;
}

From source file:com.cloudera.oryx.ml.param.Unordered.java

Unordered(Collection<T> values) {
    Objects.requireNonNull(values);
    Preconditions.checkArgument(!values.isEmpty());
    this.values = new ArrayList<>(values);
}

From source file:org.trustedanalytics.metadata.datacatalog.DataCatalogFactory.java

public DataCatalog get(RestOperations restOperations) {
    Objects.requireNonNull(restOperations);

    return new DataCatalogClient(restOperations, dataCatalogUrl);
}