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

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

Introduction

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

Prototype

public static void checkState(boolean expression, @Nullable Object errorMessage) 

Source Link

Document

Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.

Usage

From source file:org.ros.internal.transport.ConnectionHeader.java

/**
 * Decodes a header that came over the wire into a {@link Map} of fields and
 * values./*  w w w  .  j  a  va 2  s.  c  o  m*/
 *
 * @param buffer
 *          the incoming {@link ChannelBuffer} containing the header
 * @return a {@link Map} of header fields and values
 */
public static ConnectionHeader decode(ChannelBuffer buffer) {
    Map<String, String> fields = Maps.newHashMap();
    int position = 0;
    int readableBytes = buffer.readableBytes();
    while (position < readableBytes) {
        int fieldSize = buffer.readInt();
        position += 4;
        if (fieldSize == 0) {
            throw new IllegalStateException("Invalid 0 length handshake header field.");
        }
        if (position + fieldSize > readableBytes) {
            throw new IllegalStateException("Invalid line length handshake header field.");
        }
        String field = decodeAsciiString(buffer, fieldSize);
        position += field.length();
        Preconditions.checkState(field.indexOf("=") > 0,
                String.format("Invalid field in handshake header: \"%s\"", field));
        String[] keyAndValue = field.split("=");
        if (keyAndValue.length == 1) {
            fields.put(keyAndValue[0], "");
        } else {
            fields.put(keyAndValue[0], keyAndValue[1]);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Decoded header: " + fields);
    }
    ConnectionHeader connectionHeader = new ConnectionHeader();
    connectionHeader.mergeFields(fields);
    return connectionHeader;
}

From source file:com.google.code.jgntp.internal.message.read.GntpMessageResponseParser.java

public GntpMessageResponse parse(String s) {
    Iterable<String> splitted = separatorSplitter.split(s);
    Preconditions.checkState(!Iterables.isEmpty(splitted), "Empty message received from Growl");

    Iterator<String> iter = splitted.iterator();
    String statusLine = iter.next();
    Preconditions.checkState(//from  ww w .  j av  a  2s . c o m
            statusLine.startsWith(GntpMessage.PROTOCOL_ID + "/" + GntpVersion.ONE_DOT_ZERO.toString()),
            "Unknown protocol version");

    Iterable<String> statusLineIterable = statusLineSplitter.split(statusLine);
    String messageTypeText = Iterables.get(statusLineIterable, 1).substring(1);
    GntpMessageType messageType = GntpMessageType.valueOf(messageTypeText);

    Map<String, String> headers = Maps.newHashMap();
    while (iter.hasNext()) {
        String[] splittedHeader = iter.next().split(":", 2);
        headers.put(splittedHeader[0], splittedHeader[1].trim());
    }

    switch (messageType) {
    case OK:
        return createOkMessage(headers);
    case CALLBACK:
        return createCallbackMessage(headers);
    case ERROR:
        return createErrorMessage(headers);
    default:
        throw new IllegalStateException("Unknown response message type: " + messageType);
    }
}

From source file:org.locationtech.geogig.rest.repository.SingleRepositoryProvider.java

@Override
public void delete(Request request) {
    Repository repo = getGeogig(request).orNull();
    Preconditions.checkState(repo != null, "No repository to delete.");
    Optional<URI> repoUri = repo.command(ResolveGeogigURI.class).call();
    Preconditions.checkState(repoUri.isPresent(), "No repository to delete.");
    repo.close();//ww w. jav a 2  s.  c  o m
    try {
        GeoGIG.delete(repoUri.get());
        this.repo = null;
    } catch (Exception e) {
        Throwables.propagate(e);
    }

}

From source file:org.apache.usergrid.chop.example.MechanicalWatch.java

@Override
public long getTime() {
    Preconditions.checkState(spring.hasPower(), "Can't get the time if the spring is not wound.");
    return System.currentTimeMillis();
}

From source file:org.thelq.stackexchange.api.queries.site.SearchBasicQuery.java

@Override
public LinkedHashMap<String, String> buildFinalParameters() throws IllegalStateException {
    Preconditions.checkState(StringUtils.isNotBlank(inTitle) || !tagged.isEmpty(),
            "Must specify tag or intitle");
    LinkedHashMap<String, String> finalParameters = super.buildFinalParameters();
    QueryUtils.putIfNotNull(finalParameters, "inTitle", inTitle);
    return finalParameters;
}

From source file:org.apache.usergrid.chop.example.DigitalWatch.java

@Override
public long getTime() {
    Preconditions.checkState(battery.hasPower(), "Can't tell time with a dead battery!");
    return System.currentTimeMillis();
}

From source file:com.nesscomputing.service.discovery.announce.ServiceAnnouncementFactory.java

public ServiceInformationBuilder newBuilder() {
    final HttpConnector connector = httpServer.getConnectors().get("internal-http");
    Preconditions.checkState(connector != null, "not internal http connector found!");
    String internalAddress = connector.getAddress();
    int internalPort = connector.getPort();

    Preconditions.checkState(!StringUtils.isBlank(internalAddress), "blank internal address");
    Preconditions.checkState(internalPort > 0, "unconfigured internal http port");

    return new ServiceInformationBuilder().putGrabBag(ServiceInformation.PROP_SERVICE_SCHEME, "http")
            .putGrabBag(ServiceInformation.PROP_SERVICE_ADDRESS, internalAddress)
            .putGrabBag(ServiceInformation.PROP_SERVICE_PORT, Integer.toString(internalPort));
}

From source file:com.google.ipc.invalidation.external.client.types.ObjectId.java

/** Creates an object id for the given {@code source} and id {@code name}. */
private ObjectId(int source, byte[] name) {
    Preconditions.checkState(source >= 0, "source");
    this.source = source;
    this.name = Preconditions.checkNotNull(name, "name");
}

From source file:com.google.inject.service.AsyncService.java

public synchronized final Future<State> start() {
    Preconditions.checkState(state != State.STOPPED, "Cannot restart a service that has been stopped");

    // Starts are idempotent.
    if (state == State.STARTED) {
        return new FutureTask<State>(Runnables.doNothing(), State.STARTED);
    }//from   w  w w. j  a v  a2  s.  com

    return executor.submit(new Callable<State>() {
        public State call() {
            onStart();
            return state = State.STARTED;
        }
    });
}

From source file:com.google.wave.splash.rpc.StartupRpc.java

public ParticipantProfile startup(SessionContext session) {
    Preconditions.checkState(ProtocolVersion.DEFAULT.isGreaterThanOrEqual(ProtocolVersion.V2_2),
            "Robot Protocol version must be at least 0.22 or higher");

    OperationRequestClient.OperationRequestBatch batch = requestClient.newRequestBatch();
    batch.addRobotRequest(OperationType.ROBOT_NOTIFY,
            RpcParam.of(ParamsProperty.PROTOCOL_VERSION.key(), ProtocolVersion.DEFAULT.getVersionString()),
            RpcParam.of(ParamsProperty.CAPABILITIES_HASH.key(), ""));
    if (session.isAuthenticated()) {
        // TODO: Fetch the user profile.
    } else {// w  w  w  .j a v  a 2s.c o m
        // Anonymous user.
    }

    // TODO: Make this completely asynchronous.
    batch.apply();
    return new ParticipantProfile("nobody", "", "");
}