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

The following examples show how to use org.dom4j.io.SAXReader#setEncoding() . 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: DefaultDocumentFormater.java    From moql with Apache License 2.0 6 votes vote down vote up
public T importObject(InputStream is) throws XmlAccessException {
	SAXReader reader = new SAXReader();
	if (encoding != null)
		reader.setEncoding(encoding);
	Document document;
	try {
		if (validation) {
			// specify the schema to use
	        reader.setValidation(true);
	        reader.setFeature("http://apache.org/xml/features/validation/schema",true);
	        // add error handler which turns any errors into XML
	        ErrorChecker checker = new ErrorChecker();
	        reader.setErrorHandler(checker);
		}
		document = reader.read(is);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		throw new XmlAccessException("Read failed!", e);
	}
	return formater.importObjectFromElement(document.getRootElement());
}
 
Example 2
Source File: VersionProperty.java    From jfinal-api-scaffold with MIT License 6 votes vote down vote up
/**
 * Builds the document XML model up based the given reader of XML data.
 * @param in the input stream used to build the xml document
 * @throws java.io.IOException thrown when an error occurs reading the input stream.
 */
private void buildDoc(Reader in) throws IOException {
    try {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        document = xmlReader.read(in);
        buildNowVersion();
    }
    catch (Exception e) {
        Log.error("Error reading XML properties", e);
        throw new IOException(e.getMessage());
    }
    finally {
        if (in != null) {
            in.close();
        }
    }
}
 
Example 3
Source File: XmlProperty.java    From jfinal-api-scaffold with MIT License 6 votes vote down vote up
/**
 * Builds the document XML model up based the given reader of XML data.
 * @param in the input stream used to build the xml document
 * @throws java.io.IOException thrown when an error occurs reading the input stream.
 */
private void buildDoc(Reader in) throws IOException {
    try {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        document = xmlReader.read(in);
        propertyCache.clear();
    }
    catch (Exception e) {
        Log.error("Error reading XML properties", e);
        throw new IOException(e.getMessage());
    }
    finally {
        if (in != null) {
            in.close();
        }
    }
}
 
Example 4
Source File: AppiumNativePageSourceHandler.java    From agent with MIT License 5 votes vote down vote up
public String handle(String pageSource) throws IOException, DocumentException {
    if (StringUtils.isEmpty(pageSource)) {
        throw new IllegalArgumentException("pageSource cannot be empty");
    }

    try (InputStream in = new ByteArrayInputStream(pageSource.getBytes(Charset.forName("UTF-8")))) {
        SAXReader saxReader = new SAXReader();
        saxReader.setEncoding("UTF-8");

        Document document = saxReader.read(in);
        handleElement(document.getRootElement());

        return document.asXML();
    }
}
 
Example 5
Source File: PluginCacheConfigurator.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public void configure(String pluginName) {
    try {
        SAXReader saxReader = new SAXReader();
        saxReader.setEncoding("UTF-8");
        Document cacheXml = saxReader.read(configDataStream);
        List<Node> mappings = cacheXml.selectNodes("/cache-config/cache-mapping");
        for (Node mapping: mappings) {
            registerCache(pluginName, mapping);
        }
    }
    catch (DocumentException e) {
        Log.error(e.getMessage(), e);
    }
}
 
Example 6
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 7
Source File: DefaultVCardProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public DefaultVCardProvider() {
    super();
    // Initialize the pool of sax readers
    for (int i=0; i<POOL_SIZE; i++) {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlReaders.add(xmlReader);
    }
}
 
Example 8
Source File: PrivacyListProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private PrivacyListProvider() {
    super();
    // Initialize the pool of sax readers
    for (int i=0; i<POOL_SIZE; i++) {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlReaders.add(xmlReader);
    }

    // Checks if the PrivacyLists database is empty. 
    // In that case, we can optimize away many database calls. 
    databaseContainsPrivacyLists = new AtomicBoolean(false);
    loadDatabaseContainsPrivacyLists();
}
 
Example 9
Source File: UpdateManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void loadAvailablePluginsInfo() {
    Document xmlResponse;
    File file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf",
            "available-plugins.xml");
    if (!file.exists()) {
        return;
    }
    // Check read privs.
    if (!file.canRead()) {
        Log.warn("Cannot retrieve available plugins. File must be readable: " + file.getName());
        return;
    }
    try (FileReader reader = new FileReader(file)) {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlResponse = xmlReader.read(reader);
    } catch (Exception e) {
        Log.error("Error reading available-plugins.xml", e);
        return;
    }

    // Parse info and recreate available plugins
    Iterator it = xmlResponse.getRootElement().elementIterator("plugin");
    while (it.hasNext()) {
        Element plugin = (Element) it.next();
        final AvailablePlugin instance = AvailablePlugin.getInstance( plugin );
        // Add plugin to the list of available plugins at js.org
        availablePlugins.put(instance.getName(), instance);
    }
}
 
Example 10
Source File: PipelineContentImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Document getDocument() throws ContentProcessException {
    if (_xml && _document == null) {
        if (_contentStream != null) {
            try {
                SAXReader saxReader = new SAXReader();
                try {
                    saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
                    saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
                    saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
                }catch (SAXException ex){
                    LOGGER.error("Unable to turn off external entity loading, This could be a security risk.", ex);
                }
                saxReader.setEncoding(_encoding);
                _document = saxReader.read(_contentStream);
                _contentStream = null;
            } catch (DocumentException e) {
                throw new ContentProcessException("Error while converting " + _id + " into document.", e);
            } finally {
                ContentUtils.release(_contentStream);
                _contentStream = null;
            }
        } else {
            throw new ContentProcessException("Error while converting " + _id
                    + " into document. Both document and content stream cannot be null.");
        }
    }
    return _document;
}
 
Example 11
Source File: OfflineMessageStore.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws IllegalStateException {
    super.start();
    // Initialize the pool of sax readers
    for (int i=0; i<POOL_SIZE; i++) {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlReaders.add(xmlReader);
    }
    // Add this module as a user event listener so we can delete
    // all offline messages when a user is deleted
    UserEventDispatcher.addListener(this);
}
 
Example 12
Source File: XMLFileHelper.java    From anima with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取指定文件 的 xml 文档
 * 
 * @param location
 *            路径
 * @return 路径文件,如果指定资源不存在返回null
 */
public static Document getXMLFile(String location)
		throws DocumentException {
	File file = getResourceFile(DEFAULT_ClassLoader, location);
	if (file == null) {
		throw new IllegalStateException("Failed to get xml file,cause: file " + location + " not exsit!");
	} else {
		SAXReader saxReader = new SAXReader();
		saxReader.setEncoding("UTF-8");
		return saxReader.read(file);
	}
}
 
Example 13
Source File: XMLFileHelper.java    From anima with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取指定文件 的 xml 文档
 * 
 * @param location
 *            路径
 * @return 路径文件,如果指定资源不存在返回null
 */
public static Document getXMLFile(ClassLoader loader, String location)
		throws DocumentException {
	File file = getResourceFile(loader, location);
	if (file == null) {
		throw new IllegalStateException("The file " + location + " not exsit!");
	} else {
		SAXReader saxReader = new SAXReader();
		saxReader.setEncoding("UTF-8");
		return saxReader.read(file);
	}
}
 
Example 14
Source File: XMLProperties.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the document XML model up based the given reader of XML data.
 * @param in the input stream used to build the xml document
 * @throws java.io.IOException thrown when an error occurs reading the input stream.
 */
private void buildDoc(Reader in) throws IOException {
    try {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        document = xmlReader.read(in);
    }
    catch (Exception e) {
        Log.error("Error reading XML properties", e);
        throw new IOException(e.getMessage());
    }
}
 
Example 15
Source File: XMLDocUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
   * 根据模板的路径:uri 创建文档。
   * 注:如果需要得XML文档位于jar包中,则SAXReader.read()必须使用URL形式得参数,用String等会找不到
   * @return
   */
  public static Document createDoc(String uri) {
      URL fileUrl = URLUtil.getResourceFileUrl(uri);
      if (fileUrl == null) {
          throw new RuntimeException("定义的文件没有找到:" + uri);
      }
      
SAXReader saxReader = new SAXReader();
      try {
          saxReader.setEncoding("UTF-8");
          return saxReader.read(fileUrl);
      } catch (DocumentException e) {
      	throw new RuntimeException("读取XML文件出错:" + fileUrl, e);
      }
  }
 
Example 16
Source File: XMLDocUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * 根据XML文件的绝对路径来创建文档对象
 * @return
 */
public static Document createDocByAbsolutePath(String file) {
    SAXReader saxReader = new SAXReader();
    try {
        saxReader.setEncoding("UTF-8");
        return saxReader.read(file);
    } catch (DocumentException e) {
    	throw new RuntimeException("读取XML文件出错:" + file, e);
    }
}
 
Example 17
Source File: MUCRoomHistory.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new message and adds it to the history. The new message will be created based on
 * the provided information. This information will likely come from the database when loading
 * the room history from the database.
 *
 * @param senderJID the sender's JID of the message to add to the history.
 * @param nickname the sender's nickname of the message to add to the history.
 * @param sentDate the date when the message was sent to the room.
 * @param subject the subject included in the message.
 * @param body the body of the message.
 * @param stanza the stanza to add
 */
public void addOldMessage(String senderJID, String nickname, Date sentDate, String subject,
        String body, String stanza)
{
    Message message = new Message();
    message.setType(Message.Type.groupchat);
    if (stanza != null) {
        // payload initialized as XML string from DB
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        try {
            Element element = xmlReader.read(new StringReader(stanza)).getRootElement();
            for (Element child : (List<Element>)element.elements()) {
                Namespace ns = child.getNamespace();
                if (ns == null || ns.getURI().equals("jabber:client") || ns.getURI().equals("jabber:server")) {
                    continue;
                }
                Element added = message.addChildElement(child.getName(), child.getNamespaceURI());
                if (!child.getText().isEmpty()) {
                    added.setText(child.getText());
                }
                for (Attribute attr : (List<Attribute>)child.attributes()) {
                    added.addAttribute(attr.getQName(), attr.getValue());
                }
                for (Element el : (List<Element>)child.elements()) {
                    added.add(el.createCopy());
                }
            }
            if (element.attribute("id") != null) {
                message.setID(element.attributeValue("id"));
            }
        } catch (Exception ex) {
            Log.error("Failed to parse payload XML", ex);
        }
    }
    message.setSubject(subject);
    message.setBody(body);
    // Set the sender of the message
    if (nickname != null && nickname.trim().length() > 0) {
        JID roomJID = room.getRole().getRoleAddress();
        // Recreate the sender address based on the nickname and room's JID
        message.setFrom(new JID(roomJID.getNode(), roomJID.getDomain(), nickname, true));
    }
    else {
        // Set the room as the sender of the message
        message.setFrom(room.getRole().getRoleAddress());
    }

    // Add the delay information to the message
    Element delayInformation = message.addChildElement("delay", "urn:xmpp:delay");
    delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(sentDate));
    if (room.canAnyoneDiscoverJID()) {
        // Set the Full JID as the "from" attribute
        delayInformation.addAttribute("from", senderJID);
    }
    else {
        // Set the Room JID as the "from" attribute
        delayInformation.addAttribute("from", room.getRole().getRoleAddress().toString());
    }
    historyStrategy.addMessage(message);
}
 
Example 18
Source File: CrowdVCardProvider.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * @see org.jivesoftware.openfire.vcard.DefaultVCardProvider#loadVCard(java.lang.String)
 */
@Override
public Element loadVCard(String username) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("loadvcard:" + username);
    }
    
    if (MUTEX.containsKey(username)) {
        // preventing looping
        return null;
    }

    try {
        MUTEX.put(username, username);
        
        Element vcard = super.loadVCard(username);
        
        if (vcard == null) {
            CrowdUserProvider userProvider = (CrowdUserProvider) UserManager.getUserProvider();
            try {
                User user = userProvider.getCrowdUser(username);
                String str = VCARD_TEMPLATE.replace("@displayname@", user.displayName)
                        .replace("@lastname@", user.lastName)
                        .replace("@firstname@", user.firstName)
                        .replace("@email@", user.email)
                        .replace("@nickname@", username);
                
                SAXReader xmlReader = new SAXReader();
                xmlReader.setEncoding("UTF-8");
                
                vcard = xmlReader.read(new StringReader(str)).getRootElement();
                
            } catch (UserNotFoundException unfe) {
                LOG.error("Unable to find user:" + String.valueOf(username) + " for loading its vcard", unfe);
                return null;
            } catch (DocumentException de) {
                LOG.error("vcard parsing error", de);
                return null;
            }

            
            if (LOG.isDebugEnabled()) {
                LOG.debug(vcard != null ? vcard.asXML() : "vcard is null");
            }
            
            
            // store this new vcard
            if (vcard != null) {
                try {
                    createVCard(username, vcard);
                } catch (AlreadyExistsException aee) {
                    LOG.error("Unable to create and store a new vcard for user:" + username + "; one already exists", aee);
                }
            }
        }
        
        return vcard;

    } catch (RuntimeException re) {
        LOG.error("Failure occured when loading a vcard for user:" + username, re);
        throw re;
    } finally {
        MUTEX.remove(username);
    }
}
 
Example 19
Source File: XmlUtil.java    From minimybatis with MIT License 4 votes vote down vote up
/**
 * readMapperXml
 * 
 * @param fileName
 * @param mappedStatements 
 * @see 
 */
@SuppressWarnings("rawtypes")
public static void readMapperXml(File fileName, Configuration configuration)
{

    try
    {

        // 创建一个读取器
        SAXReader saxReader = new SAXReader();
        saxReader.setEncoding(Constant.CHARSET_UTF8);
        
        // 读取文件内容
        Document document = saxReader.read(fileName);

        // 获取xml中的根元素
        Element rootElement = document.getRootElement();

        // 不是beans根元素的,文件不对
        if (!Constant.XML_ROOT_LABEL.equals(rootElement.getName()))
        {
            System.err.println("mapper xml文件根元素不是mapper");
            return;
        }

        String namespace = rootElement.attributeValue(Constant.XML_SELECT_NAMESPACE);

        List<MappedStatement> statements = new ArrayList<>();
        for (Iterator iterator = rootElement.elementIterator(); iterator.hasNext();)
        {
            Element element = (Element)iterator.next();
            String eleName = element.getName();
            
            MappedStatement statement = new MappedStatement();
            
            if (SqlType.SELECT.value().equals(eleName))
            {
                String resultType = element.attributeValue(Constant.XML_SELECT_RESULTTYPE);
                statement.setResultType(resultType);
                statement.setSqlCommandType(SqlType.SELECT);
            }
            else if (SqlType.UPDATE.value().equals(eleName))
            {
                statement.setSqlCommandType(SqlType.UPDATE);
            }
            else
            {
                // 其他标签自己实现
                System.err.println("不支持此xml标签解析:" + eleName);
                statement.setSqlCommandType(SqlType.DEFAULT);
            }

            //设置SQL的唯一ID
            String sqlId = namespace + "." + element.attributeValue(Constant.XML_ELEMENT_ID); 
            
            statement.setSqlId(sqlId);
            statement.setNamespace(namespace);
            statement.setSql(CommonUtis.stringTrim(element.getStringValue()));
            statements.add(statement);
            
            System.out.println(statement);
            configuration.addMappedStatement(sqlId, statement);
            
            //这里其实是在MapperRegistry中生产一个mapper对应的代理工厂
            configuration.addMapper(Class.forName(namespace));
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

}
 
Example 20
Source File: XMLUtil.java    From APICloud-Studio with GNU General Public License v3.0 2 votes vote down vote up
/**
 * 读取XML文件
 * @param in 输入流
 * @return
 * @throws DocumentException
 */
public static Document loadXmlFile(InputStream in) throws DocumentException {
    SAXReader reader = new SAXReader();
    reader.setEncoding("UTF-8");
    return reader.read(in);
}