Java Code Examples for com.google.common.base.Preconditions

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project airlift, under directory /configuration/src/main/java/io/airlift/configuration/.

Source file: ConfigurationFactory.java

  15 
vote

/** 
 * This is used by the configuration provider
 */
<T>T build(ConfigurationProvider<T> configurationProvider,WarningsMonitor warningsMonitor){
  Preconditions.checkNotNull(configurationProvider,"configurationProvider");
  registeredProviders.add(configurationProvider);
  T instance=(T)instanceCache.get(configurationProvider);
  if (instance != null) {
    return instance;
  }
  ConfigurationHolder<T> holder=build(configurationProvider.getConfigClass(),configurationProvider.getPrefix());
  instance=holder.instance;
  if (warningsMonitor != null) {
    for (    Message message : holder.problems.getWarnings()) {
      warningsMonitor.onWarning(message.toString());
    }
  }
  T existingValue=(T)instanceCache.putIfAbsent(configurationProvider,instance);
  if (existingValue != null) {
    return existingValue;
  }
  return instance;
}
 

Example 2

From project airlift, under directory /configuration/src/main/java/io/airlift/configuration/.

Source file: ConfigurationInspector.java

  15 
vote

private ConfigRecord(ConfigurationProvider<T> configurationProvider){
  Preconditions.checkNotNull(configurationProvider,"configurationProvider");
  key=configurationProvider.getKey();
  configClass=configurationProvider.getConfigClass();
  prefix=configurationProvider.getPrefix();
  ConfigurationMetadata<T> metadata=configurationProvider.getConfigurationMetadata();
  T instance=null;
  try {
    instance=configurationProvider.get();
  }
 catch (  Throwable ignored) {
  }
  T defaults=newDefaultInstance(metadata);
  String prefix=configurationProvider.getPrefix();
  prefix=prefix == null ? "" : (prefix + ".");
  ImmutableSortedSet.Builder<ConfigAttribute> builder=ImmutableSortedSet.naturalOrder();
  for (  AttributeMetadata attribute : metadata.getAttributes().values()) {
    String propertyName=prefix + attribute.getInjectionPoint().getProperty();
    Method getter=attribute.getGetter();
    String defaultValue=getValue(getter,defaults,"-- none --");
    String currentValue=getValue(getter,instance,"-- n/a --");
    String description=attribute.getDescription();
    if (description == null) {
      description="";
    }
    builder.add(new ConfigAttribute(attribute.getName(),propertyName,defaultValue,currentValue,description));
  }
  attributes=builder.build();
}
 

Example 3

From project airlift, under directory /configuration/src/main/java/io/airlift/configuration/.

Source file: ConfigurationInspector.java

  15 
vote

private ConfigAttribute(String attributeName,String propertyName,String defaultValue,String currentValue,String description){
  Preconditions.checkNotNull(attributeName,"attributeName");
  Preconditions.checkNotNull(propertyName,"propertyName");
  Preconditions.checkNotNull(defaultValue,"defaultValue");
  Preconditions.checkNotNull(currentValue,"currentValue");
  Preconditions.checkNotNull(description,"description");
  this.attributeName=attributeName;
  this.propertyName=propertyName;
  this.defaultValue=defaultValue;
  this.currentValue=currentValue;
  this.description=description;
}
 

Example 4

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: Iterables.java

  15 
vote

/** 
 * Returns the element at the specified position in an iterable.
 * @param position position of the element to return
 * @return the element at the specified position in {@code iterable}
 * @throws IndexOutOfBoundsException if {@code position} is negative orgreater than or equal to the size of  {@code iterable}
 */
public static <T>T get(Iterable<T> iterable,int position){
  checkNotNull(iterable);
  if (iterable instanceof List) {
    return ((List<T>)iterable).get(position);
  }
  if (iterable instanceof Collection) {
    Collection<T> collection=(Collection<T>)iterable;
    Preconditions.checkElementIndex(position,collection.size());
  }
 else {
    if (position < 0) {
      throw new IndexOutOfBoundsException("position cannot be negative: " + position);
    }
  }
  return Iterators.get(iterable.iterator(),position);
}
 

Example 5

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: Iterators.java

  15 
vote

/** 
 * Returns the index in  {@code iterator} of the first element that satisfiesthe provided  {@code predicate}, or  {@code -1} if the Iterator has no suchelements. <p>More formally, returns the lowest index  {@code i} such that{@code predicate.apply(Iterators.get(iterator, i))} is {@code true}, or {@code -1} if there is no such index.<p>If -1 is returned, the iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.  Otherwise, the iterator will be set to the element which satisfies the {@code predicate}.
 * @since 2010.01.04 <b>tentative</b>
 */
public static <T>int indexOf(Iterator<T> iterator,Predicate<? super T> predicate){
  Preconditions.checkNotNull(predicate,"predicate");
  int i=0;
  while (iterator.hasNext()) {
    T current=iterator.next();
    if (predicate.apply(current)) {
      return i;
    }
    i++;
  }
  return -1;
}
 

Example 6

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: Iterators.java

  15 
vote

/** 
 * Returns an iterator containing the elements in the specified range of {@code array} in order. The returned iterator is a view of the array;subsequent changes to the array will be reflected in the iterator. <p>The  {@code Iterable} equivalent of this method is {@code Arrays.asList(array).subList(offset, offset + length)}.
 * @param array array to read elements out of
 * @param offset index of first array element to retrieve
 * @param length number of elements in iteration
 * @throws IndexOutOfBoundsException if {@code offset} is negative,{@code length} is negative, or {@code offset + length > array.length}
 */
static <T>UnmodifiableIterator<T> forArray(final T[] array,final int offset,int length){
  checkArgument(length >= 0);
  final int end=offset + length;
  Preconditions.checkPositionIndexes(offset,end,array.length);
  return new UnmodifiableIterator<T>(){
    int i=offset;
    public boolean hasNext(){
      return i < end;
    }
    public T next(){
      if (!hasNext()) {
        throw new NoSuchElementException();
      }
      return array[i++];
    }
  }
;
}
 

Example 7

From project android_packages_apps_Tag, under directory /canon/src/com/android/apps/tagcanon/.

Source file: TagCanon.java

  15 
vote

public static NdefRecord newTextRecord(String text,Locale locale,boolean encodeInUtf8){
  Preconditions.checkNotNull(text);
  Preconditions.checkNotNull(locale);
  byte[] langBytes=locale.getLanguage().getBytes(Charsets.US_ASCII);
  Charset utfEncoding=encodeInUtf8 ? Charsets.UTF_8 : Charset.forName("UTF-16");
  byte[] textBytes=text.getBytes(utfEncoding);
  int utfBit=encodeInUtf8 ? 0 : (1 << 7);
  char status=(char)(utfBit + langBytes.length);
  byte[] data=Bytes.concat(new byte[]{(byte)status},langBytes,textBytes);
  return new NdefRecord(NdefRecord.TNF_WELL_KNOWN,NdefRecord.RTD_TEXT,new byte[0],data);
}
 

Example 8

From project android_packages_apps_Tag, under directory /canon/src/com/android/apps/tagcanon/.

Source file: TagCanon.java

  15 
vote

public static NdefRecord newMimeRecord(String type,byte[] data){
  Preconditions.checkNotNull(type);
  Preconditions.checkNotNull(data);
  byte[] typeBytes=type.getBytes(Charsets.US_ASCII);
  return new NdefRecord(NdefRecord.TNF_MIME_MEDIA,typeBytes,new byte[0],data);
}
 

Example 9

From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/.

Source file: MyTagList.java

  15 
vote

@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.my_tag_activity);
  if (savedInstanceState != null) {
    mTagIdInEdit=savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT,-1);
  }
  mEnabled=(CheckBox)findViewById(R.id.toggle_enabled_checkbox);
  mEnabled.setChecked(false);
  findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
  mActiveTagDetails=findViewById(R.id.active_tag_details);
  mSelectActiveTagAnchor=findViewById(R.id.choose_my_tag);
  findViewById(R.id.active_tag).setOnClickListener(this);
  updateActiveTagView(null);
  mActiveTagId=getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG,-1);
  mAdapter=new TagAdapter(this);
  mList=(ListView)findViewById(android.R.id.list);
  mList.setAdapter(mAdapter);
  mList.setOnItemClickListener(this);
  findViewById(R.id.add_tag).setOnClickListener(this);
  mList.setEmptyView(null);
  new TagLoaderTask().execute((Void[])null);
  if (!Build.TYPE.equalsIgnoreCase("user")) {
    mWriteSupport=true;
  }
  registerForContextMenu(mList);
  if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
    NdefMessage msg=(NdefMessage)Preconditions.checkNotNull(getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
    saveNewMessage(msg);
  }
}
 

Example 10

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/client/.

Source file: AdbConnection.java

  15 
vote

/** 
 * Constructs a new instance which uses  {@code adb} from a particular path andpossible overriding of configurable ports. <p>For readability purposes, the configuration and construction of instances of this class should be performed with {@link AdbConnectionBuilder}.
 * @param adbPath the path to the {@code adb} utility
 * @param adbServerPort the port that the ADB daemon listens on to serverequests. If  {@code null}, the default port (possibly 5037) is used.
 * @param emulatorConsolePort the port the emulator is listening on forconsole commands. If  {@code null}, the default port (possibly 5554) is used.
 * @param emulatorAdbPort the port the emulator is listening on for ADBcommands. If  {@code null}, the default port (possibly 5555) is used.
 */
protected AdbConnection(String adbPath,@Nullable Integer adbServerPort,@Nullable Integer emulatorConsolePort,@Nullable Integer emulatorAdbPort){
  this.adbPath=Preconditions.checkNotNull(adbPath);
  this.adbServerPort=adbServerPort;
  this.emulatorConsolePort=emulatorConsolePort;
  this.emulatorAdbPort=emulatorAdbPort;
}
 

Example 11

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/client/.

Source file: AndroidNativeDriver.java

  15 
vote

/** 
 * Creates an instance which routes all commands to a  {@code CommandExecutor}. A mock can be passed as an argument to help with testing. This constructor also takes an  {@code AdbConnection}, to which all ADB commands will be sent.
 * @param executor a command executor through which all commands arerouted. Using a mock eliminates the need to connect to an HTTP server, where the commands are usually routed.
 * @param adbConnection receives all ADB commands, such as event injections.If  {@code null}, this instance will not support ADB functionality.
 * @see AndroidNativeDriverBuilder
 */
protected AndroidNativeDriver(CommandExecutor executor,@Nullable AdbConnection adbConnection){
  super(Preconditions.checkNotNull(executor),AndroidCapabilities.get());
  setElementConverter(new JsonToWebElementConverter(this){
    @Override protected RemoteWebElement newRemoteWebElement(){
      return new AndroidNativeElement(AndroidNativeDriver.this);
    }
  }
);
  this.adbConnection=adbConnection;
}
 

Example 12

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/client/.

Source file: FrameBufferFormat.java

  15 
vote

public FrameBufferFormat(int xResolution,int yResolution,int bitsPerPixel){
  Preconditions.checkArgument(isSupportedBitsPerPixel(bitsPerPixel));
  this.xResolution=xResolution;
  this.yResolution=yResolution;
  this.bitsPerPixel=bitsPerPixel;
}
 

Example 13

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/inputs/.

Source file: BlobstoreInput.java

  15 
vote

private List<? extends InputReader<BlobstoreRecordKey,byte[]>> split(String blobKey,long blobSize,int shardCount){
  try {
    Preconditions.checkNotNull(blobKey);
    Preconditions.checkArgument(shardCount > 0);
    Preconditions.checkArgument(blobSize >= 0);
    long splitLength=blobSize / shardCount;
    if (splitLength == 0L) {
      splitLength=blobSize;
      shardCount=1;
    }
    List<BlobstoreInputReader> result=new ArrayList<BlobstoreInputReader>();
    long startOffset=0L;
    for (int i=1; i < shardCount; i++) {
      long endOffset=(long)i * splitLength;
      result.add(new BlobstoreInputReader(blobKey,startOffset,endOffset,terminator));
      startOffset=endOffset;
    }
    result.add(new BlobstoreInputReader(blobKey,startOffset,blobSize,terminator));
    return result;
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 14

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/inputs/.

Source file: BlobstoreRecordKey.java

  15 
vote

public BlobstoreRecordKey(BlobKey blobKey,long offset){
  Preconditions.checkNotNull(blobKey);
  Preconditions.checkArgument(offset >= 0);
  this.blobKey=blobKey;
  this.offset=offset;
}
 

Example 15

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/inputs/.

Source file: DatastoreInput.java

  15 
vote

@Override public List<? extends InputReader<Key,Entity>> split(MapperJobContext<Key,Entity,?,?> context){
  Preconditions.checkNotNull(entityKind);
  logger.info("Getting input splits for: " + entityKind);
  DatastoreService datastoreService=DatastoreServiceFactory.getDatastoreService();
  Key startKey=getStartKey(entityKind,datastoreService);
  if (startKey == null) {
    return Collections.emptyList();
  }
  Key lastKey=startKey;
  List<DatastoreInputReader> result=new ArrayList<DatastoreInputReader>();
  for (  Key currentKey : chooseSplitPoints(datastoreService)) {
    DatastoreInputReader source=new DatastoreInputReader(entityKind,lastKey,currentKey);
    result.add(source);
    logger.info(String.format("Added DatastoreInputSplit %s %s %s",source,lastKey,currentKey));
    lastKey=currentKey;
  }
  result.add(new DatastoreInputReader(entityKind,lastKey,null));
  return result;
}
 

Example 16

From project astyanax, under directory /src/main/java/com/netflix/astyanax/.

Source file: AstyanaxContext.java

  15 
vote

public <T>AstyanaxContext<Keyspace> buildKeyspace(AstyanaxTypeFactory<T> factory){
  ConnectionPool<T> cp=createConnectionPool(factory.createConnectionFactory(asConfig,cpConfig,tracerFactory,monitor));
  this.cp=cp;
  final Keyspace keyspace=factory.createKeyspace(keyspaceName,cp,asConfig,tracerFactory);
  Supplier<Map<BigInteger,List<Host>>> supplier=null;
switch (getNodeDiscoveryType()) {
case DISCOVERY_SERVICE:
    Preconditions.checkNotNull(hostSupplier,"Missing host name supplier");
  supplier=hostSupplier;
break;
case RING_DESCRIBE:
supplier=new RingDescribeHostSupplier(keyspace,cpConfig.getPort());
break;
case TOKEN_AWARE:
if (hostSupplier == null) {
supplier=new RingDescribeHostSupplier(keyspace,cpConfig.getPort());
}
 else {
supplier=new FilteringHostSupplier(new RingDescribeHostSupplier(keyspace,cpConfig.getPort()),hostSupplier);
}
break;
case NONE:
supplier=null;
break;
}
if (supplier != null) {
discovery=new NodeDiscoveryImpl(StringUtils.join(Arrays.asList(clusterName,keyspaceName),"_"),asConfig.getDiscoveryDelayInSeconds() * 1000,supplier,cp);
}
return new AstyanaxContext<Keyspace>(this,keyspace);
}
 

Example 17

From project astyanax, under directory /src/main/java/com/netflix/astyanax/mapping/.

Source file: Mapping.java

  15 
vote

/** 
 * @param clazz clazz type to map
 * @param annotationSet annotations to use when analyzing a bean
 */
public Mapping(Class<T> clazz,AnnotationSet<?,?> annotationSet){
  this.clazz=clazz;
  String localKeyFieldName=null;
  ImmutableMap.Builder<String,Field> builder=ImmutableMap.builder();
  AtomicBoolean isKey=new AtomicBoolean();
  Set<String> usedNames=Sets.newHashSet();
  for (  Field field : clazz.getDeclaredFields()) {
    String name=mapField(field,annotationSet,builder,usedNames,isKey);
    if (isKey.get()) {
      Preconditions.checkArgument(localKeyFieldName == null);
      localKeyFieldName=name;
    }
  }
  Preconditions.checkNotNull(localKeyFieldName);
  fields=builder.build();
  idFieldName=localKeyFieldName;
}
 

Example 18

From project astyanax, under directory /src/main/java/com/netflix/astyanax/mapping/.

Source file: Mapping.java

  15 
vote

private <ID extends Annotation,COLUMN extends Annotation>String mapField(Field field,AnnotationSet<ID,COLUMN> annotationSet,ImmutableMap.Builder<String,Field> builder,Set<String> usedNames,AtomicBoolean isKey){
  String mappingName=null;
  ID idAnnotation=field.getAnnotation(annotationSet.getIdAnnotation());
  COLUMN columnAnnotation=field.getAnnotation(annotationSet.getColumnAnnotation());
  if ((idAnnotation != null) && (columnAnnotation != null)) {
    throw new IllegalStateException("A field cannot be marked as both an ID and a Column: " + field.getName());
  }
  if (idAnnotation != null) {
    mappingName=annotationSet.getIdName(field,idAnnotation);
    isKey.set(true);
  }
 else {
    isKey.set(false);
  }
  if ((columnAnnotation != null)) {
    mappingName=annotationSet.getColumnName(field,columnAnnotation);
  }
  if (mappingName != null) {
    Preconditions.checkArgument(!usedNames.contains(mappingName.toLowerCase()),mappingName + " has already been used for this column family");
    usedNames.add(mappingName.toLowerCase());
    field.setAccessible(true);
    builder.put(mappingName,field);
  }
  return mappingName;
}
 

Example 19

From project atlas, under directory /src/main/java/com/ning/atlas/bus/.

Source file: EventHandler.java

  15 
vote

/** 
 * Creates a new EventHandler to wrap  {@code method} on @{code target}.
 * @param target  object to which the method applies.
 * @param method  handler method.
 */
EventHandler(Object target,Method method){
  Preconditions.checkNotNull(target,"EventHandler target cannot be null.");
  Preconditions.checkNotNull(method,"EventHandler method cannot be null.");
  this.target=target;
  this.method=method;
  method.setAccessible(true);
}
 

Example 20

From project atlas, under directory /src/main/java/com/ning/atlas/spi/space/.

Source file: SpaceKey.java

  15 
vote

private SpaceKey(Identity id,String key){
  Preconditions.checkNotNull(id);
  Preconditions.checkNotNull(key);
  Preconditions.checkArgument(key.length() > 0);
  this.id=id;
  this.key=key;
}
 

Example 21

From project atlas, under directory /src/main/java/com/ning/atlas/.

Source file: Template.java

  15 
vote

public Template(String type,My my,List<?> cardinality){
  Preconditions.checkArgument(!type.contains("."),"type is not allowed to contain '.' but is '%s'",type);
  Preconditions.checkArgument(!type.contains("/"),"type is not allowed to contain '/' but is '%s'",type);
  this.my=my;
  this.type=type;
  this.cardinality=Lists.transform(cardinality,new Function<Object,String>(){
    @Override public String apply(    @Nullable Object input){
      return String.valueOf(input);
    }
  }
);
}
 

Example 22

From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/api/impl/.

Source file: ScriptSessionManagerImpl.java

  15 
vote

@Override public SessionId putSession(ScriptSession session){
  SessionId sessionId=Preconditions.checkNotNull(nextSessionId(),"nextSessionId");
  if (cliSessions.putIfAbsent(sessionId,session) != null) {
    throw new AssertionError("Internal implementation bug: UUID considered to be unique enough.");
  }
  return sessionId;
}
 

Example 23

From project b1-pack, under directory /cli/src/main/java/org/b1/pack/cli/.

Source file: ArgSet.java

  15 
vote

private void initEncrypt(String encrypt){
  if (encrypt == null)   return;
  Matcher matcher=ENCRYPT_PATTERN.matcher(encrypt);
  Preconditions.checkArgument(matcher.matches());
  encryptionName=matcher.group(1);
  String count=matcher.group(2);
  iterationCount=count == null ? null : Integer.valueOf(count);
}
 

Example 24

From project b1-pack, under directory /cli/src/main/java/org/b1/pack/cli/.

Source file: ArgSet.java

  15 
vote

private void initType(String type){
  if (type == null)   return;
  Matcher matcher=TYPE_PATTERN.matcher(type);
  Preconditions.checkArgument(matcher.matches());
  typeFormat=matcher.group(1);
  typeFlag=matcher.group(2);
}
 

Example 25

From project b1-pack, under directory /cli/src/main/java/org/b1/pack/cli/.

Source file: BuildCommand.java

  15 
vote

@Override public void execute(final ArgSet argSet) throws IOException {
  System.out.println("Starting");
  Preconditions.checkArgument(argSet.getCompression() == null,"Compression not supported in this mode");
  File outputFolder=FileTools.getOutputFolder(argSet);
  final Set<FsObject> fsObjects=FileTools.getFsObjects(argSet.getFileNames());
  PackBuilder builder=PackBuilder.getInstance(argSet.getTypeFormat());
  FsBuilderProvider provider=new FsBuilderProvider(argSet.getMaxVolumeSize());
  List<BuilderVolume> volumes=builder.build(provider,new BuilderCommand(){
    @Override public void execute(    BuilderPack pack){
      for (      FsObject fsObject : fsObjects) {
        File file=fsObject.getFile();
        if (file.isFile()) {
          pack.addFile(new FsBuilderFile(fsObject));
        }
 else         if (file.isDirectory()) {
          pack.addFolder(new FsBuilderFolder(fsObject));
        }
 else {
          throw new IllegalArgumentException("Not found: " + file);
        }
      }
    }
  }
);
  VolumeAllocator volumeAllocator=VolumeService.getInstance(argSet.getTypeFormat()).createVolumeAllocator(new FsVolumeAllocatorProvider(argSet.getPackName(),argSet.getMaxVolumeSize() != null ? volumes.size() : 0));
  for (int i=0, volumesSize=volumes.size(); i < volumesSize; i++) {
    String name=volumeAllocator.getVolumeName(i + 1);
    buildVolume(outputFolder == null ? new File(name) : new File(outputFolder,name),volumes.get(i));
  }
  System.out.println();
  System.out.println("Done");
}