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.playonlinux.wine.registry.RegistryParser.java

public RegistryKey parseFile() throws IOException, ParseException {
    BufferedReader bufferReader = new BufferedReader(new FileReader(registryFile));
    RegistryKey root = new RegistryKey(rootName);
    RegistryKey lastNode = null;/*  www  .ja v  a2 s.  c  o m*/
    String currentLine;
    int lineNumber = 1;
    do {
        currentLine = bufferReader.readLine();
        if (currentLine == null) {
            break;
        }

        if (currentLine.startsWith(";") || currentLine.startsWith("#") || StringUtils.isBlank(currentLine)
                || currentLine.startsWith("@")) {
            lineNumber++;
            continue;
        }

        if (currentLine.startsWith("[")) {
            lastNode = this.parseDirectoryLine(root, currentLine);
        } else {
            if (lineNumber == 1) {
                lineNumber++;
                continue;
            } else if (lastNode == null) {
                throw new ParseException(
                        String.format("Invalid registry file. Error found line %s", lineNumber), 0);
            } else {
                this.parseValueLine(lastNode, currentLine, lineNumber);
            }
        }
        lineNumber++;
    } while (currentLine != null);

    return root;
}

From source file:be.brunoparmentier.openbikesharing.app.parsers.BikeNetworksListParser.java

public BikeNetworksListParser(String toParse) throws ParseException {
    bikeNetworks = new ArrayList<>();

    try {/*from ww  w  .j  av a 2  s  . com*/
        JSONObject jsonObject = new JSONObject(toParse);
        JSONArray rawNetworks = jsonObject.getJSONArray("networks");
        for (int i = 0; i < rawNetworks.length(); i++) {
            JSONObject rawNetwork = rawNetworks.getJSONObject(i);

            String id = rawNetwork.getString("id");
            String name = rawNetwork.getString("name");
            String company = rawNetwork.getString("company");
            BikeNetworkLocation location;

            /* network location */
            {
                JSONObject rawLocation = rawNetwork.getJSONObject("location");

                double latitude = rawLocation.getDouble("latitude");
                double longitude = rawLocation.getDouble("longitude");
                String city = rawLocation.getString("city");
                String country = rawLocation.getString("country");

                location = new BikeNetworkLocation(latitude, longitude, city, country);

            }
            bikeNetworks.add(new BikeNetworkInfo(id, name, company, location));
        }
    } catch (JSONException e) {
        throw new ParseException("Error parsing JSON", 0);
    }
}

From source file:Main.java

/**
 * This will parse an XML stream and create a DOM document.
 * /*  w  ww  .j  a  v  a  2  s .  c om*/
 * @param fileName
 *            The file to get the XML from.
 * @return The DOM document.
 * @throws ParserConfigurationException
 * @throws IOException
 *             It there is an error creating the dom.
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 * @throws SAXException
 * @throws ParseException
 */
public static Document parse(String fileName) throws IOException, ParseException {
    final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (final ParserConfigurationException e) {
        final ParseException thrown = new ParseException(e.getMessage(), 0);
        throw thrown;
    }
    try {
        return builder.parse(fileName);
    } catch (final IOException e) {
        final IOException thrown = new IOException(e.getMessage());
        throw thrown;

    } catch (final SAXException e) {
        final ParseException thrown = new ParseException(e.getMessage(), 0);
        throw thrown;
    }
}

From source file:org.jboss.dashboard.ui.resources.ResourceName.java

public static ResourceName getInstance(String resName) {
    ResourceName resource = new ResourceName();
    try {/*w  ww  .  j  a v a 2s  .  co m*/
        //Workspace
        ParsePosition pPos = new ParsePosition(0);
        String resourceName = useBase64Names ? new String(Base64.decode(resName)) : resName;
        Object[] o = msgf.parse(resourceName, pPos);
        if (o == null)
            throw new ParseException(
                    "Cannot parse " + resourceName + ". Error at position " + pPos.getErrorIndex(),
                    pPos.getErrorIndex());
        //log.debug("Parsing result: " + Arrays.asList(o));

        //log.debug("Workspace name determined from resource name is " + o[0]);
        resource.workspaceId = (String) o[0];
        resource.workspaceId = "".equals(resource.workspaceId) ? null : resource.workspaceId;

        //Section
        //log.debug("Section determined from resource name is " + o[1]);
        String sectionId = (String) o[1];
        if (!"".equals(sectionId))
            resource.sectionId = new Long(sectionId);

        //Panel
        //log.debug("Panel determined from resource name is " + o[2]);
        String panelId = (String) o[2];
        if (!"".equals(panelId))
            resource.panelId = new Long(panelId);

        //Category
        //log.debug("Category determined from resource name is " + o[3]);
        resource.category = (String) o[3];
        if ("".equals(resource.category))
            throw new ParseException("Cannot find non-empty category name", 3);

        //CategoryId
        //log.debug("CategoryId determined from resource name is " + o[4]);
        resource.categoryId = (String) o[4];
        resource.categoryId = "".equals(resource.categoryId) ? null : resource.categoryId;

        //ResourceId
        //log.debug("Resource determined from resource name is " + o[5]);
        resource.resourceId = (String) o[5];
        if ("".equals(resource.resourceId))
            resource.resourceId = null;

        StringBuffer sb = new StringBuffer();
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.workspaceId));
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.sectionId));
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.panelId));
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.category));
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.categoryId));
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.resourceId));
        resource.resName = useBase64Names ? Base64.encode(sb.toString().getBytes()) : sb.toString();

        /*if (resource.categoryId != null) {
        sb=new StringBuffer();
        sb.append(SEPARATOR);
        sb.append(SEPARATOR);
        sb.append(SEPARATOR);
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.category));
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.categoryId));
        sb.append(SEPARATOR);
        sb.append(RenderUtils.noNull(resource.resourceId));
                
        resource.portableResourceName = useBase64Names ? Base64.encode(sb.toString().getBytes()) : sb.toString();
        }
        else{
        resource.portableResourceName = resource.resName;
        log.debug("Resource "+resource.resName+" is not portable.");
        } */
        resource.portableResourceName = resource.resName;

        resource.resourceClass = Class.forName("org.jboss.dashboard.ui.resources."
                + resource.category.substring(0, 1).toUpperCase() + resource.category.substring(1));

    } catch (Exception e) {
        log.debug("Error processing resource name. ", e);
        resource = null;
    }
    return resource;
}

From source file:org.apache.syncope.common.lib.types.AuditLoggerName.java

public static AuditLoggerName fromLoggerName(final String loggerName) throws ParseException {

    if (StringUtils.isBlank(loggerName)) {
        throw new IllegalArgumentException("Null value not permitted");
    }// w w w .j  ava2 s  . c  o  m

    if (!loggerName.startsWith(LoggerType.AUDIT.getPrefix())) {
        throw new ParseException("Audit logger name must start with " + LoggerType.AUDIT.getPrefix(), 0);
    }

    final Map.Entry<EventCategoryTO, Result> eventCategory = parseEventCategory(
            loggerName.replaceAll(LoggerType.AUDIT.getPrefix() + ".", ""));

    return new AuditLoggerName(eventCategory.getKey().getType(), eventCategory.getKey().getCategory(),
            eventCategory.getKey().getSubcategory(),
            eventCategory.getKey().getEvents().isEmpty() ? StringUtils.EMPTY
                    : eventCategory.getKey().getEvents().iterator().next(),
            eventCategory.getValue());
}

From source file:com.ok2c.lightmtp.util.InetAddressRangeParser.java

public InetAddressRange parse(final CharArrayBuffer buffer, final ParserCursor cursor, final char[] delimiters)
        throws ParseException, UnknownHostException {

    Args.notNull(buffer, "Char array buffer");
    Args.notNull(cursor, "Parser cursor");

    int pos = cursor.getPos();
    int indexFrom = cursor.getPos();
    int indexTo = cursor.getUpperBound();

    while (pos < indexTo) {
        char ch = buffer.charAt(pos);
        if (ch == '/') {
            break;
        }// w  w w. ja  v a2  s . co m
        if (isOneOf(ch, delimiters)) {
            break;
        }
        pos++;
    }

    InetAddress address = InetAddress.getByName(buffer.substringTrimmed(indexFrom, pos));
    int mask = 0;

    if (pos < indexTo && buffer.charAt(pos) == '/') {
        pos++;
        indexFrom = pos;
        while (pos < indexTo) {
            char ch = buffer.charAt(pos);
            if (isOneOf(ch, delimiters)) {
                break;
            }
            pos++;
        }
        try {
            mask = Integer.parseInt(buffer.substringTrimmed(indexFrom, pos));
            if (mask < 0) {
                throw new ParseException("Negative range mask", indexFrom);
            }
        } catch (NumberFormatException ex) {
            throw new ParseException("Invalid range mask", indexFrom);
        }
    }
    cursor.updatePos(pos);
    return new InetAddressRange(address, mask);
}

From source file:com.arcao.geocaching.api.data.coordinates.CoordinatesParser.java

public static Coordinates parse(String coordinates) throws ParseException {
    final ParseResult latitudeWrapper = parse(coordinates, CoordinateType.LAT);
    final double lat = latitudeWrapper.result;
    // cut away the latitude part when parsing the longitude
    final ParseResult longitudeWrapper = parse(
            coordinates.substring(latitudeWrapper.matcherPos + latitudeWrapper.matcherLen), CoordinateType.LON);

    if (longitudeWrapper.matcherPos - (latitudeWrapper.matcherPos + latitudeWrapper.matcherLen) >= 10) {
        throw new ParseException("Distance between latitude and longitude text is to large.",
                latitudeWrapper.matcherPos + latitudeWrapper.matcherLen + longitudeWrapper.matcherPos);
    }//from   ww w.  jav  a  2 s  .c  om

    final double lon = longitudeWrapper.result;
    return new Coordinates(lat, lon);
}

From source file:com.liquid.wallpapers.free.dao.wallpapers.parsing.JsonWallpaperParser.java

@Override
public List<Wallpaper> parse(String data) throws ParseException {
    try {/*from w ww.jav  a2  s  . c  o  m*/
        JSONArray array = new JSONArray(data);
        List<Wallpaper> wallpapers = new ArrayList<Wallpaper>();

        for (int i = 0; i < array.length(); i++) {
            JSONObject jsonWallpaper = array.getJSONObject(i);

            wallpapers.add(new Wallpaper(jsonWallpaper.getString(Messages.getString("JsonWallpaperParser.0")), //$NON-NLS-1$
                    jsonWallpaper.getString(Messages.getString("JsonWallpaperParser.1")), URI //$NON-NLS-1$
                            .create(jsonWallpaper.getString(Messages.getString("JsonWallpaperParser.2"))), //$NON-NLS-1$
                    URI.create(jsonWallpaper.getString(Messages.getString("JsonWallpaperParser.3"))), URI //$NON-NLS-1$
                            .create(jsonWallpaper.getString(Messages.getString("JsonWallpaperParser.4"))), //$NON-NLS-1$
                    jsonWallpaper.getString(Messages.getString("JsonWallpaperParser.5")))); //$NON-NLS-1$
        }

        return wallpapers;
    } catch (JSONException ex) {
        throw new ParseException(ex.getMessage(), 0);
    }
}

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

public void importData(InputStream is) throws IOException, ParseException {
    if (is == null)
        throw new IllegalArgumentException("import input stream cannot be null");

    logger.debug("araqne confdb: start import data");
    db.lock();/*from  w ww. jav a2  s  . c o m*/

    try {
        JSONTokener t = new JSONTokener(new InputStreamReader(is, Charset.forName("utf-8")));

        Map<String, Object> metadata = parseMetadata(t);
        Integer version = (Integer) metadata.get("version");
        if (version != 1)
            throw new ParseException("unsupported confdb data format version: " + version, -1);

        Manifest manifest = db.getManifest(null);
        List<ConfigChange> configChanges = new ArrayList<ConfigChange>();

        char comma = t.nextClean();
        if (comma == ',')
            parseCollections(t, manifest, configChanges);

        writeManifestLog(manifest);
        writeChangeLog(configChanges, manifest.getId());
        logger.debug("araqne confdb: import complete");
    } catch (JSONException e) {
        throw new ParseException(e.getMessage(), 0);
    } finally {
        db.unlock();
    }
}

From source file:org.cook_e.data.StorageParser.java

/**
 * Parses a serialized list of steps/*from   w  w w. ja v  a 2s. c o  m*/
 * @param stepsString a string representing a list of steps, in the format returned by
 *                    {@link #serializeRecipeSteps(List)}
 * @return the steps in the provided String
 * @throws java.text.ParseException if the steps could not be parsed
 */
public List<Step> parseRecipeSteps(String stepsString) throws ParseException {
    try {
        final JSONArray json = new JSONArray(stepsString);
        final List<Step> steps = new ArrayList<>(json.length());
        for (int i = 0; i < json.length(); i++) {
            final JSONObject stepJson = json.getJSONObject(i);

            final String description = stepJson.getString("description");
            final Duration duration = Duration.millis(stepJson.getLong("duration_ms"));
            final boolean simultaneous = stepJson.getBoolean("simultaneous");

            final JSONArray ingredientsJson = stepJson.getJSONArray("ingredients");
            final List<String> ingredients = new ArrayList<>(ingredientsJson.length());
            for (int j = 0; j < ingredientsJson.length(); j++) {
                ingredients.add(ingredientsJson.getString(j));
            }
            steps.add(new Step(ingredients, description, duration, simultaneous, i));
        }

        return steps;
    } catch (JSONException e) {
        final ParseException parseException = new ParseException("Invalid JSON", 0);
        parseException.initCause(e);
        throw parseException;
    }
}