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(String s) 

Source Link

Document

Constructs a NumberFormatException with the specified detail message.

Usage

From source file:com.doitnext.http.router.responsehandlers.DefaultErrorHandlerTest.java

@Test
public void testHandleResponseFail() {
    DefaultErrorHandler h = new DefaultErrorHandler();
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    Exception responseData = new IllegalArgumentException("Hidey Ho!!", new NumberFormatException("3r3"));
    Exception e = new RuntimeException();
    Mockito.doThrow(e).when(response).setContentType(Mockito.anyString());
    logger.info(//  w  w w  . ja  v a2 s  . c o  m
            "Testing DefaultErrorHandler ability to handle exceptions while interacting with HttpServletResponse");
    boolean handled = h.handleResponse(null, null, response, responseData);
    Assert.assertFalse(handled);
    logger.info("Awesome!! DefaultErrorHandler handled the exception appropriately.");
}

From source file:fr.gael.dhus.datastore.IncomingManager.java

public boolean isAnIncomingElement(File file) {
    int maxfileno = cfgManager.getArchiveConfiguration().getIncomingConfiguration().getMaxFileNo();

    boolean is_digit = true;
    try {/*from  w w w . j a v a 2  s . c  om*/
        // Incoming folders are "X5F" can be parse "0X5F" by decode
        // Warning '09' means octal value that raise error because 9>8...
        String filename = file.getName();
        if (filename.toUpperCase().startsWith("X"))
            filename = "0" + filename;

        if (Long.decode(filename) > maxfileno)
            throw new NumberFormatException("Expected value exceeded.");
    } catch (NumberFormatException e) {
        is_digit = false;
    }

    return isInIncoming(file) && (is_digit
            || file.getName().equals(HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME)
            || (file.getName().equals(INCOMING_PRODUCT_DIR)
                    && file.getParentFile().getName().equals(HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME)));
}

From source file:org.okinawaopenlabs.ofpm.utils.OFPMUtils.java

/**
 * Charactor is represented band-width converted to value of Mbps. For example, 1.2Gbps is  converted to 1229.
 * Available range is from Mbps to Ybps.
 * @param bandWidth [Number][kMGTPEZY]bps
 * @return/*from w  ww  .  j  a v  a 2s . c  om*/
 */
public static long bandWidthToBaseMbps(String bandWidth) {
    String reg = "([0-9]+)([MGTPEZY])bps";
    Pattern pat = Pattern.compile(reg);
    Matcher mat = pat.matcher(bandWidth);
    if (!mat.find()) {
        throw new NumberFormatException(String.format(PARSE_ERROR, bandWidth));
    }
    String numb = mat.group(1);
    String base = mat.group(2);

    long value = Long.parseLong(numb);
    if (base.equals("G")) {
        value *= 1024L;
    } else if (base.equals("T")) {
        value *= 1048576L;
    } else if (base.equals("P")) {
        value *= 1073741824L;
    } else if (base.equals("E")) {
        value *= 1099511627776L;
    } else if (base.equals("Z")) {
        value *= 1125899906842624L;
    } else if (base.equals("Y")) {
        value *= 1152921504606846976L;
    }
    return value;
}

From source file:org.diorite.commons.math.RomanNumeral.java

private static int letterToNumber(char letter) {
    switch (letter) {
    case 'I':
        return 1;
    case 'V':
        return 5;
    case 'X':
        return 10;
    case 'L':
        return 50;
    case 'C':
        return 100;
    case 'D':
        return 500;
    case 'M':
        return 1000;
    default://from   w  ww .  j  a  v  a2  s  .  c  om
        throw new NumberFormatException("Illegal character \"" + letter + "\" in Roman numeral");
    }
}

From source file:org.terrier.utility.UnitUtils.java

public static double parseDouble(String str) {
    if (str == null)
        throw new NullPointerException();
    int notNumberIndex = StringUtils.indexOfAnyBut(str, "0123456789");
    if (notNumberIndex == -1)
        return Double.parseDouble(str);
    double ret = Double.parseDouble(str.substring(0, notNumberIndex));
    switch (str.substring(notNumberIndex).trim()) {
    case "G":
        return ret * G_FACTOR;
    case "M":
        return ret * M_FACTOR;
    case "K":
        return ret * K_FACTOR;
    case "Gi":
        return ret * Gi_FACTOR;
    case "Mi":
        return ret * Mi_FACTOR;
    case "Ki":
        return ret * Ki_FACTOR;
    }//  w ww .j  av  a  2s  . c  o  m
    throw new NumberFormatException(str + " can't be correctly parsed.");
}

From source file:org.diorite.utils.math.RomanNumeral.java

private static int letterToNumber(final char letter) {
    switch (letter) {
    case 'I':
        return 1;
    case 'V':
        return 5;
    case 'X':
        return 10;
    case 'L':
        return 50;
    case 'C':
        return 100;
    case 'D':
        return 500;
    case 'M':
        return 1000;
    default://from ww w. j  a va  2  s.com
        throw new NumberFormatException("Illegal character \"" + letter + "\" in Roman numeral");
    }
}

From source file:TimeFormatter.java

public static long parseDuration(String duration) throws NumberFormatException {
    long out = 0;
    for (String part : duration.split(" ")) {
        if (part.length() == 0)
            continue;

        int i = 0;
        for (; i < part.length(); i++) {
            char c = part.charAt(i);
            if ((c < '0') || (c > '9'))
                break;
        }/*  w w  w  .  j  a  v  a 2 s. c  o  m*/
        long base = Long.parseLong(part.substring(0, i));
        String unit = part.substring(i).toLowerCase();

        switch (unit.charAt(0)) {
        case 's':
            if ("s".equals(unit) || "second".equals(unit) || "seconds".equals(unit)) {
                out += base * SECOND;
                continue;
            }
            break;
        case 'm':
            if ("m".equals(unit) || "min".equals(unit) || "mins".equals(unit) || "minute".equals(unit)
                    || "minutes".equals(unit)) {
                out += base * MINUTE;
                continue;
            }
            break;
        case 'h':
            if ("h".equals(unit) || "hour".equals(unit) || "hours".equals(unit)) {
                out += base * HOUR;
                continue;
            }
            break;
        case 'd':
            if ("d".equals(unit) || "day".equals(unit) || "days".equals(unit)) {
                out += base * DAY;
                continue;
            }
            break;
        case 'w':
            if ("w".equals(unit) || "week".equals(unit) || "weeks".equals(unit)) {
                out += base * WEEK;
                continue;
            }
            break;
        }
        throw new NumberFormatException("Invalid unit: " + unit);
    }
    return out;
}

From source file:Main.java

/**
 * Converts a byte array to an integer of base radix.
 * <br><br>//  www. ja  v a 2 s .co  m
 * Array constraints are:
 * <li>Number must be less than 10 digits</li>
 * <li>Number must be positive</li>
 * @param bArray Byte Array representation of number
 * @param radix Number base to use
 * @return integer value of number
 * @throws NumberFormatException
 */
public static int parseInt(byte[] bArray, int radix) throws NumberFormatException {
    int length = bArray.length;
    if (length > 9)
        throw new NumberFormatException("Number can have maximum 9 digits");
    int result = 0;
    int index = 0;
    int digit = Character.digit((char) bArray[index++], radix);
    if (digit == -1)
        throw new NumberFormatException("Byte array contains non-digit");
    result = digit;
    while (index < length) {
        result *= radix;
        digit = Character.digit((char) bArray[index++], radix);
        if (digit == -1)
            throw new NumberFormatException("Byte array contains non-digit");
        result += digit;
    }
    return result;
}

From source file:jdchub.module.commands.handlers.BanCommand.java

@Override
public String execute(String cmd, String args, AbstractClient commandOwner) {
    banExpiresDate = new Date();

    this.commandOwner = commandOwner;

    this.nick = null;

    this.reason = null;

    LongOpt[] longOpts = new LongOpt[5];

    longOpts[0] = new LongOpt("nick", LongOpt.REQUIRED_ARGUMENT, null, 'n');
    longOpts[1] = new LongOpt("reason", LongOpt.REQUIRED_ARGUMENT, null, 'r');
    longOpts[2] = new LongOpt("time", LongOpt.REQUIRED_ARGUMENT, null, 't');
    longOpts[3] = new LongOpt("ip", LongOpt.REQUIRED_ARGUMENT, null, 'i');
    longOpts[4] = new LongOpt("mask", LongOpt.REQUIRED_ARGUMENT, null, 'm');

    String[] argArray = CommandUtils.strArgToArray(args);

    Getopt getopt = new Getopt(cmd, argArray, "n:r:t:i:m:", longOpts);

    if (argArray.length < 1) {
        showHelp();/*from w  ww.  j av  a  2s .  co m*/
        return null;
    }

    int c;

    while ((c = getopt.getopt()) != -1) {
        switch (c) {
        case 'n':
            this.nick = getopt.getOptarg();
            break;

        case 'r':
            this.reason = getopt.getOptarg();
            break;

        case 'i':
            this.ip = getopt.getOptarg();
            break;

        case 'm':
            this.mask = getopt.getOptarg();
            break;

        case 't':
            // Valid entries for <time> are Ns, Nm, Nh, Nd, Nw, NM, Ny
            String timeString = getopt.getOptarg();
            int timeType = timeString.charAt(timeString.length() - 1);
            int time;
            try {
                time = Integer.parseInt(timeString.substring(0, timeString.length() - 1));
                if (time <= 0) {
                    throw new NumberFormatException("Invalid time format : time must be greater than 0");
                }
            } catch (NumberFormatException ex) {
                showError("Invalid time format.");
                return "Invalid expires time.";
            }

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(banExpiresDate);

            switch (timeType) {
            case 's':
                timeType = Calendar.SECOND;
                break;

            case 'm':
                timeType = Calendar.MINUTE;
                break;

            case 'h':
                timeType = Calendar.HOUR;
                break;

            case 'd':
                timeType = Calendar.DAY_OF_YEAR;
                break;

            case 'w':
                timeType = Calendar.WEEK_OF_YEAR;
                break;

            case 'M':
                timeType = Calendar.MONTH;
                break;

            case 'Y':
                timeType = Calendar.YEAR;
                break;

            default:
                showError("Invalid time format.");
            }

            calendar.add(timeType, time);
            this.banExpiresDate = calendar.getTime();
            this.banType = Constants.BAN_TEMPORARY;

            break;

        case '?':
            showHelp();
            break;

        default:
            showHelp();
            break;
        }
    }

    return ban();
}

From source file:com.alfaariss.oa.engine.core.crypto.factory.AbstractCipherFactory.java

/**
 * Create and start the <code>AbstractCipherFactory</code>.
        //  w ww. ja v  a  2s. co  m
 * @param configManager
 * @param eCipherFactorySection
 * @return The created cipher factory 
 * @throws CryptoException
 */
public static AbstractCipherFactory createInstance(IConfigurationManager configManager,
        Element eCipherFactorySection) throws CryptoException {
    String sCipherFactory = null;
    if (configManager == null)
        throw new IllegalArgumentException("Supplied configuration manager is empty");
    if (eCipherFactorySection == null)
        throw new IllegalArgumentException("Supplied section is empty");
    try {
        try {
            sCipherFactory = configManager.getParam(eCipherFactorySection, "class");
        } catch (ConfigurationException e) {
            _logger.error("Could not read 'class' config parameter", e);
            throw new CryptoException(SystemErrors.ERROR_CONFIG_READ, e);
        }

        if (sCipherFactory == null) {
            _logger.error("Could not retrieve 'class' config parameter");
            throw new CryptoException(SystemErrors.ERROR_CONFIG_READ);
        }

        AbstractCipherFactory cipherFactory = (AbstractCipherFactory) Class.forName(sCipherFactory)
                .newInstance();
        cipherFactory._configurationManager = configManager;
        cipherFactory._eCipherFactorySection = eCipherFactorySection;

        //get expiration timeout
        String sExpiration;
        try {
            sExpiration = configManager.getParam(eCipherFactorySection, "expire");
        } catch (ConfigurationException e) {
            _logger.error("Could not read 'expire' config parameter", e);
            throw new CryptoException(SystemErrors.ERROR_CONFIG_READ, e);
        }
        try {
            cipherFactory._lExpiration = Long.parseLong(sExpiration);
            if (cipherFactory._lExpiration <= 0) {
                _logger.debug("NumberFormatException when parsing: " + sExpiration);
                throw new NumberFormatException("Less then or equeal to zero");
            }
            cipherFactory._lExpiration *= 1000;
        } catch (NumberFormatException e) {
            _logger.error("Invalid 'expire' configuration: " + sExpiration, e);
            throw new CryptoException(SystemErrors.ERROR_CONFIG_READ, e);
        }

        //Get interval
        String sInterval;
        try {
            sInterval = configManager.getParam(eCipherFactorySection, "interval");
        } catch (ConfigurationException e) {
            _logger.error("Could not read 'interval' config parameter", e);
            throw new CryptoException(SystemErrors.ERROR_CONFIG_READ, e);
        }
        try {
            cipherFactory._lInterval = Long.parseLong(sInterval);
            if (cipherFactory._lInterval <= 0) {
                _logger.info("Storage cleaner interval less then or equal to zero, cleaning is disabled");
            } else {
                cipherFactory._lInterval *= 1000;
                //Create cleaner
                cipherFactory._oCleaner = new Cleaner(cipherFactory._lInterval, cipherFactory, _logger);

                cipherFactory._tCleaner = new Thread(cipherFactory._oCleaner);

                String sOrigName = cipherFactory._tCleaner.getName();
                StringBuffer sbName = new StringBuffer(cipherFactory.getClass().getName());
                sbName.append("(");
                sbName.append(sOrigName);
                sbName.append(")");
                cipherFactory._tCleaner.setName(sbName.toString());
            }
        } catch (NumberFormatException e) {
            _logger.error("Invalid 'interval' configuration: " + sInterval, e);
            throw new CryptoException(SystemErrors.ERROR_CONFIG_READ);
        }

        return cipherFactory;
    } catch (InstantiationException e) {
        _logger.error("Could not instantiate cipher factory with name: " + sCipherFactory, e);
        throw new CryptoException(SystemErrors.ERROR_INIT, e);
    } catch (IllegalAccessException e) {
        _logger.error("Illegal Access when instantiating cipher factory with name: " + sCipherFactory, e);
        throw new CryptoException(SystemErrors.ERROR_INIT, e);
    } catch (ClassNotFoundException e) {
        _logger.error("No cipher factory found with name: " + sCipherFactory, e);
        throw new CryptoException(SystemErrors.ERROR_INIT, e);
    }
}