Example usage for org.apache.commons.lang StringUtils rightPad

List of usage examples for org.apache.commons.lang StringUtils rightPad

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils rightPad.

Prototype

public static String rightPad(String str, int size) 

Source Link

Document

Right pad a String with spaces (' ').

Usage

From source file:edu.cornell.kfs.fp.batch.service.impl.AdvanceDepositServiceImpl.java

private String getEmailMessageText(AchIncomeFile achIncomeFile, String payerMessage) {
    StringBuilder message = new StringBuilder();

    int totalPostedTransation = achTotalPostedTransactions + wiredTotalPostedTransactions;
    KualiDecimal totalPostedTransactionAmount = achTotalPostedTransactionAmount
            .add(wiredTotalPostedTransactionAmount);

    String fileDateTime;//from w  w  w.  j a  v  a  2 s  .c  o m
    try {
        fileDateTime = getFormattedTimestamp(achIncomeFile, "fileDate/Time").toString();
    } catch (FormatException e) {
        // use the original file Date/Time string if encountered invalid format
        fileDateTime = achIncomeFile.getFileDate() + " " + achIncomeFile.getFileTime();
    }

    message.append("File Date: " + fileDateTime);
    message.append("\n");
    message.append("                    ");
    message.append("COUNT               ");
    message.append("        AMOUNT     ");
    message.append("\n");
    message.append(StringUtils.rightPad("ACH Posted", 20));
    message.append(StringUtils.rightPad(achTotalPostedTransactions + "", 20));
    message.append(
            StringUtils.leftPad(getFormattedAmount("##,##,##0.00", achTotalPostedTransactionAmount), 20));
    message.append("\n");
    message.append(StringUtils.rightPad("Wire Posted", 20));
    message.append(StringUtils.rightPad(wiredTotalPostedTransactions + "", 20));
    message.append(
            StringUtils.leftPad(getFormattedAmount("##,##,##0.00", wiredTotalPostedTransactionAmount), 20));
    message.append("\n");
    message.append(StringUtils.rightPad("Total Posted", 20));
    message.append(StringUtils.rightPad(totalPostedTransation + "", 20));
    message.append(StringUtils.leftPad(getFormattedAmount("##,##,##0.00", totalPostedTransactionAmount), 20));
    message.append("\n");
    message.append("\n");
    message.append(StringUtils.rightPad("ACH Skipped", 20));
    message.append(StringUtils.rightPad(achTotalSkippedTransactions + "", 20));
    message.append(
            StringUtils.leftPad(getFormattedAmount("##,##,##0.00", achTotalSkippedTransactionAmount), 20));
    message.append("\n");
    message.append(StringUtils.rightPad("Wire Skipped", 20));
    message.append(StringUtils.rightPad(wiredTotalSkippedTransactions + "", 20));
    message.append(
            StringUtils.leftPad(getFormattedAmount("##,##,##0.00", wiredTotalSkippedTransactionAmount), 20));
    message.append("\n");
    if (StringUtils.isNotBlank(payerMessage)) {
        message.append("\n");
        message.append("Transactions Missing Payer Name: ");
        message.append("\n");
        message.append(payerMessage);
    }
    return message.toString();
}

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Creates the General Ledger file given the database data.
 * <p/>/* www  . j  a va 2  s.c  om*/
 * This method does not throw any exception.
 *
 * @param glFileDirectory The directory to create GL file.
 * @param procMessage The process message. Used to build the mail message.
 * @param now The current date.
 * @return true if execution is successful; false otherwise.
 */
private boolean makeGLFile(File glFileDirectory, StringBuilder procMessage, Date now) {
    if (!glFileDirectory.exists() || !glFileDirectory.isDirectory() || !glFileDirectory.canRead()
            || !glFileDirectory.canWrite()) {
        logger.warn("Can not make GL file in directory:" + glFileDirectory);
        procMessage.append(CRLF).append(CRLF).append("Can not make GL file in directory:" + glFileDirectory)
                .append(CRLF);
        return false;
    }

    File outputGLFile = new File(glFileDirectory, "SCGL" + new SimpleDateFormat("yyMMdd").format(now) + ".txt");

    PrintWriter output = null;

    try {
        startTransaction();

        StoredProcedureQuery sp = entityManager.createNamedStoredProcedureQuery("BatchDailyGLFile");
        sp.setParameter("pDayToProcess", now, TemporalType.DATE);
        sp.execute();

        @SuppressWarnings("unchecked")
        List<GLFileRecord> records = sp.getResultList();

        commitTransaction();

        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        String dayOfYear = String.format("%03d", cal.get(Calendar.DAY_OF_YEAR));

        for (GLFileRecord record : records) {
            StringBuilder line = new StringBuilder("");
            line.append(record.getFeederSystemId());
            line.append(record.getJulianDate());
            line.append(dayOfYear);
            line.append(record.getGlFiller());
            line.append(record.getGlCode());

            int fiscalYear = record.getFiscalYear() == null ? 0 : record.getFiscalYear();
            if (fiscalYear < 1000) {
                line.append(StringUtils.rightPad(record.getGlAccountingCode(), 20));
            } else {
                line.append(fiscalYear % 100);
                line.append("  ");
                line.append(StringUtils.rightPad(record.getGlAccountingCode(), 16));
            }

            line.append(String.format("%015d",
                    record.getRecipientAmount().multiply(BatchProcessHelper.HUNDRED).longValue()));

            line.append(record.getRevenueSourceCode());

            // Pad 28 spaces
            for (int i = 0; i < 28; i++) {
                line.append(" ");
            }

            if (output == null) {
                // Lazily create output file only when there is line to write
                output = new PrintWriter(outputGLFile);
            }
            output.println(line.toString());
        }

        if (output != null) {
            output.flush();
            logger.info("General Ledger file created.");
            procMessage.append(CRLF).append(CRLF).append("General Ledger file created.").append(CRLF);
        } else {
            String info = "There are no GL entries for "
                    + DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(now)
                    + " so no GL file was created. ";
            logger.info(info);
            procMessage.append(CRLF).append(CRLF).append(info).append(CRLF);
        }

        return true;
    } catch (PersistenceException pe) {
        logger.error("Database error creating the GL file.", pe);
        procMessage.append(CRLF).append(CRLF).append("Database error creating the GL file.").append(CRLF);
        return false;
    } catch (IOException e) {
        logger.error("IO error creating the GL file.", e);
        procMessage.append(CRLF).append(CRLF).append("IO error creating the GL file.").append(CRLF);
        return false;
    } finally {
        if (output != null) {
            output.close();
        }
    }
}

From source file:net.unicon.sakora.impl.csv.CsvCommonHandlerService.java

public synchronized void completeRun(boolean success) {
    // run this after a run completes
    String runId = getCurrentSyncRunId();
    Date start = (Date) syncVars.get(SYNC_VAR_STARTDATE);
    log.info("SakoraCSV sync complete (" + (success ? "success" : "FAILED") + ") for run (" + runId
            + ") started on " + DateFormat.getDateTimeInstance().format(start));
    syncVars.put(SYNC_VAR_STATUS, success ? SYNC_STATE_COMPLETE : SYNC_STATE_FAILED);
    if (success) {
        StringBuilder sb = new StringBuilder();
        int total_lines = 0;
        int total_errors = 0;
        int total_adds = 0;
        int total_updates = 0;
        int total_deletes = 0;
        int total_seconds = 0;
        // compile and output the stats data to the logs
        @SuppressWarnings("unchecked")
        Map<String, Map<String, Integer>> stats = getCurrentSyncVar(SYNC_VAR_HANDLER_STATS, Map.class);
        for (Map.Entry<String, Map<String, Integer>> entry : stats.entrySet()) {
            String handler = entry.getKey();
            Map<String, Integer> handlerStats = entry.getValue();
            int lines = handlerStats.get("lines");
            int errors = handlerStats.get("errors");
            int adds = handlerStats.get("adds");
            int updates = handlerStats.get("updates");
            int deletes = handlerStats.get("deletes");
            int seconds = handlerStats.get("seconds");
            total_lines += lines;//from w ww.j a  v  a 2  s.c om
            total_errors += errors;
            total_adds += adds;
            total_updates += updates;
            total_deletes += deletes;
            total_seconds += seconds;
            sb.append("  - ");
            sb.append(StringUtils.rightPad(handler, 20));
            sb.append(": processed ");
            sb.append(String.format("%6d", lines));
            sb.append(" lines with ");
            sb.append(String.format("%4d", errors));
            sb.append(" errors in ");
            sb.append(String.format("%4d", seconds));
            sb.append(" seconds: ");
            sb.append(String.format("%4d", adds));
            sb.append(" adds, ");
            sb.append(String.format("%4d", updates));
            sb.append(" updates, ");
            sb.append(String.format("%4d", deletes));
            sb.append(" deletes\n");
        }
        // total summary (start, end, totals)
        sb.append("  --- TOTAL:         processed ");
        sb.append(String.format("%6d", total_lines));
        sb.append(" lines with ");
        sb.append(String.format("%5d", total_errors));
        sb.append(" errors in ");
        sb.append(String.format("%5d", total_seconds));
        sb.append(" seconds: ");
        sb.append(String.format("%5d", total_adds));
        sb.append(" adds, ");
        sb.append(String.format("%5d", total_updates));
        sb.append(" updates, ");
        sb.append(String.format("%5d", total_deletes));
        sb.append(" deletes\n");
        syncVars.put(SYNC_VAR_SUMMARY, sb.toString());
        log.info("SakoraCSV sync statistics for run (" + runId + "):\n" + sb.toString());
    }
}

From source file:nl.nn.adapterframework.extensions.tibco.TibcoLogJmsListener.java

public String getStringFromRawMessage(Object rawMessage, Map context, boolean soap, String soapHeaderSessionKey,
        SoapWrapper soapWrapper) throws JMSException, DomBuilderException, TransformerException, IOException {
    TibjmsMapMessage tjmMessage;/*from ww w  .j  a v  a  2 s .  c  om*/
    try {
        tjmMessage = (TibjmsMapMessage) rawMessage;
    } catch (ClassCastException e) {
        log.error(
                "message received by listener on [" + getDestinationName()
                        + "] was not of type TibjmsMapMessage, but [" + rawMessage.getClass().getName() + "]",
                e);
        return null;
    }
    Enumeration enumeration = tjmMessage.getMapNames();
    List list = Collections.list(enumeration);
    Collections.sort(list);
    Iterator it = list.iterator();
    StringBuffer sb = new StringBuffer();
    long creationTimes = 0;
    int severity = 0;
    String severityStr = null;
    String msg = null;
    String engineName = null;
    String jobId = null;
    String environment = null;
    String node = null;
    boolean first = true;
    while (it.hasNext()) {
        String mapName = (String) it.next();
        if (mapName.equalsIgnoreCase("_cl.creationTimes")) {
            creationTimes = tjmMessage.getLong(mapName);
        } else {
            if (mapName.equalsIgnoreCase("_cl.severity")) {
                severity = tjmMessage.getInt(mapName);
                severityStr = logLevelToText(severity);
                if (severityStr == null) {
                    severityStr = "[" + severity + "]";
                }
                severityStr = StringUtils.rightPad(severityStr, 5);
            } else {
                if (mapName.equalsIgnoreCase("_cl.msg")) {
                    msg = tjmMessage.getString(mapName);
                } else {
                    if (mapName.equalsIgnoreCase("_cl.engineName")) {
                        engineName = tjmMessage.getString(mapName);
                    } else {
                        if (mapName.equalsIgnoreCase("_cl.jobId")) {
                            jobId = tjmMessage.getString(mapName);
                        } else {
                            String mapValue = tjmMessage.getString(mapName);
                            if (mapName.equalsIgnoreCase("_cl.physicalCompId.matrix.env")) {
                                environment = mapValue;
                                context.put("environment", environment);
                            }
                            if (mapName.equalsIgnoreCase("_cl.physicalCompId.matrix.node")) {
                                node = mapValue;
                            }
                            if (first) {
                                first = false;
                            } else {
                                sb.append(",");
                            }
                            sb.append("[" + mapName + "]=[" + mapValue + "]");
                        }
                    }
                }
            }
        }
    }
    return DateUtils.format(creationTimes) + " " + severityStr + " ["
            + (engineName != null ? engineName : (environment + "-" + node)) + "] ["
            + (jobId != null ? jobId : "") + "] " + msg + " " + sb.toString();
}

From source file:nl.nn.adapterframework.parameters.Parameter.java

/**
 * determines the raw value /*from  ww w .ja va  2s . c o  m*/
 * @param alreadyResolvedParameters
 * @return the raw value as object
 * @throws IbisException
 */
public Object getValue(ParameterValueList alreadyResolvedParameters, ParameterResolutionContext prc)
        throws ParameterException {
    Object result = null;
    log.debug("Calculating value for Parameter [" + getName() + "]");
    if (!configured) {
        throw new ParameterException("Parameter [" + getName() + "] not configured");
    }

    TransformerPool pool = getTransformerPool();
    if (pool != null) {
        try {
            Object transformResult = null;
            Source source = null;
            if (StringUtils.isNotEmpty(getValue())) {
                source = XmlUtils.stringToSourceForSingleUse(getValue(), prc.isNamespaceAware());
            } else if (StringUtils.isNotEmpty(getSessionKey())) {
                String sourceString;
                Object sourceObject = prc.getSession().get(getSessionKey());
                if (TYPE_LIST.equals(getType()) && sourceObject instanceof List) {
                    List<String> items = (List<String>) sourceObject;
                    XmlBuilder itemsXml = new XmlBuilder("items");
                    for (Iterator<String> it = items.iterator(); it.hasNext();) {
                        String item = it.next();
                        XmlBuilder itemXml = new XmlBuilder("item");
                        itemXml.setValue(item);
                        itemsXml.addSubElement(itemXml);
                    }
                    sourceString = itemsXml.toXML();
                } else if (TYPE_MAP.equals(getType()) && sourceObject instanceof Map) {
                    Map<String, String> items = (Map<String, String>) sourceObject;
                    XmlBuilder itemsXml = new XmlBuilder("items");
                    for (Iterator<String> it = items.keySet().iterator(); it.hasNext();) {
                        String item = it.next();
                        XmlBuilder itemXml = new XmlBuilder("item");
                        itemXml.addAttribute("name", item);
                        itemXml.setValue(items.get(item));
                        itemsXml.addSubElement(itemXml);
                    }
                    sourceString = itemsXml.toXML();
                } else {
                    sourceString = (String) sourceObject;
                }
                if (StringUtils.isNotEmpty(sourceString)) {
                    log.debug("Parameter [" + getName() + "] using sessionvariable [" + getSessionKey()
                            + "] as source for transformation");
                    source = XmlUtils.stringToSourceForSingleUse(sourceString, prc.isNamespaceAware());
                } else {
                    log.debug("Parameter [" + getName() + "] sessionvariable [" + getSessionKey()
                            + "] empty, no transformation will be performed");
                }
            } else if (StringUtils.isNotEmpty(getPattern())) {
                String sourceString = format(alreadyResolvedParameters, prc);
                if (StringUtils.isNotEmpty(sourceString)) {
                    log.debug("Parameter [" + getName() + "] using pattern [" + getPattern()
                            + "] as source for transformation");
                    source = XmlUtils.stringToSourceForSingleUse(sourceString, prc.isNamespaceAware());
                } else {
                    log.debug("Parameter [" + getName() + "] pattern [" + getPattern()
                            + "] empty, no transformation will be performed");
                }
            } else {
                source = prc.getInputSource();
            }
            if (source != null) {
                if (transformerPoolRemoveNamespaces != null) {
                    String rnResult = transformerPoolRemoveNamespaces.transform(source, null);
                    source = XmlUtils.stringToSource(rnResult);
                }
                transformResult = transform(source, prc);
            }
            if (!(transformResult instanceof String) || StringUtils.isNotEmpty((String) transformResult)) {
                result = transformResult;
            }
        } catch (Exception e) {
            throw new ParameterException(
                    "Parameter [" + getName() + "] exception on transformation to get parametervalue", e);
        }
    } else {
        if (StringUtils.isNotEmpty(getSessionKey())) {
            result = prc.getSession().get(getSessionKey());
        } else if (StringUtils.isNotEmpty(getPattern())) {
            result = format(alreadyResolvedParameters, prc);
        } else if (StringUtils.isNotEmpty(getValue())) {
            result = getValue();
        } else {
            result = prc.getInput();
        }
    }
    if (result != null) {
        if (log.isDebugEnabled()) {
            log.debug("Parameter [" + getName() + "] resolved to ["
                    + (isHidden() ? hide(result.toString()) : result) + "]");
        }
    } else {
        // if value is null then return specified default value
        StringTokenizer stringTokenizer = new StringTokenizer(getDefaultValueMethods(), ",");
        while (result == null && stringTokenizer.hasMoreElements()) {
            String token = stringTokenizer.nextToken();
            if ("defaultValue".equals(token)) {
                result = getDefaultValue();
            } else if ("sessionKey".equals(token)) {
                result = prc.getSession().get(getSessionKey());
            } else if ("pattern".equals(token)) {
                result = format(alreadyResolvedParameters, prc);
            } else if ("value".equals(token)) {
                result = getValue();
            } else if ("input".equals(token)) {
                result = prc.getInput();
            }
        }
        log.debug("Parameter [" + getName() + "] resolved to defaultvalue ["
                + (isHidden() ? hide(result.toString()) : result) + "]");
    }
    if (result != null && result instanceof String) {
        if (getMinLength() >= 0 && !TYPE_NUMBER.equals(getType())) {
            if (result.toString().length() < getMinLength()) {
                log.debug("Padding parameter [" + getName() + "] because length [" + result.toString().length()
                        + "] deceeds minLength [" + getMinLength() + "]");
                result = StringUtils.rightPad(result.toString(), getMinLength());
            }
        }
        if (getMaxLength() >= 0) {
            if (result.toString().length() > getMaxLength()) {
                log.debug("Trimming parameter [" + getName() + "] because length [" + result.toString().length()
                        + "] exceeds maxLength [" + getMaxLength() + "]");
                result = result.toString().substring(0, getMaxLength());
            }
        }
        if (TYPE_NODE.equals(getType())) {
            try {
                result = XmlUtils.buildNode((String) result, prc.isNamespaceAware());
                if (log.isDebugEnabled())
                    log.debug("final result [" + result.getClass().getName() + "][" + result + "]");
            } catch (DomBuilderException e) {
                throw new ParameterException(
                        "Parameter [" + getName() + "] could not parse result [" + result + "] to XML nodeset",
                        e);
            }
        }
        if (TYPE_DOMDOC.equals(getType())) {
            try {
                result = XmlUtils.buildDomDocument((String) result, prc.isNamespaceAware(), prc.isXslt2());
                if (log.isDebugEnabled())
                    log.debug("final result [" + result.getClass().getName() + "][" + result + "]");
            } catch (DomBuilderException e) {
                throw new ParameterException(
                        "Parameter [" + getName() + "] could not parse result [" + result + "] to XML document",
                        e);
            }
        }
        if (TYPE_DATE.equals(getType()) || TYPE_DATETIME.equals(getType()) || TYPE_TIMESTAMP.equals(getType())
                || TYPE_TIME.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result
                    + "] to date using formatString [" + getFormatString() + "]");
            DateFormat df = new SimpleDateFormat(getFormatString());
            try {
                result = df.parseObject((String) result);
            } catch (ParseException e) {
                throw new ParameterException("Parameter [" + getName() + "] could not parse result [" + result
                        + "] to Date using formatString [" + getFormatString() + "]", e);
            }
        }
        if (TYPE_XMLDATETIME.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result
                    + "] from xml dateTime to date");
            result = DateUtils.parseXmlDateTime((String) result);
        }
        if (TYPE_NUMBER.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result
                    + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator()
                    + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]");
            DecimalFormat df = new DecimalFormat();
            df.setDecimalFormatSymbols(decimalFormatSymbols);
            try {
                Number n = df.parse((String) result);
                result = n;
            } catch (ParseException e) {
                throw new ParameterException(
                        "Parameter [" + getName() + "] could not parse result [" + result
                                + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator()
                                + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]",
                        e);
            }
            if (getMinLength() >= 0 && result.toString().length() < getMinLength()) {
                log.debug("Adding leading zeros to parameter [" + getName() + "]");
                result = StringUtils.leftPad(result.toString(), getMinLength(), '0');
            }
        }
        if (TYPE_INTEGER.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result + "] to integer");
            try {
                Integer i = Integer.parseInt((String) result);
                result = i;
            } catch (NumberFormatException e) {
                throw new ParameterException(
                        "Parameter [" + getName() + "] could not parse result [" + result + "] to integer", e);
            }
        }
    }
    if (result != null) {
        if (getMinInclusive() != null || getMaxInclusive() != null) {
            if (getMinInclusive() != null) {
                if (((Number) result).floatValue() < minInclusive.floatValue()) {
                    log.debug("Replacing parameter [" + getName() + "] because value [" + result
                            + "] exceeds minInclusive [" + getMinInclusive() + "]");
                    result = minInclusive;
                }
            }
            if (getMaxInclusive() != null) {
                if (((Number) result).floatValue() > maxInclusive.floatValue()) {
                    log.debug("Replacing parameter [" + getName() + "] because value [" + result
                            + "] exceeds maxInclusive [" + getMaxInclusive() + "]");
                    result = maxInclusive;
                }
            }
        }
    }

    return result;
}

From source file:org.apache.cocoon.util.log.ExtensiblePatternFormatter.java

/**
 * Utility to append a string to buffer given certain constraints.
 *
 * @param sb the StringBuffer//from   ww w  .  ja v  a2 s. co  m
 * @param minSize the minimum size of output (0 to ignore)
 * @param maxSize the maximum size of output (0 to ignore)
 * @param rightJustify true if the string is to be right justified in it's box.
 * @param output the input string
 */
protected void append(final StringBuffer sb, final int minSize, final int maxSize, final boolean rightJustify,
        final String output) {
    if (output.length() < minSize) {
        if (rightJustify) {
            sb.append(StringUtils.leftPad(output, minSize));
        } else {
            sb.append(StringUtils.rightPad(output, minSize));
        }
    } else if (maxSize > 0) {
        if (rightJustify) {
            sb.append(StringUtils.right(output, maxSize));
        } else {
            sb.append(StringUtils.left(output, maxSize));
        }
    } else {
        sb.append(output);
    }
}

From source file:org.apache.ctakes.jdl.test.SqlJdl.java

/**
 * @param connection//from w ww.j  a va  2 s.  c  om
 *            the connetcion to manage
 * @param print
 *            check if print rows
 * @return list of rows
 * @throws SQLException
 *             exception
 */
public static List<String[]> select(Connection connection, boolean print) throws SQLException {
    List<String[]> list = select(connection);
    if (print) {
        for (String[] c : list) {
            System.out.println(c[0] + "\t" + StringUtils.rightPad(c[1], 31) + c[2] + "\t"
                    + StringUtils.rightPad(c[3], 23) + c[4] + "\t" + c[5]);
        }
    }
    return list;
}

From source file:org.apache.hadoop.hive.common.type.HiveBaseChar.java

public static String getPaddedValue(String val, int maxLength) {
    if (val == null) {
        return null;
    }/*from   w w w.  j a va  2s.c  o  m*/
    if (maxLength < 0) {
        return val;
    }

    int valLength = val.codePointCount(0, val.length());
    if (valLength > maxLength) {
        return enforceMaxLength(val, maxLength);
    }

    if (maxLength > valLength) {
        // Make sure we pad the right amount of spaces; valLength is in terms of code points,
        // while StringUtils.rpad() is based on the number of java chars.
        int padLength = val.length() + (maxLength - valLength);
        val = StringUtils.rightPad(val, padLength);
    }
    return val;
}

From source file:org.apache.mahout.classifier.chi_rwcs.mapreduce.BuildModel.java

private void writeToFileBuildTime(String time) throws IOException {
    FileSystem outFS = timePath.getFileSystem(getConf());
    FSDataOutputStream ofile = null;/*  w  w w . j a  v  a2s.  com*/
    Path filenamePath = new Path(timePath, dataName + "_build_time").suffix(".txt");
    try {
        if (ofile == null) {
            // this is the first value, it contains the name of the input file
            ofile = outFS.create(filenamePath);
            // write the Build Time                                    
            StringBuilder returnString = new StringBuilder(200);
            returnString.append("=======================================================").append('\n');
            returnString.append("Build Time\n");
            returnString.append("-------------------------------------------------------").append('\n');
            returnString.append(StringUtils.rightPad(time, 5)).append('\n');
            returnString.append("-------------------------------------------------------").append('\n');
            String output = returnString.toString();
            ofile.writeUTF(output);
            ofile.close();
        }
    } finally {
        Closeables.closeQuietly(ofile);
    }
}

From source file:org.apache.mahout.classifier.chi_rwcs.mapreduce.TestModel.java

private void parseOutput(ResultAnalyzer analyzer) throws IOException {
    NumberFormat decimalFormatter = new DecimalFormat("0.########");
    outFS = outputPath.getFileSystem(getConf());
    FSDataOutputStream ofile = null;/*from w w  w . j  a  v a  2  s  . c o m*/
    int pos = dataName.indexOf('t');
    String subStr = dataName.substring(0, pos);
    Path filenamePath = new Path(outputPath, subStr + "_confusion_matrix").suffix(".txt");
    try {
        if (ofile == null) {
            // this is the first value, it contains the name of the input file
            ofile = outFS.create(filenamePath);
            // write the Confusion Matrix                                    
            StringBuilder returnString = new StringBuilder(200);
            returnString.append("=======================================================").append('\n');
            returnString.append("Confusion Matrix\n");
            returnString.append("-------------------------------------------------------").append('\n');
            int[][] matrix = analyzer.getConfusionMatrix().getConfusionMatrix();
            for (int i = 0; i < matrix.length - 1; i++) {
                for (int j = 0; j < matrix[i].length - 1; j++) {
                    returnString.append(StringUtils.rightPad(Integer.toString(matrix[i][j]), 5)).append('\t');
                }
                returnString.append('\n');
            }
            returnString.append("-------------------------------------------------------").append('\n');
            returnString.append("AUC - Area Under the Curve ROC\n");
            returnString.append(StringUtils.rightPad(decimalFormatter.format(computeAuc(matrix)), 5))
                    .append('\n');
            returnString.append("-------------------------------------------------------").append('\n');
            returnString.append("GM - Geometric Mean\n");
            returnString.append(StringUtils.rightPad(decimalFormatter.format(computeGM(matrix)), 5))
                    .append('\n');
            returnString.append("-------------------------------------------------------").append('\n');
            String output = returnString.toString();
            ofile.writeUTF(output);
            ofile.close();
        }
    } finally {
        Closeables.closeQuietly(ofile);
    }
}