org.dom4j.DocumentException Java Examples

The following examples show how to use org.dom4j.DocumentException. 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: SelectTagTests.java    From spring-analysis-note with MIT License 8 votes vote down vote up
private void assertStringArray() throws JspException, DocumentException {
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();
	assertTrue(output.startsWith("<select "));
	assertTrue(output.endsWith("</select>"));

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();
	assertEquals("select", rootElement.getName());
	assertEquals("name", rootElement.attribute("name").getValue());

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

	Element e = (Element) rootElement.selectSingleNode("option[text() = 'Rob']");
	assertEquals("Rob node not selected", "selected", e.attribute("selected").getValue());
}
 
Example #2
Source File: OFDDoc.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
/**
 * 修改一个OFD文档
 *
 * @param reader  OFD解析器
 * @param outPath 修改后文档生成位置
 */
public OFDDoc(OFDReader reader, Path outPath) throws DocReadException {
    if (reader == null) {
        throw new IllegalArgumentException("OFD解析器(reader)不能为空");
    }
    if (outPath == null) {
        throw new IllegalArgumentException("OFD文件存储路径(outPath)为空");
    }
    if (Files.isDirectory(outPath)) {
        throw new IllegalArgumentException("OFD文件存储路径(outPath)不能是目录");
    }
    this.outPath = outPath;
    this.reader = reader;
    // 通过OFD解析器初始化文档对象
    try {
        containerInit(reader);
    } catch (FileNotFoundException | DocumentException e) {
        throw new DocReadException("OFD文件解析异常", e);
    }
}
 
Example #3
Source File: TestTool.java    From iaf with Apache License 2.0 6 votes vote down vote up
public static void windiff(ServletContext application, HttpServletRequest request, String expectedFileName, String result, String expected) throws IOException, DocumentException, SenderException {
	IbisContext ibisContext = getIbisContext(application);
	AppConstants appConstants = getAppConstants(ibisContext);
	String windiffCommand = appConstants.getResolvedProperty("larva.windiff.command");
	if (windiffCommand == null) {
		String servletPath = request.getServletPath();
		int i = servletPath.lastIndexOf('/');
		String realPath = application.getRealPath(servletPath.substring(0, i));
		List<String> scenariosRootDirectories = new ArrayList<String>();
		List<String> scenariosRootDescriptions = new ArrayList<String>();
		String currentScenariosRootDirectory = TestTool.initScenariosRootDirectories(
				appConstants, realPath,
				null, scenariosRootDirectories,
				scenariosRootDescriptions, null);
		windiffCommand = currentScenariosRootDirectory + "..\\..\\IbisAlgemeenWasbak\\WinDiff\\WinDiff.Exe";
	}
	File tempFileResult = writeTempFile(expectedFileName, result);
	File tempFileExpected = writeTempFile(expectedFileName, expected);
	String command = windiffCommand + " " + tempFileResult + " " + tempFileExpected;
	ProcessUtil.executeCommand(command);
}
 
Example #4
Source File: AbstractSolver.java    From unitime with Apache License 2.0 6 votes vote down vote up
public void importXml(byte[] data) throws IOException {
    try {
        Document document = (new SAXReader()).read(new ByteArrayInputStream(data));
        readProperties(document);
        
        M model = createModel(getProperties());
        Progress.getInstance(model).addProgressListener(new ProgressWriter(System.out));
        
        setInitalSolution(model);
        initSolver();

        restureCurrentSolutionFromBackup(document);
        Progress.getInstance(model).setStatus(MSG.statusReady());
    } catch (DocumentException e) {
    	throw new IOException(e.getMessage(), e);
    }
}
 
Example #5
Source File: SvgDataObjectReferenceComponent.java    From fixflow with Apache License 2.0 6 votes vote down vote up
public String createComponent(SvgBaseTo svgTo) {
	String result = null;
	try {
		SvgDataObjectReferenceTo stevent = (SvgDataObjectReferenceTo)svgTo;
		InputStream in = SvgBench.class.getResourceAsStream(comPath);
		Document doc = XmlUtil.read(in);
		String str = doc.getRootElement().asXML();
		str = FlowSvgUtil.replaceAll(str, local_x, StringUtil.getString(stevent.getX()));
		str = FlowSvgUtil.replaceAll(str, local_y, StringUtil.getString(stevent.getY()));
		str = FlowSvgUtil.replaceAll(str, id, stevent.getId());
		str = FlowSvgUtil.replaceAll(str, text, stevent.getLabel());
		str = FlowSvgUtil.replaceAll(str, input, none);
		str = FlowSvgUtil.replaceAll(str, output, none);
		result = str;
	} catch (DocumentException e) {
		throw new FixFlowException("",e);
	}
	return result;
}
 
Example #6
Source File: OpenWxController.java    From jeewx-boot with Apache License 2.0 6 votes vote down vote up
/**
   * 一键授权功能(仅支持公众号)
   * @param request
   * @param response
   * @throws IOException
   * @throws AesException
   * @throws DocumentException
   */
  @RequestMapping(value = "/goAuthor")
  public void goAuthor(HttpServletRequest request, HttpServletResponse response) throws IOException, AesException, DocumentException {
  	//从数据库获取ticket
  	WeixinOpenAccount  weixinOpenAccount = getWeixinOpenAccount(CommonWeixinProperties.component_appid);
  	try {
	String componentAccessToken = weixinOpenAccount.getComponentAccessToken();
	//预授权码
	String preAuthCode = JwThirdAPI.getPreAuthCode(CommonWeixinProperties.component_appid, componentAccessToken);
	//auth_type:要授权的帐号类型, 1则商户扫码后,手机端仅展示公众号、2表示仅展示小程序,3表示公众号和小程序都展示。
	String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid="+CommonWeixinProperties.component_appid+"&pre_auth_code="+preAuthCode+"&auth_type=1"+"&redirect_uri="+CommonWeixinProperties.domain+"/rest/openwx/authorCallback";
	response.sendRedirect(url);
} catch (WexinReqException e) {
	e.printStackTrace();
}
  }
 
Example #7
Source File: DBConfig.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public DBConfig(URL dbconfig, MetaData metaData){
	this.metaData = metaData;
	try {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(dbconfig);
		root = doc.getRootElement();
		
		Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
		URL defaultUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
		SAXReader defaultReader = new SAXReader();
		Document defaultDoc = defaultReader.read(defaultUrl);
		defaultRoot = defaultDoc.getRootElement();
	} catch (DocumentException e) {
		logger.warn("", e);
	}
}
 
Example #8
Source File: InMsgParser.java    From jfinal-weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 消息类型
 * 1:text 文本消息
 * 2:image 图片消息
 * 3:voice 语音消息
 * 4:video 视频消息
 *	shortvideo 小视频消息
 * 5:location 地址位置消息
 * 6:link 链接消息
 * 7:event 事件
 */
private static InMsg doParse(String xml) throws DocumentException {
	Document doc = DocumentHelper.parseText(xml);
	Element root = doc.getRootElement();
	String toUserName = root.elementText("ToUserName");
	String fromUserName = root.elementText("FromUserName");
	Integer createTime = Integer.parseInt(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 ("voice".equals(msgType))
		return parseInVoiceMsgAndInSpeechRecognitionResults(root, toUserName, fromUserName, createTime, msgType);
	if ("video".equals(msgType))
		return parseInVideoMsg(root, toUserName, fromUserName, createTime, msgType);
	if ("shortvideo".equals(msgType))	 //支持小视频
		return parseInShortVideoMsg(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 parseInEvent(root, toUserName, fromUserName, createTime, msgType);
	throw new RuntimeException("无法识别的消息类型 " + msgType + ",请查阅微信公众平台开发文档");
}
 
Example #9
Source File: ConfigurationServiceImpl.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Document getConfigurationAsDocument(@ProtectedResourceId(SITE_ID_RESOURCE_ID) String siteId, String module,
                                           String path, String environment)
        throws DocumentException, IOException {
    String content = getEnvironmentConfiguration(siteId, module, path, environment);
    Document retDocument = null;
    if (StringUtils.isNotEmpty(content)) {
        SAXReader saxReader = new SAXReader();
        try {
            saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
            saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        } catch (SAXException ex) {
            logger.error("Unable to turn off external entity loading, this could be a security risk.", ex);
        }
        try (InputStream is = IOUtils.toInputStream(content)) {
            retDocument = saxReader.read(is);
        }
    }
    return retDocument;
}
 
Example #10
Source File: OFDDoc.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
/**
 * 获取附件列表文件,如果文件不存在则创建
 * <p>
 * 该操作将会切换资源加载器到与附件文件同级的位置
 *
 * @param rl     资源加载器
 * @param docDir 文档目录
 * @return 附件列表文件
 */
private Attachments obtainAttachments(DocDir docDir, ResourceLocator rl) {
    ST_Loc attLoc = ofdDocument.getAttachments();
    Attachments attachments = null;
    if (attLoc != null) {
        try {
            attachments = rl.get(attLoc, Attachments::new);
            // 切换目录到资源文件所在目录
            rl.cd(attLoc.parent());
        } catch (DocumentException | FileNotFoundException e) {
            // 忽略错误
            System.err.println(">> 无法解析Attachments.xml文件,将重新创建该文件");
            attachments = null;
        }
    }
    if (attachments == null) {
        attachments = new Attachments();
        docDir.putObj(DocDir.Attachments, attachments);
        ofdDocument.setAttachments(docDir.getAbsLoc().cat(DocDir.Attachments));
    }
    return attachments;
}
 
Example #11
Source File: DBConfig.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
public DBConfig(URL dbconfig, MetaData metaData){
	this.metaData = metaData;
	try {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(dbconfig);
		root = doc.getRootElement();
		
		Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
		URL defaultUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
		SAXReader defaultReader = new SAXReader();
		Document defaultDoc = defaultReader.read(defaultUrl);
		defaultRoot = defaultDoc.getRootElement();
	} catch (DocumentException e) {
		logger.warn("", e);
	}
}
 
Example #12
Source File: ExtensionXmlHandler.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void loadExtensions(Set<GameExtension> set) throws IOException, DocumentException {
	if (!xmlFile.exists()) {
		return;
	}
	
	try (InputStream in = new FileInputStream(xmlFile);
			Reader reader = new InputStreamReader(in, UTF8)) {
		Document document = saxReader.read(reader);
		Element rootElement = document.getRootElement();
		
		List<Element> extensionElements = rootElement.elements("extension");
		for (Element extensionElement : extensionElements) {
			String name = extensionElement.attributeValue("name");
			Class<? extends GameExtension> expected = registry.getExtensionClass(name);
			
			GameExtension extension = context.read(extensionElement, expected);
			set.add(extension);
		}
	}
}
 
Example #13
Source File: MetadataFactory.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Initializes the meta data from the xml file.
 *
 * @throws CheckstylePluginException
 *           error loading the meta data file
 */
private static void doInitialization() throws CheckstylePluginException {

  ClassLoader classLoader = CheckstylePlugin.getDefault().getAddonExtensionClassLoader();
  Collection<String> potentialMetadataFiles = getAllPotentialMetadataFiles(classLoader);
  for (String metadataFile : potentialMetadataFiles) {

    try (InputStream metadataStream = classLoader.getResourceAsStream(metadataFile)) {

      if (metadataStream != null) {

        ResourceBundle metadataBundle = getMetadataI18NBundle(metadataFile, classLoader);
        parseMetadata(metadataStream, metadataBundle);
      }
    } catch (DocumentException | IOException e) {
      CheckstyleLog.log(e, "Could not read metadata " + metadataFile); //$NON-NLS-1$
    }
  }
}
 
Example #14
Source File: ProjectConfigurationFactory.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static IProjectConfiguration getProjectConfiguration(InputStream in, IProject project)
        throws DocumentException, CheckstylePluginException {

  SAXReader reader = new SAXReader();
  Document document = reader.read(in);

  Element root = document.getRootElement();

  String version = root.attributeValue(XMLTags.FORMAT_VERSION_TAG);
  if (!SUPPORTED_VERSIONS.contains(version)) {
    throw new CheckstylePluginException(NLS.bind(Messages.errorUnknownFileFormat, version));
  }

  boolean useSimpleConfig = Boolean.valueOf(root.attributeValue(XMLTags.SIMPLE_CONFIG_TAG))
          .booleanValue();
  boolean syncFormatter = Boolean.valueOf(root.attributeValue(XMLTags.SYNC_FORMATTER_TAG))
          .booleanValue();

  List<ICheckConfiguration> checkConfigs = getLocalCheckConfigs(root, project);
  List<FileSet> fileSets = getFileSets(root, checkConfigs);
  List<IFilter> filters = getFilters(root);

  return new ProjectConfiguration(project, checkConfigs, fileSets, filters, useSimpleConfig,
          syncFormatter);
}
 
Example #15
Source File: XSLTests.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
@Test
/**
 * Check whether the enumeration in Constants generates valid files.
 */
public void testTagsFromConstants() {

	for (final XSLTag tag : this.tags.values()) {

		System.out.println("Tag under consideration : " + tag.getXSLTagDetails().getXSLTagFaceName());
		boolean validTag = false;
		final StringBuilder dataFromFile = new StringBuilder();

		dataFromFile.append(XSLStringGenerationAndManipulation.generateXSLStringFromPath(null, "", new Point(0, 0), tag.toString()));

		try {
			DocumentHelper.parseText(dataFromFile.toString());
			validTag = true;
		}
		catch (final DocumentException e) {
			validTag = false;
		}

		assertTrue(validTag);

	}
}
 
Example #16
Source File: WeiXinController.java    From wangmarket with Apache License 2.0 6 votes vote down vote up
/**
 * 微信服务器推送消息,推送到此接口
 * @throws IOException 
 * @throws DocumentException 
 */
@RequestMapping("weixin${url.suffix}")
public void weixin(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException{
	MessageReceive message = com.xnx3.wangmarket.weixin.Global.getWeiXinUtil().receiveMessage(request);
	
	AliyunLog.addActionLog("weixinMessage", message.getReceiveBody());
	
	if(request.getQueryString() == null){
		//return "<html><head><meta charset=\"utf-8\"></head><body>浏览器中直接输入网址访问是不行的!这个接口是接收微信服务器返回数据的,得通过微信服务器返回得数据测试才行</body></html>";
	}
	
	/**** 针对微信自动回复插件 ****/
	try {
		AutoReplyPluginManage.autoReply(request, response, message);
	} catch (InstantiationException | IllegalAccessException
			| NoSuchMethodException | SecurityException
			| IllegalArgumentException | InvocationTargetException e) {
		e.printStackTrace();
	}
	
}
 
Example #17
Source File: Dom4jProcessorUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, TransformerException, URISyntaxException, DocumentException, SAXException {
    String path = getClass().getResource("/xml/attribute.xml")
        .toString();
    Dom4jTransformer transformer = new Dom4jTransformer(path);
    String attribute = "customer";
    String oldValue = "true";
    String newValue = "false";
    String expectedXml = new String(Files.readAllBytes((Paths.get(getClass().getResource("/xml/attribute_expected.xml")
        .toURI()))));

    String result = transformer
      .modifyAttribute(attribute, oldValue, newValue)
      .replaceAll("(?m)^[ \t]*\r?\n", "");//Delete extra spaces added by Java 11

    assertThat(result).and(expectedXml)
        .areSimilar();
}
 
Example #18
Source File: SvgDataInputComponent.java    From fixflow with Apache License 2.0 6 votes vote down vote up
public String createComponent(SvgBaseTo svgTo) {
	String result = null;
	try {
		SvgDataInputTo stevent = (SvgDataInputTo)svgTo;
		InputStream in = SvgBench.class.getResourceAsStream(comPath);
		Document doc = XmlUtil.read(in);
		String str = doc.getRootElement().asXML();
		str = FlowSvgUtil.replaceAll(str, local_x, StringUtil.getString(stevent.getX()));
		str = FlowSvgUtil.replaceAll(str, local_y, StringUtil.getString(stevent.getY()));
		str = FlowSvgUtil.replaceAll(str, id, stevent.getId());
		str = FlowSvgUtil.replaceAll(str, text, stevent.getLabel());
		str = FlowSvgUtil.replaceAll(str, input, "");
		str = FlowSvgUtil.replaceAll(str, output, none);
		result = str;
	} catch (DocumentException e) {
		throw new FixFlowException("",e);
	}
	return result;
}
 
Example #19
Source File: OpenWxController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
   * 处理授权事件的推送
   * 
   * @param request
   * @throws IOException
   * @throws AesException
   * @throws DocumentException
   */
  public void processAuthorizeEvent(HttpServletRequest request) throws IOException, DocumentException, AesException {
      try {
      	String nonce = request.getParameter("nonce");
          String timestamp = request.getParameter("timestamp");
          String signature = request.getParameter("signature");
          String msgSignature = request.getParameter("msg_signature");
   
          if (!StringUtils.isNotBlank(msgSignature))
              return;// 微信推送给第三方开放平台的消息一定是加过密的,无消息加密无法解密消息
          boolean isValid = checkSignature(CommonWeixinProperties.COMPONENT_TOKEN, signature, timestamp, nonce);
          log.info("第三方平台校验签名时验证是否正确"+isValid);
          if (isValid) {
              StringBuilder sb = new StringBuilder();
              BufferedReader in = request.getReader();
              String line;
              while ((line = in.readLine()) != null) {
                  sb.append(line);
              }
              String xml = sb.toString();
              String encodingAesKey = CommonWeixinProperties.COMPONENT_ENCODINGAESKEY;// 第三方平台组件加密密钥
              WXBizMsgCrypt pc = new WXBizMsgCrypt(CommonWeixinProperties.COMPONENT_TOKEN, encodingAesKey, CommonWeixinProperties.component_appid);
              xml = pc.decryptMsg(msgSignature, timestamp, nonce, xml);
              processAuthorizationEvent(xml);
          }
} catch (Exception e) {
	e.printStackTrace();
	log.error("processAuthorizeEvent error={}.",new Object[]{e});
}
  }
 
Example #20
Source File: PluginCacheConfigurator.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public void configure(String pluginName) {
    try {
        SAXReader saxReader = new SAXReader();
        saxReader.setEncoding("UTF-8");
        Document cacheXml = saxReader.read(configDataStream);
        List<Node> mappings = cacheXml.selectNodes("/cache-config/cache-mapping");
        for (Node mapping: mappings) {
            registerCache(pluginName, mapping);
        }
    }
    catch (DocumentException e) {
        Log.error(e.getMessage(), e);
    }
}
 
Example #21
Source File: ConfigManager.java    From WeSync with MIT License 5 votes vote down vote up
/**
 * 读取xml,加载到dom
 */
public void reloadDom() {
    SAXReader reader = new SAXReader();
    try {
        document = reader.read(new File(ConstantsTools.PATH_CONFIG));
    } catch (DocumentException e) {
        e.printStackTrace();
        logger.error("Read config xml error:" + e.toString());
    }
}
 
Example #22
Source File: WxXMLUtilTest.java    From WeixinMultiPlatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMsgLoc() throws DocumentException {
	WxMsgLocEntity msgLoc = WxXmlUtil.getMsgLoc(WxXmlUtil.toXML(MSG_LOC_XML));
	assertBaseFieldsWithMsgId(msgLoc);
	Assert.assertEquals(Double.valueOf(23.134521d), msgLoc.getLocationX());
	Assert.assertEquals(Double.valueOf(113.358803d), msgLoc.getLocationY());
	Assert.assertEquals(Double.valueOf(20), msgLoc.getScale());
	Assert.assertEquals("位置信息", msgLoc.getLabel());
}
 
Example #23
Source File: OFDReader.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 获取默认的签名列表对象
 *
 * @return 签名列表对象
 */
public Signatures getDefaultSignatures() {
    ST_Loc signaturesLoc = getDefaultDocSignaturesPath();
    if (signaturesLoc == null) {
        throw new BadOFDException("OFD文档中不存在Signatures.xml");
    }
    // 获取签名列表对象
    try {
        return rl.get(signaturesLoc, Signatures::new);
    } catch (FileNotFoundException | DocumentException e) {
        throw new BadOFDException("错误OFD结构和文件格式", e);
    }
}
 
Example #24
Source File: PersistParserTest.java    From bulbasaur with Apache License 2.0 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 #25
Source File: XMLParserTest.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testXMLValidity() throws DocumentException, IOException {
	final String encoding = "UTF-8";
	final byte[] encoded = Files.readAllBytes(Paths.get(this.validFilePath));
	final String validXML = new String(encoded, encoding);
	final XMLClaferParser xmlparser = new XMLClaferParser();

	final String xml = xmlparser.displayInstanceValues(this.inst, this.constraints).asXML();
	assertEquals(uglifyXML(validXML), uglifyXML(xml));
}
 
Example #26
Source File: BpmnParseHandlerImpl.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public BpmnParseHandlerImpl() {
	SAXReader reader = new SAXReader();
	try {
		Document doc = reader.read(this.getClass().getClassLoader().getResourceAsStream("config/style.xml"));
		Element element = doc.getRootElement();
		Element configElement = element.element("elementStyleConfig");
		String currentStyle = configElement.attributeValue("currentStyle");
		Iterator<Element> elemIterator = configElement.elements("elementStyle").iterator();
		Element styleConfigElemnt = null;
		while (elemIterator.hasNext()) {
			styleConfigElemnt = elemIterator.next();
			String styleId = styleConfigElemnt.attributeValue("styleId");
			if (currentStyle.equals(styleId)) {
				break;
			}
		}
		if (styleConfigElemnt == null) {
			throw new RuntimeException("style.xml文件格式不正确,请检查!");
		}
		Iterator<Element> styleElementIterator = styleConfigElemnt.elements("style").iterator();
		while (styleElementIterator.hasNext()) {
			Element styleElement = styleElementIterator.next();
			Style tmpStyle = new Style();
			String elementType = styleElement.attributeValue("object");
			tmpStyle.setElementType(elementType);
			tmpStyle.setBackGround(styleElement.attributeValue("background"));
			tmpStyle.setForeGround(styleElement.attributeValue("foreground"));
			tmpStyle.setSelectedColor(styleElement.attributeValue("selectedColor"));
			tmpStyle.setMulitSelectedColor(styleElement.attributeValue("selectedColor"));
			tmpStyle.setTextColor(styleElement.attributeValue("textColor"));
			tmpStyle.setFont(styleElement.attributeValue("font"));
			styleContainer.put(elementType, tmpStyle);
		}
	} catch (DocumentException e) {
		throw ExceptionUtil.getException("10106000", e);
	}
}
 
Example #27
Source File: HuaweiXmlParser.java    From onos with Apache License 2.0 5 votes vote down vote up
private Iterator getInterfaceIterator() {
    Document doc;
    try {
        doc = DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        throw new IllegalArgumentException(INT_PARSE_ERR);
    }
    Element root = doc.getRootElement();
    Element parent = root.element(DATA).element(IFM).element(IFS);
    return parent.elementIterator(IF);
}
 
Example #28
Source File: WeixinInMsgParser.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 解析微信服务器请求的xml报文体为com.jadyer.sdk.weixin.msg.in.WeixinInMsg对象
 * @see 若无法识别请求的MsgType或解析xml出错,会抛出RuntimeException
 * @create Oct 18, 2015 12:59:48 PM
 * @author 玄玉<https://jadyer.cn/>
 */
public static WeixinInMsg parse(String xml) {
    try {
        return doParse(xml);
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: TestReport.java    From PatatiumWebUi with Apache License 2.0 5 votes vote down vote up
private String getTestngParametersValue(String path,String ParametersName) throws DocumentException, IOException
{
	File file = new File(path);
	if (!file.exists()) {
		throw new IOException("Can't find " + path);

	}
	String value=null;
	SAXReader reader = new SAXReader();
	Document  document = reader.read(file);
	Element root = document.getRootElement();
	for (Iterator<?> i = root.elementIterator(); i.hasNext();)
	{
		Element page = (Element) i.next();
		if(page.attributeCount()>0)
		{
			if (page.attribute(0).getValue().equalsIgnoreCase(ParametersName))
			{
				value=page.attribute(1).getValue();
				//System.out.println(page.attribute(1).getValue());
			}
			continue;
		}
		//continue;
	}
	return value;

}
 
Example #30
Source File: OFDReader.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 获取页面信息
 *
 * @param pageNum 页码,从1开始
 * @return 页面信息
 */
public PageInfo getPageInfo(int pageNum) {
    if (pageNum <= 0) {
        throw new NumberFormatException("页码(pageNum)不能小于0");
    }
    try {
        int index = pageNum - 1;
        // 保存切换目录前的工作区
        rl.save();
        DocBody docBody = ofdDir.getOfd().getDocBody();
        ST_Loc docRoot = docBody.getDocRoot();
        // 路径解析对象获取并缓存虚拟容器
        Document document = rl.get(docRoot, Document::new);
        rl.cd(docRoot.parent());
        Pages pages = document.getPages();
        List<org.ofdrw.core.basicStructure.pageTree.Page> pageList = pages.getPages();
        if (index >= pageList.size()) {
            throw new NumberFormatException(pageNum + "超过最大页码:" + pageList.size());
        }
        // 获取页面的路径
        ST_Loc pageLoc = pageList.get(index).getBaseLoc();

        Page obj = rl.get(pageLoc, Page::new);
        // 获取页面的容器绝对路径
        pageLoc = rl.getAbsTo(pageLoc);

        ST_Box pageSize = getPageSize(obj);
        return new PageInfo()
                .setIndex(pageNum)
                .setId(pageList.get(index).getID())
                .setObj(obj)
                .setSize(pageSize.clone())
                .setPageAbsLoc(pageLoc);
    } catch (FileNotFoundException | DocumentException e) {
        throw new RuntimeException("OFD解析失败,原因:" + e.getMessage(), e);
    } finally {
        // 还原原有工作区
        rl.restore();
    }
}