Java Code Examples for org.dom4j.io.SAXReader#setEntityResolver()

The following examples show how to use org.dom4j.io.SAXReader#setEntityResolver() . 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: XMLParserFactoryProducer.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static SAXReader getSAXReader( final EntityResolver resolver ) {
  SAXReader reader = new SAXReader();
  if ( resolver != null ) {
    reader.setEntityResolver( resolver );
  }
  try {
    reader.setFeature( FEATURE_SECURE_PROCESSING, true );
    reader.setFeature( "http://xml.org/sax/features/external-general-entities", false );
    reader.setFeature( "http://xml.org/sax/features/external-parameter-entities", false );
    reader.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false );
  } catch ( SAXException e ) {
    logger.error( "Some parser properties are not supported." );
  }
  reader.setIncludeExternalDTDDeclarations( false );
  reader.setIncludeInternalDTDDeclarations( false );
  return reader;
}
 
Example 2
Source File: CfTableRepository.java    From mybatis-dalgen with Apache License 2.0 6 votes vote down vote up
/**
 * Gain cf table cf table.
 *
 * @param tableFile the table file
 * @return the cf table
 * @throws DocumentException the document exception
 */
public CfTable gainCfTable(File tableFile) throws DocumentException {
    CfTable cfTable = new CfTable();

    SAXReader saxReader = new SAXReader();
    saxReader.setEntityResolver(new IgnoreDTDEntityResolver()); // ignore dtd
    Document document = saxReader.read(tableFile);

    Element table = document.getRootElement();

    cfTable.setSqlname(attr(table, "sqlname"));
    cfTable.setPhysicalName(attr(table, "physicalName"));
    cfTable.setRemark(attr(table, "remark"));
    cfTable.setSequence(attr(table, "sequence"));

    fillColumns(cfTable, table);

    fillResultMap(cfTable, table);

    fillOperation(cfTable, table);

    return cfTable;
}
 
Example 3
Source File: ConfigurationReader.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Reads the checkstyle configuration from the given stream and returns a list of all modules within
 * this configuration.
 *
 * @param in
 *          the stream the configuration is loaded from
 * @return the list of modules
 * @throws CheckstylePluginException
 *           error while reading the configuration
 */
public static List<Module> read(InputSource in) throws CheckstylePluginException {

  List<Module> rules = null;
  try {

    final SAXReader reader = new SAXReader();
    reader.setEntityResolver(new XMLUtil.InternalDtdEntityResolver(PUBLIC2INTERNAL_DTD_MAP));
    final Document document = reader.read(in);

    rules = getModules(document);
  } catch (final DocumentException ex) {
    CheckstylePluginException.rethrow(ex);
  }

  return rules != null ? rules : new ArrayList<>();
}
 
Example 4
Source File: XmlFileSnapshot.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
private XmlNode loadXmlFile( String agent, String filePath ) {

        // load the file as a String
        String fileContent = loadFileContent(agent, filePath);

        try {
            SAXReader reader = new SAXReader();

            // following code prevents dom4j from running DTD XML validation
            reader.setEntityResolver(new EntityResolver() {

                @Override
                public InputSource resolveEntity( String publicId, String systemId ) throws SAXException,
                                                                                     IOException {

                    return new InputSource(new StringReader(""));
                }
            });

            // load XML document
            Document xmlDocument = reader.read(new StringReader(fileContent));
            return new XmlNode(null, xmlDocument.getRootElement());
        } catch (XMLException | DocumentException e) {
            throw new XMLException("Error parsing XML file: " + filePath, e);
        }
    }
 
Example 5
Source File: ImportSipP.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Function that adds a node to the resulting file
 * It takes an array list of Nodes, the root of the result document, the result document and
  	the template file name
 * @param sippNode
 * @param resultDocRoot
 * @param resultDoc
 * @param templateFile
 * @throws SAXException
 * @throws IOException
 * @throws DocumentException
 */
public static void addNodeCheckParameters(ArrayList<Element> sippNode, Element resultDocRoot, Document resultDoc, String templateFile, int scenarioNum) throws SAXException, IOException, DocumentException{		
	//Parsing the corresponding template file
 	SAXReader reader = new SAXReader();
 	reader.setEntityResolver(new XMLLoaderEntityResolver()); 	
 	Document template = reader.read("../conf/importsipp/Templates/"+templateFile+".xml");
	Element templateRoot = template.getRootElement(); 
	if(sippNode.size()>0)//if scenario
		resultDocRoot.addComment(sippNode.get(0).getName());
	
	//Run through all template elements
	for (Iterator i = templateRoot.elementIterator();i.hasNext();) 
	{
		Element templateElement = (Element) i.next();
		if(templateElement.getName().equals("parameter") && !sippNode.get(0).getName().equals("recvCmd")
				&& !sippNode.get(0).getName().equals("sendCmd"))
		{
			if(checkParameter(sippNode, templateElement))
				writeNodes(resultDoc,templateElement,sippNode,resultDocRoot,scenarioNum);
		}
       	else
       		writeNodes(resultDoc,templateElement,sippNode,resultDocRoot,scenarioNum);
	}
}
 
Example 6
Source File: XmlParserFactoryProducer.java    From hop with Apache License 2.0 6 votes vote down vote up
public static SAXReader getSAXReader( final EntityResolver resolver ) {
  SAXReader reader = new SAXReader();
  if ( resolver != null ) {
    reader.setEntityResolver( resolver );
  }
  try {
    reader.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true );
    reader.setFeature( "http://xml.org/sax/features/external-general-entities", false );
    reader.setFeature( "http://xml.org/sax/features/external-parameter-entities", false );
    reader.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false );
  } catch ( SAXException e ) {
    logger.error( "Some parser properties are not supported." );
  }
  reader.setIncludeExternalDTDDeclarations( false );
  reader.setIncludeInternalDTDDeclarations( false );
  return reader;
}
 
Example 7
Source File: DiameterManagerTest.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * read the message from XML scenario
 * @param    request The request to send
 * @return The answer to the request. Null if there is no answer (all peers down, or other error)
 */
private Element readMessageFromXml(String fileName) throws Exception {
    String filename = "../conf/diameter/diameterMessage.xml" ;

    // Instanciate the XML parser
    //TODO
    SAXReader reader = new SAXReader(false);
    reader.setEntityResolver(new XMLLoaderEntityResolver());
    
    File file = new File(filename);
    org.dom4j.Document doc = reader.read(file);

    // scenario level
    return (Element) doc.getRootElement().elements().get(0);
}
 
Example 8
Source File: MybatisXmlHandler.java    From gd-generator with MIT License 5 votes vote down vote up
@Override
protected MybatisXmlMeta read(Class<?> entityClass) throws Exception {
    MybatisXmlMeta meta = new MybatisXmlMeta();
    File file = new File(getXmlFilePath(entityClass));
    if (file.exists()) {
        SAXReader reader = new SAXReader();
        reader.setEntityResolver(new MyEntityResolver());
        Document doc = reader.read(file);
        if (doc != null) {
            @SuppressWarnings("unchecked")
            List<Element> elements = doc.getRootElement().elements();
            elements.forEach((element) -> {
                String id = element.attribute("id").getStringValue().intern();
                final boolean isAdd =
                        id == "delete".intern()
                                || id == "insert".intern()
                                || id == "update".intern()
                                || id == "findOne".intern()
                                || id == "findAll".intern()
                                || id == "baseResultMap".intern()
                                || id == "merge".intern()
                                || id == "count".intern()
                                || id == "baseColumn".intern()
                                || id == "condition".intern();
                if (!isAdd) {
                    meta.getOtherMappings().add(element.asXML());
                }
            });
        }
    }
    return meta;
}
 
Example 9
Source File: Utils.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public static Document stringParseXML(String xml, boolean deleteNS) throws Exception
{
	// remove beginning to '<' character
	int iPosBegin = xml.indexOf('<');
	if (iPosBegin > 0)
	{
		xml = xml.substring(iPosBegin);
	}
	// remove from '>' character to the end
	int iPosEnd = xml.lastIndexOf('>');
	if ((iPosEnd > 0) && (iPosEnd < xml.length() - 1))
	{
		xml = xml.substring(0, iPosEnd + 1);
	}
	
	int iPosXMLLine = xml.indexOf("<?xml");
	if (iPosXMLLine < 0)
	{
		xml = "<?xml version='1.0' encoding='ISO-8859-15'?>" + xml;
	}
	
	// remove the namespace because the parser does not support them if there are not declare in the root node
	if (deleteNS)
	{
		xml = xml.replaceAll("<[a-zA-Z\\.0-9_]+:", "<");
		xml = xml.replaceAll("</[a-zA-Z\\.0-9_]+:", "</");
	}
	// remove doctype information (dtd files for the XML syntax)
	xml = xml.replaceAll("<!DOCTYPE\\s+\\w+\\s+\\w+\\s+[^>]+>", "");
	
	InputStream input = new ByteArrayInputStream(xml.getBytes());
    SAXReader reader = new SAXReader(false);
    reader.setEntityResolver(new XMLLoaderEntityResolver());
    Document document = reader.read(input);
    return document;
}
 
Example 10
Source File: ASNInitializer.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public static Document getDocumentXML(final String xmlFileName)
{
    Document document = null;
    SAXReader reader = new SAXReader();
    reader.setEntityResolver(new XMLLoaderEntityResolver());
    try 
    {
        document = reader.read(xmlFileName);
    }
    catch (DocumentException ex) 
    {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, ex, "Wrong ASN1 file : ");
    }
    return document;
}
 
Example 11
Source File: PluginMetadataHelper.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of an element selected via an xpath expression from
 * a Plugin's plugin.xml file.
 *
 * @param pluginDir the path of the plugin directory.
 * @param xpath     the xpath expression.
 * @return the value of the element selected by the xpath expression.
 */
static String getElementValue( Path pluginDir, String xpath )
{
    if ( pluginDir == null )
    {
        return null;
    }
    try
    {
        final Path pluginConfig = pluginDir.resolve( "plugin.xml" );
        if ( Files.exists( pluginConfig ) )
        {
            final SAXReader saxReader = new SAXReader();
            saxReader.setEntityResolver(new EntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                    throw new IOException("External entity denied: " + publicId + " // " + systemId);
                }
            });
            saxReader.setEncoding( "UTF-8" );
            final Document pluginXML = saxReader.read( pluginConfig.toFile() );
            final Element element = (Element) pluginXML.selectSingleNode( xpath );
            if ( element != null )
            {
                return element.getTextTrim();
            }
        }
    }
    catch ( Exception e )
    {
        Log.error( "Unable to get element value '{}' from plugin.xml of plugin in '{}':", xpath, pluginDir, e );
    }
    return null;
}
 
Example 12
Source File: StackDiameterTest.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * read the message from XML scenario
 * @param    request The request to send
 * @return The answer to the request. Null if there is no answer (all peers down, or other error)
 */
private Element readMessageFromXml(String fileName) throws Exception {
    String filename = "../conf/diameter/diameterMessage.xml" ;

    // Instanciate the XML parser
    SAXReader reader = new SAXReader(false);
    reader.setEntityResolver(new XMLLoaderEntityResolver());
    
    File file = new File(filename);
    org.dom4j.Document doc = reader.read(file);

    // scenario level
    return (Element) doc.getRootElement().elements().get(0);
}
 
Example 13
Source File: XmlToAsn1.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public static Document getDocumentXML(final String xmlFileName)
{
    Document document = null;
    SAXReader reader = new SAXReader();
    reader.setEntityResolver(new XMLLoaderEntityResolver());       
    try 
    {
        document = reader.read(xmlFileName);
    }
    catch (DocumentException ex) 
    {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, ex, "Wrong ASN1 file : ");
    }
    return document;
}
 
Example 14
Source File: Asn1ToXml.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public static Document getDocumentXML(final String xmlFileName)
{
    Document document = null;
    SAXReader reader = new SAXReader();
    reader.setEntityResolver(new XMLLoaderEntityResolver());        
    try 
    {
        document = reader.read(xmlFileName);
    }
    catch (DocumentException ex) 
    {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, ex, "Wrong ASN1 file : ");
    }
    return document;
}
 
Example 15
Source File: XMLParser.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @param in
 * @param validateXML
 * @return parsed document
 */
public Document parse(InputStream in, boolean validateXML) {
    Document document;
    try {
        SAXReader reader = new SAXReader();
        reader.setEntityResolver(er);
        reader.setValidation(validateXML);
        document = reader.read(in, "");
    } catch (Exception e) {
        log.error("Exception reading XML", e);
        throw new OLATRuntimeException(XMLParser.class, "Exception reading XML", e);
    }
    return document;
}
 
Example 16
Source File: LowercaseTableNames.java    From unitime with Apache License 2.0 4 votes vote down vote up
public LowercaseTableNames() throws DocumentException, SAXException {
	iSAXReader = new SAXReader();
	iSAXReader.setEntityResolver(iEntityResolver);
	iSAXReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
}
 
Example 17
Source File: CreateBaseModelFromXml.java    From unitime with Apache License 2.0 4 votes vote down vote up
public CreateBaseModelFromXml() throws DocumentException {
	iSAXReader = new SAXReader();
	iSAXReader.setEntityResolver(iEntityResolver);
}
 
Example 18
Source File: Parameter.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public void applyXPath(String xml, String xpath, boolean deleteNS) throws Exception
  {
// remove beginning to '<' character
int iPosBegin = xml.indexOf('<');
if (iPosBegin > 0)
{
	xml = xml.substring(iPosBegin);
}
// remove from '>' character to the end
int iPosEnd = xml.lastIndexOf('>');
if ((iPosEnd > 0) && (iPosEnd < xml.length() - 1))
{
	xml = xml.substring(0, iPosEnd + 1);
}

int iPosXMLLine = xml.indexOf("<?xml");
if (iPosXMLLine < 0)
{
	// when java writes string, it is in ISO-8859-nn format
	xml = "<?xml version='1.0' encoding=\"ISO-8859-15\"?>\n" + xml;
}

// remove the namespace because the parser does not support them if there are not declare in the root node
if (deleteNS)
{
	xml = xml.replaceAll("<[a-zA-Z\\.0-9_]+:", "<");
	xml = xml.replaceAll("</[a-zA-Z\\.0-9_]+:", "</");
}
// remove doctype information (dtd files for the XML syntax)
xml = xml.replaceAll("<!DOCTYPE\\s+\\w+\\s+\\w+\\s+[^>]+>", "");

InputStream input = new ByteArrayInputStream(xml.getBytes());
   SAXReader reader = new SAXReader(false);
   reader.setEntityResolver(new XMLLoaderEntityResolver());
   Document document = reader.read(input);
   
   XPath xpathObject = document.createXPath(xpath);
   Object obj = xpathObject.evaluate(document.getRootElement());
	
   if (obj instanceof List)
   {
       List<Node> list = (List<Node>) obj;
       for (Node node : list)
       {
       	addObject(node);
       }
   }
   else 
   {
   	addObject(obj);
   }
  }
 
Example 19
Source File: LoopNodesImportProgressDialog.java    From hop with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "unchecked" )
private String[] doScan( IProgressMonitor monitor ) throws Exception {
  monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile",
      filename ), 1 );

  SAXReader reader = XmlParserFactoryProducer.getSAXReader( null );
  monitor.worked( 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  // Validate XML against specified schema?
  if ( meta.isValidating() ) {
    reader.setValidation( true );
    reader.setFeature( "http://apache.org/xml/features/validation/schema", true );
  } else {
    // Ignore DTD
    reader.setEntityResolver( new IgnoreDtdEntityResolver() );
  }
  monitor.worked( 1 );
  monitor
      .beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument" ), 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  InputStream is = null;
  try {
    Document document = null;
    if ( !Utils.isEmpty( filename ) ) {
      is = HopVfs.getInputStream( filename );
      document = reader.read( is, encoding );
    } else {
      if ( !Utils.isEmpty( xml ) ) {
        document = reader.read( new StringReader( xml ) );
      } else {
        document = reader.read( new URL( url ) );
      }
    }
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened" ),
        1 );
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode" ), 1 );

    if ( monitor.isCanceled() ) {
      return null;
    }
    List<Node> nodes = document.selectNodes( document.getRootElement().getName() );
    monitor.worked( 1 );
    monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes" ) );

    if ( monitor.isCanceled() ) {
      return null;
    }
    for ( Node node : nodes ) {
      if ( monitor.isCanceled() ) {
        return null;
      }
      if ( !listpath.contains( node.getPath() ) ) {
        nr++;
        monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes",
            String.valueOf( nr ) ) );
        monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.AddingNode", node
            .getPath() ) );
        listpath.add( node.getPath() );
        addLoopXPath( node, monitor );
      }
    }
    monitor.worked( 1 );
  } finally {
    try {
      if ( is != null ) {
        is.close();
      }
    } catch ( Exception e ) { /* Ignore */
    }
  }
  String[] list_xpath = listpath.toArray( new String[listpath.size()] );

  monitor.setTaskName( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned" ) );

  monitor.done();

  return list_xpath;

}
 
Example 20
Source File: XmlInputFieldsImportProgressDialog.java    From hop with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "unchecked" )
private RowMetaAndData[] doScan( IProgressMonitor monitor ) throws Exception {
  monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile",
      filename ), 1 );

  SAXReader reader = XmlParserFactoryProducer.getSAXReader( null );
  monitor.worked( 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  // Validate XML against specified schema?
  if ( meta.isValidating() ) {
    reader.setValidation( true );
    reader.setFeature( "http://apache.org/xml/features/validation/schema", true );
  } else {
    // Ignore DTD
    reader.setEntityResolver( new IgnoreDtdEntityResolver() );
  }
  monitor.worked( 1 );
  monitor
      .beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument" ), 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  InputStream is = null;
  try {

    Document document = null;
    if ( !Utils.isEmpty( filename ) ) {
      is = HopVfs.getInputStream( filename );
      document = reader.read( is, encoding );
    } else {
      if ( !Utils.isEmpty( xml ) ) {
        document = reader.read( new StringReader( xml ) );
      } else {
        document = reader.read( new URL( url ) );
      }
    }

    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened" ),
        1 );
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode" ), 1 );

    if ( monitor.isCanceled() ) {
      return null;
    }
    List<Node> nodes = document.selectNodes( this.loopXPath );
    monitor.worked( 1 );
    monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes" ) );

    if ( monitor.isCanceled() ) {
      return null;
    }
    for ( Node node : nodes ) {
      if ( monitor.isCanceled() ) {
        return null;
      }

      nr++;
      monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", String
          .valueOf( nr ) ) );
      monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", node
          .getPath() ) );
      setNodeField( node, monitor );
      childNode( node, monitor );

    }
    monitor.worked( 1 );
  } finally {
    try {
      if ( is != null ) {
        is.close();
      }
    } catch ( Exception e ) { /* Ignore */
    }
  }

  RowMetaAndData[] listFields = fieldsList.toArray( new RowMetaAndData[fieldsList.size()] );

  monitor.setTaskName( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned" ) );

  monitor.done();

  return listFields;

}