Example usage for java.lang NumberFormatException getLocalizedMessage

List of usage examples for java.lang NumberFormatException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.artemis.toolkit.table.gen.NoMoreDataException.java

public genDate(order iorder, int istep, String irange) {
    super(iorder, istep, irange);

    try {// www .j  av  a  2 s.  com
        mLowestValue = mDateFormat.parse("1970-01-01").getTime();
    } catch (ParseException e1) {
        // ignore
    }

    String lOption = mDataRange.getOption(0);
    if (lOption != null && lOption.length() > 0) {
        try {
            mLowestValue = mDateFormat.parse(lOption).getTime();
        } catch (NumberFormatException e) {
            LOG.warn(e.getLocalizedMessage());
        } catch (ParseException e) {
            LOG.warn(e.getLocalizedMessage());
        }
    }

    mBoundaryValue = (new Date()).getTime(); // today

    lOption = mDataRange.getOption(1);
    if (lOption != null && lOption.length() > 0) {
        try {
            mBoundaryValue = mDateFormat.parse(lOption).getTime();
        } catch (NumberFormatException e) {
            LOG.warn(e.getLocalizedMessage());
        } catch (ParseException e) {
            LOG.warn(e.getLocalizedMessage());
        }
    }

    mDurationValue = mBoundaryValue - mLowestValue;

    if (mOrder == analyticsops.order.Ascend) {
        mCalendar.setTimeInMillis(mLowestValue);
    } else if (mOrder == analyticsops.order.Descend) {
        mCalendar.setTimeInMillis(mBoundaryValue);
    }

}

From source file:org.signserver.web.GenericProcessServlet.java

private long getMaxUploadSize() {
    final String confValue = globalSession.getGlobalConfiguration()
            .getProperty(GlobalConfiguration.SCOPE_GLOBAL, HTTP_MAX_UPLOAD_SIZE);
    long result = MAX_UPLOAD_SIZE;
    if (confValue != null) {
        try {/*from   w w  w. j  a v a 2s. c o  m*/
            result = Long.parseLong(confValue);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Using " + HTTP_MAX_UPLOAD_SIZE + ": " + result);
            }
        } catch (NumberFormatException ex) {
            LOG.error("Incorrect value for global configuration property " + HTTP_MAX_UPLOAD_SIZE + ": "
                    + ex.getLocalizedMessage());
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Using default max upload size as no " + HTTP_MAX_UPLOAD_SIZE + " configured");
        }
    }
    return result;
}

From source file:org.apache.hadoop.fs.loadGenerator.LoadGenerator.java

/** Parse the command line arguments and initialize the data */
protected int parseArgs(boolean runAsMapReduce, String[] args) throws IOException {
    try {//  ww w .j  a v a 2s.  com
        for (int i = 0; i < args.length; i++) { // parse command line
            if (args[i].equals("-scriptFile")) {
                scriptFile = args[++i];
                if (durations[0] > 0) {
                    System.err.println("Can't specify elapsedTime and use script.");
                    return -1;
                }
            } else if (args[i].equals("-readProbability")) {
                if (scriptFile != null) {
                    System.err.println("Can't specify probabilities and use script.");
                    return -1;
                }
                readProbs[0] = Double.parseDouble(args[++i]);
                if (readProbs[0] < 0 || readProbs[0] > 1) {
                    System.err.println("The read probability must be [0, 1]: " + readProbs[0]);
                    return -1;
                }
            } else if (args[i].equals("-writeProbability")) {
                if (scriptFile != null) {
                    System.err.println("Can't specify probabilities and use script.");
                    return -1;
                }
                writeProbs[0] = Double.parseDouble(args[++i]);
                if (writeProbs[0] < 0 || writeProbs[0] > 1) {
                    System.err.println("The write probability must be [0, 1]: " + writeProbs[0]);
                    return -1;
                }
            } else if (args[i].equals("-root")) {
                root = new Path(args[++i]);
            } else if (args[i].equals("-maxDelayBetweenOps")) {
                maxDelayBetweenOps = Integer.parseInt(args[++i]); // in milliseconds
            } else if (args[i].equals("-numOfThreads")) {
                numOfThreads = Integer.parseInt(args[++i]);
                if (numOfThreads <= 0) {
                    System.err.println("Number of threads must be positive: " + numOfThreads);
                    return -1;
                }
            } else if (args[i].equals("-startTime")) {
                startTime = Long.parseLong(args[++i]);
            } else if (args[i].equals("-elapsedTime")) {
                if (scriptFile != null) {
                    System.err.println("Can't specify elapsedTime and use script.");
                    return -1;
                }
                durations[0] = Long.parseLong(args[++i]);
            } else if (args[i].equals("-seed")) {
                seed = Long.parseLong(args[++i]);
                r = new Random(seed);
            } else if (args[i].equals("-flagFile")) {
                LOG.info("got flagFile:" + flagFile);
                flagFile = new Path(args[++i]);
            } else {
                System.err.println(USAGE);
                ToolRunner.printGenericCommandUsage(System.err);
                return -1;
            }
        }
    } catch (NumberFormatException e) {
        System.err.println("Illegal parameter: " + e.getLocalizedMessage());
        System.err.println(USAGE);
        return -1;
    }

    // Load Script File if not MR; for MR scriptFile is loaded by Mapper
    if (!runAsMapReduce && scriptFile != null) {
        if (loadScriptFile(scriptFile, true) == -1)
            return -1;
    }

    for (int i = 0; i < readProbs.length; i++) {
        if (readProbs[i] + writeProbs[i] < 0 || readProbs[i] + writeProbs[i] > 1) {
            System.err.println("The sum of read probability and write probability must be [0, 1]: "
                    + readProbs[i] + " " + writeProbs[i]);
            return -1;
        }
    }
    return 0;
}

From source file:org.kalypso.wspwin.core.WspCfg.java

private IStatus readWspCfg(final File profDir, final Collection<ZustandBean> zustandBeans) {
    final File wspCfgFile = new File(profDir, WspWinFiles.WSP_CFG);

    try (LineNumberReader reader = new LineNumberReader(new FileReader(wspCfgFile))) {
        final String firstLine = reader.readLine();
        if (firstLine == null || firstLine.length() == 0)
            return new Status(IStatus.ERROR, KalypsoWspWinCorePlugin.PLUGIN_ID,
                    Messages.getString("org.kalypso.wspwin.core.WspCfg.1")); //$NON-NLS-1$

        // ignore the values, we read the count from the linecount
        // just parse the type
        final char type = firstLine.charAt(firstLine.length() - 1);
        setType(type);//from   w w  w.  j  a v  a  2  s.  c o m

        while (reader.ready()) {
            final String line = reader.readLine();
            if (line == null)
                break;

            final String trimmedLine = line.trim();
            if (trimmedLine.length() == 0 || trimmedLine.length() < 85)
                continue;

            try {
                final String waterName = trimmedLine.substring(0, 15).trim();
                final String name = trimmedLine.substring(15, 30).trim();
                // normally it should always be german, but it depends on the wspwin installation
                final DateFormat dateInstance = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT,
                        Locale.GERMAN);
                final String dateString = trimmedLine.substring(30, 41).trim();
                final Date date = dateInstance.parse(dateString);
                final BigDecimal start = new BigDecimal(trimmedLine.substring(41, 56).trim());
                final BigDecimal end = new BigDecimal(trimmedLine.substring(56, 71).trim());
                final String fileName = trimmedLine.substring(71).trim();

                final ZustandBean zustandBean = new ZustandBean(name, waterName, fileName, start, end, date);
                zustandBeans.add(zustandBean);
            } catch (final NumberFormatException e) {
                e.printStackTrace();
                throw new ParseException(
                        Messages.getString("org.kalypso.wspwin.core.WspCfg.3", reader.getLineNumber()), //$NON-NLS-1$
                        reader.getLineNumber());
            }
        }

        return Status.OK_STATUS;
    } catch (final ParseException | IOException e) {
        return new Status(IStatus.ERROR, KalypsoWspWinCorePlugin.PLUGIN_ID, e.getLocalizedMessage(), e);
    }
}

From source file:com.googlecode.jgenhtml.Config.java

/**
 * Set the user preference for expanding tab characters to spaces in source code view.
 * @param numSpaces The number of spaces tabs will be expanded to.
 *//*  w  ww  .  ja  v a  2s  .  co m*/
private void setNumSpaces(final String numSpaces) {
    try {
        int spaces = Integer.parseInt(numSpaces);
        setNumSpaces(spaces);
    } catch (NumberFormatException ex) {
        LOGGER.log(Level.WARNING, ex.getLocalizedMessage());
    }
}

From source file:com.googlecode.jgenhtml.Config.java

/**
 * Gets the value of a numeric option.//from w w w .  j  a v a 2 s.  c  o  m
 * @param properties The properties in which to search for the option
 * @param optName the name of the option to fetch
 * @return The value of the option if it is explicitly set
 * null if the option is not set
 */
private Integer getNumericValue(final Properties properties, final String optName) {
    Integer result = null;
    if (properties.containsKey(optName)) {
        try {
            int propval = Integer.parseInt(properties.getProperty(optName));
            result = propval;
        } catch (NumberFormatException ex) {
            LOGGER.log(Level.WARNING, "{0} {1}", new Object[] { optName, ex.getLocalizedMessage() });
        }
    }
    return result;
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WFSRequestHandler.java

public void writeResponse(DataWrapper data, User user) throws Exception {
    OGCResponse ogcresponse = getNewOGCResponse();
    OGCRequest ogcrequest = data.getOgcrequest();

    String version = ogcrequest.getFinalVersion();
    String spInUrl = ogcrequest.getServiceProviderName();

    Integer[] orgIds = user.getOrganizationIds();
    OutputStream os = data.getOutputStream();

    Object identity = null;//from w ww .  j  a  v a  2  s .  co  m
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        boolean forAdmin = isConfigInUrlAndAdmin(data, user);
        // zet layers uit request in een list
        List<LayerSummary> layerSummaryList = prepareRequestLayers(ogcrequest);
        if (layerSummaryList == null) {
            // als geen layers meegegeven, dan alle layers gebruiken
            // alleen bij getcapabilities
            EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
            String[] al = getOrganisationLayers(em, orgIds, version, forAdmin);
            layerSummaryList = LayerSummary.createLayerSummaryList(Arrays.asList(al), spInUrl, true);
        }

        // maak lijst waarin de layers per sp zijn verzameld
        // boolean om volgorde van de lagen te bewaren
        List<SpLayerSummary> spLayerSummaries = null;
        if (forAdmin) {
            spLayerSummaries = getLayerSummaries(layerSummaryList, spInUrl);
        } else {
            spLayerSummaries = getServiceProviderURLS(layerSummaryList, orgIds, false, data, false);
        }
        if (spLayerSummaries == null || spLayerSummaries.isEmpty()) {
            throw new UnsupportedOperationException(
                    "No Serviceprovider available! User might not have rights to any Serviceprovider!");
        }
        if (spLayerSummaries.size() > 1 && version.equals(OGCConstants.WFS_VERSION_UNSPECIFIED)) {
            // forceren dat alle sp dezelfde versie retourneren, indien meer dan 1
            ogcrequest.addOrReplaceParameter(OGCConstants.VERSION, OGCConstants.WFS_VERSION_110);
        }

        DataMonitoring rr = data.getRequestReporting();
        long startprocestime = System.currentTimeMillis();
        String xmlEncoding = "UTF-8";

        for (SpLayerSummary sp : spLayerSummaries) {
            if (spInUrl != null && !spInUrl.equals(sp.getSpAbbr())) {
                // sp in url en dit is een andere sp
                continue;
            }
            sp.setSpInUrl(spInUrl);

            // zet de juiste layers voor deze sp
            OGCRequest sprequest = (OGCRequest) ogcrequest.clone();
            prepareRequest4Sp(sprequest, sp);

            String lurl = sp.getSpUrl();
            if (lurl.length() == 0) {
                throw new UnsupportedOperationException("No Serviceprovider for this service available!");
            }
            ServiceProviderRequest wfsRequest = this.createServiceProviderRequest(data, lurl,
                    sp.getServiceproviderId(), 0l);

            B3PCredentials credentials = new B3PCredentials();
            credentials.setUserName(sp.getUsername());
            credentials.setPassword(sp.getPassword());
            credentials.setUrl(lurl);
            HttpClientConfigured hcc = new HttpClientConfigured(credentials);

            HttpUriRequest method = null;
            if (sprequest.getHttpMethod().equalsIgnoreCase("POST")) {
                method = createPostMethod(sprequest, sp, wfsRequest);
            } else { // get
                method = createGetMethod(sprequest, sp, wfsRequest);
            }

            try {
                HttpResponse response = hcc.execute(method);

                try {

                    int statusCode = response.getStatusLine().getStatusCode();
                    wfsRequest.setResponseStatus(statusCode);
                    HttpEntity entity = response.getEntity();

                    if (statusCode != 200) {
                        log.error("Failed to connect with " + method.getURI() + " Using body: "
                                + sprequest.getXMLBody());
                        throw new UnsupportedOperationException("Failed to connect with " + method.getURI()
                                + " Using body: " + sprequest.getXMLBody());
                    }

                    wfsRequest.setRequestResponseTime(System.currentTimeMillis() - startprocestime);

                    data.setContentType("text/xml");
                    InputStream is = entity.getContent();

                    InputStream isx = null;
                    byte[] bytes = null;
                    int rsl = 0;
                    try {
                        rsl = new Integer(KBConfiguration.RESPONSE_SIZE_LIMIT);
                    } catch (NumberFormatException nfe) {
                        log.debug("KBConfiguration.RESPONSE_SIZE_LIMIT not properly configured: "
                                + nfe.getLocalizedMessage());
                    }
                    if (KBConfiguration.SAVE_MESSAGES) {
                        int len = 1;
                        byte[] buffer = new byte[2024];
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = is.read(buffer, 0, buffer.length)) > 0) {
                            bos.write(buffer, 0, len);
                            if (buffer.length > rsl && rsl > 0) {
                                throw new ProviderException(
                                        "Response size exceeds maximum set in configuration:" + buffer.length
                                                + ", max is: " + rsl);
                            }
                        }
                        bytes = bos.toByteArray();
                        isx = new ByteArrayInputStream(bytes);
                    } else {
                        isx = new CountingInputStream(is);
                    }

                    if (KBConfiguration.SAVE_MESSAGES || spInUrl == null || !mayDirectWrite()) {
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        dbf.setNamespaceAware(true);
                        DocumentBuilder builder = dbf.newDocumentBuilder();
                        Document doc = builder.parse(isx);
                        // indien meerdere sp met verschillende encodings
                        // dan wint de laatste!
                        String docEncoding = doc.getXmlEncoding();
                        if (docEncoding != null) {
                            xmlEncoding = docEncoding;
                        }

                        int len = 0;
                        if (KBConfiguration.SAVE_MESSAGES) {
                            wfsRequest.setMessageReceived(new String(bytes));
                        } else {
                            len = new Integer(((CountingInputStream) isx).getCount());
                            wfsRequest.setBytesReceived(new Long(len));
                        }
                        if (len > rsl && rsl > 0) {
                            throw new ProviderException("Response size exceeds maximum set in configuration:"
                                    + len + ", max is: " + rsl);
                        }

                        String prefix = sp.getSpAbbr();
                        if (spInUrl != null && !spInUrl.isEmpty()) {
                            // sp in url dus geen prefix toevoegen
                            prefix = null;
                        }

                        if (OGCResponse.isWfsV100ErrorResponse(doc.getDocumentElement())) {
                            // wfs 1.0.0 error
                            ogcresponse.rebuildWfsV100ErrorResponse(doc, sprequest, prefix);
                        } else if (OGCResponse.isOwsV100ErrorResponse(doc.getDocumentElement())) {
                            // wfs 1.1.0 error
                            ogcresponse.rebuildOwsV100ErrorResponse(doc, sprequest, prefix);
                        } else {
                            // normale response
                            ogcresponse.rebuildResponse(doc, sprequest, prefix);
                        }
                    } else {
                        /**
                         * Deze methode kan alleen aangeroepen worden als
                         * aan de volgende voorwaarden is voldaan:
                         * <li> slechts n sp nodig voor aanroep
                         * <li> spabbr zit in de url en niet als prefix in
                         * de layer name
                         * <li> KBConfiguration.SAVE_MESSAGES is false Als
                         * aan voorwaarden is voldaan dat wordt direct
                         * doorgestreamd indien er geen fout is opgetreden.
                         * <li> de aanroep methode mayDirectWrite is true.
                         */
                        // direct write possible
                        byte[] h = prepareDirectWrite(isx);
                        if (h != null) {
                            os.write(h);
                        }
                        // write rest
                        IOUtils.copy(isx, os);
                        wfsRequest.setBytesReceived(new Long(((CountingInputStream) isx).getCount()));
                        ogcresponse.setAlreadyDirectWritten(true);
                        break;
                    }
                } finally {
                    hcc.close(response);
                    hcc.close();
                }

            } catch (Exception e) {
                wfsRequest.setExceptionMessage("Failed to send bytes to client: " + e.getMessage());
                wfsRequest.setExceptionClass(e.getClass());

                throw e;
            } finally {
                rr.addServiceProviderRequest(wfsRequest);
            }
        }

        // only write when not already direct written
        if (!ogcresponse.isAlreadyDirectWritten()) {
            String responseBody = ogcresponse.getResponseBody(spLayerSummaries, ogcrequest, xmlEncoding);
            if (responseBody != null && !responseBody.equals("")) {
                byte[] buffer = responseBody.getBytes(xmlEncoding);
                os.write(buffer);
            } else {
                throw new UnsupportedOperationException("XMLbody empty!");
            }
        }
        doAccounting(user.getMainOrganizationId(), data, user);

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}

From source file:com.hybris.mobile.app.commerce.fragment.ProductDetailFragmentBase.java

/**
 * Enable Add to cart button when text is entered in quantity field
 *//* w w w .  jav a2 s .  c om*/
protected void setClickableAddToCartButton() {
    boolean enable = false;

    if (CommerceApplication.isOnline()) {
        try {
            enable = (mQuantityEditText.getText() != null && !mQuantityEditText.getText().toString().isEmpty()
                    && StringUtils.isNotBlank(mQuantityEditText.getText().toString())
                    && Integer.parseInt(mQuantityEditText.getText().toString()) > 0) && mProduct != null
                    && !mProduct.isOutOfStock();
        } catch (NumberFormatException e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
    }
    // Offline we disable the add to cart and the quantity
    else {
        mQuantityEditText.setEnabled(false);
        enable = false;
    }

    enableAddToCartButton(enable);
}

From source file:pcgen.persistence.lst.BioSetLoader.java

@Override
public void parseLine(LoadContext context, String lstLine, URI sourceURI) {
    if (lstLine.startsWith("#")) {
        //Is a comment
        return;//  ww w.  j  a  va  2s  .  c o m
    }
    if (lstLine.startsWith("AGESET:")) {
        String line = lstLine.substring(7);
        int pipeLoc = line.indexOf('|');
        if (pipeLoc == -1) {
            Logging.errorPrint("Found invalid AGESET " + "in Bio Settings " + sourceURI
                    + ", was expecting a |: " + lstLine);
            return;
        }
        String ageIndexString = line.substring(0, pipeLoc);
        try {
            currentAgeSetIndex = Integer.parseInt(ageIndexString);
        } catch (NumberFormatException e) {
            Logging.errorPrint("Illegal Index for AGESET " + "in Bio Settings " + sourceURI + ": "
                    + ageIndexString + " was not an integer");
        }
        StringTokenizer colToken = new StringTokenizer(line.substring(pipeLoc + 1), SystemLoader.TAB_DELIM);
        AgeSet ageSet = new AgeSet();
        ageSet.setSourceURI(sourceURI);
        ageSet.setAgeIndex(currentAgeSetIndex);
        ageSet.setName(colToken.nextToken().intern());
        while (colToken.hasMoreTokens()) {
            try {
                LstUtils.processToken(context, ageSet, sourceURI, colToken.nextToken());
            } catch (PersistenceLayerException e) {
                Logging.errorPrint("Error in token parse: " + e.getLocalizedMessage());
            }
        }

        ageSet = bioSet.addToAgeMap(region, ageSet, sourceURI);
        Integer oldIndex = bioSet.addToNameMap(ageSet);
        if (oldIndex != null && oldIndex != currentAgeSetIndex) {
            Logging.errorPrint("Incompatible Index for AGESET " + "in Bio Settings " + sourceURI + ": "
                    + oldIndex + " and " + currentAgeSetIndex + " for " + ageSet.getDisplayName());
        }

    } else if (lstLine.startsWith("REGION:")) {
        region = Optional.of(Region.getConstant(lstLine.substring(7).intern()));
    } else if (lstLine.startsWith("RACENAME:")) {
        StringTokenizer colToken = new StringTokenizer(lstLine, SystemLoader.TAB_DELIM);
        String raceName = colToken.nextToken().substring(9).intern();
        List<String> preReqList = null;

        while (colToken.hasMoreTokens()) {
            String colString = colToken.nextToken();

            if (PreParserFactory.isPreReqString(colString)) {
                if (preReqList == null) {
                    preReqList = new ArrayList<>();
                }

                preReqList.add(colString);
            } else {
                String aString = colString;

                if (preReqList != null) {
                    final StringBuilder sBuf = new StringBuilder(100 + colString.length());
                    sBuf.append(colString);

                    for (String aPreReqList : preReqList) {
                        sBuf.append('[').append(aPreReqList).append(']');
                    }

                    aString = sBuf.toString();
                }

                bioSet.addToUserMap(region, raceName, aString.intern(), currentAgeSetIndex);
            }
        }
    } else if (!StringUtils.isEmpty(lstLine)) {
        Logging.errorPrint("Unable to process line " + lstLine + "in Bio Settings " + sourceURI);
    }
}

From source file:com.hybris.mobile.app.commerce.fragment.ProductDetailFragmentBase.java

protected void addToCart() {
    try {//w w w .  j ava  2  s. c o  m
        int quantity = Integer.parseInt(mQuantityEditText.getText().toString());

        CartHelperBase.addToCart(getActivity(), mProductDetailRequestId, new OnAddToCart() {

            @Override
            public void onAddToCart(CartModification productAdded) {

                if (productAdded.isOutOfStock()) {
                    enableAddToCartButton(false);
                } else if (productAdded.isQuantityAddedNotFulfilled()) {
                    mQuantityEditText.setText(productAdded.getQuantityAdded() + "");
                } else {
                    mQuantityEditText.setText(getString(R.string.default_qty));
                }

                UIUtils.hideKeyboard(getActivity());

            }

            @Override
            public void onAddToCartError(boolean isOutOfStock) {
                mQuantityEditText.setBackgroundResource(R.drawable.quantity_editext_invalid);
                enableAddToCartButton(!isOutOfStock);
                UIUtils.hideKeyboard(getActivity());
            }

        }, mProduct.getCode(), quantity, Arrays.asList(mAddToCartButton, mProductDetailAddToCartText), null);

    } catch (NumberFormatException e) {
        Log.e(TAG, e.getLocalizedMessage());
    }
}