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:esg.common.Utils.java

/**
   In an attempt to be a bit more efficient.  If there is a lot of
   comparing that needs to be done it is better to pass in
   matchers, rather than have the matchers be instantiated by the
   Pattern every time a comparison is done.  Matchers are not
   thread safe therefore this method is NOT thread safe.  So be
   aware.  If in doubt call the other version of this method.
        //from w ww  .jav  a2s .  co  m
   @param candidate the first version value to compare
   @param c_matcher a Matcher object from a Pattern that knows how to tokenize the version values
   @param reference the second version value to compare
   @param r_matcher a Matcher object from a Pattern that knows how to tokenize the version values
   @throws InvalideVersionStringException runtime exception thrown when a value cannot be numerically parsed.
   @return 1 if candidate > reference; -1 if candidate < reference; 0 if candidate = refernece;
 */
public static int versionCompare(String candidate, Matcher c_matcher, String reference, Matcher r_matcher)
        throws esg.common.InvalidVersionStringException {
    c_matcher.reset(candidate);
    r_matcher.reset(reference);

    int c, r = 0;
    try {
        while (c_matcher.find() && r_matcher.find()) {
            c = Integer.parseInt(c_matcher.group(1));
            r = Integer.parseInt(r_matcher.group(1));

            //log.trace("Comparing "+c+" and "+r);
            if (c > r)
                return 1;
            else if (c < r)
                return -1;
        }

        //When version positions don't line up...
        int c_len = candidate.length();
        int r_len = reference.length();
        //log.trace("candidate length = "+c_len);
        //log.trace("reference length = "+r_len);
        if (c_len > r_len) {
            c_matcher.reset(candidate.substring(r_len));
            while (c_matcher.find()) {
                if (Integer.parseInt(c_matcher.group(1)) > 0) {
                    return 1;
                }
            }
        }
        if (c_len < r_len) {
            r_matcher.reset(reference.substring(c_len));
            while (r_matcher.find()) {
                if (Integer.parseInt(r_matcher.group(1)) > 0) {
                    return -1;
                }
            }
        }
        return 0;
    } catch (NumberFormatException e) {
        log.error("Improper version string! " + e.getMessage());
        throw new InvalidVersionStringException(e);
    } catch (Exception e) {
        log.error("Improper version string! " + e.getMessage());
        throw new InvalidVersionStringException(e);
    }
}

From source file:controllers.api.v1.Metric.java

public static Result getPagedMetricsByDashboardandGroup(String dashboardName, String group) {

    ObjectNode result = Json.newObject();
    String username = session("user");

    int page = 1;
    String pageStr = request().getQueryString("page");
    if (StringUtils.isBlank(pageStr)) {
        page = 1;/*from   ww w  .j av a  2 s. co m*/
    } else {
        try {
            page = Integer.parseInt(pageStr);
        } catch (NumberFormatException e) {
            Logger.warn(
                    "Metric Controller getPagedMetricsByDashboardandGroup wrong page parameter. Error message: "
                            + e.getMessage());
            page = 1;
        }
    }

    int size = 10;
    String sizeStr = request().getQueryString("size");
    if (StringUtils.isBlank(sizeStr)) {
        size = 10;
    } else {
        try {
            size = Integer.parseInt(sizeStr);
        } catch (NumberFormatException e) {
            Logger.warn(
                    "Metric Controller getPagedMetricsByDashboardandGroup wrong size parameter. Error message: "
                            + e.getMessage());
            size = 10;
        }
    }

    result.put("status", "ok");
    result.set("data", MetricsDAO.getPagedMetrics(dashboardName, group, page, size, username));
    return ok(result);
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API for creating connection to ftp server.
 * //from  w  w w .j a v  a  2s.  c o  m
 * @param client {@link FTPClient} the ftp client instance
 * @throws SocketException generate if any error occurs while making the connection.
 * @throws IOException generate if any error occur while making the connection.
 */
public static void createConnection(final FTPClient client, final String ftpServerURL, final String ftpUsername,
        final String ftpPassword, final String ftpDataTimeOut) throws SocketException, IOException {
    client.connect(ftpServerURL);
    client.login(ftpUsername, ftpPassword);
    try {
        int ftpDataTimeOutLocal = Integer.parseInt(ftpDataTimeOut);
        client.setDataTimeout(ftpDataTimeOutLocal);
    } catch (NumberFormatException e) {
        LOGGER.error(EphesoftStringUtil.concatenate("Error occuring in converting ftpDataTimeOut :",
                e.getMessage(), e));
    }
}

From source file:com.evozon.evoportal.my_account.util.MyAccountUtil.java

public static int getIntValue(String field) {
    int result = 0;
    try {//  w w  w . jav a 2s  . c  o m
        result = Integer.parseInt(field);
    } catch (NumberFormatException e) {
        result = -1;
        logger.warn(e.getMessage());
    }
    return result;
}

From source file:com.twitter.hraven.etl.JobHistoryFileParserBase.java

/**
 * fetches the submit time from a raw job history byte representation
 * @param jobHistoryRaw from which to pull the SUBMIT_TIME
 * @return the job submit time in milliseconds since January 1, 1970 UTC;
 *         or 0 if no value can be found.
 *//*from ww w.  j  a va2 s. c  o  m*/
public static long getSubmitTimeMillisFromJobHistory(byte[] jobHistoryRaw) {

    long submitTimeMillis = 0;
    if (null == jobHistoryRaw) {
        return submitTimeMillis;
    }

    HadoopVersion hv = JobHistoryFileParserFactory.getVersion(jobHistoryRaw);

    switch (hv) {
    case TWO:
        // look for the job submitted event, since that has the job submit time
        int startIndex = ByteUtil.indexOf(jobHistoryRaw, Constants.JOB_SUBMIT_EVENT_BYTES, 0);
        if (startIndex != -1) {
            // now look for the submit time in this event
            int secondQuoteIndex = ByteUtil.indexOf(jobHistoryRaw, Constants.SUBMIT_TIME_PREFIX_HADOOP2_BYTES,
                    startIndex);
            if (secondQuoteIndex != -1) {
                // read the string that contains the unix timestamp
                String submitTimeMillisString = Bytes.toString(jobHistoryRaw,
                        secondQuoteIndex + Constants.EPOCH_TIMESTAMP_STRING_LENGTH,
                        Constants.EPOCH_TIMESTAMP_STRING_LENGTH);
                try {
                    submitTimeMillis = Long.parseLong(submitTimeMillisString);
                } catch (NumberFormatException nfe) {
                    LOG.error(" caught NFE during conversion of submit time " + submitTimeMillisString + " "
                            + nfe.getMessage());
                    submitTimeMillis = 0;
                }
            }
        }
        break;

    case ONE:
    default:
        // The start of the history file looks like this:
        // Meta VERSION="1" .
        // Job JOBID="job_20120101120000_12345" JOBNAME="..."
        // USER="username" SUBMIT_TIME="1339063492288" JOBCONF="

        // First we look for the first occurrence of SUBMIT_TIME="
        // Then we find the place of the next close quote "
        // Then our value is in between those two if valid at all.

        startIndex = ByteUtil.indexOf(jobHistoryRaw, Constants.SUBMIT_TIME_PREFIX_BYTES, 0);
        if (startIndex != -1) {
            int prefixEndIndex = startIndex + Constants.SUBMIT_TIME_PREFIX_BYTES.length;

            // Find close quote in the snippet, start looking where the prefix ends.
            int secondQuoteIndex = ByteUtil.indexOf(jobHistoryRaw, Constants.QUOTE_BYTES, prefixEndIndex);
            if (secondQuoteIndex != -1) {
                int numberLength = secondQuoteIndex - prefixEndIndex;
                String submitTimeMillisString = Bytes.toString(jobHistoryRaw, prefixEndIndex, numberLength);
                try {
                    submitTimeMillis = Long.parseLong(submitTimeMillisString);
                } catch (NumberFormatException nfe) {
                    LOG.error(" caught NFE during conversion of submit time " + submitTimeMillisString + " "
                            + nfe.getMessage());
                    submitTimeMillis = 0;
                }
            }
        }
        break;
    }

    return submitTimeMillis;
}

From source file:de.sub.goobi.forms.ModuleServerForm.java

/**
 * get Prozess von shortSessionID./*ww  w . j  a  v a  2s.c o m*/
 */
public static Process getProcessFromShortSession(String sessionId) throws GoobiException {
    String prozessidStr = getProcessIDFromShortSession(sessionId);
    try {
        Process tempProz = serviceManager.getProcessService().getById(Integer.parseInt(prozessidStr));
        Helper.getHibernateSession().flush();
        Helper.getHibernateSession().clear();
        if (tempProz != null && tempProz.getId() != null) {
            Helper.getHibernateSession().refresh(tempProz);
        }

        return tempProz;
    } catch (NumberFormatException e) {
        throw new GoobiException(5, "******** wrapped NumberFormatException ********: " + e.getMessage() + "\n"
                + Helper.getStacktraceAsString(e));
    } catch (DAOException e) {
        throw new GoobiException(1400, "******** wrapped DAOException ********: " + e.getMessage() + "\n"
                + Helper.getStacktraceAsString(e));
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.webcrawler.CookieManager.java

/** Convert a string to a port array.
*///ww  w .ja v  a  2s.  c o m
protected static int[] stringToPorts(String value) throws ManifoldCFException {
    String[] ports = value.split(",");
    int[] rval = new int[ports.length];
    int i = 0;
    while (i < rval.length) {
        try {
            rval[i] = Integer.parseInt(ports[i]);
        } catch (NumberFormatException e) {
            throw new ManifoldCFException(e.getMessage(), e);
        }
        i++;
    }
    return rval;
}

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

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

    HttpURLConnection connection = null;
    Reader reader = null;//www  .  j a va2s . 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 rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final Fiat rate = Fiat.parseFiat(currencyCode, rateStr);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new org.bitcoinj.utils.ExchangeRate(rate), 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:eu.riscoss.RemoteRiskAnalyser.java

static RiskDataAndErrors getRiskDataFromRequest(RiskAnalysisEngine riskAnalysisEngine,
        Map<String, String[]> requestParams) {
    Map<String, Object> riskData = new HashMap<String, Object>();
    Map<String, String> errors = new HashMap<String, String>();

    Iterable<Chunk> chunks = riskAnalysisEngine.queryModel(ModelSlice.INPUT_DATA);
    for (Chunk chunk : chunks) {
        Field field = riskAnalysisEngine.getField(chunk, FieldType.INPUT_VALUE);
        try {/*from w w  w .  j ava 2  s.co m*/

            String[] values = requestParams.get(chunk.getId());

            switch (field.getDataType()) {
            case INTEGER:
                int i = 0;

                if (values != null && !values[0].isEmpty()) {
                    i = Integer.parseInt(values[0]);
                }

                riskData.put(chunk.getId(), i);
                break;
            case REAL:
                double d = 0.0d;

                if (values != null && !values[0].isEmpty()) {
                    d = Double.parseDouble(values[0]);
                }

                riskData.put(chunk.getId(), d);
                break;
            case EVIDENCE:
                if (values != null && values.length == 2) {
                    double p = 0.0;
                    double n = 0.0;

                    if (!values[0].isEmpty()) {
                        p = Double.parseDouble(values[0]);
                    }

                    if (!values[1].isEmpty()) {
                        n = Double.parseDouble(values[1]);
                    }

                    Evidence evidence = new Evidence(p, n);
                    riskData.put(chunk.getId(), evidence);
                } else {
                    errors.put(chunk.getId(), "Two values are required");
                }
                break;
            case DISTRIBUTION:
                List<Double> distributionValues = new ArrayList<Double>();
                if (values != null) {
                    for (String v : values) {
                        if (!v.isEmpty()) {
                            distributionValues.add(Double.parseDouble(v));
                        } else {
                            distributionValues.add(0.0d);
                        }
                    }
                } else {
                    for (int n = 0; n < ((Distribution) field.getValue()).getValues().size(); n++) {
                        distributionValues.add(0.0d);
                    }
                }

                Distribution distribution = new Distribution();
                distribution.setValues(distributionValues);
                riskData.put(chunk.getId(), distribution);
                break;
            case STRING:
                riskData.put(chunk.getId(), values[0]);
                break;
            }
        } catch (NumberFormatException e) {
            errors.put(chunk.getId(), String.format("Invalid number format for %s", field.getDataType()));
        } catch (Exception e) {
            errors.put(chunk.getId(), e.getMessage());
        }
    }

    RiskDataAndErrors result = new RiskDataAndErrors();
    result.riskData = riskData;
    result.errors = errors;

    return result;
}

From source file:eu.stratosphere.nephele.instance.HardwareDescriptionFactory.java

/**
 * Returns the size of the physical memory in bytes on a Linux-based
 * operating system./*from   w  w w.ja  va2 s .c o m*/
 * 
 * @return the size of the physical memory in bytes or <code>-1</code> if
 *         the size could not be determined
 */
@SuppressWarnings("resource")
private static long getSizeOfPhysicalMemoryForLinux() {
    BufferedReader lineReader = null;
    try {
        lineReader = new BufferedReader(new FileReader(LINUX_MEMORY_INFO_PATH));

        String line = null;
        while ((line = lineReader.readLine()) != null) {
            Matcher matcher = LINUX_MEMORY_REGEX.matcher(line);
            if (matcher.matches()) {
                String totalMemory = matcher.group(1);
                return Long.parseLong(totalMemory) * 1024L; // Convert from kilobyte to byte
            }
        }

        // expected line did not come
        LOG.error("Cannot determine the size of the physical memory using '/proc/meminfo'. Unexpected format.");
        return -1;
    } catch (NumberFormatException e) {
        LOG.error("Cannot determine the size of the physical memory using '/proc/meminfo'. Unexpected format.");
        return -1;
    } catch (IOException e) {
        LOG.error("Cannot determine the size of the physical memory using '/proc/meminfo': " + e.getMessage(),
                e);
        return -1;
    } finally {
        // Make sure we always close the file handle
        try {
            if (lineReader != null) {
                lineReader.close();
            }
        } catch (Throwable t) {
        }
    }
}