Example usage for java.text ParseException ParseException

List of usage examples for java.text ParseException ParseException

Introduction

In this page you can find the example usage for java.text ParseException ParseException.

Prototype

public ParseException(String s, int errorOffset) 

Source Link

Document

Constructs a ParseException with the specified detail message and offset.

Usage

From source file:com.turborep.turbotracker.home.WeatherSer.java

public ArrayList<WeatherForecastBean> getWeathrtForecast() throws WeatherException, ParseException {
    WeatherForecastBean aWeatherForecastBean = null;
    String aStr = connectWebservice();
    ArrayList<WeatherForecastBean> aWeatherForecastList = new ArrayList<WeatherForecastBean>();
    try {/*from  w ww  . ja  va2  s  .  c  om*/
        String aCurrentweatherDesc;
        JSONObject aWeatherObj = new JSONObject(aStr).getJSONObject("data");
        WeatherForecastBean aCurrentWeatherBean = new WeatherForecastBean();
        JSONObject aCurrentWeatherObj = aWeatherObj.getJSONArray("current_condition").getJSONObject(0);
        JSONArray aWeatherDescObj = aCurrentWeatherObj.getJSONArray("weatherDesc");
        JSONObject aCurrDescObj = (JSONObject) aWeatherDescObj.get(0);
        aCurrentweatherDesc = aCurrDescObj.getString("value");
        aCurrentWeatherBean.setItsCurrentWeatherDescription(aCurrentweatherDesc);
        aCurrentWeatherBean.setItsCurrentTempCelc(aCurrentWeatherObj.getInt("temp_C"));
        aCurrentWeatherBean.setItsCurrentWeatherIconlocation(
                ((JSONObject) aCurrentWeatherObj.getJSONArray("weatherIconUrl").get(0)).getString("value"));
        aWeatherForecastList.add(aCurrentWeatherBean);
        JSONArray aWeatherArray = aWeatherObj.getJSONArray("weather");
        for (int index = 0; index < aWeatherArray.length(); index++) {
            aWeatherForecastBean = new WeatherForecastBean();
            JSONObject aWeatherForecastArr = aWeatherArray.getJSONObject(index);
            aWeatherForecastBean.setItsForecastDate(aWeatherForecastArr.getString("date"));
            aWeatherForecastBean.setItsMaxTempCelc((int) aWeatherForecastArr.getInt("tempMaxC"));
            aWeatherForecastBean.setItsMinTempCelc((int) aWeatherForecastArr.getInt("tempMinC"));
            aWeatherForecastBean.setItsMaxTempFH((int) aWeatherForecastArr.getInt("tempMaxF"));
            aWeatherForecastBean.setItsMinTempFH((int) aWeatherForecastArr.getInt("tempMinF"));
            aWeatherForecastBean.setItsWeatherDescription(
                    ((JSONObject) aWeatherForecastArr.getJSONArray("weatherDesc").get(0)).getString("value"));
            aWeatherForecastBean.setItsWeatherIconlocation(
                    ((JSONObject) aWeatherForecastArr.getJSONArray("weatherIconUrl").get(0))
                            .getString("value"));
            aWeatherForecastList.add(aWeatherForecastBean);
        }
    } catch (ParseException e) {
        logger.error(e.getMessage(), e);
        ParseException aParseException = new ParseException(e.getMessage(), e.getErrorOffset());
        throw aParseException;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        WeatherException aWeatherException = new WeatherException(e.getMessage(), e);
        throw aWeatherException;
    }
    return aWeatherForecastList;
}

From source file:com.gisgraphy.util.DateUtil.java

/**
 * This method converts a String to a date using the datePattern
 * //  w ww.j  a  v  a 2s  . co  m
 * @param strDate
 *                the date to convert (in format MM/dd/yyyy)
 * @return a date object
 * @throws ParseException
 *                 when String doesn't match the expected format
 */
public static Date convertStringToDate(String strDate) throws ParseException {
    Date aDate = null;

    try {
        if (log.isDebugEnabled()) {
            log.debug("converting date with pattern: " + getDatePattern());
        }

        aDate = convertStringToDate(getDatePattern(), strDate);
    } catch (ParseException pe) {
        log.error("Could not convert '" + strDate + "' to a date, throwing exception");
        throw new ParseException(pe.getMessage(), pe.getErrorOffset());
    }

    return aDate;
}

From source file:com.autsia.bracer.BracerParser.java

/**
 * Parses the math expression (complicated formula) and stores the result
 *
 * @param expression <code>String</code> input expression (math formula)
 * @throws <code>ParseException</code> if the input expression is not
 *                                     correct
 * @since 3.0//from w  w w .  j av a 2s  .  c om
 */
public void parse(String expression) throws ParseException {
    /* cleaning stacks */
    stackOperations.clear();
    stackRPN.clear();

    /*
     * make some preparations: remove spaces; handle unary + and -, handle
     * degree character
     */
    expression = expression.replace(" ", "").replace("", "*" + Double.toString(Math.PI) + "/180")
            .replace("(-", "(0-").replace(",-", ",0-").replace("(+", "(0+").replace(",+", ",0+")
            .replace("true", "1").replace("false", "0").replace("or", "|").replace("and", "&");
    if (expression.charAt(0) == '-' || expression.charAt(0) == '+') {
        expression = "0" + expression;
    }
    /* splitting input string into tokens */
    StringTokenizer stringTokenizer = new StringTokenizer(expression, OPERATORS + SEPARATOR + "()", true);

    /* loop for handling each token - shunting-yard algorithm */
    while (stringTokenizer.hasMoreTokens()) {
        String token = stringTokenizer.nextToken();
        if (isSeparator(token)) {
            while (!stackOperations.empty() && !isOpenBracket(stackOperations.lastElement())) {
                stackRPN.push(stackOperations.pop());
            }
        } else if (isOpenBracket(token)) {
            stackOperations.push(token);
        } else if (isCloseBracket(token)) {
            while (!stackOperations.empty() && !isOpenBracket(stackOperations.lastElement())) {
                stackRPN.push(stackOperations.pop());
            }
            stackOperations.pop();
            if (!stackOperations.empty() && isFunction(stackOperations.lastElement())) {
                stackRPN.push(stackOperations.pop());
            }
        } else if (isNumber(token)) {
            if (token.equals(IMAGINARY)) {
                stackRPN.push(complexFormat.format(new Complex(0, 1)));
            } else if (token.contains(IMAGINARY)) {
                stackRPN.push(complexFormat.format(complexFormat.parse("0+" + token)));
            } else {
                stackRPN.push(token);
            }
        } else if (isOperator(token)) {
            while (!stackOperations.empty() && isOperator(stackOperations.lastElement())
                    && getPrecedence(token) <= getPrecedence(stackOperations.lastElement())) {
                stackRPN.push(stackOperations.pop());
            }
            stackOperations.push(token);
        } else if (isFunction(token)) {
            stackOperations.push(token);
        } else {
            throw new ParseException("Unrecognized token: " + token, 0);
        }
    }
    while (!stackOperations.empty()) {
        stackRPN.push(stackOperations.pop());
    }

    /* reverse stack */
    Collections.reverse(stackRPN);
}

From source file:org.apache.cassandra.jmeter.AbstractCassandaTestElement.java

private static byte[] hexStringToByteArray(String s) throws ParseException {

    if (!s.startsWith("0x")) {
        throw new ParseException("blob must start with 0x", 0);
    }/*from w ww .j  a v  a 2s  .  c  om*/
    int len = s.length() - 2;
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((charToHexDigit(s.charAt(i + 2)) << 4) + charToHexDigit(s.charAt(i + 3)));
    }
    return data;
}

From source file:com.datastax.loader.CqlDelimParser.java

private void processCqlSchema(String cqlSchema, Session session) throws ParseException {
    String kstnRegex = "^\\s*(\\\"?[A-Za-z0-9_]+\\\"?)\\.(\\\"?[A-Za-z0-9_]+\\\"?)\\s*[\\(]\\s*(\\\"?[A-Za-z0-9_]+\\\"?\\s*(,\\s*\\\"?[A-Za-z0-9_]+\\\"?\\s*)*)[\\)]\\s*$";
    Pattern p = Pattern.compile(kstnRegex);
    Matcher m = p.matcher(cqlSchema);
    if (!m.find()) {
        throw new ParseException("Badly formatted schema  " + cqlSchema, 0);
    }/*from w  w w  .  ja v  a 2 s  .  c  o  m*/
    keyspace = m.group(1);
    tablename = m.group(2);
    String schemaString = m.group(3);
    sbl = schemaBits(schemaString, session);
}

From source file:org.oclc.firefly.hadoop.backup.Import.java

/**
 * Used by constructor//w w  w .jav  a  2 s  . c om
 * @param conf The cluster configuration
 * @param backupDirPath The backup directory path
 * @param ignoreBadName Ignores the backup directory name. Does not parse start/end date of backup
 * @throws IOException Thrown if failed to get file system
 * @throws ParseException Thrown if directory does not contain a valid backup name
 */
private void init(Configuration conf, Path backupDirPath, boolean ignoreBadName)
        throws IOException, ParseException {
    this.conf = conf;
    this.fs = FileSystem.get(conf);
    this.backupDirPath = backupDirPath;
    this.hadmin = new HBaseAdmin(conf);

    if (!fs.exists(backupDirPath)) {
        throw new FileNotFoundException("Backup directory " + backupDirPath + " does not exist");
    }

    String backupDirName = backupDirPath.getName();
    String[] splitDirName = backupDirName.split("-");

    if (splitDirName.length == 3) {
        if (splitDirName[0].equals("bak")) {
            try {
                startDate = BackupUtils.BACKUP_DATE_FORMAT.parse(splitDirName[1]);
                endDate = BackupUtils.BACKUP_DATE_FORMAT.parse(splitDirName[2]);
            } catch (Exception e) {
                startDate = null;
                endDate = null;
            }
        }
    }

    if (!ignoreBadName && (startDate == null || endDate == null || !startDate.before(endDate))) {
        throw new ParseException("Backup directory does not have a valid name", 0);
    }

    tableNames = getTableNamesFromBackup();
}

From source file:NumericTextField.java

public Number getNumberValue() throws ParseException {
    try {/* w w w  .  j a  v  a2s.c o m*/
        String content = getText(0, getLength());
        parsePos.setIndex(0);
        Number result = format.parse(content, parsePos);
        if (parsePos.getIndex() != getLength()) {
            throw new ParseException("Not a valid number: " + content, 0);
        }

        return result;
    } catch (BadLocationException e) {
        throw new ParseException("Not a valid number", 0);
    }
}

From source file:org.deidentifier.arx.DataHandle.java

/**
 * Returns a double value from the specified cell.
 *
 * @param row The cell's row index/*w  ww . j av a2 s .c  o m*/
 * @param col The cell's column index
 * @return the double
 * @throws ParseException the parse exception
 */
public Double getDouble(int row, int col) throws ParseException {
    String value = getValue(row, col);
    DataType<?> type = getDataType(getAttributeName(col));
    if (type instanceof ARXDecimal) {
        return ((ARXDecimal) type).parse(value);
    } else if (type instanceof ARXInteger) {
        Long _long = ((ARXInteger) type).parse(value);
        return _long == null ? null : _long.doubleValue();
    } else {
        throw new ParseException("Invalid datatype: " + type.getClass().getSimpleName(), col);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.fields.ActivityInfo.java

/**
 * Applies the given value(s) for the specified field to the appropriate internal data field for reporting field to
 * the JKool Cloud./*w w  w  .  j  a  v a  2 s  . co  m*/
 *
 * @param field
 *            field to apply
 * @param value
 *            value to apply for this field, which could be an array of objects if value for field consists of
 *            multiple locations
 *
 * @throws ParseException
 *             if an error parsing the specified value based on the field definition (e.g. does not match defined
 *             format, etc.)
 */
public void applyField(ActivityField field, Object value) throws ParseException {
    LOGGER.log(OpLevel.TRACE,
            StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityInfo.applying.field"),
            field, value);
    Object[] values = Utils.makeArray(Utils.simplifyValue(value));

    List<ActivityFieldLocator> locators = field.getLocators();
    if (values != null && CollectionUtils.isNotEmpty(locators)) {
        if (locators.size() > 1 && locators.size() != values.length) {
            throw new ParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                    "ActivityInfo.failed.parsing", field), 0);
        }

        ActivityFieldLocator locator;
        Object fValue;
        List<Object> fvList = new ArrayList<>(locators.size());
        for (int v = 0; v < values.length; v++) {
            locator = locators.size() == 1 ? locators.get(0) : locators.get(v);
            fValue = formatValue(field, locator, values[v]);
            if (fValue == null && locator.isOptional()) {
                continue;
            }
            fvList.add(fValue);
        }

        values = fvList.toArray();

        if (field.isEnumeration() && values.length > 1) {
            throw new ParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                    "ActivityInfo.multiple.enum.values", field), 0);
        }
    }

    Object fieldValue = Utils.simplifyValue(values);

    if (fieldValue == null) {
        LOGGER.log(OpLevel.TRACE, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ActivityInfo.field.value.null"), field);
        return;
    }
    LOGGER.log(OpLevel.TRACE, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
            "ActivityInfo.applying.field.value"), field, Utils.toString(fieldValue));

    fieldValue = transform(field, fieldValue);
    fieldValue = filterFieldValue(field, fieldValue);

    if (!field.isTransparent()) {
        setFieldValue(field, fieldValue);
    } else {
        addActivityProperty(field.getFieldTypeName(), fieldValue, TRANSPARENT_PROP_TYPE);
    }
}

From source file:gov.nih.nci.cabig.caaers.utils.DateUtils.java

public static Date parseDate(String dateStr, String... parsePatterns) throws ParseException {

    if (dateStr == null || parsePatterns == null) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }/*from w  ww  .  j  av  a  2  s.c o m*/

    String strDate = dateStr;
    //do year correction. (partial year >=50 will be 1999 and <50 will be 2000)
    String[] parts = StringUtils.split(dateStr, '/');
    int len = parts.length;

    if (len != 3 || parts[0].length() > 2 || parts[1].length() > 2)
        throw new ParseException("Unable to parse the date " + strDate, -1);

    String yStr = parts[2];

    if (!(yStr.length() == 4 || yStr.length() == 2 || yStr.length() == 10))
        throw new ParseException("Unable to parse the date " + strDate, -1);
    if (yStr.length() == 2 && StringUtils.isNumeric(yStr)) {

        if (Integer.parseInt(yStr) < 50)
            yStr = "20" + yStr;
        else
            yStr = "19" + yStr;

        parts[2] = yStr;
        strDate = StringUtils.join(parts, '/');
    }

    //BJ: date formats are not thread save, so we need to create one each time.
    SimpleDateFormat parser = null;
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {
        if (i == 0) {
            parser = new SimpleDateFormat(parsePatterns[0]);
        } else {
            parser.applyPattern(parsePatterns[i]);
        }
        pos.setIndex(0);

        Date date = parser.parse(strDate, pos);
        if (date != null && pos.getIndex() == strDate.length()) {
            return date;
        }
    }
    throw new ParseException("Unable to parse the date: " + strDate, -1);
}