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.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParser.java

private Document cropDocumentForNode(Node xmlDoc) throws ParseException {
    if (xmlDoc.getParentNode() != null) { // if node is not document root node
        try {//from  www.j av a2  s .  co m
            Document nodeXmlDoc;
            synchronized (builder) {
                nodeXmlDoc = builder.newDocument();
            }
            Node importedNode = nodeXmlDoc.importNode(xmlDoc, true);
            nodeXmlDoc.appendChild(importedNode);

            return nodeXmlDoc;
        } catch (Exception exc) {
            ParseException pe = new ParseException(StreamsResources.getString(
                    StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityXmlParser.xmlDocument.parse.error"), 0);
            pe.initCause(exc);

            throw pe;
        }
    }

    return null;
}

From source file:org.inwiss.platform.common.util.StringUtil.java

/**
 * Converts a string to map. First string is split by a regexp to several
 * fragments, after this each fragment is split to two components by another
 * regexp. First component of each fragment is a key, while the second
 * component is corresponding value.//from   w w w. j  av a  2s  .c o  m
 *
 * @param str           string to parse
 * @param outerRegex    regex by which to split the string to fragments
 * @param innerRegex    regex by which to split fragment to key and value
 * @param trimOuter     if true, each fragment will be trimmed before
 * being split
 * @param trimInner     if true, each fragment's component will be trimmed
 * before being put to a map
 * @return map from keys to values
 * @throws java.text.ParseException thrown if one of fragments does not
 * contain a string which matches innerRegex
 */
public static Map stringToMap(String str, String outerRegex, String innerRegex, boolean trimOuter,
        boolean trimInner) throws ParseException {
    Map result = new HashMap();
    String[] fragments = str.split(outerRegex);
    for (int i = 0; i < fragments.length; i++) {
        String fragment = fragments[i];
        if (trimOuter) {
            fragment = fragment.trim();
        }
        String components[] = fragment.split(innerRegex, 2);
        if (components.length != 2) {
            throw new ParseException(innerRegex + " was expected but was not found in " + fragment, 0);
        }
        String key = components[0];
        String value = components[1];
        if (trimInner) {
            key = key.trim();
            value = value.trim();
        }
        result.put(key, value);
    }
    return result;
}

From source file:com.microsoft.tfs.util.datetime.LenientDateTimeParser.java

/**
 * Parse a free-form date and time first with the default format for the
 * default locale, then by parsing a list of known formats until one
 * succeeds. If the date cannot be parsed, ParseException is thrown.
 * <p>/*w  w  w.j a  v a2 s.c om*/
 * WARNING: GMT doesn't parse as a time zone in on my platform (JDK 1.5,
 * Linux). Use UTC in your input instead.
 * <p>
 * This method may be somewhat slow, although it is probably not an area of
 * concern for most programs. Because of the way SimpleDateFormat parses,
 * all of the longer, more precise patterns must be tried first (and these
 * are least likely to be used by the user). This means we must walk an
 * array for each search and common formats are necessarily near the end. In
 * reality, most searches can be done under a few (6) milliseconds on a 3
 * GHz computer.
 * <p>
 * <b>Notes on Default Date and Time</b>
 * <p>
 * The defaultDate and defaultTime parameters control whether the returned
 * Calendar has its date and/or time components set to the current date
 * and/or time (instead of the Date class epoch) when the given date time
 * string matches a pattern that does not specify <b>both</b> date and time
 * components. These parameters do <b>not</b> affect the order in which
 * patterns are tested or the criteria for a pattern match. They simply
 * choose which date or time is returned in the date- or time-only pattern
 * match where one of the components was unspecified. When either
 * defaultDate or defaultTime is false the Date class's epoch (1970/01/01
 * 00:00:00 UTC) is used for the default date or time.
 * <p>
 * Both defaultDate and defaultTime may be set to true, but as these
 * parameters do not affect the matching behavior, a given string missing
 * <b>both</b> date and time components will still match no patterns
 * (causing a ParseException to be thrown).
 *
 * @param dateTimeString
 *        the date string to parse (not null).
 * @param defaultDate
 *        if true and the given date time string matches a time-only
 *        pattern, today's date is used in the returned Calendar. If false
 *        and a time-only pattern is matched, 1970/01/01 is used for the
 *        date. See the method Javadoc for more information.
 * @param defaultTime
 *        if true and the given date time string matches a date-only
 *        pattern, the current time is used in the returned Calendar. If
 *        false and a date-only pattern is matched, 00:00:00 is used for the
 *        date. See the method Javadoc for more information.
 * @return a {@link LenientDateTimeResult} containing the date/time that was
 *         in the given dateTimeString and additional match information.
 * @throws ParseException
 *         if the date time string could not be parsed.
 */
public LenientDateTimeResult parseExtended(String dateTimeString, final boolean defaultDate,
        final boolean defaultTime) throws ParseException {
    Check.notNull(dateTimeString, "dateTimeString"); //$NON-NLS-1$

    final long start = System.currentTimeMillis();
    int i = 0;
    Calendar calendar = Calendar.getInstance(timeZone, locale);
    calendar.clear();

    // Java's SimpleDateFormat.parse() doesn't support some common time
    // zones, so we convert them before parsing.
    dateTimeString = convertUnsupportedTimeZones(dateTimeString);

    for (i = 0; i < expandedFormats.length; i++) {
        final LenientDateTimeFormat format = expandedFormats[i];

        try {
            calendar.setTime(format.getDateFormat().parse(dateTimeString));

            if (defaultDate && format.specifiesDate() == false) {
                /*
                 * We matched a pattern that doesn't specify a date and the
                 * user wants a default of today. Copy now's date info into
                 * ret.
                 */

                final Calendar now = new GregorianCalendar(timeZone, locale);
                calendar.set(Calendar.ERA, now.get(Calendar.ERA));
                calendar.set(Calendar.YEAR, now.get(Calendar.YEAR));
                calendar.set(Calendar.MONTH, now.get(Calendar.MONTH));
                calendar.set(Calendar.DATE, now.get(Calendar.DATE));
            }

            if (defaultTime && format.specifiesTime() == false) {
                /*
                 * We matched a pattern that doesn't specify a time and the
                 * user wants a default of now. Copy the parsed Calendar's
                 * date info into a new time.
                 */

                final Calendar newRet = new GregorianCalendar(timeZone, locale);
                newRet.set(Calendar.ERA, calendar.get(Calendar.ERA));
                newRet.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
                newRet.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
                newRet.set(Calendar.DATE, calendar.get(Calendar.DATE));

                calendar = newRet;
            }

            final String messageFormat = "matched at index {0} in {1} ms: {2}"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, i, (System.currentTimeMillis() - start),
                    dateTimeString);
            log.trace(message);

            return new LenientDateTimeResult(calendar, format.getDateFormat(), format.specifiesDate(),
                    format.specifiesTime());
        } catch (final ParseException e) {
            // Ignore and keep looping.
        }
    }

    String messageFormat = "no match in {0} ms: {1}"; //$NON-NLS-1$
    String message = MessageFormat.format(messageFormat, (System.currentTimeMillis() - start), dateTimeString);
    log.trace(message);

    messageFormat = Messages.getString("LenientDateTimeParser.UnknownDateFormat"); //$NON-NLS-1$
    message = MessageFormat.format(messageFormat, dateTimeString);
    throw new ParseException(message, 0);
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.GenericActivityParser.java

/**
 * Parse the specified prepared activity data, converting each field in prepared data to its corresponding value of
 * activity info item./*  www.  j a va  2  s .co  m*/
 *
 * @param cData
 *            prepared activity data item context to parse
 * @return converted activity info, or {@code null} if activity data is {@code null}
 * @throws ParseException
 *             if exception occurs applying locator format properties to specified value
 */
protected ActivityInfo parsePreparedItem(ActivityContext cData) throws ParseException {
    if (cData == null || cData.getData() == null) {
        return null;
    }

    ActivityInfo ai = new ActivityInfo();
    ActivityField field = null;
    cData.setActivity(ai);
    try {
        // apply fields for parser
        Object value;
        for (ActivityField aField : fieldList) {
            field = aField;
            cData.setField(aField);
            value = Utils.simplifyValue(parseLocatorValues(field, cData));

            applyFieldValue(field, value, cData);
        }
    } catch (Exception e) {
        ParseException pe = new ParseException(StreamsResources.getStringFormatted(
                StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityParser.parsing.failed", field), 0);
        pe.initCause(e);
        throw pe;
    }

    return ai;
}

From source file:com.zilotti.hostsjuggler.view.ActiveHostsFileWindow.java

/**
 * Parses a hosts file and loads it into its corresponding Javabean 
 * representation./*from   w ww .j  a v  a 2  s . co  m*/
 *  
 * @param hostsFile
 * @return
 * @throws IOException
 */
private HostsFile loadHostsFile(File hostsFile) throws IOException, ParseException {
    /* Object to be returned */
    HostsFile hostsFileObject = new HostsFile();

    BufferedReader br = null;

    int lineCounter = 1;
    try {
        br = new BufferedReader(new FileReader(hostsFile));

        String line = null;
        while ((line = br.readLine()) != null) {
            line += "\n";

            /* Remark */
            if (line.startsWith(REM_LINE_CHAR)) {
                CommentLine commentLine = new CommentLine();
                commentLine.setLine(line);
                hostsFileObject.addLine(commentLine);
            } else if (StringUtils.isBlank(line)) // Blank line
            {
                BlankLine blankLine = new BlankLine();
                blankLine.setLine(line);
                hostsFileObject.addLine(blankLine);
            } else {
                Scanner scanner = new Scanner(line);
                HostLine hostLine = new HostLine();

                if (scanner.hasNext()) {
                    /* Expects an IP address */
                    String ipAddress = scanner.next();

                    if (NetworkUtils.isIpAddress(ipAddress)) {
                        hostLine.setIpAddress(ipAddress);
                    } else
                        throw new ParseException("Expected an IP address but found '" + ipAddress + "'",
                                lineCounter);

                    /* Expects a list of hostnames */
                    List<String> hostNames = new LinkedList<String>();
                    String hostName = null;
                    while (scanner.hasNext()) {
                        hostName = scanner.next();

                        if (NetworkUtils.isHostName(hostName)) {
                            hostNames.add(hostName);
                        } else
                            throw new ParseException("Expected a hostname but found '" + hostName + "'",
                                    lineCounter);
                    }

                    hostLine.setHostNames(hostNames);
                    hostLine.setLine(line);
                    hostsFileObject.addLine(hostLine);
                }
            }
        }
    } finally {
        if (br != null)
            br.close();
    }

    return hostsFileObject;
}

From source file:com.silverpeas.util.StringUtil.java

/**
   * Decodes the specified text with hexadecimal values in bytes of those same values. The text is
   * considered to be in the UTF-8 charset.
   *//w w w .  j  a v a  2s.c  om
   * @param hexText the text with hexadecimal-based characters.
   * @return the binary representation of the text.
   * @throws ParseException if an odd number or illegal of characters is supplied.
   */
  public static byte[] fromHex(String hexText) throws ParseException {
      try {
          return Hex.decodeHex(hexText.toCharArray());
      } catch (DecoderException ex) {
          throw new ParseException(ex.getMessage(), -1);
      }
  }

From source file:py.una.pol.karaku.util.FormatProvider.java

private void throwException(String string, String format) throws ParseException {

    throw new ParseException("Imposible parsear cadena: " + string + " con formato " + format, 0);
}

From source file:org.paxle.core.norm.impl.ReferenceNormalizer.java

static String urlDecode(final String str, final Charset charset) throws ParseException {
    int percent = str.indexOf('%');
    if (percent == -1)
        return str;

    final StringBuffer sb = new StringBuffer(str.length()); // buffer to build the converted string
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(8); // buffer for conversion of contiguous %-encoded bytes
    int last = 0;
    final int len = str.length();
    do {/*from www.j a va  2s.  c o m*/
        sb.append(str.substring(last, percent)); // write non-encoded part

        // loop to convert sequence of %-encoded tokens into bytes. Contiguous byte-sequences have to be dealt with
        // in one block before decoding, because - dependant on the charset - more than one byte may be needed to
        // represent a single character. If the conversion to bytes was done sequentially, decoding might fail
        do {
            if (percent + 3 > str.length())
                throw new ParseException("unexpected end of input", percent + 3);
            final String token = str.substring(percent + 1, percent + 3);
            if (!token.matches("[0-9a-fA-F]{2}"))
                throw new ParseException("illegal url-encoded token '" + token + "'", percent);

            final int tokenValue = Integer.parseInt(token, 16) & 0xFF;
            baos.write(tokenValue);
            percent += 3;
        } while (percent < len && str.charAt(percent) == '%');

        if (baos.size() > 0) {
            final CharBuffer decoded = charset.decode(ByteBuffer.wrap(baos.toByteArray()));
            baos.reset(); // reuse the ByteArrayOutputStream in the next run
            for (int i = 0; i < decoded.length(); i++) {
                final char c = decoded.charAt(i);
                switch (c) {
                case '#':
                    sb.append("%23");
                    continue;
                case '%':
                    sb.append("%25");
                    continue;
                case '&':
                    sb.append("%26");
                    continue;
                case '=':
                    sb.append("%3D");
                    continue;
                case '?':
                    sb.append("%3F");
                    continue;
                default:
                    sb.append(c);
                    continue;
                }
            }
        }

        last = percent; // byte after the token
        percent = str.indexOf('%', last); // search for next token, returns -1 if last > len
    } while (percent != -1);
    return sb.append(str.substring(last)).toString();
}

From source file:hudson.plugins.dimensionsscm.DimensionsAPI.java

/**
 * Parses a base database specification//from ww w  .j  av  a 2  s  .c o  m
 * <p>
 * Valid patterns are dbName/dbPassword@dbConn or dbName@dbConn. Anything
 * else will cause a java.text.ParseException to be thrown. Returns an array
 * of either [dbName, dbConn, dbPassword] or [dbName, dbConn].
 *
 * @param database
 *            a base database specification
 * @return an array of base database specification components
 * @throws ParseException
 *             if the supplied String does not conform to the above rules
 */
private static String[] parseDatabaseString(String database) throws ParseException {
    String[] dbCompts;
    int endName = database.indexOf('/');
    int startConn = database.indexOf('@');
    if (startConn < 1 || startConn == database.length() - 1) {
        throw new ParseException(BAD_BASE_DATABASE_SPEC, startConn);
    }
    String dbName = null;
    String dbConn = null;
    String dbPassword = null;
    if (endName < 0 || startConn <= endName) {
        // no '/' or '@' is before '/':
        dbName = database.substring(0, startConn);
        dbConn = database.substring(startConn + 1);
        dbCompts = new String[2];
        dbCompts[0] = dbName;
        dbCompts[1] = dbConn;
    } else if (endName == 0 || startConn == endName + 1) {
        // '/' at start or '/' immediately followed by '@':
        throw new ParseException(BAD_BASE_DATABASE_SPEC, endName);
    } else {
        dbName = database.substring(0, endName);
        dbPassword = database.substring(endName + 1, startConn);
        dbConn = database.substring(startConn + 1);
        dbCompts = new String[3];
        dbCompts[0] = dbName;
        dbCompts[1] = dbConn;
        dbCompts[2] = dbPassword;
    }
    return dbCompts;
}

From source file:com.krawler.esp.servlets.importProjectPlanCSV.java

/**
 * Adds the task into proj_task and temp table. any exception will return a HashMap contining error description
 *//*from   w  ww .  j  a  v a 2s . co  m*/
protected HashMap<Integer, String> storeInDB(Connection conn, JSONObject temp, String projectid,
        String appendchoice, String userid, int totalOldTasks, int recordIndex) throws ServiceException {
    int skipped = 0;
    HashMap<Integer, String> skip = new HashMap<Integer, String>();
    try {
        int nonworkweekArr[] = projdb.getNonWorkWeekDays(conn, projectid);
        String holidayArr[] = projdb.getCompHolidays(conn, projectid, "");
        try {
            String tid = UUID.randomUUID().toString();
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            String startdate = StringUtil.serverHTMLStripper(temp.getString("startdate"));
            java.util.Date SDateVal = sdf.parse(startdate);
            startdate = sdf.format(SDateVal);
            Calendar cal = Calendar.getInstance();
            cal.setTime(SDateVal);
            java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd");
            boolean flag = true;
            while (flag) {
                if ((Arrays.binarySearch(nonworkweekArr, SDateVal.getDay()) >= 0
                        || Arrays.binarySearch(holidayArr, sdf1.format(SDateVal)) >= 0)) {
                    cal.setTime(SDateVal);
                    cal.add(Calendar.DATE, 1);
                    SDateVal = cal.getTime();
                    flag = true;
                } else {
                    flag = false;
                }
            }
            temp.remove("startdate");
            temp.put("startdate", sdf1.format(SDateVal));
            java.util.Date EDateVal = new Date();
            String acduration = "";
            String enddate = "";
            String dura = temp.getString("duration");
            if (!temp.getString("enddate").equals("")) {
                enddate = StringUtil.serverHTMLStripper(temp.getString("enddate"));
                EDateVal = sdf.parse(enddate);
                acduration = getActualDuration_importCSV(SDateVal, EDateVal, nonworkweekArr, holidayArr, dura);
            } else {
                if (!StringUtil.isNullOrEmpty(dura)) {
                    EDateVal = projdb.calculateEndDate(conn, SDateVal, dura, nonworkweekArr, holidayArr, "");
                    enddate = sdf.format(EDateVal);
                    acduration = dura;
                } else {
                    throw new ParseException("Insufficient Data", 0);
                }
            }

            temp.put("duration", acduration);
            temp.put("actstartdate", startdate);
            temp.put("enddate", enddate);
            temp.put("level", "0");
            temp.put("isparent", "false");
            temp.put("loginid", userid);
            temp.put("links", "");
            projdb.InsertTask(conn, temp, tid, projectid, Integer.toString(totalOldTasks));
            totalOldTasks++;
            DbUtil.executeUpdate(conn, "INSERT INTO tempImportData VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    new Object[] { recordIndex, tid, temp.getString("taskname"), temp.getString("duration"),
                            temp.getString("startdate"), temp.getString("enddate"),
                            temp.getInt("percentcomplete"), temp.getString("priority"), temp.getString("notes"),
                            temp.getString("resourcename"), temp.getString("predecessor"),
                            temp.getString("parent"), "" });
            String resnames = temp.getString("resourcename");
            String[] res = resnames.split(",");
            for (int c = 0; c < res.length; c++) {
                if (!StringUtil.equal(res[c], ""))
                    resNames.add(res[c]);
            }
        } catch (com.krawler.utils.json.base.JSONException ex) {
            //                skip.put(++skipped, MessageSourceProxy.getMessage(KWLErrorMsgs.importCSVInvFormat, null, locale));
            skip.put(++skipped, KWLErrorMsgs.importCSVInvFormat);
        } catch (ParseException ex) {
            //                skip.put(++skipped, MessageSourceProxy.getMessage(KWLErrorMsgs.importCSVInvDateFormat, null, locale));
            skip.put(++skipped, KWLErrorMsgs.importCSVInvDateFormat);
        } catch (ServiceException ex) {
            //                skip.put(++skipped, MessageSourceProxy.getMessage(KWLErrorMsgs.importCSVTaskFailure, null, locale));
            skip.put(++skipped, KWLErrorMsgs.importCSVTaskFailure);
        }
    } catch (ServiceException ex) {
        KrawlerLog.op.warn("Problem Storing Data In DB [importProjectPlanCSV.storeInDB()]:" + ex.toString());
        throw ServiceException.FAILURE("importProjectPlanCSV.storeInDB error", ex);
    }
    return skip;
}