Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

From source file:com.cloudera.recordbreaker.analyzer.XMLSchemaDescriptor.java

void computeSchema() throws IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = null;
    // Unfortunately, validation is often not possible
    factory.setValidating(false);/*from   www. j  ava  2  s .c  om*/

    try {
        // The XMLProcessor builds up a tree of tags
        XMLProcessor xp = new XMLProcessor();
        parser = factory.newSAXParser();
        parser.parse(dd.getRawBytes(), xp);

        // Grab the root tag
        this.rootTag = xp.getRoot();

        // Once the tree is built, we:
        // a) Find the correct repetition node (and throws out 'bad' repeats)
        // b) Flatten hierarchies of subfields into a single layer, so it's suitable
        //    for relational-style handling
        // c) Build an overall schema object that can summarize every expected
        //    object, even if the objects' individual schemas differ somewhat
        this.rootTag.completeTree();
    } catch (SAXException saxe) {
        throw new IOException(saxe.toString());
    } catch (ParserConfigurationException pcee) {
        throw new IOException(pcee.toString());
    }
}

From source file:net.smart_json_database.JSONDatabase.java

private JSONDatabase(Context context, String configurationName) throws InitJSONDatabaseExcepiton {

    AssetManager assetManager = context.getAssets();
    InputStream stream = null;//  w ww . jav  a2 s. c o  m

    String configXML = null;
    try {
        configXML = configurationName + ".xml";
        stream = assetManager.open(configXML);

    } catch (IOException e) {
        throw new InitJSONDatabaseExcepiton("Could not load asset " + configXML);
    } finally {
        if (stream != null) {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLConfigHandler handler = new XMLConfigHandler();
            SAXParser saxparser;
            try {
                saxparser = factory.newSAXParser();
                saxparser.parse(stream, handler);
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("Parser-Error while reading the " + configXML, e);
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("SAX-Error while reading the " + configXML, e);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw new InitJSONDatabaseExcepiton("IO-Error while reading the " + configXML, e);
            }

            mDbName = handler.getDbName();

            if (Util.IsNullOrEmpty(mDbName))
                throw new InitJSONDatabaseExcepiton("db name is empty check the xml configuration");

            mDbVersion = handler.getDbVersion();

            if (mDbVersion < 1)
                throw new InitJSONDatabaseExcepiton(
                        "db version must be 1 or greater -  check the xml configuration");

            mUpgradeClassPath = handler.getUpgradeClass();

            if (!Util.IsNullOrEmpty(mUpgradeClassPath)) {
                try {
                    Class<?> x = Class.forName(mUpgradeClassPath);
                    dbUpgrade = (IUpgrade) x.newInstance();
                } catch (Exception e) {
                }
            }

            dbHelper = new DBHelper(context, mDbName, mDbVersion);
            listeners = new ArrayList<IDatabaseChangeListener>();
            tags = new HashMap<String, Integer>();
            invertedTags = new HashMap<Integer, String>();
            updateTagMap();

        } else {
            throw new InitJSONDatabaseExcepiton(configXML + " is empty");
        }
    }
}

From source file:com.agiletec.aps.system.common.entity.ApsEntityManager.java

/**
 * Create and populate the entity as specified by its type and XML definition.
 * @param entityTypeCode The Entity Type code.
 * @param xml The XML of the associated entity.
 * @return The populated entity.//from w  ww .j  a  va 2 s. co  m
 * @throws ApsSystemException If errors detected while retrieving the entity.
 */
protected IApsEntity createEntityFromXml(String entityTypeCode, String xml) throws ApsSystemException {
    try {
        IApsEntity entityPrototype = this.getEntityPrototype(entityTypeCode);
        SAXParserFactory parseFactory = SAXParserFactory.newInstance();
        SAXParser parser = parseFactory.newSAXParser();
        InputSource is = new InputSource(new StringReader(xml));
        EntityHandler handler = this.getEntityHandler();
        handler.initHandler(entityPrototype, this.getXmlAttributeRootElementName(), this.getCategoryManager());
        parser.parse(is, handler);
        return entityPrototype;
    } catch (Throwable t) {
        _logger.error("Error detected while creating the entity. typecode: {} - xml: {}", entityTypeCode, xml,
                t);
        //ApsSystemUtils.logThrowable(t, this, "createEntityFromXml");
        throw new ApsSystemException("Error detected while creating the entity", t);
    }
}

From source file:de.betterform.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 *///from www  . j  av a 2 s .  co m
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation",
                    schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

From source file:com.microsoft.tfs.client.common.ui.dialogs.connect.ACSCredentialsDialogD11.java

private ACSConfigurationResult configureAuthenticationFromAuthProvider(final String target,
        final NameValuePair[] formInput) throws Exception {
    final URI targetURI;

    try {/*from  www . jav a 2s.c om*/
        targetURI = new URI(target);
    } catch (final Exception e) {
        log.warn(MessageFormat.format("ACS form action is not parseable: {0}", target), e); //$NON-NLS-1$
        throw new Exception("ACS form action is not parseable"); //$NON-NLS-1$
    }

    /* Make sure we're posting back to ACS */
    if (!ACS_SCHEME.equalsIgnoreCase(targetURI.getScheme()) || targetURI.getHost() == null
            || !targetURI.getHost().toLowerCase().endsWith(ACS_DOMAIN)
            || !ACS_PATH.equalsIgnoreCase(targetURI.getPath())
            || !ACS_QUERY.equalsIgnoreCase(targetURI.getQuery())) {
        throw new Exception(MessageFormat.format("ACS form location is not in the domain: {0}", ACS_DOMAIN)); //$NON-NLS-1$
    }

    /*
     * Build a connection to the server to submit the form.
     */
    final HttpClient httpClient = getHttpClient();
    final PostMethod postMethod = new PostMethod(target);

    /*
     * Ignore cookies, do not follow redirects, do not do authentication. We
     * expect the resultant page (and only the resultant page) to populate
     * our cookies.
     */
    postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    postMethod.setFollowRedirects(false);
    postMethod.setDoAuthentication(false);
    postMethod.getParams().setContentCharset("UTF-8"); //$NON-NLS-1$

    /* Add the ACS form elements */
    for (int i = 0; i < formInput.length; i++) {
        postMethod.addParameter(formInput[i]);
    }

    final int status = httpClient.executeMethod(postMethod);

    if (status != HttpStatus.SC_OK) {
        final String message = MessageFormat.format("ACS authentication did not return success: {0}", //$NON-NLS-1$
                Integer.toString(status));
        throw new Exception(message);
    }

    final SAXParser acsResultParser = SAXUtils.newSAXParser();
    final ACSResultHandler acsResultHandler = new ACSResultHandler();
    acsResultParser.parse(postMethod.getResponseBodyAsStream(), acsResultHandler);

    final String finalTarget = acsResultHandler.getFormAction();
    final NameValuePair[] finalParameters = acsResultHandler.getFormInputs();

    return configureAuthenticationFromACS(finalTarget, finalParameters);
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * @param xmlData/*from  ww w. ja va 2 s  .c om*/
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
private static String getNameSpaceFromXml(final String xmlData)
        throws ParserConfigurationException, SAXException, IOException, UnsupportedEncodingException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    DefaultHandler handler = new DefaultHandler() {
        private String nameSpace = null;
        private boolean first = true;

        public void startElement(String uri, String localName, String qName, Attributes attributes) {
            if (first) {
                if (qName.contains(":")) {
                    String prefix = qName.substring(0, qName.indexOf(":"));
                    String attributeName = "xmlns:" + prefix;
                    nameSpace = attributes.getValue(attributeName);
                } else {
                    nameSpace = attributes.getValue("xmlns");
                }
                first = false;
            }

        }

        public String toString() {
            return nameSpace;
        }
    };
    parser.parse(new ByteArrayInputStream(xmlData.getBytes("UTF-8")), handler);
    String nameSpace = handler.toString();
    return nameSpace;
}

From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java

private StoringInputStream toStream(URI ovfUri) throws IOException {
    SAXParser saxParser = newSaxParser();
    DefaultHandler handler = new DefaultHandler();

    InputStream is;//from w ww  .ja  v a2  s.co  m
    HttpResponse response = null;
    HttpGet request = null;

    if (ovfUri.getScheme().equals("file")) {
        is = new FileInputStream(new File(ovfUri));
    } else {
        request = new HttpGet(ovfUri);
        response = this.client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new IOException(
                    "Ovf descriptor not found at " + ovfUri + ". Error code " + response.getStatusLine());
        }

        is = response.getEntity().getContent();
    }

    StoringInputStream storingInputStream = new StoringInputStream(is);

    try {
        saxParser.parse(storingInputStream, handler);
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    } catch (SAXException e) {
        // not a valid ovf - abort
        if (request != null) {
            request.abort();
        }
        EntityUtils.consumeQuietly(response.getEntity());

        throw new IOException("Ovf not a valid xml: " + e.getMessage(), e);
    } finally {
        //close stream, could be file
        IOUtils.closeQuietly(is);
    }

    return storingInputStream;
}

From source file:com.silverwrist.venice.core.impl.ConferencingImporter.java

final List importMessages(InputStream xmlstm) throws DataException {
    try { // create a SAX parser and let it loose on the input data with our listener
        SAXParserFactory fact = SAXParserFactory.newInstance();
        fact.setNamespaceAware(false);//w w w. j av  a2s  . c  o  m
        fact.setValidating(false);
        SAXParser parser = fact.newSAXParser();
        parser.parse(xmlstm, new Listener());

    } // end try
    catch (ParserConfigurationException e) { // configuration error
        throw new DataException("Error configuring XML parser for message import: " + e.getMessage(), e);

    } // end catch
    catch (SAXException e) { // give an error message
        throw new DataException("Error importing messages: " + e.getMessage(), e);

    } // end catch
    catch (IOException e) { // I/O error in parsing!
        throw new DataException("Error importing messages: " + e.getMessage(), e);

    } // end catch

    if (m_events == null)
        return Collections.EMPTY_LIST;
    ArrayList rc = new ArrayList(m_events);
    m_events = null;
    return Collections.unmodifiableList(rc);

}

From source file:com.connectsdk.service.RokuService.java

@Override
public void getAppList(final AppListListener listener) {
    ResponseListener<Object> responseListener = new ResponseListener<Object>() {

        @Override// ww w  .  j  a v a2s. co m
        public void onSuccess(Object response) {
            String msg = (String) response;

            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            InputStream stream;
            try {
                stream = new ByteArrayInputStream(msg.getBytes("UTF-8"));
                SAXParser saxParser = saxParserFactory.newSAXParser();

                RokuApplicationListParser parser = new RokuApplicationListParser();
                saxParser.parse(stream, parser);

                List<AppInfo> appList = parser.getApplicationList();

                Util.postSuccess(listener, appList);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    };

    String action = "query";
    String param = "apps";

    String uri = requestURL(action, param);

    ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(this, uri,
            null, responseListener);
    request.setHttpMethod(ServiceCommand.TYPE_GET);
    request.send();
}

From source file:com.itude.mobile.mobbl.core.model.parser.MBXmlDocumentParser.java

private void doParseFragment(byte[] data, MBDocument document, String rootPath, boolean copyRootAttributes) {
    if (data != null) {
        try {/*from  w w w . j av a 2 s.  co m*/
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();

            _stack = new Stack<MBElementContainer>();
            _pathStack = new Stack<String>();
            _definition = document.getDefinition();
            _characters = new StringBuilder();
            _copyRootAttributes = copyRootAttributes;
            _ignoredPaths = new HashSet<String>();

            if (rootPath != null) {
                List<String> parts = MBPathUtil.splitPath(rootPath);
                for (String part : parts) {
                    _pathStack.add(NUMBERPATTERN.matcher(part).replaceAll(""));
                }

                _rootElementName = _pathStack.peek();
                _rootElement = (MBElementContainer) document.getValueForPath(rootPath);
            } else {
                _rootElement = document;
                _rootElementName = (_definition.getRootElement() != null) ? _definition.getRootElement()
                        : _definition.getName();
            }

            parser.parse(new ByteArrayInputStream(data), this);
        } catch (Exception e) {
            MBLog.d(MBConstants.APPLICATION_NAME, new String(data));
            MBLog.e(MBConstants.APPLICATION_NAME,
                    "MBXmlDocumentParser.doParseFragment (for the data, see debug log above)", e);
        }
    }
}