Example usage for java.lang NumberFormatException getMessage

List of usage examples for java.lang NumberFormatException getMessage

Introduction

In this page you can find the example usage for java.lang NumberFormatException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:Main.java

public static Integer stringToInteger(String str) {
    if (str == null) {
        return null;
    } else {/* ww  w .j  av  a  2  s. c om*/
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            try {
                Double d = Double.valueOf(str);
                if (d.doubleValue() > mMaxInt.doubleValue() + 1.0) {
                    Log.w(TAG, "Value " + d + " too large for integer");
                    return null;
                }
                return Integer.valueOf(d.intValue());
            } catch (NumberFormatException nfe2) {
                Log.w(TAG,
                        "Unable to interpret value " + str + " in field being "
                                + "converted to int, caught NumberFormatException <" + e.getMessage()
                                + "> field discarded");
                return null;
            }
        }
    }
}

From source file:org.eumetsat.metop.visat.SounderInfoView.java

protected static Number getScalingFactor(EpsFile sounderFile, String sequenceName) throws IOException {
    try {//w  w  w.j a  va  2s  .com
        return Double.valueOf(getMetaData(sounderFile, sequenceName).getScalingFactor().replace("10^", "1.0E"));
    } catch (NumberFormatException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:org.escidoc.browser.elabsmodul.service.ELabsService.java

private static InvestigationBean resolveInvestigation(final ContainerProxy containerProxy) {
    final String URI_DC = "http://purl.org/dc/elements/1.1/";
    final String URI_EL = "http://escidoc.org/ontologies/bw-elabs/re#";
    final String URI_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

    if (containerProxy == null) {
        throw new NullPointerException("Container Proxy is null.");
    }//from   www .j  av a  2s .com
    final InvestigationBean investigationBean = new InvestigationBean();
    final Element e = containerProxy.getMetadataRecords().get("escidoc").getContent();
    investigationBean.setObjid(containerProxy.getId());

    if (!(("Investigation".equals(e.getLocalName()) && URI_EL.equals(e.getNamespaceURI()))
            || "el:Investigation".equals(e.getTagName()))) {
        LOG.error("Container is not an eLabs Investigation");
        return investigationBean;
    }

    final NodeList nodeList = e.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        final String nodeName = node.getLocalName();
        final String nsUri = node.getNamespaceURI();

        if (nodeName == null || nsUri == null) {
            continue;
        }

        if ("title".equals(nodeName) && URI_DC.equals(nsUri)) {
            investigationBean.setName(node.getTextContent());
        } else if ("description".equals(nodeName) && URI_DC.equals(nsUri)) {
            investigationBean.setDescription(node.getTextContent());
        } else if ("max-runtime".equals(nodeName) && URI_EL.equals(nsUri)) {
            investigationBean.setMaxRuntime("<<not used>>");
            try {
                investigationBean.setMaxRuntimeInMin(Integer.valueOf(node.getTextContent()));
            } catch (final NumberFormatException nfe) {
                LOG.error(nfe.getMessage());
                investigationBean.setMaxRuntimeInMin(0);
            }
        } else if ("deposit-endpoint".equals(nodeName) && URI_EL.equals(nsUri)) {
            investigationBean.setDepositEndpoint(node.getTextContent());
        } else if ("investigator".equals(nodeName) && URI_EL.equals(nsUri)) {
            final String investigatorId = node.getAttributes().getNamedItemNS(URI_RDF, "resource")
                    .getTextContent();
            investigationBean.setInvestigator(investigatorId);
        } else if ("rig".equals(nodeName) && URI_EL.equals(nsUri)) {
            final String rigId = node.getAttributes().getNamedItemNS(URI_RDF, "resource").getTextContent();
            if (StringUtils.notEmpty(rigId)) {
                final RigBean rigBean = new RigBean();
                rigBean.setObjectId(rigId);
                investigationBean.setRigBean(rigBean);
            }
        } else if ("instrument".equals(nodeName) && URI_EL.equals(nsUri)) {
            final String instrument = node.getAttributes().getNamedItemNS(URI_RDF, "resource").getTextContent();
            final String folder = node.getTextContent().trim();
            investigationBean.getInstrumentFolder().put(instrument, folder);
        }
    }
    return investigationBean;
}

From source file:dao.MetricsDAO.java

public static String updateMetricValues(int id, Map<String, String[]> params) {
    String message = "Internal error";
    if (params == null || params.size() == 0) {
        return "Empty post body";
    }/*  w ww  . j  ava2 s  . c o m*/

    boolean needAnd = false;
    String setClause = "";
    String description = "";
    String[] descArray = null;
    List<Object> args = new ArrayList<Object>();
    List<Integer> argTypes = new ArrayList<Integer>();

    if (params.containsKey(MetricRowMapper.METRIC_DESCRIPTION_COLUMN)) {
        descArray = params.get(MetricRowMapper.METRIC_DESCRIPTION_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_DESCRIPTION)) {
        descArray = params.get(MetricRowMapper.METRIC_MODULE_DESCRIPTION);
    }

    if (descArray != null && descArray.length > 0) {
        description = descArray[0];
        setClause += MetricRowMapper.METRIC_DESCRIPTION_COLUMN + " = ? ";
        needAnd = true;
        args.add(description);
        argTypes.add(Types.VARCHAR);
    }

    String dashboard = "";
    String[] dashboardArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN)) {
        dashboardArray = params.get(MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_DASHBOARD_NAME)) {
        dashboardArray = params.get(MetricRowMapper.METRIC_MODULE_DASHBOARD_NAME);
    }

    if (dashboardArray != null && dashboardArray.length > 0) {
        dashboard = dashboardArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN + " = ? ";
        needAnd = true;
        args.add(dashboard);
        argTypes.add(Types.VARCHAR);
    }

    String type = "";
    String[] typeArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN)) {
        typeArray = params.get(MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_REF_ID_TYPE)) {
        typeArray = params.get(MetricRowMapper.METRIC_MODULE_REF_ID_TYPE);
    }

    if (typeArray != null && typeArray.length > 0) {
        type = typeArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN + " = ? ";
        needAnd = true;
        args.add(type);
        argTypes.add(Types.VARCHAR);
    }
    String grain = "";
    String[] grainArray = null;

    if (params.containsKey(MetricRowMapper.METRIC_GRAIN_COLUMN)) {
        grainArray = params.get(MetricRowMapper.METRIC_GRAIN_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_GRAIN)) {
        grainArray = params.get(MetricRowMapper.METRIC_MODULE_GRAIN);
    }

    if (grainArray != null && grainArray.length > 0) {
        grain = grainArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_GRAIN_COLUMN + " = ? ";
        needAnd = true;
        args.add(grain);
        argTypes.add(Types.VARCHAR);
    }

    String formula = "";
    String[] formulaArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_FORMULA_COLUMN)) {
        formulaArray = params.get(MetricRowMapper.METRIC_FORMULA_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_FORMULA)) {
        formulaArray = params.get(MetricRowMapper.METRIC_MODULE_FORMULA);
    }

    if (formulaArray != null && formulaArray.length > 0) {
        formula = formulaArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_FORMULA_COLUMN + " = ? ";
        needAnd = true;
        args.add(formula);
        argTypes.add(Types.VARCHAR);
    }

    String displayFactorString = "";
    Double displayFactor = 0.0;
    String[] displayFactorArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_DISPLAY_FACTOR_COLUMN)) {
        displayFactorArray = params.get(MetricRowMapper.METRIC_DISPLAY_FACTOR_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_DISPLAY_FACTOR)) {
        displayFactorArray = params.get(MetricRowMapper.METRIC_MODULE_DISPLAY_FACTOR);
    }

    if (displayFactorArray != null && displayFactorArray.length > 0) {
        displayFactorString = displayFactorArray[0];
        try {
            displayFactor = Double.parseDouble(displayFactorString);
            if (needAnd) {
                setClause += ", ";
            }
            setClause += MetricRowMapper.METRIC_DISPLAY_FACTOR_COLUMN + " = ? ";
            needAnd = true;
            args.add(displayFactor);
            argTypes.add(Types.DECIMAL);
        } catch (NumberFormatException e) {
            Logger.error("MetricDAO updateMetricValues wrong page parameter. Error message: " + e.getMessage());
            displayFactor = 0.0;
        }
    }

    String displayFactorSym = "";
    String[] factorSymArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_DISPLAY_FACTOR_SYM_COLUMN)) {
        factorSymArray = params.get(MetricRowMapper.METRIC_DISPLAY_FACTOR_SYM_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_DISPLAY_FACTOR_SYM)) {
        factorSymArray = params.get(MetricRowMapper.METRIC_MODULE_DISPLAY_FACTOR_SYM);
    }

    if (factorSymArray != null && factorSymArray.length > 0) {
        displayFactorSym = factorSymArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_DISPLAY_FACTOR_SYM_COLUMN + " = ? ";
        needAnd = true;
        args.add(displayFactorSym);
        argTypes.add(Types.VARCHAR);
    }

    String groupSkString = "";
    Integer groupSk = 0;
    String[] groupSkArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_SUB_CATEGORY_COLUMN)) {
        groupSkArray = params.get(MetricRowMapper.METRIC_SUB_CATEGORY_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_SUB_CATEGORY)) {
        groupSkArray = params.get(MetricRowMapper.METRIC_MODULE_SUB_CATEGORY);
    }

    if (groupSkArray != null && groupSkArray.length > 0) {
        groupSkString = groupSkArray[0];
        try {
            groupSk = Integer.parseInt(groupSkString);
            if (needAnd) {
                setClause += ", ";
            }
            setClause += MetricRowMapper.METRIC_SUB_CATEGORY_COLUMN + " = ? ";
            needAnd = true;
            args.add(groupSk);
            argTypes.add(Types.INTEGER);
        } catch (NumberFormatException e) {
            Logger.error("MetricDAO updateMetricValues wrong page parameter. Error message: " + e.getMessage());
            groupSk = 0;
        }
    }

    String metricSource = "";
    String[] metricSourceArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_SOURCE_COLUMN)) {
        metricSourceArray = params.get(MetricRowMapper.METRIC_SOURCE_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_SOURCE)) {
        metricSourceArray = params.get(MetricRowMapper.METRIC_MODULE_SOURCE);
    }

    if (metricSourceArray != null && metricSourceArray.length > 0) {
        metricSource = metricSourceArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_SOURCE_COLUMN + " = ? ";
        needAnd = true;
        args.add(metricSource);
        argTypes.add(Types.VARCHAR);
    }

    if (StringUtils.isNotBlank(setClause)) {
        args.add(id);
        argTypes.add(Types.SMALLINT);
        int row = getJdbcTemplate().update(UPDATE_METRIC.replace("$SET_CLAUSE", setClause), args.toArray(),
                Ints.toArray(argTypes));
        if (row > 0) {
            message = "";
        }
    } else {
        message = "Wrong post body";
    }
    return message;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.importer.ExcelImportUtilities.java

private static String getNumericCellContentAsString(Cell cell, ProcessingLog processingLog) {
    // for numeric cells / dates we have to look at the cell format to tell if it's a date cell
    // If so, we retrieve the value as a date and convert it to ISO String notation

    if (HSSFDateUtil.isCellDateFormatted(cell)) {
        // is it a date-formatted number? then return the ISO-formatted date instead of the number
        Date cellDate = contentAsDate(cell);
        final SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        return dateformatter.format(cellDate);
    }//from w ww  . j  av  a2  s .  com

    Double d = null;
    try {
        d = contentAsDouble(cell);
    } catch (NumberFormatException ex) {
        processingLog.warn("Cell [{0}] {1}; ignoring the value", getCellRef(cell), ex.getMessage());
    } catch (IllegalStateException e) {
        processingLog.warn("Cell [{0}] {1}; ignoring the value", getCellRef(cell), e.getMessage());
    }

    if (d != null) {
        // cut off *.0
        double i = d.doubleValue() - d.intValue();

        if (i == 0) {
            Integer j = Integer.valueOf(d.intValue());
            return j.toString();
        } else {
            return d.toString();
        }
    }
    return "";
}

From source file:Main.java

/**
 * Normalizes a floating point number to its canonical representation.
 * /*from  w  ww  .ja v  a 2  s  .  co m*/
 * @param value
 *            The value to normalize.
 * @param minMantissa
 *            A normalized decimal indicating the lowest value that the
 *            mantissa may have.
 * @param maxMantissa
 *            A normalized decimal indicating the highest value that the
 *            mantissa may have.
 * @param minExponent
 *            A normalized integer indicating the lowest value that the
 *            exponent may have.
 * @param maxExponent
 *            A normalized integer indicating the highest value that the
 *            exponent may have.
 * @return The canonical representation of <tt>value</tt>.
 * @throws IllegalArgumentException
 *             If the supplied value is not a legal floating point number.
 */
private static String normalizeFPNumber(String value, String minMantissa, String maxMantissa,
        String minExponent, String maxExponent) {
    value = collapseWhiteSpace(value);

    // handle special values
    if (value.equals("INF") || value.equals("-INF") || value.equals("NaN")) {
        return value;
    }

    // Search for the exponent character E or e
    int eIdx = value.indexOf('E');
    if (eIdx == -1) {
        // try lower case
        eIdx = value.indexOf('e');
    }

    // Extract mantissa and exponent
    String mantissa, exponent;
    if (eIdx == -1) {
        mantissa = normalizeDecimal(value);
        exponent = "0";
    } else {
        mantissa = normalizeDecimal(value.substring(0, eIdx));
        exponent = normalizeInteger(value.substring(eIdx + 1));
    }

    // Check lower and upper bounds, if applicable
    if (minMantissa != null) {
        if (compareCanonicalDecimals(mantissa, minMantissa) < 0) {
            throwIAE("Mantissa smaller than minimum value (" + minMantissa + ")");
        }
    }
    if (maxMantissa != null) {
        if (compareCanonicalDecimals(mantissa, maxMantissa) > 0) {
            throwIAE("Mantissa larger than maximum value (" + maxMantissa + ")");
        }
    }
    if (minExponent != null) {
        if (compareCanonicalIntegers(exponent, minExponent) < 0) {
            throwIAE("Exponent smaller than minimum value (" + minExponent + ")");
        }
    }
    if (maxExponent != null) {
        if (compareCanonicalIntegers(exponent, maxExponent) > 0) {
            throwIAE("Exponent larger than maximum value (" + maxExponent + ")");
        }
    }

    // Normalize mantissa to one non-zero digit before the dot
    int shift = 0;

    int dotIdx = mantissa.indexOf('.');
    int digitCount = dotIdx;
    if (mantissa.charAt(0) == '-') {
        digitCount--;
    }

    if (digitCount > 1) {
        // more than one digit before the dot, e.g 123.45, -10.0 or 100.0
        StringBuilder sb = new StringBuilder(mantissa.length());
        int firstDigitIdx = 0;
        if (mantissa.charAt(0) == '-') {
            sb.append('-');
            firstDigitIdx = 1;
        }
        sb.append(mantissa.charAt(firstDigitIdx));
        sb.append('.');
        sb.append(mantissa.substring(firstDigitIdx + 1, dotIdx));
        sb.append(mantissa.substring(dotIdx + 1));

        mantissa = sb.toString();

        // Check if the mantissa has excessive trailing zeros.
        // For example, 100.0 will be normalize to 1.000 and
        // -10.0 to -1.00.
        int nonZeroIdx = mantissa.length() - 1;
        while (nonZeroIdx >= 3 && mantissa.charAt(nonZeroIdx) == '0') {
            nonZeroIdx--;
        }

        if (nonZeroIdx < 3 && mantissa.charAt(0) == '-') {
            nonZeroIdx++;
        }

        if (nonZeroIdx < mantissa.length() - 1) {
            mantissa = mantissa.substring(0, nonZeroIdx + 1);
        }

        shift = 1 - digitCount;
    } else if (mantissa.startsWith("0.") || mantissa.startsWith("-0.")) {
        // Example mantissas: 0.0, -0.1, 0.00345 and 0.09
        // search first non-zero digit
        int nonZeroIdx = 2;
        while (nonZeroIdx < mantissa.length() && mantissa.charAt(nonZeroIdx) == '0') {
            nonZeroIdx++;
        }

        // 0.0 does not need any normalization:
        if (nonZeroIdx < mantissa.length()) {
            StringBuilder sb = new StringBuilder(mantissa.length());
            sb.append(mantissa.charAt(nonZeroIdx));
            sb.append('.');
            if (nonZeroIdx == mantissa.length() - 1) {
                // There was only one non-zero digit, e.g. as in 0.09
                sb.append('0');
            } else {
                sb.append(mantissa.substring(nonZeroIdx + 1));
            }

            mantissa = sb.toString();
            shift = nonZeroIdx - 1;
        }
    }

    if (shift != 0) {
        try {
            int exp = Integer.parseInt(exponent);
            exponent = String.valueOf(exp - shift);
        } catch (NumberFormatException e) {
            throw new RuntimeException("NumberFormatException: " + e.getMessage());
        }
    }

    return mantissa + "E" + exponent;
}

From source file:de.langerhans.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, double dogeBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*from  w  w w .  ja  va  2  s.  co  m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                final double btcRate = Double
                                        .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString());
                                DecimalFormat df = new DecimalFormat("#.########");
                                df.setRoundingMode(RoundingMode.HALF_UP);
                                DecimalFormatSymbols dfs = new DecimalFormatSymbols();
                                dfs.setDecimalSeparator('.');
                                dfs.setGroupingSeparator(',');
                                df.setDecimalFormatSymbols(dfs);
                                final Fiat dogeRate = Fiat.parseFiat(currencyCode,
                                        df.format(btcRate * dogeBtcConversion));

                                if (dogeRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TableContextUtil.java

public static String getPartitionSizeValidationError(int colType, String column, String partitionSize) {
    switch (colType) {
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
        try {/*from w  w  w  . j  a  v  a 2  s . com*/
            int intVal = Integer.parseInt(partitionSize);
            if (intVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.BIGINT:
        // TIME, DATE, and TIMESTAMP are represented as long (epoch)
    case Types.TIME:
    case Types.DATE:
    case Types.TIMESTAMP:
        try {
            long longVal = Long.parseLong(partitionSize);
            if (longVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.FLOAT:
    case Types.REAL:
        try {
            float floatVal = Float.parseFloat(partitionSize);
            if (floatVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.DOUBLE:
        try {
            double doubleVal = Double.parseDouble(partitionSize);
            if (doubleVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.NUMERIC:
    case Types.DECIMAL:
        try {
            BigDecimal decimalValue = new BigDecimal(partitionSize);
            if (decimalValue.signum() < 1) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    }
    return null;
}

From source file:com.basetechnology.s0.agentserver.util.JsonUtils.java

static public Value parseJson(String s) throws RuntimeException {
    if (s == null)
        return NullValue.one;
    String sTrim = s.trim();/*from w  w w .  j ava  2s.c  om*/
    int len = s.length();
    if (len == 0)
        return NullValue.one;
    char ch = len < 1 ? 0 : sTrim.charAt(0);
    try {
        if (ch == '[') {
            JSONArray arrayJson = new JSONArray(s);
            return convertJsonArray(arrayJson);
        } else if (ch == '{') {
            JSONObject objectJson = new JSONObject(s);
            return convertJsonObject(objectJson);
        } else {
            // Must be a simple Java object
            // Check for boolean
            if (s.equalsIgnoreCase("true"))
                return BooleanValue.create(true);
            else if (s.equalsIgnoreCase("false"))
                return BooleanValue.create(false);

            // Check for string
            if (len > 1 && s.charAt(0) == '"')
                return new StringValue(StringUtils.parseQuotedString(s));

            // Try for an integer
            try {
                long longInteger = Long.parseLong(s);
                return new IntegerValue(longInteger);
            } catch (NumberFormatException e) {
                // Try for a real number
                try {
                    double doubleFloat = Double.parseDouble(s);
                    return new FloatValue(doubleFloat);
                } catch (NumberFormatException e1) {
                    throw new RuntimeException(
                            "parseJson exception - string is not a valid JSON value: '" + s + "'");
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("parseJson exception: " + e.getMessage());
    }
}

From source file:com.cloudera.flume.conf.FlumeBuilder.java

/**
 * Build a flume source from a flume config specification.
 * //  w  ww . ja  v a  2s  . c  o m
 * This should only throw FlumeSpecExceptions (No illegal arg exceptions
 * anymore)
 */
public static EventSource buildSource(Context ctx, String s) throws FlumeSpecException {
    try {
        CommonTree srcTree = parseSource(s);
        return buildEventSource(ctx, srcTree);
    } catch (RecognitionException re) {
        LOG.debug("Failure to parse and instantiate sink: '" + s + "'", re);
        throw new FlumeSpecException(re.toString());
    } catch (NumberFormatException nfe) {
        LOG.debug("Failure to parse and instantiate sink: '" + s + "'", nfe);
        throw new FlumeSpecException(nfe.getMessage());
    } catch (IllegalArgumentException iae) {
        LOG.debug("Failure to parse and instantiate sink: '" + s + "'", iae);
        throw new FlumeSpecException(iae.getMessage());
    } catch (RuntimeRecognitionException re) {
        LOG.debug("Failure to parse and instantiate sink: '" + s + "'", re);
        throw new FlumeSpecException(re.getMessage());
    }
}