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:com.lyncode.xoai.serviceprovider.verbs.Identify.java

public IdentifyType harvest() throws InternalHarvestException, BadArgumentException {
    HttpClient httpclient = new DefaultHttpClient();
    String url = makeUrl();/*  w w w  .java 2s. c o  m*/
    this.getServiceProvider().getLogger().info("Harvesting: " + url);
    HttpGet httpget = new HttpGet(url);
    httpget.addHeader("User-Agent", getServiceProvider().getServiceName() + " : XOAI Service Provider");
    httpget.addHeader("From", getServiceProvider().getServiceName());

    HttpResponse response = null;

    try {
        response = httpclient.execute(httpget);
        StatusLine status = response.getStatusLine();

        this.getServiceProvider().getLogger().debug(response.getStatusLine());

        if (status.getStatusCode() == 503) // 503 Status (must wait)
        {
            org.apache.http.Header[] headers = response.getAllHeaders();
            for (org.apache.http.Header h : headers) {
                if (h.getName().equals("Retry-After")) {
                    String retry_time = h.getValue();
                    try {
                        Thread.sleep(Integer.parseInt(retry_time) * 1000);
                    } catch (NumberFormatException e) {
                        this.getServiceProvider().getLogger().warn("Cannot parse " + retry_time + " to Integer",
                                e);
                    } catch (InterruptedException e) {
                        this.getServiceProvider().getLogger().debug(e.getMessage(), e);
                    }
                    httpclient.getConnectionManager().shutdown();
                    httpclient = new DefaultHttpClient();
                    response = httpclient.execute(httpget);
                }
            }
        }

        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();

        OAIPMHtype pmh = OAIPMHParser.parse(instream, getServiceProvider());

        return pmh.getIdentify();
    } catch (IOException e) {
        throw new InternalHarvestException(e);
    } catch (ParseException e) {
        throw new InternalHarvestException(e);
    }

}

From source file:com.uber.stream.kafka.mirrormaker.controller.rest.resources.TopicPartitionBlacklistRestletResource.java

/**
 * blacklist or whitelist topic partition
 *
 * @return status// w  w w . j ava 2 s . c o m
 */
@Post
public Representation post() {
    Form params = getRequest().getResourceRef().getQueryAsForm();
    String topicName = params.getFirstValue("topic");
    String partitionName = params.getFirstValue("partition");
    String opt = params.getFirstValue("opt");
    if (StringUtils.isEmpty(topicName) || StringUtils.isEmpty(partitionName) || StringUtils.isEmpty(opt)) {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        return new StringRepresentation("Parameter topic, partition and opt are required.");
    }

    try {
        int partition = Integer.parseInt(partitionName);

        if ("blacklist".equalsIgnoreCase(opt)) {
            _helixMirrorMakerManager.updateTopicPartitionStateInMirrorMaker(topicName, partition,
                    Constants.HELIX_OFFLINE_STATE);
        } else if ("whitelist".equalsIgnoreCase(opt)) {
            _helixMirrorMakerManager.updateTopicPartitionStateInMirrorMaker(topicName, partition,
                    Constants.HELIX_ONLINE_STATE);
        } else {
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            return new StringRepresentation("Invalid parameter opt");
        }
    } catch (NumberFormatException e) {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        return new StringRepresentation("Parameter partition should be Integer");
    } catch (IllegalArgumentException e) {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        return new StringRepresentation(e.getMessage());
    } catch (Exception e) {
        getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
        return new StringRepresentation(e.getMessage());
    }
    return new StringRepresentation("OK");
}

From source file:org.psidnell.omnifocus.model.CommonProjectAndTaskAttributes.java

private Date adjustTime(Date date, String time) {

    String bits[] = time.split(":");
    if (bits.length == 2) {
        try {//from  w w  w.  j a  va 2 s.  c  om
            Calendar cal = new GregorianCalendar();
            cal.setTime(date);
            int hours = Integer.parseInt(bits[0]);
            int mins = Integer.parseInt(bits[1]);
            cal.set(Calendar.HOUR_OF_DAY, hours);
            cal.set(Calendar.MINUTE, mins);
            return cal.getTime();
        } catch (NumberFormatException e) {
            LOGGER.warn(e.getMessage());
        }
    }

    return date;
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.coprincipalinvestigator.CoPIVisCodeGenerator.java

/**
 * This method is used to setup parameters for the sparkline value object. These parameters
 * will be used in the template to construct the actual html/javascript code.
 * @param visMode/*from  ww  w.  j  a  v a2 s . c  o  m*/
 * @param visContainer
 */
private SparklineData setupSparklineParameters(String visMode, String providedVisContainerID) {

    SparklineData sparklineData = new SparklineData();

    int numOfYearsToBeRendered = 0;

    /*
     * It was decided that to prevent downward curve that happens if there are no publications 
     * in the current year seems a bit harsh, so we consider only publications from the last 10
     * complete years. 
     * */
    int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
    int shortSparkMinYear = currentYear - VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE + 1;

    /*
     * This is required because when deciding the range of years over which
     * the vis was rendered we dont want to be influenced by the
     * "DEFAULT_GRANT_YEAR".
     */
    Set<String> investigatedYears = new HashSet<String>(yearToUniqueCoPIs.keySet());
    investigatedYears.remove(VOConstants.DEFAULT_GRANT_YEAR);

    /*
     * We are setting the default value of minGrantYear to be 10 years
     * before the current year (which is suitably represented by the
     * shortSparkMinYear), this in case we run into invalid set of investigated
     * years.
     */
    int minGrantYear = shortSparkMinYear;

    String visContainerID = null;

    if (yearToUniqueCoPIs.size() > 0) {
        try {
            minGrantYear = Integer.parseInt(Collections.min(investigatedYears));
        } catch (NoSuchElementException e1) {
            log.debug("vis: " + e1.getMessage() + " error occurred for " + yearToUniqueCoPIs.toString());
        } catch (NumberFormatException e2) {
            log.debug("vis: " + e2.getMessage() + " error occurred for " + yearToUniqueCoPIs.toString());
        }
    }

    int minGrantYearConsidered = 0;

    /*
     * There might be a case that the person investigated his first grant
     * within the last 10 years but we want to make sure that the sparkline
     * is representative of at least the last 10 years, so we will set the
     * minGrantYearConsidered to "currentYear - 10" which is also given by
     * "shortSparkMinYear".
     */
    if (minGrantYear > shortSparkMinYear) {
        minGrantYearConsidered = shortSparkMinYear;
    } else {
        minGrantYearConsidered = minGrantYear;
    }

    numOfYearsToBeRendered = currentYear - minGrantYearConsidered + 1;

    sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);

    int uniqueCoPICounter = 0;
    Set<Collaborator> allCoPIsWithKnownGrantShipYears = new HashSet<Collaborator>();
    List<YearToEntityCountDataElement> yearToUniqueInvestigatorsCountDataTable = new ArrayList<YearToEntityCountDataElement>();

    for (int grantYear = minGrantYearConsidered; grantYear <= currentYear; grantYear++) {

        String grantYearAsString = String.valueOf(grantYear);
        Set<Collaborator> currentCoPIs = yearToUniqueCoPIs.get(grantYearAsString);

        Integer currentUniqueCoPIs = null;

        if (currentCoPIs != null) {
            currentUniqueCoPIs = currentCoPIs.size();
            allCoPIsWithKnownGrantShipYears.addAll(currentCoPIs);
        } else {
            currentUniqueCoPIs = 0;
        }

        yearToUniqueInvestigatorsCountDataTable.add(
                new YearToEntityCountDataElement(uniqueCoPICounter, grantYearAsString, currentUniqueCoPIs));

        uniqueCoPICounter++;
    }

    /*
     * For the purpose of this visualization I have come up with a term
     * "Sparks" which essentially means data points. Sparks that will be
     * rendered in full mode will always be the one's which have any year
     * associated with it. Hence.
     */
    sparklineData.setRenderedSparks(allCoPIsWithKnownGrantShipYears.size());

    sparklineData.setYearToEntityCountDataTable(yearToUniqueInvestigatorsCountDataTable);

    /*
     * This is required only for the sparklines which convey collaborationships like 
     * coinvestigatorships and coauthorship. There are edge cases where a collaborator can be 
     * present for in a collaboration with known & unknown year. We do not want to repeat the 
     * count for this collaborator when we present it in the front-end. 
     * */
    Set<Collaborator> totalUniqueCoInvestigators = new HashSet<Collaborator>(allCoPIsWithKnownGrantShipYears);

    /*
     * Total grants will also consider grants that have no year
     * associated with them. Hence.
     */
    Integer unknownYearGrants = 0;
    if (yearToUniqueCoPIs.get(VOConstants.DEFAULT_GRANT_YEAR) != null) {
        unknownYearGrants = yearToUniqueCoPIs.get(VOConstants.DEFAULT_GRANT_YEAR).size();
        totalUniqueCoInvestigators.addAll(yearToUniqueCoPIs.get(VOConstants.DEFAULT_GRANT_YEAR));
    }

    sparklineData.setTotalCollaborationshipCount(totalUniqueCoInvestigators.size());

    sparklineData.setUnknownYearGrants(unknownYearGrants);

    if (providedVisContainerID != null) {
        visContainerID = providedVisContainerID;
    } else {
        visContainerID = DEFAULT_VISCONTAINER_DIV_ID;
    }

    sparklineData.setVisContainerDivID(visContainerID);

    /*
     * By default these represents the range of the rendered sparks. Only in
     * case of "short" sparkline mode we will set the Earliest
     * RenderedGrant year to "currentYear - 10".
     */
    sparklineData.setEarliestYearConsidered(minGrantYearConsidered);
    sparklineData.setEarliestRenderedGrantYear(minGrantYear);
    sparklineData.setLatestRenderedGrantYear(currentYear);

    /*
     * The Full Sparkline will be rendered by default. Only if the url has
     * specific mention of SHORT_SPARKLINE_MODE_KEY then we render the short
     * sparkline and not otherwise.
     */
    if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {

        sparklineData.setEarliestRenderedGrantYear(shortSparkMinYear);
        sparklineData.setShortVisMode(true);

    } else {
        sparklineData.setShortVisMode(false);
    }

    if (yearToUniqueCoPIs.size() > 0) {

        sparklineData.setFullTimelineNetworkLink(UtilityFunctions.getCollaboratorshipNetworkLink(individualURI,
                VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
                VisualizationFrameworkConstants.COPI_VIS_MODE));

        sparklineData.setDownloadDataLink(
                UtilityFunctions.getCSVDownloadURL(individualURI, VisualizationFrameworkConstants.CO_PI_VIS,
                        VisualizationFrameworkConstants.COPIS_COUNT_PER_YEAR_VIS_MODE));

        Map<String, Integer> yearToUniqueCoPIsCount = new HashMap<String, Integer>();
        for (Map.Entry<String, Set<Collaborator>> currentYearToUniqueCoPIsCount : yearToUniqueCoPIs
                .entrySet()) {

            yearToUniqueCoPIsCount.put(currentYearToUniqueCoPIsCount.getKey(),
                    currentYearToUniqueCoPIsCount.getValue().size());
        }

        sparklineData.setYearToActivityCount(yearToUniqueCoPIsCount);

    }

    return sparklineData;
}

From source file:edu.csudh.goTorosBank.WithdrawServlet.java

/**
 * TODO: Finish filling this out..../*from ww  w.  jav a2  s . co  m*/
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException 
 */
@Override
@SuppressWarnings("unchecked") //need this to suppress warnings for our json.put
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    getServletContext().log("goGet () called");

    JSONObject returnJSON = new JSONObject();
    response.setContentType("application/json");

    HttpSession userSession = request.getSession();
    String username = (String) userSession.getAttribute("username");

    try {
        DatabaseInterface database = new DatabaseInterface();
        User myUser = database.getUser(username);
        if (request.getParameter("accountID") == null || request.getParameter("amount") == null) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "Not valid arguments!");
            //response.getWriter().write(returnJSON.toJSONString());
            return;
        }
        int accountID = Integer.parseInt(request.getParameter("accountID"));
        float amount = Float.parseFloat(request.getParameter("amount"));
        Account accountFrom = myUser.getUserAccount(accountID);
        String personGettingPaid = request.getParameter("personGettingPaid");
        String billType = request.getParameter("billType");
        String memo = request.getParameter("memo");

        //Checks if user has selected an account
        if (myUser.getUserAccounts().size() == 0) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "No account to withdraw from");
        }

        //checks if user has sufficient funds
        else if (0 > (accountFrom.getAccountBalance() - amount)) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "Insufficient funds in account" + accountFrom.getAccountNumber());
        }
        //checks that user withdraws in amounts of 20
        else if (amount % 20 != 0) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "Must withdraw in amounts of 20");
        }
        //checks that uer doesn't withdraw more than $500.00
        else if (amount > 500) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "Withdraw amount cannot exceed $500.00");
        } else if (personGettingPaid == null) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "There is no person getting payed");
        } else if (billType == null) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "There is no bill description");
        }
        //creates check for user and makes changes to the database...
        else {

            //response.setContentType("image/jpeg");
            File blueCheck = new File("blank-blue-check");
            String pathToWeb = getServletContext().getRealPath("/" + blueCheck);
            //File blueCheck = new File(pathToWeb + "blank-blue-check.jpg");
            returnJSON.put("pathToWeb", pathToWeb);

            String fullpath = writeIntoCheck(pathToWeb, username, Float.toString(amount), "AMOUNT IN WORDS",
                    "DATE", personGettingPaid, "BULLSHIT");
            String[] fullpathSplit = fullpath.split("/");
            String filename = fullpathSplit[fullpathSplit.length - 1];
            database.withdraw(accountID, amount, username);
            returnJSON.put("filename", filename);
            returnJSON.put("successfulWithdraw", true);
            returnJSON.put("message", "Successfully withdrew $" + amount + " from account " + accountID);
        }
    } catch (SQLException s) {
        returnJSON.put("errorMessage", "Sorry we have a SQLException");
        returnJSON.put("errorMessage2", s);
    } catch (ClassNotFoundException cl) {
        returnJSON.put("errorMessage", "Sorry we have a ClassNotFoundException");
        returnJSON.put("errorMessage2", cl);
    } catch (ParseException p) {
        returnJSON.put("successfulWithdraw", false);
        returnJSON.put("message", "ParseException: " + p.getMessage());
    }
    /*added new case, where parseInt finds nothing*/
    catch (NumberFormatException e) {
        returnJSON.put("successfulWithdraw", false);
        returnJSON.put("message", "NumberFormatException " + e.getMessage());
    }
    response.getWriter().write(returnJSON.toJSONString());
}

From source file:edu.lternet.pasta.auditmanager.AuditManagerResourceTest.java

/**
 * Test the create service method and the get service method
 *///  w ww . j a  v a  2s.  c  o  m
@Test
public void testCreateAndGet() {
    try {
        String auditEntry = readTestAuditEntry();
        HttpHeaders httpHeaders = new DummyCookieHttpHeaders(testUser);

        // Test CREATE for OK status
        Response response = auditManagerResource.create(httpHeaders, auditEntry);
        int statusCode = response.getStatus();
        assertEquals(201, statusCode);

        MultivaluedMap<String, Object> map = response.getMetadata();
        List<Object> location = map.get(HttpHeaders.LOCATION);
        URI uri = (URI) location.get(0);
        String uriPath = uri.getPath(); // e.g. "/audit/22196"

        try {
            auditId = Integer.parseInt(uriPath.substring(uriPath.lastIndexOf('/') + 1));
        } catch (NumberFormatException e) {
            fail("Failed to return valid audit entry ID value: " + uriPath);
        }
    } catch (IOException e) {
        fail(e.getMessage());
    }

    if (auditId == null) {
        fail("Null auditId value");
    } else {
        DummyCookieHttpHeaders httpHeaders = new DummyCookieHttpHeaders(testUser);

        // Test Evaluate for OK status
        Response response = auditManagerResource.getAuditRecord(httpHeaders, auditId);
        int statusCode = response.getStatus();
        assertEquals(200, statusCode);

        // Check the message body
        String entityString = (String) response.getEntity();
        String auditReport = entityString.trim();
        assertTrue(auditReport.length() > 1);
        assertTrue(auditReport.startsWith("<auditReport>"));
        assertTrue(auditReport.contains(String.format("<oid>%d</oid>", auditId)));
        assertTrue(auditReport.endsWith("</auditReport>"));
    }
}

From source file:info.magnolia.cms.taglibs.util.BaseImageTag.java

/**
 * Converts HEX color to RGB color./*www.j av a  2 s.  c  o m*/
 * @param The HEX value
 */
public int[] convertHexToRGB(String hex) {
    hex.trim();
    if (hex.startsWith("#")) {
        hex = hex.substring(1);
    }
    if (hex.length() == 3) {
        // allow three digit codes like for css
        hex = String.valueOf(hex.charAt(0)) + String.valueOf(hex.charAt(0)) + String.valueOf(hex.charAt(1))
                + String.valueOf(hex.charAt(1)) + String.valueOf(hex.charAt(2)) + String.valueOf(hex.charAt(2));
    }

    int[] rgb = new int[3];
    try {
        // Convert rrggbb string to hex ints
        rgb[0] = Integer.parseInt(hex.substring(0, 2), 16);
        rgb[1] = Integer.parseInt(hex.substring(2, 4), 16);
        rgb[2] = Integer.parseInt(hex.substring(4), 16);
    } catch (NumberFormatException e) {
        log.error("NumberFormatException occured during text-to-image conversion: "
                + "Attempting to convert Hex [" + hex + "] color to RGB color: " + e.getMessage(), e);
        rgb = new int[] { 255, 0, 0 }; // red
    }
    return rgb;
}

From source file:com.appdynamics.monitors.pingdom.communicator.PingdomCommunicator.java

/**
 * Parse the headers of the HTTP request for the remaining allowed requests in the remaining time frame
 * @param metrics//from  w  w  w.j  av a 2s . c o  m
 * @param responseHeaders
 */
private void getLimits(Map<String, Integer> metrics, Header[] responseHeaders) {

    for (Header header : responseHeaders) {
        if (header.getName().equals("Req-Limit-Short")) {
            String[] value = header.getValue().split("\\s+");
            try {
                metrics.put("Limits|Req-Limit-Short|Remaining", Integer.parseInt(value[1]));
                metrics.put("Limits|Req-Limit-Short|Time until reset", Integer.parseInt(value[5]));
            } catch (NumberFormatException e) {
                logger.error("Error parsing metric value for Limits|Req-Limit-Short" + e.getMessage());
            }
        } else if (header.getName().equals("Req-Limit-Long")) {
            String[] value = header.getValue().split("\\s+");
            try {
                metrics.put("Limits|Req-Limit-Long|Remaining", Integer.parseInt(value[1]));
                metrics.put("Limits|Req-Limit-Long|Time until reset", Integer.parseInt(value[5]));
            } catch (NumberFormatException e) {
                logger.error("Error parsing metric value for Limits|Req-Limit-Long" + e.getMessage());
            }
        }
    }
}

From source file:com.nextep.designer.dbgm.services.impl.DatatypeService.java

private boolean matchExpr(String expr, int value) {
    if (isWildcard(expr)) {
        return true;
    } else {// w  w  w. ja v  a 2 s  . com
        Integer val = null;
        try {
            val = Integer.valueOf(expr);
            if (val != null && value == val.intValue()) {
                return true;
            }
        } catch (NumberFormatException e) {
            LOGGER.error("Unable to parse domain expression '" + expr + "' as a numeric expression: "
                    + e.getMessage(), e);
        }
    }
    return false;
}

From source file:com.lyncode.xoai.serviceprovider.verbs.GetRecord.java

public GetRecordType harvest() throws InternalHarvestException, CannotDisseminateFormatException,
        IdDoesNotExistException, BadArgumentException {
    HttpClient httpclient = new DefaultHttpClient();
    String url = makeUrl();//from www. java2 s .co m
    super.getServiceProvider().getLogger().debug("Harvesting: " + url);
    HttpGet httpget = new HttpGet(url);
    httpget.addHeader("User-Agent", getServiceProvider().getServiceName() + " : XOAI Service Provider");
    httpget.addHeader("From", getServiceProvider().getServiceName());

    HttpResponse response = null;

    try {
        response = httpclient.execute(httpget);
        StatusLine status = response.getStatusLine();

        super.getServiceProvider().getLogger().debug(response.getStatusLine());

        if (status.getStatusCode() == 503) // 503 Status (must wait)
        {
            org.apache.http.Header[] headers = response.getAllHeaders();
            for (org.apache.http.Header h : headers) {
                if (h.getName().equals("Retry-After")) {
                    String retry_time = h.getValue();
                    try {
                        Thread.sleep(Integer.parseInt(retry_time) * 1000);
                    } catch (NumberFormatException e) {
                        super.getServiceProvider().getLogger()
                                .warn("Cannot parse " + retry_time + " to Integer", e);
                    } catch (InterruptedException e) {
                        super.getServiceProvider().getLogger().debug(e.getMessage(), e);
                    }
                    httpclient.getConnectionManager().shutdown();
                    httpclient = new DefaultHttpClient();
                    response = httpclient.execute(httpget);
                }
            }
        }

        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();

        OAIPMHtype pmh = OAIPMHParser.parse(instream, getServiceProvider());

        if (!pmh.getError().isEmpty()) {
            switch (pmh.getError().get(0).getCode()) {
            case BAD_ARGUMENT:
                throw new BadArgumentException(pmh.getError().get(0).getValue());

            default:
                throw new BadArgumentException(pmh.getError().get(0).getValue());
            }
        }

        return pmh.getGetRecord();
    } catch (IOException e) {
        throw new InternalHarvestException(e);
    } catch (ParseException e) {
        throw new InternalHarvestException(e);
    }

}