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:org.opengeoportal.proxy.controllers.DynamicOgcController.java

/**
* <p>Encodes characters in the query or fragment part of the URI.
*
* <p>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
*//*from  www .  j  a  v a2 s .c  om*/
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
            formatter.close();
        }
    }
    return outBuf != null ? outBuf : in;
}

From source file:org.odk.collect.android.utilities.EnhancedDigestScheme.java

/**
 * Creates digest-response header as defined in RFC2617.
 * //  ww  w  .j  a v a2 s. com
 * @param credentials
 *            User credentials
 * 
 * @return The digest-response as String.
 */
private Header createDigestHeader(final Credentials credentials) throws AuthenticationException {
    String uri = getParameter("uri");
    String realm = getParameter("realm");
    String nonce = getParameter("nonce");
    String opaque = getParameter("opaque");
    String method = getParameter("methodname");
    String algorithm = getParameter("algorithm");
    if (uri == null) {
        throw new IllegalStateException("URI may not be null");
    }
    if (realm == null) {
        throw new IllegalStateException("Realm may not be null");
    }
    if (nonce == null) {
        throw new IllegalStateException("Nonce may not be null");
    }

    // TODO: add support for QOP_INT
    int qop = QOP_UNKNOWN;
    String qoplist = getParameter("qop");
    if (qoplist != null) {
        StringTokenizer tok = new StringTokenizer(qoplist, ",");
        while (tok.hasMoreTokens()) {
            String variant = tok.nextToken().trim();
            if (variant.equals("auth")) {
                qop = QOP_AUTH;
                break;
            }
        }
    } else {
        qop = QOP_MISSING;
    }

    if (qop == QOP_UNKNOWN) {
        throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
    }

    // If an algorithm is not specified, default to MD5.
    if (algorithm == null) {
        algorithm = "MD5";
    }
    // If an charset is not specified, default to ISO-8859-1.
    String charset = getParameter("charset");
    if (charset == null) {
        charset = "ISO-8859-1";
    }

    String digAlg = algorithm;
    if (digAlg.equalsIgnoreCase("MD5-sess")) {
        digAlg = "MD5";
    }

    MessageDigest digester;
    try {
        digester = createMessageDigest(digAlg);
    } catch (UnsupportedDigestAlgorithmException ex) {
        throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg);
    }

    String uname = credentials.getUserPrincipal().getName();
    String pwd = credentials.getPassword();

    if (nonce.equals(this.lastNonce)) {
        nounceCount++;
    } else {
        nounceCount = 1;
        cnonce = null;
        lastNonce = nonce;
    }
    StringBuilder sb = new StringBuilder(256);
    Formatter formatter = new Formatter(sb, Locale.US);
    formatter.format("%08x", nounceCount);
    String nc = sb.toString();

    if (cnonce == null) {
        cnonce = createCnonce();
    }

    a1 = null;
    a2 = null;
    // 3.2.2.2: Calculating digest
    if (algorithm.equalsIgnoreCase("MD5-sess")) {
        // H( unq(username-value) ":" unq(realm-value) ":" passwd )
        // ":" unq(nonce-value)
        // ":" unq(cnonce-value)

        // calculated one per session
        sb.setLength(0);
        sb.append(uname).append(':').append(realm).append(':').append(pwd);
        String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset)));
        sb.setLength(0);
        sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
        a1 = sb.toString();
    } else {
        // unq(username-value) ":" unq(realm-value) ":" passwd
        sb.setLength(0);
        sb.append(uname).append(':').append(realm).append(':').append(pwd);
        a1 = sb.toString();
    }

    String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));

    if (qop == QOP_AUTH) {
        // Method ":" digest-uri-value
        a2 = method + ':' + uri;
    } else if (qop == QOP_AUTH_INT) {
        // Method ":" digest-uri-value ":" H(entity-body)
        // TODO: calculate entity hash if entity is repeatable
        throw new AuthenticationException("qop-int method is not suppported");
    } else {
        a2 = method + ':' + uri;
    }

    String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset)));

    // 3.2.2.1

    String digestValue;
    if (qop == QOP_MISSING) {
        sb.setLength(0);
        sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);
        digestValue = sb.toString();
    } else {
        sb.setLength(0);
        sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':').append(cnonce)
                .append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth").append(':').append(hasha2);
        digestValue = sb.toString();
    }

    String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue)));

    CharArrayBuffer buffer = new CharArrayBuffer(128);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Digest ");

    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
    params.add(new BasicNameValuePair("username", uname));
    params.add(new BasicNameValuePair("realm", realm));
    params.add(new BasicNameValuePair("nonce", nonce));
    params.add(new BasicNameValuePair("uri", uri));
    params.add(new BasicNameValuePair("response", digest));

    if (qop != QOP_MISSING) {
        params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth"));
        params.add(new BasicNameValuePair("nc", nc));
        params.add(new BasicNameValuePair("cnonce", cnonce));
    }
    if (algorithm != null) {
        params.add(new BasicNameValuePair("algorithm", algorithm));
    }
    if (opaque != null) {
        params.add(new BasicNameValuePair("opaque", opaque));
    }

    for (int i = 0; i < params.size(); i++) {
        BasicNameValuePair param = params.get(i);
        if (i > 0) {
            buffer.append(", ");
        }
        boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName());
        BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes);
    }
    return new BufferedHeader(buffer);
}

From source file:com.github.jengelman.gradle.plugins.integration.TestFile.java

public TestFile writelns(Iterable<String> lines) {
    Formatter formatter = new Formatter();
    for (String line : lines) {
        formatter.format("%s%n", line);
    }//w  ww.  ja v  a  2 s  .c  o  m
    return write(formatter);
}

From source file:gemlite.core.internal.db.AsyncEventHelper.java

/**
 * Log the given formatted message and exception to the provided logger. The
 * format expected is the same as supported by
 * {@link String#format(String, Object...)}.
 * /*from   w w  w  . j  a v a 2s .c  om*/
 * @param logger
 *          the {@link Logger} to log the message to
 * @param level
 *          the {@link Level} to use for logging the message
 * @param t
 *          the exception whose backtrace is to be logged; can be null in
 *          which case it is ignored
 * @param format
 *          the message format
 * @param params
 *          the parameters to the message format
 * 
 * @see String#format(String, Object...)
 * @see Formatter#format(String, Object...)
 */
public final void logFormat(Logger logger, Level level, Throwable t, String format, Object... params) {
    StringBuilder sb = new StringBuilder();
    Formatter fmt = new Formatter(sb);
    fmt.format(format, params);
    if (t != null) {
        sb.append(": ");
        getStackTrace(t, sb);
    }
    if (Level.SEVERE.equals(level.toString()))
        logger.error(sb.toString());
    else
        logger.info(sb.toString());
    fmt.close();
}

From source file:fll.web.scoreEntry.ScoreEntry.java

/**
 * Output the body for the check_restrictions method.
 * //from   ww  w.  j ava  2 s  .c  om
 * @param writer where to write
 * @throws IOException
 * @throws ParseException
 */
public static void generateCheckRestrictionsBody(final Writer writer, final ServletContext application)
        throws IOException, ParseException {
    final ChallengeDescription description = ApplicationAttributes.getChallengeDescription(application);
    final Formatter formatter = new Formatter(writer);

    final PerformanceScoreCategory performanceElement = description.getPerformance();

    final Collection<String> goalsWithRestrictions = new LinkedList<String>();
    final List<Restriction> restrictions = performanceElement.getRestrictions();

    // find out which goals are involved in restrictions
    for (final Restriction restrictEle : restrictions) {
        goalsWithRestrictions.addAll(getGoalsInRestriction(restrictEle));
    }

    // output variable declaration for each goal
    for (final String goalName : goalsWithRestrictions) {
        formatter.format("  var %s = \"\";%n", getElementIDForError(goalName));
    }

    // output actual check of restriction
    for (int restrictIdx = 0; restrictIdx < restrictions.size(); ++restrictIdx) {
        final Restriction restrictEle = restrictions.get(restrictIdx);
        final double lowerBound = restrictEle.getLowerBound();
        final double upperBound = restrictEle.getUpperBound();
        final String message = restrictEle.getMessage();

        final String polyString = polyToString(restrictEle);
        final String restrictValStr = String.format("restriction_%d_value", restrictIdx);
        formatter.format("  var %s = %s;%n", restrictValStr, polyString);
        formatter.format("  if(%s > %f || %s < %f) {%n", restrictValStr, upperBound, restrictValStr,
                lowerBound);
        // append error text to each error cell if the restriction is violated
        for (final String goalName : getGoalsInRestriction(restrictEle)) {
            final String errorId = getElementIDForError(goalName);
            formatter.format("    %s = %s + \" \" + \"%s\";%n", errorId, errorId, message);
        }
        formatter.format("    error_found = true;%n");
        formatter.format("  }%n");
    }

    // output text assignment for each goal involved in a restriction
    for (final String goalName : goalsWithRestrictions) {
        final String errorId = getElementIDForError(goalName);
        formatter.format("  replaceText(\"%s\", %s);%n", errorId, errorId);
        formatter.format("  if(%s.length > 0) {%n", errorId);
        formatter.format("    var el = document.getElementById(\"%s\");%n", errorId);
        formatter.format("  }%n");
        formatter.format("  replaceText(\"%s\", %s);%n", errorId, errorId);
        formatter.format("%n");
    }
}

From source file:org.jasig.cas.adaptors.ldap.LdapPasswordPolicyEnforcer.java

/**
 * Calculates the number of days left to the expiration date based on the
 * {@code expireDate} parameter.//from   www. j av a2  s.  c om
 * @param expireDate password expiration date
 * @param userId the authenticating user id
 * @return number of days left to the expiration date, or {@value #PASSWORD_STATUS_PASS}
 * @throws LdapPasswordPolicyEnforcementException if authentication fails as the result of a date mismatch
 */
private long getDaysToExpirationDate(final String userId, final DateTime expireDate)
        throws LdapPasswordPolicyEnforcementException {

    logger.debug("Calculating number of days left to the expiration date for user {}", userId);

    final DateTime currentTime = new DateTime(DEFAULT_TIME_ZONE);

    logger.info("Current date is {}, expiration date is {}", currentTime.toString(), expireDate.toString());

    final Days d = Days.daysBetween(currentTime, expireDate);
    int daysToExpirationDate = d.getDays();

    if (expireDate.equals(currentTime) || expireDate.isBefore(currentTime)) {
        final Formatter fmt = new Formatter();

        fmt.format("Authentication failed because account password has expired with %s ", daysToExpirationDate)
                .format("to expiration date. Verify the value of the %s attribute ", this.dateAttribute)
                .format("and ensure it's not before the current date, which is %s", currentTime.toString());

        final LdapPasswordPolicyEnforcementException exc = new LdapPasswordPolicyEnforcementException(
                fmt.toString());

        logger.error(fmt.toString(), exc);
        IOUtils.closeQuietly(fmt);
        throw exc;
    }

    /*
     * Warning period begins from X number of ways before the expiration date
     */
    DateTime warnPeriod = new DateTime(DateTime.parse(expireDate.toString()), DEFAULT_TIME_ZONE);

    warnPeriod = warnPeriod.minusDays(this.warningDays);
    logger.info("Warning period begins on {}", warnPeriod.toString());

    if (this.warnAll) {
        logger.info("Warning all. The password for {} will expire in {} days.", userId, daysToExpirationDate);
    } else if (currentTime.equals(warnPeriod) || currentTime.isAfter(warnPeriod)) {
        logger.info("Password will expire in {} days.", daysToExpirationDate);
    } else {
        logger.info("Password is not expiring. {} days left to the warning", daysToExpirationDate);
        daysToExpirationDate = PASSWORD_STATUS_PASS;
    }

    return daysToExpirationDate;
}

From source file:org.kalypso.kalypsomodel1d2d.sim.SwanResultProcessor.java

private void processSWANTabFile(final FileObject swanResOutTabFile, final FileObject swanResShiftFile) {
    final GM_Position lShiftPosition = SWANDataConverterHelper.readCoordinateShiftValues(swanResShiftFile);
    if (lShiftPosition == null)
        return;// ww  w  .  j  av  a 2 s  . c o m

    try {
        // FIXME: why?! should never happen...!
        if (swanResOutTabFile.isContentOpen())
            swanResOutTabFile.close();

        final FileObject swanResOutTabFileBackUp = swanResOutTabFile.getParent()
                .resolveFile(swanResOutTabFile.getName().getBaseName() + ".bck"); //$NON-NLS-1$
        swanResOutTabFile.moveTo(swanResOutTabFileBackUp);

        final OutputStream lOutStream = swanResOutTabFile.getContent().getOutputStream();
        final Formatter lFormatter = new Formatter(lOutStream, Charset.defaultCharset().name(), Locale.US);

        final BufferedReader lInDataStream = new BufferedReader(
                new InputStreamReader(swanResOutTabFileBackUp.getContent().getInputStream()));

        while (lInDataStream.ready()) {
            final String lStrTmpLine = lInDataStream.readLine().trim();
            if (lStrTmpLine.startsWith("%")) //$NON-NLS-1$
            {
                lFormatter.format("%s\n", lStrTmpLine); //$NON-NLS-1$
                continue;
            }

            final StringTokenizer lStrTokenizer = new StringTokenizer(lStrTmpLine, " "); //$NON-NLS-1$
            int lIntTokenCounter = 0;
            String lStrNewLine = ""; //$NON-NLS-1$
            while (lStrTokenizer.hasMoreTokens()) {
                final String lStrToken = lStrTokenizer.nextToken();
                if (lIntTokenCounter == 1) {
                    lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$
                            NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getX());
                } else if (lIntTokenCounter == 2) {
                    lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$
                            NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getY());
                } else {
                    lStrNewLine += lStrToken + "\t"; //$NON-NLS-1$
                }
                lIntTokenCounter++;
            }
            lFormatter.format("%s\n", lStrNewLine); //$NON-NLS-1$
        }

        // FIXME: not closed in a save way!
        lFormatter.close();
        lInDataStream.close();
        lOutStream.close();
    } catch (final Exception e) {
        // FIXME: this is no way to handle an error !
    }
}

From source file:com.zimbra.cs.mailclient.imap.ImapConnection.java

public String newTag() {
    Formatter fmt = new Formatter();
    fmt.format(TAG_FORMAT, tagCount.incrementAndGet());
    return fmt.toString();
}

From source file:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverterTelemac.java

/**
 * Writes the Control Data Block of the Telemac-Kalypso control file (INPUT)
 *///from  www  . j  a  v a2s.com

public void writeInputControlFile(final Formatter formatter) throws IOException {
    formatter.format("PARALLEL PROCESSORS : %d%n", 1); //TODO: forward settings about processors from the UI
    //    initTimeStrings();

    //    formateCoordinatesShift();

    formateControlHeader(formatter);

    //    formateMesh( formatter );

    //    formateBottomData( formatter );

    //    formateWaterLevelData( formatter );

    //    formateWindData( formatter );

    //    formateCurrentsData( formatter );

    //    formateInitialBoundaries( formatter );

    //    formateInitLine( formatter );

    formateSimulationOperationsSpec(formatter);

    formateSimulationOutputSpec(formatter);

    FormatterUtils.checkIoException(formatter);

    formatter.format("&ETA           ");
}

From source file:org.nuxeo.lang.ext.LangExtAssistantRoot.java

public String escapeUnicode(String input) {
    StringBuilder b = new StringBuilder(input.length());
    Formatter f = new Formatter(b);
    for (char c : input.toCharArray()) {
        if (c < 128) {
            b.append(c);//from   ww w  .j  a  v  a 2  s.c o m
        } else {
            f.format("\\u%04x", (int) c);
        }
    }
    return b.toString();
}