Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2013 DroidDriver committers
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package io.appium.droiddriver.util;
     18 
     19 /**
     20  * Static helper methods for manipulating strings.
     21  */
     22 public class Strings {
     23   public static String charSequenceToString(CharSequence input) {
     24     return input == null ? null : input.toString();
     25   }
     26 
     27   public static ToStringHelper toStringHelper(Object self) {
     28     return new ToStringHelper(self.getClass().getSimpleName());
     29   }
     30 
     31   public static final class ToStringHelper {
     32     private final StringBuilder builder;
     33     private boolean needsSeparator = false;
     34 
     35     /**
     36      * Use {@link #toStringHelper(Object)} to create an instance.
     37      */
     38     private ToStringHelper(String className) {
     39       this.builder = new StringBuilder(32).append(className).append('{');
     40     }
     41 
     42     public ToStringHelper addValue(Object value) {
     43       maybeAppendSeparator().append(value);
     44       return this;
     45     }
     46 
     47     public ToStringHelper add(String name, Object value) {
     48       maybeAppendSeparator().append(name).append('=').append(value);
     49       return this;
     50     }
     51 
     52     @Override
     53     public String toString() {
     54       return builder.append('}').toString();
     55     }
     56 
     57     private StringBuilder maybeAppendSeparator() {
     58       if (needsSeparator) {
     59         return builder.append(", ");
     60       } else {
     61         needsSeparator = true;
     62         return builder;
     63       }
     64     }
     65   }
     66 }
     67