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:de.steilerdev.myVerein.server.controller.init.InitController.java

License:asdf

/**
 * This function is temporarily saving the general settings during the initial setup. The values are stored permanently after calling the initSuperAdmin function. This function is invoked by POSTing the parameters to the URI /api/init/settings.
 * @param clubName The name of the club.
 * @param databaseHost The hostname of the MongoDB server (Default localhost).
 * @param databasePort The port of the MongoDB server (Default 27017).
 * @param databaseUser The user used to authenticate against the MongoDB server (may be empty if not needed).
 * @param databasePassword The password used to authenticate against the MongoDB server (may be empty if not needed).
 * @param databaseCollection The name of the database collection (Default myVerein).
 * @param locale The current locale of the user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 *///  www.  j  ava  2  s .  com
@RequestMapping(value = "settings", method = RequestMethod.POST)
public ResponseEntity<String> initSettings(@RequestParam String clubName, @RequestParam String databaseHost,
        @RequestParam String databasePort, @RequestParam String databaseUser,
        @RequestParam String databasePassword, @RequestParam String databaseCollection, Locale locale) {
    logger.trace("Starting initial settings configuration");
    Settings settings = new Settings();
    if (!settings.isInitialSetup()) {
        logger.warn("An initial setup API was used, even though the system is already configured.");
        return new ResponseEntity<>(
                messageSource.getMessage("init.message.settings.notAllowed", null,
                        "You are not allowed to perform this action at the moment", locale),
                HttpStatus.BAD_REQUEST);
    } else if (clubName.isEmpty()) {
        logger.warn("The club name is not present");
        return new ResponseEntity<>(messageSource.getMessage("init.message.settings.noName", null,
                "The club name is required", locale), HttpStatus.BAD_REQUEST);
    } else {
        int databasePortInt = 27017;
        if (databaseHost.isEmpty()) {
            logger.warn("The database host is empty, using default value.");
            databaseHost = "localhost";
        }
        if (databasePort.isEmpty()) {
            logger.warn("The database port is empty, using default value.");
            databasePort = "27017";
        } else {
            try {
                databasePortInt = Integer.parseInt(databasePort);
            } catch (NumberFormatException e) {
                logger.warn("The database port does not seem to be a number " + databasePort + ", "
                        + e.getMessage());
                return new ResponseEntity<>(messageSource.getMessage("init.message.settings.dbPortNoNumber",
                        null, "The database port needs to be a number", locale), HttpStatus.BAD_REQUEST);
            }
        }
        if (databaseCollection.isEmpty()) {
            logger.warn("The database collection name is empty, using default value");
            databaseCollection = "myVerein";
        }

        if (!mongoIsAvailable(databaseHost, databasePortInt, databaseUser, databasePassword,
                databaseCollection)) {
            logger.warn("The stated MongoDB is not available");
            return new ResponseEntity<>(messageSource.getMessage("init.message.settings.mongoNotAvailable",
                    null, "The stated MongoDB is not available", locale), HttpStatus.BAD_REQUEST);
        }

        try {
            logger.debug("Temporarily storing settings information");
            settings.setClubName(clubName);
            settings.setDatabaseHost(databaseHost);
            settings.setDatabasePort(databasePort);
            settings.setDatabaseUser(databaseUser);
            settings.setDatabasePassword(databasePassword);
            settings.setDatabaseName(databaseCollection);
            databaseName = databaseCollection;
            savingInitialSetup(null, null, settings);
        } catch (IOException e) {
            logger.warn("Unable to save settings.");
            return new ResponseEntity<>(
                    messageSource.getMessage("init.message.settings.savingSettingsError", null,
                            "Unable to save settings, please try again", locale),
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
        logger.info("Successfully stored and validated settings information");
        return new ResponseEntity<>(messageSource.getMessage("init.message.settings.savingSettingsSuccess",
                null, "Successfully saved settings", locale), HttpStatus.OK);
    }
}

From source file:com.impetus.kundera.validation.rules.AttributeConstraintRule.java

/**
 * Checks whether a given value is a valid maximum decimal digit when compared to given value 
 * or not/*from w w w . jav  a 2 s .com*/
 * 
 * @param validationObject
 * @param annotate
 * @return
 */
private boolean validateMaxDecimal(Object validationObject, Annotation annotate) {
    if (validationObject != null) {
        try {
            if (checkvalidDeciDigitTypes(validationObject.getClass())) {
                BigDecimal maxValue = NumberUtils.createBigDecimal(((DecimalMax) annotate).value());
                BigDecimal actualValue = NumberUtils.createBigDecimal(toString(validationObject));
                int res = actualValue.compareTo(maxValue);
                if (res > 0) {
                    throwValidationException(((DecimalMax) annotate).message());
                }

            }
        } catch (NumberFormatException nfe) {
            throw new RuleValidationException(nfe.getMessage());
        }

    }
    return true;
}

From source file:com.impetus.kundera.validation.rules.AttributeConstraintRule.java

/**
 * Checks whether a given value is a valid minimum decimal digit when compared to given value 
 * or not//from ww w  .  j  av a 2 s  .  co m
 * 
 * @param validationObject
 * @param annotate
 * @return
 */
private boolean validateMinDecimal(Object validationObject, Annotation annotate) {

    if (validationObject != null) {
        try {
            if (checkvalidDeciDigitTypes(validationObject.getClass())) {
                BigDecimal minValue = NumberUtils.createBigDecimal(((DecimalMin) annotate).value());
                BigDecimal actualValue = NumberUtils.createBigDecimal(toString(validationObject));
                int res = actualValue.compareTo(minValue);
                if (res < 0) {
                    throwValidationException(((DecimalMin) annotate).message());
                }

            }
        } catch (NumberFormatException nfe) {
            throw new RuleValidationException(nfe.getMessage());
        }

    }

    return true;
}

From source file:dk.dma.ais.abnormal.analyzer.AbnormalAnalyzerAppModule.java

private List<BoundingBox> parseGeoMaskXmlInputStream(InputStream is) {
    List<BoundingBox> boundingBoxes = new ArrayList<>();
    try {/*  w  ww  .j ava 2s.c  om*/
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = documentBuilder.parse(is);
        document.normalizeDocument();
        final NodeList areaPolygons = document.getElementsByTagName("area_polygon");
        final int numAreaPolygons = areaPolygons.getLength();
        for (int i = 0; i < numAreaPolygons; i++) {
            Node areaPolygon = areaPolygons.item(i);
            LOG.debug(
                    "XML reading area_polygon " + areaPolygon.getAttributes().getNamedItem("name").toString());
            NodeList polygons = areaPolygon.getChildNodes();
            int numPolygons = polygons.getLength();
            for (int p = 0; p < numPolygons; p++) {
                Node polygon = polygons.item(p);
                if (polygon instanceof Element) {
                    NodeList items = polygon.getChildNodes();
                    int numItems = items.getLength();
                    BoundingBox boundingBox = null;
                    try {
                        for (int j = 0; j < numItems; j++) {
                            Node item = items.item(j);
                            if (item instanceof Element) {
                                final double lat = Double
                                        .parseDouble(item.getAttributes().getNamedItem("lat").getNodeValue());
                                final double lon = Double
                                        .parseDouble(item.getAttributes().getNamedItem("lon").getNodeValue());
                                if (boundingBox == null) {
                                    boundingBox = BoundingBox.create(Position.create(lat, lon),
                                            Position.create(lat, lon), CoordinateSystem.CARTESIAN);
                                } else {
                                    boundingBox = boundingBox.include(Position.create(lat, lon));
                                }
                            }
                        }
                        LOG.info("Blocking messages in bbox "
                                + areaPolygon.getAttributes().getNamedItem("name").toString() + ": "
                                + boundingBox.toString() + " "
                                + (boundingBox.getMaxLat() - boundingBox.getMinLat()) + " "
                                + (boundingBox.getMaxLon() - boundingBox.getMinLon()));
                        boundingBoxes.add(boundingBox);
                    } catch (NumberFormatException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }

    return boundingBoxes;
}

From source file:com.pivotal.gemfire.tools.pulse.internal.controllers.PulseController.java

@RequestMapping(value = "/dataBrowserQuery", method = RequestMethod.GET)
public void dataBrowserQuery(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // get query string
    String query = request.getParameter("query");
    String members = request.getParameter("members");
    int limit = 0;

    try {//from ww  w .  java 2 s . c  o m
        limit = Integer.valueOf(request.getParameter("limit"));
    } catch (NumberFormatException e) {
        limit = 0;
        if (LOGGER.finerEnabled()) {
            LOGGER.finer(e.getMessage());
        }
    }

    JSONObject queryResult = new JSONObject();
    try {

        if (StringUtils.isNotNullNotEmptyNotWhiteSpace(query)) {
            // get cluster object
            Cluster cluster = Repository.get().getCluster();
            String userName = request.getUserPrincipal().getName();

            // Call execute query method
            queryResult = cluster.executeQuery(query, members, limit);

            // Add query in history if query is executed successfully
            if (!queryResult.has("error")) {
                // Add query to history
                cluster.addQueryInHistory(query, userName);
            }
        }
    } catch (JSONException eJSON) {
        LOGGER.logJSONError(eJSON, new String[] { "queryResult:" + queryResult });
    } catch (Exception e) {
        if (LOGGER.fineEnabled()) {
            LOGGER.fine("Exception Occured : " + e.getMessage());
        }
    }

    response.getOutputStream().write(queryResult.toString().getBytes());
}

From source file:com.ge.predix.sample.blobstore.repository.BlobstoreService.java

/**
 * Get the Blob from the binded bucket//  w  w  w.  j  a v  a  2s. c om
 *
 * @param fileName String
 * @throws Exception
 */
public InputStream get(String fileName, String range) throws Exception {

    if (range != null && !range.isEmpty()) {
        String[] r = range.split(":");
        if (r.length != 2) {
            throw new Exception("Invalid range format");
        }

        try {
            long start = Long.parseLong(r[0]);
            long end = Long.parseLong(r[1]);

            GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucket, fileName);
            rangeObjectRequest.setRange(start, end);
            S3Object objectPortion = s3Client.getObject(rangeObjectRequest);

            InputStream objectData = objectPortion.getObjectContent();

            return objectData;

        } catch (NumberFormatException e) {
            throw new Exception("Invalid range specified ", e);
        }
    } else {
        try {
            S3Object object = s3Client.getObject(new GetObjectRequest(bucket, fileName));
            InputStream objectData = object.getObjectContent();

            return objectData;

        } catch (Exception e) {
            log.error("Exception Occurred in get(): " + e.getMessage());
            throw e;
        }
    }

}

From source file:com.ibm.jaggr.core.impl.transport.RequestedModuleNames.java

/**
 * @param request//from w  w  w . j  av  a  2 s .com
 *            the HTTP request object
 * @param idList
 *            list of module names used for module name id encoding
 * @param idListHash
 *            hash of the idList - used to validate encoding of requests
 * @throws IOException
 */
RequestedModuleNames(HttpServletRequest request, List<String> idList, byte[] idListHash) throws IOException {
    final String sourceMethod = "<ctor>"; //$NON-NLS-1$
    if (isTraceLogging) {
        log.entering(RequestedModuleNames.class.getName(), sourceMethod,
                new Object[] { request.getQueryString(), "<omitted>", TypeUtil.byteArray2String(idListHash) }); //$NON-NLS-1$
    }
    this.idList = idList;
    this.idListHash = idListHash;
    moduleQueryArg = request.getParameter(AbstractHttpTransport.REQUESTEDMODULES_REQPARAM);
    moduleIdsQueryArg = request.getParameter(AbstractHttpTransport.REQUESTEDMODULEIDS_REQPARAM);
    String countParam = request.getParameter(AbstractHttpTransport.REQUESTEDMODULESCOUNT_REQPARAM);
    if (moduleQueryArg == null)
        moduleQueryArg = ""; //$NON-NLS-1$
    if (moduleIdsQueryArg == null)
        moduleIdsQueryArg = ""; //$NON-NLS-1$
    try {
        if (countParam != null) {
            count = Integer
                    .parseInt(request.getParameter(AbstractHttpTransport.REQUESTEDMODULESCOUNT_REQPARAM));
            // put a reasonable upper limit on the value of count
            if (count < 1 || count > AbstractHttpTransport.REQUESTED_MODULES_MAX_COUNT) {
                throw new BadRequestException("count:" + count); //$NON-NLS-1$
            }
        }
        try {
            moduleQueryArg = URLDecoder.decode(moduleQueryArg, "UTF-8"); //$NON-NLS-1$
        } catch (UnsupportedEncodingException e) {
            throw new BadRequestException(e.getMessage());
        }

        if (count > 0) {
            // Defer decoding the module list from the request until it is asked for.
            // For now, just set the value returned by toString().
            strRep = moduleQueryArg
                    + ((moduleQueryArg.length() > 0 && moduleIdsQueryArg.length() > 0) ? ":" : "") //$NON-NLS-1$//$NON-NLS-2$
                    + moduleIdsQueryArg;
        } else if (moduleQueryArg.length() > 0) {
            // Hand crafted URL; get module names from one or more module query args (deprecated)
            scripts = Collections.unmodifiableList(Arrays.asList(moduleQueryArg.split("\\s*,\\s*", 0))); //$NON-NLS-1$
            modules = Collections.emptyList();
            // Set request attribute to warn about use of deprecated param
            IAggregator aggr = (IAggregator) request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
            if (aggr.getOptions().isDebugMode() || aggr.getOptions().isDevelopmentMode()) {
                request.setAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_MODULES_QUERYARG,
                        Boolean.TRUE);
            }
        }
    } catch (NumberFormatException ex) {
        throw new BadRequestException(ex.getMessage(), ex);
    }
    // Get the deprecated require list
    @SuppressWarnings("deprecation")
    List<String> required = getNameListFromQueryArg(request, AbstractHttpTransport.REQUIRED_REQPARAM);
    if (required != null) {
        deps = required;
        // Log console warning about deprecated query arg if in debug/dev mode
        IAggregator aggr = (IAggregator) request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
        if (aggr.getOptions().isDebugMode() || aggr.getOptions().isDevelopmentMode()) {
            request.setAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_REQUIRED_QUERYARG, Boolean.TRUE);
        }
    }

    // Get the scripts list
    List<String> names = getNameListFromQueryArg(request, AbstractHttpTransport.SCRIPTS_REQPARAM);
    if (names != null) {
        if (moduleQueryArg.length() != 0 || required != null) {
            throw new BadRequestException(request.getQueryString());
        }
        scripts = Collections.unmodifiableList(names);
    }
    names = getNameListFromQueryArg(request, AbstractHttpTransport.DEPS_REQPARAM);
    if (names != null) {
        if (moduleQueryArg.length() != 0 || required != null) {
            throw new BadRequestException(request.getQueryString());
        }
        deps = Collections.unmodifiableList(names);
    }
    names = getNameListFromQueryArg(request, AbstractHttpTransport.PRELOADS_REQPARAM);
    if (names != null) {
        if (moduleQueryArg.length() != 0 || required != null) {
            throw new BadRequestException(request.getQueryString());
        }
        preloads = Collections.unmodifiableList(names);
    }
    if (isTraceLogging) {
        log.exiting(RequestedModuleNames.class.getName(), sourceMethod, this);
    }
}

From source file:net.duckling.ddl.web.controller.LynxEditPageController.java

private int getRequestVersion(HttpServletRequest request) {
    String version = request.getParameter("version");
    if (version != null) {
        try {/*from w  ww .  jav a2  s.  c om*/
            return Integer.parseInt(version);
        } catch (NumberFormatException e) {
            LOG.warn(e.getMessage());
        }
    }
    return VWBContext.LATEST_VERSION;
}

From source file:com.hp.mqm.clt.CliParser.java

public Settings parse(String[] args) {
    Settings settings = new Settings();
    CommandLineParser parser = new DefaultParser();
    try {/*from   w w w.j  a v a2  s.  co m*/
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            printHelp();
            System.exit(ReturnCode.SUCCESS.getReturnCode());
        }

        if (cmd.hasOption("v")) {
            printVersion();
            System.exit(ReturnCode.SUCCESS.getReturnCode());
        }

        if (!areCmdArgsValid(cmd)) {
            printHelp();
            System.exit(ReturnCode.FAILURE.getReturnCode());
        }

        if (!addInputFilesToSettings(cmd, settings)) {
            printHelp();
            System.exit(ReturnCode.FAILURE.getReturnCode());
        }

        // load config
        String filename = null;
        if (cmd.hasOption("c")) {
            filename = cmd.getOptionValue("c");
        }
        try {
            settings.load(filename);
        } catch (NumberFormatException e) {
            System.out.println("Can not convert string from properties file to integer: " + e.getMessage());
            System.exit(ReturnCode.FAILURE.getReturnCode());
        } catch (IllegalArgumentException e) {
            // Inform user that loading was not successful
            // Configuration must be specified in arguments in this case
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println("Can not read from properties file: " + filename);
            System.exit(ReturnCode.FAILURE.getReturnCode());
        }

        if (cmd.hasOption("i")) {
            settings.setInternal(true);
        }

        if (cmd.hasOption("e")) {
            settings.setSkipErrors(true);
        }

        if (cmd.hasOption("o")) {
            settings.setOutputFile(cmd.getOptionValue("o"));
        }

        if (cmd.hasOption("s")) {
            settings.setServer(cmd.getOptionValue("s"));
        }

        if (cmd.hasOption("d")) {
            settings.setSharedspace(((Long) cmd.getParsedOptionValue("d")).intValue());
        }

        if (cmd.hasOption("w")) {
            settings.setWorkspace(((Long) cmd.getParsedOptionValue("w")).intValue());
        }

        if (cmd.hasOption("u")) {
            settings.setUser(cmd.getOptionValue("u"));
        }

        if (settings.getOutputFile() == null) {
            if (cmd.hasOption("p")) {
                settings.setPassword(cmd.getOptionValue("p"));
            } else if (cmd.hasOption("password-file")) {
                try {
                    settings.setPassword(
                            FileUtils.readFileToString(new File(cmd.getOptionValue("password-file"))));
                } catch (IOException e) {
                    System.out
                            .println("Can not read the password file: " + cmd.getOptionValue("password-file"));
                    System.exit(ReturnCode.FAILURE.getReturnCode());
                }
            } else {
                System.out.println("Please enter your password if it's required and hit enter: ");
                settings.setPassword(new String(System.console().readPassword()));
            }
        }

        if (cmd.hasOption("proxy-host")) {
            settings.setProxyHost(cmd.getOptionValue("proxy-host"));
        }

        if (cmd.hasOption("proxy-port")) {
            settings.setProxyPort(((Long) cmd.getParsedOptionValue("proxy-port")).intValue());
        }

        if (cmd.hasOption("proxy-user")) {
            settings.setProxyUser(cmd.getOptionValue("proxy-user"));
        }

        if (settings.getOutputFile() == null && StringUtils.isNotEmpty(settings.getProxyUser())) {
            if (cmd.hasOption("proxy-password")) {
                settings.setProxyPassword(cmd.getOptionValue("proxy-password"));
            } else if (cmd.hasOption("proxy-password-file")) {
                try {
                    settings.setProxyPassword(
                            FileUtils.readFileToString(new File(cmd.getOptionValue("proxy-password-file"))));
                } catch (IOException e) {
                    System.out.println(
                            "Can not read the password file: " + cmd.getOptionValue("proxy-password-file"));
                    System.exit(ReturnCode.FAILURE.getReturnCode());
                }
            } else {
                System.out.println("Please enter your proxy password if it's required and hit enter: ");
                settings.setProxyPassword(new String(System.console().readPassword()));
            }
        }

        if (cmd.hasOption("check-result")) {
            settings.setCheckResult(true);
        }

        if (cmd.hasOption("check-result-timeout")) {
            settings.setCheckResultTimeout(
                    ((Long) cmd.getParsedOptionValue("check-status-timeout")).intValue());
        }

        if (cmd.hasOption("t")) {
            settings.setTags(Arrays.asList(cmd.getOptionValues("t")));
        }

        if (cmd.hasOption("f")) {
            settings.setFields(Arrays.asList(cmd.getOptionValues("f")));
        }

        if (cmd.hasOption("r")) {
            settings.setRelease(((Long) cmd.getParsedOptionValue("r")).intValue());
        }

        if (cmd.hasOption("started")) {
            settings.setStarted((Long) cmd.getParsedOptionValue("started"));
        }

        if (cmd.hasOption("a")) {
            settings.setProductAreas(cmd.getOptionValues("a"));
        }

        if (cmd.hasOption("b")) {
            settings.setBacklogItems(cmd.getOptionValues("b"));
        }

        if (!areSettingsValid(settings)) {
            System.exit(ReturnCode.FAILURE.getReturnCode());
        }

    } catch (ParseException e) {
        printHelp();
        System.exit(ReturnCode.FAILURE.getReturnCode());
    }
    return settings;
}

From source file:de.fraunhofer.iosb.ilt.sta.service.Service.java

private <T> ServiceResponse<T> executeDelete(ServiceRequest request) {
    ServiceResponse<T> response = new ServiceResponse<>();
    PersistenceManager pm = null;//  w w w . j av  a  2s.  c om
    try {
        if (request.getUrlPath() == null || request.getUrlPath().equals("/")) {
            return response.setStatus(400, "DELETE only allowed on Entities.");
        }
        ResourcePath path;
        try {
            path = PathParser.parsePath(settings.getServiceRootUrl(), request.getUrlPath());
        } catch (NumberFormatException e) {
            return response.setStatus(404, "Not a valid id.");
        } catch (IllegalStateException e) {
            return response.setStatus(404, "Not a valid id: " + e.getMessage());
        }
        if (!(path.getMainElement() instanceof EntityPathElement)) {
            return response.setStatus(400, "DELETE only allowed on Entities.");
        }
        if (path.getMainElement() != path.getLastElement()) {
            return response.setStatus(400, "DELETE only allowed on Entities.");
        }
        EntityPathElement mainEntity = (EntityPathElement) path.getMainElement();
        if (mainEntity.getId() == null) {
            return response.setStatus(400, "DELETE only allowed on Entities.");
        }
        if (request.getUrlQuery() != null && !request.getUrlQuery().isEmpty()) {
            return response.setStatus(400, "Not query options allowed on PACTH.");
        }

        pm = PersistenceManagerFactory.getInstance().create();
        try {

            if (pm.delete(mainEntity)) {
                pm.commitAndClose();
                response.setCode(200);
            } else {
                LOGGER.debug("Failed to delete entity.");
                pm.rollbackAndClose();
            }
        } catch (NoSuchEntityException e) {
            pm.rollbackAndClose();
            response.setStatus(404, e.getMessage());
        }
    } catch (Exception e) {
        LOGGER.error("", e);
    } finally {
        if (pm != null) {
            pm.rollbackAndClose();
        }
    }
    return response;
}