Example usage for org.xml.sax InputSource setCharacterStream

List of usage examples for org.xml.sax InputSource setCharacterStream

Introduction

In this page you can find the example usage for org.xml.sax InputSource setCharacterStream.

Prototype

public void setCharacterStream(Reader characterStream) 

Source Link

Document

Set the character stream for this input source.

Usage

From source file:org.wso2.carbon.identity.user.registration.UserRegistrationService.java

private TenantRegistrationConfig getTenantSignUpConfig(int tenantId) throws IdentityException {
    TenantRegistrationConfig config;//from  w  w  w .j a v  a  2  s. c  om
    NodeList nodes;
    try {
        // start tenant flow to load tenant registry
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        Registry registry = (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .getRegistry(RegistryType.SYSTEM_GOVERNANCE);
        if (registry.resourceExists(SelfRegistrationConstants.SIGN_UP_CONFIG_REG_PATH)) {
            Resource resource = registry.get(SelfRegistrationConstants.SIGN_UP_CONFIG_REG_PATH);
            // build config from tenant registry resource
            DocumentBuilder builder = getSecuredDocumentBuilder();
            String configXml = new String((byte[]) resource.getContent());
            InputSource configInputSource = new InputSource();
            configInputSource.setCharacterStream(new StringReader(configXml.trim()));
            Document doc = builder.parse(configInputSource);
            nodes = doc.getElementsByTagName(SelfRegistrationConstants.SELF_SIGN_UP_ELEMENT);
            if (nodes.getLength() > 0) {
                config = new TenantRegistrationConfig();
                config.setSignUpDomain(((Element) nodes.item(0))
                        .getElementsByTagName(SelfRegistrationConstants.SIGN_UP_DOMAIN_ELEMENT).item(0)
                        .getTextContent());
                // there can be more than one <SignUpRole> elements, iterate through all elements
                NodeList rolesEl = ((Element) nodes.item(0))
                        .getElementsByTagName(SelfRegistrationConstants.SIGN_UP_ROLE_ELEMENT);
                for (int i = 0; i < rolesEl.getLength(); i++) {
                    Element tmpEl = (Element) rolesEl.item(i);
                    String tmpRole = tmpEl.getElementsByTagName(SelfRegistrationConstants.ROLE_NAME_ELEMENT)
                            .item(0).getTextContent();
                    boolean tmpIsExternal = Boolean.parseBoolean(
                            tmpEl.getElementsByTagName(SelfRegistrationConstants.IS_EXTERNAL_ELEMENT).item(0)
                                    .getTextContent());
                    config.getRoles().put(tmpRole, tmpIsExternal);
                }
                return config;
            } else {
                return null;
            }
        }
    } catch (RegistryException e) {
        throw new IdentityException("Error retrieving sign up config from registry " + e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        throw new IdentityException("Error parsing tenant sign up configuration " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new IdentityException("Error parsing tenant sign up configuration " + e.getMessage(), e);
    } catch (IOException e) {
        throw new IdentityException("Error parsing tenant sign up configuration " + e.getMessage(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return null;
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.SyncmlParserTest.java

@Test
public void parseSyncML() throws IOException, SyncmlMessageFormatException, SyncmlOperationException {

    SyncmlParser syncmlParser = new SyncmlParser();
    File syncmlTestMessage = new File(
            getClass().getClassLoader().getResource("syncml-test-message.xml").getFile());

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;//from   ww w.  j a va2  s. c  om
    Document document = null;

    try {
        docBuilder = docBuilderFactory.newDocumentBuilder();
        if (docBuilder != null) {
            document = docBuilder.parse(syncmlTestMessage);
        }
    } catch (ParserConfigurationException e) {
        Assert.fail("Test failure in parser configuration while reading syncml-test-message.xml.");
    } catch (SAXException e) {
        Assert.fail("Test failure occurred while reading syncml-test-message.xml.");
    } catch (IOException e) {
        Assert.fail("Test failure while accessing syncml-test-message.xml.");
    }

    SyncmlGenerator generator = new SyncmlGenerator();
    String fileInputSyncmlMsg = FileUtils.readFileToString(syncmlTestMessage);
    String inputSyncmlMessage = null;

    String generatedSyncmlMsg = generator.generatePayload(syncmlParser.parseSyncmlPayload(document));

    Document documentInputSyncML;
    try {
        DocumentBuilder documentBuilderInputSyncML = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource inputSourceInputSyncML = new InputSource();
        inputSourceInputSyncML.setCharacterStream(new StringReader(fileInputSyncmlMsg));
        documentInputSyncML = documentBuilderInputSyncML.parse(inputSourceInputSyncML);

        inputSyncmlMessage = convertToString(documentInputSyncML);
    } catch (Exception e) {
        log.info("Failure occurred in input test XML file parsing.");
    }
    Assert.assertEquals(inputSyncmlMessage, generatedSyncmlMsg);
}

From source file:org.wso2.carbon.tools.wsdlvalidator.WsdlValidator.java

/**
 * Securely parse XML document.//w w  w.j  ava 2  s  . c o m
 *
 * @param payload String XML
 * @return XML Document
 * @throws WSDLValidatorException on SAX, IO or parsing error
 */
private Document secureParseXML(String payload) throws WSDLValidatorException {

    Document document;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);

        // Perform namespace processing
        dbf.setFeature("http://xml.org/sax/features/namespaces", true);

        // Validate the document and report validity errors.
        dbf.setFeature("http://xml.org/sax/features/validation", true);

        // Build the grammar but do not use the default attributes and attribute types information it contains.
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);

        // Ignore the external DTD completely.
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(payload));
        document = db.parse(inputSource);
    } catch (ParserConfigurationException e) {
        throw new WSDLValidatorException("Error parsing XML document", e);
    } catch (SAXException e) {
        throw new WSDLValidatorException("SAX error in processing XML document", e);
    } catch (IOException e) {
        throw new WSDLValidatorException("IO error in processing XML document", e);
    }
    return document;
}

From source file:org.wso2.carbon.webapp.list.ui.WebAppDataExtractor.java

/**
 * This method reads the web.xml file and seach for whether cxf configuration file is included
 *
 * @param stream stream//from w ww .j  a va  2  s  .c  om
 * @return cxf file localtion
 */

private void processWebXml(String stream) {

    try {
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(stream));

        DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        org.w3c.dom.Document doc = b.parse(is); //doc.getDomConfig().setParameter();

        XPath xPath = XPathFactory.newInstance().newXPath();
        String configLocationParam = xPath.evaluate(
                "/web-app/servlet/init-param[param-name[contains(text(),'config-location')]]/param-value/text()",
                doc.getDocumentElement());
        if (configLocationParam == null || configLocationParam == "") {
            configLocationParam = xPath.evaluate(
                    "/web-app/context-param[param-name[contains(text(),'contextConfigLocation')]]/param-value/text()",
                    doc.getDocumentElement());
        }
        String cxfServletName = xPath.evaluate(
                "/web-app/servlet[servlet-class[contains(text(),'org.apache.cxf.transport.servlet.CXFServlet')]]/servlet-name/text()",
                doc.getDocumentElement());
        String jaxservletUrlPattern = xPath.evaluate(
                "/web-app/servlet-mapping[servlet-name/text()=\"" + cxfServletName + "\"]/url-pattern/text()",
                doc.getDocumentElement());

        if (!"".equals(configLocationParam) && configLocationParam != null) {
            cxfConfigFileLocation = configLocationParam;
        } else {
            cxfConfigFileLocation = "WEB-INF/cxf-servlet.xml";
        }
        if (!"".equals(jaxservletUrlPattern) && jaxservletUrlPattern != null) {
            if (jaxservletUrlPattern.endsWith("/*")) {
                jaxservletUrlPattern = jaxservletUrlPattern.substring(0, jaxservletUrlPattern.length() - 2);
            }
            if (jaxservletUrlPattern.startsWith("/")) {
                jaxservletUrlPattern = jaxservletUrlPattern.substring(1);
            }
            this.jaxservletUrlPattern = jaxservletUrlPattern;
        } else {
            this.jaxservletUrlPattern = "services";
        }

    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.wso2.carbon.webapp.list.ui.WebAppDataExtractor.java

/**
 * This method reads the web.xml file and seach for whether service-list-path init param is set
 *
 * @param stream stream//from   w w  w.  ja v  a  2  s .  c  o m
 * @return cxf file localtion
 */

private String processServiceListPathWebXml(String stream) {

    try {
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(stream));

        DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        org.w3c.dom.Document doc = b.parse(is);

        XPath xPath = XPathFactory.newInstance().newXPath();
        String serviceListPathParam = xPath.evaluate(
                "/web-app/servlet/init-param[param-name[contains(text(), 'service-list-path')]]/param-value/text()",
                doc.getDocumentElement());

        if (!"".equals(serviceListPathParam) && serviceListPathParam != null) {
            return serviceListPathParam;
        } else {
            return "";
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        return "";
    }
}

From source file:org.wso2.carbon.wsdl2form.Util.java

/**
 * Securely parse XML document.//from   w  w w  .  j  av  a  2  s  .  c o m
 *
 * @param payload String XML
 * @return XML Document
 * @throws ParserConfigurationException error parsing xml
 * @throws IOException                  IO error in processing XML document
 * @throws SAXException                 SAX error in processing XML document
 */
private static Document secureParseXML(String payload)
        throws ParserConfigurationException, IOException, SAXException {

    Document document;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);

    // Perform namespace processing
    dbf.setFeature("http://xml.org/sax/features/namespaces", true);

    // Validate the document and report validity errors.
    dbf.setFeature("http://xml.org/sax/features/validation", true);

    // Build the grammar but do not use the default attributes and attribute types information it contains.
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);

    // Ignore the external DTD completely.
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource inputSource = new InputSource();
    inputSource.setCharacterStream(new StringReader(payload));
    document = db.parse(inputSource);
    return document;
}

From source file:pl.baczkowicz.spy.xml.XMLParser.java

/**
 * Unmarshals the given XML with the given root class.
 * //from   w w  w  . jav  a 2  s.c o m
 * @param xml The XML to unmarshal
 * @param rootClass The root class
 * 
 * @return The unmarshalled XML document
 * 
 * @throws XMLException When cannot unmarshal the XML document 
 */
public Object unmarshal(final String xml, final Class rootClass) throws XMLException {
    Object readObject = null;
    try {
        if (xml == null || xml.isEmpty()) {
            throw new XMLException("Cannot parse empty XML");
        }
        final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));

        readObject = unmarshaller.unmarshal(db.parse(is).getFirstChild(), rootClass);
        if (readObject instanceof JAXBElement) {
            readObject = ((JAXBElement) readObject).getValue();
        }
    } catch (JAXBException e) {
        throw new XMLException("Cannot read the XML ", e);
    } catch (IllegalArgumentException e) {
        throw new XMLException("Cannot read the XML ", e);
    } catch (SAXException e) {
        throw new XMLException("Cannot read the XML ", e);
    } catch (IOException e) {
        throw new XMLException("Cannot read the XML ", e);
    } catch (ParserConfigurationException e) {
        throw new XMLException("Cannot read the XML ", e);
    }

    return readObject;
}

From source file:SeedGenerator.MainForm.java

private void btnParseResponseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnParseResponseActionPerformed
    try {//w w  w  . j av  a 2  s.com
        String SQLurl = "SELECT id,resultSet FROM queryqueue where commonQueryId between 7 and 13;";
        Statement stmturl = con1.createStatement();
        ResultSet rsurl = stmturl.executeQuery(SQLurl);

        while (rsurl.next()) {
            try {
                String s = rsurl.getString("resultSet");
                int id = rsurl.getInt("id");
                //get the factory
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(s));

                Document doc = db.parse(is);
                boolean bool = true;

                Node n = doc.getFirstChild();

                Node firstnode = doc.getFirstChild();
                recursiveXmlParse(firstnode, id, false);
                //                    NodeList headnodes = doc.getElementsByTagName("head");
                //                    NodeList resultnodes = doc.getElementsByTagName("result");
                //                    for (int i = 0; i < headnodes.getLength(); i++) {
                //                        Element element = (Element) headnodes.item(i);
                //                        String b = element.getElementsByTagName("binding").item(0).getTextContent();
                //                        System.out.println(b);
                //                        //            System.out.println(element.getNodeName());
                //                    }
                //                    for (int i = 0; i < resultnodes.getLength(); i++) {
                //                        Element element = (Element) resultnodes.item(i);
                //                        System.out.println(element.getTextContent());
                //                    }
            } catch (Exception ex) {
                //             System.out.println(ex.getMessage());
            }
        }
        stmturl.close();
        rsurl.close();

        // return id + 1;
    } catch (Exception ex) {
        //    System.out.println(ex.getMessage());
    } // TODO add your handling code here:
}

From source file:SeedGenerator.MainForm.java

private void btnLodstatsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLodstatsActionPerformed

    try {//from www. j  a va2  s  .  c o m
        final WebClient webClient = new WebClient();//BrowserVersion.FIREFOX_24);
        for (int i = 1; i < 22; i++) {
            HtmlPage page = webClient.getPage(txtLodstatsUrl.getText() + "/rdfdocs?page=" + i);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(page.asXml()));
            Document doc = db.parse(is);

            NodeList nodeList = doc.getElementsByTagName("tr");
            String datasetName;
            String url;
            String format;
            String rowFormat;
            for (int j = 0; j < nodeList.getLength(); j++) {
                Node node = nodeList.item(j);
                try {
                    NodeList tdNodeList = node.getChildNodes();
                    url = tdNodeList.item(1).getChildNodes().item(1).getAttributes().getNamedItem("href")
                            .getNodeValue().trim();
                    datasetName = tdNodeList.item(1).getChildNodes().item(1).getTextContent().trim();
                    format = tdNodeList.item(7).getTextContent().trim();
                    if (format.equals("sparql")) {
                        HtmlPage page2 = webClient.getPage(txtLodstatsUrl.getText() + url);
                        File f = new File("datasets/lodstats/stats.lod2.eu" + url + "-"
                                + (new java.util.Date(System.nanoTime())).toString().replaceAll(" ", "")
                                        .replaceAll(":", "")
                                + ".html");
                        f.getParentFile().mkdirs();
                        f.createNewFile();
                        FileUtils.writeStringToFile(f, page2.getWebResponse().getContentAsString());

                        DocumentBuilderFactory dbf2 = DocumentBuilderFactory.newInstance();
                        DocumentBuilder db2 = dbf.newDocumentBuilder();
                        InputSource is2 = new InputSource();
                        is2.setCharacterStream(new StringReader(page2.asXml()));
                        Document doc2 = db.parse(is2);

                        NodeList liNodeList = doc2.getElementsByTagName("div");
                        for (int k = 0; k < nodeList.getLength(); k++) {
                            try {
                                if (liNodeList.item(k).getAttributes().getNamedItem("class").getTextContent()
                                        .equals("content")) {
                                    String endpointurl = liNodeList.item(k).getChildNodes().item(3)
                                            .getChildNodes().item(1).getChildNodes().item(1).getTextContent()
                                            .trim();
                                    if (endpointurl.endsWith("/")) {
                                        endpointurl = endpointurl.substring(0, endpointurl.length() - 1);
                                    }

                                    String SQL = "SELECT * FROM endpoints where endpointUrl='" + endpointurl
                                            + "' and source='lodstats'";
                                    Statement stmt = con.createStatement();
                                    ResultSet rs = stmt.executeQuery(SQL);
                                    if (!rs.next()) {

                                        String SQLi = "INSERT INTO endpoints (datasetName,endpointUrl,source) VALUES (?,?,?);";
                                        PreparedStatement pstmt = con.prepareStatement(SQLi);
                                        pstmt.setString(1, datasetName);
                                        pstmt.setString(2, endpointurl);
                                        pstmt.setString(3, "lodstats");
                                        //Statement stmt = con.createStatement();
                                        pstmt.executeUpdate();
                                        pstmt.close();

                                    }
                                    rs.close();
                                    stmt.close();
                                    System.out
                                            .println(liNodeList.item(k).getChildNodes().item(3).getChildNodes()
                                                    .item(1).getChildNodes().item(1).getTextContent().trim());
                                }
                            } catch (Exception ex) {

                            }
                            // .getChildNodes().item(1).getTextContent();
                        }
                    }
                    //System.out.println(format + " " + datasetName + " " + url);
                } catch (Exception ex) {
                    System.out.println(ex.toString());
                }
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    // do something with the current element
                    //                 System.out.println(node.getNodeName());
                }
            }
            //    recursiveXmlParse(doc, i, isStarted);
        }
    } catch (Exception ex) {

    }
    // TODO add your handling code here:
}

From source file:tufts.vue.ds.XMLIngest.java

public static void main(String[] args) throws IOException {
    DEBUG.Enabled = DEBUG.DR = DEBUG.IO = DEBUG.SCHEMA = true;

    tufts.vue.VUE.parseArgs(args);//w  w  w .  j a va 2s.  c om

    org.apache.log4j.Logger.getRootLogger().removeAllAppenders(); // need to do this or we get everything twice
    org.apache.log4j.Logger.getRootLogger()
            .addAppender(new org.apache.log4j.ConsoleAppender(tufts.vue.VUE.MasterLogPattern, "System.err"));

    //final XmlSchema schema = new RssSchema();

    errout("Max mem: " + Util.abbrevBytes(Runtime.getRuntime().maxMemory()));
    //getXMLStream();System.exit(0);

    final String file = args[0];
    final String key = args[1];

    Log.debug("File: " + file);
    Log.debug("Key: " + key);

    final InputSource is = new InputSource(file);
    is.setCharacterStream(new FileReader(file));

    //XMLIngest.XML_DEBUG = true;

    Schema schema = ingestXML(null, is, key);

    //schema.dumpSchema(System.err);

    System.err.println("\n");
    Log.debug("done");
}