Example usage for org.xml.sax.helpers DefaultHandler DefaultHandler

List of usage examples for org.xml.sax.helpers DefaultHandler DefaultHandler

Introduction

In this page you can find the example usage for org.xml.sax.helpers DefaultHandler DefaultHandler.

Prototype

DefaultHandler

Source Link

Usage

From source file:com.android.tools.idea.templates.RepositoryUrlManager.java

/**
 * Parses a Maven metadata file and returns a string of the highest found version
 *
 * @param metadataFile    the files to parse
 * @param includePreviews if false, preview versions of the library will not be returned
 * @return the string representing the highest version found in the file or "0.0.0" if no versions exist in the file
 *//*ww w.  j a v  a 2s .  co  m*/
@Nullable
private static String getLatestVersionFromMavenMetadata(@NotNull File metadataFile,
        @Nullable String filterPrefix, boolean includePreviews, @NotNull FileOp fileOp) throws IOException {
    String xml = fileOp.toString(metadataFile, StandardCharsets.UTF_8);

    List<GradleCoordinate> versions = Lists.newLinkedList();
    try {
        SAXParserFactory.newInstance().newSAXParser().parse(IOUtils.toInputStream(xml), new DefaultHandler() {
            boolean inVersionTag = false;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                if (qName.equals(TAG_VERSION)) {
                    inVersionTag = true;
                }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                // Get the version and compare it to the current known max version
                if (inVersionTag) {
                    inVersionTag = false;
                    String revision = new String(ch, start, length);
                    //noinspection StatementWithEmptyBody
                    if (!includePreviews && "5.2.08".equals(revision)
                            && metadataFile.getPath().contains(PLAY_SERVICES.getArtifactId())) {
                        // This version (despite not having -rcN in its version name is actually a preview
                        // (See https://code.google.com/p/android/issues/detail?id=75292)
                        // Ignore it
                    } else if (filterPrefix == null || revision.startsWith(filterPrefix)) {
                        versions.add(GradleCoordinate.parseVersionOnly(revision));
                    }
                }
            }
        });
    } catch (Exception e) {
        LOG.warn(e);
    }

    if (versions.isEmpty()) {
        return REVISION_ANY;
    } else if (includePreviews) {
        return GRADLE_COORDINATE_ORDERING.max(versions).getRevision();
    } else {
        return versions.stream().filter(v -> !v.isPreview()).max(GRADLE_COORDINATE_ORDERING)
                .map(GradleCoordinate::getRevision).orElse(null);
    }
}

From source file:info.magnolia.about.app.AboutPresenter.java

String[] getConnectionString() {
    File config = null;/*from   w  w  w  . j av a  2  s  .  co m*/
    // Assuming, the path to the repository-config.-file is configured relative, starting with WEB-INF.
    // Otherwise, assuming it's an absolute path for this config. (See JIRA MGNLUI-3163)
    String configuredPath = magnoliaProperties.getProperty("magnolia.repositories.jackrabbit.config");
    if (configuredPath != null) {
        if (configuredPath.startsWith("WEB-INF")) {
            config = new File(magnoliaProperties.getProperty("magnolia.app.rootdir") + "/" + configuredPath);
        } else {
            config = new File(configuredPath);
        }
    }
    // No special handling here if the config (file) is null or not existing.
    // If the path is wrong or not set, Magnolia won't start up properly and it won't be possible to launch the About-app.

    final String[] connectionString = new String[3];
    try {
        SAXParserFactory.newInstance().newSAXParser().parse(config, new DefaultHandler() {
            private boolean inPM;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                super.startElement(uri, localName, qName, attributes);
                if ("PersistenceManager".equals(qName) || "DataSource".equals(qName)) {
                    inPM = true;
                }
                if (inPM && "param".equals(qName)) {
                    if ("url".equals(attributes.getValue("name"))) {
                        connectionString[0] = attributes.getValue("value");
                    }
                    if ("user".equals(attributes.getValue("name"))) {
                        connectionString[1] = attributes.getValue("value");
                    }
                    if ("password".equals(attributes.getValue("name"))) {
                        connectionString[2] = attributes.getValue("value");
                    }
                }
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                super.endElement(uri, localName, qName);
                if ("PersistenceManager".equals(localName) || "DataSource".equals(qName)) {
                    inPM = false;
                }
            }
        });
        return connectionString;
    } catch (Exception e) {
        log.debug("Failed to obtain DB connection info with {}", e.getMessage(), e);
    }
    return null;
}

From source file:com.nidhinova.tika.server.TikaService.java

/**
 * Serves HTTP PUT Returns metadata formatted as json or plain text content
 * of the file/*  w ww  .  j  a v  a 2 s. co  m*/
 * 
 * @param filename
 * @param pathkey
 *            (JNDI lookup key)
 * @param opkey
 *            (can be "text" or "metadata")
 * @param httpHeaders
 * @return
 * @throws Exception
 */

@PUT
@Consumes("*/*")
@Produces({ MediaType.APPLICATION_JSON })
@Path("/{opkey}")
public StreamingOutput getMetadata(final InputStream is, @PathParam("opkey") final String opkey,
        @Context HttpHeaders httpHeaders) throws Exception {
    final Detector detector = createDetector(httpHeaders);
    final AutoDetectParser parser = new AutoDetectParser(detector);
    final ParseContext context = new ParseContext();
    context.set(Parser.class, parser);
    final org.apache.tika.metadata.Metadata metadata = new org.apache.tika.metadata.Metadata();
    setMetadataFromHeader(parser, metadata, httpHeaders);

    return new StreamingOutput() {
        public void write(OutputStream outputStream) throws IOException, WebApplicationException {

            StringWriter textBuffer = new StringWriter();

            ContentHandler handler = null;
            if (opkey.equalsIgnoreCase("metadata")) {
                handler = new DefaultHandler();
            } else if (opkey.equalsIgnoreCase("text") || opkey.equalsIgnoreCase("fulldata")) {
                handler = new BodyContentHandler(textBuffer);
            }
            try {
                parser.parse(new BufferedInputStream(is), handler, metadata, context);
                String contentEncoding = (metadata
                        .get(org.apache.tika.metadata.HttpHeaders.CONTENT_TYPE) == null ? "UTF-8"
                                : metadata.get(org.apache.tika.metadata.HttpHeaders.CONTENT_TYPE));
                Writer outWriter = getOutputWriter(outputStream, contentEncoding);

                //metadata is always gathered
                // munch tika metadata object it to make json
                String jsonMetadata = JSONHelper.metadataToJson(metadata);

                if (opkey.equalsIgnoreCase("metadata")) {
                    outWriter.write("{\"metadata\":" + jsonMetadata + "}");
                } else if (opkey.equalsIgnoreCase("text")) {
                    // write it out
                    outWriter.write("{ \"text\":" + JSONHelper.toJSON(textBuffer.toString()) + " }");
                } else if (opkey.equalsIgnoreCase("fulldata")) {
                    StringBuilder data = new StringBuilder();
                    data.append("{ \"metadata\":" + jsonMetadata).append(", ")
                            .append("\"text\":" + JSONHelper.toJSON(textBuffer.toString()) + " }");
                    outWriter.write(data.toString());
                }
                outWriter.flush();
            } catch (SAXException e) {
                throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
            } catch (TikaException e) {
                if (e.getCause() != null && e.getCause() instanceof WebApplicationException) {
                    throw (WebApplicationException) e.getCause();
                }

                if (e.getCause() != null && e.getCause() instanceof IllegalStateException) {
                    throw new WebApplicationException(Response.status(422).build());
                }

                if (e.getCause() != null && e.getCause() instanceof EncryptedDocumentException) {
                    throw new WebApplicationException(Response.status(422).build());
                }

                if (e.getCause() != null && e.getCause() instanceof OldWordFileFormatException) {
                    throw new WebApplicationException(Response.status(422).build());
                }

                logger.warn("Text extraction failed", e);

                throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
            }
        }
    };

}

From source file:info.magnolia.about.app.AboutPresenter.java

String getRepoName() {
    String repoConfigPath = magnoliaProperties.getProperty("magnolia.repositories.config");
    File config = new File(magnoliaProperties.getProperty("magnolia.app.rootdir") + "/" + repoConfigPath);
    final String[] repoName = new String[1];
    try {//from   w  w  w.java 2  s . com
        SAXParserFactory.newInstance().newSAXParser().parse(config, new DefaultHandler() {
            private boolean inRepo;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                super.startElement(uri, localName, qName, attributes);
                if ("RepositoryMapping".equals(qName)) {
                    inRepo = true;
                }
                if (inRepo && "Map".equals(qName)) {
                    if ("config".equals(attributes.getValue("name"))) {
                        repoName[0] = attributes.getValue("repositoryName");
                    }
                }
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                super.endElement(uri, localName, qName);
                if ("RepositoryMapping".equals(localName)) {
                    inRepo = false;
                }
            }
        });
        return repoName[0];
    } catch (Exception e) {
        log.debug("Failed to obtain repository configuration info with {}", e.getMessage(), e);
    }
    return null;
}

From source file:com.farmafene.commons.cas.ValidateTGT.java

/**
 * Retrieve the text for a specific element (when we know there is only
 * one)./*from   w  w  w. ja v a2  s .  c  om*/
 * 
 * @param xmlAsString
 *            the xml response
 * @param element
 *            the element to look for
 * @return the text value of the element.
 */
private String getTextForElement(final String xmlAsString, final String element) {
    final XMLReader reader = getXmlReader();
    final StringBuffer buffer = new StringBuffer();

    final DefaultHandler handler = new DefaultHandler() {

        private boolean foundElement = false;

        public void startElement(final String uri, final String localName, final String qName,
                final Attributes attributes) throws SAXException {
            if (localName.equals(element)) {
                this.foundElement = true;
            }
        }

        public void endElement(final String uri, final String localName, final String qName)
                throws SAXException {
            if (localName.equals(element)) {
                this.foundElement = false;
            }
        }

        public void characters(char[] ch, int start, int length) throws SAXException {
            if (this.foundElement) {
                buffer.append(ch, start, length);
            }
        }
    };

    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);

    try {
        reader.parse(new InputSource(new StringReader(xmlAsString)));
    } catch (final Exception e) {
        logger.error("", e);
        return null;
    }

    return buffer.toString();
}

From source file:hudson.XmlFile.java

/**
 * Parses the beginning of the file and determines the encoding.
 *
 * @throws IOException//from   w w  w .j  av a2s  .  c  o  m
 *      if failed to detect encoding.
 * @return
 *      always non-null.
 */
public String sniffEncoding() throws IOException {
    class Eureka extends SAXException {
        final String encoding;

        public Eureka(String encoding) {
            this.encoding = encoding;
        }
    }

    try (InputStream in = Files.newInputStream(file.toPath())) {
        InputSource input = new InputSource(file.toURI().toASCIIString());
        input.setByteStream(in);
        JAXP.newSAXParser().parse(input, new DefaultHandler() {
            private Locator loc;

            @Override
            public void setDocumentLocator(Locator locator) {
                this.loc = locator;
            }

            @Override
            public void startDocument() throws SAXException {
                attempt();
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                attempt();
                // if we still haven't found it at the first start element, then we are not going to find it.
                throw new Eureka(null);
            }

            private void attempt() throws Eureka {
                if (loc == null)
                    return;
                if (loc instanceof Locator2) {
                    Locator2 loc2 = (Locator2) loc;
                    String e = loc2.getEncoding();
                    if (e != null)
                        throw new Eureka(e);
                }
            }
        });
        // can't reach here
        throw new AssertionError();
    } catch (Eureka e) {
        if (e.encoding != null)
            return e.encoding;
        // the environment can contain old version of Xerces and others that do not support Locator2
        // in such a case, assume UTF-8 rather than fail, since Jenkins internally always write XML in UTF-8
        return "UTF-8";
    } catch (SAXException e) {
        throw new IOException("Failed to detect encoding of " + file, e);
    } catch (InvalidPathException e) {
        throw new IOException(e);
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e); // impossible
    }
}

From source file:self.philbrown.javaQuery.AjaxTask.java

@Override
protected TaskResponse doInBackground(Void... arg0) {
    //handle cached responses
    CachedResponse cachedResponse = URLresponses
            .get(String.format(Locale.US, "%s_?=%s", options.url(), options.dataType()));
    //handle ajax caching option
    if (cachedResponse != null) {
        if (options.cache()) {
            if (new Date().getTime() - cachedResponse.timestamp.getTime() < options.cacheTimeout()) {
                //return cached response
                Success s = new Success();
                s.obj = cachedResponse.response;
                s.reason = "cached response";
                s.headers = null;//  w ww  .  j ava  2s . co m
                return s;
            }
        }

    }

    if (request == null) {
        String type = options.type();
        if (type == null)
            type = "GET";
        if (type.equalsIgnoreCase("DELETE")) {
            request = new HttpDelete(options.url());
        } else if (type.equalsIgnoreCase("GET")) {
            request = new HttpGet(options.url());
        } else if (type.equalsIgnoreCase("HEAD")) {
            request = new HttpHead(options.url());
        } else if (type.equalsIgnoreCase("OPTIONS")) {
            request = new HttpOptions(options.url());
        } else if (type.equalsIgnoreCase("POST")) {
            request = new HttpPost(options.url());
        } else if (type.equalsIgnoreCase("PUT")) {
            request = new HttpPut(options.url());
        } else if (type.equalsIgnoreCase("TRACE")) {
            request = new HttpTrace(options.url());
        } else if (type.equalsIgnoreCase("CUSTOM")) {
            try {
                request = options.customRequest();
            } catch (Exception e) {
                request = null;
            }

            if (request == null) {
                Log.w("javaQuery.ajax",
                        "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                request = new HttpGet();
            }

        } else {
            //default to GET
            request = new HttpGet();
        }
    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", request);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class });
            if (options.processData() == null) {
                setEntity.invoke(request, new StringEntity(options.data().toString()));
            } else {
                Class<?> dataProcessor = Class.forName(options.processData());
                Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class });
                setEntity.invoke(request, constructor.newInstance(options.data()));
            }
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    HttpParams params = new BasicHttpParams();

    if (options.timeout() != 0) {
        HttpConnectionParams.setConnectionTimeout(params, options.timeout());
        HttpConnectionParams.setSoTimeout(params, options.timeout());
    }

    HttpClient client = new DefaultHttpClient(params);

    HttpResponse response = null;
    try {

        if (options.cookies() != null) {
            CookieStore cookies = new BasicCookieStore();
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue()));
            }
            HttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
            response = client.execute(request, httpContext);
        } else {
            response = client.execute(request);
        }

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke(new $(options.context()), response, options.dataType());
            else
                options.dataFilter().invoke(null, response, options.dataType());
        }

        StatusLine statusLine = response.getStatusLine();

        Function function = options.statusCode().get(statusLine);
        if (function != null) {
            if (options.context() != null)
                function.invoke(new $(options.context()));
            else
                function.invoke(null);
        }

        if (statusLine.getStatusCode() >= 300) {
            //an error occurred
            Error e = new Error();
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        } else {
            //handle dataType
            String dataType = options.dataType();
            if (dataType == null)
                dataType = "text";
            Object parsedResponse = null;
            boolean success = true;
            try {
                if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                    parsedResponse = parseText(response);
                } else if (dataType.equalsIgnoreCase("xml")) {
                    if (options.customXMLParser() != null) {
                        InputStream is = response.getEntity().getContent();
                        if (options.SAXContentHandler() != null)
                            options.customXMLParser().parse(is, options.SAXContentHandler());
                        else
                            options.customXMLParser().parse(is, new DefaultHandler());
                        parsedResponse = "Response handled by custom SAX parser";
                    } else if (options.SAXContentHandler() != null) {
                        InputStream is = response.getEntity().getContent();

                        SAXParserFactory factory = SAXParserFactory.newInstance();

                        factory.setFeature("http://xml.org/sax/features/namespaces", false);
                        factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                        SAXParser parser = factory.newSAXParser();

                        XMLReader reader = parser.getXMLReader();
                        reader.setContentHandler(options.SAXContentHandler());
                        reader.parse(new InputSource(is));
                        parsedResponse = "Response handled by custom SAX content handler";
                    } else {
                        parsedResponse = parseXML(response);
                    }
                } else if (dataType.equalsIgnoreCase("json")) {
                    parsedResponse = parseJSON(response);
                } else if (dataType.equalsIgnoreCase("script")) {
                    parsedResponse = parseScript(response);
                } else if (dataType.equalsIgnoreCase("image")) {
                    parsedResponse = parseImage(response);
                }
            } catch (ClientProtocolException cpe) {
                if (options.debug())
                    cpe.printStackTrace();
                success = false;
                Error e = new Error();
                AjaxError error = new AjaxError();
                error.request = request;
                error.options = options;
                e.status = statusLine.getStatusCode();
                e.reason = statusLine.getReasonPhrase();
                error.status = e.status;
                error.reason = e.reason;
                e.headers = response.getAllHeaders();
                e.error = error;
                return e;
            } catch (Exception ioe) {
                if (options.debug())
                    ioe.printStackTrace();
                success = false;
                Error e = new Error();
                AjaxError error = new AjaxError();
                error.request = request;
                error.options = options;
                e.status = statusLine.getStatusCode();
                e.reason = statusLine.getReasonPhrase();
                error.status = e.status;
                error.reason = e.reason;
                e.headers = response.getAllHeaders();
                e.error = error;
                return e;
            }
            if (success) {
                //Handle cases where successful requests still return errors (these include
                //configurations in AjaxOptions and HTTP Headers
                String key = String.format(Locale.US, "%s_?=%s", options.url(), options.dataType());
                CachedResponse cache = URLresponses.get(key);
                Date now = new Date();
                //handle ajax caching option
                if (cache != null) {
                    if (options.cache()) {
                        if (now.getTime() - cache.timestamp.getTime() < options.cacheTimeout()) {
                            parsedResponse = cache;
                        } else {
                            cache.response = parsedResponse;
                            cache.timestamp = now;
                            synchronized (URLresponses) {
                                URLresponses.put(key, cache);
                            }
                        }
                    }

                }
                //handle ajax ifModified option
                Header[] lastModifiedHeaders = response.getHeaders("last-modified");
                if (lastModifiedHeaders.length >= 1) {
                    try {
                        Header h = lastModifiedHeaders[0];
                        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                        Date lastModified = format.parse(h.getValue());
                        if (options.ifModified() && lastModified != null) {
                            if (cache.lastModified != null && cache.lastModified.compareTo(lastModified) == 0) {
                                //request response has not been modified. 
                                //Causes an error instead of a success.
                                Error e = new Error();
                                AjaxError error = new AjaxError();
                                error.request = request;
                                error.options = options;
                                e.status = statusLine.getStatusCode();
                                e.reason = statusLine.getReasonPhrase();
                                error.status = e.status;
                                error.reason = e.reason;
                                e.headers = response.getAllHeaders();
                                e.error = error;
                                Function func = options.statusCode().get(304);
                                if (func != null) {
                                    if (options.context() != null)
                                        func.invoke(new $(options.context()));
                                    else
                                        func.invoke(null);
                                }
                                return e;
                            } else {
                                cache.lastModified = lastModified;
                                synchronized (URLresponses) {
                                    URLresponses.put(key, cache);
                                }
                            }
                        }
                    } catch (Throwable t) {
                        Log.e("Ajax", "Could not parse Last-Modified Header");
                    }

                }

                //Now handle a successful request

                Success s = new Success();
                s.obj = parsedResponse;
                s.reason = statusLine.getReasonPhrase();
                s.headers = response.getAllHeaders();
                return s;
            }
            //success
            Success s = new Success();
            s.obj = parsedResponse;
            s.reason = statusLine.getReasonPhrase();
            s.headers = response.getAllHeaders();
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error();
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (response != null)
                e.headers = response.getAllHeaders();
            else
                e.headers = new Header[0];
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:com.mercatis.lighthouse3.commons.commons.XmlMuncher.java

/**
 * The constructor, which sets up the XML muncher against an XML document
 *
 * @param xml the XML document to munch.
 * @throws DOMException an exception is thrown in case of an error during XML parsing
 *//*from   ww  w  .  j  a  va2s .c  om*/
public XmlMuncher(String xml) throws DOMException {
    SAXParser saxParser = null;
    try {
        saxParser = (SAXParser) pool.borrowObject();
        saxParser.parse(new InputSource(new StringReader(xml)), new DefaultHandler() {

            private LinkedList<String> currentPathStack = new LinkedList<String>();
            private StringBuilder currentValue;

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (this.currentValue != null)
                    this.currentValue.append(ch, start, length);
            }

            @Override
            public void startElement(String uri, String localName, String name, Attributes attributes)
                    throws SAXException {

                this.currentValue = new StringBuilder();
                String newPath = null;

                if (this.currentPathStack.isEmpty()) {
                    newPath = "/" + localName;
                    rootElementName = localName;
                    documentPaths.add(new LinkedHashMap<String, String>());
                } else {
                    newPath = this.currentPathStack.getFirst() + "/" + localName;
                }

                this.currentPathStack.add(0, newPath);

                addDocumentPath(documentPaths, newPath, null);

            }

            @Override
            public void endElement(String uri, String localName, String name) throws SAXException {
                String currentPath = this.currentPathStack.removeFirst();

                if (currentValue != null && !"".equals(this.currentValue.toString()))
                    addDocumentPath(documentPaths, currentPath, this.currentValue.toString());

                this.currentValue = null;
            }
        });

    } catch (ParserConfigurationException e) {
        throw new DOMException((short) 0,
                "SAX-Parser configuration exception caught while munching XML document: " + e.getMessage());
    } catch (SAXException e) {
        throw new DOMException((short) 0,
                "SAX parsing exception caught while munching XML document: " + e.getMessage());
    } catch (IOException e) {
        throw new DOMException((short) 0, "IO exception caught while munching XML document: " + e.getMessage());
    } catch (Exception e) {
        throw new DOMException((short) 0, "exception caught while munching XML document: " + e.getMessage());
    } finally {
        try {
            pool.returnObject(saxParser);
        } catch (Exception e) {
            throw new DOMException((short) 0,
                    "exception caught while munching XML document: " + e.getMessage());
        }
    }
}

From source file:de.laeubisoft.tools.ant.validation.W3CMarkupValidationTask.java

/**
 * Takes an {@link URL} and tries to find out all linked resources
 * /*from   ww w . j  a va2s  . c om*/
 * @param uriToRecurse
 * @return a set of discovered urls
 */
private Set<URL> recurseInto(final URL uriToRecurse) throws BuildException {
    final Set<URL> urlsFound = new HashSet<URL>();
    XMLReader reader = new Parser();
    reader.setContentHandler(new DefaultHandler() {
        @Override
        public void startElement(String nsuri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if ("a".equalsIgnoreCase(qName)) {
                String value = attributes.getValue("href");
                if (value != null) {
                    try {
                        URL url = new URL(uriToRecurse, value);
                        if (url.getHost().equalsIgnoreCase(uriToRecurse.getHost())
                                && url.getPort() == uriToRecurse.getPort()) {
                            urlsFound.add(url);
                        }
                    } catch (MalformedURLException e) {
                        log("can't parse URL for href = " + value + ", it will be ignored!", Project.MSG_ERR);
                    }
                }
            }
        }
    });
    // Parsen wird gestartet
    try {
        reader.parse(new InputSource(uriToRecurse.openStream()));
        return urlsFound;
    } catch (IOException e) {
        throw new BuildException("error while accessing data at " + uriToRecurse, e);
    } catch (SAXException e) {
        throw new BuildException("error while parsing data at " + uriToRecurse, e);
    }
}

From source file:com.abstratt.mdd.core.util.MDDUtil.java

public static boolean isGenerated(java.net.URI uri) {
    if (cachedParserFactory == null) {
        cachedParserFactory = SAXParserFactory.newInstance();
    }//from  w  ww.j  a  v  a  2 s .c  o  m
    SAXParser xmlParser;
    try {
        xmlParser = cachedParserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error creating XML parser", e);
        return false;
    } catch (SAXException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error creating XML parser", e);
        return false;
    }
    final boolean[] generated = { false };
    final boolean[] aborted = { false };
    InputStream stream = null;
    try {
        stream = new BufferedInputStream(uri.toURL().openStream());
        xmlParser.parse(stream, new DefaultHandler() {
            private boolean skipping = true;

            @Override
            public void startElement(String uri, String localName, String name, Attributes attributes)
                    throws SAXException {
                if (name.equalsIgnoreCase("eAnnotations"))
                    if (GENERATED.equals(attributes.getValue("source"))) {
                        generated[0] = true;
                        aborted[0] = true;
                        throw new SAXParseException("", null);
                    } else
                        return;
                if (!skipping) {
                    // should have seen the annotation by now
                    aborted[0] = true;
                    throw new SAXParseException("", null);
                }
                if (name.startsWith("uml"))
                    skipping = false;
            }
        });
    } catch (SAXException e) {
        if (!aborted[0] && Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error parsing " + uri, e);
    } catch (IOException e) {
        if (Platform.inDebugMode())
            LogUtils.logError(MDDCore.PLUGIN_ID, "Error parsing " + uri, e);
    } finally {
        if (stream != null)
            try {
                stream.close();
            } catch (IOException e) {
                // no biggie
            }
    }
    return generated[0];
}