Java Code Examples for java.util.Formatter

The following are top voted examples for showing how to use java.util.Formatter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: an2linuxclient   File: ServerDatabaseHandler.java   View source code 7 votes vote down vote up
/**
 * @return certificate id or -1 if not found
 */
public long getCertificateId(byte[] certificateBytes){
    Formatter formatter = new Formatter();
    for (byte b : Sha256Helper.sha256(certificateBytes)){
        formatter.format("%02x", b);
    }

    SQLiteDatabase db = this.getWritableDatabase();

    Cursor c = db.query(TABLE_CERTIFICATES,
            new String[]{COLUMN_ID},
            COLUMN_FINGERPRINT + "=?", new String[]{formatter.toString()},
            null, null, null);

    long returnValue;
    if (c.moveToFirst()){
        returnValue = c.getLong(0);
    } else {
        returnValue = -1;
    }
    c.close();
    db.close();
    return returnValue;
}
 
Example 2
Project: LivroJavaComoProgramar10Edicao   File: CreateTextFile.java   View source code 7 votes vote down vote up
public static void openFile()
{
   try
   {
      output = new Formatter("clients.txt"); // open the file
   }
   catch (SecurityException securityException)
   {
      System.err.println("Write permission denied. Terminating.");
      System.exit(1); // terminate the program
   } 
   catch (FileNotFoundException fileNotFoundException)
   {
      System.err.println("Error opening file. Terminating.");
      System.exit(1); // terminate the program
   } 
}
 
Example 3
Project: appinventor-extensions   File: PhoneStatus.java   View source code 6 votes vote down vote up
@SimpleFunction(description = "Establish the secret seed for HOTP generation. " +
  "Return the SHA1 of the provided seed, this will be used to contact the " +
  "rendezvous server.")
public String setHmacSeedReturnCode(String seed) {
  AppInvHTTPD.setHmacKey(seed);
  MessageDigest Sha1;
  try {
    Sha1 = MessageDigest.getInstance("SHA1");
  } catch (Exception e) {
    Log.e(LOG_TAG, "Exception getting SHA1 Instance", e);
    return "";
  }
  Sha1.update(seed.getBytes());
  byte [] result = Sha1.digest();
  StringBuffer sb = new StringBuffer(result.length * 2);
  Formatter formatter = new Formatter(sb);
  for (byte b : result) {
    formatter.format("%02x", b);
  }
  Log.d(LOG_TAG, "Seed = " + seed);
  Log.d(LOG_TAG, "Code = " + sb.toString());
  return sb.toString();
}
 
Example 4
Project: jdk8u-jdk   File: ZipFileAttributes.java   View source code 6 votes vote down vote up
public String toString() {
    StringBuilder sb = new StringBuilder(1024);
    Formatter fm = new Formatter(sb);
    if (creationTime() != null)
        fm.format("    creationTime    : %tc%n", creationTime().toMillis());
    else
        fm.format("    creationTime    : null%n");

    if (lastAccessTime() != null)
        fm.format("    lastAccessTime  : %tc%n", lastAccessTime().toMillis());
    else
        fm.format("    lastAccessTime  : null%n");
    fm.format("    lastModifiedTime: %tc%n", lastModifiedTime().toMillis());
    fm.format("    isRegularFile   : %b%n", isRegularFile());
    fm.format("    isDirectory     : %b%n", isDirectory());
    fm.format("    isSymbolicLink  : %b%n", isSymbolicLink());
    fm.format("    isOther         : %b%n", isOther());
    fm.format("    fileKey         : %s%n", fileKey());
    fm.format("    size            : %d%n", size());
    fm.format("    compressedSize  : %d%n", compressedSize());
    fm.format("    crc             : %x%n", crc());
    fm.format("    method          : %d%n", method());
    fm.close();
    return sb.toString();
}
 
Example 5
Project: an2linuxclient   File: ServerDatabaseHandler.java   View source code 6 votes vote down vote up
private long addCertificate(byte[] certificateBytes){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_CERTIFICATE, certificateBytes);

    Formatter formatter = new Formatter();
    for (byte b : Sha256Helper.sha256(certificateBytes)){
        formatter.format("%02x", b);
    }
    values.put(COLUMN_FINGERPRINT, formatter.toString());

    long rowId = db.insert(TABLE_CERTIFICATES, null, values);

    db.close();
    return rowId;
}
 
Example 6
Project: springboot-shiro-cas-mybatis   File: CasEnvironmentContextListener.java   View source code 6 votes vote down vote up
/**
 * Collect environment info with
 * details on the java and os deployment
 * versions.
 *
 * @return environment info
 */
private String collectEnvironmentInfo() {
    final Properties properties = System.getProperties();
    try (Formatter formatter = new Formatter()) {
        formatter.format("\n******************** Welcome to CAS *******************\n");
        formatter.format("CAS Version: %s\n", CasVersion.getVersion());
        formatter.format("Build Date/Time: %s\n", CasVersion.getDateTime());
        formatter.format("Java Home: %s\n", properties.get("java.home"));
        formatter.format("Java Vendor: %s\n", properties.get("java.vendor"));
        formatter.format("Java Version: %s\n", properties.get("java.version"));
        formatter.format("OS Architecture: %s\n", properties.get("os.arch"));
        formatter.format("OS Name: %s\n", properties.get("os.name"));
        formatter.format("OS Version: %s\n", properties.get("os.version"));
        formatter.format("*******************************************************\n");
        return formatter.toString();
    }
}
 
Example 7
Project: springboot-shiro-cas-mybatis   File: EhCacheStatistics.java   View source code 6 votes vote down vote up
@Override
public void toString(final StringBuilder builder) {
    final String name = this.getName();
    if (StringUtils.isNotBlank(name)) {
        builder.append(name).append(':');
    }
    final int free = getPercentFree();
    final Formatter formatter = new Formatter(builder);
    if (useBytes) {
        formatter.format("%.2f", heapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB heap, ");
        formatter.format("%.2f", diskSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB disk, ");
    } else {
        builder.append(heapSize).append(" items in heap, ");
        builder.append(diskSize).append(" items on disk, ");
    }
    formatter.format("%.2f", offHeapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
    builder.append("MB off-heap, ");
    builder.append(free).append("% free, ");
    builder.append(getEvictions()).append(" evictions");
    formatter.close();
}
 
Example 8
Project: springboot-shiro-cas-mybatis   File: EhCacheStatistics.java   View source code 6 votes vote down vote up
@Override
public void toString(final StringBuilder builder) {
    final String name = this.getName();
    if (StringUtils.isNotBlank(name)) {
        builder.append(name).append(':');
    }
    final int free = getPercentFree();
    final Formatter formatter = new Formatter(builder);
    if (useBytes) {
        formatter.format("%.2f", heapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB heap, ");
        formatter.format("%.2f", diskSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB disk, ");
    } else {
        builder.append(heapSize).append(" items in heap, ");
        builder.append(diskSize).append(" items on disk, ");
    }
    formatter.format("%.2f", offHeapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
    builder.append("MB off-heap, ");
    builder.append(free).append("% free, ");
    builder.append(getEvictions()).append(" evictions");
    formatter.close();
}
 
Example 9
Project: ListVideoPlayer   File: ListVideoUtils.java   View source code 6 votes vote down vote up
public static String stringForTime(int timeMs) {
    if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) {
        return "00:00";
    }
    int totalSeconds = timeMs / 1000;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    StringBuilder stringBuilder = new StringBuilder();
    Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}
 
Example 10
Project: HeadlineNews   File: JCUtils.java   View source code 6 votes vote down vote up
public static String stringForTime(int timeMs) {
    if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) {
        return "00:00";
    }
    int totalSeconds = timeMs / 1000;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    StringBuilder stringBuilder = new StringBuilder();
    Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}
 
Example 11
Project: springboot-shiro-cas-mybatis   File: TicketsResource.java   View source code 6 votes vote down vote up
/**
 * Create new ticket granting ticket.
 *
 * @param requestBody username and password application/x-www-form-urlencoded values
 * @param request raw HttpServletRequest used to call this method
 * @return ResponseEntity representing RESTful response
 */
@RequestMapping(value = "/tickets", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public final ResponseEntity<String> createTicketGrantingTicket(@RequestBody final MultiValueMap<String, String> requestBody,
                                                               final HttpServletRequest request) {
    try (Formatter fmt = new Formatter()) {
        final TicketGrantingTicket tgtId = this.cas.createTicketGrantingTicket(obtainCredential(requestBody));
        final URI ticketReference = new URI(request.getRequestURL().toString() + '/' + tgtId.getId());
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ticketReference);
        headers.setContentType(MediaType.TEXT_HTML);
        fmt.format("<!DOCTYPE HTML PUBLIC \\\"-//IETF//DTD HTML 2.0//EN\\\"><html><head><title>");
        //IETF//DTD HTML 2.0//EN\\\"><html><head><title>");
        fmt.format("%s %s", HttpStatus.CREATED, HttpStatus.CREATED.getReasonPhrase())
                .format("</title></head><body><h1>TGT Created</h1><form action=\"%s", ticketReference.toString())
                .format("\" method=\"POST\">Service:<input type=\"text\" name=\"service\" value=\"\">")
                .format("<br><input type=\"submit\" value=\"Submit\"></form></body></html>");
        return new ResponseEntity<String>(fmt.toString(), headers, HttpStatus.CREATED);
    } catch (final Throwable e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
 
Example 12
Project: FJ-VDMJ   File: CharacterValue.java   View source code 6 votes vote down vote up
@Override
public void formatTo(Formatter formatter, int flags, int width, int precision)
{
	String s = null;

	if ((flags & FormattableFlags.ALTERNATE) > 0)
	{
		s = toString();
	}
	else
	{
		s = "" + unicode;
	}

	formatTo(s, formatter, flags, width, precision);
}
 
Example 13
Project: Pogamut3   File: AgentStats.java   View source code 6 votes vote down vote up
/**
 * Outputs stats headers into the 'output'.
 * 
 * @param output
 */
public void outputHeader(Formatter output) {
	if (output == null) return;
	synchronized(output) {
		output.format("MatchTime;UT2004Time;Health;Armor;Adrenaline;Score;Deaths;Suicides;Killed;WasKilled;NumKillsWithoutDeath;"
				//      1            1.1       2      3      4         5      6       7       8       9        10          
				     +"Team;TeamScore;"
				//      11     12
				     +"ItemsCollect;WeaponsCollect;AmmoCollect;HealthCollect;ArmorCollect;ShieldCollect;AdrenalineCollect;OtherCollect;"				     
                //        13          14              15             16           17             18           19              20
				     +"TimeMoving;TimeShooting;DoubleDamageCount;DoubleDamageTime;TraveledDistance;"
				//         21           22               23              24              25     
				     +"Combo;HasDoubleDamage;IsShooting;Velocity;Location_x;Location_y;Location_z");
			    //      26         27          28          29         30         31      32
		// WEAPON USED
		for (ItemType weapon : ItemType.Category.WEAPON.getTypes()) {
			output.format(";" + fixSemicolon(weapon.getName()).replace(".", "_") + "_TimeUsed");
		}
		// EVENTS
		output.format(";Event;EventParams...\n");
		output.flush();
	}
}
 
Example 14
Project: google-log-aggregation-example   File: TableNameByWindowFnTest.java   View source code 6 votes vote down vote up
@Test
public void testApply() {
  DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
  Instant start = format.parseDateTime("2017-01-01 00:00:00").toInstant();
  Instant end = format.parseDateTime("2017-01-01 00:01:00").toInstant();
  IntervalWindow window = new IntervalWindow(start, end);

  String projectId = "testProject_id";
  String datasetId = "testDatasetId";
  String tablePrefix = "testTablePrefix";
  TableNameByWindowFn fn = new TableNameByWindowFn(projectId, datasetId, tablePrefix);
  String result = fn.apply(window);
  String expected = new Formatter()
      .format("%s:%s.%s_%s", projectId, datasetId, tablePrefix, "20170101")
      .toString();
  assertEquals(expected, result);
}
 
Example 15
Project: cas-5.1.0   File: EhCacheStatistics.java   View source code 6 votes vote down vote up
@Override
public void toString(final StringBuilder builder) {
    final String name = this.getName();
    if (StringUtils.isNotBlank(name)) {
        builder.append(name).append(':');
    }
    final int free = getPercentFree();
    try (Formatter formatter = new Formatter(builder)) {
        if (this.useBytes) {
            formatter.format("%.2f", this.heapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
            builder.append("MB heap, ");
            formatter.format("%.2f", this.diskSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
            builder.append("MB disk, ");
        } else {
            builder.append(this.heapSize).append(" items in heap, ");
            builder.append(this.diskSize).append(" items on disk, ");
        }
        formatter.format("%.2f", this.offHeapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB off-heap, ");
        builder.append(free).append("% free, ");
        builder.append(getEvictions()).append(" evictions");
    }
}
 
Example 16
Project: matrix-toolkits-java   File: AbstractVector.java   View source code 6 votes vote down vote up
@Override
public String toString() {
    // Output into coordinate format. Indices start from 1 instead of 0
    Formatter out = new Formatter();

    out.format("%10d %19d\n", size, Matrices.cardinality(this));

    int i = 0;
    for (VectorEntry e : this) {
        if (e.get() != 0)
            out.format("%10d % .12e\n", e.index() + 1, e.get());
        if (++i == 100) {
            out.format("...\n");
            break;
        }
    }

    return out.toString();
}
 
Example 17
Project: PicShow-zhaipin   File: JCUtils.java   View source code 6 votes vote down vote up
public static String stringForTime(int timeMs) {
    if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) {
        return "00:00";
    }
    int totalSeconds = timeMs / 1000;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    StringBuilder stringBuilder = new StringBuilder();
    Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}
 
Example 18
Project: UDOOBluLib-android   File: Conversion.java   View source code 6 votes vote down vote up
static String BytetohexString(byte[] b, boolean reverse) {
    StringBuilder sb = new StringBuilder(b.length * (2 + 1));
    Formatter formatter = new Formatter(sb);

    if (!reverse) {
        for (int i = 0; i < b.length; i++) {
            if (i < b.length - 1)
                formatter.format("%02X:", b[i]);
            else
                formatter.format("%02X", b[i]);

        }
    } else {
        for (int i = (b.length - 1); i >= 0; i--) {
            if (i > 0)
                formatter.format("%02X:", b[i]);
            else
                formatter.format("%02X", b[i]);

        }
    }
    formatter.close();

    return sb.toString();
}
 
Example 19
Project: openjdk-jdk10   File: Bug8038436.java   View source code 6 votes vote down vote up
private static void securityTests() {
    Policy.setPolicy(new MyPolicy());
    System.setSecurityManager(new SecurityManager());

    /*
     * Test for AccessClassInPackage security exception. Confirms that
     * exeption won't be thrown if an application sets a Permission that
     * does not allow any RuntimePermission, on loading LocaleDataMetaInfo
     * from jdk.localedata module.
     */
    System.out.println(new Formatter(Locale.JAPAN).format("%1$tB %1$te, %1$tY",
                       new GregorianCalendar()));

    /*
     * Check only English/ROOT locales are returned if the jdk.localedata
     * module is not loaded (implied by "--limit-modules java.base").
     */
    List<Locale> nonEnglishLocales= (Arrays.stream(Locale.getAvailableLocales())
            .filter(l -> (l != Locale.ROOT && !(l.getLanguage() == "en" && (l.getCountry() == "US" || l.getCountry() == "" ))))
            .collect(Collectors.toList()));

    if (!nonEnglishLocales.isEmpty()) {
        throw new RuntimeException("non English locale(s)" + nonEnglishLocales + " included in available locales");
    }
}
 
Example 20
Project: imagingbook-common   File: MathematicaIO.java   View source code 6 votes vote down vote up
/**
 * Generates a string holding the named definition
 * of a 2D double array for Mathematica in the form
 * name = {{A[0][0],...,A[0][m-1]},
 * {A[1][0],...,A[1][m-1]}, ...,
 * {A[n-1][0], A[n-1][1], ...,A[n-1][m-1]}};
 * @param name the identifier to be used in Mathematica.
 * @param A the array to be encoded (of length m).
 * @return a String holding the Mathematica definition.
 */
public static String listArray(String name, double[][] A) {
	StringBuilder sb = new StringBuilder();
	Formatter formatter = new Formatter(sb, Locale.US);
	String fs = PrintPrecision.getFormatStringFloat();
	formatter.format(name + " = {");
	for (int i = 0; i < A.length; i++) {
		if (i == 0)
			formatter.format("{");
		else
			formatter.format(", \n{");
		for (int j = 0; j < A[i].length; j++) {
			if (j == 0) 
				formatter.format(fs, A[i][j]);
			else
				formatter.format(", " + fs, A[i][j]);
		}
		formatter.format("}");
	}
	formatter.format("};\n");
	String result = formatter.toString();
	formatter.close();
	return result;
}
 
Example 21
Project: thingplug-sdk-android   File: TDVBuilder.java   View source code 6 votes vote down vote up
/**
 * build TDV string of the sensor control command
 * @param info     sensor info
 * @param value    command value
 * @return TDV command string
 */
public static String buildSensorControlCommand(SensorInfo info, int value) {
    Formatter formatter = new Formatter();
    formatter.format("%02x", info.getType().getValueTDVTypes()[0]);
    switch (info.getType()) {
        case BUZZER:
            formatter.format("%02x", ValueType.UCHAR.getCode());
            formatter.format("%02x", value);
            break;
        case LED:
            formatter.format("%02x", ValueType.CHAR3.getCode());
            formatter.format("%06x", value);
            break;
        default:
            formatter.format("%02x", ValueType.BOOL.getCode());
            formatter.format("%02x", value);
            break;
    }
    String result = formatter.toString();
    formatter.close();
    return result;
}
 
Example 22
Project: neoscada   File: LegacyRedhatHandler.java   View source code 6 votes vote down vote up
private String makeChangeLog ( final List<ChangeEntry> changes )
{
    final ArrayList<ChangeEntry> sortedChanges = new ArrayList<> ( changes );
    Collections.sort ( sortedChanges, new ChangeEntryComparator ( true ) );

    final StringBuilder sb = new StringBuilder ();

    for ( final ChangeEntry entry : sortedChanges )
    {
        final Formatter f = new Formatter ( sb, Locale.ENGLISH );
        f.format ( "* %3$ta %3$tb %3$td %3$tY %1$s <%2$s> %4$s", entry.getAuthor ().getName (), entry.getAuthor ().getEmail (), entry.getDate (), entry.getVersion () );
        f.close ();
        sb.append ( '\n' );
        sb.append ( entry.getDescription () );
        sb.append ( '\n' );
    }

    return sb.toString ();
}
 
Example 23
Project: cas4.0.x-server-wechat   File: EhCacheStatistics.java   View source code 6 votes vote down vote up
@Override
public void toString(final StringBuilder builder) {
    if (getName() != null) {
        builder.append(getName()).append(':');
    }
    final int free = getPercentFree();
    final Formatter formatter = new Formatter(builder);
    if (useBytes) {
        formatter.format("%.2f", heapSize / 1048510.0);
        builder.append("MB heap, ");
        formatter.format("%.2f", diskSize / 1048510.0);
        builder.append("MB disk, ");
    } else {
        builder.append(heapSize).append(" items in heap, ");
        builder.append(diskSize).append(" items on disk, ");
    }
    formatter.format("%.2f", offHeapSize / 1048510.0);
    builder.append("MB off-heap, ");
    builder.append(free).append("% free, ");
    builder.append(getEvictions()).append(" evictions");
    formatter.close();
}
 
Example 24
Project: Encryption   File: Hash.java   View source code 6 votes vote down vote up
/**
 * Converting String to sha512 hash
 */
public String sha512(String message){
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-512");

        byte[] hash = digest.digest(message.getBytes());

        Formatter formatter = new Formatter();

        for (byte b : hash) {
            formatter.format("%02x", b);
        }

        return formatter.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 25
Project: LivroJavaComoProgramar10Edicao   File: TicTacToeServer.java   View source code 6 votes vote down vote up
public Player(Socket socket, int number)
{
   playerNumber = number; // store this player's number
   mark = MARKS[playerNumber]; // specify player's mark
   connection = socket; // store socket for client
   
   try // obtain streams from Socket
   {
      input = new Scanner(connection.getInputStream());
      output = new Formatter(connection.getOutputStream());
   } 
   catch (IOException ioException) 
   {
      ioException.printStackTrace();
      System.exit(1);
   } 
}
 
Example 26
Project: LivroJavaComoProgramar10Edicao   File: TicTacToeClient.java   View source code 6 votes vote down vote up
public void startClient()
{
   try // connect to server and get streams
   {
      // make connection to server
      connection = new Socket(
         InetAddress.getByName(ticTacToeHost), 12345);

      // get streams for input and output
      input = new Scanner(connection.getInputStream());
      output = new Formatter(connection.getOutputStream());
   } 
   catch (IOException ioException)
   {
      ioException.printStackTrace();         
   } 

   // create and start worker thread for this client
   ExecutorService worker = Executors.newFixedThreadPool(1);
   worker.execute(this); // execute client
}
 
Example 27
Project: aliyun-maxcompute-data-collectors   File: OracleCompatTest.java   View source code 6 votes vote down vote up
@Override
protected String getBlobInsertStr(String blobData) {
  // Oracle wants blob data encoded as hex (e.g. '01fca3b5').

  StringBuilder sb = new StringBuilder();
  sb.append("'");

  Formatter fmt = new Formatter(sb);
  try {
    for (byte b : blobData.getBytes("UTF-8")) {
      fmt.format("%02X", b);
    }
  } catch (UnsupportedEncodingException uee) {
    // Should not happen; Java always supports UTF-8.
    fail("Could not get utf-8 bytes for blob string");
    return null;
  }
  sb.append("'");
  return sb.toString();
}
 
Example 28
Project: chromium-for-android-56-debug-video   File: PwsClientImpl.java   View source code 6 votes vote down vote up
/**
 * Given a list of comma-delimited language codes in decreasing order of preference, insert
 * q-values to represent the relative quality/precedence of each language. The logic should
 * match GenerateAcceptLanguageHeader in net/http/http_util.cc.
 * @param languageList A comma-delimited list of language codes containing no whitespace.
 * @return An Accept-Language header with q-values.
 */
@VisibleForTesting
static String generateAcceptLanguageHeader(String languageList) {
    // We use integers for qvalue and qvalue decrement that are 10 times larger than actual
    // values to avoid a problem with comparing two floating point numbers.
    int kQvalueDecrement10 = 2;
    int qvalue10 = 10;
    String[] parts = languageList.split(",");
    Formatter langListWithQ = new Formatter();
    for (String language : parts) {
        if (qvalue10 == 10) {
            // q=1.0 is implicit
            langListWithQ.format("%s", language);
        } else {
            langListWithQ.format(",%s;q=0.%d", language, qvalue10);
        }
        // It does not make sense to have 'q=0'.
        if (qvalue10 > kQvalueDecrement10) {
            qvalue10 -= kQvalueDecrement10;
        }
    }
    return langListWithQ.toString();
}
 
Example 29
Project: openNaEF   File: Notifier.java   View source code 6 votes vote down vote up
/**
 * 設定ファイルを元に NaEF Restful API の DtoChanges 取得 API の URL を生成する
 * <p>
 * http://{naef-addr}:{naef-rest-api-port}/api/{naef-rest-api-version}/dto-changes?version={tx}&time={time}
 *
 * @param tx   ターゲットとなるトランザクション ID
 * @param time ターゲットとなる時間
 * @return NaEF Restful API DtoChanges URL
 */
public static URL getDtoChangesUri(TransactionId.W tx, DateTime time) throws IOException {
    NotifierConfig conf = NotifierConfig.instance();
    String urlStr = new Formatter().format(
            "http://%s:%s/api/%s/dto-changes",
            conf.naefAddr(),
            conf.naefRestApiPort(),
            conf.naefRestApiVersion())
            .toString();

    StringJoiner queries = new StringJoiner("&");
    if (tx != null) {
        queries.add("version=" + tx.toString());
    }
    if (time != null) {
        queries.add("time=" + time.getValue());
    }

    if (queries.length() > 0) {
        urlStr += "?" + queries.toString();
    }

    return new URL(urlStr);
}
 
Example 30
Project: jdk8u-jdk   File: AbstractTCKTest.java   View source code 6 votes vote down vote up
/**
 * Utility method to dump a byte array in a java syntax.
 * @param bytes and array of bytes
 * @return a string containing the bytes formatted in java syntax
 */
protected static String dumpSerialStream(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 5);
    Formatter fmt = new Formatter(sb);
    fmt.format("    byte[] bytes = {" );
    final int linelen = 10;
    for (int i = 0; i < bytes.length; i++) {
        if (i % linelen == 0) {
            fmt.format("%n        ");
        }
        fmt.format(" %3d,", bytes[i] & 0xff);
        if ((i % linelen) == (linelen-1) || i == bytes.length - 1) {
            fmt.format("  /*");
            int s = i / linelen * linelen;
            int k = i % linelen;
            for (int j = 0; j <= k && s + j < bytes.length; j++) {
                fmt.format(" %c", bytes[s + j] & 0xff);
            }
            fmt.format(" */");
        }
    }
    fmt.format("%n    };%n");
    return sb.toString();
}
 
Example 31
Project: businessworks   File: Errors.java   View source code 6 votes vote down vote up
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 32
Project: Reer   File: DefaultServiceRegistry.java   View source code 5 votes vote down vote up
public ServiceProvider getService(LookupContext context, TypeSpec serviceType) {
    if (providers == null) {
        return null;
    }
    List<ServiceProvider> candidates = new ArrayList<ServiceProvider>();
    for (Provider provider : providers) {
        ServiceProvider service = provider.getService(context, serviceType);
        if (service != null) {
            candidates.add(service);
        }
    }

    if (candidates.size() == 0) {
        return null;
    }
    if (candidates.size() == 1) {
        return candidates.get(0);
    }

    Set<String> descriptions = new TreeSet<String>();
    for (ServiceProvider candidate : candidates) {
        descriptions.add(candidate.getDisplayName());
    }

    Formatter formatter = new Formatter();
    formatter.format("Multiple services of type %s available in %s:", format(serviceType.getType()), getDisplayName());
    for (String description : descriptions) {
        formatter.format("%n   - %s", description);
    }
    throw new ServiceLookupException(formatter.toString());
}
 
Example 33
Project: Reer   File: TestFile.java   View source code 5 votes vote down vote up
public TestFile writelns(Iterable<String> lines) {
    Formatter formatter = new Formatter();
    for (String line : lines) {
        formatter.format("%s%n", line);
    }
    return write(formatter);
}
 
Example 34
Project: Reer   File: ModuleVersionResolveException.java   View source code 5 votes vote down vote up
@Override
public String getMessage() {
    if (paths.isEmpty()) {
        return super.getMessage();
    }
    Formatter formatter = new Formatter();
    formatter.format("%s%nRequired by:", super.getMessage());
    for (List<? extends ComponentIdentifier> path : paths) {
        formatter.format("%n    %s", toString(path.get(0)));
        for (int i = 1; i < path.size(); i++) {
            formatter.format(" > %s", toString(path.get(i)));
        }
    }
    return formatter.toString();
}
 
Example 35
Project: Facebook-Video-Downloader   File: VideoControllerView.java   View source code 5 votes vote down vote up
private void initControllerView(View v) {
    mPauseButton = (ImageView) v.findViewById(R.id.pause);
    if (mPauseButton != null) {
        mPauseButton.requestFocus();
        mPauseButton.setOnClickListener(mPauseListener);
    }
    
    mFullscreenButton = (ImageView) v.findViewById(R.id.fullscreen);
    if (mFullscreenButton != null) {
        mFullscreenButton.requestFocus();
        mFullscreenButton.setOnClickListener(mFullscreenListener);
    }

    mFfwdButton = (ImageView) v.findViewById(R.id.ffwd);
    if (mFfwdButton != null) {
        mFfwdButton.setOnClickListener(mFfwdListener);
        if (!mFromXml) {
            mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
        }
    }

    mRewButton = (ImageView) v.findViewById(R.id.rew);
    if (mRewButton != null) {
        mRewButton.setOnClickListener(mRewListener);
        if (!mFromXml) {
            mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
        }
    }

    // By default these are hidden. They will be enabled when setPrevNextListeners() is called 
    mNextButton = (ImageView) v.findViewById(R.id.next);
    if (mNextButton != null && !mFromXml && !mListenersSet) {
        mNextButton.setVisibility(View.GONE);
    }
    mPrevButton = (ImageView) v.findViewById(R.id.prev);
    if (mPrevButton != null && !mFromXml && !mListenersSet) {
        mPrevButton.setVisibility(View.GONE);
    }

    mProgress = (SeekBar) v.findViewById(R.id.mediacontroller_progress);
    if (mProgress != null) {
        if (mProgress instanceof SeekBar) {
            SeekBar seeker = (SeekBar) mProgress;
            seeker.setOnSeekBarChangeListener(mSeekListener);
        }
        mProgress.setMax(1000);
    }

    mEndTime = (TextView) v.findViewById(R.id.time);
    mCurrentTime = (TextView) v.findViewById(R.id.time_current);
    mFormatBuilder = new StringBuilder();
    mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

    installPrevNextListeners();
}
 
Example 36
Project: FJ-VDMJ   File: SeqValue.java   View source code 5 votes vote down vote up
@Override
public void formatTo(Formatter formatter, int flags, int width, int precision)
{
	String s = values.toString();

	if ((flags & FormattableFlags.ALTERNATE) == 0 && s.charAt(0) == '"')
	{
		s = s.substring(1, s.length()-1);
	}

	formatTo(s, formatter, flags, width, precision);
}
 
Example 37
Project: an2linuxclient   File: Sha256Helper.java   View source code 5 votes vote down vote up
public static String getFourLineHexString(byte[] sha256Hash){
    Formatter formatter = new Formatter();
    for (int i = 0; i < 32; i++) {
        formatter.format("%02X", sha256Hash[i]);
        if (i == 7 || i == 15 || i == 23) {
            formatter.format("\n");
        } else if (i != 31) {
            formatter.format(" ");
        }
    }
    return formatter.toString();
}
 
Example 38
Project: an2linuxclient   File: Sha256Helper.java   View source code 5 votes vote down vote up
public static String getFourLineHexString(String hexString){
    Formatter formatter = new Formatter();
    for (int i = 0; i < 64; i+=2) {
        formatter.format(hexString.substring(i, i+2).toUpperCase());
        if (i == 14 || i == 30 || i == 46) {
            formatter.format("\n");
        } else if (i != 62) {
            formatter.format(" ");
        }
    }
    return formatter.toString();
}
 
Example 39
Project: rapidminer   File: Linear.java   View source code 5 votes vote down vote up
static void printf(Formatter formatter, String format, Object... args) throws IOException {
	formatter.format(format, args);
	IOException ioException = formatter.ioException();
	if (ioException != null) {
		throw ioException;
	}
}
 
Example 40
Project: openjdk-jdk10   File: Http2Connection.java   View source code 5 votes vote down vote up
private static String toHexdump1(ByteBuffer bb) {
    bb.mark();
    StringBuilder sb = new StringBuilder(512);
    Formatter f = new Formatter(sb);

    while (bb.hasRemaining()) {
        int i =  Byte.toUnsignedInt(bb.get());
        f.format("%02x:", i);
    }
    sb.deleteCharAt(sb.length()-1);
    bb.reset();
    return sb.toString();
}