Example usage for com.google.common.base Preconditions checkElementIndex

List of usage examples for com.google.common.base Preconditions checkElementIndex

Introduction

In this page you can find the example usage for com.google.common.base Preconditions checkElementIndex.

Prototype

public static int checkElementIndex(int index, int size, @Nullable String desc) 

Source Link

Document

Ensures that index specifies a valid element in an array, list or string of size size .

Usage

From source file:org.apache.brooklyn.demo.Publish.java

public static void main(String... argv) throws Exception {
    Preconditions.checkElementIndex(0, argv.length, "Must specify broker URL");
    String url = argv[0];/*from  w  w  w.  j ava2  s . co m*/

    // Set Qpid client properties
    System.setProperty(ClientProperties.AMQP_VERSION, "0-10");
    System.setProperty(ClientProperties.DEST_SYNTAX, "ADDR");

    // Connect to the broker
    AMQConnectionFactory factory = new AMQConnectionFactory(url);
    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    try {
        // Create a producer for the queue
        Queue destination = session.createQueue(QUEUE);
        MessageProducer messageProducer = session.createProducer(destination);

        // Send 100 messages
        for (int n = 0; n < 100; n++) {
            String body = String.format("test message %03d", n + 1);
            TextMessage message = session.createTextMessage(body);
            messageProducer.send(message);
            System.out.printf("Sent message %s\n", body);
        }
    } catch (Exception e) {
        System.err.printf("Error while sending - %s\n", e.getMessage());
        System.err.printf("Cause: %s\n", Throwables.getStackTraceAsString(e));
    } finally {
        session.close();
        connection.close();
    }
}

From source file:brooklyn.demo.Subscribe.java

public static void main(String... argv) throws Exception {
    Preconditions.checkElementIndex(0, argv.length, "Must specify broker URL");
    String url = argv[0];//from   w w w  .  ja  v  a  2s .  com

    // Set Qpid client properties
    System.setProperty(ClientProperties.AMQP_VERSION, "0-10");
    System.setProperty(ClientProperties.DEST_SYNTAX, "ADDR");

    // Connect to the broker
    AMQConnectionFactory factory = new AMQConnectionFactory(url);
    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    System.out.printf("Waiting up to %s milliseconds to receive %s messages\n", MESSAGE_TIMEOUT_MILLIS,
            MESSAGE_COUNT);
    try {
        // Create a producer for the queue
        Queue destination = session.createQueue(QUEUE);
        MessageConsumer messageConsumer = session.createConsumer(destination);

        // Try and receive 100 messages
        for (int n = 0; n < MESSAGE_COUNT; n++) {
            TextMessage msg = (TextMessage) messageConsumer.receive(MESSAGE_TIMEOUT_MILLIS);
            if (msg == null) {
                System.out.printf("No message received in %s milliseconds, exiting", MESSAGE_TIMEOUT_MILLIS);
                break;
            }
            System.out.printf("Got message %d: '%s'\n", n + 1, msg.getText());
        }
    } catch (Exception e) {
        System.err.printf("Error while receiving - %s\n", e.getMessage());
        System.err.printf("Cause: %s\n", Throwables.getStackTraceAsString(e));
    } finally {
        session.close();
        connection.close();
    }
}

From source file:io.pravega.common.io.StreamHelpers.java

/**
 * Reads at most 'maxLength' bytes from the given input stream, as long as the stream still has data to serve.
 *
 * @param stream      The InputStream to read from.
 * @param target      The target array to write data to.
 * @param startOffset The offset within the target array to start writing data to.
 * @param maxLength   The maximum number of bytes to copy.
 * @return The number of bytes copied.//from   ww w.j  a v  a  2 s  .c om
 * @throws IOException If unable to read from the given stream.
 */
public static int readAll(InputStream stream, byte[] target, int startOffset, int maxLength)
        throws IOException {
    Preconditions.checkNotNull(stream, "stream");
    Preconditions.checkNotNull(stream, "target");
    Preconditions.checkElementIndex(startOffset, target.length, "startOffset");
    Exceptions.checkArgument(maxLength >= 0, "maxLength", "maxLength must be a non-negative number.");

    int totalBytesRead = 0;
    while (totalBytesRead < maxLength) {
        int bytesRead = stream.read(target, startOffset + totalBytesRead, maxLength - totalBytesRead);
        if (bytesRead < 0) {
            // End of stream/
            break;
        }

        totalBytesRead += bytesRead;
    }

    return totalBytesRead;
}

From source file:ezbake.deployer.cli.commands.UnDeployCommand.java

@Override
public void call() throws IOException, TException, DeploymentException {

    String[] args = globalParameters.unparsedArgs;
    minExpectedArgs(2, args, this);
    String applicationId = args[0];
    String serviceId = args[1];/*www.  j  ava 2s  .co  m*/
    Preconditions.checkElementIndex(1, args.length, "Insufficient number of arguments, requirement: 2");

    getClient().undeploy(applicationId, serviceId, getSecurityToken());
}

From source file:com.facebook.stats.topk.ArrayBasedIntegerTopK.java

@Override
public synchronized void add(Integer key, long count) {
    Preconditions.checkNotNull(key, "key can't be null");
    Preconditions.checkElementIndex(key, counts.length, "key");
    Preconditions.checkArgument(count >= 0, "count to add must be non-negative, got %s", count);

    counts[key] += count;/*from w  w  w. j  a v a2 s  . c  o  m*/
}

From source file:com.zaradai.kunzite.optimizer.model.OutputRowSchema.java

public String getName(int index) {
    Preconditions.checkElementIndex(index, getNumColumns(), "Index is out of range");

    for (Map.Entry<String, Integer> entry : columnByName.entrySet()) {
        if (entry.getValue() == index) {
            return entry.getKey();
        }//from ww  w  . ja  v  a 2 s  .c o  m
    }

    return null;
}

From source file:com.zaradai.kunzite.optimizer.model.InputRowSchema.java

public String getName(int index) {
    Preconditions.checkElementIndex(index, getNumColumns(), "Index is out of range");

    for (Map.Entry<String, InputSpec> entry : columnByName.entrySet()) {
        if (entry.getValue().getPosition() == index) {
            return entry.getKey();
        }//w ww. j  a va2 s. c om
    }

    return null;
}

From source file:codecrafter47.bungeetablistplus.layout.Layout.java

public void placeSection(S section, int row, int column, int size) {
    Preconditions.checkElementIndex(row, rows, "row");
    Preconditions.checkElementIndex(column, columns, "column");
    int startIndex = coordinatesToInt(row, column);
    placeSection(section, startIndex, size);
}

From source file:io.pravega.test.integration.selftest.adapters.TruncateableArray.java

@Override
public byte get(int index) {
    Preconditions.checkElementIndex(index, this.length,
            "index must be non-negative and less than the length of the array.");

    // Adjust the index based on the first entry offset.
    index += this.firstArrayOffset;

    // Find the array which contains the sought index.
    for (byte[] array : this.arrays) {
        if (index < array.length) {
            // This is the array we are looking for; use 'index' to look up into it.
            return array[index];
        }//from   ww  w  . j  a v  a 2 s .c  o m

        index -= array.length;
    }

    throw new AssertionError("unable to locate an inner array based on given input");
}

From source file:com.facebook.stats.topk.TreeBasedIntegerTopK.java

@Override
public synchronized void add(Integer key, long count) {
    Preconditions.checkNotNull(key, "key can't be null");
    Preconditions.checkElementIndex(key, counts.length, "key");
    Preconditions.checkArgument(count >= 0, "count to add must be non-negative, got %s", count);

    if (count == 0) {
        return;//from  w w  w  . j  av a  2s.  co m
    }

    long currentCount = counts[key];

    counts[key] += count;

    if (isInTop[key]) {
        topPairs.remove(new ComparablePair<Long, Integer>(currentCount, key));
        topPairs.add(new ComparablePair<Long, Integer>(counts[key], key));
    } else if (topPairs.size() < k) {
        topPairs.add(new ComparablePair<Long, Integer>(counts[key], key));
        isInTop[key] = true;
        smallestTopCount = Math.min(smallestTopCount, counts[key]);
    } else if (counts[key] > smallestTopCount) {
        ComparablePair<Long, Integer> smallestTopPair = topPairs.pollFirst();

        isInTop[smallestTopPair.getSecond()] = false;
        topPairs.add(new ComparablePair<Long, Integer>(counts[key], key));
        isInTop[key] = true;
        smallestTopCount = topPairs.first().getFirst();
    }
}