Java Code Examples for org.dom4j.DocumentHelper

The following examples show how to use org.dom4j.DocumentHelper. These examples are extracted from open source projects. 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 Project: jeewx-boot   Source File: OpenWxController.java    License: Apache License 2.0 6 votes vote down vote up
public void checkWeixinAllNetworkCheck(HttpServletRequest request, HttpServletResponse response,String xml) throws DocumentException, IOException, AesException{
    String nonce = request.getParameter("nonce");
    String timestamp = request.getParameter("timestamp");
    String msgSignature = request.getParameter("msg_signature");
 
    WXBizMsgCrypt pc = new WXBizMsgCrypt(CommonWeixinProperties.COMPONENT_TOKEN, CommonWeixinProperties.COMPONENT_ENCODINGAESKEY, CommonWeixinProperties.component_appid);
    xml = pc.decryptMsg(msgSignature, timestamp, nonce, xml);
 
    Document doc = DocumentHelper.parseText(xml);
    Element rootElt = doc.getRootElement();
    String msgType = rootElt.elementText("MsgType");
    String toUserName = rootElt.elementText("ToUserName");
    String fromUserName = rootElt.elementText("FromUserName");
 
    if("event".equals(msgType)){
    	 String event = rootElt.elementText("Event");
      replyEventMessage(request,response,event,toUserName,fromUserName);
    }else if("text".equals(msgType)){
    	 String content = rootElt.elementText("Content");
      processTextMessage(request,response,content,toUserName,fromUserName);
    }
}
 
Example 2
/**
 * Generates the error tag
 * 
 * @param xml XMLWriter
 */
protected void generateError(XMLWriter xml)
{
    try
    {
        // Output the start of the error element
        Attributes nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_ERROR, WebDAV.XML_NS_ERROR, nullAttr);
        // Output error
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_CANNOT_MODIFY_PROTECTED_PROPERTY));

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_ERROR, WebDAV.XML_NS_ERROR);
    }
    catch (Exception ex)
    {
        // Convert to a runtime exception
        throw new AlfrescoRuntimeException("XML processing error", ex);
    }
}
 
Example 3
Source Project: das   Source File: ResourceUtil.java    License: Apache License 2.0 6 votes vote down vote up
public boolean initializeDasSetXml() throws Exception {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(DATA_SET_ROOT).addAttribute("name", DAS_SET_APPID);
    root.addElement("databaseSets").addElement("databaseSet")
            .addAttribute("name", DATA_SET_BASE).addAttribute("provider", "mysqlProvider")
            .addElement("add")
            .addAttribute("name", DATA_BASE)
            .addAttribute("connectionString", DATA_BASE)
            .addAttribute("databaseType", "Master")
            .addAttribute("sharding", "1");
    Element connectionLocator =  root.addElement("ConnectionLocator");
    connectionLocator.addElement("locator").addText("com.ppdai.das.core.DefaultConnectionLocator");
    connectionLocator.addElement("settings").addElement("dataSourceConfigureProvider").addText("com.ppdai.das.console.config.init.ConsoleDataSourceConfigureProvider");
    try (FileWriter fileWriter = new FileWriter(getDasXmlPath())) {
        XMLWriter writer = new XMLWriter(fileWriter);
        writer.write(document);
        writer.close();
    }
    return true;
}
 
Example 4
Source Project: Openfire   Source File: VCardTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, all placeholder in a template (defined in the same element) get
 * correctly replaced, when part of a larger element value.
 */
@Test
public void testReplaceEmbeddedPlaceholders() throws Exception
{
    // Setup fixture.
    final Document doc = DocumentHelper.parseText("<vcard><el>foo {placeholderA}, {placeholderB} bar</el></vcard>");
    final LdapVCardProvider.VCardTemplate template = new LdapVCardProvider.VCardTemplate(doc);
    final Map<String, String> attributes = new HashMap<>();
    attributes.put("placeholderA", "valueA");
    attributes.put("placeholderB", "valueB");

    // Execute system under test.
    final LdapVCardProvider.VCard vCard = new LdapVCardProvider.VCard(template);
    final Element result = vCard.getVCard(attributes);

    // Verify result.
    assertNotNull( result );
    assertEquals( "<vcard><el>foo valueA, valueB bar</el></vcard>", result.asXML() );
}
 
Example 5
Source Project: Openfire   Source File: VCardTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, all placeholders get correctly identified in a VCardTemplate, when
 * they're defined in the format that uses the first non-empty placeholder that's available.
 *
 * @see <a href="https://issues.igniterealtime.org/browse/OF-1106">OF-1106</a>
 */
@Test
public void testIdentifyPrioritizedPlaceholders() throws Exception
{
    // Setup fixture.
    final Document input = DocumentHelper.parseText("<vcard><el>(|({placeholderA})({placeholderB})({placeholderC}))</el></vcard>");

    // Execute system under test.
    final LdapVCardProvider.VCardTemplate result = new LdapVCardProvider.VCardTemplate(input);

    // Verify result.
    assertNotNull( result );
    assertNotNull( result.getAttributes() );
    assertEquals( 3, result.getAttributes().length );
    assertTrue( Arrays.asList( result.getAttributes()).contains("placeholderA") );
    assertTrue( Arrays.asList( result.getAttributes()).contains("placeholderB") );
    assertTrue( Arrays.asList( result.getAttributes()).contains("placeholderC") );
}
 
Example 6
Source Project: frpMgr   Source File: XmlMapper.java    License: MIT License 6 votes vote down vote up
/**
 * xml转map 不带属性
 * @param xmlStr
 * @param needRootKey 是否需要在返回的map里加根节点键
 * @throws DocumentException
 */
@SuppressWarnings("unchecked")
public static Map<String, Object> xmlToMap(String xmlStr, boolean needRootKey) {
	try {
		Document doc = DocumentHelper.parseText(xmlStr);
		Element root = doc.getRootElement();
		Map<String, Object> map = (Map<String, Object>) xmlToMap(root);
		if (root.elements().size() == 0 && root.attributes().size() == 0) {
			return map;
		}
		if (needRootKey) {
			//在返回的map里加根节点键(如果需要)
			Map<String, Object> rootMap = new HashMap<String, Object>();
			rootMap.put(root.getName(), map);
			return rootMap;
		}
		return map;
	} catch (DocumentException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 7
Source Project: Openfire   Source File: PubSubEngine.java    License: Apache License 2.0 6 votes vote down vote up
private void getDefaultNodeConfiguration(PubSubService service, IQ iq,
                                         Element childElement, Element defaultElement) {
    String type = defaultElement.attributeValue("type");
    type = type == null ? "leaf" : type;

    boolean isLeafType = "leaf".equals(type);
    DefaultNodeConfiguration config = service.getDefaultNodeConfiguration(isLeafType);
    if (config == null) {
        // Service does not support the requested node type so return an error
        Element pubsubError = DocumentHelper.createElement(
                QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", isLeafType ? "leaf" : "collections");
        sendErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
        return;
    }

    // Return data form containing default node configuration
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    replyChildElement.element("default").add(config.getConfigurationForm().getElement());
    router.route(reply);
}
 
Example 8
public void readFromXml(final String menuAsXml)
{
  if (menu == null) {
    log.error("User's menu is null, can't get FavoritesMenu!");
    return;
  }
  if (log.isDebugEnabled() == true) {
    log.debug("readFromXml: " + menuAsXml);
  }
  Document document = null;
  try {
    document = DocumentHelper.parseText(menuAsXml);
  } catch (final DocumentException ex) {
    log.error("Exception encountered " + ex, ex);
    return;
  }
  final MenuBuilderContext context = new MenuBuilderContext(menu, PFUserContext.getUser(), false);
  final Element root = document.getRootElement();
  menuEntries = new ArrayList<MenuEntry>();
  for (final Iterator< ? > it = root.elementIterator("item"); it.hasNext();) {
    final Element item = (Element) it.next();
    final MenuEntry menuEntry = readFromXml(item, context);
    menuEntries.add(menuEntry);
  }
}
 
Example 9
public Document saveDocument() {
    Document document = DocumentHelper.createDocument();
    document.addComment("University Course Timetabling");

    if (iSaveCurrent && getAssignment().nrAssignedVariables() != 0) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getSolution() == null ? getModel().getExtendedInfo(getAssignment()) : getSolution().getExtendedInfo());
        for (String key : new TreeSet<String>(solutionInfo.keySet())) {
            String value = solutionInfo.get(key);
            comments.append("    " + key + ": " + value + "\n");
        }
        document.addComment(comments.toString());
    }

    Element root = document.addElement("timetable");

    doSave(root);

    return document;
}
 
Example 10
Source Project: Openfire   Source File: VCardTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, all placeholder in a template defined in the format that is intended
 * to be replaced with the first non-empty matching attribute value, get correctly replaced.
 *
 * @see <a href="https://issues.igniterealtime.org/browse/OF-1106">OF-1106</a>
 */
@Test
public void testReplacePrioritizedPlaceholdersVariantC() throws Exception
{
    // Setup fixture.
    final Document doc = DocumentHelper.parseText("<vcard><el>(|({placeholderA})({placeholderB})({placeholderC}))</el></vcard>");
    final LdapVCardProvider.VCardTemplate template = new LdapVCardProvider.VCardTemplate(doc);
    final Map<String, String> attributes = new HashMap<>();
    attributes.put("placeholderA", "");
    attributes.put("placeholderB", "");
    attributes.put("placeholderC", "valueC");

    // Execute system under test.
    final LdapVCardProvider.VCard vCard = new LdapVCardProvider.VCard(template);
    final Element result = vCard.getVCard(attributes);

    // Verify result.
    assertNotNull( result );
    assertEquals( "<vcard><el>valueC</el></vcard>", result.asXML() );
}
 
Example 11
Source Project: tutorials   Source File: Dom4JParser.java    License: MIT License 6 votes vote down vote up
public void generateNewDocument() {
    try {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("XMLTutorials");
        Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01");
        tutorialElement.addAttribute("type", "xml");

        tutorialElement.addElement("title").addText("XML with Dom4J");

        tutorialElement.addElement("description").addText("XML handling with Dom4J");

        tutorialElement.addElement("date").addText("14/06/2016");

        tutorialElement.addElement("author").addText("Dom4J tech writer");

        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_dom4j_new.xml")), format);
        writer.write(document);
        writer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
Example 12
Source Project: roncoo-pay   Source File: WxCommonUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Xml转Map
 *
 * @param resultStr 带转换字符串
 * @return
 */
public final static Map<String, Object> xmlToMap(final String resultStr) {
    if (resultStr == null || StringUtil.isEmpty(resultStr)) {
        logger.error("微信服务商--待解析的XML报文为空!");
        return null;
    }
    try {
        Map<String, Object> resultMap = new HashMap<>();
        Document doc = DocumentHelper.parseText(resultStr);
        List<Element> list = doc.getRootElement().elements();
        for (Element element : list) {
            resultMap.put(element.getName(), element.getText());
        }
        return resultMap;
    } catch (DocumentException e) {
        logger.error("微信服务商--解析XML失败!{}", e);
        return null;
    }
}
 
Example 13
/**
 * Test convert document to byte array.
 * 
 * @throws Exception
 *             If something unexpected goes wrong.
 */
@Test
@PrepareForTest
@SuppressStaticInitializationFor
public void testConvertDocumentToByteArray() throws Exception {
	// Create a fake document.
	Document document = DocumentHelper.createDocument();
	Element root = document.addElement("ListExecutionContexts");
	root.addAttribute("id", "2");
	replayAll();
	// Perform the test
	final byte[] array = tested.convertDocumentToByteArray(document);
	verifyAll();
	assertNotNull(array);
	assertEquals(70, array.length);
}
 
Example 14
Source Project: Openfire   Source File: VCardTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, a placeholder gets correctly identified in a VCardTemplate when the
 * element value is made up of more than just the placeholder.
 */
@Test
public void testIdentifyEmbeddedPlaceholder() throws Exception
{
    // Setup fixture.
    final Document input = DocumentHelper.parseText("<vcard><el>foo{placeholder}bar</el></vcard>");

    // Execute system under test.
    final LdapVCardProvider.VCardTemplate result = new LdapVCardProvider.VCardTemplate(input);

    // Verify result.
    assertNotNull( result );
    assertNotNull( result.getAttributes() );
    assertEquals( 1, result.getAttributes().length );
    assertEquals( "placeholder", result.getAttributes()[0] );
}
 
Example 15
@Test
public void testOmitFields()
{
  final XmlObjectWriter writer = new XmlObjectWriter();
  final Document document = DocumentHelper.createDocument();
  final Element root = document.addElement("root");
  final TestObject obj = new TestObject();
  obj.s0 = "s0";
  obj.t0 = "t0";
  obj.color1 = obj.color2 = TestEnum.RED;
  Element el = writer.write(root, obj);
  containsElements(el, "s0");
  containsAttrs(el, "color1", "color2");
  containsNotAttrs(el, "OMIT_STATIC", "omitFinal", "omitTransient", "s0", "t0");
  containsNotElements(el, "t0");
  writer.setOnlyAnnotatedFields(true);
  el = writer.write(root, obj);
  containsNotAttrs(el, "color1", "s0", "t0");
  containsNotElements(el, "s0", "t0");
}
 
Example 16
Source Project: urule   Source File: FrameServletHandler.java    License: Apache License 2.0 6 votes vote down vote up
public void fileSource(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	String path=req.getParameter("path");
	path=Utils.decodeURL(path);
	InputStream inputStream=repositoryService.readFile(path,null);
	String content=IOUtils.toString(inputStream,"utf-8");
	inputStream.close();
	String xml=null;
	try{
		Document doc=DocumentHelper.parseText(content);
		OutputFormat format=OutputFormat.createPrettyPrint();
		StringWriter out=new StringWriter();
		XMLWriter writer=new XMLWriter(out, format);
		writer.write(doc);
		xml=out.toString();
	}catch(Exception ex){
		xml=content;
	}
	Map<String,Object> result=new HashMap<String,Object>();
	result.put("content", xml);
	writeObjectToJson(resp, result);
}
 
Example 17
Source Project: Openfire   Source File: VCardTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, all placeholder in a template (defined in the same element) get
 * correctly replaced.
 */
@Test
public void testReplacePlaceholders() throws Exception
{
    // Setup fixture.
    final Document doc = DocumentHelper.parseText("<vcard><el>{placeholderA}, {placeholderB}</el></vcard>");
    final LdapVCardProvider.VCardTemplate template = new LdapVCardProvider.VCardTemplate(doc);
    final Map<String, String> attributes = new HashMap<>();
    attributes.put("placeholderA", "valueA");
    attributes.put("placeholderB", "valueB");

    // Execute system under test.
    final LdapVCardProvider.VCard vCard = new LdapVCardProvider.VCard(template);
    final Element result = vCard.getVCard(attributes);

    // Verify result.
    assertNotNull( result );
    assertEquals( "<vcard><el>valueA, valueB</el></vcard>", result.asXML() );
}
 
Example 18
Source Project: Openfire   Source File: VCardTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, a placeholder in a template gets correctly replaced.
 */
@Test
public void testReplacePlaceholder() throws Exception
{
    // Setup fixture.
    final Document doc = DocumentHelper.parseText("<vcard><el>{placeholder}</el></vcard>");
    final LdapVCardProvider.VCardTemplate template = new LdapVCardProvider.VCardTemplate(doc);
    final Map<String, String> attributes = new HashMap<>();
    attributes.put("placeholder", "value");

    // Execute system under test.
    final LdapVCardProvider.VCard vCard = new LdapVCardProvider.VCard(template);
    final Element result = vCard.getVCard(attributes);

    // Verify result.
    assertNotNull( result );
    assertEquals( "<vcard><el>value</el></vcard>", result.asXML() );
}
 
Example 19
Source Project: jeewx   Source File: OpenwxController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "{appid}/callback")
    public void acceptMessageAndEvent(HttpServletRequest request, HttpServletResponse response) throws IOException, AesException, DocumentException {
        String msgSignature = request.getParameter("msg_signature");
        //LogUtil.info("第三方平台全网发布-------------{appid}/callback-----------验证开始。。。。msg_signature="+msgSignature);
        if (!StringUtils.isNotBlank(msgSignature))
            return;// 微信推送给第三方开放平台的消息一定是加过密的,无消息加密无法解密消息
 
        StringBuilder sb = new StringBuilder();
        BufferedReader in = request.getReader();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();
 
        String xml = sb.toString();
        Document doc = DocumentHelper.parseText(xml);
        Element rootElt = doc.getRootElement();
        String toUserName = rootElt.elementText("ToUserName");
 
        //微信全网测试账号
//        if (StringUtils.equalsIgnoreCase(toUserName, APPID)) {
//           LogUtil.info("全网发布接入检测消息反馈开始---------------APPID="+ APPID +"------------------------toUserName="+toUserName);
           checkWeixinAllNetworkCheck(request,response,xml);
//        }
    }
 
Example 20
private static File createPernsistenceXml(List<Class<?>> classes, File directory) throws Exception {
	Document document = DocumentHelper.createDocument();
	Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
	persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
			"http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
	persistence.addAttribute("version", "2.0");
	Element unit = persistence.addElement("persistence-unit");
	unit.addAttribute("name", "enhance");
	for (Class<?> o : classes) {
		Element element = unit.addElement("class");
		element.addText(o.getCanonicalName());
	}
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	File file = new File(directory, "persistence.xml");
	XMLWriter writer = new XMLWriter(new FileWriter(file), format);
	writer.write(document);
	writer.close();
	return file;
}
 
Example 21
Source Project: seed   Source File: WeixinInMsgParser.java    License: Apache License 2.0 6 votes vote down vote up
private static WeixinInMsg doParse(String xml) throws DocumentException {
    Document doc = DocumentHelper.parseText(xml);
    Element root = doc.getRootElement();
    String toUserName = root.elementText("ToUserName");
    String fromUserName = root.elementText("FromUserName");
    long createTime = Long.parseLong(root.elementText("CreateTime"));
    String msgType = root.elementText("MsgType");
    if("text".equals(msgType)){
        return parseInTextMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    if("image".equals(msgType)){
        return parseInImageMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    if("location".equals(msgType)){
        return parseInLocationMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    if("link".equals(msgType)){
        return parseInLinkMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    if("event".equals(msgType)){
        return parseInEventMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    throw new RuntimeException("未知的消息类型" + msgType + ", 请查阅微信公众平台开发者文档https://mp.weixin.qq.com/wiki");
}
 
Example 22
Source Project: Openfire   Source File: VCardTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, element values that are not a placeholder do not get replaced.
 */
@Test
public void testDontReplaceNonPlaceholder() throws Exception
{
    // Setup fixture.
    final Document doc = DocumentHelper.parseText("<vcard><el>placeholder</el></vcard>");
    final LdapVCardProvider.VCardTemplate template = new LdapVCardProvider.VCardTemplate(doc);
    final Map<String, String> attributes = new HashMap<>();
    attributes.put("placeholder", "value");

    // Execute system under test.
    final LdapVCardProvider.VCard vCard = new LdapVCardProvider.VCard(template);
    final Element result = vCard.getVCard(attributes);

    // Verify result.
    assertNotNull( result );
    assertEquals( "<vcard><el>placeholder</el></vcard>", result.asXML() );
}
 
Example 23
Source Project: boubei-tss   Source File: RemoteArticleService.java    License: Apache License 2.0 6 votes vote down vote up
private String createReturnXML(PageInfo pageInfo, Long channelId){
    Channel channel = channelDao.getEntity(channelId);
    List<?> articleList = pageInfo.getItems();
    
    Document doc = DocumentHelper.createDocument();
    Element channelElement = doc.addElement("rss").addAttribute("version", "2.0");
    
    channelElement.addElement("channelName").setText( channel.getName() ); // 多个栏目一起查找,取第一个栏目
    channelElement.addElement("totalRows").setText(String.valueOf(pageInfo.getTotalRows()));
    channelElement.addElement("totalPageNum").setText(String.valueOf(pageInfo.getTotalPages()));
    channelElement.addElement("currentPage").setText(String.valueOf(pageInfo.getPageNum()));
    for (int i = 0; i < articleList.size(); i++) {
        Object[] fields = (Object[]) articleList.get(i);
        Element itemElement = createArticleElement(channelElement, fields);
        
        Long articleId = (Long) fields[0];
        List<Attachment> attachments = articleDao.getArticleAttachments(articleId);
        ArticleHelper.addPicListInfo(itemElement, attachments);
    }
    
    return channelElement.asXML();
}
 
Example 24
Source Project: nbp   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
public Document loadConigXml(String filename) {
    Document document = null;
    Reader xmlReader = null;
    FileInputStream stream = null;
    try {
        SAXReader saxReader = new SAXReader();
        stream =  new FileInputStream(new File(filename));
        xmlReader = new InputStreamReader(stream, "UTF-8");
        document = saxReader.read(xmlReader);
    }
    catch (Exception ex) {
        _logger.error(String.format("the filename of document is %s, error [%s]" , filename
                ,ex.getMessage()));
        document = DocumentHelper.createDocument();
        document.addElement("ROOT");
    } finally {
        closeStream(xmlReader);
        closeStream(stream);
    }
    return document;
}
 
Example 25
Source Project: syndesis   Source File: UnifiedXmlDataShapeGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateArrayFromExamples() throws IOException {
    final Map<String, Oas20Schema> namedPropertyMap = propertyFrom(jsonSchemaSnippet);
    final Map.Entry<String, Oas20Schema> namedProperty = namedPropertyMap.entrySet().iterator().next();

    final String propertyName = namedProperty.getKey();
    final Oas20Schema array = namedProperty.getValue();

    final Document document = DocumentHelper.createDocument();
    final Element parent = document.addElement("xsd:sequence", XmlSchemaHelper.XML_SCHEMA_NS);


    assertThat(UnifiedXmlDataShapeSupport.determineArrayItemName(propertyName, array)).isEqualTo(arrayItemName);
    assertThat(UnifiedXmlDataShapeSupport.determineArrayElementName(propertyName, array)).isEqualTo(arrayElementName);

    UnifiedXmlDataShapeGenerator unifiedXmlDataShapeGenerator = new UnifiedXmlDataShapeGenerator();
    unifiedXmlDataShapeGenerator.defineArrayElement(array, propertyName, parent, NO_OPEN_API_DOC, NO_MORE_SCHEMAS);
    assertThat(XmlSchemaHelper.serialize(document)).isXmlEqualTo(schema(xmlSchemaSnippet));
}
 
Example 26
Source Project: boubei-tss   Source File: XMLDocUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Document dataXml2Doc(String dataXml) {
	if( EasyUtils.isNullOrEmpty(dataXml) ) return null;
	
    if (!dataXml.startsWith("<?xml")) {
    	dataXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + dataXml;
    }
    
    Document doc;
    try {
        doc = DocumentHelper.parseText(dataXml);
    } 
    catch (DocumentException e) {
    	try {
            doc = DocumentHelper.parseText(XmlUtil.stripNonValidXMLCharacters(dataXml));
        } catch (Exception e1) {
        	throw new RuntimeException("由dataXml生成doc出错:", e);
        }
    }
    return doc;
}
 
Example 27
Source Project: cuba   Source File: AbstractViewRepository.java    License: Apache License 2.0 6 votes vote down vote up
protected void init() {
    StopWatch initTiming = new Slf4JStopWatch("ViewRepository.init." + getClass().getSimpleName());

    storage.clear();
    readFileNames.clear();

    String configName = AppContext.getProperty("cuba.viewsConfig");
    if (!StringUtils.isBlank(configName)) {
        Element rootElem = DocumentHelper.createDocument().addElement("views");

        StringTokenizer tokenizer = new StringTokenizer(configName);
        for (String fileName : tokenizer.getTokenArray()) {
            addFile(rootElem, fileName);
        }

        viewLoader.checkDuplicates(rootElem);

        for (Element viewElem : Dom4j.elements(rootElem, "view")) {
            deployView(rootElem, viewElem, new HashSet<>());
        }
    }

    initTiming.stop();
}
 
Example 28
Source Project: Openfire   Source File: VCardTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, all placeholders get correctly identified in a VCardTemplate, when
 * they're defined in the value of the same element that also holds additional, hardcoded values.
 */
@Test
public void testIdentifyEmbeddedPlaceholders() throws Exception
{
    // Setup fixture.
    final Document input = DocumentHelper.parseText("<vcard><el>foo {placeholderA}, {placeholderB} bar</el></vcard>");

    // Execute system under test.
    final LdapVCardProvider.VCardTemplate result = new LdapVCardProvider.VCardTemplate(input);

    // Verify result.
    assertNotNull( result );
    assertNotNull( result.getAttributes() );
    assertEquals( 2, result.getAttributes().length );
    assertTrue( Arrays.asList( result.getAttributes()).contains("placeholderA") );
    assertTrue( Arrays.asList( result.getAttributes()).contains("placeholderB") );
}
 
Example 29
Source Project: Openfire   Source File: VCardTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that, using a simplified template, element values that are not a placeholder do not get replaced, even
 * if the elemnent value contains a separator character used in the implementation to distinguish individual
 * placeholders.
 *
 * @see <a href="https://issues.igniterealtime.org/browse/OF-1947">OF-1947</a>
 */
@Test
public void testIdentifyNonPlaceholderWithSeparatorChar() throws Exception
{
    // Setup fixture.
    final Document doc = DocumentHelper.parseText("<vcard><el>place/holder</el></vcard>");
    final LdapVCardProvider.VCardTemplate template = new LdapVCardProvider.VCardTemplate(doc);
    final Map<String, String> attributes = new HashMap<>();
    attributes.put("place", "value");
    attributes.put("holder", "value");

    // Execute system under test.
    final LdapVCardProvider.VCard vCard = new LdapVCardProvider.VCard(template);
    final Element result = vCard.getVCard(attributes);

    // Verify result.
    assertNotNull( result );
    assertEquals( "<vcard><el>place/holder</el></vcard>", result.asXML() );
}
 
Example 30
/**
 * Verifies that {@link BookmarkInterceptor#findStorageElementInPrivateXmlStorage(Element)} gracefully fails when no XEP-0048 storage element is defined
 * in the input that is otherwise a proper XEP-0049-formatted element.
 */
@Test
public void testFindStorageElementInPrivateXmlStorageNoXEP0048() throws Exception
{
    // Setup fixture.
    final Element element = DocumentHelper.parseText(
        "<query xmlns=\"jabber:iq:private\">\n" +
            "  <exodus xmlns=\"exodus:prefs\">\n" +
            "    <defaultnick>Hamlet</defaultnick>\n" +
            "  </exodus>\n" +
            "</query>" ).getRootElement();

    // Execute system under test.
    final Element result = BookmarkInterceptor.findStorageElementInPrivateXmlStorage( element );

    // Verify results.
    assertNull( result );
}