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:org.apache.metron.parsers.utils.DateUtils.java

/**
 * Parse the data according to a sequence of possible parse patterns.
 * /*from w w  w  . jav a  2s .  c o  m*/
 * If the given date is entirely numeric, it is assumed to be a unix
 * timestamp.
 * 
 * If the year is not specified in the date string, use the current year.
 * Assume that any date more than 4 days in the future is in the past as per
 * SyslogUtils
 * 
 * @param candidate
 *            The possible date.
 * @param validPatterns
 *            A list of SimpleDateFormat instances to try parsing with.
 * @return A java.util.Date based on the parse result
 * @throws ParseException
 */
public static long parseMultiformat(String candidate, List<SimpleDateFormat> validPatterns)
        throws ParseException {
    if (StringUtils.isNumeric(candidate)) {
        return Long.valueOf(candidate);
    } else {
        for (SimpleDateFormat pattern : validPatterns) {
            try {
                Calendar cal = Calendar.getInstance();
                cal.setTime(pattern.parse(candidate));
                Calendar current = Calendar.getInstance();
                if (cal.get(Calendar.YEAR) == 1970) {
                    cal.set(Calendar.YEAR, current.get(Calendar.YEAR));
                }
                current.add(Calendar.DAY_OF_MONTH, 4);
                if (cal.after(current)) {
                    cal.add(Calendar.YEAR, -1);
                }
                return cal.getTimeInMillis();
            } catch (ParseException e) {
                continue;
            }
        }
        throw new ParseException("Failed to parse any of the given date formats", 0);
    }
}

From source file:wicket.markup.parser.filter.HtmlHandler.java

/**
 * Get the next MarkupElement from the parent MarkupFilter and handle it if
 * the specific filter criteria are met. Depending on the filter, it may
 * return the MarkupElement unchanged, modified or it remove by asking the
 * parent handler for the next tag.//  w w  w.  ja v a  2s . co m
 * 
 * @see wicket.markup.parser.IMarkupFilter#nextTag()
 * @return Return the next eligible MarkupElement
 */
public MarkupElement nextTag() throws ParseException {
    // Get the next tag. If null, no more tags are available
    final ComponentTag tag = nextComponentTag();
    if (tag == null) {
        // No more tags from the markup.
        // If there's still a non-simple tag left, it's an error
        while (stack.size() > 0) {
            final ComponentTag top = stack.peek();

            if (!requiresCloseTag(top.getName())) {
                stack.pop();
            } else {
                throw new ParseException("Tag " + top + " at " + top.getPos() + " did not have a close tag",
                        top.getPos());
            }
        }

        return tag;
    }

    if (log.isDebugEnabled()) {
        log.debug("tag: " + tag.toUserDebugString() + ", stack: " + stack);
    }

    // Check tag type
    if (tag.isOpen()) {
        // Push onto stack
        stack.push(tag);
    } else if (tag.isClose()) {
        // Check that there is something on the stack
        if (stack.size() > 0) {
            // Pop the top tag off the stack
            ComponentTag top = stack.pop();

            // If the name of the current close tag does not match the
            // tag on the stack then we may have a mismatched close tag
            boolean mismatch = !top.hasEqualTagName(tag);

            if (mismatch) {
                top.setHasNoCloseTag(true);

                // Pop any simple tags off the top of the stack
                while (mismatch && !requiresCloseTag(top.getName())) {
                    top.setHasNoCloseTag(true);

                    // Pop simple tag
                    top = stack.pop();

                    // Does new top of stack mismatch too?
                    mismatch = !top.hasEqualTagName(tag);
                }

                // If adjusting for simple tags did not fix the problem,
                // it must be a real mismatch.
                if (mismatch) {
                    throw new ParseException("Tag " + top.toUserDebugString()
                            + " has a mismatched close tag at " + tag.toUserDebugString(), top.getPos());
                }
            }

            // Tag matches, so add pointer to matching tag
            tag.setOpenTag(top);
        } else {
            throw new ParseException("Tag " + tag.toUserDebugString() + " does not have a matching open tag",
                    tag.getPos());
        }
    } else if (tag.isOpenClose()) {
        // Tag closes itself
        tag.setOpenTag(tag);
    }

    return tag;
}

From source file:org.apache.hadoop.chukwa.rest.bean.ParametersBean.java

public ParametersBean(JSONObject json) throws ParseException {
    try {//from ww w.  j  a  v a  2s  .  c o  m
        name = json.getString("name");
        type = json.getString("type");
        if (json.has("value")) {
            if (json.get("value").getClass() == JSONArray.class) {
                JSONArray ja = json.getJSONArray("value");
                Collection<String> c = new HashSet<String>();
                for (int i = 0; i < ja.length(); i++) {
                    c.add(ja.getString(i));
                }
                this.value = c;
            } else {
                Collection<String> c = new HashSet<String>();
                c.add(json.getString("value"));
                this.value = c;
            }
        }
        if (json.has("label")) {
            label = json.getString("label");
        } else {
            label = json.getString("name");
        }
        if (json.get("type").toString().intern() == "custom".intern()) {
            control = json.getString("control");
        }
        if (json.has("callback")) {
            callback = json.getString("callback");
        }
        if (json.has("options")) {
            JSONArray aj = json.getJSONArray("options");
            options = new OptionBean[aj.length()];
            for (int i = 0; i < aj.length(); i++) {
                OptionBean o = new OptionBean(aj.getJSONObject(i));
                options[i] = o;
            }
        }
        if (json.has("edit")) {
            edit = json.getInt("edit");
        }
    } catch (Exception e) {
        log.error(ExceptionUtil.getStackTrace(e));
        throw new ParseException(ExceptionUtil.getStackTrace(e), 0);
    }
}

From source file:org.ameba.http.Response.java

/**
 * Checks whether all mandatory fields are set on the String passed as {@literal s} and parses this String into a valid instance.
 *
 * @param s The String to get the mandatory fields from
 * @return The instance/* ww w.  j  av  a2  s.co m*/
 * @throws ParseException In case the passen String didn't match
 */
public static Response<?> parse(String s) throws ParseException {
    if (s.contains("message") && s.contains("messageKey") && s.contains("httpStatus") && s.contains("class")) {
        Object d = Configuration.defaultConfiguration().jsonProvider().parse(s);
        String[] obj = read(d, "$.obj");
        Response<?> r = new Response<>(read(d, "$.message"), read(d, "$.messageKey"), read(d, "$.httpStatus"),
                obj);
        r.any();
    }
    throw new ParseException(String.format("String does not contain mandatory fields. [%s]", s), -1);
}

From source file:io.moquette.spi.impl.security.ResourceAuthenticator.java

private void parse(Reader reader) throws ParseException {
    if (reader == null) {
        return;//from  w  w  w.jav  a 2  s .c  o  m
    }

    BufferedReader br = new BufferedReader(reader);
    String line;
    try {
        while ((line = br.readLine()) != null) {
            int commentMarker = line.indexOf('#');
            if (commentMarker != -1) {
                if (commentMarker == 0) {
                    // skip its a comment
                    continue;
                } else {
                    // it's a malformed comment
                    throw new ParseException(line, commentMarker);
                }
            } else {
                if (line.isEmpty() || line.matches("^\\s*$")) {
                    // skip it's a black line
                    continue;
                }

                // split till the first space
                int delimiterIdx = line.indexOf(':');
                String username = line.substring(0, delimiterIdx).trim();
                String password = line.substring(delimiterIdx + 1).trim();

                m_identities.put(username, password);
            }
        }
    } catch (IOException ex) {
        throw new ParseException("Failed to read", 1);
    }
}

From source file:org.araqne.confdb.file.Importer.java

private void parseCollections(JSONTokener t, Manifest manifest, List<ConfigChange> configChanges)
        throws JSONException, ParseException, IOException {
    Object key = t.nextValue();//from   w  ww.j  a  v  a  2  s.  c  o  m
    if (!key.equals("collections"))
        throw new ParseException("collections should be placed after metadata: token is " + key, -1);

    // "collections":{"COLNAME":["list",[...]]}
    t.nextClean(); // :
    t.nextClean(); // {

    if (t.nextClean() == '}')
        return;
    t.back();

    int i = 0;
    List<String> importColNames = new ArrayList<String>();
    while (true) {
        if (i++ != 0)
            t.nextClean();

        String colName = (String) t.nextValue();
        importColNames.add(colName);
        CollectionEntry collectionEntry = checkCollectionEntry(manifest, colName);
        manifest.add(collectionEntry);

        t.nextTo('[');
        t.nextClean();

        // type token (should be 'list')
        t.nextValue();
        t.nextTo("[");
        t.nextClean();

        // check empty config list
        char c = t.nextClean();
        if (c == ']') {
            t.nextClean(); // last ']'
            char marker = t.nextClean(); // ',' or '}'
            if (marker == '}')
                break;
            else
                t.back();

            continue;
        }

        t.back();

        int collectionId = collectionEntry.getId();
        RevLogWriter writer = null;
        try {
            File logFile = new File(db.getDbDirectory(), "col" + collectionId + ".log");
            File datFile = new File(db.getDbDirectory(), "col" + collectionId + ".dat");

            writer = new RevLogWriter(logFile, datFile);

            while (true) {
                @SuppressWarnings("unchecked")
                Object doc = removeType((List<Object>) parse((JSONArray) t.nextValue()));
                ConfigEntry configEntry = writeConfigEntry(writer, doc, collectionId);
                configChanges.add(new ConfigChange(CommitOp.CreateDoc, colName, collectionEntry.getId(),
                        configEntry.getDocId()));
                manifest.add(configEntry);

                // check next list item
                char delimiter = t.nextClean();
                if (delimiter == ']')
                    break;
            }
        } finally {
            if (writer != null)
                writer.close();
        }

        // end of list
        t.nextClean();

        char delimiter = t.nextClean();
        if (delimiter == '}')
            break;
    }

    for (String colName : db.getCollectionNames()) {
        if (importColNames.contains(colName))
            continue;
        configChanges.add(new ConfigChange(CommitOp.DropCol, colName, 0, 0));
        manifest.remove(new CollectionEntry(db.getCollectionId(colName), colName));
    }
}

From source file:org.osaf.cosmo.calendar.ICalValueParser.java

/**
 * Parses the text value.//w  ww .j  a va  2 s  .  com
 */
public void parse() throws ParseException {
    int nextToken = nextToken();
    // log.debug("starting token: " + tokenizer);
    if (nextToken != ';')
        return;

    nextToken = nextToken();
    while (nextToken != ':' && nextToken != StreamTokenizer.TT_EOF) {
        // log.debug("param name token: " + tokenizer);
        if (nextToken != StreamTokenizer.TT_WORD)
            throw new ParseException("expected word, read " + tokenizer.ttype, 1);
        String name = tokenizer.sval;

        nextToken = nextToken();
        // log.debug("param = token: " + tokenizer);
        if (nextToken != '=')
            throw new ParseException("expected =, read " + tokenizer.ttype, 1);

        nextToken = nextToken();
        // log.debug("param val token: " + tokenizer);
        if (!(nextToken == StreamTokenizer.TT_WORD || nextToken == '"'))
            throw new ParseException("expected word, read " + tokenizer.ttype, 1);
        String value = tokenizer.sval;

        // log.debug("parameter " + name + ": " + value);

        params.put(name, value);

        nextToken = nextToken();
        // log.debug("post param token: " + tokenizer);

        if (nextToken == ':')
            break;
        else if (nextToken == ';')
            nextToken = nextToken();
        else
            throw new ParseException("expected either : or ;, read " + tokenizer.ttype, 1);
    }

    nextToken = nextToken();
    // log.debug("prop val token: " + tokenizer);
    if (nextToken != StreamTokenizer.TT_WORD)
        throw new ParseException("expected " + StreamTokenizer.TT_WORD + ", read " + tokenizer.ttype, 1);
    value = tokenizer.sval;

    // log.debug("property: " + value + ", params: " + params);
}

From source file:org.azkfw.datasource.xml.XmlDatasourceFactory.java

/**
 * XML???//  w w w  .j a  v a  2 s  . c  om
 * 
 * @param aName ??
 * @param aFile XML
 * @return 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Datasource generate(final String aName, final File aFile)
        throws FileNotFoundException, ParseException, IOException {
    XmlDatasource datasource = new XmlDatasource();
    datasource.name = aName;

    List<XmlTableEntity> tableList = null;

    InputStream stream = null;
    try {
        stream = new FileInputStream(aFile);
        Digester digester = new Digester();

        digester.addObjectCreate("datasource/tables", ArrayList.class);

        digester.addObjectCreate("datasource/tables/table", XmlTableEntity.class);
        digester.addSetProperties("datasource/tables/table");
        digester.addSetNext("datasource/tables/table", "add");

        digester.addObjectCreate("datasource/tables/table/fields", ArrayList.class);
        digester.addSetNext("datasource/tables/table/fields", "setFields");

        digester.addObjectCreate("datasource/tables/table/fields/field", XmlFieldEntity.class);
        digester.addSetProperties("datasource/tables/table/fields/field");
        digester.addSetNext("datasource/tables/table/fields/field", "add");

        digester.addObjectCreate("datasource/tables/table/records", ArrayList.class);
        digester.addSetNext("datasource/tables/table/records", "setRecords");

        digester.addObjectCreate("datasource/tables/table/records/record", XmlRecordEntity.class);
        digester.addSetNext("datasource/tables/table/records/record", "add");

        digester.addObjectCreate("datasource/tables/table/records/record/data", XmlRecordDataEntity.class);
        digester.addSetProperties("datasource/tables/table/records/record/data");
        digester.addSetNext("datasource/tables/table/records/record/data", "add");

        tableList = digester.parse(stream);
    } catch (SAXException ex) {
        throw new ParseException(ex.getMessage(), -1);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (null != stream) {
            try {
                stream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    List<XmlTable> tables = new ArrayList<XmlTable>();
    for (XmlTableEntity t : tableList) {
        XmlTable table = new XmlTable();
        table.label = t.label;
        table.name = t.name;

        // Read Field
        List<XmlField> fields = new ArrayList<XmlField>();
        for (int col = 0; col < t.fields.size(); col++) {
            XmlFieldEntity f = t.fields.get(col);
            XmlField field = readField(col, f);
            fields.add(field);
        }

        // Read Data
        List<XmlRecord> records = new ArrayList<XmlRecord>();
        for (int row = 0; row < t.records.size(); row++) {
            XmlRecordEntity r = t.records.get(row);
            if (r.data.size() == fields.size()) {
                XmlRecord record = readData(row, r, fields);
                records.add(record);
            } else {
                System.out.println(
                        "Skip row(unmatch field count).[table: " + table.getName() + "; row: " + r + ";]");
            }
        }

        table.fields = (List) fields;
        table.records = (List) records;

        tables.add(table);
    }

    datasource.tables = (List) tables;
    return datasource;
}

From source file:com.worldline.easycukes.rest.utils.DateHelper.java

/**
 * Used to get date value//from www.ja v a  2 s  .co m
 *
 * @param expression the expression to parse
 * @return the date value in json format for the specified expression
 * @throws ParseException
 */
public static String getDateValue(@NonNull final String expression) throws ParseException {
    log.info("Getting the date value from " + expression);
    final Calendar calendar = Calendar.getInstance();
    if (!expression.contains(RestConstants.YESTERDAY) && !expression.contains(RestConstants.TODAY)
            && !expression.contains(RestConstants.TOMORROW))
        return parseDateToJson(expression);

    int value = 0;
    int calendarField = -1;
    String toAdd = null;
    if (expression.startsWith(RestConstants.TODAY))
        toAdd = expression.substring(expression.indexOf(RestConstants.TODAY) + RestConstants.TODAY.length());
    else if (expression.startsWith(RestConstants.YESTERDAY)) {
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        toAdd = expression
                .substring(expression.indexOf(RestConstants.YESTERDAY) + RestConstants.YESTERDAY.length());
    } else if (expression.startsWith(RestConstants.TOMORROW)) {
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        toAdd = expression
                .substring(expression.indexOf(RestConstants.TOMORROW) + RestConstants.TOMORROW.length());
    } else
        throw new ParseException("the date expression is not valid ! : " + expression, 0);
    if (StringUtils.isNotEmpty(toAdd)) {
        if (toAdd.endsWith("year")) {
            value = Integer.valueOf(toAdd.substring(0, toAdd.indexOf("year")));
            calendarField = Calendar.YEAR;
        } else if (toAdd.endsWith("day")) {
            value = Integer.valueOf(toAdd.substring(0, toAdd.indexOf("day")));
            calendarField = Calendar.DAY_OF_MONTH;
        } else if (toAdd.endsWith("month")) {
            value = Integer.valueOf(toAdd.substring(0, toAdd.indexOf("month")));
            calendarField = Calendar.MONTH;
        } else {
            value = Integer.valueOf(toAdd);
            calendarField = Calendar.DAY_OF_MONTH;
        }
        calendar.add(calendarField, value);

    }
    return convertDateToJsonFormat(calendar.getTime());
}

From source file:com.ksa.myanmarlottery.service.parser.ExcelFileParser.java

@Override
public List<Result> getResult(InputStream in) throws FileNotFoundException, IOException, ParseException {
    List<Prize> prizes = null;
    List<Result> resultList = new ArrayList<>();
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"); // 01-May-2017
    try {/* ww  w .  ja  va  2  s . com*/
        Workbook workbook = new XSSFWorkbook(in);
        Sheet datatypeSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = datatypeSheet.iterator();

        while (iterator.hasNext()) {

            Row currentRow = iterator.next();
            Cell cell0 = currentRow.getCell(0); // get first cell.

            if (cell0.getCellTypeEnum() == CellType.NUMERIC) {
                int numberic = (int) cell0.getNumericCellValue();
                log.info("Numberic - " + numberic);

                // check lottery type
                if (ConstantUtil.OLD_LOTTERY_TYPE == numberic || ConstantUtil.NEW_LOTTERY_TYPE == numberic) { // for lottery type result
                    Result result = new Result();
                    result.setType(numberic);
                    result.setNumberOfTimes((int) currentRow.getCell(1).getNumericCellValue());
                    //                        result.setResultFor(format.parse(currentRow.getCell(2).toString()));
                    result.setResultFor(currentRow.getCell(2).getDateCellValue());
                    result.setDataProvider(currentRow.getCell(3).getStringCellValue());
                    result.setCompanyName(currentRow.getCell(4).getStringCellValue());

                    prizes = new ArrayList<>();
                    result.setPrizes(prizes);
                    resultList.add(result);
                }

            } else if (cell0.getCellTypeEnum() == CellType.STRING) { // result data
                String character = cell0.getStringCellValue();
                log.info("character - " + character);

                // check validation for character.
                String value = charMap.get(character);
                if (value == null) {
                    throw new ParseException(
                            "Character is Not valid at Row: " + currentRow.getRowNum() + " > column:" + 0, 400);
                }
                Cell cell1 = currentRow.getCell(1);
                if (cell1.getCellTypeEnum() != CellType.NUMERIC) {
                    throw new ParseException(
                            "Should be Number at Row: " + currentRow.getRowNum() + " > column:" + 1, 400);
                }
                log.info("Cell Type " + cell1.getCellTypeEnum());
                int code = (int) cell1.getNumericCellValue();
                log.info("code - " + code + " Row:" + currentRow.getRowNum() + " > column:" + 1);
                String prizeTitle = currentRow.getCell(2).getStringCellValue();
                log.info("prizeTitle - " + prizeTitle);
                String prizeDesc = currentRow.getCell(4).getStringCellValue();
                log.info("prizeDesc - " + prizeDesc);
                prizes.add(new Prize(character, code, prizeTitle, prizeDesc));
            }
        }
        log.info("resultList size: " + resultList.size());
        for (Result r : resultList) {
            log.info("prizeList size: " + r.getPrizes().size());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
    return resultList;
}