Example usage for java.lang NumberFormatException NumberFormatException

List of usage examples for java.lang NumberFormatException NumberFormatException

Introduction

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

Prototype

public NumberFormatException() 

Source Link

Document

Constructs a NumberFormatException with no detail message.

Usage

From source file:userinterface.graph.GUIImageExportDialog.java

public void changedUpdate(DocumentEvent e) {
    try {//from ww w.j av a  2s.c om
        exportWidth = Integer.parseInt(widthInputField.getText());
        if (exportWidth <= 0)
            throw new NumberFormatException();
        exportHeight = Integer.parseInt(heightInputField.getText());
        if (exportHeight <= 0)
            throw new NumberFormatException();
        GUIImageExportDialog.this.warningLabel.setVisible(false);
        GUIImageExportDialog.this.okayButton.setEnabled(true);
    } catch (NumberFormatException nfe) {
        GUIImageExportDialog.this.warningLabel.setVisible(true);
        GUIImageExportDialog.this.okayButton.setEnabled(false);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.masterDegree.administrativeOffice.candidate.CandidateRegistrationDispatchAction.java

public ActionForward confirm(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    DynaActionForm candidateRegistration = (DynaActionForm) form;

    User userView = getUserView(request);
    String candidateID = (String) candidateRegistration.get("candidateID");
    String branchID = (String) candidateRegistration.get("branchID");

    String studentNumberString = (String) candidateRegistration.get("studentNumber");
    Integer studentNumber = null;
    if ((studentNumberString != null) && (studentNumberString.length() > 0)) {
        try {/*  w w w. j  a  v a  2 s  .c om*/
            studentNumber = new Integer(studentNumberString);
            if (studentNumber.intValue() < 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            throw new InvalidInformationInFormActionException(
                    "error.exception.invalidInformationInStudentNumber");
        }
    }

    if ((request.getParameter("confirmation") == null)
            || request.getParameter("confirmation").equals("Confirmar")) {

        InfoCandidateRegistration infoCandidateRegistration = null;
        try {

            infoCandidateRegistration = RegisterCandidate.run(candidateID, branchID, studentNumber, userView);
        } catch (InvalidStudentNumberServiceException e) {
            throw new InvalidStudentNumberActionException(e);
        } catch (ActiveStudentCurricularPlanAlreadyExistsServiceException e) {
            throw new ActiveStudentCurricularPlanAlreadyExistsActionException(e);
        } catch (GratuityValuesNotDefinedServiceException e) {
            throw new GratuityValuesNotDefinedActionException(e);
        } catch (ExistingServiceException e) {

            List branchList = null;
            try {

                branchList = GetBranchListByCandidateID.run(candidateID);
            } catch (FenixServiceException ex) {
                throw new FenixActionException(ex);
            }

            request.setAttribute("branchList", branchList);

            try {

                GetCandidatesByID.run(candidateID);
            } catch (NonExistingServiceException ex) {
                throw new FenixActionException(ex);
            }
            throw new ExistingActionException("O Aluno", e);
        } catch (InvalidChangeServiceException e) {
            throw new InvalidChangeActionException("error.cantRegisterCandidate", e);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }

        candidateRegistration.set("studentCurricularPlanID",
                infoCandidateRegistration.getInfoStudentCurricularPlan().getExternalId());
        request.setAttribute("infoCandidateRegistration", infoCandidateRegistration);

        return mapping.findForward("ShowResult");
    }
    return mapping.findForward("PrepareCandidateList");

}

From source file:com.redhat.rhn.frontend.action.systems.virtualization.ProvisionVirtualizationWizardAction.java

private ActionErrors validateInput(DynaActionForm form) {
    ActionErrors errors = new ActionErrors();
    String name = form.getString(GUEST_NAME);

    if (name.length() < ProvisionVirtualInstanceCommand.MIN_NAME_SIZE) {
        errors.add(ActionErrors.GLOBAL_MESSAGE,
                new ActionMessage("frontend.actions.systems.virt.invalidguestnamelength",
                        (ProvisionVirtualInstanceCommand.MIN_NAME_SIZE)));
    }// w w w  .j  av a2  s .c  o  m

    Pattern pattern = Pattern.compile(ProvisionVirtualInstanceCommand.GUEST_NAME_REGEXP,
            Pattern.CASE_INSENSITIVE);
    if (!pattern.matcher(name).matches()) {
        errors.add(ActionErrors.GLOBAL_MESSAGE,
                new ActionMessage("frontend.actions.systems.virt.invalidregexp"));
    }

    if (!StringUtils.isEmpty(form.getString(MEMORY_ALLOCATION))) {
        try {
            Long memory = Long.parseLong(form.getString(MEMORY_ALLOCATION));
            if (memory <= 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            errors.add(ActionErrors.GLOBAL_MESSAGE,
                    new ActionMessage("frontend.actions.systems.virt.invalidmemvalue"));
        }
    }

    if (!StringUtils.isEmpty(form.getString(VIRTUAL_CPUS))) {
        try {
            Long cpus = Long.parseLong(form.getString(VIRTUAL_CPUS));
            if (cpus <= 0 || cpus > ProvisionVirtualInstanceCommand.MAX_CPU) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            errors.add(ActionErrors.GLOBAL_MESSAGE,
                    new ActionMessage("frontend.actions.systems.virt.invalidcpuvalue",
                            (ProvisionVirtualInstanceCommand.MAX_CPU + 1)));
        }
    }

    if (!StringUtils.isEmpty(form.getString(LOCAL_STORAGE_GB))) {
        try {
            Long storage = Long.parseLong(form.getString(LOCAL_STORAGE_GB));
            if (storage <= 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            errors.add(ActionErrors.GLOBAL_MESSAGE,
                    new ActionMessage("frontend.actions.systems.virt.invalidstoragevalue"));
            form.set(LOCAL_STORAGE_GB, "");
        }
    }

    if (!StringUtils.isEmpty(form.getString(MAC_ADDRESS))) {
        try {
            String macAddress = form.getString(MAC_ADDRESS);
            macAddress = macAddress.replace(":", "");
            if (macAddress.length() != 12 || !macAddress.matches("^[0-9a-fA-F]+$")) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            errors.add(ActionErrors.GLOBAL_MESSAGE,
                    new ActionMessage("frontend.actions.systems.virt.invalidmacaddressvalue"));
            form.set(MAC_ADDRESS, "");
        }
    }

    return errors;
}

From source file:com.tulskiy.musique.system.configuration.Configuration.java

public Rectangle getRectangle(String key, Rectangle def) {
    try {/*from  www.  ja  va 2s. c o m*/
        String value = getString(key);
        String[] tokens = value.split(" ");
        if (tokens.length != 4)
            throw new NumberFormatException();

        int[] values = new int[4];
        for (int i = 0; i < tokens.length; i++) {
            String s = tokens[i];
            values[i] = Integer.parseInt(s);
        }
        return new Rectangle(values[0], values[1], values[2], values[3]);
    } catch (Exception e) {
        setRectangle(key, def);
        return def;
    }
}

From source file:uk.ac.diamond.scisoft.analysis.plotclient.PlotWindowManager.java

private String getUniqueName(String base, IWorkbenchPage page) {
    try {/*  w  w w  .j  a  va 2 s  .c o  m*/
        Set<String> knownNames = new HashSet<String>(Arrays.asList(getAllPossibleViews(page, true)));
        int lastSpaceIndex = base.lastIndexOf(' ');
        if (lastSpaceIndex >= 0) {
            String numString = base.substring(lastSpaceIndex + 1);
            int viewNum = Integer.parseInt(numString);
            String prefix = base.substring(0, lastSpaceIndex + 1);
            String winner;
            do {
                viewNum++;
                winner = prefix + viewNum;
                if (viewNum > 1000000 || viewNum <= 0) {
                    throw new NumberFormatException();
                }
            } while (knownViews.containsKey(winner) || knownNames.contains(winner));
            return winner;
        }
    } catch (NumberFormatException e) {
        // no number at end of string, fall through
    }
    return getUniqueName(base + " 0", page);
}

From source file:net.amigocraft.mpt.util.MiscUtil.java

/**
 * Compares two version strings./* w w  w.j a va  2  s.  co  m*/
 * @param version1 the first version to compare
 * @param version2 the second version to compare
 * @return -1 if the first is more recent, 1 if the second is more recent, or 0 if the versions are equal
 */
public static int compareVersions(String version1, String version2) {
    // separate main version from qualifier
    String vStr1 = version1.contains("-") ? version1.split("-")[0] : version1;
    String vStr2 = version2.contains("-") ? version2.split("-")[0] : version2;

    // compare major versions
    int major1;
    int major2;
    try {
        major1 = Integer.parseInt(vStr1.split("\\.")[0]);
        if (major1 < 0)
            throw new NumberFormatException();
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Version string \"" + vStr1 + "\" contains invalid major version!");
    }
    try {
        major2 = Integer.parseInt(vStr2.split("\\.")[0]);
        if (major2 < 0)
            throw new NumberFormatException();
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Version string \"" + vStr2 + "\" contains invalid major version!");
    }
    if (major2 > major1)
        return 1;
    else if (major2 < major1)
        return -1;
    // else major versions are equal

    // compare minor versions
    int minor1;
    int minor2;
    try {
        minor1 = vStr1.split("\\.").length > 1 ? Integer.parseInt(vStr1.split("\\.")[1]) : 0;
        if (minor1 < 0)
            throw new NumberFormatException();
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Version string \"" + vStr1 + "\" contains invalid minor version!");
    }
    try {
        minor2 = vStr2.split("\\.").length > 1 ? Integer.parseInt(vStr2.split("\\.")[1]) : 0;
        if (minor2 < 0)
            throw new NumberFormatException();
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Version string \"" + vStr2 + "\" contains invalid minor version!");
    }
    if (minor2 > minor1)
        return 1;
    else if (minor2 < minor1)
        return -1;
    // else minor versions are equal

    // compare incremental versions
    int inc1;
    int inc2;
    try {
        inc1 = vStr1.split("\\.").length > 2 ? Integer.parseInt(vStr1.split("\\.")[2]) : 0;
        if (inc1 < 0)
            throw new NumberFormatException();
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Version string \"" + vStr1 + "\" contains invalid minor version!");
    }
    try {
        inc2 = vStr2.split("\\.").length > 2 ? Integer.parseInt(vStr2.split("\\.")[2]) : 0;
        if (inc2 < 0)
            throw new NumberFormatException();
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Version string \"" + vStr2 + "\" contains invalid minor version!");
    }
    if (inc2 > inc1)
        return 1;
    else if (inc2 < inc1)
        return -1;
    // else incremental versions are equal

    String qual1 = version1.contains("-") ? version1.substring(version1.indexOf("-") + 1) : "";
    String qual2 = version2.contains("-") ? version2.substring(version2.indexOf("-") + 1) : "";
    int lex = qual1.compareTo(qual2);
    if (lex > 0)
        return -1;
    else if (lex < 0)
        return 1;
    else
        return 0;
}

From source file:org.apache.fop.util.ColorUtil.java

/**
 * Parse a color given in the #.... format.
 *
 * @param value/*from  ww  w .j  av a  2 s. c  o  m*/
 *            the complete line
 * @return a color if possible
 * @throws PropertyException
 *             if the format is wrong.
 */
private static Color parseWithHash(String value) throws PropertyException {
    Color parsedColor;
    try {
        int len = value.length();
        int alpha;
        if (len == 5 || len == 9) {
            alpha = Integer.parseInt(value.substring((len == 5) ? 3 : 7), 16);
        } else {
            alpha = 0xFF;
        }
        int red = 0;
        int green = 0;
        int blue = 0;
        if ((len == 4) || (len == 5)) {
            //multiply by 0x11 = 17 = 255/15
            red = Integer.parseInt(value.substring(1, 2), 16) * 0x11;
            green = Integer.parseInt(value.substring(2, 3), 16) * 0x11;
            blue = Integer.parseInt(value.substring(3, 4), 16) * 0X11;
        } else if ((len == 7) || (len == 9)) {
            red = Integer.parseInt(value.substring(1, 3), 16);
            green = Integer.parseInt(value.substring(3, 5), 16);
            blue = Integer.parseInt(value.substring(5, 7), 16);
        } else {
            throw new NumberFormatException();
        }
        parsedColor = new Color(red, green, blue, alpha);
    } catch (RuntimeException re) {
        throw new PropertyException(
                "Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA");
    }
    return parsedColor;
}

From source file:com.datatorrent.contrib.parser.FixedWidthParser.java

/**
 * Function to validate and set the current field.
 * @param currentField the field which is to be validated and set
 * @param value the parsed value of the field
 * @param typeInfo information about the field in POJO
 * @param pojoObject POJO which is to be set
 * @param toEmit the map to be emitted/*from  w w w  .  ja v  a  2  s  .  co m*/
 */
private void validateAndSetCurrentField(FixedWidthSchema.Field currentField, String value,
        FixedWidthParser.TypeInfo typeInfo, Object pojoObject, HashMap toEmit) {
    try {
        String fieldName = currentField.getName();
        if (value != null && !value.isEmpty()) {
            Object result;
            switch (currentField.getType()) {
            case INTEGER:
                result = Integer.parseInt(value);
                break;
            case DOUBLE:
                result = Double.parseDouble(value);
                break;
            case STRING:
                result = value;
                break;
            case CHARACTER:
                result = value.charAt(0);
                break;
            case FLOAT:
                result = Float.parseFloat(value);
                break;
            case LONG:
                result = Long.parseLong(value);
                break;
            case SHORT:
                result = Short.parseShort(value);
                break;
            case BOOLEAN:
                if (value.compareToIgnoreCase(currentField.getTrueValue()) == 0) {
                    result = Boolean.parseBoolean("true");
                } else if (value.compareToIgnoreCase(currentField.getFalseValue()) == 0) {
                    result = Boolean.parseBoolean("false");
                } else {
                    throw new NumberFormatException();
                }
                break;
            case DATE:
                DateFormat df = new SimpleDateFormat(currentField.getDateFormat());
                df.setLenient(false);
                result = df.parse(value);
                break;
            default:
                throw new RuntimeException("Invalid Type in Field", new Exception());
            }
            toEmit.put(fieldName, result);
            if (typeInfo != null && pojoObject != null) {
                typeInfo.setter.set(pojoObject, result);
            }
        } else {
            toEmit.put(fieldName, value);
        }
    } catch (NumberFormatException e) {
        throw new RuntimeException("Error parsing" + value + " to Integer type", e);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing" + value, e);
    } catch (Exception e) {
        throw new RuntimeException("Error setting " + value + " in the given class" + typeInfo.toString(), e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission.java

/**
 * need to generate something like/*from  ww  w.  j a  va 2 s .  c o  m*/
 *  "09:10:11"^^<http://www.w3.org/2001/XMLSchema#time>
 */
public Literal getTime(Map<String, String[]> queryParameters, String fieldName) {
    List<String> hour = Arrays.asList(queryParameters.get("hour" + fieldName));
    List<String> minute = Arrays.asList(queryParameters.get("minute" + fieldName));

    if (hour == null || hour.size() == 0 || minute == null || minute.size() == 0) {
        log.info("Could not find query parameter values for time field " + fieldName);
        validationErrors.put(fieldName, "time must be supplied");
        return null;
    }

    int hourInt = -1;
    int minuteInt = -1;

    String hourParamStr = hour.get(0);
    String minuteParamStr = minute.get(0);

    // if all fields are blank, just return a null value
    if (hourParamStr.length() == 0 && minuteParamStr.length() == 0) {
        return null;
    }

    String errors = "";
    try {
        hourInt = Integer.parseInt(hour.get(0));
        if (hourInt < 0 || hourInt > 23) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException nfe) {
        errors += "Please enter a valid hour.  ";
    }
    try {
        minuteInt = Integer.parseInt(minute.get(0));
        if (minuteInt < 0 || minuteInt > 59) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException nfe) {
        errors += "Please enter a valid minute.  ";
    }
    if (errors.length() > 0) {
        validationErrors.put(fieldName, errors);
        return null;
    }

    String hourStr = (hourInt < 10) ? "0" + Integer.toString(hourInt) : Integer.toString(hourInt);
    String minuteStr = (minuteInt < 10) ? "0" + Integer.toString(minuteInt) : Integer.toString(minuteInt);
    String secondStr = "00";

    return new EditLiteral(hourStr + ":" + minuteStr + ":" + secondStr, TIME_URI, null);

}

From source file:jp.terasoluna.fw.web.struts.form.FieldChecksExTest05.java

/**
 * testValidateStringLength05()/*from  w  w w  . ja  v  a 2s .c o  m*/
 * <br><br>
 *
 * (??n)
 * <br>
 * _?FF
 * <br><br>
 * l?F(?) bean:String:"abc0#"<br>
 *         (?) va:not null<br>
 *         (?) field:not null<br>
 *                var:stringLength="A"<br>
 *                Msg("message","message")<br>
 *         (?) errors:not null<br>
 *                (vf)<br>
 *         (?) validator:not null<br>
 *         (?) request:not null<br>
 *
 * <br>
 * l?F(l) boolean:true<br>
 *         (?) ?O:?Ox?FG?[<br>
 *                    ?bZ?[W?F<br>
 *                    "stringLength is not numeric(integer)."<br>
 *                    O?FNumberFormatException<br>
 *         (?) errors:not null<br>
 *                    (vf)<br>
 *
 * <br>
 * fieldstringLengthl?l?Atrue
 * mF?B
 * <br>
 *
 * @throws Exception ?\bh?O
 */
public void testValidateStringLength05() throws Exception {
    //eXgf?[^?
    // ++++ beanIuWFNg ++++
    String bean = "abc0#";
    // ++++ ??IuWFNg
    ValidatorAction va = new ValidatorAction();
    va.setName("message");
    // ++++ ?tB?[h?
    Field field = new Field();
    // ?bZ?[W?
    Msg msg = new Msg();
    msg.setKey("message");
    msg.setName("message");
    msg.setResource(false);
    field.addMsg(msg);
    Var var = new Var();
    var.setName("stringLength");
    var.setValue("A");
    field.addVar(var);

    // G?[?
    ActionMessages errors = new ActionMessages();
    // [HTTPNGXg
    MockHttpServletRequest request = new MockHttpServletRequest();
    // ValidatorResourcesCX^X
    ValidatorResources validatorResources = new ValidatorResources();
    // ValidatorCX^X
    Validator validator = new Validator(validatorResources);

    // eXg?s
    boolean result = FieldChecksEx.validateStringLength(bean, va, field, errors, validator, request);
    // eXgmF
    // truep?B
    assertTrue(result);
    // G?[??B
    assertTrue(errors.isEmpty());

    // G?[?OmF
    assertTrue(LogUTUtil.checkError("stringLength is not numeric(integer).", new NumberFormatException()));
}