Java Code Examples for org.dom4j.Document#getRootElement()

The following examples show how to use org.dom4j.Document#getRootElement() . 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: BeanUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
public static Map<String,Object> xml2map(String xml){ 
	Map<String,Object> map = new HashMap<String,Object>(); 
	Document document; 
	try { 
		document =  DocumentHelper.parseText(xml);  
		Element root = document.getRootElement(); 
		for(Iterator<Element> itrProperty=root.elementIterator(); itrProperty.hasNext();){ 
			Element element = itrProperty.next(); 
			String key = element.getName(); 
			String value = element.getTextTrim(); 
			map.put(key, value); 
		} 
	} catch (DocumentException e) { 
		e.printStackTrace(); 
	} 
	return map; 
}
 
Example 2
Source File: SelectTagTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void multipleWithBooleanFalse() throws Exception {
	this.tag.setPath("name");
	this.tag.setItems(Country.getCountries());
	this.tag.setItemValue("isoCode");
	this.tag.setMultiple(false);
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();
	output = "<doc>" + output + "</doc>";

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();
	assertEquals(1, rootElement.elements().size());

	Element selectElement = rootElement.element("select");
	assertEquals("select", selectElement.getName());
	assertEquals("name", selectElement.attribute("name").getValue());
	assertNull(selectElement.attribute("multiple"));

	List children = selectElement.elements();
	assertEquals("Incorrect number of children", 4, children.size());
}
 
Example 3
Source File: ManifestFileUtils.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Update the plug-in's minSdkVersion and targetSdkVersion
 *
 * @param androidManifestFile
 * @throws IOException
 * @throws DocumentException
 */
public static String getVersionName(File androidManifestFile) throws IOException, DocumentException {
    SAXReader reader = new SAXReader();
    String versionName = "";
    if (androidManifestFile.exists()) {
        Document document = reader.read(androidManifestFile);// Read the XML file
        Element root = document.getRootElement();// Get the root node
        if ("manifest".equalsIgnoreCase(root.getName())) {
            List<Attribute> attributes = root.attributes();
            for (Attribute attr : attributes) {
                if (StringUtils.equalsIgnoreCase(attr.getName(), "versionName")) {
                    versionName = attr.getValue();
                }
            }
        }
    }
    return versionName;
}
 
Example 4
Source File: SelectTagTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void multipleExplicitlyFalse() throws Exception {
	this.tag.setPath("name");
	this.tag.setItems(Country.getCountries());
	this.tag.setItemValue("isoCode");
	this.tag.setMultiple("false");
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();
	output = "<doc>" + output + "</doc>";

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();
	assertEquals(1, rootElement.elements().size());

	Element selectElement = rootElement.element("select");
	assertEquals("select", selectElement.getName());
	assertEquals("name", selectElement.attribute("name").getValue());
	assertNull(selectElement.attribute("multiple"));

	List children = selectElement.elements();
	assertEquals("Incorrect number of children", 4, children.size());
}
 
Example 5
Source File: ManifestFileUtils.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Delete the custom header
 *
 * @param document
 * @param manifestOptions
 */
private static void removeCustomLaunches(Document document, ManifestOptions manifestOptions) {
    if (null == manifestOptions) {
        return;
    }
    Element root = document.getRootElement();// Get the root node
    // Update launch information
    if (manifestOptions.getRetainLaunches() != null && manifestOptions.getRetainLaunches().size() > 0) {
        List<? extends Node> nodes = root.selectNodes(
            "//activity/intent-filter/category|//activity-alias/intent-filter/category");
        for (Node node : nodes) {
            Element e = (Element)node;
            if ("android.intent.category.LAUNCHER".equalsIgnoreCase(e.attributeValue("name"))) {
                Element activityElement = e.getParent().getParent();
                String activiyName = activityElement.attributeValue("name");
                if (!manifestOptions.getRetainLaunches().contains(activiyName)) {
                    if (activityElement.getName().equalsIgnoreCase("activity-alias")) {
                        activityElement.getParent().remove(activityElement);
                    } else {
                        e.getParent().remove(e);
                    }
                }
            }
        }
    }
}
 
Example 6
Source File: RemoteArticleService.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public String getArticleXML(Long articleId) {
    Article article = articleDao.getEntity(articleId);
    if(article == null 
    		|| checkBrowsePermission(article.getChannel().getId() ) < 0 ) {
    	return ""; // 如果文章不存在 或 对文章所在栏目没有浏览权限
    }
    
    String pubUrl = article.getPubUrl();
    Document articleDoc = XMLDocUtil.createDocByAbsolutePath2(pubUrl);
    Element articleElement = articleDoc.getRootElement();
    Element hitRateNode = (Element) articleElement.selectSingleNode("//hitCount");
    hitRateNode.setText(article.getHitCount().toString()); // 更新点击率
    
    Document doc = org.dom4j.DocumentHelper.createDocument();
    Element articleInfoElement = doc.addElement("Response").addElement("ArticleInfo");
    articleInfoElement.addElement("rss").addAttribute("version", "2.0").add(articleElement);

    // 添加文章点击率;
    HitRateManager.getInstanse("cms_article").output(articleId);
    
    return doc.asXML();
}
 
Example 7
Source File: LabelDao.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
public static void initLanguageMap() {
	try {
		SAXReader reader = XmlHelper.createSaxReader();
		appClass = getAppClass();
		Document document = reader.read(getLangFile());
		Element root = document.getRootElement();
		languages.clear();
		for (Iterator<Element> it = root.elementIterator("lang"); it.hasNext();) {
			Element item = it.next();
			Long id = Long.valueOf(item.attributeValue("id"));
			String code = item.attributeValue("code");
			if (id == 3L) {
				continue;
			}
			languages.put(id, new OmLanguage(Locale.forLanguageTag(code)));
		}
	} catch (Exception e) {
		log.error("Error while building language map");
	}
}
 
Example 8
Source File: DomUtils.java    From kafka-eagle with Apache License 2.0 6 votes vote down vote up
public static void getTomcatServerXML(String xml, String modifyPort) throws Exception {
	SAXReader reader = new SAXReader();
	Document document = reader.read(new File(xml));
	Element node = document.getRootElement();
	List<?> tasks = node.elements();
	for (Object task : tasks) {
		Element taskNode = (Element) task;
		String name = taskNode.attributeValue("name");
		if ("Catalina".equals(name)) {
			String protocol = taskNode.element("Connector").attributeValue("protocol");
			if ("HTTP/1.1".equals(protocol)) {
				taskNode.element("Connector").addAttribute("port", modifyPort);
			}
		}
	}

	XMLWriter writer = new XMLWriter(new FileWriter(xml));
	writer.write(document);
	writer.close();
}
 
Example 9
Source File: WindowsServiceMojo.java    From joylau-springboot-daemon-windows with MIT License 6 votes vote down vote up
/**
 * 属性转化
 * @param xmlFile xml文件
 */
private void convert(File xmlFile){
    SAXReader reader = new SAXReader();
    try {
        Document document = reader.read(xmlFile);
        Element root = document.getRootElement();
        root.element("id").setText(artifactId);
        root.element("name").setText(getJarPrefixName());
        root.element("description").setText(null == description ? "暂无描述" : description);
        if (arguments.length > 0) {
            getLog().warn("arguments 参数设置已过期,参数配置可能不会生效,请分别设置 vmOptions 参数 和 programArguments 参数 [https://github.com/JoyLau/joylau-springboot-daemon-windows]");
        }
        String vm_options = StringUtils.isEmpty(vmOptions) ? " " : " " + vmOptions + " ";
        String program_arguments = StringUtils.isEmpty(programArguments) ? "" : " " + programArguments;
        root.element("arguments").setText(vm_options + "-jar " + getJarName() +  program_arguments);
        saveXML(document,xmlFile);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: ComponentHelper.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
/**
 * 根据元素XML配置文件,将各个属性设置到元素实体中,保存实体。
 * @param service
 * @param component
 * @param file
 * @return
 */
private static Component importXml(IComponentService service, Component component, File file) {
    Document document = XMLDocUtil.createDocByAbsolutePath(file.getPath());
    
    try {
        org.dom4j.Element rootElement = document.getRootElement();
        if(!rootElement.getName().equals(component.getComponentType())) {
            throw new BusinessException(EX.P_08);
        }
        org.dom4j.Element propertyElement = rootElement.element("property");
        component.setName(propertyElement.elementText("name"));
        component.setDescription(propertyElement.elementText("description"));
        component.setVersion(propertyElement.elementText("version"));
        component.setDefinition(document.asXML());
        if(component.isLayout()) {
            component.setPortNumber(1);
        }
    } catch (Exception e) {
        throw new BusinessException(EX.P_09, e);
    }
    
    return service.saveComponent(component);
}
 
Example 11
Source File: SavedSearchResultsMap.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.alfresco.repo.template.BaseTemplateMap#get(java.lang.Object)
 */
public Object get(Object key)
{
    String search = null;
    
    if (key != null && key.toString().length() != 0)
    {
        // read the Saved Search XML on the specified node - and get the Lucene search from it
        try
        {
            NodeRef ref = new NodeRef(key.toString());
            
            ContentReader content = services.getContentService().getReader(ref, ContentModel.PROP_CONTENT);
            if (content != null && content.exists())
            {
                // get the root element
                SAXReader reader = new SAXReader();
                Document document = reader.read(new StringReader(content.getContentString()));
                Element rootElement = document.getRootElement();
                
                Element queryElement = rootElement.element(ELEMENT_QUERY);
                if (queryElement != null)
                {
                    search = queryElement.getText();
                }
            }
        }
        catch (Throwable err)
        {
            throw new AlfrescoRuntimeException("Failed to find or load saved Search: " + key, err);
        }
    }
    
    // execute the search
    return query(search);
}
 
Example 12
Source File: XmlHelper.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public static Element fromString(final String str)
{
  if (StringUtils.isBlank(str) == true) {
    return null;
  }
  try {
    final Document document = DocumentHelper.parseText(str);
    return document.getRootElement();
  } catch (final DocumentException ex) {
    log.error("Exception encountered " + ex.getMessage());
  }
  return null;
}
 
Example 13
Source File: SelectTagTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void multipleExplicitlyTrue() throws Exception {
	this.tag.setPath("name");
	this.tag.setItems(Country.getCountries());
	this.tag.setItemValue("isoCode");
	this.tag.setMultiple("true");
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();
	output = "<doc>" + output + "</doc>";

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();
	assertEquals(2, rootElement.elements().size());

	Element selectElement = rootElement.element("select");
	assertEquals("select", selectElement.getName());
	assertEquals("name", selectElement.attribute("name").getValue());
	assertEquals("multiple", selectElement.attribute("multiple").getValue());

	List children = selectElement.elements();
	assertEquals("Incorrect number of children", 4, children.size());

	Element inputElement = rootElement.element("input");
	assertNotNull(inputElement);
}
 
Example 14
Source File: XmlUtils.java    From nbp with Apache License 2.0 5 votes vote down vote up
public ErrorCode xmlWriteVcenterInfo(VCenterInfo vc) {
    Document doc = loadConigXml(VCENTER_CONFIG);
    Element root = doc.getRootElement();
    Iterator< ? > it = root.elementIterator();
    while (it.hasNext())
    {
        Element vcElement = (Element) it.next();
        vcElement.attribute("vcip").setText(vc.getvCenterIp());
        vcElement.attribute("vcname").setText(vc.getvCenterUser());
        vcElement.attribute("vcpwd").setText(vc.getvCenterPassword());
        vcElement.attribute("registerflag").setText(vc.getRegisterFlag());
    }
    return writeToXML(VCENTER_CONFIG, doc);
}
 
Example 15
Source File: FlowDefinitionReferenceUpdater.java    From urule with Apache License 2.0 5 votes vote down vote up
public String update(String oldPath, String newPath, String xml) {
	try{
		boolean modify=false;
		Document doc=DocumentHelper.parseText(xml);
		Element element=doc.getRootElement();
		for(Object obj:element.elements()){
			if(!(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			String name=ele.getName();
			boolean match=false;
			if(name.equals("import-variable-library")){
				match=true;
			}else if(name.equals("import-constant-library")){
				match=true;
			}else if(name.equals("import-action-library")){
				match=true;
			}else if(name.equals("import-parameter-library")){
				match=true;
			}
			if(!match){
				continue;
			}
			String path=ele.attributeValue("path");
			if(path.endsWith(oldPath)){
				ele.addAttribute("path", newPath);
				modify=true;
			}
		}
		if(modify){
			return xmlToString(doc);
		}
		return null;
	}catch(Exception ex){
		throw new RuleException(ex);
	}
}
 
Example 16
Source File: XmlServletHandler.java    From urule with Apache License 2.0 5 votes vote down vote up
protected Element parseXml(InputStream stream){
	SAXReader reader=new SAXReader();
	Document document;
	try {
		document = reader.read(stream);
		Element root=document.getRootElement();
		return root;
	} catch (DocumentException e) {
		throw new RuleException(e);
	}
}
 
Example 17
Source File: RemoteArticleService.java    From boubei-tss with Apache License 2.0 4 votes vote down vote up
public String getArticleListByChannelAndTime(Long channelId, Integer year, Integer month) {
    if(channelId == null){
        throw new BusinessException(EX.CMS_1);
    }
    if(year == null || month == null){
        throw new BusinessException(EX.CMS_10);
    }
    
    Channel channel = channelDao.getEntity(channelId);
    if(channel == null) {
        throw new BusinessException(EX.CMS_11);
    }
    Channel site = channel.getSite();
    String publishBaseDir = site.getPath();
   
    String publishDir = publishBaseDir + "/" + year + "/" + DateUtil.fixMonth(month);
    List<File> xmlFiles = FileHelper.listFilesByTypeDeeply(".xml", new File(publishDir));
  
    Document doc = org.dom4j.DocumentHelper.createDocument();
    Element channelElement = doc.addElement("rss").addAttribute("version", "2.0");
 
    channelElement.addElement("channelName").setText(channel.getName()); 
    channelElement.addElement("totalPageNum").setText("1");
    channelElement.addElement("totalRows").setText("100");
    channelElement.addElement("currentPage").setText("1");
    for( File xmlFile : xmlFiles ){
        if(xmlFile.getName().startsWith(channelId + "_")){
            Document articleDoc = XMLDocUtil.createDocByAbsolutePath2(xmlFile.getPath());
            
            Node articleNode   = articleDoc.getRootElement();
            Node idNode        = articleNode.selectSingleNode("//id");
            Node titleNode     = articleNode.selectSingleNode("//title");
            Node authorNode    = articleNode.selectSingleNode("//author");
            Node summaryNode   = articleNode.selectSingleNode("//summary");
            Node issueDateNode = articleNode.selectSingleNode("//issueDate");
            
            createArticleElement(channelElement,
            		XMLDocUtil.getNodeText(idNode), 
            		XMLDocUtil.getNodeText(titleNode), 
            		XMLDocUtil.getNodeText(authorNode),
            		DateUtil.parse(XMLDocUtil.getNodeText(issueDateNode)), 
            		XMLDocUtil.getNodeText(summaryNode), 
                    0, 0, null);
        }
    }
    return "<Response><ArticleList>" + channelElement.asXML() + "</ArticleList></Response>";
}
 
Example 18
Source File: ImsCPFileResource.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Check for title and at least one resource.
 * 
 * @param unzippedDir
 * @return True if is of type.
 */
public static boolean validate(final File unzippedDir) throws AddingResourceException {
    final File fManifest = new File(unzippedDir, "imsmanifest.xml");
    final Document doc = IMSLoader.loadIMSDocument(fManifest);
    // do not throw exception already here, as it might be only a generic zip file
    if (doc == null) {
        return false;
    }

    // get all organization elements. need to set namespace
    final Element rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    final Map nsuris = new HashMap(1);
    nsuris.put("ns", nsuri);

    // Check for organiztaion element. Must provide at least one... title gets ectracted from either
    // the (optional) <title> element or the mandatory identifier attribute.
    // This makes sure, at least a root node gets created in CPManifestTreeModel.
    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);
    final Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AddingResourceException("resource.no.organisation");
    }

    // Check for at least one <item> element referencing a <resource>, which will serve as an entry point.
    // This is mandatory, as we need an entry point as the user has the option of setting
    // CPDisplayController to not display a menu at all, in which case the first <item>/<resource>
    // element pair gets displayed.
    final XPath resourcesXPath = rootElement.createXPath("//ns:resources");
    resourcesXPath.setNamespaceURIs(nsuris);
    final Element elResources = (Element) resourcesXPath.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AddingResourceException("resource.no.resource"); // no <resources> element.
    }
    final XPath itemsXPath = rootElement.createXPath("//ns:item");
    itemsXPath.setNamespaceURIs(nsuris);
    final List items = itemsXPath.selectNodes(rootElement);
    if (items.size() == 0) {
        throw new AddingResourceException("resource.no.item"); // no <item> element.
    }
    for (final Iterator iter = items.iterator(); iter.hasNext();) {
        final Element item = (Element) iter.next();
        final String identifierref = item.attributeValue("identifierref");
        if (identifierref == null) {
            continue;
        }
        final XPath resourceXPath = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        resourceXPath.setNamespaceURIs(nsuris);
        final Element elResource = (Element) resourceXPath.selectSingleNode(elResources);
        if (elResource == null) {
            throw new AddingResourceException("resource.no.matching.resource");
        }
        if (elResource.attribute("scormtype") != null) {
            return false;
        }
        if (elResource.attribute("scormType") != null) {
            return false;
        }
        if (elResource.attribute("SCORMTYPE") != null) {
            return false;
        }
        if (elResource.attributeValue("href") != null) {
            return true; // success.
        }
    }
    return false;
    // throw new AddingResourceException("resource.general.error");
}
 
Example 19
Source File: SearchProxy.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void writeResponse(InputStream input, OutputStream output)
    throws IOException
{
    if (response.getContentType().startsWith(MimetypeMap.MIMETYPE_ATOM) ||
        response.getContentType().startsWith(MimetypeMap.MIMETYPE_RSS))
    {
        // Only post-process ATOM and RSS feeds
        // Replace all navigation links with "proxied" versions
        SAXReader reader = new SAXReader();
        try
        {
            Document document = reader.read(input);
            Element rootElement = document.getRootElement();

            XPath xpath = rootElement.createXPath(ATOM_LINK_XPATH);
            Map<String,String> uris = new HashMap<String,String>();
            uris.put(ATOM_NS_PREFIX, ATOM_NS_URI);
            xpath.setNamespaceURIs(uris);

            List nodes = xpath.selectNodes(rootElement);
            Iterator iter = nodes.iterator();
            while (iter.hasNext())
            {
                Element element = (Element)iter.next();
                Attribute hrefAttr = element.attribute("href");
                String mimetype = element.attributeValue("type");
                if (mimetype == null || mimetype.length() == 0)
                {
                    mimetype = MimetypeMap.MIMETYPE_HTML;
                }
                String url = createUrl(engine, hrefAttr.getValue(), mimetype);
                if (url.startsWith("/"))
                {
                    url = rootPath + url;
                }
                hrefAttr.setValue(url);
            }
            
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(output, outputFormat);
            writer.write(rootElement);
            writer.flush();                
        }
        catch(DocumentException e)
        {
            throw new IOException(e.toString());
        }
    }
    else
    {
        super.writeResponse(input, output);
    }
}
 
Example 20
Source File: HuaXinSMSProvider.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@Override
public MessageResult sendSingleMessage(String mobile, String content) throws Exception {
    org.apache.http.client.HttpClient httpclient = new SSLClient();
    HttpPost post = new HttpPost(gateway);
    post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
    List<org.apache.http.NameValuePair> nvps = new ArrayList<org.apache.http.NameValuePair>();
    nvps.add(new BasicNameValuePair("action", "send"));
    nvps.add(new BasicNameValuePair("userid", ""));
    nvps.add(new BasicNameValuePair("account", username));
    nvps.add(new BasicNameValuePair("password", password));
    //多个手机号用逗号分隔
    nvps.add(new BasicNameValuePair("mobile", mobile));
    nvps.add(new BasicNameValuePair("content", content));
    nvps.add(new BasicNameValuePair("sendTime", ""));
    nvps.add(new BasicNameValuePair("extno", ""));
    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    HttpResponse response = httpclient.execute(post);
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    // 将字符转化为XML
    String returnString = EntityUtils.toString(entity, "UTF-8");
    Document doc = DocumentHelper.parseText(returnString);
    // 获取根节点
    Element rootElt = doc.getRootElement();
    // 获取根节点下的子节点的值
    String returnstatus = rootElt.elementText("returnstatus").trim();
    String message = rootElt.elementText("message").trim();
    String remainpoint = rootElt.elementText("remainpoint").trim();
    String taskID = rootElt.elementText("taskID").trim();
    String successCounts = rootElt.elementText("successCounts").trim();
    log.info(" mobile : " + mobile + "content : " + content);
    System.out.println(returnString);
    System.out.println("返回状态为:" + returnstatus);
    System.out.println("返回信息提示:" + message);
    System.out.println("返回余额:" + remainpoint);
    System.out.println("返回任务批次:" + taskID);
    System.out.println("返回成功条数:" + successCounts);
    EntityUtils.consume(entity);
    MessageResult messageResult = MessageResult.success(message);
    if (!"Success".equals(returnstatus)) {
        messageResult.setCode(500);
    }
    return messageResult;
}