Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setValidating()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#setValidating() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DOMHelper.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private DocumentBuilder getDocumentBuilder() {
    DocumentBuilder builder = null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setExpandEntityReferences(false);
    factory.setValidating(false);

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return builder;
}
 
Example 2
Source File: XMLUtil.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static DocumentBuilder getDocumentBuilder(final boolean namespaceAware,
                                                 final boolean validating)
{ 
   try
   {
      final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(namespaceAware);
      dbf.setValidating(validating);
      return dbf.newDocumentBuilder();
   }
   catch (ParserConfigurationException pce)
   {
      LOGGER.error(pce);
      return null;
   }
}
 
Example 3
Source File: XmlSupport.java    From java-scanner-access-twain with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Document loadPrefsDoc(InputStream in)
    throws SAXException, IOException
{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringComments(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new Resolver());
        db.setErrorHandler(new EH());
        return db.parse(new InputSource(in));
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e);
    }
}
 
Example 4
Source File: TypeGen.java    From j-road with Apache License 2.0 6 votes vote down vote up
/**
 * Parse WSDL files - extract types (schemas) and generate metadata for marshalling XmlBeans objects to XTee queries.
 *
 * @param wsdls
 * @throws Exception
 */
private static void loadWsdlSchemasAndGenerateMetadata(File[] wsdls) throws Exception {
  DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
  fac.setNamespaceAware(true);
  fac.setValidating(false);

  DocumentBuilder builder = fac.newDocumentBuilder();

  for (File wsdl : wsdls) {
    Document xmlWsdl = builder.parse(wsdl);
    curWsdl = wsdl;
    schemas.addAll(getSchemas(xmlWsdl.getElementsByTagNameNS(WSDL_NS, "types").item(0),
                              getNamespaces(xmlWsdl),
                              wsdl.getParent()));
    Properties databaseProps = getDatabaseProps(wsdl.getParentFile());
    String databaseNameOverride = databaseProps.getProperty(PROPERTY__DATABASE_NAME_OVERRIDE);
    if (databaseNameOverride != null) {
      logInfo(PROPERTY__DATABASE_NAME_OVERRIDE + " is set to '" + databaseNameOverride
          + "', will use it as database identifier.");
      dbDesc.setId(databaseNameOverride, true);
    }

    createMetadata(xmlWsdl);
    logInfo("Created metadata for database " + dbDesc.getId());
  }
}
 
Example 5
Source File: Maven.java    From IJava with MIT License 5 votes vote down vote up
private Path readConfiguredLocalRepositoryPath(Path settingsXmlPath) throws IOException, SAXException {
    if (!Files.isRegularFile(settingsXmlPath))
        return null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);

    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // We are configuring the factory, the configuration will be fine...
        e.printStackTrace();
        return null;
    }

    try (InputStream in = Files.newInputStream(settingsXmlPath)) {
        Document settingsDoc = builder.parse(in);
        NodeList settings = settingsDoc.getElementsByTagName("settings");
        if (settings.getLength() == 0)
            return null;

        for (int i = 0; i < settings.getLength(); i++) {
            Node setting = settings.item(i);
            switch (setting.getNodeName()) {
                case "localRepository":
                    String localRepository = setting.getTextContent();
                    localRepository = this.replaceMavenVars(localRepository);
                    return Paths.get(localRepository);
            }
        }
    }

    return null;
}
 
Example 6
Source File: XMLFactory.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link DocumentBuilderFactory} using the defaults defined in
 * this class ({@link #DEFAULT_DOM_NAMESPACE_AWARE},
 * {@link #DEFAULT_DOM_VALIDATING} etc.).
 *
 * @return Never <code>null</code>.
 */
@Nonnull
public static DocumentBuilderFactory createDefaultDocumentBuilderFactory ()
{
  final DocumentBuilderFactory aDocumentBuilderFactory = DocumentBuilderFactory.newInstance ();
  aDocumentBuilderFactory.setNamespaceAware (DEFAULT_DOM_NAMESPACE_AWARE);
  aDocumentBuilderFactory.setValidating (DEFAULT_DOM_VALIDATING);
  aDocumentBuilderFactory.setIgnoringElementContentWhitespace (DEFAULT_DOM_IGNORING_ELEMENT_CONTENT_WHITESPACE);
  aDocumentBuilderFactory.setExpandEntityReferences (DEFAULT_DOM_EXPAND_ENTITY_REFERENCES);
  aDocumentBuilderFactory.setIgnoringComments (DEFAULT_DOM_IGNORING_COMMENTS);
  aDocumentBuilderFactory.setCoalescing (DEFAULT_DOM_COALESCING);
  try
  {
    // Set secure processing to be the default. This is anyway the default in
    // JDK8
    aDocumentBuilderFactory.setFeature (EXMLParserFeature.SECURE_PROCESSING.getName (), true);
  }
  catch (final ParserConfigurationException ex1)
  {
    // Ignore
  }
  try
  {
    aDocumentBuilderFactory.setXIncludeAware (DEFAULT_DOM_XINCLUDE_AWARE);
  }
  catch (final UnsupportedOperationException ex)
  {
    // Ignore
  }
  return aDocumentBuilderFactory;
}
 
Example 7
Source File: RestApiPublisherUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method will validate the given xml content for the syntactical correctness
 *
 * @param xmlContent string of xml content
 * @return true if the xml content is valid, false otherwise
 * @throws APIManagementException
 */
public static boolean validateXMLSchema(String xmlContent) throws APIManagementException {
    xmlContent = "<xml>" + xmlContent + "</xml>";
    DocumentBuilderFactory factory = APIUtil.getSecuredDocumentBuilder();
    factory.setValidating(false);
    factory.setNamespaceAware(false);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.parse(new InputSource(new StringReader(xmlContent)));
    } catch (ParserConfigurationException | IOException | SAXException e) {
        log.error("Error occurred while parsing the provided xml content.", e);
        return false;
    }
    return true;
}
 
Example 8
Source File: ConfigManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private DocumentBuilder getNonValidatingBuilder() throws Exception {

            DocumentBuilderFactory tFactory = DbfFactory.getFactory();
            tFactory.setValidating(false);
            DocumentBuilder tBuilder = tFactory.newDocumentBuilder();
            tBuilder.setEntityResolver(DbfFactory.FACES_ENTITY_RESOLVER);
            tBuilder.setErrorHandler(DbfFactory.FACES_ERROR_HANDLER);
            return tBuilder;

        }
 
Example 9
Source File: XmlUtils.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parses the given XML string as a DOM document, using the JDK parser. The parser does not
 * validate, and is optionally namespace aware.
 *
 * @param xml            the XML content to be parsed (must be well formed)
 * @param namespaceAware whether the parser is namespace aware
 * @return the DOM document
 */
@NonNull
public static Document parseDocument(@NonNull String xml, boolean namespaceAware)
        throws ParserConfigurationException, IOException, SAXException {
    xml = stripBom(xml);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    InputSource is = new InputSource(new StringReader(xml));
    factory.setNamespaceAware(namespaceAware);
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(is);
}
 
Example 10
Source File: ImportFileDialog.java    From JuiceboxLegacy with MIT License 5 votes vote down vote up
private void loadFile(File currentFile, MainWindow mainWindow) {

        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "XML Files", "xml", "XML");
        setFileFilter(filter);

        int actionDialog = showOpenDialog(mainWindow);
        if (actionDialog == APPROVE_OPTION) {
            File importedFile = getSelectedFile();
            String path = importedFile.getAbsolutePath();
            mainWindow.updateNamesFromImport(path);

            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(false);
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                builder.setErrorHandler(new SimpleErrorHandler());
                builder.parse(new InputSource(path));
                copyFile(currentFile, originalStates);
                copyFile(importedFile, currentFile);
                JOptionPane.showMessageDialog(mainWindow, "Importing File:\n" + importedFile.getName(), "Opening",
                        JOptionPane.INFORMATION_MESSAGE);
                JOptionPane.showMessageDialog(mainWindow, "Previous states have been saved under file:\n" + originalStates.getName(), "Creating Backup",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(mainWindow, "Error while importing file:\n" + e.getMessage(), "Error",
                        JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }

            System.out.println("Opening File: " + importedFile.getName());

        }
    }
 
Example 11
Source File: TableDatabaseToHTML.java    From TableDisentangler with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] table_list = {7,36,115,394,428,440,464,765,766,771,799,944,1062,1091,1098,1102,1111,1112,1127,1170,1181,1209,1217,1243,1274,1277,
                1279,1280,1285,1296,1297,1309,1390,
                1423, 1424,1425,1465,1466,1486,1515,1517,1544,1551,1585,1618,1624,1635,1664,1676,1764,1792,1800,1838,1871,1875,1916,1930,1947,1951,1958,
1959,1962,1963,1978,2013,2027,2045,2066,2161,2171,2249,2279,2286,2295,2316,2338,2374,2406,2532,2662,2699,2750,2778,2782,2885,2888,2923,
3155,3156,3162,3176,3251,3333,3338,3369,3371,3378,3379,3391,3399,3400,3419,3420,3478,3479,3484,3514,3543,3558,3592,3661,3736,3762,3766,
3811,3829,3848,3849,3888,3931,3979,4004,4019,4025,4028,4055,4068,4093,4111,4136,4163,4202,4205,4206,4209,4223,4227,4312,4350,4351,4359,
4379,4380,4385,4406,4442,4485,4496,4532,4552,4559,4588,4589,4594,4595,4596,4610,4615,4617,4625,4629,4650,4664,4672,4673,4674,4675,4682,
4726,4781,4798,4850,4859,4882,4883,4923,4947,4963,4973,4975,4987,4988,4999,5000,5063,5092,5093,5106,5186,5226,5240,5243,5284,5305,5322,8049,
8071,8107,8117,8139,8148, 293, 653, 1048,1658,1862,2466,2467,3272,3985,3986,4127,4868,4901,4951,5292,5602,6186,6857,7052,7103,7104,7105,7506,7507,7508,7509,
7961,8163,8446,9505,11072,12375,12465,12466,12519,12559};
		String ClassName = "AdverseEvents";
		try{
			TableDatabaseToHTML h = new TableDatabaseToHTML();
		h.DataBase();
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("html");
		doc.appendChild(rootElement);

		// staff elements
		Element body = doc.createElement("body");
		rootElement.appendChild(body);
		String SQL = "SELECT * from arttable inner join originalarticle on originalarticle.Article_idArticle=arttable.Article_idArticle where idTable in "+Arrays.toString(table_list);
		SQL = SQL.replace("[", "(").replace("]", ")");
		Statement st = h.conn.createStatement();
		h.rs = st.executeQuery(SQL);
		while(h.rs.next())
		{
			String idTable = h.rs.getString(1);
			String TableOrder = h.rs.getString(2);
			String classA = h.rs.getString(10);
			String PMC = h.rs.getString(12);
			String xml =  h.rs.getString(16);
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setNamespaceAware(true);
			factory.setValidating(false);
			DocumentBuilder builder = factory.newDocumentBuilder();
		    InputSource is = new InputSource(new StringReader(xml));
		    Document parse =  builder.parse(is);
		    NodeList tablesxml = parse.getElementsByTagName("table-wrap");
		    for(int i = 0;i<tablesxml.getLength();i++)
		    {
		    	String table = Utilities.CreateXMLStringFromSubNode(tablesxml.item(i));
		    	if(table.contains("xlink"))
		    		continue;
		    	
		    	String label = "Table without label";
				List<Node> nl = getChildrenByTagName(tablesxml.item(i),"label");
				if(nl.size()>0)
				{
					label = Utilities.getString(nl.get(0));
				}
				if(label.equals(TableOrder))
				{
					Element MetaElement = doc.createElement("div");
					MetaElement.setTextContent("PMC:"+PMC+"   TableOrder:"+TableOrder+"   Tableid:"+idTable+"   TableClass: "+ClassName);
					Node TableNode = doc.importNode(tablesxml.item(i), true);
					MetaElement.appendChild(TableNode);
					body.appendChild(MetaElement);	
				}
		    }
		}
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		//StreamResult result = new StreamResult(new File("table_data_file.html"));

		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);
		 String body_out = Utilities.CreateXMLStringFromSubNode(body);
		 BufferedWriter writer = new BufferedWriter( new FileWriter( "table_data_file.html"));
		 writer.write( body_out);
		//transformer.transform(source, result);

		System.out.println("File saved!");
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}
 
Example 12
Source File: DOMCatalogReader.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Read a catalog from an input stream.
 *
 * <p>This class reads a catalog from an input stream:</p>
 *
 * <ul>
 * <li>Based on the QName of the root element, it determines which
 * parser to instantiate for this catalog.</li>
 * <li>It constructs a DOM Document from the catalog and</li>
 * <li>For each child of the root node, it calls the parser's
 * parseCatalogEntry method. This method is expected to make
 * appropriate calls back into the catalog to add entries for the
 * entries in the catalog. It is free to do this in whatever manner
 * is appropriate (perhaps using just the node passed in, perhaps
 * wandering arbitrarily throughout the tree).</li>
 * </ul>
 *
 * @param catalog The catalog for which this reader is called.
 * @param is The input stream that is to be read.
 * @throws IOException if the URL cannot be read.
 * @throws UnknownCatalogFormatException if the catalog format is
 * not recognized.
 * @throws UnparseableCatalogException if the catalog cannot be parsed.
 * (For example, if it is supposed to be XML and isn't well-formed or
 * if the parser class cannot be instantiated.)
 */
public void readCatalog(Catalog catalog, InputStream is)
  throws IOException, CatalogException {

  DocumentBuilderFactory factory = null;
  DocumentBuilder builder = null;

  factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setValidating(false);
  try {
    builder = factory.newDocumentBuilder();
  } catch (ParserConfigurationException pce) {
    throw new CatalogException(CatalogException.UNPARSEABLE);
  }

  Document doc = null;

  try {
    doc = builder.parse(is);
  } catch (SAXException se) {
    throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
  }

  Element root = doc.getDocumentElement();

  String namespaceURI = Namespaces.getNamespaceURI(root);
  String localName    = Namespaces.getLocalName(root);

  String domParserClass = getCatalogParser(namespaceURI,
                                           localName);

  if (domParserClass == null) {
    if (namespaceURI == null) {
      catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
                                                + localName);
    } else {
      catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
                                                + "{" + namespaceURI + "}"
                                                + localName);
    }
    return;
  }

  DOMCatalogParser domParser = null;

  try {
    domParser = (DOMCatalogParser) ReflectUtil.forName(domParserClass).newInstance();
  } catch (ClassNotFoundException cnfe) {
    catalog.getCatalogManager().debug.message(1, "Cannot load XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (InstantiationException ie) {
    catalog.getCatalogManager().debug.message(1, "Cannot instantiate XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (IllegalAccessException iae) {
    catalog.getCatalogManager().debug.message(1, "Cannot access XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (ClassCastException cce ) {
    catalog.getCatalogManager().debug.message(1, "Cannot cast XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  }

  Node node = root.getFirstChild();
  while (node != null) {
    domParser.parseCatalogEntry(catalog, node);
    node = node.getNextSibling();
  }
}
 
Example 13
Source File: DOMCatalogReader.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Read a catalog from an input stream.
 *
 * <p>This class reads a catalog from an input stream:</p>
 *
 * <ul>
 * <li>Based on the QName of the root element, it determines which
 * parser to instantiate for this catalog.</li>
 * <li>It constructs a DOM Document from the catalog and</li>
 * <li>For each child of the root node, it calls the parser's
 * parseCatalogEntry method. This method is expected to make
 * appropriate calls back into the catalog to add entries for the
 * entries in the catalog. It is free to do this in whatever manner
 * is appropriate (perhaps using just the node passed in, perhaps
 * wandering arbitrarily throughout the tree).</li>
 * </ul>
 *
 * @param catalog The catalog for which this reader is called.
 * @param is The input stream that is to be read.
 * @throws IOException if the URL cannot be read.
 * @throws UnknownCatalogFormatException if the catalog format is
 * not recognized.
 * @throws UnparseableCatalogException if the catalog cannot be parsed.
 * (For example, if it is supposed to be XML and isn't well-formed or
 * if the parser class cannot be instantiated.)
 */
public void readCatalog(Catalog catalog, InputStream is)
  throws IOException, CatalogException {

  DocumentBuilderFactory factory = null;
  DocumentBuilder builder = null;

  factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setValidating(false);
  try {
    builder = factory.newDocumentBuilder();
  } catch (ParserConfigurationException pce) {
    throw new CatalogException(CatalogException.UNPARSEABLE);
  }

  Document doc = null;

  try {
    doc = builder.parse(is);
  } catch (SAXException se) {
    throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
  }

  Element root = doc.getDocumentElement();

  String namespaceURI = Namespaces.getNamespaceURI(root);
  String localName    = Namespaces.getLocalName(root);

  String domParserClass = getCatalogParser(namespaceURI,
                                           localName);

  if (domParserClass == null) {
    if (namespaceURI == null) {
      catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
                                                + localName);
    } else {
      catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
                                                + "{" + namespaceURI + "}"
                                                + localName);
    }
    return;
  }

  DOMCatalogParser domParser = null;

  try {
    domParser = (DOMCatalogParser) ReflectUtil.forName(domParserClass).newInstance();
  } catch (ClassNotFoundException cnfe) {
    catalog.getCatalogManager().debug.message(1, "Cannot load XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (InstantiationException ie) {
    catalog.getCatalogManager().debug.message(1, "Cannot instantiate XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (IllegalAccessException iae) {
    catalog.getCatalogManager().debug.message(1, "Cannot access XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (ClassCastException cce ) {
    catalog.getCatalogManager().debug.message(1, "Cannot cast XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  }

  Node node = root.getFirstChild();
  while (node != null) {
    domParser.parseCatalogEntry(catalog, node);
    node = node.getNextSibling();
  }
}
 
Example 14
Source File: DOMCatalogReader.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/**
 * Read a catalog from an input stream.
 *
 * <p>This class reads a catalog from an input stream:</p>
 *
 * <ul>
 * <li>Based on the QName of the root element, it determines which
 * parser to instantiate for this catalog.</li>
 * <li>It constructs a DOM Document from the catalog and</li>
 * <li>For each child of the root node, it calls the parser's
 * parseCatalogEntry method. This method is expected to make
 * appropriate calls back into the catalog to add entries for the
 * entries in the catalog. It is free to do this in whatever manner
 * is appropriate (perhaps using just the node passed in, perhaps
 * wandering arbitrarily throughout the tree).</li>
 * </ul>
 *
 * @param catalog The catalog for which this reader is called.
 * @param is The input stream that is to be read.
 * @throws IOException if the URL cannot be read.
 * @throws UnknownCatalogFormatException if the catalog format is
 * not recognized.
 * @throws UnparseableCatalogException if the catalog cannot be parsed.
 * (For example, if it is supposed to be XML and isn't well-formed or
 * if the parser class cannot be instantiated.)
 */
public void readCatalog(Catalog catalog, InputStream is)
  throws IOException, CatalogException {

  DocumentBuilderFactory factory = null;
  DocumentBuilder builder = null;

  factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setValidating(false);
  try {
    builder = factory.newDocumentBuilder();
  } catch (ParserConfigurationException pce) {
    throw new CatalogException(CatalogException.UNPARSEABLE);
  }

  Document doc = null;

  try {
    doc = builder.parse(is);
  } catch (SAXException se) {
    throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
  }

  Element root = doc.getDocumentElement();

  String namespaceURI = Namespaces.getNamespaceURI(root);
  String localName    = Namespaces.getLocalName(root);

  String domParserClass = getCatalogParser(namespaceURI,
                                           localName);

  if (domParserClass == null) {
    if (namespaceURI == null) {
      catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
                                                + localName);
    } else {
      catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
                                                + "{" + namespaceURI + "}"
                                                + localName);
    }
    return;
  }

  DOMCatalogParser domParser = null;

  try {
    domParser = (DOMCatalogParser) ReflectUtil.forName(domParserClass).newInstance();
  } catch (ClassNotFoundException cnfe) {
    catalog.getCatalogManager().debug.message(1, "Cannot load XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (InstantiationException ie) {
    catalog.getCatalogManager().debug.message(1, "Cannot instantiate XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (IllegalAccessException iae) {
    catalog.getCatalogManager().debug.message(1, "Cannot access XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  } catch (ClassCastException cce ) {
    catalog.getCatalogManager().debug.message(1, "Cannot cast XML Catalog Parser class", domParserClass);
    throw new CatalogException(CatalogException.UNPARSEABLE);
  }

  Node node = root.getFirstChild();
  while (node != null) {
    domParser.parseCatalogEntry(catalog, node);
    node = node.getNextSibling();
  }
}
 
Example 15
Source File: WSS4JInOutTest.java    From steady with Apache License 2.0 4 votes vote down vote up
@Test
public void testCustomProcessorObject() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
    msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(WSHandlerConstants.USER, "myalias");
    msg.put("password", "myAliasPassword");

    handler.handleMessage(msg);

    doc = part;
    
    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/ds:Signature", doc);

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    final Map<String, Object> properties = new HashMap<String, Object>();
    final Map<QName, Object> customMap = new HashMap<QName, Object>();
    customMap.put(
        new QName(
            WSConstants.SIG_NS,
            WSConstants.SIG_LN
        ),
        CustomProcessor.class
    );
    properties.put(
        WSS4JInInterceptor.PROCESSOR_MAP,
        customMap
    );
    WSS4JInInterceptor inHandler = new WSS4JInInterceptor(properties);

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);

    inHandler.handleMessage(inmsg);
    
    WSSecurityEngineResult result = 
        (WSSecurityEngineResult) inmsg.get(WSS4JInInterceptor.SIGNATURE_RESULT);
    assertNotNull(result);
    
    Object obj = result.get("foo");
    assertNotNull(obj);
    assertEquals(obj.getClass().getName(), CustomProcessor.class.getName());
}
 
Example 16
Source File: MavenResolver.java    From IJava with MIT License 4 votes vote down vote up
private String solidifyPartialPOM(String rawIn) throws ParserConfigurationException, IOException, SAXException, TransformerException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();

    // Wrap in a dummy tag to allow fragments
    InputStream inStream = new SequenceInputStream(Collections.enumeration(Arrays.asList(
            new ByteArrayInputStream("<ijava>".getBytes(Charset.forName("utf-8"))),
            new ByteArrayInputStream(rawIn.getBytes(Charset.forName("utf-8"))),
            new ByteArrayInputStream("</ijava>".getBytes(Charset.forName("utf-8")))
    )));

    Document doc = builder.parse(inStream);
    NodeList rootChildren = doc.getDocumentElement().getChildNodes();

    // If input was a single "project" tag then we don't touch it. It is assumed
    // to be complete.
    if (rootChildren.getLength() == 1 && "project".equalsIgnoreCase(rootChildren.item(0).getNodeName()))
        return this.writeDOM(new DOMSource(rootChildren.item(0)));

    // Put the pieces together and fill in the blanks.
    Document fixed = builder.newDocument();

    Node project = fixed.appendChild(fixed.createElement("project"));

    Node dependencies = project.appendChild(fixed.createElement("dependencies"));
    Node repositories = project.appendChild(fixed.createElement("repositories"));

    boolean setModelVersion = false;
    boolean setGroupId = false;
    boolean setArtifactId = false;
    boolean setVersion = false;

    for (int i = 0; i < rootChildren.getLength(); i++) {
        Node child = rootChildren.item(i);

        switch (child.getNodeName()) {
            case "modelVersion":
                setModelVersion = true;
                this.appendChildInNewDoc(child, fixed, project);
                break;
            case "groupId":
                setGroupId = true;
                this.appendChildInNewDoc(child, fixed, project);
                break;
            case "artifactId":
                setArtifactId = true;
                this.appendChildInNewDoc(child, fixed, project);
                break;
            case "version":
                setVersion = true;
                this.appendChildInNewDoc(child, fixed, project);
                break;
            case "dependency":
                this.appendChildInNewDoc(child, fixed, dependencies);
                break;
            case "repository":
                this.appendChildInNewDoc(child, fixed, repositories);
                break;
            case "dependencies":
                // Add all dependencies to the collecting tag
                NodeList dependencyChildren = child.getChildNodes();
                for (int j = 0; j < dependencyChildren.getLength(); j++)
                    this.appendChildInNewDoc(dependencyChildren.item(j), fixed, dependencies);
                break;
            case "repositories":
                // Add all repositories to the collecting tag
                NodeList repositoryChildren = child.getChildNodes();
                for (int j = 0; j < repositoryChildren.getLength(); j++)
                    this.appendChildInNewDoc(repositoryChildren.item(j), fixed, repositories);
                break;
            default:
                this.appendChildInNewDoc(child, fixed, project);
                break;
        }
    }

    if (!setModelVersion) {
        Node modelVersion = project.appendChild(fixed.createElement("modelVersion"));
        modelVersion.setTextContent("4.0.0");
    }

    if (!setGroupId) {
        Node groupId = project.appendChild(fixed.createElement("groupId"));
        groupId.setTextContent("ijava.notebook");
    }

    if (!setArtifactId) {
        Node artifactId = project.appendChild(fixed.createElement("artifactId"));
        artifactId.setTextContent("cell");
    }

    if (!setVersion) {
        Node version = project.appendChild(fixed.createElement("version"));
        version.setTextContent("1");
    }

    return this.writeDOM(new DOMSource(fixed));
}
 
Example 17
Source File: WSS4JFaultCodeTest.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Test for WSS4JInInterceptor when it receives a message with no security header. 
 */
@Test
public void testNoSecurity() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);
    doc = part;
    
    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.ENCRYPT);
    inHandler.setProperty(WSHandlerConstants.DEC_PROP_FILE, "insecurity.properties");
    inHandler.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, TestPwdCallback.class.getName());

    try {
        inHandler.handleMessage(inmsg);
        fail("Expected failure on an message with no security header");
    } catch (SoapFault fault) {
        assertTrue(fault.getReason().startsWith(
            "An error was discovered processing the <wsse:Security> header"));
        QName faultCode = new QName(WSConstants.WSSE_NS, "InvalidSecurity");
        assertTrue(fault.getFaultCode().equals(faultCode));
    }
}
 
Example 18
Source File: Canonicalizer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This method tries to canonicalize the given bytes. It's possible to even
 * canonicalize non-wellformed sequences if they are well-formed after being
 * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
 *
 * @param inputBytes
 * @return the result of the canonicalization.
 * @throws CanonicalizationException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 */
public byte[] canonicalize(byte[] inputBytes)
    throws javax.xml.parsers.ParserConfigurationException,
    java.io.IOException, org.xml.sax.SAXException, CanonicalizationException {
    InputStream bais = new ByteArrayInputStream(inputBytes);
    InputSource in = new InputSource(bais);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

    dfactory.setNamespaceAware(true);

    // needs to validate for ID attribute normalization
    dfactory.setValidating(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    /*
     * for some of the test vectors from the specification,
     * there has to be a validating parser for ID attributes, default
     * attribute values, NMTOKENS, etc.
     * Unfortunately, the test vectors do use different DTDs or
     * even no DTD. So Xerces 1.3.1 fires many warnings about using
     * ErrorHandlers.
     *
     * Text from the spec:
     *
     * The input octet stream MUST contain a well-formed XML document,
     * but the input need not be validated. However, the attribute
     * value normalization and entity reference resolution MUST be
     * performed in accordance with the behaviors of a validating
     * XML processor. As well, nodes for default attributes (declared
     * in the ATTLIST with an AttValue but not specified) are created
     * in each element. Thus, the declarations in the document type
     * declaration are used to help create the canonical form, even
     * though the document type declaration is not retained in the
     * canonical form.
     */
    db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

    Document document = db.parse(in);
    return this.canonicalizeSubtree(document);
}
 
Example 19
Source File: WSS4JFaultCodeTest.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Test that an action mismatch gets mapped to a proper fault code 
 */
@Test
public void testActionMismatch() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);

    handler.handleMessage(msg);

    doc = part;
    
    assertValid("//wsse:Security", doc);

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, 
        WSHandlerConstants.TIMESTAMP + " " + WSHandlerConstants.USERNAME_TOKEN);
    inHandler.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, TestPwdCallback.class.getName());

    try {
        inHandler.handleMessage(inmsg);
        fail("Expected failure on an action mismatch");
    } catch (SoapFault fault) {
        assertTrue(fault.getReason().startsWith(
            "An error was discovered processing the <wsse:Security> header"));
        QName faultCode = new QName(WSConstants.WSSE_NS, "InvalidSecurity");
        assertTrue(fault.getFaultCode().equals(faultCode));
    }
}
 
Example 20
Source File: ResTag.java    From Stringlate with MIT License 4 votes vote down vote up
public static String sanitizeContent(String content) {
    char c;
    int length = content.length();
    StringBuilder sb = new StringBuilder(length + 16); // 16 seems to be the default capacity

    boolean replaceLtGt = false;
    if (content.contains("<")) {
        // The string contains (X|HT)ML tags, ensure it's valid by parsing the content
        // If it's not, then replace every <> with &lt; &gt; not to break the XML file
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setNamespaceAware(true);

            DocumentBuilder builder = factory.newDocumentBuilder();
            // Every XML needs to have a root tag, however, this is not the case for
            // Android strings, and so we need to wrap it around some arbitrary tags
            // in order to check whether the inner content is right or not.
            builder.parse(new InputSource(new StringReader("<a>" + content + "</a>")));
        } catch (Exception ignored) {
            replaceLtGt = true;
        }
    }

    // Keep track of insideAngleBrackets to escape " only if we're outside.
    boolean insideAngleBrackets = false;
    for (int i = 0; i < length; i++) {
        c = content.charAt(i);
        if (insideAngleBrackets) {
            if (c == '>') {
                insideAngleBrackets = false;
            }
            sb.append(c);
            continue;
        }

        switch (c) {
            // These should always be escaped
            case '\'':
                sb.append("\\'");
                break;
            // Keep an actual newline afterwards for more readability
            case '\n':
                sb.append("\\n\n");
                break;

            case '\\':
                if (i + 1 < length && isEscapeSequence(content.charAt(i + 1))) {
                    // Don't escape the \ itself if the next
                    // character belongs to a escape sequence.
                    // Also skip the next character to avoid processing it.
                    sb.append(c);
                    i++;
                } else {
                    sb.append("\\\\");
                }
                break;
            case '&':
                if (isHtmlEntity(content, i + 1)) {
                    sb.append(c);
                } else {
                    sb.append("&amp;");
                }
                break;

            // We might or not need to replace <>
            case '<':
                if (replaceLtGt) {
                    sb.append("&lt;");
                } else {
                    insideAngleBrackets = true;
                    sb.append(c);
                }
                break;
            case '>':
                sb.append(replaceLtGt ? "&gt;" : ">");
                break;

            // Quotes are a bit special
            case '"':
                if ((i == 0 && content.charAt(length - 1) == '"') ||
                        (i == length - 1 && content.charAt(0) == '"'))
                    sb.append('"');
                else
                    sb.append("\\\"");
                break;

            // Normal character
            default:
                sb.append(c);
                break;
        }
    }
    return sb.toString();
}