Example usage for java.util Formatter format

List of usage examples for java.util Formatter format

Introduction

In this page you can find the example usage for java.util Formatter format.

Prototype

public Formatter format(String format, Object... args) 

Source Link

Document

Writes a formatted string to this object's destination using the specified format string and arguments.

Usage

From source file:models.Attachment.java

/**
 * Moves a file to the Upload Directory.
 *
 * This method is used to move a file stored in temporary directory by
 * PlayFramework to the Upload Directory managed by Yobi.
 *
 * @param file/* w w w. jav a2  s.  c  o m*/
 * @return SHA1 hash of the file
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
private static String moveFileIntoUploadDirectory(File file) throws NoSuchAlgorithmException, IOException {
    // Compute sha1 checksum.
    MessageDigest algorithm = MessageDigest.getInstance("SHA1");
    byte buf[] = new byte[10240];
    FileInputStream fis = new FileInputStream(file);
    for (int size = 0; size >= 0; size = fis.read(buf)) {
        algorithm.update(buf, 0, size);
    }
    Formatter formatter = new Formatter();
    for (byte b : algorithm.digest()) {
        formatter.format("%02x", b);
    }
    String hash = formatter.toString();
    formatter.close();
    fis.close();

    // Store the file.
    // Before do that, create upload directory if it doesn't exist.
    File uploads = new File(uploadDirectory);
    uploads.mkdirs();
    if (!uploads.isDirectory()) {
        throw new NotDirectoryException("'" + file.getAbsolutePath() + "' is not a directory.");
    }
    File attachedFile = new File(uploadDirectory, hash);
    boolean isMoved = file.renameTo(attachedFile);

    if (!isMoved) {
        FileUtils.copyFile(file, attachedFile);
        file.delete();
    }

    // Close all resources.

    return hash;
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected static String convertToHex(byte[] in) {
    StringBuilder builder = new StringBuilder(in.length * 2);

    Formatter formatter = new Formatter(builder);
    for (byte inByte : in)
        formatter.format("%02x", inByte);

    return builder.toString();
}

From source file:net.ftb.util.DownloadUtils.java

public static String fileHash(File file, String type) throws IOException {
    if (!file.exists()) {
        return "";
    }/*from  ww w  .java  2 s.  c om*/
    if (type.equalsIgnoreCase("md5"))
        return fileMD5(file);
    if (type.equalsIgnoreCase("sha1"))
        return fileSHA(file);
    URL fileUrl = file.toURI().toURL();
    MessageDigest dgest = null;
    try {
        dgest = MessageDigest.getInstance(type);
    } catch (NoSuchAlgorithmException e) {
    }
    InputStream str = fileUrl.openStream();
    byte[] buffer = new byte[65536];
    int readLen;
    while ((readLen = str.read(buffer, 0, buffer.length)) != -1) {
        dgest.update(buffer, 0, readLen);
    }
    str.close();
    Formatter fmt = new Formatter();
    for (byte b : dgest.digest()) {
        fmt.format("%02X", b);
    }
    String result = fmt.toString();
    fmt.close();
    return result;
}

From source file:fi.mikuz.boarder.util.FileProcessor.java

private static String byteArray2Hex(byte[] hash) {
    Formatter formatter = new Formatter();
    for (byte b : hash) {
        formatter.format("%02x", b);
    }/*from  w  w w. ja  v a2s  . c  om*/
    return formatter.toString();
}

From source file:com.hazelcast.stabilizer.Utils.java

public static String formatLong(long number, int length) {
    StringBuffer sb = new StringBuffer();
    Formatter f = new Formatter(sb);
    f.format("%,d", number);

    return padLeft(sb.toString(), length);
}

From source file:com.hazelcast.stabilizer.Utils.java

/**
 * Formats a number and adds padding to the left.
 * It is very inefficient; but a lot easier to deal with the formatting API.
 *
 * @param number    number to format/*ww  w  .ja  va2 s  .  com*/
 * @param length    width of padding
 * @return formatted number
 */
public static String formatDouble(double number, int length) {
    StringBuffer sb = new StringBuffer();
    Formatter f = new Formatter(sb);
    f.format("%,.2f", number);

    return padLeft(sb.toString(), length);
}

From source file:com.ideateam.plugin.Version.java

public static String getSHA1FromFileContent(String filename) throws NoSuchAlgorithmException, IOException {

    final MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");

    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    final byte[] buffer = new byte[1024];

    for (int read = 0; (read = is.read(buffer)) != -1;) {
        messageDigest.update(buffer, 0, read);
    }/*from w w w. j  a va  2  s . c  o m*/

    is.close();

    // Convert the byte to hex format
    Formatter formatter = new Formatter();

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

    String res = formatter.toString();

    formatter.close();

    return res;
}

From source file:com.jungle.base.utils.MiscUtils.java

public static String formatTime(long timeMs) {
    if (timeMs <= 0) {
        return "00:00";
    }//from  w  w w .j  ava2 s  .  c  o m

    long totalSeconds = timeMs / 1000;
    long seconds = totalSeconds % 60;
    long minutes = totalSeconds / 60 % 60;
    long hours = totalSeconds / 3600;

    Formatter formatter = new Formatter();
    return hours > 0 ? formatter.format("%d:%02d:%02d", new Object[] { hours, minutes, seconds }).toString()
            : formatter.format("%02d:%02d", new Object[] { minutes, seconds }).toString();
}

From source file:io.mapzone.controller.vm.http.HttpForwarder.java

/**
 * Encodes characters in the query or fragment part of the URI.
 *
 * <p>/*  www. java  2 s .  c  om*/
 * Unfortunately, an incoming URI sometimes has characters disallowed by the
 * spec. HttpClient insists that the outgoing proxied request has a valid URI
 * because it uses Java's {@link URI}. To be more forgiving, we must escape the
 * problematic characters. See the URI class for the spec.
 *
 * @param in example: name=value&foo=bar#fragment
 */
protected static CharSequence encodeUriQuery(CharSequence in) {
    // Note that I can't simply use URI.java to encode because it will escape
    // pre-existing escaped things.
    StringBuilder outBuf = null;
    Formatter formatter = null;
    for (int i = 0; i < in.length(); i++) {
        char c = in.charAt(i);
        boolean escape = true;
        if (c < 128) {
            if (asciiQueryChars.get((int) c)) {
                escape = false;
            }
        } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {// not-ascii
            escape = false;
        }
        if (!escape) {
            if (outBuf != null)
                outBuf.append(c);
        } else {
            // escape
            if (outBuf == null) {
                outBuf = new StringBuilder(in.length() + 5 * 3);
                outBuf.append(in, 0, i);
                formatter = new Formatter(outBuf);
            }
            // leading %, 0 padded, width 2, capital hex
            formatter.format("%%%02X", (int) c);// TODO
        }
    }
    return outBuf != null ? outBuf : in;
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

/**
 * Calculates the hash of the certificate known as the "thumbprint"
 * and returns it as a string representation.
 *
 * @param cert The certificate to hash.//from  w w w. j a  v a  2s  .c o  m
 * @param algorithm The hash algorithm to use.
 * @return The SHA-1 hash of the certificate.
 * @throws CertificateException
 */
private static String getThumbprint(Certificate cert, String algorithm) throws CertificateException {
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException(e);
    }
    byte[] encodedCert = cert.getEncoded();
    StringBuilder sb = new StringBuilder(encodedCert.length * 2);
    Formatter f = new Formatter(sb);
    try {
        for (byte b : digest.digest(encodedCert))
            f.format("%02x", b);
    } finally {
        f.close();
    }
    return sb.toString();
}