Example usage for java.util Formatter close

List of usage examples for java.util Formatter close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes this formatter.

Usage

From source file:uniol.apt.ui.impl.UIUtils.java

/**
 * Returns a usage string describing how to use the module.
 *
 * @param module//w ww.ja v  a  2 s  . c o  m
 *                module in question
 * @param parametersTransformer
 *                transformer for getting descriptions of the string
 *                transformations
 * @return usage string
 * @throws NoSuchTransformationException
 *                 thrown if there is no applicable transformation for a
 *                 parameter
 */
public static String getModuleUsage(Module module, ParametersTransformer parametersTransformer)
        throws NoSuchTransformationException {
    List<Parameter> parameters = ModuleUtils.getParameters(module);
    List<OptionalParameter<?>> optionalParameters = ModuleUtils.getOptionalParameters(module);
    List<ReturnValue> fileReturnValues = ModuleUtils.getFileReturnValues(module);

    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb);
    formatter.format("Usage: apt %s", module.getName());

    for (Parameter parameter : parameters) {
        formatter.format(" <%s>", parameter.getName());
    }

    for (Parameter parameter : optionalParameters) {
        formatter.format(" [<%s>]", parameter.getName());
    }

    for (ReturnValue fileReturnValue : fileReturnValues) {
        formatter.format(" [<%s>]", fileReturnValue.getName());
    }
    formatter.format("%n");

    for (Parameter parameter : parameters) {
        formatter.format("  %-10s %s%n", parameter.getName(), parameter.getDescription());
    }
    for (OptionalParameter<?> parameter : optionalParameters) {
        Object def = parameter.getDefaultValueString();
        String extra = "";
        if (def != null)
            extra = String.format(" The default value is '%s'.", def);
        formatter.format("  %-10s %s%s%n", parameter.getName(), parameter.getDescription(), extra);
    }
    for (ReturnValue value : fileReturnValues) {
        formatter.format("  %-10s Optional file name for writing the output to%n", value.getName());
    }

    formatter.format("%n%s", module.getLongDescription());

    boolean printedHeader = false;
    for (Parameter parameter : union(parameters, optionalParameters)) {
        String desc = parametersTransformer.getTransformationDescription(parameter.getKlass());
        if ("".equals(desc))
            continue;

        if (!printedHeader)
            formatter.format("%n%nFormat descriptions of parameters:");
        printedHeader = true;
        formatter.format("%n%n%s:%n%s", parameter.getName(), desc);
    }

    formatter.close();
    return sb.toString();
}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Calculates the domains per network feature for each cluster generated
 * on a specific run date.//  w ww .j a  v  a  2 s. c om
 * 
 * @param log_date the run date
 * @param window the number of days previous to use in feature calculation
 * @return a table of values where the keys are cluster ids and the values 
 *       are the feature values
 * @throws SQLException if there is an error calculating the feature values
 */

public Map<Integer, Double> calculateDomainsPerNetwork(Date log_date, int window) throws SQLException {
    HashMap<Integer, Double> retval = new HashMap<Integer, Double>();
    ArrayList<Date> prevDates = getPrevDates(log_date, window);
    if (prevDates.size() > 0) {
        String logDateStr = df.format(log_date);
        StringBuffer add_query = new StringBuffer();
        Formatter formatter = new Formatter(add_query);

        for (Date prevDate : prevDates) {
            String prevDateStr = df.format(prevDate);
            formatter.format(" " + properties.getProperty(DOMAINSPERNETWORK_QUERY1KEY) + " ", logDateStr,
                    prevDateStr, prevDateStr);
        }
        formatter.close();

        StringBuffer querybuf = new StringBuffer();
        formatter = new Formatter(querybuf);
        formatter.format(properties.getProperty(DOMAINSPERNETWORK_QUERY2KEY), logDateStr, logDateStr,
                logDateStr, add_query.toString());
        ResultSet rs = null;
        try {
            rs = dbi.executeQueryWithResult(querybuf.toString());
            while (rs.next()) {
                retval.put(rs.getInt(1), rs.getDouble(2));
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        } finally {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
            formatter.close();
        }
    }
    return retval;
}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Calculates the previous cluster ratio feature for each cluster generated
 * on a specific run date and within the a specific window
 *
 * @param log_date the run date/*w w w.  ja v a2s  .com*/
 * @param window the number of days previous to use in feature calculation
 * @return a table of results, the keys of the table are cluster ids and the
 *       values are lists of two elements.  The first element is the 
 *       last_growth_ratio_prev_clusters value and the second element is the
 *       last_growth_prefix_ratio_prev_clusters value
 * @throws SQLException if there is and error calculating the feature
 */
public Hashtable<Integer, List<Double>> calculatePrevClusterRatios(Date log_date, int window)
        throws SQLException {
    Hashtable<Integer, List<Double>> retval = new Hashtable<Integer, List<Double>>();

    ArrayList<Date> prevDates = getPrevDates(log_date, window);
    String query1 = properties.getProperty(PREVCLUSTER_QUERY1KEY);
    String query2 = properties.getProperty(PREVCLUSTER_QUERY2KEY);
    String logDateStr = df.format(log_date);
    String completequery = new String();

    StringBuffer addQueryBuff = new StringBuffer();
    for (int i = 0; i < prevDates.size(); i++) {
        String prevDateStr = df.format(prevDates.get(i));
        StringBuffer querybuf = new StringBuffer();
        Formatter formatter = new Formatter(querybuf);
        formatter.format(query1, logDateStr, logDateStr, prevDateStr, prevDateStr, prevDateStr);
        addQueryBuff.append(querybuf.toString());
        if (i < prevDates.size() - 1) {
            addQueryBuff.append(" UNION ");
        }
        formatter.close();
    }

    if (addQueryBuff.length() > 0) {
        StringBuffer querybuf = new StringBuffer();
        Formatter formatter = new Formatter(querybuf);
        formatter.format(query2, logDateStr, logDateStr, addQueryBuff.toString());
        completequery = querybuf.toString();
        formatter.close();
    }

    if (completequery.length() > 0) {
        ResultSet rs = null;
        try {
            rs = dbi.executeQueryWithResult(completequery);
            while (rs.next()) {
                ArrayList<Double> temp = new ArrayList<Double>();
                temp.add(rs.getDouble(3));
                temp.add(rs.getDouble(4));
                retval.put(rs.getInt(1), temp);
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        } finally {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
        }
        Hashtable<Integer, Double> queryPerDomain = getQueriesPerDomain(log_date);
        for (Integer clusterid : retval.keySet()) {
            List<Double> values = retval.get(clusterid);
            values.set(0, values.get(0) / queryPerDomain.get(clusterid));
            values.set(1, values.get(1) / queryPerDomain.get(clusterid));
        }
    }

    return retval;
}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Calculates the cluster novelty feature for each cluster generated
 * on a specific run date and stores them in the database.
 *
 * @param log_date the run date/*from  w w  w .  j  a v  a2s  .c  om*/
 * @throws Exception if there is an error calculating or storing the feature
 *       values
 */
public void updateNoveltyFeature(Date log_date) throws Exception {
    Map<Integer, String> windowvals = new TreeMap<Integer, String>();
    String[] windowsstr = properties.getProperty(NOVELTY_WINDOWSKEY).split(",");
    String[] windowfields = properties.getProperty(NOVELTY_WINFIELDSKEY).split(",");

    if (windowfields.length != windowsstr.length) {
        throw new Exception("Number of novelty window values and fields do not match.");
    }

    for (int i = 0; i < windowsstr.length; i++) {
        windowvals.put(Integer.parseInt(windowsstr[i]), windowfields[i]);
    }

    //We start from largest window to smallest so we can cache the prevDates results for later use
    List<Integer> windowkeys = new ArrayList<Integer>(windowvals.keySet());
    Collections.reverse(windowkeys);

    for (int window : windowkeys) {
        Map<Integer, Double> novelty = calculateNoveltyFeature(log_date, window);
        for (int clusterid : novelty.keySet()) {
            StringBuffer querybuf = new StringBuffer();
            Formatter formatter = new Formatter(querybuf);
            formatter.format(properties.getProperty(NOVELTY_QUERY3KEY), df.format(log_date),
                    windowvals.get(window), String.valueOf(novelty.get(clusterid)), String.valueOf(clusterid),
                    df.format(log_date));
            dbi.executeQueryNoResult(querybuf.toString());
            formatter.close();
        }
    }

}

From source file:eu.stratosphere.pact.runtime.hash.HashFunctionCollisionBenchmark.java

private void printStatistics() {
    for (int level = 0; level < maxLevel; level++) {
        int bucketCountInLevel = 0;

        SortedMap<Integer, Integer> levelMap = bucketSizesPerLevel.get(level);
        Iterator<Integer> bucketSizeIterator = levelMap.keySet().iterator();

        LOG.debug("Statistics for level: " + level);
        LOG.debug("----------------------------------------------");
        LOG.debug("");
        LOG.debug("Bucket Size |      Count");
        LOG.debug("------------------------");

        int i = 0;
        while (bucketSizeIterator.hasNext()) {
            int bucketSize = bucketSizeIterator.next();
            if (bucketSize != 0) {
                int countForBucketSize = levelMap.get(bucketSize);
                bucketCountInLevel += countForBucketSize;
                Formatter formatter = new Formatter();
                formatter.format(" %10d | %10d", bucketSize, countForBucketSize);

                if (levelMap.size() < 20 || i < 3 || i >= (levelMap.size() - 3)) {
                    LOG.debug(formatter.out());
                } else if (levelMap.size() / 2 == i) {
                    LOG.debug("         .. |         ..");
                    LOG.debug(formatter.out());
                    LOG.debug("         .. |         ..");
                }/*from  w w  w .  j  a  v  a  2  s  .co  m*/
                i++;
                formatter.close();
            }
        }

        LOG.debug("");
        LOG.debug("Number of non-empty buckets in level: " + bucketCountInLevel);
        LOG.debug("Number of empty buckets in level    : " + levelMap.get(0));
        LOG.debug("Number of different bucket sizes    : " + (levelMap.size() - 1));
        LOG.debug("");
        LOG.debug("");
        LOG.debug("");
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstSybase.CFAstSybaseSchema.java

public static String getDateString(Calendar val) {
    if (val == null) {
        return ("null");
    } else {/*  ww w .  j  a  va  2  s  . co  m*/
        StringBuffer buff = new StringBuffer();
        Formatter fmt = new Formatter(buff);
        fmt.format("%1$04d", val.get(Calendar.YEAR));
        fmt.format("%1$02d", val.get(Calendar.MONTH) + 1);
        fmt.format("%1$02d", val.get(Calendar.DAY_OF_MONTH));
        fmt.close();
        return (buff.toString());
    }
}

From source file:com.diversityarrays.dalclient.DalUtil.java

/**
 * Computes the MD5 checksum of the bytes in the InputStream.
 * The input is close()d on exit.//  w  ww. j a va  2  s .  c o m
 * @param input is the InputStream for which to compute the checksum
 * @return the MD5 checksum as a String of hexadecimal characters
 */
static public String computeMD5checksum(InputStream input) {
    DigestInputStream dis = null;
    Formatter formatter = null;
    try {
        MessageDigest md = MessageDigest.getInstance(DIGEST_MD5);
        dis = new DigestInputStream(input, md);
        while (-1 != dis.read())
            ;

        byte[] digest = md.digest();
        formatter = new Formatter();
        for (byte b : digest) {
            formatter.format("%02x", b); //$NON-NLS-1$
        }
        return formatter.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException ignore) {
            }
        }
        if (formatter != null) {
            formatter.close();
        }
    }
}

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

private void formateCoordinatesShift() throws IOException {
    final Formatter lFormatter = getFormatter(ISimulation1D2DConstants.SIM_SWAN_COORD_SHIFT_FILE);
    lFormatter.format("Kalypso-SWAN Coordinates shift\n"); //$NON-NLS-1$
    lFormatter.format("%s=%f\n%s=%f\nEND\n", ISimulation1D2DConstants.SIM_SWAN_COORD_SHIFT_X, m_doubleShiftX, //$NON-NLS-1$
            ISimulation1D2DConstants.SIM_SWAN_COORD_SHIFT_Y, m_doubleShiftY);
    lFormatter.close();
}

From source file:edu.ku.brc.af.auth.UserAndMasterPasswordMgr.java

/**
 * Super simple encryption of just converting string to HEX.
 * @param str the string to be encrypted
 * @return hex-ified string//from   w w  w  .  j av  a2s.c  o m
 */
private String encrypt(final String str) {
    Formatter formatter = new Formatter();
    for (byte b : str.getBytes()) {
        formatter.format("%02x", b);
    }
    String s = formatter.toString();
    formatter.close();
    return s;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstSybase.CFAstSybaseSchema.java

public static String getTimeString(Calendar val) {
    if (val == null) {
        return ("null");
    } else {/*from w  w w.java  2  s .  c  o m*/
        StringBuffer buff = new StringBuffer();
        Formatter fmt = new Formatter(buff);
        fmt.format("%1$02d", val.get(Calendar.HOUR_OF_DAY));
        buff.append(":");
        fmt.format("%1$02d", val.get(Calendar.MINUTE));
        buff.append(":");
        fmt.format("%1$02d", val.get(Calendar.SECOND));
        fmt.close();
        return (buff.toString());
    }
}