Example usage for java.util Formatter toString

List of usage examples for java.util Formatter toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns the result of invoking toString() on the destination for the output.

Usage

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

/**
 * Convert a polynomial to a string. Handles both {@link BasicPolynomial} and
 * {@link ComplexPolynomial}.//from   ww w.jav  a 2s .  c om
 * 
 * @param poly the polynomial
 * @return the string that represents the polynomial
 * @throws ParseException
 */
private static String polyToString(final BasicPolynomial poly) throws ParseException {
    final Formatter formatter = new Formatter();

    boolean first = true;
    for (final Term term : poly.getTerms()) {
        if (!first) {
            formatter.format(" + ");
        } else {
            first = false;
        }

        final double coefficient = term.getCoefficient();

        final Formatter termFormatter = new Formatter();
        termFormatter.format("%f", coefficient);

        for (final GoalRef goalRef : term.getGoals()) {
            final String goal = goalRef.getGoalName();
            final GoalScoreType scoreType = goalRef.getScoreType();
            final String varName;
            switch (scoreType) {
            case RAW:
                varName = getVarNameForRawScore(goal);
                break;
            case COMPUTED:
                varName = getVarNameForComputedScore(goal);
                break;
            default:
                throw new RuntimeException("Expected 'raw' or 'computed', but found: " + scoreType);
            }
            termFormatter.format("* %s", varName);
        }

        for (final VariableRef varRef : term.getVariables()) {
            final String var = varRef.getVariableName();
            final String varName = getComputedGoalLocalVarName(var);
            termFormatter.format("* %s", varName);
        }

        formatter.format("%s", termFormatter.toString());
    }

    final FloatingPointType floatingPoint = poly.getFloatingPoint();
    return applyFloatingPoint(formatter.toString(), floatingPoint);
}

From source file:com.itemanalysis.psychometrics.scaling.ScoreTable.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    String f1 = "%10." + precision + "f";
    String f2 = "%10s";
    //      String f3="%10.4f";

    //table header
    f.format("%28s", "SCORE TABLE");
    f.format("%n");
    f.format("%45s", "=============================================");
    f.format("%n");
    f.format(f2, "Original");
    f.format("%5s", "");
    f.format(f2, "Kelley");
    f.format("%n");

    f.format(f2, "Value");
    f.format("%5s", "");
    f.format(f2, "Score");
    f.format("%n");
    f.format("%45s", "---------------------------------------------");
    f.format("%n");

    for (Double d : table.keySet()) {
        f.format(f1, d);//from   w w  w  . j  av  a2s. com
        f.format("%5s", "");
        f.format(f1, table.get(d));
        f.format("%5s", "");
        f.format("%n");
    }

    f.format("%45s", "=============================================");
    f.format("%n");
    return f.toString();

}

From source file:edu.cmu.tetrad.cli.AbstractAlgorithmCli.java

private String createArgsInfo() {
    Formatter fmt = new Formatter();
    if (dataFile != null) {
        fmt.format("data = %s%n", dataFile.getFileName());
    }/*  ww w  .j a  v  a 2  s  .  c  o  m*/
    if (excludedVariableFile != null) {
        fmt.format("exclude-variables = %s%n", excludedVariableFile.getFileName());
    }
    if (knowledgeFile != null) {
        fmt.format("knowledge = %s%n", knowledgeFile.getFileName());
    }
    fmt.format("delimiter = %s%n", Args.getDelimiterName(delimiter));
    fmt.format("verbose = %s%n", verbose);
    fmt.format("thread = %s%n", numOfThreads);
    printParameterInfos(fmt);

    printValidationInfos(fmt);

    fmt.format("out = %s%n", dirOut.getFileName().toString());
    fmt.format("output-prefix = %s%n", outputPrefix);
    fmt.format("no-validation-output = %s%n", !validationOutput);

    return fmt.toString();
}

From source file:com.itemanalysis.psychometrics.factoranalysis.RotationResults.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    int nrow = L.getRowDimension();
    int ncol = L.getColumnDimension();
    f.format("%-40s", "Factor Loadings: " + rotationMethod.toString());
    f.format("%n");
    f.format("%40s", "========================================");
    f.format("%n");
    for (int i = 0; i < nrow; i++) {
        for (int j = 0; j < ncol; j++) {
            f.format("% 6.4f", L.getEntry(i, j));
            f.format("%4s", "");
        }/*from  ww w. j a  va2s .  c om*/
        f.format("%n");
    }
    f.format("%n");
    f.format("%n");

    f.format("%-30s", "Factor Correlations");
    f.format("%n");
    f.format("%30s", "==============================");
    f.format("%n");
    for (int i = 0; i < Phi.getRowDimension(); i++) {
        for (int j = 0; j < Phi.getColumnDimension(); j++) {
            f.format("% 6.4f", Phi.getEntry(i, j));
            f.format("%4s", "");
        }
        f.format("%n");
    }
    f.format("%n");

    return f.toString();
}

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 w w w  .  j  a v  a  2 s . c  o m
 * @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.jasig.cas.support.rest.TicketsResource.java

/**
 * Create new ticket granting ticket./*  w  w w  . j  ava  2 s.  c  o  m*/
 *
 * @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) {

    Formatter fmt = null;
    try {
        final String tgtId = this.cas.createTicketGrantingTicket(obtainCredential(requestBody));
        final URI ticketReference = new URI(request.getRequestURL().toString() + "/" + tgtId);
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ticketReference);
        headers.setContentType(MediaType.TEXT_HTML);

        fmt = new Formatter();
        fmt.format("<!DOCTYPE HTML PUBLIC \\\"-//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);
    } finally {
        IOUtils.closeQuietly(fmt);
    }
}

From source file:com.itemanalysis.psychometrics.cmh.CochranMantelHaenszel.java

/**
 * From 1999 South Carolina PACT Technical Documentation
 *
 *
 * @return//w  ww. j  a va 2 s. co  m
 */
//    public String etsPolytomousClassification(double cochranMantelHaenszel, double pvalue, double polytomousEffectSize){
//        String difClass = "BB";
//        if(pvalue > 0.05){
//            difClass = "AA ";
//        }else if(Math.abs(polytomousEffectSize)<=0.17){
//            difClass = "AA ";
//        }else if(0.17<Math.abs(polytomousEffectSize) && Math.abs(polytomousEffectSize)<=0.25){
//            difClass = "BB";
//            if(polytomousEffectSize>=0) difClass += "+"; else difClass += "-";
//        }else if(Math.abs(polytomousEffectSize)>0.25){
//            difClass = "CC";
//            if(polytomousEffectSize>=0) difClass += "+"; else difClass += "-";
//        }
//        return difClass;
//    }

public String printTables() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    Set<Double> keys = strata.keySet();
    Iterator<Double> iter = keys.iterator();
    CmhTable table = null;
    Double score = null;

    while (iter.hasNext()) {
        score = iter.next();
        table = strata.get(score);
        f.format("%n");
        f.format("%n");
        f.format("%n");
        f.format("%45s", "Score Level: ");
        f.format("%-10.4f", +score);
        f.format("%n");
        f.format("%100s", table.toString());
        f.format("%n");
    }
    return f.toString();
}

From source file:com.itemanalysis.psychometrics.cmh.CmhTable.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    double score = 0.0;

    Iterator<Comparable<?>> iter = columnMargin.valuesIterator();
    f.format("%26s", " ");
    while (iter.hasNext()) {
        score = ((Double) iter.next()).doubleValue();
        f.format("%10.0f", score);
        f.format("%5s", " ");
    }/*from w  w w.j  a va2 s.c  om*/
    f.format("%n");
    f.format("%51s", "-------------------------");

    iter = columnMargin.valuesIterator();
    int index = 0;
    while (iter.hasNext()) {
        score = ((Double) iter.next()).doubleValue();
        if (index > 1)
            f.format("%15s", "---------------");
        index++;
    }
    f.format("%n");

    f.format("%11s", "Reference: ");
    f.format("%-100s", referenceRow.toString());
    f.format("%n");
    f.format("%11s", "Focal:     ");
    f.format("%-100s", focalRow.toString());
    f.format("%n");

    return f.toString();
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

/**
 * @param hash//from  w  ww.  j av  a  2 s  .  c  o  m
 * @return
 */
private String byteArray2Hex(byte[] hash) {
    Formatter formatter = new Formatter();
    for (byte b : hash) {
        formatter.format("%02x", b);
    }
    String s = formatter.toString();
    formatter.close();
    return s;
}

From source file:org.openecomp.sdc.common.config.EcompErrorLogUtil.java

public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum,
        boolean logMissingParams, String... ecompDescriptionParams) {
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb, Locale.US);
    try {/*from  w w  w  . j  a  v a 2 s .c  o  m*/
        String description = ecompErrorEnum.getEcompErrorCode().getDescription();

        Either<String, Boolean> setDescriptionParamsResult = setDescriptionParams(ecompErrorEnum,
                ecompDescriptionParams);
        if (setDescriptionParamsResult.isLeft()) {
            description = setDescriptionParamsResult.left().value();
        } else {
            EcompErrorEnum mismatchErrorEnum = EcompErrorEnum.EcompMismatchParam;
            if (logMissingParams == true) {
                logEcompError("logEcompError", mismatchErrorEnum, false, ecompErrorEnum.name().toString());
                return;
            } else {
                log.info("Failed to log the error code " + mismatchErrorEnum);
                return;
            }
        }
        EcompClassification classification = ecompErrorEnum.getClassification();

        EcompErrorConfiguration.EcompErrorSeverity severity = EcompErrorSeverity.ERROR;
        // Since there is no FATAL log level, this is how we distinguish the
        // FATAL errors
        if (classification == EcompClassification.FATAL) {
            description = FATAL_ERROR_PREFIX + description;
            severity = EcompErrorSeverity.FATAL;
        } else if (classification == EcompClassification.WARNING) {
            severity = EcompErrorSeverity.WARN;
        } else if (classification == EcompClassification.INFORMATION) {
            severity = EcompErrorSeverity.INFO;
        }

        String eCode = createEcode(ecompErrorEnum);

        MDC.put("alarmSeverity", ecompErrorEnum.alarmSeverity.name());
        // else it stays ERROR
        formatter.format(ECOMP_ERROR_TMPL, ecompErrorEnum.geteType(), ecompErrorEnum.name(), eCode,
                ecompErrorContext, description);
        switch (severity) {
        case INFO:
            log.info(formatter.toString());
            break;
        case WARN:
            log.warn(formatter.toString());
            break;
        case ERROR:
            log.error(formatter.toString());
            break;
        case FATAL:
            // same as ERROR for now, might be additional logic later..
            log.error(formatter.toString());
            break;
        default:
            break;
        }
    } finally {
        formatter.close();
        MDC.remove("alarmSeverity");
    }
}