Java Code Examples for java.util.Formatter

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 guice-jit-providers, under directory /core/src/com/google/inject/internal/.

Source file: Errors.java

  23 
vote

public Errors childBindingAlreadySet(Key<?> key,Set<Object> sources){
  Formatter allSources=new Formatter();
  for (  Object source : sources) {
    if (source == null) {
      allSources.format("%n    (bound by a just-in-time binding)");
    }
 else {
      allSources.format("%n    bound at %s",source);
    }
  }
  Errors errors=addMessage("Unable to create binding for %s." + " It was already configured on one or more child injectors or private modules" + "%s%n"+ "  If it was in a PrivateModule, did you forget to expose the binding?",key,allSources.out());
  return errors;
}
 

Example 2

From project httpClient, under directory /httpclient-cache/src/main/java/org/apache/http/impl/client/cache/.

Source file: BasicIdGenerator.java

  23 
vote

public synchronized void generate(final StringBuilder buffer){
  this.count++;
  int rndnum=this.rnd.nextInt();
  buffer.append(System.currentTimeMillis());
  buffer.append('.');
  Formatter formatter=new Formatter(buffer,Locale.US);
  formatter.format("%1$016x-%2$08x",this.count,rndnum);
  buffer.append('.');
  buffer.append(this.hostname);
}
 

Example 3

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.

Source file: BasicIdGenerator.java

  22 
vote

public synchronized void generate(final StringBuilder buffer){
  this.count++;
  int rndnum=this.rnd.nextInt();
  buffer.append(System.currentTimeMillis());
  buffer.append('.');
  Formatter formatter=new Formatter(buffer,Locale.US);
  formatter.format("%1$016x-%2$08x",this.count,rndnum);
  buffer.append('.');
  buffer.append(this.hostname);
}
 

Example 4

From project AndroidCommon, under directory /src/com/asksven/android/common/privateapiproxies/.

Source file: StatElement.java

  22 
vote

public final String formatRatio(long num,long den){
  StringBuilder mFormatBuilder=new StringBuilder(8);
  Formatter mFormatter=new Formatter(mFormatBuilder);
  if (den == 0L) {
    return "---%";
  }
  float perc=((float)num) / ((float)den) * 100;
  mFormatBuilder.setLength(0);
  mFormatter.format("%.1f%%",perc);
  return mFormatBuilder.toString();
}
 

Example 5

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/util/.

Source file: ErrorReporter.java

  22 
vote

private static void appendReport(final StringBuilder report,final File file,final int indent){
  final Formatter formatter=new Formatter(report);
  for (int i=0; i < indent; i++)   report.append("  - ");
  formatter.format("%tF %tT  %s  [%d]\n",file.lastModified(),file.lastModified(),file.getName(),file.length());
  if (file.isDirectory())   for (  final File f : file.listFiles())   appendReport(report,f,indent + 1);
}
 

Example 6

From project byteman, under directory /sample/src/org/jboss/byteman/sample/helper/.

Source file: ThreadHistoryMonitorHelper.java

  22 
vote

@Override public String getEventReport() throws IOException {
  StringWriter sw=new StringWriter();
  Formatter format=new Formatter(sw);
  writeEvents(format,"Thread.create",createMap.values());
  writeEvents(format,"Thread.start",startMap.values());
  writeEvents(format,"Thread.exit",exitMap.values());
  writeEvents(format,"Runable.run",runMap.values());
  sw.close();
  return sw.toString();
}
 

Example 7

From project camel-mongodb, under directory /src/test/java/org/apache/camel/component/mongodb/.

Source file: AbstractMongoDbTest.java

  22 
vote

protected void pumpDataIntoTestCollection(){
  String[] scientists={"Einstein","Darwin","Copernicus","Pasteur","Curie","Faraday","Newton","Bohr","Galilei","Maxwell"};
  for (int i=1; i <= 1000; i++) {
    int index=i % scientists.length;
    Formatter f=new Formatter();
    String doc=f.format("{\"_id\":\"%d\", \"scientist\":\"%s\", \"fixedField\": \"fixedValue\"}",i,scientists[index]).toString();
    testCollection.insert((DBObject)JSON.parse(doc),WriteConcern.SAFE);
  }
  assertEquals("Data pumping of 1000 entries did not complete entirely",1000L,testCollection.count());
}
 

Example 8

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/monitor/.

Source file: SimpleCacheStatistics.java

  22 
vote

public void toString(final StringBuilder builder){
  if (this.name != null) {
    builder.append(this.name).append(':');
  }
  final Formatter formatter=new Formatter(builder);
  formatter.format("%.2f",this.size / BYTES_PER_MB);
  builder.append("MB used, ");
  builder.append(getPercentFree()).append("% free, ");
  builder.append(this.evictions).append(" evictions");
}
 

Example 9

From project drools-chance, under directory /drools-informer/drools-informer-loader/src/main/java/org/drools/informer/write/questionnaire/.

Source file: ApplicationTemplate.java

  22 
vote

/** 
 * Make sure that the directories and files exist, setting up for actually writing the drl file. Will include copyright and import files (simple read line and then write line).
 * @return
 */
public byte[] generateDRLAsBytes(){
  TemplateManager tm=LoaderTemplateManager.getInstance();
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Formatter fmtFile=new Formatter(baos);
  compileToDRL(tm,fmtFile);
  int count=1;
  for (Iterator<Page> iterator=app.getPageList().iterator(); iterator.hasNext(); ) {
    Page pg=iterator.next();
    new PageTemplate(pg).compileDRL(tm,fmtFile,app,count);
    count++;
  }
  fmtFile.close();
  return baos.toByteArray();
}
 

Example 10

From project erjang, under directory /src/main/java/erjang/.

Source file: EDouble.java

  22 
vote

/** 
 * @return
 */
public EString to_list(){
  Formatter form=new Formatter();
  form=form.format("%.20e",value);
  String value=form.toString();
  return new EString(value);
}
 

Example 11

From project fasthat, under directory /src/com/sun/tools/hat/internal/server/.

Source file: QueryHandler.java

  22 
vote

/** 
 * Returns a link to <code>/<var>path</var>/<var>pathInfo</var></code> with the given label and parameters.
 * @param path the static portion of the link target (should onlycontain trusted text)
 * @param pathInfo the non-static portion of the link target (will beURL-encoded)
 * @param label the link text to use
 * @param params any {@code GET} parameters to append to the link target
 * @return an HTML {@code <a>} tag formatted as described
 */
protected static String formatLink(String path,String pathInfo,String label,Multimap<String,String> params){
  StringBuilder sb=new StringBuilder();
  Formatter fmt=new Formatter(sb);
  fmt.format("<a href='/%s/%s?",path,encodeForURL(Strings.nullToEmpty(pathInfo)));
  if (params != null) {
    for (    Map.Entry<String,String> entry : params.entries()) {
      fmt.format("%s=%s&",encodeForURL(entry.getKey()),encodeForURL(entry.getValue()));
    }
  }
  sb.setLength(sb.length() - 1);
  fmt.format("'>%s</a>",Misc.encodeHtml(label));
  return sb.toString();
}
 

Example 12

From project Gmote, under directory /gmoteclient/src/org/gmote/client/android/.

Source file: GmoteMediaPlayer.java

  22 
vote

/** 
 * Utility function to format a duration into an easy to diaplay min:sec.
 */
public static String formatTime(int duration){
  int durationInSec=duration / 1000;
  int minutes=durationInSec / (60);
  int seconds=durationInSec - (minutes * 60);
  Formatter formatter=new Formatter();
  return minutes + ":" + formatter.format("%02d",seconds);
}
 

Example 13

From project griffon, under directory /subprojects/griffon-wrapper/src/main/java/org/gradle/wrapper/.

Source file: WrapperExecutor.java

  22 
vote

private URI readDistroUrlDeprecatedWay() throws URISyntaxException {
  String distroUrl=null;
  try {
    distroUrl=getProperty("urlRoot") + "/" + getProperty("distributionName")+ "-"+ getProperty("distributionVersion")+ "-"+ getProperty("distributionClassifier")+ ".zip";
    Formatter formatter=new Formatter();
    formatter.format("%s contains deprecated entries: 'urlRoot', 'distributionName', 'distributionVersion' and 'distributionClassifier' are deprecated and will be removed soon. Please use '%s' instead.%n",properties,DISTRIBUTION_URL_PROPERTY);
    warningOutput.append(formatter.toString());
  }
 catch (  Exception e) {
    reportMissingProperty(DISTRIBUTION_URL_PROPERTY);
  }
  return new URI(distroUrl);
}
 

Example 14

From project ig-undx, under directory /src/main/java/org/illegalaccess/undx/.

Source file: ClassHandler.java

  22 
vote

private static void logfmtstr3(String regres,String regadd1,String regadd2,String fmt){
  StringBuilder sb=new StringBuilder();
  Formatter f=new Formatter(sb,Locale.US);
  f.format(fmt,regres,regadd1,regadd2);
  jlog.info(sb.toString());
}
 

Example 15

From project karaf, under directory /shell/console/src/main/java/org/apache/karaf/shell/console/impl/.

Source file: Converters.java

  22 
vote

private CharSequence print(ServiceReference ref){
  StringBuilder sb=new StringBuilder();
  Formatter f=new Formatter(sb);
  String spid="";
  Object pid=ref.getProperty("service.pid");
  if (pid != null) {
    spid=pid.toString();
  }
  f.format("%06d %3s %-40s %s",ref.getProperty("service.id"),ref.getBundle().getBundleId(),getShortNames((String[])ref.getProperty("objectclass")),spid);
  return sb;
}
 

Example 16

From project lightbox-android-webservices, under directory /LightboxAndroidWebServices/src/com/lightbox/android/bitmap/.

Source file: BitmapUtils.java

  22 
vote

private static String md5ToString(byte[] md5Hash){
  Formatter formatter=new Formatter();
  for (  byte b : md5Hash) {
    formatter.format("%02x",b);
  }
  return formatter.toString();
}
 

Example 17

From project McZLauncher, under directory /src/ru/zetrix/settings/.

Source file: ShieldUtil.java

  22 
vote

private static String byteToHex(final byte[] hash){
  Formatter formatter=new Formatter();
  for (  byte b : hash) {
    formatter.format("%02x",b);
  }
  return formatter.toString();
}
 

Example 18

From project mkgmap, under directory /src/uk/me/parabola/mkgmap/main/.

Source file: StyleTester.java

  22 
vote

/** 
 * This is so we can run against versions of mkgmap that do not have toString methods on MapLine and MapRoad.
 */
private static String lineToString(MapLine el){
  Formatter fmt=new Formatter();
  fmt.format("Line 0x%x, name=<%s>, ref=<%s>, res=%d-%d",el.getType(),el.getName(),el.getRef(),el.getMinResolution(),el.getMaxResolution());
  if (el.isDirection())   fmt.format(" oneway");
  fmt.format(" ");
  for (  Coord co : el.getPoints())   fmt.format("(%s),",co);
  return fmt.toString();
}
 

Example 19

From project movsim, under directory /viewer/src/main/java/org/movsim/viewer/util/.

Source file: StringHelper.java

  22 
vote

public static String getFormatedTime(double timeInSeconds){
  int intTime=(int)timeInSeconds;
  final int hours=intTime / 3600;
  intTime=intTime % 3600;
  final int min=intTime / 60;
  intTime=intTime % 60;
  final StringBuilder stringBuilder=new StringBuilder();
  final Formatter formatter=new Formatter(stringBuilder);
  formatter.format("%02d:%02d:%02d",hours,min,intTime);
  return stringBuilder.toString();
}
 

Example 20

From project ohmagePhone, under directory /src/org/ohmage/db/.

Source file: DbHelper.java

  22 
vote

public static String getSHA1Hash(String input) throws NoSuchAlgorithmException {
  Formatter formatter=new Formatter();
  MessageDigest md=MessageDigest.getInstance("SHA1");
  byte[] hash=md.digest(input.getBytes());
  for (  byte b : hash) {
    formatter.format("%02x",b);
  }
  return formatter.toString();
}
 

Example 21

From project Ohmage_Phone, under directory /src/org/ohmage/db/.

Source file: DbHelper.java

  22 
vote

public static String getSHA1Hash(String input) throws NoSuchAlgorithmException {
  Formatter formatter=new Formatter();
  MessageDigest md=MessageDigest.getInstance("SHA1");
  byte[] hash=md.digest(input.getBytes());
  for (  byte b : hash) {
    formatter.format("%02x",b);
  }
  return formatter.toString();
}
 

Example 22

From project onebusaway-nyc, under directory /onebusaway-nyc-transit-data-federation/src/main/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/.

Source file: TripIdentifier.java

  22 
vote

private String gtfsAndStifTimeFormat(int time){
  StringBuilder sb=new StringBuilder();
  Formatter formatter=new Formatter(sb);
  int hours=time / 3600;
  int minutes=(time - hours * 3600) / 60;
  int seconds=time % 60;
  int centiminutes=(time * 100) / 60;
  formatter.format("%02d:%02d:%02d or %d",hours,minutes,seconds,centiminutes);
  return sb.toString();
}
 

Example 23

From project Opal, under directory /opal-system/src/main/java/com/lyndir/lhunath/opal/system/.

Source file: CodeUtils.java

  22 
vote

public static String encodeHex(@Nullable final byte[] data,final boolean pretty){
  StringBuilder bytes=new StringBuilder(data == null ? 0 : (data.length + (pretty ? 1 : 0)) * 2);
  Formatter formatter=new Formatter(bytes);
  String format=String.format("%%02X%s",pretty ? ":" : "");
  if (data != null)   for (  final byte b : data) {
    formatter.format(format,b);
  }
  if (pretty && bytes.length() > 0)   bytes.deleteCharAt(bytes.length() - 1);
  return bytes.toString();
}
 

Example 24

From project OpenMEAP, under directory /samples/banking/banking-web/src/com/openmeap/samples/banking/web/model/.

Source file: BankingService.java

  22 
vote

private static String getSha1(String value){
  MessageDigest sha1;
  try {
    sha1=MessageDigest.getInstance("SHA1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
  Formatter formatter=new Formatter();
  for (  byte b : sha1.digest(value.getBytes())) {
    formatter.format("%02x",b);
  }
  return formatter.toString();
}
 

Example 25

From project pepe, under directory /jdt-derby-proxy/src/main/java/edu/stanford/pepe/jdt/.

Source file: Fingerprint.java

  22 
vote

@Override public String toString(){
  StringBuilder sb=new StringBuilder();
  Formatter f=new Formatter();
  for (  byte b : fingerprint) {
    sb.append(f.format("%02X",b));
  }
  return sb.toString();
}
 

Example 26

From project recommenders, under directory /plugins/org.eclipse.recommenders.utils/src/org/eclipse/recommenders/utils/.

Source file: Fingerprints.java

  22 
vote

private static String toHexString(final byte[] hash){
  ensureIsNotNull(hash);
  final Formatter formatter=new Formatter();
  for (  final byte b : hash) {
    formatter.format("%02x",b);
  }
  return formatter.toString();
}
 

Example 27

From project replication-benchmarker, under directory /src/main/java/jbenchmarker/abt/.

Source file: ABTLog.java

  22 
vote

public void printHistory(List<ABTOperation> H){
  for (int i=H.size(); i > 0; i--) {
    Formatter fmt=new Formatter();
    fmt.format("%4d",i);
    System.out.print("|" + fmt + ":"+ H.get(i - 1)+ "\t| ");
    System.out.println("\t" + H.get(i - 1).getReplica() + ":"+ H.get(i - 1).vc+ "     ");
  }
  if (H.size() > 0)   System.out.println("+-----------------------+");
}
 

Example 28

From project sandbox, under directory /xwiki-security-rightservice/src/main/java/org/xwiki/security/internal/.

Source file: DefaultRightService.java

  22 
vote

/** 
 * Convert an action to a right.
 * @param action String representation of action.
 * @return The corresponding right, or {@link ILLEGAL}.
 */
protected final Right actionToRight(String action){
  Right right=Right.actionToRight(action);
  if (right == ILLEGAL) {
    Formatter f=new Formatter();
    getLogger().error(f.format("No action named '%s'",action.toString()).toString());
  }
  return right;
}
 

Example 29

From project sisu-guice, under directory /core/src/com/google/inject/internal/.

Source file: Errors.java

  22 
vote

public Errors childBindingAlreadySet(Key<?> key,Set<Object> sources){
  Formatter allSources=new Formatter();
  for (  Object source : sources) {
    if (source == null) {
      allSources.format("%n    (bound by a just-in-time binding)");
    }
 else {
      allSources.format("%n    bound at %s",source);
    }
  }
  Errors errors=addMessage("Unable to create binding for %s." + " It was already configured on one or more child injectors or private modules" + "%s%n"+ "  If it was in a PrivateModule, did you forget to expose the binding?",key,allSources.out());
  return errors;
}
 

Example 30

From project spark, under directory /spark-spi/src/test/java/spark/spi/util/.

Source file: TestDateTime.java

  22 
vote

private static String format(String fmt,int yr){
  StringBuilder sb=new StringBuilder();
  if (yr < 0) {
    sb.append('-');
    yr=-yr;
  }
  Formatter f=new Formatter(sb);
  f.format(fmt,yr);
  return sb.toString();
}
 

Example 31

From project speed4j, under directory /src/main/java/com/ecyrd/speed4j/log/.

Source file: PeriodicalLog.java

  22 
vote

/** 
 * Writes to the internal logger, just like ye goode olde C printf().
 * @param pattern Pattern to write to (see {@link Formatter#format(String,Object)}
 * @param args Arguments for the pattern.
 */
private void printf(String pattern,Object... args){
  if (m_log != null) {
    StringBuilder sb=new StringBuilder();
    Formatter formatter=new Formatter(sb);
    try {
      formatter.format(pattern,args);
      m_log.info(sb.toString());
    }
  finally {
      formatter.close();
    }
  }
}
 

Example 32

From project storm-counts, under directory /src/test/java/com/mapr/storm/.

Source file: Fake.java

  22 
vote

@Override public String toString(){
  int i=0;
  Formatter f=new Formatter();
  f.format("[");
  String separator="";
  for (  String field : fields) {
    f.format("%s%s=%s",separator,field,getValue(i++));
    separator=", ";
  }
  f.format("]");
  return f.toString();
}
 

Example 33

From project uomo, under directory /bundles/org.eclipse.uomo.units/src/main/java/org/eclipse/uomo/units/impl/format/.

Source file: LocalUnitFormatImpl.java

  22 
vote

/** 
 * Formats the given <code>Formattable</code> to the given StringBuffer and returns the given precedence of the converter's mathematical operation.
 * @param f the formattable to be formatted
 * @param unitPrecedence the operator precedence of the operation expressed by the unit being modified by the given converter.
 * @param buffer the <code>StringBuffer</code> to append to.
 * @return the given operator precedence
 */
private int formatFormattable(Formattable f,int unitPrecedence,StringBuilder buffer){
  Formatter fmt=new Formatter();
  fmt.format(Messages.LocalFormat_Pattern,f);
  buffer.replace(0,1,fmt.toString());
  return unitPrecedence;
}
 

Example 34

From project agraph-java-client, under directory /src/test/stress/.

Source file: Events.java

  21 
vote

public static void trace(String format,Object... values){
  StringBuilder sb=new StringBuilder();
  Formatter formatter=new Formatter(sb);
  if (Defaults.LOG == Defaults.LOGT.ALL) {
    formatter.format("%s [%2$tF %2$tT.%2$tL]: ",Thread.currentThread().getName(),GregorianCalendar.getInstance());
  }
 else   if (Defaults.LOG == Defaults.LOGT.ELAPSED) {
    formatter.format("%s [%d]: ",Thread.currentThread().getName(),(System.currentTimeMillis() - START));
  }
 else   if (Defaults.LOG == Defaults.LOGT.NOTIME) {
    formatter.format("%s: ",Thread.currentThread().getName());
  }
  formatter.format(format,values);
  System.out.println(sb.toString());
}
 

Example 35

From project android-xbmcremote, under directory /src/org/xbmc/api/object/.

Source file: Song.java

  21 
vote

/** 
 * Returns a formatted string (MM:SS) for a number of seconds.
 * @param d Number of seconds
 * @return Formatted time
 */
public static String getDuration(int d){
  StringBuilder sb=new StringBuilder();
  if (d > 3600) {
    sb.append((int)d / 3600);
    sb.append(":");
    d%=3600;
  }
  int min=(int)d / 60;
  Formatter f=new Formatter();
  if (sb.length() > 0) {
    if (min < 10)     sb.append(0);
    sb.append(min);
    sb.append(":");
  }
 else {
    sb.append(min + ":");
  }
  d%=60;
  sb.append(f.format("%02d",d));
  return sb.toString();
}
 

Example 36

From project Arecibo, under directory /dashboard/src/main/java/com/ning/arecibo/dashboard/format/.

Source file: DoubleFormatter.java

  21 
vote

public static String formatNDecimalsAndStripTrailingZeroes(Object value,int numDecimals,boolean okToAddHtml){
  if (!(value instanceof Number))   return "NaN";
  double v=((Number)value).doubleValue();
  StringBuilder sb=new StringBuilder();
  if (Math.abs(v) >= 0.1 || v == 0.0) {
    Formatter formatter=new Formatter(sb);
    formatter.format("%." + numDecimals + "f",v);
    removeTrailingZeroes(sb);
  }
 else {
    Formatter formatter=new Formatter(sb);
    String formatStr="%." + numDecimals + "g";
    formatter.format(formatStr,v);
    int expIndex=sb.indexOf("e");
    if (expIndex == -1) {
      removeTrailingZeroes(sb);
    }
 else {
      expIndex=removeTrailingZeroes(sb,expIndex);
      if (okToAddHtml) {
        sb.insert(expIndex + 1,"<sup>");
        sb.append("</sup>");
      }
    }
  }
  return sb.toString();
}
 

Example 37

From project capedwarf-green, under directory /connect/src/main/java/org/jboss/capedwarf/connect/config/.

Source file: DefaultConfiguration.java

  21 
vote

/** 
 * Default appspot configuration.
 * @param appspotName the appspot name
 */
public DefaultConfiguration(String appspotName){
  boolean debug=(appspotName == null || appspotName.length() == 0);
  setDebugMode(debug);
  setDebugLogging(debug);
  setSslPort(443);
  setPort(isDebugMode() ? 8080 : 80);
  String localhost="localhost";
  Environment env=EnvironmentFactory.getEnvironment();
  if (env.envType() == EnvironmentType.ANDROID)   localhost="://10.0.2.2";
  setHostName(isDebugMode() ? localhost : new Formatter().format(Constants.HOST,appspotName).toString());
}
 

Example 38

From project cp-common-utils, under directory /src/com/clarkparsia/common/base/.

Source file: Memory.java

  21 
vote

/** 
 * Detailed memory information logged only at TRACE level.
 */
public static String detailedUsage(){
  StringBuilder sb=new StringBuilder();
  try {
    Formatter formatter=new Formatter(sb);
    formatter.format("%nDETAILED MEMORY INFO%n");
    formatter.format("Heap Memory Usage: %s%n",MEMORY.getHeapMemoryUsage());
    formatter.format("Non-Heap Memory Usage: %s%n",MEMORY.getNonHeapMemoryUsage());
    List<GarbageCollectorMXBean> gcmBeans=ManagementFactory.getGarbageCollectorMXBeans();
    for (    GarbageCollectorMXBean gcmBean : gcmBeans) {
      formatter.format("Name: %s%n",gcmBean.getName());
      formatter.format("\tCollection count: %s%n",gcmBean.getCollectionCount());
      formatter.format("\tCollection time: %s%n",gcmBean.getCollectionTime());
      formatter.format("\tMemory Pools: %s%n",Arrays.toString(gcmBean.getMemoryPoolNames()));
    }
    formatter.format("Memory Pools Info");
    List<MemoryPoolMXBean> mpBeans=ManagementFactory.getMemoryPoolMXBeans();
    for (    MemoryPoolMXBean mpBean : mpBeans) {
      formatter.format("Name: %s%n",mpBean.getName());
      formatter.format("\tUsage: %s%n",mpBean.getUsage());
      formatter.format("\tCollection Usage: %s%n",mpBean.getCollectionUsage());
      formatter.format("\tPeak Usage: %s%n",mpBean.getPeakUsage());
      formatter.format("\tType: %s%n",mpBean.getType());
      formatter.format("\tMemory Manager Names: %s%n",Arrays.toString(mpBean.getMemoryManagerNames()));
    }
  }
 catch (  Exception e) {
    LOGGER.warn("Cannot get memory info",e);
  }
  return sb.toString();
}
 

Example 39

From project crash, under directory /cmdline/src/main/java/org/crsh/cmdline/.

Source file: ClassDescriptor.java

  21 
vote

@Override public void printUsage(Appendable writer) throws IOException {
  if (methodMap.size() == 1) {
    methodMap.values().iterator().next().printUsage(writer);
  }
 else {
    writer.append("usage: ").append(getName());
    for (    OptionDescriptor<?> option : getOptions()) {
      option.printUsage(writer);
    }
    writer.append(" COMMAND [ARGS]\n\n");
    writer.append("The most commonly used ").append(getName()).append(" commands are:\n");
    String format="   %1$-16s %2$s\n";
    for (    MethodDescriptor<T> method : getMethods()) {
      Formatter formatter=new Formatter(writer);
      formatter.format(format,method.getName(),method.getUsage());
    }
  }
}
 

Example 40

From project fuzzydb-samples, under directory /sample-webapp/src/main/java/org/fuzzydb/samples/.

Source file: Utils.java

  21 
vote

/** 
 * A little help for things like Arrays
 * @param object
 * @return formatted string representation
 */
public static String toString(Object object){
  if (object == null) {
    return "";
  }
  if (object instanceof Object[]) {
    Object[] array=(Object[])object;
    StringBuilder sb=new StringBuilder();
    for (int i=0; i < array.length; i++) {
      sb.append(array[i].toString());
      if (i < array.length - 1) {
        sb.append(", ");
      }
    }
    return sb.toString();
  }
 else   if (object instanceof float[]) {
    float[] array=(float[])object;
    StringBuilder sb=new StringBuilder();
    Formatter f=new Formatter(sb);
    for (int i=0; i < array.length; i++) {
      f.format("%.1f",array[i]);
      if (i < array.length - 1) {
        sb.append(", ");
      }
    }
    return sb.toString();
  }
 else   if (object instanceof Float) {
    return String.format("%.0f",object);
  }
  return object.toString();
}
 

Example 41

From project jgraphx, under directory /src/com/mxgraph/util/.

Source file: mxUtils.java

  21 
vote

/** 
 * Returns the Md5 hash for the given text.
 * @param text String whose Md5 hash should be returned.
 * @return Returns the Md5 hash for the given text.
 */
public static String getMd5Hash(String text){
  StringBuffer result=new StringBuffer(32);
  try {
    MessageDigest md5=MessageDigest.getInstance("MD5");
    md5.update(text.getBytes());
    Formatter f=new Formatter(result);
    byte[] digest=md5.digest();
    for (int i=0; i < digest.length; i++) {
      f.format("%02x",new Object[]{new Byte(digest[i])});
    }
  }
 catch (  NoSuchAlgorithmException ex) {
    ex.printStackTrace();
  }
  return result.toString();
}
 

Example 42

From project jolokia, under directory /agent/jvm/src/main/java/org/jolokia/jvmagent/client/command/.

Source file: ListCommand.java

  21 
vote

/** 
 * {@inheritDoc} 
 */
@Override @SuppressWarnings("PMD.SystemPrintln") int execute(OptionsAndArgs pOpts,Object pVm,VirtualMachineHandler pHandler) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
  List<ProcessDescription> vmDescriptors=pHandler.listProcesses();
  for (  ProcessDescription descriptor : vmDescriptors) {
    System.out.println(new Formatter().format("%7.7s   %-100.100s",descriptor.getId(),descriptor.getDisplay()));
  }
  return 0;
}
 

Example 43

From project kevoree-library, under directory /android/org.kevoree.library.android.osmdroid/src/main/java/org/osmdroid/contributor/util/.

Source file: RecordedRouteGPXFormatter.java

  21 
vote

/** 
 * Creates a String in the following XML format: <PRE> &lt;?xml version=&quot;1.0&quot;?&gt; &lt;gpx version=&quot;1.1&quot; creator=&quot;AndNav - http://www.andnav.org - Android Navigation System&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns=&quot;http://www.topografix.com/GPX/1/1&quot; xsi:schemaLocation=&quot;http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd&quot;&gt; &lt;time&gt;2008-09-22T00:46:20Z&lt;/time&gt; &lt;trk&gt; &lt;name&gt;plusminus--yyyyMMdd_HHmmss-yyyyMMdd_HHmmss&lt;/name&gt; &lt;trkseg&gt; &lt;trkpt lat=&quot;49.472767&quot; lon=&quot;8.654174&quot;&gt; &lt;time&gt;2008-09-22T00:46:20Z&lt;/time&gt; &lt;/trkpt&gt; &lt;trkpt lat=&quot;49.472797&quot; lon=&quot;8.654102&quot;&gt; &lt;time&gt;2008-09-22T00:46:35Z&lt;/time&gt; &lt;/trkpt&gt; &lt;trkpt lat=&quot;49.472802&quot; lon=&quot;8.654185&quot;&gt; &lt;time&gt;2008-09-22T00:46:50Z&lt;/time&gt; &lt;/trkpt&gt; &lt;/trkseg&gt; &lt;/trk&gt; &lt;/gpx&gt; </PRE>
 */
public static String create(final List<RecordedGeoPoint> someRecords) throws IllegalArgumentException {
  if (someRecords == null)   throw new IllegalArgumentException("Records may not be null.");
  if (someRecords.size() == 0)   throw new IllegalArgumentException("Records size == 0");
  final StringBuilder sb=new StringBuilder();
  final Formatter f=new Formatter(sb);
  sb.append(XML_VERSION);
  f.format(GPX_TAG,OSM_CREATOR_INFO);
  f.format(GPX_TAG_TIME,Util.convertTimestampToUTCString(System.currentTimeMillis()));
  sb.append(GPX_TAG_TRACK);
  f.format(GPX_TAG_TRACK_NAME,OSM_USERNAME + "--" + formatterCompleteDateTime.format(new Date(someRecords.get(0).getTimeStamp()).getTime())+ "-"+ formatterCompleteDateTime.format(new Date(someRecords.get(someRecords.size() - 1).getTimeStamp()).getTime()));
  sb.append(GPX_TAG_TRACK_SEGMENT);
  for (  final RecordedGeoPoint rgp : someRecords) {
    f.format(GPX_TAG_TRACK_SEGMENT_POINT,rgp.getLatitudeAsDouble(),rgp.getLongitudeAsDouble());
    f.format(GPX_TAG_TRACK_SEGMENT_POINT_TIME,Util.convertTimestampToUTCString(rgp.getTimeStamp()));
    if (rgp.mNumSatellites != NOT_SET)     f.format(GPX_TAG_TRACK_SEGMENT_POINT_SAT,rgp.mNumSatellites);
    sb.append(GPX_TAG_TRACK_SEGMENT_POINT_CLOSE);
  }
  sb.append(GPX_TAG_TRACK_SEGMENT_CLOSE).append(GPX_TAG_TRACK_CLOSE).append(GPX_TAG_CLOSE);
  return sb.toString();
}
 

Example 44

From project medsavant, under directory /MedSavantShared/src/com/healthmarketscience/sqlbuilder/.

Source file: QueryPreparer.java

  21 
vote

/** 
 * outputs the static place holders in order
 */
@Override public String toString(){
  Formatter fmt=new Formatter();
  if (_staticPlaceHolders != null) {
    for (    StaticPlaceHolder placeHolder : _staticPlaceHolders) {
      if (placeHolder != null) {
        fmt.format("[%s] %s%n",placeHolder.getClass().getSimpleName(),placeHolder.displayToString());
      }
 else {
        fmt.format("<null>???");
      }
    }
  }
 else {
    fmt.format("<No static place holders>%n");
  }
  return fmt.toString();
}
 

Example 45

From project MobiPerf, under directory /android/src/com/mobiperf/speedometer/.

Source file: MeasurementResult.java

  21 
vote

@Override public String toString(){
  StringBuilder builder=new StringBuilder();
  StringBuilderPrinter printer=new StringBuilderPrinter(builder);
  Formatter format=new Formatter();
  try {
    if (type == PingTask.TYPE) {
      getPingResult(printer,values);
    }
 else     if (type == HttpTask.TYPE) {
      getHttpResult(printer,values);
    }
 else     if (type == DnsLookupTask.TYPE) {
      getDnsResult(printer,values);
    }
 else     if (type == TracerouteTask.TYPE) {
      getTracerouteResult(printer,values);
    }
 else     if (type == UDPBurstTask.TYPE) {
      getUDPBurstResult(printer,values);
    }
 else {
      Logger.e("Failed to get results for unknown measurement type " + type);
    }
    return builder.toString();
  }
 catch (  NumberFormatException e) {
    Logger.e("Exception occurs during constructing result string for user",e);
  }
catch (  ClassCastException e) {
    Logger.e("Exception occurs during constructing result string for user",e);
  }
catch (  Exception e) {
    Logger.e("Exception occurs during constructing result string for user",e);
  }
  return "Measurement has failed";
}
 

Example 46

From project modelmapper, under directory /core/src/main/java/org/modelmapper/internal/.

Source file: Errors.java

  21 
vote

/** 
 * Returns the formatted message for an exception with the specified messages. 
 */
public static String format(String heading,Collection<ErrorMessage> errorMessages){
  Formatter fmt=new Formatter().format(heading).format(":%n%n");
  int index=1;
  boolean displayCauses=getOnlyCause(errorMessages) == null;
  for (  ErrorMessage errorMessage : errorMessages) {
    fmt.format("%s) %s%n",index++,errorMessage.getMessage());
    Throwable cause=errorMessage.getCause();
    if (displayCauses && cause != null) {
      StringWriter writer=new StringWriter();
      cause.printStackTrace(new PrintWriter(writer));
      fmt.format("Caused by: %s",writer.getBuffer());
    }
    fmt.format("%n");
  }
  if (errorMessages.size() == 1)   fmt.format("1 error");
 else   fmt.format("%s errors",errorMessages.size());
  return fmt.toString();
}
 

Example 47

From project OpenTripPlanner, under directory /opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/ned/.

Source file: NEDDownloader.java

  21 
vote

private List<URL> getDownloadURLsCached(){
  Envelope extent=graph.getExtent();
  Formatter formatter=new Formatter();
  String filename=formatter.format("%f,%f-%f,%f.urls",extent.getMinX(),extent.getMinY(),extent.getMaxX(),extent.getMaxY()).toString();
  formatter.close();
  try {
    File file=new File(cacheDirectory,filename);
    List<URL> urls;
    if (!file.exists()) {
      return getAndCacheUrls(file);
    }
    FileInputStream is=new FileInputStream(file);
    BufferedReader reader=new BufferedReader(new InputStreamReader(is));
    urls=new ArrayList<URL>();
    while (true) {
      String line=reader.readLine();
      if (line == null || line.length() == 0) {
        break;
      }
      urls.add(new URL(line));
    }
    reader.close();
    is.close();
    if (urls.size() == 0) {
      return getAndCacheUrls(file);
    }
    return urls;
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 48

From project packages_apps_Calendar, under directory /src/com/android/calendar/agenda/.

Source file: AgendaByDayAdapter.java

  21 
vote

public AgendaByDayAdapter(Context context){
  mContext=context;
  mAgendaAdapter=new AgendaAdapter(context,R.layout.agenda_item);
  mInflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  mStringBuilder=new StringBuilder(50);
  mFormatter=new Formatter(mStringBuilder,Locale.getDefault());
  mTimeZone=Utils.getTimeZone(context,mTZUpdater);
  mTmpTime=new Time(mTimeZone);
}
 

Example 49

From project platform_packages_apps_calendar, under directory /src/com/android/calendar/agenda/.

Source file: AgendaByDayAdapter.java

  21 
vote

public AgendaByDayAdapter(Context context){
  mContext=context;
  mAgendaAdapter=new AgendaAdapter(context,R.layout.agenda_item);
  mInflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  mStringBuilder=new StringBuilder(50);
  mFormatter=new Formatter(mStringBuilder,Locale.getDefault());
  mTimeZone=Utils.getTimeZone(context,mTZUpdater);
  mTmpTime=new Time(mTimeZone);
}
 

Example 50

From project sparsemapcontent, under directory /core/src/main/java/org/sakaiproject/nakamura/api/lite/util/.

Source file: ISO8601Date.java

  21 
vote

@Override public String toString(){
  Formatter formatter=new Formatter();
  int year=get(YEAR);
  int month=get(MONTH) + 1;
  int day=get(DAY_OF_MONTH);
  int hour=get(HOUR_OF_DAY);
  int min=get(MINUTE);
  int second=get(SECOND);
  if (date) {
    formatter.format("%04d-%02d-%02d",year,month,day);
  }
 else {
    long offset=getTimeZone().getOffset(getTimeInMillis()) / (60000L);
    int hoffset=(int)(offset / 60L);
    int minoffset=(int)(offset % 60L);
    if (offset == 0) {
      formatter.format("%04d-%02d-%02dT%02d:%02d:%02dZ",year,month,day,hour,min,second);
    }
 else     if (offset < 0) {
      formatter.format("%04d-%02d-%02dT%02d:%02d:%02d-%02d:%02d",year,month,day,hour,min,second,-hoffset,-minoffset);
    }
 else {
      formatter.format("%04d-%02d-%02dT%02d:%02d:%02d+%02d:%02d",year,month,day,hour,min,second,hoffset,minoffset);
    }
  }
  return formatter.toString();
}
 

Example 51

From project Speedometer, under directory /android/src/com/google/wireless/speed/speedometer/.

Source file: MeasurementResult.java

  21 
vote

@Override public String toString(){
  StringBuilder builder=new StringBuilder();
  StringBuilderPrinter printer=new StringBuilderPrinter(builder);
  Formatter format=new Formatter();
  try {
    if (type == PingTask.TYPE) {
      getPingResult(printer,values);
    }
 else     if (type == HttpTask.TYPE) {
      getHttpResult(printer,values);
    }
 else     if (type == DnsLookupTask.TYPE) {
      getDnsResult(printer,values);
    }
 else     if (type == TracerouteTask.TYPE) {
      getTracerouteResult(printer,values);
    }
 else     if (type == UDPBurstTask.TYPE) {
      getUDPBurstResult(printer,values);
    }
    return builder.toString();
  }
 catch (  NumberFormatException e) {
    Logger.e("Exception occurs during constructing result string for user",e);
  }
catch (  ClassCastException e) {
    Logger.e("Exception occurs during constructing result string for user",e);
  }
catch (  Exception e) {
    Logger.e("Exception occurs during constructing result string for user",e);
  }
  return "Measurement has failed";
}
 

Example 52

From project spring-hadoop, under directory /src/main/java/org/springframework/data/hadoop/util/.

Source file: PathUtils.java

  21 
vote

/** 
 * Generates a timed-based path, based on the given date, using the format of  {@link java.util.Formatter}.
 * @param pathFormat Path format, the variable in the path will be replaced by  {@link java.util.Date}.
 * @param appendUUID whether or not to append a UUID at the end
 * @param date date to use 
 * @return generated path
 */
public static String format(String pathFormat,boolean appendUUID,Date date){
  if (pathFormat == null || pathFormat.length() == 0) {
    return "";
  }
  pathFormat=pathFormat.replace('/',File.separatorChar);
  StringBuilder strBuffer=new StringBuilder();
  Formatter formatter=new Formatter(strBuffer,Locale.US);
  formatter.format(pathFormat,date);
  if (!pathFormat.endsWith(File.separator)) {
    strBuffer.append(File.separator);
  }
  if (appendUUID) {
    strBuffer.append(UUID.randomUUID());
    strBuffer.append(File.separator);
  }
  return strBuffer.toString();
}
 

Example 53

From project sqoop, under directory /src/java/org/apache/sqoop/io/.

Source file: SplittingOutputStream.java

  21 
vote

/** 
 * Initialize the OutputStream to the next file to write to.
 */
private void openNextFile() throws IOException {
  StringBuffer sb=new StringBuffer();
  Formatter fmt=new Formatter(sb);
  fmt.format("%05d",this.fileNum++);
  String filename=filePrefix + fmt.toString();
  if (codec != null) {
    filename=filename + codec.getDefaultExtension();
  }
  Path destFile=new Path(destDir,filename);
  FileSystem fs=destFile.getFileSystem(conf);
  LOG.debug("Opening next output file: " + destFile);
  if (fs.exists(destFile)) {
    Path canonicalDest=destFile.makeQualified(fs);
    throw new IOException("Destination file " + canonicalDest + " already exists");
  }
  OutputStream fsOut=fs.create(destFile);
  this.countingFilterStream=new CountingOutputStream(fsOut);
  if (codec != null) {
    this.writeStream=codec.createOutputStream(this.countingFilterStream);
  }
 else {
    this.writeStream=this.countingFilterStream;
  }
}
 

Example 54

From project sulky, under directory /sulky-blobs/src/main/java/de/huxhorn/sulky/blobs/impl/.

Source file: BlobRepositoryImpl.java

  21 
vote

private boolean valid(String id,File file){
  if (!validating) {
    return true;
  }
  MessageDigest digest=createMessageDigest();
  FileInputStream input=null;
  try {
    input=new FileInputStream(file);
    DigestInputStream dis=new DigestInputStream(input,digest);
    for (; ; ) {
      if (dis.read() < 0) {
        break;
      }
    }
    byte[] hash=digest.digest();
    Formatter formatter=new Formatter();
    for (    byte b : hash) {
      formatter.format("%02x",b);
    }
    return formatter.toString().equals(id);
  }
 catch (  IOException e) {
  }
 finally {
    IOUtils.closeQuietly(input);
  }
  return false;
}
 

Example 55

From project vlcj, under directory /src/main/java/uk/co/caprica/vlcj/logger/.

Source file: Logger.java

  21 
vote

private static void out(String level,String msg,Throwable t,Object... args){
  PrintWriter out=INSTANCE.out;
synchronized (out) {
    StackTraceElement el=getLine();
    Formatter formatter=new Formatter();
    try {
      String location=formatter.format("(%s:%d)",el.getFileName(),el.getLineNumber()).toString();
      out.printf("vlcj: %-46s | %-5s | %s%n",location,level,format(msg,args));
      out.flush();
      if (t != null) {
        PrintWriter err=INSTANCE.err;
        err.printf("vlcj: %-46s | %-5s | %s%n",location,level,t.getMessage());
        err.flush();
        t.printStackTrace();
      }
    }
  finally {
      formatter.close();
    }
  }
}
 

Example 56

From project xwiki-eclipse, under directory /plugins/org.xwiki.eclipse.storage/src/main/java/org/xwiki/eclipse/model/.

Source file: XWikiExtendedId.java

  21 
vote

@Override public String toString(){
  StringBuffer sb=new StringBuffer();
  Formatter f=new Formatter(sb);
  f.format("%s",basePageId);
  if (parametersMap.size() != 0) {
    f.format("?");
    String[] keys=parametersMap.keySet().toArray(new String[0]);
    for (int i=0; i < keys.length; i++) {
      if (i != (keys.length - 1)) {
        f.format("%s=%s&",keys[i],parametersMap.get(keys[i]));
      }
 else {
        f.format("%s=%s",keys[i],parametersMap.get(keys[i]));
      }
    }
  }
  return sb.toString();
}
 

Example 57

From project Bio-PEPA, under directory /uk.ac.ed.inf.common.ui.plotting/src/uk/ac/ed/inf/common/ui/plotting/internal/.

Source file: LineChartBuilder.java

  20 
vote

@Override protected void buildYSeries(){
  SeriesDefinition sdY=SeriesDefinitionImpl.create();
  yAxis.getSeriesDefinitions().add(sdY);
  int i=0, j=0;
  for (  uk.ac.ed.inf.common.ui.plotting.data.Series series : ((InfoWithAxes)info).getYSeries()) {
    double[] values=series.getValues();
    LineSeries ls=createLineSeries(values);
    ls.setSeriesIdentifier(series.getLabel());
    setAttibutes(ls,i,j);
    sdY.getSeries().add(ls);
    if (series instanceof ConfidenceSeries) {
      this.chart.setType("Stock Chart");
      this.chart.setSubType("Standard Stock Chart");
      double[] radii=((ConfidenceSeries)series).getRadii();
      StockSeries ss=createStockSeries(values,radii);
      String id=new Formatter().format("%2.1f%% c.i.",((ConfidenceSeries)series).getConfidenceLevel() * 100).toString();
      ss.setSeriesIdentifier(id);
      setAttibutes(ss,i,j);
      sdY.getSeries().add(ss);
    }
    i++;
    j++;
  }
}
 

Example 58

From project jredis, under directory /core/ri/src/main/java/org/jredis/ri/alphazero/support/.

Source file: Assert.java

  20 
vote

/** 
 * Not really intended for external use since you could simply throw new E (msg).  <p> <b>Usage</b> (if you must): <pre><code> // ... somewhere within the bowels of your code .. // Assert.throwIt ("why am i calling Assert.throwIt() when I could be throwing myself?", YourRuntimeException.class); </code> </pre>
 * @param < E > {@link RuntimeException} subclass to to throw
 * @param msg message to set in the exception
 * @param clazz the Class of E
 * @throws E your requested exception (unless reflection instantiate failed, in which case it will be a plain old  {@link RuntimeException})
 */
private static final <E extends RuntimeException>void throwIt(String msg,Class<E> clazz) throws E {
  int fidx=0;
  StackTraceElement ste[]=Thread.currentThread().getStackTrace();
  int j=0;
  for (  StackTraceElement e : ste) {
    j++;
    if (e.getClassName().equals(Assert.class.getName()))     fidx=j;
  }
  StackTraceElement[] filtered=new StackTraceElement[ste.length - fidx];
  for (int i=fidx; i < ste.length; i++)   filtered[i - fidx]=ste[i];
  StackTraceElement src=filtered[0];
  String simpleClassName=src.getClassName().substring(src.getClassName().lastIndexOf('.') + 1);
  int scni=src.getClassName().indexOf(simpleClassName) > 0 ? src.getClassName().indexOf(simpleClassName) - 1 : 0;
  String packageName=src.getClassName().substring(0,scni);
  @SuppressWarnings("boxing") String info=new Formatter().format("%s in method %s.%s() [file: %s line:%d - package: %s]",msg,simpleClassName,src.getMethodName(),src.getFileName(),src.getLineNumber(),packageName).toString();
  RuntimeException rte=new IllegalArgumentException(info);
  try {
    rte=clazz.getDeclaredConstructor(String.class,Throwable.class).newInstance(info,rte);
  }
 catch (  InstantiationException e) {
    e.printStackTrace();
  }
catch (  IllegalAccessException e) {
    e.printStackTrace();
  }
catch (  IllegalArgumentException e) {
    e.printStackTrace();
  }
catch (  SecurityException e) {
    e.printStackTrace();
  }
catch (  InvocationTargetException e) {
    e.printStackTrace();
  }
catch (  NoSuchMethodException e) {
    e.printStackTrace();
  }
  rte.setStackTrace(filtered);
  throw rte;
}
 

Example 59

From project juzu, under directory /core/src/main/java/juzu/impl/compiler/.

Source file: Message.java

  20 
vote

public StringBuilder format(StringBuilder sb,boolean formal){
  if (formal) {
    sb=sb.append("[").append(code.getKey()).append("](");
    for (int i=0; i < arguments.length; i++) {
      if (i > 0) {
        sb.append(',');
      }
      sb.append(String.valueOf(arguments[i]));
    }
    sb.append(")");
  }
 else {
    new Formatter(sb).format(Locale.getDefault(),code.getMessage(),arguments).flush();
  }
  return sb;
}
 

Example 60

From project netty, under directory /example/src/main/java/io/netty/example/localtime/.

Source file: LocalTimeClientHandler.java

  20 
vote

public List<String> getLocalTimes(Collection<String> cities){
  Locations.Builder builder=Locations.newBuilder();
  for (  String c : cities) {
    String[] components=c.split("/");
    builder.addLocation(Location.newBuilder().setContinent(Continent.valueOf(components[0].toUpperCase())).setCity(components[1]).build());
  }
  channel.write(builder.build());
  LocalTimes localTimes;
  boolean interrupted=false;
  for (; ; ) {
    try {
      localTimes=answer.take();
      break;
    }
 catch (    InterruptedException e) {
      interrupted=true;
    }
  }
  if (interrupted) {
    Thread.currentThread().interrupt();
  }
  List<String> result=new ArrayList<String>();
  for (  LocalTime lt : localTimes.getLocalTimeList()) {
    result.add(new Formatter().format("%4d-%02d-%02d %02d:%02d:%02d %s",lt.getYear(),lt.getMonth(),lt.getDayOfMonth(),lt.getHour(),lt.getMinute(),lt.getSecond(),lt.getDayOfWeek().name()).toString());
  }
  return result;
}
 

Example 61

From project platform_packages_apps_contacts, under directory /tests/src/com/android/contacts/calllog/.

Source file: CallLogFragmentTest.java

  20 
vote

/** 
 * Insert a range [start, end) of random numbers in the DB. For each row, there is a 1/10 probability that the number will be marked as PRIVATE or UNKNOWN or VOICEMAIL. For regular numbers, a number is inserted, its last 4 digits will be the number of the iteration in the range.
 * @param start Of the range.
 * @param end Of the range (excluded).
 * @return An array with 2 booleans [0 = private number, 1 =unknown number, 2 = voicemail] to indicate if at least one private or unknown or voicemail number has been inserted. Since the numbers are random some tests may want to enforce the insertion of such numbers.
 */
private boolean[] insertRandomRange(int start,int end){
  boolean[] privateOrUnknownOrVm=new boolean[]{false,false,false};
  for (int i=start; i < end; i++) {
    int type=mRnd.nextInt(10);
    if (0 == type) {
      insertPrivate(NOW,RAND_DURATION);
      privateOrUnknownOrVm[0]=true;
    }
 else     if (1 == type) {
      insertUnknown(NOW,RAND_DURATION);
      privateOrUnknownOrVm[1]=true;
    }
 else     if (2 == type) {
      insertCalltoVoicemail(NOW,RAND_DURATION);
      privateOrUnknownOrVm[2]=true;
    }
 else {
      int inout=mRnd.nextBoolean() ? Calls.OUTGOING_TYPE : Calls.INCOMING_TYPE;
      String number=new Formatter().format("1800123%04d",i).toString();
      insert(number,NOW,RAND_DURATION,inout);
    }
  }
  return privateOrUnknownOrVm;
}
 

Example 62

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/cache/.

Source file: RadixTreeImpl.java

  19 
vote

/** 
 * WARNING! Do not use this for a large Trie, it's for testing purpose only.
 */
private void formatNodeTo(Formatter f,int level,RadixTreeNode<T> node){
  for (int i=0; i < level; i++) {
    f.format(" ");
  }
  f.format("|");
  for (int i=0; i < level; i++) {
    f.format("-");
  }
  if (node.isReal() == true)   f.format("%s[%s]*%n",node.getKey(),node.getValue());
 else   f.format("%s%n",node.getKey());
  for (  RadixTreeNode<T> child : node.getChildern()) {
    formatNodeTo(f,level + 1,child);
  }
}
 

Example 63

From project brut.apktool.smali, under directory /util/src/main/java/ds/tree/.

Source file: RadixTreeImpl.java

  19 
vote

/** 
 * WARNING! Do not use this for a large Trie, it's for testing purpose only.
 */
private void formatNodeTo(Formatter f,int level,RadixTreeNode<T> node){
  for (int i=0; i < level; i++) {
    f.format(" ");
  }
  f.format("|");
  for (int i=0; i < level; i++) {
    f.format("-");
  }
  if (node.isReal() == true)   f.format("%s[%s]*%n",node.getKey(),node.getValue());
 else   f.format("%s%n",node.getKey());
  for (  RadixTreeNode<T> child : node.getChildern()) {
    formatNodeTo(f,level + 1,child);
  }
}
 

Example 64

From project drools-mas, under directory /drools-mas-core/src/main/java/org/drools/mas/core/.

Source file: SessionTemplateManager.java

  19 
vote

protected void applyTemplate(String templateName,Object context,Map vars,Formatter fmt){
  CompiledTemplate template=(CompiledTemplate)getRegistry().getNamedTemplate(templateName);
  try {
    fmt.out().append(TemplateRuntime.execute(template,context,vars).toString());
  }
 catch (  IOException ioe) {
    ioe.printStackTrace();
  }
}
 

Example 65

From project jsf-test, under directory /maven-mockgenerator-plugin/src/main/java/org/jboss/mockgenerator/.

Source file: MockJavaSource.java

  19 
vote

public void formatTo(Formatter formatter,int flags,int width,int precision){
  for (int i=0; i < this.parameterTypes.length; i++) {
    Class<?> parameter=this.parameterTypes[i];
    formatter.format(getFormat(),classToString(parameter,varargs && i == this.parameterTypes.length - 1),i,0 == i ? "" : ",");
  }
}