Java Code Examples for org.dom4j.DocumentException

The following are top voted examples for showing how to use org.dom4j.DocumentException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: phoenix.webui.framework   File: Phoenix.java   Source Code and License 7 votes vote down vote up
/**
 * 从操作系统路径中加载配置文件
 * @param filePath filePath
 * @throws IOException  IOException
 * @throws FileNotFoundException  FileNotFoundException
 * @throws DocumentException  DocumentException
 * @throws SAXException SAXException
 */
public void readFromSystemPath(String filePath) throws FileNotFoundException, 
	IOException, DocumentException, SAXException
{
	configFile = new File(filePath);
	if(!configFile.isFile())
	{
		throw new ConfigException(String.format("Target file [%s] is not a file.", filePath), "");
	}
	else if(!filePath.endsWith(".xml"))
	{
		logger.warn("Target file [%s] is not end with .xml", filePath);
	}
	
	try(InputStream configInput = new FileInputStream(configFile))
	{
		read(configInput);
	}
}
 
Example 2
Project: iBase4J   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 解析XML并将其节点元素压入Dto返回(基于节点值形式的XML格式)
 * 
 * @param pStrXml 待解析的XML字符串
 * @return outDto 返回Dto
 */
public static final Map parseXml2Map(String pStrXml) {
	Map map = new HashMap();
	String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	Document document = null;
	try {
		if (pStrXml.indexOf("<?xml") < 0)
			pStrXml = strTitle + pStrXml;
		document = DocumentHelper.parseText(pStrXml);

	} catch (DocumentException e) {
		log.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
	}
	// 获取根节点
	Element elNode = document.getRootElement();
	// 遍历节点属性值将其压入Dto
	for (Iterator it = elNode.elementIterator(); it.hasNext();) {
		Element leaf = (Element) it.next();
		map.put(leaf.getName().toLowerCase(), leaf.getData());
	}
	return map;
}
 
Example 3
Project: fcrepo3-security-jaas   File: DrupalMultisiteAuthModuleTest.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings({
    "rawtypes", "unchecked"
})
public void testFindUserAuthenticatedUser() throws IOException, DocumentException {
    Map<String, String> users = new HashMap<String, String>();
    users.put("alpha", "first");
    users.put("bravo", "second");
    users.put("charlie", "third");

    for (String key : users.keySet()) {
        mockInstance = new DrupalMultisiteAuthModuleMock();
        Set<String> roles = findRoles(key, users.get(key));
        assertTrue(roles.contains("authenticated user"));
    }
}
 
Example 4
Project: phoenix.webui.framework   File: SettingUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * 测试简单流程,数据在数据源(xml格式)中
 * @throws SAXException 
 * @throws DocumentException 
 * @throws IOException 
 */
@Test
public void dataSource() throws IOException, DocumentException, SAXException
{
	util.readFromClassPath("elements/xml/maimai.xml");
	util.initData();
	
	HomePage homePage = util.getPage(HomePage.class);
	Assert.assertNotNull(homePage);

	Assert.assertNotNull(homePage.getUrl());
	Assert.assertTrue("起始页地址不合法",
			homePage.paramTranslate(homePage.getUrl()).startsWith("http"));
	homePage.open();
	Button toLoginBut = homePage.getToLoginBut();
	Assert.assertNotNull(toLoginBut);
	toLoginBut.click();
	
	LoginPage loginPage = util.getPage(LoginPage.class);
	Assert.assertNotNull(loginPage);
	
	Text phone = loginPage.getPhone();
	Assert.assertNotNull(phone);
	Assert.assertNotNull("数据未从数据源中加载", phone.getValue());
	phone.fillNotBlankValue();
}
 
Example 5
Project: bulbasaur   File: TaskTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testdeployDefinition() {
    // 初始化

    SAXReader reader = new SAXReader();
    // 拿不到信息
    //URL url = this.getClass().getResource("/multipleTask.xml");
    URL url = this.getClass().getResource("/singleTask.xml");
    Document document = null;
    try {
        document = reader.read(url);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String definitionContent = document.asXML();
    // deploy first time
    DefinitionHelper.getInstance().deployDefinition("singleTask", "测试单人任务流程", definitionContent, true);
    //DefinitionHelper.getInstance().deployDefinition("multipleTask", "测试多人任务流程", definitionContent, true);
}
 
Example 6
Project: liteFlow   File: Dom4JReader.java   Source Code and License 6 votes vote down vote up
public static Document getDocument(Reader reader) throws DocumentException, IOException {
    SAXReader saxReader = new SAXReader();

    Document document = null;
    try {
        document = saxReader.read(reader);
    } catch (DocumentException e) {
        throw e;
    } finally {
        if (reader != null) {
            reader.close();
        }
    }

    return document;
}
 
Example 7
Project: iBase4J-Common   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 解析XML并将其节点元素压入Dto返回(基于节点值形式的XML格式)
 * 
 * @param pStrXml 待解析的XML字符串
 * @param pXPath 节点路径(例如:"//paralist/row" 则表示根节点paralist下的row节点的xPath路径)
 * @return outDto 返回Dto
 */
public static final Map parseXml2Map(String pStrXml, String pXPath) {
    Map map = new HashMap();
    String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    Document document = null;
    try {
        if (pStrXml.indexOf("<?xml") < 0) pStrXml = strTitle + pStrXml;
        document = DocumentHelper.parseText(pStrXml);
    } catch (DocumentException e) {
        logger.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
    }
    // 获取根节点
    Element elNode = document.getRootElement();
    // 遍历节点属性值将其压入Dto
    for (Iterator it = elNode.elementIterator(); it.hasNext();) {
        Element leaf = (Element)it.next();
        map.put(leaf.getName().toLowerCase(), leaf.getData());
    }
    return map;
}
 
Example 8
Project: JAVA-   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 解析XML并将其节点元素压入Dto返回(基于节点值形式的XML格式)
 * 
 * @param pStrXml 待解析的XML字符串
 * @return outDto 返回Dto
 */
public static final Map parseXml2Map(String pStrXml) {
	Map map = new HashMap();
	String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	Document document = null;
	try {
		if (pStrXml.indexOf("<?xml") < 0)
			pStrXml = strTitle + pStrXml;
		document = DocumentHelper.parseText(pStrXml);

	} catch (DocumentException e) {
		log.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
	}
	// 获取根节点
	Element elNode = document.getRootElement();
	// 遍历节点属性值将其压入Dto
	for (Iterator it = elNode.elementIterator(); it.hasNext();) {
		Element leaf = (Element) it.next();
		map.put(leaf.getName().toLowerCase(), leaf.getData());
	}
	return map;
}
 
Example 9
Project: alfresco-repository   File: QueryRegisterComponentImpl.java   Source Code and License 6 votes vote down vote up
public void loadQueryCollection(String location)
{
    try
    {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(location);
        SAXReader reader = new SAXReader();
        Document document = reader.read(is);
        is.close();
        QueryCollection collection = QueryCollectionImpl.createQueryCollection(document.getRootElement(), dictionaryService, namespaceService);
        collections.put(location, collection);
    }
    catch (DocumentException de)
    {
        throw new AlfrescoRuntimeException("Error reading XML", de);
    }
    catch (IOException e)
    {
        throw new AlfrescoRuntimeException("IO Error reading XML", e);
    }
}
 
Example 10
Project: bulbasaur   File: PersistDefinationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testdeployDefinition() {
    // 初始化

    SAXReader reader = new SAXReader();
    // 拿不到信息
    URL url = this.getClass().getResource("/process12.xml");
    Document document = null;
    try {
        document = reader.read(url);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String definitionContent = document.asXML();
    // deploy first time
    DefinitionHelper.getInstance().deployDefinition("process", "测试流程", definitionContent, true);
}
 
Example 11
Project: xpath-to-xml   File: XmlBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldNotModifyDocumentWhenAllXPathsTraversable()
        throws XPathExpressionException, DocumentException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    String xml = fixtureAccessor.getPutValueXml();
    Document oldDocument = stringToXml(xml);
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties)
            .build(oldDocument);

    assertThat(xmlToString(builtDocument)).isEqualTo(xml);

    builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties.keySet())
            .build(oldDocument);

    assertThat(xmlToString(builtDocument)).isEqualTo(xml);
}
 
Example 12
Project: joai-project   File: DCSServiceTester.java   Source Code and License 6 votes vote down vote up
/**
 *  Perform GetId by directly issuing request URL
 *
 *@param  collection  Description of the Parameter
 */
private void getIdDirect(String collection) {
	String qs = "verb=" + verb;
	qs += "&collection=" + collection;
	URL url;
	Document doc;
	try {
		url = new URL(baseUrl + "?" + qs);
		doc = Dom4jUtils.getXmlDocument(url);
	} catch (MalformedURLException mue) {
		prtln("URL error: " + mue.getCause());
		return;
	} catch (org.dom4j.DocumentException de) {
		prtln(de.getMessage());
		return;
	}

	prtln(Dom4jUtils.prettyPrint(doc));
}
 
Example 13
Project: atlas   File: BundleInfoUtils.java   Source Code and License 6 votes vote down vote up
public static void setupAwbBundleInfos(AppVariantContext appVariantContext) throws IOException, DocumentException {

        String apkVersion = appVariantContext.getVariantConfiguration().getVersionName();

        AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees.get(
            appVariantContext.getScope().
                getVariantConfiguration().getFullName());

        /**
         * name Is artifictId
         */
        Map<String, BundleInfo> bundleInfoMap = getBundleInfoMap(appVariantContext);

        String baseVersion = apkVersion;

        if (null != appVariantContext.apContext && null != appVariantContext.apContext.getBaseManifest() && appVariantContext.apContext.getBaseManifest().exists()){
            baseVersion = ManifestFileUtils.getVersionName(appVariantContext.apContext.getBaseManifest());
        }

        for (AwbBundle awbBundle : atlasDependencyTree.getAwbBundles()) {
            update(awbBundle, bundleInfoMap, appVariantContext, apkVersion, baseVersion);
        }
    }
 
Example 14
Project: liteFlow   File: Dom4JReader.java   Source Code and License 6 votes vote down vote up
public static Document getDocument(InputStream inputStream) throws DocumentException, IOException {
    SAXReader saxReader = new SAXReader();

    Document document = null;
    try {
        document = saxReader.read(inputStream);
    } catch (DocumentException e) {
        throw e;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }

    return document;
}
 
Example 15
Project: parabuild-ci   File: CheckMessages.java   Source Code and License 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
	if (argv.length < 2) {
		System.err.println("Usage: " + CheckMessages.class.getName() +
			" <plugin descriptor xml> <bug description xml> [<bug description xml>...]");
		System.exit(1);
	}

	String pluginDescriptor = argv[0];

	try {
		CheckMessages checkMessages = new CheckMessages(pluginDescriptor);
		for (int i = 1; i < argv.length; ++i) {
			String messagesFile = argv[i];
			System.out.println("Checking messages file " + messagesFile);
			checkMessages.checkMessages(new XMLFile(messagesFile));
		}
	} catch (DocumentException e) {
		System.err.println("Could not verify messages files: " + e.getMessage());
		System.exit(1);
	}

	System.out.println("Messages files look OK!");
}
 
Example 16
Project: atlas   File: ManifestFileUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Get the packageId for the manifest file
 *
 * @param manifestFile
 * @return
 */
public static String getApplicationId(File manifestFile) {
    SAXReader reader = new SAXReader();
    if (manifestFile.exists()) {
        Document document = null;// Read the XML file
        try {
            document = reader.read(manifestFile);
            Element root = document.getRootElement();// Get the root node
            String packageName = root.attributeValue("package");
            return packageName;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 17
Project: atlas   File: ManifestFileUtils.java   Source Code and License 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 18
Project: atlas   File: ManifestFileUtils.java   Source Code and License 6 votes vote down vote up
public static String getVersionCode(File androidManifestFile) throws IOException, DocumentException {
    SAXReader reader = new SAXReader();
    String versionCode = "";
    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(), "versionCode")) {
                    versionCode = attr.getValue();
                }
            }
        }
    }
    return versionCode;
}
 
Example 19
Project: jwx   File: InMessageFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 生成请求消息
 * @param xmlText
 * @return
 * @throws DocumentException
 * @throws WeixinInMsgHandleException 
 */
public InMessage creator(String xmlText) throws DocumentException, WeixinInMsgHandleException{
	// 获取xml文本document对象
	Document document = DocumentHelper.parseText(xmlText);
	// 得到 xml 根元素
	Element root = document.getRootElement();
	String msgType = root.element("MsgType").getTextTrim();
	
	InMessage in = null;
	
	if(REQUEST_EVENT_MESSAGE_TYPE.equals(msgType)){
		in = creatEventMsg(root);
	} else {
		in = creatPlainMsg(root, msgType);
	}
	
	if(in == null){
		throw new WeixinInMsgHandleException("无法识别的消息请求类型");
	}
	
	return in;
}
 
Example 20
Project: phoenix.webui.suite.runner   File: SuiteUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 判断是否为suite的xml配置
 * @param content
 * @return
 */
public static boolean isSuiteXml(byte[] content)
{
	SAXReader reader = new SAXReader();
	try
	{
		Document doc = reader.read(new ByteArrayInputStream(content));
		Element rootEle = doc.getRootElement();
		
		String rootEleName = rootEle.getName();
		
		return "suite".equals(rootEleName);
	}
	catch (DocumentException e)
	{
		e.printStackTrace();
	}
	
	return false;
}
 
Example 21
Project: PackagePlugin   File: FileUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 摸查项目输出目录
 * <p>
 * @param projectPath
 * @param kind        output 或 src
 * @return
 */
public static String readXML(String projectPath, String kind) {
    try {
        SAXReader saxReader = new SAXReader();
        File classpath = new File(projectPath + "/.classpath");
        if (classpath.exists()) {
            Document document = saxReader.read(classpath);
            List<Element> out = (List<Element>) document.selectNodes("/classpath/classpathentry[@kind='" + kind + "']");
            String tmp = "";
            for (Element out1 : out) {
                String combineaccessrules = out1.attributeValue("combineaccessrules");
                if ("false".equals(combineaccessrules) && "src".equals(kind)) {
                    continue;
                }
                tmp += out1.attributeValue("path") + ",";
            }
            return tmp.isEmpty() ? tmp : tmp.substring(0, tmp.length() - 1);
        }
    } catch (DocumentException ex) {
        MainFrame.LOGGER.log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, ex.getLocalizedMessage());
    }
    return "";
}
 
Example 22
Project: unitimes   File: DoubleVarcharSizes.java   Source Code and License 5 votes vote down vote up
public void generate() throws IOException, DocumentException {
	Document document = read(iConfig);
	Element root = document.getRootElement();
	Element sessionFactoryElement = root.element("session-factory");
	for (Iterator<Element> i = sessionFactoryElement.elementIterator("mapping"); i.hasNext(); ) {
		Element m = i.next();
		String resource = m.attributeValue("resource");
		if (resource == null) continue;
		generate(read(resource).getRootElement(), null);
	}
}
 
Example 23
Project: GraphicsViewJambi   File: ImportSumoNetwork.java   Source Code and License 5 votes vote down vote up
/**
 * Read all Node in the XML File
 * 
 * @param node
 * 		Node to Manage
 */
@SuppressWarnings("unchecked")
public void listNodes(final Element node) throws DocumentException
{
	manageAttributeInfo(node, false);
	
	//start next node if has
	final Iterator<Element> it = node.elementIterator();
	while (it.hasNext())
	{
		final Element e = it.next();
		listNodes(e);
	}
}
 
Example 24
Project: parabuild-ci   File: CheckMessages.java   Source Code and License 5 votes vote down vote up
public XMLFile(String filename) throws DocumentException, MalformedURLException {
	this.filename = filename;

	File file = new File(filename);
	SAXReader saxReader = new SAXReader();
	this.document = saxReader.read(file);
}
 
Example 25
Project: phoenix.webui.framework   File: XmlDataSource.java   Source Code and License 5 votes vote down vote up
/**
 * 解析xml文档
 * @param inputStream
 * @param row 
 * @throws DocumentException 
 */
private void parse(InputStream inputStream, int row) throws DocumentException
{
	Document document = new SAXReader().read(inputStream);

	parse(document, row);
}
 
Example 26
Project: banana   File: MessageUtil.java   Source Code and License 5 votes vote down vote up
public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
    Map<String, String> rtnMap = new HashMap<>();

    SAXReader reader = new SAXReader();

    try (ServletInputStream in = request.getInputStream()) {
        Document root = reader.read(in);
        Element rootElement = root.getRootElement();

        List<Element> elements = rootElement.elements();
        elements.forEach(e -> rtnMap.put(e.getName(), e.getText()));
    }

    return rtnMap;
}
 
Example 27
Project: minlia-iot-xapi   File: SignUtils.java   Source Code and License 5 votes vote down vote up
public static Element readerXml(String body,String encode) throws DocumentException {
    SAXReader reader = new SAXReader(false);
    InputSource source = new InputSource(new StringReader(body));
    source.setEncoding(encode);
    Document doc = reader.read(source);
    Element element = doc.getRootElement();
    return element;
}
 
Example 28
Project: unitimes   File: XmlApiHelper.java   Source Code and License 5 votes vote down vote up
@Override
public Document getRequest(Type requestType) throws IOException {
	Reader reader = iRequest.getReader();
	try {
		return new SAXReader().read(reader);
	} catch (DocumentException e) {
		throw new IOException(e.getMessage(), e);
	} finally {
		reader.close();
	}
}
 
Example 29
Project: unitimes   File: LowercaseTableNames.java   Source Code and License 5 votes vote down vote up
protected Document read(String resource) throws IOException, DocumentException {
	if (iSource == null) {
		info("  -- reading " + resource + " ...");
		return iSAXReader.read(getClass().getClassLoader().getResourceAsStream(resource));
	} else {
		info("  -- reading " + iSource + File.separator + resource + " ...");
		return iSAXReader.read(new File(iSource + File.separator + resource));
	}
}
 
Example 30
Project: sbc-qsystem   File: Executer.java   Source Code and License 5 votes vote down vote up
@Override
synchronized public AJsonRPC20 process(CmdParams cmdParams, String ipAdress, byte[] IP) {
    QLog.l().logQUser().debug("saveBoardConfig");
    super.process(cmdParams, ipAdress, IP);
    try {
        MainBoard.getInstance()
            .saveConfig(DocumentHelper.parseText(cmdParams.textData).getRootElement());
    } catch (DocumentException ex) {
        QLog.l().logger().error("Не сохранилась конфигурация табло.", ex);
    }
    return new JsonRPC20OK();
}
 
Example 31
Project: iBase4J-Common   File: XmlUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 将XML规范的字符串转为List对象(XML基于节点属性值的方式)
 * 
 * @param pStrXml 传入的符合XML格式规范的字符串
 * @return list 返回List对象
 */
public static final List parseXml2List(String pStrXml) {
    List lst = new ArrayList();
    String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    Document document = null;
    try {
        if (pStrXml.indexOf("<?xml") < 0) pStrXml = strTitle + pStrXml;
        document = DocumentHelper.parseText(pStrXml);
    } catch (DocumentException e) {
        logger.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
    }
    // 获取到根节点
    Element elRoot = document.getRootElement();
    // 获取根节点的所有子节点元素
    Iterator elIt = elRoot.elementIterator();
    while (elIt.hasNext()) {
        Element el = (Element)elIt.next();
        Iterator attrIt = el.attributeIterator();
        Map map = new HashMap();
        while (attrIt.hasNext()) {
            Attribute attribute = (Attribute)attrIt.next();
            map.put(attribute.getName().toLowerCase(), attribute.getData());
        }
        lst.add(map);
    }
    return lst;
}
 
Example 32
Project: parabuild-ci   File: PluginLoader.java   Source Code and License 5 votes vote down vote up
private void addCollection(List<Document> messageCollectionList, String filename)
        throws DocumentException {
	URL messageURL = findResource(filename);
	if (messageURL != null) {
		SAXReader reader = new SAXReader();
		Document messageCollection = reader.read(messageURL);
		messageCollectionList.add(messageCollection);
	}
}
 
Example 33
Project: aliyun-maxcompute-data-collectors   File: DatahubHandlerTest.java   Source Code and License 5 votes vote down vote up
@BeforeMethod
public void reInit() throws DocumentException {
    configure = ConfigureReader.reader("src/test/resources/configure.xml");

    datahubHandler.setConfigure(configure);

    DataHubWriter.reInit(configure);
}
 
Example 34
Project: sucok-framework   File: XMLParse.java   Source Code and License 5 votes vote down vote up
public static Map<String, Object> xml2Map(String xml){
  	  SAXReader saxReader = new SAXReader();
        Document doc;
try {
	doc = saxReader.read(new StringReader(xml));
	 return document2Map(doc);
} catch (DocumentException e) {
	e.printStackTrace();
	return null;
}
       
  }
 
Example 35
Project: bulbasaur   File: PersistParserTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testMachineRunWithPersistParser() {

    SAXReader reader = new SAXReader();
    // 拿不到信息
    URL url = this.getClass().getResource("/persist_definition.xml");
    Document document = null;
    try {
        document = reader.read(url);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String definitionContent = document.asXML();
    int definitionVersion = DefinitionHelper.getInstance().deployDefinition("persist_definition","测试", definitionContent,
        true).getDefinitionVersion();

    PersistMachine p = persistMachineFactory.newInstance(String.valueOf(System.currentTimeMillis()),
        "persist_definition");
    Assert.assertEquals(definitionVersion, p.getProcessVersion());
    Map m = new HashMap();
    m.put("goto", 2);
    m.put("_i", 3);
    p.addContext(m);
    p.run();
    Assert.assertEquals(6, p.getContext("_a"));
}
 
Example 36
Project: bulbasaur   File: PersistParserTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPersistParser() {

    // deploy 2 version of definition first

    SAXReader reader = new SAXReader();
    // 拿不到信息
    URL url = this.getClass().getResource("/persist_definition.xml");
    Document document = null;
    try {
        document = reader.read(url);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String definitionContent = document.asXML();

    DefinitionHelper.getInstance().deployDefinition("persist_definition", "测试", definitionContent, true);
    DefinitionHelper.getInstance().deployDefinition("persist_definition", "测试", definitionContent, true);

    Definition definition = persistParser.parse("persist_definition", 0);
    Assert.assertEquals("persist_definition", definition.getName());
    Assert.assertEquals(2, definition.getVersion());
    Assert.assertNotNull(definition.getState("i'm start"));
    Definition definition1 = persistParser.parse("persist_definition", 1);
    Assert.assertEquals(1, definition1.getVersion());
}
 
Example 37
Project: sbc-qsystem   File: FClient.java   Source Code and License 5 votes vote down vote up
private static void initIndicatorBoardFX(String cfgFile) throws DocumentException {
    File f = new File(cfgFile);
    if (!clientboardFX && f.exists()) {
        // todo
        //todo    board.showBoard(f);
        clientboardFX = true;
    }
}
 
Example 38
Project: automat   File: XmlUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 将XML规范的字符串转为List对象(XML基于节点属性值的方式)
 * 
 * @param pStrXml 传入的符合XML格式规范的字符串
 * @return list 返回List对象
 */
public static final List parseXml2List(String pStrXml) {
	List lst = new ArrayList();
	String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	Document document = null;
	try {
		if (pStrXml.indexOf("<?xml") < 0)
			pStrXml = strTitle + pStrXml;
		document = DocumentHelper.parseText(pStrXml);
	} catch (DocumentException e) {
		log.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
	}
	// 获取到根节点
	Element elRoot = document.getRootElement();
	// 获取根节点的所有子节点元素
	Iterator elIt = elRoot.elementIterator();
	while (elIt.hasNext()) {
		Element el = (Element) elIt.next();
		Iterator attrIt = el.attributeIterator();
		Map map = new HashMap();
		while (attrIt.hasNext()) {
			Attribute attribute = (Attribute) attrIt.next();
			map.put(attribute.getName().toLowerCase(), attribute.getData());
		}
		lst.add(map);
	}
	return lst;
}
 
Example 39
Project: push-server   File: XMLBeanFactory.java   Source Code and License 5 votes vote down vote up
/**
 * 构造方法.
 * @param xmlName xmlName.
 */
public XMLBeanFactory(String xmlName) { // 在构造方法中
    try {
        this.xmlName = xmlName;
        reader = new SAXReader();
        document = reader.read(this.getClass().getClassLoader().getResourceAsStream(xmlName));
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}
 
Example 40
Project: ats-framework   File: XmlText.java   Source Code and License 5 votes vote down vote up
private void init(
                   String xmlText ) throws XMLException {

    Document document = null;
    try {
        document = new SAXReader().read(new StringReader(xmlText));
    } catch (DocumentException e) {
        throw new XMLException("Error parsing XML text:\n" + xmlText, e);
    }

    this.root = document.getRootElement();
}
 
Example 41
Project: parabuild-ci   File: CheckMessages.java   Source Code and License 5 votes vote down vote up
public void checkDescribed(String description, XMLFile xmlFile,
	Set<String> declared, Set<String> described) throws DocumentException {

	Set<String> notDescribed = new HashSet<String>();
	notDescribed.addAll(declared);
	notDescribed.removeAll(described);

	if (!notDescribed.isEmpty())
		throw new CheckMessagesException(description + ": " + notDescribed.toString(), xmlFile);
}
 
Example 42
Project: SimpleController   File: XMLManager.java   Source Code and License 5 votes vote down vote up
private Element readXML(String path){
	SAXReader reader=new SAXReader();
       Document document= null;
       try {
           document = reader.read(path);
       } catch (DocumentException e) {
           e.printStackTrace();
       }
       Element root=document.getRootElement();
       return root;
}
 
Example 43
Project: joai-project   File: Dom4jUtils.java   Source Code and License 5 votes vote down vote up
/**
 *  Load XML into a dom4j Document. If error, return null. No validation is performed.
 *
 * @param  s                      A string representation of an XML document
 * @return                        An XML Document containing the dom4j DOM, or null if unable to process the
 *      string.
 * @exception  DocumentException  If dom4j error
 */
public static Document getXmlDocument(String s)
	 throws DocumentException {
	// No validation...
	SAXReader reader = new SAXReader(false);
	StringReader sr = new StringReader(s);
	Document document = reader.read(sr);
	sr.close();
	return document;
}
 
Example 44
Project: joai-project   File: Dom4jUtils.java   Source Code and License 5 votes vote down vote up
/**
 *  Load XML into a dom4j Document and localize the XML by removing all namespaces from it. If error, return
 *  null. No validation is performed.
 *
 * @param  xml                    A string representation of an XML document
 * @return                        An XML Document containing the localized dom4j DOM, or null if unable to
 *      process the string.
 * @exception  DocumentException  If dom4j error
 */
public static Document getXmlDocumentLocalized(String xml)
	 throws DocumentException {
	// No validation...
	SAXReader reader = new SAXReader(false);
	StringReader sr = new StringReader(localizeXml(xml));
	Document document = reader.read(sr);
	sr.close();
	return document;
}
 
Example 45
Project: joai-project   File: MetaDataFramework.java   Source Code and License 5 votes vote down vote up
/**
 *  Converts an editable Document into a writable xmlRecord (string) via {@link
 *  #getWritableRecordXml(Document) getWritableRecordXml} and writes it to
 *  disk.
 *
 * @param  doc                    an editable Document
 * @param  file                   destination file for write operation.
 * @exception  DocumentException  Description of the Exception
 */
public void writeEditableDocument(Document doc, File file)
	 throws DocumentException {
	String xmlRecord = getWritableRecordXml(doc);
	try {
		Files.writeFile(xmlRecord, file);
	} catch (IOException ioe) {
		throw new DocumentException("Could not write document to file: " + ioe.getMessage());
	}
}
 
Example 46
Project: SimpleController   File: TestLogWriter.java   Source Code and License 5 votes vote down vote up
@Test
public void testLogWriter() throws IOException, DocumentException{
	ActionLog actionLog=new ActionLog();
	actionLog.setName("login");
	Date startTime=new Date();//get current time
	actionLog.setStartTime(startTime);
	Date endTime=new Date();
	actionLog.setEndTime(endTime);
	actionLog.setResult("success");
	String path="src/log.xml";
	LogWriter logWriter=new LogWriter();
	logWriter.log(actionLog);
}
 
Example 47
Project: SimpleController   File: LogWriter.java   Source Code and License 5 votes vote down vote up
private Document readDocument(String path, ActionLog actionLog) throws DocumentException{
	SAXReader reader=new SAXReader();
	Document logDocument=reader.read(path);
	Element log=logDocument.getRootElement();
	Element action=log.addElement("action");
	action.addElement("name").addText(actionLog.getName());
	action.addElement("s-time").addText(actionLog.getStartTime().toString());
	action.addElement("e-time").addText(actionLog.getEndTime().toString());
	action.addElement("result").addText(actionLog.getResult());
	System.out.println("Write "+log.getName());
       System.out.println(path);
       return logDocument;
}
 
Example 48
Project: de.flapdoodle.solid   File: XmlParserTest.java   Source Code and License 5 votes vote down vote up
@Test
public void sampleWordpressVisitor() throws DocumentException, IOException {
	try (Reader reader = new InputStreamReader(Resources.asByteSource(Resources.getResource(getClass(), "wordpress-sample-rss.xml")).openBufferedStream())) {
		XmlParser.of(reader)
			.collect(v -> {
				System.out.println("visitor: "+v.current());
				v.visit(v2 -> {
					System.out.println("sub: "+v2.current());
				});
				return "Foo";
			});
	}
}
 
Example 49
Project: atlas   File: ManifestFileUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Remove comments from XML
 *
 * @param document
 * @throws IOException
 * @throws DocumentException
 */
private static void removeComments(Document document) throws IOException, DocumentException {
    Visitor visitor = new VisitorSupport() {

        @Override
        public void visit(Comment comment) {
            comment.setText(" ");
        }
    };
    document.accept(visitor);
}
 
Example 50
Project: minlia-iot   File: XmlSignatureAnnotationHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 预检验签名
 *
 * @param xml xml字符串
 * @param salt partnerApiKey
 * @param clazz 类型
 * @return 是否通过验证
 */
@SuppressWarnings("unchecked")
public static boolean prepareCheckSign(String xml, String salt, Boolean excludeSaltParameter,
    Class<?> clazz,
    SignatureAlgorithmic algorithmic, String saltParameterPrefix, String charset,
    CaseControl caseControl, String delimiter) {
  Field signField = signField(clazz);
  XmlElement xmlElementAnnotation = signField.getAnnotation(XmlElement.class);
  try {
    Document document = DocumentHelper.parseText(xml);
    Element rootElement = document.getRootElement();
    List<FieldPaired> fieldPaireds = new LinkedList<>();
    String targetSign = null;
    for (Iterator<Element> iterator = rootElement.elementIterator(); iterator.hasNext(); ) {
      Element element = iterator.next();
      if (element.getName().equals(xmlElementAnnotation.name())) {
        targetSign = element.getTextTrim();
      } else {
        String text = element.getTextTrim();
        if (StringUtils.isNotBlank(text)) {
          fieldPaireds.add(new FieldPaired(element.getName(), text));
        }
      }
    }
    if (StringUtils.isBlank(targetSign)) {
      log.warn("Sign shoud not be empty.");
    }
    String signStr = "";

    signStr = makeSignBySinpleFieldList(fieldPaireds, salt, excludeSaltParameter, algorithmic,
        saltParameterPrefix, charset, caseControl, delimiter);
    return signStr.equals(targetSign);
  } catch (DocumentException e) {
    e.printStackTrace();
    return false;
  }
}
 
Example 51
Project: de.flapdoodle.solid   File: WordpressRssConverter.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException, DocumentException {
	System.out.println("solid wordpress converter");
	Preconditions.checkArgument(args.length>=2,"usage: <rss-xml> <exportDirectory>");
	
	Path rssXml = Paths.get(args[0]);
	Path target = Paths.get(args[1]);
	
	try (Reader reader = new InputStreamReader(Files.newInputStream(rssXml, StandardOpenOption.READ))) {
		WordpressRss wordpressRss = WordpressRssConverter.build(XmlParser.of(reader));
		ImmutableList<Document> documents = WordpressRss2Solid.convert(wordpressRss);
		ImmutableSet<String> allPaths = documents.stream()
			.map(Document::path)
			.collect(ImmutableSet.toImmutableSet());
		Preconditions.checkArgument(allPaths.size()==documents.size(),"path collisions");
		
		// create directory for page and post
		createDirectoryIfNotExist(target.resolve("post"));
		createDirectoryIfNotExist(target.resolve("page"));
		
		documents.forEach((Document d) -> {
			Path filePath = target.resolve(d.path());
			Try.runable(() -> {
				Files.write(filePath, asBytes(d.content()), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
			})
			.mapCheckedException(RuntimeException::new)
			.run();
		});
	}
}
 
Example 52
Project: parabuild-ci   File: EclipseClasspath.java   Source Code and License 5 votes vote down vote up
public Plugin(String directory, boolean isDependent)
		throws DocumentException, EclipseClasspathException, IOException {
	this.directory = directory;
	this.isDependent = isDependent;
	this.requiredPluginIdList = new LinkedList<String>();
	this.exportedLibraryList = new LinkedList<String>();

	// Figure out whether this is an old-style (Eclipse 2.1.x)
	// or new-style (3.0, OSGI-based) plugin.

	boolean oldStyle = false;

	Document document = null;
	File pluginDescriptorFile = new File(directory + File.separator + "plugin.xml");
	if (pluginDescriptorFile.isFile()) {
		SAXReader reader = new SAXReader();
		document = reader.read(new EclipseXMLReader(new FileReader(pluginDescriptorFile)));

		Node plugin = document.selectSingleNode("/plugin");
		if (plugin == null)
			throw new EclipseClasspathException("No plugin node in plugin descriptor");

		oldStyle = !plugin.valueOf("@id").equals("");
	}

	// Get the plugin id

	if (oldStyle) {
		parseOldPluginDescriptor(directory, document, isDependent);
	} else {
		parseNewPluginDescriptor(directory, isDependent);
	}
}
 
Example 53
Project: urule   File: XmlServletHandler.java   Source Code and License 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 54
Project: urule   File: CommonServletHandler.java   Source Code and License 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 55
Project: urule   File: AbstractBuilder.java   Source Code and License 5 votes vote down vote up
protected Element parseResource(String content){
	try {
		Document document = DocumentHelper.parseText(content);
		Element root=document.getRootElement();
		return root;
	} catch (DocumentException e) {
		throw new RuleException(e);
	}
}
 
Example 56
Project: FH-Manager   File: ConfigurationWrapper.java   Source Code and License 5 votes vote down vote up
private ConfigurationWrapper() {

        try {
            File configFile = getConfigFile();
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(configFile);
            rootElement = document.getRootElement();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
 
Example 57
Project: parabuild-ci   File: CheckMessages.java   Source Code and License 5 votes vote down vote up
/**
 * Build collection of the values of given attribute
 * in all nodes matching given XPath expression.
 */
public Set<String> collectAttributes(String xpath, String attrName)
	throws DocumentException {
	HashSet<String> result = new HashSet<String>();

	for (Iterator i = xpathIterator(xpath); i.hasNext(); ) {
		Node node = (Node) i.next();
		String value = checkAttribute(node, attrName).getValue();
		result.add(value);
	}

	return result;
}
 
Example 58
Project: testing_platform   File: Tools.java   Source Code and License 5 votes vote down vote up
public static String getCsvDataXPath(String jmxPath) throws MalformedURLException, DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(new File(jmxPath));
    Element root = document.getRootElement();

    try{
        read(root);
    }catch (Exception e){
        e.printStackTrace();
    }
    return targetPath;
}
 
Example 59
Project: aaden-pay   File: XmlUtils.java   Source Code and License 5 votes vote down vote up
public static Document getDocument(String path) throws DocumentException {
	Document document = null;
	SAXReader reader = new SAXReader();
	File file = new File(path);
	if (file.exists()) {
		document = reader.read(file);
	}
	return document;
}
 
Example 60
Project: lams   File: Dom4JDriver.java   Source Code and License 5 votes vote down vote up
@Override
public HierarchicalStreamReader createReader(final InputStream in) {
    try {
        final SAXReader reader = new SAXReader();
        final Document document = reader.read(in);
        return new Dom4JReader(document, getNameCoder());
    } catch (final DocumentException e) {
        throw new StreamException(e);
    }
}