org.dom4j.DocumentHelper Java Examples

The following examples show how to use org.dom4j.DocumentHelper. 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: RemoteArticleService.java    From boubei-tss with 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 #2
Source File: VCardTest.java    From Openfire with 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 #3
Source File: OpenWxController.java    From jeewx-boot with 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 #4
Source File: PubSubEngine.java    From Openfire with 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 #5
Source File: VCardTemplateTest.java    From Openfire with 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 #6
Source File: ResourceUtil.java    From das with 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 #7
Source File: BookmarkInterceptorTest.java    From openfire-ofmeet-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
}
 
Example #8
Source File: BookmarkInterceptorTest.java    From openfire-ofmeet-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that {@link BookmarkInterceptor#findStorageElementInPubsub(Element)} gracefully fails when no XEP-0048 storage element is defined
 * in the input that is otherwise a proper pubsub element.
 */
@Test
public void testFindStorageElementInPubsubNoXEP0048() throws Exception
{
    // Setup fixture.
    final Element element = DocumentHelper.parseText(
        "  <event xmlns='http://jabber.org/protocol/pubsub#event'>\n" +
            "    <items node='http://jabber.org/protocol/tune'>\n" +
            "      <item>\n" +
            "        <tune xmlns='http://jabber.org/protocol/tune'>\n" +
            "          <artist>Gerald Finzi</artist>\n" +
            "          <length>255</length>\n" +
            "          <source>Music for \"Love's Labors Lost\" (Suite for small orchestra)</source>\n" +
            "          <title>Introduction (Allegro vigoroso)</title>\n" +
            "          <track>1</track>\n" +
            "        </tune>\n" +
            "      </item>\n" +
            "    </items>\n" +
            "  </event>" ).getRootElement();

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

    // Verify results.
    assertNull( result );
}
 
Example #9
Source File: BookmarkInterceptorTest.java    From openfire-ofmeet-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that {@link BookmarkInterceptor#findStorageElementInPubsub(Element)} finds a storage element in a proper Pubsub item retrieval element.
 */
@Test
public void testFindStorageElementInPubsubHappyFlowItemRetrieval() throws Exception
{
    // Setup fixture.
    final Element element = DocumentHelper.parseText(
        "  <pubsub xmlns='http://jabber.org/protocol/pubsub'>\n" +
            "    <items node='storage:bookmarks'>\n" +
            "      <item id='current'>\n" +
            "        <storage xmlns='storage:bookmarks'>\n" +
            "          <conference name='The Play&apos;s the Thing'\n" +
            "                      autojoin='true'\n" +
            "                      jid='[email protected]'>\n" +
            "            <nick>JC</nick>\n" +
            "          </conference>\n" +
            "        </storage>\n" +
            "      </item>\n" +
            "    </items>\n" +
            "  </pubsub>" ).getRootElement();

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

    // Verify results.
    assertNotNull( result );
}
 
Example #10
Source File: VCardTemplateTest.java    From Openfire with 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 #11
Source File: VCardTest.java    From Openfire with 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 #12
Source File: FavoritesMenu.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public void storeAsUserPref()
{
  if (CollectionUtils.isEmpty(menuEntries) == true) {
    UserPreferencesHelper.putEntry(USER_PREF_FAVORITES_MENU_ENTRIES_KEY, "", true);
    UserPreferencesHelper.removeEntry(USER_PREF_FAVORITES_MENU_KEY);
    return;
  }
  final Document document = DocumentHelper.createDocument();
  final Element root = document.addElement("root");
  for (final MenuEntry menuEntry : menuEntries) {
    buildElement(root.addElement("item"), menuEntry);
  }
  final String xml = document.asXML();
  if (xml.length() > UserXmlPreferencesDO.MAX_SERIALIZED_LENGTH) {
    throw new UserException("menu.favorite.maxSizeExceeded");
  }
  UserPreferencesHelper.putEntry(USER_PREF_FAVORITES_MENU_ENTRIES_KEY, xml, true);
  UserPreferencesHelper.putEntry(USER_PREF_FAVORITES_MENU_KEY, this, false);
  if (log.isDebugEnabled() == true) {
    log.debug("Favorites menu stored: " + xml);
  }
  log.info("Favorites menu stored: " + xml);
}
 
Example #13
Source File: XmlMapper.java    From frpMgr with 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 #14
Source File: XMLDocUtil.java    From boubei-tss with 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 #15
Source File: UnifiedXmlDataShapeGeneratorTest.java    From syndesis with 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 #16
Source File: XmlUtils.java    From nbp with 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 #17
Source File: VCardTest.java    From Openfire with 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 #18
Source File: WeixinInMsgParser.java    From seed with 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 #19
Source File: TimetableXMLSaver.java    From cpsolver with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #20
Source File: VCardTest.java    From Openfire with 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 #21
Source File: EnhanceBaseBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #22
Source File: Dom4JParser.java    From tutorials with 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 #23
Source File: WxCommonUtil.java    From roncoo-pay with 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 #24
Source File: AbstractXMLRequestCreatorBaseTest.java    From powermock-examples-maven with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #25
Source File: OpenwxController.java    From jeewx with 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 #26
Source File: VCardTest.java    From Openfire with 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 #27
Source File: VCardTest.java    From Openfire with 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 #28
Source File: FrameServletHandler.java    From urule with 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 #29
Source File: XmlStreamTest.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
@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 #30
Source File: VCardTemplateTest.java    From Openfire with 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] );
}