Example usage for java.util Formatter Formatter

List of usage examples for java.util Formatter Formatter

Introduction

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

Prototype

public Formatter() 

Source Link

Document

Constructs a new formatter.

Usage

From source file:au.gov.ansto.bragg.kowari.ui.views.AnalysisControlView.java

private String getDeviceInfo(Plot inputdata, String deviceName, String numericFormat, int index) {
    String result = "";
    if (deviceName != null) {
        try {//from   w  ww. j ava 2 s . c  om
            Object item = inputdata.getContainer(deviceName);
            if (item == null)
                item = inputdata.getContainer("old_" + deviceName);
            IArray signal = null;
            String units = "";
            if (item instanceof IDataItem) {
                signal = ((IDataItem) item).getData();
                units = ((IDataItem) item).getUnitsString();
            } else if (item instanceof IAttribute)
                signal = ((IAttribute) item).getValue();
            if (signal.getElementType() == Character.TYPE)
                result = signal.toString();
            else {
                double signalMax = signal.getArrayMath().getMaximum();
                double signalMin = signal.getArrayMath().getMinimum();
                //               result = deviceName + "=";
                if (numericFormat == null)
                    numericFormat = "%.5f";
                if (signalMax == signalMin)
                    result += (new Formatter()).format(numericFormat, signalMax) + " ";
                else
                    result += (new Formatter()).format(numericFormat,
                            signal.getDouble(signal.getIndex().set(index))) + " ";
            }
        } catch (Exception e) {
        }
    }
    return result;
}

From source file:com.flexive.shared.FxFormatUtils.java

/**
 * Generic SQL escape method./*from   www .  ja  v a  2 s  .com*/
 *
 * @param value the value to be formatted
 * @return the formatted value
 */
public static String escapeForSql(Object value) {
    if (value instanceof FxValue) {
        return ((FxValue) value).getSqlValue();
    } else if (value instanceof String) {
        return "'" + StringUtils.replace((String) value, "'", "''") + "'";
    } else if (value instanceof Date) {
        return "'" + new Formatter().format("%tF", (Date) value) + "'";
    } else if (value instanceof FxSelectListItem) {
        return String.valueOf(((FxSelectListItem) value).getId());
    } else if (value instanceof SelectMany) {
        final SelectMany selectMany = (SelectMany) value;
        final List<Long> selectedIds = selectMany.getSelectedIds();
        if (selectedIds.size() > 1) {
            return "(" + StringUtils.join(selectedIds.iterator(), ',') + ")";
        } else if (selectedIds.size() == 1) {
            return String.valueOf(selectedIds.get(0));
        } else {
            return "-1";
        }
    } else if (value != null && value.getClass().isArray()) {
        // decode array via reflection to support primitive arrays
        final List<Object> result = new ArrayList<Object>();
        final int len = Array.getLength(value);
        for (int i = 0; i < len; i++) {
            result.add(Array.get(value, i));
        }
        return makeTuple(result);
    } else if (value instanceof Collection) {
        return makeTuple((Collection) value);
    } else if (value != null) {
        return value.toString();
    } else {
        return "null";
    }
}

From source file:au.gov.ansto.bragg.kowari.ui.views.AnalysisControlView.java

private String getFormatedString(double value, String numericFormat) {
    return (new Formatter()).format(numericFormat, value).toString();
}

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  om

    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:fi.mikuz.boarder.util.FileProcessor.java

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

From source file:jeplus.data.ParameterItem.java

/**
 * To parse the given string as a range delimited with colon ':', e.g. -20:1:20
 * @param rstr The string to be parse//ww  w. java2  s  .  c o m
 * @return A parsed list of strings
 * @throws java.lang.Exception
 */
private String[] parseRange(String rstr) throws Exception {
    String[] s = rstr.split("\\s*:\\s*");
    if (s.length != 3)
        throw new MalformedValuesException("Range format: [LB:Int:UB]");
    if (Type == INTEGER) {
        int lb = Integer.parseInt(s[0]);
        int intv = Integer.parseInt(s[1]);
        if (intv <= 0)
            throw new MalformedValuesException(
                    "Range format: [LB:Int:UB]; incremental value must be greater than 0.");
        int ub = Integer.parseInt(s[2]);
        ArrayList<String> list = new ArrayList();
        while (lb <= ub) {
            list.add(Integer.toString(lb));
            lb += intv;
        }
        return list.toArray(new String[0]);
    } else if (Type == DOUBLE) {
        double lb = Double.parseDouble(s[0]);
        double intv = Double.parseDouble(s[1]);
        if (intv <= 0)
            throw new MalformedValuesException(
                    "Range format: [LB:Int:UB]; incremental value must be greater than 0.");
        double ub = Double.parseDouble(s[2]);
        ArrayList<String> list = new ArrayList();
        while (lb <= ub) {
            // list.add(Double.toString(lb));
            String val = new Formatter().format("%g", lb).toString();
            if (val.contains(".")) { // only when a decimal point is present
                // split at 'e'
                String[] parts = val.split("e");
                val = parts[0];
                while (val.length() > 3 && val.endsWith("0"))
                    val = val.substring(0, val.length() - 1);
                if (parts.length > 1 && parts[1] != null)
                    val = val.concat("e").concat(parts[1]);
            }
            list.add(val);
            lb += intv;
        }
        return list.toArray(new String[0]);
    }
    throw new MalformedValuesException("parseRange failed: unsupported parameter type.");
}

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 ww w.  java 2 s .c om
 */
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:fll.scheduler.SchedulerUI.java

private void loadScheduleDescription(final File file) {
    final Properties properties = new Properties();
    try (final Reader reader = new InputStreamReader(new FileInputStream(file), Utilities.DEFAULT_CHARSET)) {
        properties.load(reader);//from www .ja v  a  2 s  .  co  m
    } catch (final IOException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error loading file: %s", e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error loading file",
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(properties.toString());
    }

    try {
        final SolverParams params = new SolverParams();
        params.load(properties);
        mScheduleDescriptionEditor.setParams(params);
    } catch (final ParseException pe) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error parsing file: %s", pe.getMessage());
        LOGGER.error(errorFormatter, pe);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error parsing file",
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    mScheduleDescriptionFile = file;

    mDescriptionFilename.setText(file.getName());
}

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:com.zimbra.cs.util.ProxyConfOverride.java

@Override
public void update() throws ServiceException, ProxyConfException {
    ArrayList<String> servers = new ArrayList<String>();

    /* $(zmprov gamcs) */
    List<Server> mcs = mProv.getAllServers(Provisioning.SERVICE_MEMCACHED);
    for (Server mc : mcs) {
        String serverName = mc.getAttr(Provisioning.A_zimbraServiceHostname, "");
        int serverPort = mc.getIntAttr(Provisioning.A_zimbraMemcachedBindPort, 11211);
        try {/*from ww w.j  a v  a 2  s .c  o  m*/
            InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(serverName);

            Formatter f = new Formatter();
            if (ip instanceof Inet4Address) {
                f.format("%s:%d", ip.getHostAddress(), serverPort);
            } else {
                f.format("[%s]:%d", ip.getHostAddress(), serverPort);
            }

            servers.add(f.toString());
            f.close();
        } catch (ProxyConfException pce) {
            mLog.error("Error resolving memcached host name: '" + serverName + "'", pce);
        }
    }
    if (servers.isEmpty()) {
        throw new ProxyConfException("No available memcached servers could be contacted");
    }
    mValue = servers;
}