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.pentaho.di.core.util.DateDetector.java

/**
 * /* w w w.  ja v a2  s .  c  om*/
 * @param dateString
 *          date string for parse
 * @param dateFormat
 *          format which should be applied for string
 * @return {@link java.util.Date} converted from dateString by format
 * @throws ParseException
 *           if we can not parse date string
 */
public static Date getDateFromStringByFormat(String dateString, String dateFormat) throws ParseException {
    if (dateFormat == null) {
        throw new ParseException("Unknown date format. Format is null. ", 0);
    }
    if (dateString == null) {
        throw new ParseException("Unknown date string. Date string is null. ", 0);
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
    simpleDateFormat.setLenient(false); // Don't automatically convert invalid date.
    return simpleDateFormat.parse(dateString);
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDateParser.java

@Override
public Date parse(final String source) throws ParseException {
    final ParsePosition pp = new ParsePosition(0);
    final Date date = parse(source, pp);
    if (date == null) {
        // Add a note re supported date range
        if (locale.equals(JAPANESE_IMPERIAL)) {
            throw new ParseException("(The " + locale + " locale does not support dates before 1868 AD)\n"
                    + "Unparseable date: \"" + source, pp.getErrorIndex());
        }//from  w ww  .  j  a v  a2s .  c om
        throw new ParseException("Unparseable date: " + source, pp.getErrorIndex());
    }
    return date;
}

From source file:com.turn.ttorrent.client.ConnectionHandler.java

/**
 * Validate an expected handshake on a connection.
 *
 * <p>/*  ww w .  j a  va  2s.c o  m*/
 * Reads an expected handshake message from the given connected socket,
 * parses it and validates that the torrent hash_info corresponds to the
 * torrent we're sharing, and that the peerId matches the peer ID we expect
 * to see coming from the remote peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer.
 * @param peerId The peer ID we expect in the handshake. If <em>null</em>,
 * any peer ID is accepted (this is the case for incoming connections).
 * @return The validated handshake message object.
 */
private Handshake validateHandshake(SocketChannel channel, byte[] peerId) throws IOException, ParseException {
    ByteBuffer len = ByteBuffer.allocate(1);
    ByteBuffer data;

    // Read the handshake from the wire
    logger.trace("Reading handshake size (1 byte) from {}...", this.socketRepr(channel));
    if (channel.read(len) < len.capacity()) {
        throw new IOException("Handshake size read underrrun");
    }

    len.rewind();
    int pstrlen = len.get();

    data = ByteBuffer.allocate(Handshake.BASE_HANDSHAKE_LENGTH + pstrlen);
    data.put((byte) pstrlen);
    int expected = data.remaining();
    int read = channel.read(data);
    if (read < expected) {
        throw new IOException("Handshake data read underrun (" + read + " < " + expected + " bytes)");
    }

    // Parse and check the handshake
    data.rewind();
    Handshake hs = Handshake.parse(data);
    if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
        throw new ParseException("Handshake for unknow torrent " + Utils.bytesToHex(hs.getInfoHash()) + " from "
                + this.socketRepr(channel) + ".", pstrlen + 9);
    }

    if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
        throw new ParseException("Announced peer ID " + Utils.bytesToHex(hs.getPeerId())
                + " did not match expected peer ID " + Utils.bytesToHex(peerId) + ".", pstrlen + 29);
    }

    return hs;
}

From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java

/**
 * Validate an expected handshake on a connection.
 *
 * <p>/* ww  w.j  a  v  a2 s.c om*/
 * Reads an expected handshake message from the given connected socket,
 * parses it and validates that the torrent hash_info corresponds to the
 * torrent we're sharing, and that the peerId matches the peer ID we expect
 * to see coming from the remote peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer.
 * @param peerId The peer ID we expect in the handshake. If <em>null</em>,
 * any peer ID is accepted (this is the case for incoming connections).
 * @return The validated handshake message object.
 */
private Handshake validateHandshake(SocketChannel channel, byte[] peerId) throws IOException, ParseException {
    ByteBuffer len = ByteBuffer.allocate(1);
    ByteBuffer data;

    // Read the handshake from the wire
    logger.trace("Reading handshake size (1 byte) from {}...", this.socketRepr(channel));
    if (channel.read(len) < len.capacity()) {
        throw new IOException("Handshake size read underrrun");
    }

    len.rewind();
    int pstrlen = len.get();

    data = ByteBuffer.allocate(Handshake.BASE_HANDSHAKE_LENGTH + pstrlen);
    data.put((byte) pstrlen);
    int expected = data.remaining();
    int read = channel.read(data);
    if (read < expected) {
        throw new IOException("Handshake data read underrun (" + read + " < " + expected + " bytes)");
    }

    // Parse and check the handshake
    data.rewind();
    Handshake hs = Handshake.parse(data);
    if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
        throw new ParseException("Handshake for unknow torrent "
                + Torrent.byteArrayToHexString(hs.getInfoHash()) + " from " + this.socketRepr(channel) + ".",
                pstrlen + 9);
    }

    if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
        throw new ParseException(
                "Announced peer ID " + Torrent.byteArrayToHexString(hs.getPeerId())
                        + " did not match expected peer ID " + Torrent.byteArrayToHexString(peerId) + ".",
                pstrlen + 29);
    }

    return hs;
}

From source file:com.ettrema.zsync.Upload.java

/**
 * Parses a String header by setting the appropriate field in upload if the key is recognized 
 * and ignoring keys that are not recognized.
 * /*w  w  w.  j a  v a  2 s  .c om*/
 * @param key The key String with leading/trailing whitespace omitted
 * @param value The value String with leading/trailing whitespace omitted
 * @throws ParseException if the value of a recognized key cannot be properly parsed
 */
private void parseParam(String key, String value) throws ParseException {

    if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {

        return;
    }
    try {
        if (key.equalsIgnoreCase(VERSION)) {
            this.setVersion(value);
        } else if (key.equalsIgnoreCase(FILELENGTH)) {
            this.setFilelength(Long.parseLong(value));
        } else if (key.equalsIgnoreCase(BLOCKSIZE)) {
            this.setBlocksize(Long.parseLong(value));
        } else if (key.equalsIgnoreCase(SHA_1)) {
            this.setSha1(value);
        }
    } catch (NumberFormatException ex) {

        throw new ParseException("Cannot parse " + value + " into a long.", -1);
    }
}

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

private XmlRecord readData(final int aRowNum, final XmlRecordEntity aRecord, final List<XmlField> aFields)
        throws ParseException {
    Map<String, Object> data = new HashMap<String, Object>();
    for (int i = 0; i < aFields.size(); i++) {
        XmlField field = aFields.get(i);
        XmlRecordDataEntity d = aRecord.data.get(i);

        String value = d.value;/*from   w  w w  .  j  a va 2 s .  co m*/

        if (nullString.equals(value)) {
            data.put(field.name, null);
        } else {
            if (FieldType.String == field.type) {
                String obj = value;
                data.put(field.name, obj);
            } else if (FieldType.Boolean == field.type) {
                Boolean obj = Boolean.parseBoolean(value);
                data.put(field.name, obj);
            } else if (FieldType.Integer == field.type) {
                Double obj = Double.parseDouble(value);
                data.put(field.name, Integer.valueOf(obj.intValue()));
            } else if (FieldType.Long == field.type) {
                Double obj = Double.parseDouble(value);
                data.put(field.name, Long.valueOf(obj.longValue()));
            } else if (FieldType.Float == field.type) {
                Float obj = Float.parseFloat(value);
                data.put(field.name, obj);
            } else if (FieldType.Double == field.type) {
                Double obj = Double.parseDouble(value);
                data.put(field.name, obj);
            } else if (FieldType.Timestamp == field.type) {
                Timestamp obj = new Timestamp(
                        new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(value).getTime());
                data.put(field.name, obj);
            } else if (FieldType.Date == field.type) {
                Timestamp ts = new Timestamp(new SimpleDateFormat("yyyy/MM/dd").parse(value).getTime());
                Date obj = new Date(ts.getTime());
                data.put(field.name, obj);
            } else if (FieldType.Time == field.type) {
                Timestamp ts = new Timestamp(new SimpleDateFormat("HH:mm:ss").parse(value).getTime());
                Time obj = new Time(ts.getTime());
                data.put(field.name, obj);
            } else {
                throw new ParseException("Undefined type.[" + field.getType() + "]", aRowNum);
            }
        }
    }

    XmlRecord record = new XmlRecord();
    record.data = data;
    return record;
}

From source file:org.dspace.app.itemupdate.MetadataUtilities.java

/**
 *    Parses metadata field given in the form <schema>.<element>[.<qualifier>|.*]
 *    checks for correct number of elements (2 or 3) and for empty strings
 *    //from  ww w . ja  v a  2s.c  o m
 *    @return String Array
 *    @throws ParseException if validity checks fail
 *    
 */
public static String[] parseCompoundForm(String compoundForm) throws ParseException {
    String[] ar = compoundForm.split("\\s*\\.\\s*"); //trim ends

    if ("".equals(ar[0])) {
        throw new ParseException("schema is empty string: " + compoundForm, 0);
    }

    if ((ar.length < 2) || (ar.length > 3) || "".equals(ar[1])) {
        throw new ParseException("element is malformed or empty string: " + compoundForm, 0);
    }

    return ar;
}

From source file:com.s3d.webapps.util.time.DateUtils.java

/**
 * <p>Parses a string representing a date by trying a variety of different parsers.</p>
 * /*from   w ww.jav a 2  s .  co  m*/
 * <p>The parse will try each parse pattern in turn.
 * A parse is only deemed successful if it parses the whole of the input string.
 * If no parse patterns match, a ParseException is thrown.</p>
 * 
 * @param str  the date to parse, not null
 * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
 * @param lenient Specify whether or not date/time parsing is to be lenient.
 * @return the parsed date
 * @throws IllegalArgumentException if the date string or pattern array is null
 * @throws ParseException if none of the date patterns were suitable
 * @see java.util.Calender#isLenient()
 */
private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient)
        throws ParseException {
    if (str == null || parsePatterns == null) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }

    SimpleDateFormat parser = new SimpleDateFormat();
    parser.setLenient(lenient);
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {

        String pattern = parsePatterns[i];

        // LANG-530 - need to make sure 'ZZ' output doesn't get passed to SimpleDateFormat
        if (parsePatterns[i].endsWith("ZZ")) {
            pattern = pattern.substring(0, pattern.length() - 1);
        }

        parser.applyPattern(pattern);
        pos.setIndex(0);

        String str2 = str;
        // LANG-530 - need to make sure 'ZZ' output doesn't hit SimpleDateFormat as it will ParseException
        if (parsePatterns[i].endsWith("ZZ")) {
            int signIdx = indexOfSignChars(str2, 0);
            while (signIdx >= 0) {
                str2 = reformatTimezone(str2, signIdx);
                signIdx = indexOfSignChars(str2, ++signIdx);
            }
        }

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

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

private void highlightActiveHostsFile(File hostsFile) throws IOException, ParseException {
    BufferedReader br = null;//from  ww w  .j  a v a2s. co m

    try {
        /* Converts the file to text */
        // StringReader fileReader = new StringReader(getLinuxHostsFile()); // For testing
        br = new BufferedReader(new FileReader(hostsFile));

        /* Character counter */
        int charCounter = 0;

        /* Line counter */
        int lineCounter = 1;

        /* Line */
        String line = null;

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

            /*
             * Remark line
             */
            if (line.startsWith(REM_LINE_CHAR)) {
                int prevCharCounter = charCounter;
                charCounter += line.length();

                formatRemark(prevCharCounter, charCounter);

                if (log.isTraceEnabled()) {
                    log.trace("line  ='" + line + "'");
                    //log.trace("remark='"+ getWindowsHostsFile().substring(prevCharCounter, charCounter) +"' ("+ prevCharCounter +","+ charCounter +")");
                }
            } else if (StringUtils.isBlank(line)) // Empty line
            {
                charCounter += line.length();
            } else // Expects a host line
            {
                int localCharCounter = charCounter;
                charCounter += line.length();

                Scanner scanner = new Scanner(line);
                scanner.useDelimiter(Pattern.compile("(\\s)"));

                /* Output of the parsing code */
                String ipAddress = null;

                /* Verifies the number of tokens. At least two must exist (IP address and one name) */
                if (scanner.hasNext()) {
                    /* The first token must be an IP address */
                    {
                        ipAddress = scanner.next();

                        if (!NetworkUtils.isIpAddress(ipAddress))
                            throw new ParseException("IP address expected. Token found: " + ipAddress,
                                    lineCounter);

                        int prevCharCounter = localCharCounter;
                        localCharCounter += ipAddress.length() + 1; // Sums 1 because of the lost space

                        formatIpAddress(prevCharCounter, localCharCounter);
                    }

                    /* The remaining tokens are the host names associated to the IP address */
                    {
                        while (scanner.hasNext()) {
                            String hostName = scanner.next();

                            if (StringUtils.isWhitespace(hostName) || StringUtils.isBlank(hostName)) {
                                localCharCounter++;
                            } else if (NetworkUtils.isHostName(hostName)) {
                                int prevCharCounter = localCharCounter;
                                localCharCounter += hostName.length() + 1; // 1 to compensate the space lost

                                //                        if(log.isTraceEnabled())
                                //                           log.trace("hostName='"+ getWindowsHostsFile().substring(prevCharCounter, localCharCounter) +"' ("+ prevCharCounter +","+ localCharCounter +")");

                                formatHostName(prevCharCounter, localCharCounter);
                            } else
                                throw new ParseException("Host name expected at token " + localCharCounter
                                        + ". Found: " + hostName, lineCounter);
                        }
                    }
                } else
                    throw new ParseException("At least 2 tokens are expected from a host line.", lineCounter);
            }

            lineCounter++;
        }
    } finally {
        if (br != null)
            br.close();
    }
}

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

/**
 * Gets field raw data value resolved by locator and formats it according locator definition.
 *
 * @param locator/*from   www . jav  a2s.c  om*/
 *            activity field locator
 * @param cData
 *            activity object XML DOM document
 * @param formattingNeeded
 *            flag to set if value formatting is not needed
 * @return value formatted based on locator definition or {@code null} if locator is not defined
 *
 * @throws ParseException
 *             if exception occurs while resolving raw data value or applying locator format properties to specified
 *             value
 *
 * @see ActivityFieldLocator#formatValue(Object)
 */
@Override
protected Object resolveLocatorValue(ActivityFieldLocator locator, ActivityContext cData,
        AtomicBoolean formattingNeeded) throws ParseException {
    Object val = null;
    String locStr = locator.getLocator();
    Node xmlDoc = cData.getData();

    if (ActivityField.isDynamicAttr(locStr)) {
        ActivityInfo ai = cData.getActivity();
        locStr = StreamsCache.fillInKeyPattern(locStr, ai, this.getName());
    }

    if (StringUtils.isNotEmpty(locStr)) {
        Document nodeDocument = cropDocumentForNode(xmlDoc);
        try {
            XPathExpression expr;
            synchronized (xPath) {
                expr = xPath.compile(locStr);
            }

            if (nodeDocument != null) { // try expression relative to node
                val = resolveValueOverXPath(nodeDocument, expr, formattingNeeded);
            }
            if (val == null) { // otherwise try on complete document
                val = resolveValueOverXPath(xmlDoc, expr, formattingNeeded);
            }

            if (val instanceof Node) {
                Node node = (Node) val;

                if (!isNodeSupportedByStackedParser(cData.getField(), node)) {
                    val = getTextContent(locator, node);
                }
            }
        } catch (XPathExpressionException exc) {
            ParseException pe = new ParseException(StreamsResources
                    .getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityXMLParser.xPath.exception"), 0);
            pe.initCause(exc);

            throw pe;
        }
    }

    return val;
}