org.dom4j.Document Java Examples

The following examples show how to use org.dom4j.Document. 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: TestSummaryCreatorTask.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the specified attribute of the node determined by the given xpath.
 * 
 * @param doc      The XML document
 * @param xpath    The xpath selecting the node whose attribute we want
 * @param attrName The name of the attribute
 * @return The attribute value
 */
private String getAttrValue(Document doc, String xpath, String attrName)
{
	Node node = doc.selectSingleNode(xpath);

	if (node instanceof Attribute)
	{
		// we ignore the attribute name then
		return ((Attribute)node).getValue();
	}
	else if (node != null)
	{
		return node.valueOf("@" + attrName);
	}
    else
    {
        return null;
    }
}
 
Example #2
Source File: RemoteArticleService.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public String getArticleXML(Long articleId) {
    Article article = articleDao.getEntity(articleId);
    if(article == null 
    		|| checkBrowsePermission(article.getChannel().getId() ) < 0 ) {
    	return ""; // 如果文章不存在 或 对文章所在栏目没有浏览权限
    }
    
    String pubUrl = article.getPubUrl();
    Document articleDoc = XMLDocUtil.createDocByAbsolutePath2(pubUrl);
    Element articleElement = articleDoc.getRootElement();
    Element hitRateNode = (Element) articleElement.selectSingleNode("//hitCount");
    hitRateNode.setText(article.getHitCount().toString()); // 更新点击率
    
    Document doc = org.dom4j.DocumentHelper.createDocument();
    Element articleInfoElement = doc.addElement("Response").addElement("ArticleInfo");
    articleInfoElement.addElement("rss").addAttribute("version", "2.0").add(articleElement);

    // 添加文章点击率;
    HitRateManager.getInstanse("cms_article").output(articleId);
    
    return doc.asXML();
}
 
Example #3
Source File: FilterParserImpl.java    From cuba with Apache License 2.0 6 votes vote down vote up
/**
 * Converts filter conditions tree to filter xml
 * @param conditions conditions tree
 * @param valueProperty Describes what parameter value will be serialized to xml: current value or default one
 * @return filter xml
 */
@Override
@Nullable
public String getXml(ConditionsTree conditions, Param.ValueProperty valueProperty) {
    String xml = null;
    if (conditions != null && !conditions.getRootNodes().isEmpty()) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("filter");
        Element element = root.addElement("and");
        for (Node<AbstractCondition> node : conditions.getRootNodes()) {
            recursiveToXml(node, element, valueProperty);
        }
        xml = dom4JTools.writeDocument(document, true);
    }
    log.trace("toXML: {}", xml);
    return xml;
}
 
Example #4
Source File: OptionsTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void withoutItems() throws Exception {
	this.tag.setItemValue("isoCode");
	this.tag.setItemLabel("name");
	this.selectTag.setPath("testBean");

	this.selectTag.doStartTag();
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);
	this.tag.doEndTag();
	this.selectTag.doEndTag();

	String output = getOutput();
	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();

	List children = rootElement.elements();
	assertEquals("Incorrect number of children", 0, children.size());
}
 
Example #5
Source File: FilePersister.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Persist results for this user/aiid as an XML document. dlPointer is aiid in this case.
 * 
 * @param doc
 * @param type
 * @param info
 */
public static void createResultsReporting(final Document doc, final Identity subj, final String type, final long aiid) {
    final File fUserdataRoot = new File(getQtiFilePath());
    final String path = RES_REPORTING + File.separator + subj.getName() + File.separator + type;
    final File fReportingDir = new File(fUserdataRoot, path);
    try {
        fReportingDir.mkdirs();
        final OutputStream os = new FileOutputStream(new File(fReportingDir, aiid + ".xml"));
        final Element element = doc.getRootElement();
        final XMLWriter xw = new XMLWriter(os, new OutputFormat("  ", true));
        xw.write(element);
        // closing steams
        xw.close();
        os.close();
    } catch (final Exception e) {
        throw new OLATRuntimeException(FilePersister.class,
                "Error persisting results reporting for subject: '" + subj.getName() + "'; assessment id: '" + aiid + "'", e);
    }
}
 
Example #6
Source File: Dom4JReader.java    From liteFlow with Apache License 2.0 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 #7
Source File: XMPPPacketReaderTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Check that the 'jabber:client' default namespace declaration is explicitly _not_ stripped from a child element
 * of a stanza.
 *
 * Openfire strips this namespace (among others) to make the resulting XML 're-usable', in context of the
 * implementation note in RFC 6120, section 4.8.3.
 *
 * @see <a href="https://issues.igniterealtime.org/browse/OF-1335">Issue OF-1335: Forwarded messages rewritten to default namespace over S2S</a>
 * @see <a href="https://xmpp.org/rfcs/rfc6120.html#streams-ns-xmpp">RFC 6120, 4.8.3. XMPP Content Namespaces</a>
 */
@Test
public void testAvoidStrippingInternalContentNamespace() throws Exception
{
    // Setup fixture
    final String input =
        "<stream:stream xmlns:stream='http://etherx.jabber.org/streams' to='example.com' version='1.0'>" +
        "  <message xmlns='jabber:client'>" +
        "    <other xmlns='something:else'>" +
        "      <message xmlns='jabber:client'/>" +
        "    </other>" +
        "  </message>" +
        "</stream:stream>";

    final Document result = packetReader.read( new StringReader( input ) );

    // Verify result.
    Assert.assertFalse( "'jabber:client' should not occur before 'something:else'", result.asXML().substring( 0, result.asXML().indexOf("something:else") ).contains( "jabber:client" ) );
    Assert.assertTrue( "'jabber:client' should occur after 'something:else'", result.asXML().substring( result.asXML().indexOf("something:else") ).contains( "jabber:client" ) );
}
 
Example #8
Source File: ComponentFinder.java    From Whack with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of an element selected via an xpath expression from
 * a component's component.xml file.
 *
 * @param component the component.
 * @param xpath the xpath expression.
 * @return the value of the element selected by the xpath expression.
 */
private String getElementValue(Component component, String xpath) {
    File componentDir = componentDirs.get(component);
    if (componentDir == null) {
        return null;
    }
    try {
        File componentConfig = new File(componentDir, "component.xml");
        if (componentConfig.exists()) {
            SAXReader saxReader = new SAXReader();
            Document componentXML = saxReader.read(componentConfig);
            Element element = (Element)componentXML.selectSingleNode(xpath);
            if (element != null) {
                return element.getTextTrim();
            }
        }
    }
    catch (Exception e) {
        manager.getLog().error(e);
    }
    return null;
}
 
Example #9
Source File: XSLStringGenerationAndManipulation.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method is created to be able to exit the nested loops as soon as the correct instance is found.
 *
 * @param question The question object from the outer loop.
 * @param answer The answer object from the outer loop.
 * @param xmlParser This object is needed to generate the xml string.
 * @param instanceGenerator This object is needed to generate the instances
 * @param claferDependency The claferDependency from the outer loop
 * @return
 */
private static Document getXMLForNewAlgorithmInsertion(final Question question, final Answer answer, final XMLClaferParser xmlParser, final InstanceGenerator instanceGenerator,
		final ClaferDependency claferDependency) {
	final HashMap<Question, Answer> constraints = new HashMap<>();
	constraints.put(question, answer);
	final String constraintOnType = claferDependency.getAlgorithm();
	for (final InstanceClafer instance : instanceGenerator.generateInstances(constraints)) {
		for (final InstanceClafer childInstance : instance.getChildren()) {
			// check if the name of the constraint on the clafer instance is the same as the one on the clafer dependency from the outer loop.
			if (childInstance.getType().getName().equals(constraintOnType)) {
				return xmlParser.displayInstanceValues(instance, constraints);
			}
		} // child instance loop
	} // instance loop
	return null;
}
 
Example #10
Source File: SurveyFileResourceValidator.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate(final File unzippedDir) {
    // with VFS FIXME:pb:c: remove casts to LocalFileImpl and LocalFolderImpl if no longer needed.
    final VFSContainer vfsUnzippedRoot = new LocalFolderImpl(unzippedDir);
    final VFSItem vfsQTI = vfsUnzippedRoot.resolve("qti.xml");
    // getDocument(..) ensures that InputStream is closed in every case.
    final Document doc = QTIHelper.getDocument((LocalFileImpl) vfsQTI);
    // if doc is null an error loading the document occured
    if (doc == null) {
        return false;
    }
    final List metas = doc.selectNodes("questestinterop/assessment/qtimetadata/qtimetadatafield");
    for (final Iterator iter = metas.iterator(); iter.hasNext();) {
        final Element el_metafield = (Element) iter.next();
        final Element el_label = (Element) el_metafield.selectSingleNode("fieldlabel");
        final String label = el_label.getText();
        if (label.equals(AssessmentInstance.QMD_LABEL_TYPE)) { // type meta
            final Element el_entry = (Element) el_metafield.selectSingleNode("fieldentry");
            final String entry = el_entry.getText();
            return entry.equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY);
        }
    }

    return false;
}
 
Example #11
Source File: QTIObjectTreeBuilder.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
* 
*
*/
  public List getQTIItemObjectList() {
      final Resolver resolver = new ImsRepositoryResolver(repositoryEntryKey);
      final Document doc = resolver.getQTIDocument();
      final Element root = doc.getRootElement();
      final List items = root.selectNodes("//item");

      final ArrayList itemList = new ArrayList();

      for (final Iterator iter = items.iterator(); iter.hasNext();) {
          final Element el_item = (Element) iter.next();
          if (el_item.selectNodes(".//response_lid").size() > 0) {
              itemList.add(new ItemWithResponseLid(el_item));
          } else if (el_item.selectNodes(".//response_str").size() > 0) {
              itemList.add(new ItemWithResponseStr(el_item));
          }
      }
      return itemList;
  }
 
Example #12
Source File: TaskTest.java    From bulbasaur with Apache License 2.0 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 #13
Source File: CmisServiceImpl.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private DataSourceRepository getConfiguration(String site, String cmisRepo) throws CmisRepositoryNotFoundException {
    String configPath = Paths.get(getConfigLocation()).toString();
    Document document =  null;
    DataSourceRepository repositoryConfig = null;
    try {
        document = contentService.getContentAsDocument(site, configPath);
        Node node = document.selectSingleNode(REPOSITORY_CONFIG_XPATH.replace(CMIS_REPO_ID_VARIABLE, cmisRepo));
        if (node != null) {
            repositoryConfig = new DataSourceRepository();
            repositoryConfig.setId(getPropertyValue(node, ID_PROPERTY));
            repositoryConfig.setType(getPropertyValue(node, TYPE_PROPERTY));
            repositoryConfig.setUrl(getPropertyValue(node, URL_PROPERTY));
            repositoryConfig.setUsername(getPropertyValue(node, USERNAME_PROPERTY));
            repositoryConfig.setPassword(getPropertyValue(node, PASSWORD_PROPERTY));
            repositoryConfig.setBasePath(getPropertyValue(node, BASE_PATH_PROPERTY));
            repositoryConfig.setDownloadUrlRegex(getPropertyValue(node, DOWNLOAD_URL_REGEX_PROPERTY));
            repositoryConfig.setUseSsl(Boolean.parseBoolean(getPropertyValue(node, USE_SSL_PROPERTY)));
        } else {
            throw new CmisRepositoryNotFoundException();
        }
    } catch (DocumentException e) {
        logger.error("Error while getting configuration for site: " + site + " cmis: " + cmisRepo +
                " (config path: " + configPath + ")");
    }
    return repositoryConfig;
}
 
Example #14
Source File: Command.java    From ApkCustomizationTool with Apache License 2.0 6 votes vote down vote up
/**
 * 修改strings.xml文件内容
 *
 * @param file    strings文件
 * @param strings 修改的值列表
 */
private void updateStrings(File file, List<Strings> strings) {
    try {
        if (strings == null || strings.isEmpty()) {
            return;
        }
        Document document = new SAXReader().read(file);
        List<Element> elements = document.getRootElement().elements();
        elements.forEach(element -> {
            final String name = element.attribute("name").getValue();
            strings.forEach(s -> {
                if (s.getName().equals(name)) {
                    element.setText(s.getValue());
                    callback("修改 strings.xml name='" + name + "' value='" + s.getValue() + "'");
                }
            });
        });
        XMLWriter writer = new XMLWriter(new FileOutputStream(file));
        writer.write(document);
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: StageXmlRepresenterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@FileSource(files = "/feeds/stage.xml")
void shouldGenerateDocumentForStage(String expectedXML) {
    String pipelineName = "BulletinBoard";
    String stageName = "UnitTest";
    String jobName = "run-junit";
    XmlWriterContext context = new XmlWriterContext("https://go-server/go", null, null, null, new SystemEnvironment());
    Stage stage = StageMother.cancelledStage(stageName, jobName);
    stage.getJobInstances().get(0).setIdentifier(new JobIdentifier(pipelineName, 1, null, stageName, "1", jobName));
    stage.getJobInstances().get(0).getTransitions().first()
        .setStateChangeTime(parseISO8601("2020-01-03T11:14:19+05:30"));
    stage.setIdentifier(new StageIdentifier(pipelineName, 10, stage.getName(), "4"));

    Document document = new StageXmlRepresenter(stage).toXml(context);

    assertThat(document.asXML()).and(expectedXML)
        .ignoreWhitespace()
        .areIdentical();
}
 
Example #16
Source File: CheckboxTagTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void withCollection() throws Exception {
	this.tag.setPath("someList");
	this.tag.setValue("foo");
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();

	// wrap the output so it is valid XML
	output = "<doc>" + output + "</doc>";

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element checkboxElement = (Element) document.getRootElement().elements().get(0);
	assertEquals("input", checkboxElement.getName());
	assertEquals("checkbox", checkboxElement.attribute("type").getValue());
	assertEquals("someList", checkboxElement.attribute("name").getValue());
	assertEquals("checked", checkboxElement.attribute("checked").getValue());
	assertEquals("foo", checkboxElement.attribute("value").getValue());
}
 
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, 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 #18
Source File: PaymentFactory.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * Xml字符串转换为Map
 *
 * @param xmlStr
 * @return
 */
public static Map<String, String> xmlStrToMap(String xmlStr) {
    Map<String, String> map = new HashMap<String, String>();
    Document doc;
    try {
        doc = DocumentHelper.parseText(xmlStr);
        Element root = doc.getRootElement();
        List children = root.elements();
        if (children != null && children.size() > 0) {
            for (int i = 0; i < children.size(); i++) {
                Element child = (Element) children.get(i);
                map.put(child.getName(), child.getTextTrim());
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return map;
}
 
Example #19
Source File: SvgAnnotationComponent.java    From fixflow with Apache License 2.0 6 votes vote down vote up
public String createComponent(SvgBaseTo svgTo) {
	String result = null;
	try {
		SvgAnnotationTo annoTo = (SvgAnnotationTo)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(annoTo.getX()));
		str = FlowSvgUtil.replaceAll(str, local_y, StringUtil.getString(annoTo.getY()));
		str = FlowSvgUtil.replaceAll(str, id, annoTo.getId());
		str = FlowSvgUtil.replaceAll(str, text, annoTo.getLabel());
		StringBuffer sb = new StringBuffer();
		sb.append(" M19 0  L0 0  L0 ");
		sb.append(annoTo.getHeight());
		sb.append("  L19 ");
		sb.append(annoTo.getHeight());
		str = FlowSvgUtil.replaceAll(str, path, sb.toString());
		result = str;
	} catch (DocumentException e) {
		throw new FixFlowException("",e);
	}
	
	return result;
}
 
Example #20
Source File: XmlClobType.java    From unitime with Apache License 2.0 5 votes vote down vote up
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
      Clob clob = rs.getClob(names[0]);
      if (clob==null) return null;
try {
	SAXReader reader = new SAXReader();
	Document document = reader.read(clob.getCharacterStream());
	return document;
} catch (DocumentException e) {
	throw new HibernateException(e.getMessage(),e);
}
  }
 
Example #21
Source File: PersistParserTest.java    From bulbasaur with Apache License 2.0 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 #22
Source File: XmlMapperTest.java    From vjtools with Apache License 2.0 5 votes vote down vote up
/**
 * 使用Dom4j验证Jaxb所生成XML的正确性.
 */
private static void assertXmlByDom4j(String xml) {
	Document doc = null;
	try {
		doc = DocumentHelper.parseText(xml);
	} catch (DocumentException e) {
		fail(e.getMessage());
	}
	Element user = doc.getRootElement();
	assertThat(user.attribute("id").getValue()).isEqualTo("1");

	Element interests = (Element) doc.selectSingleNode("//interests");
	assertThat(interests.elements()).hasSize(2);
	assertThat(((Element) interests.elements().get(0)).getText()).isEqualTo("movie");
}
 
Example #23
Source File: XmlUtils.java    From nbp with Apache License 2.0 5 votes vote down vote up
public List<TaskInfo> xmlReadAllTaskInfo() {
    Document docen = load(TASKINFO_EN);
    Document doczh = load(TASKINFO_ZH);
    List<TaskInfo> taskInfoList = xmlReadTaskInfo(docen, "en");
    List<TaskInfo> taskInfoListZh = xmlReadTaskInfo(doczh, "zh");
    taskInfoList.addAll(taskInfoListZh);
    return taskInfoList;
}
 
Example #24
Source File: Servlet3MultiRequest.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 解析合并请求xml数据流
 * </p>
 *
 * @param request
 */
private Document parseRequestXML(HttpServletRequest request) {
	ServletInputStream is = null;
	SAXReader saxReader = new SAXReader();
	try {
		is = request.getInputStream();
		return saxReader.read(is);
		
	} catch (Exception e) {
		throw new BusinessException("解析合并请求的xml数据流失败", e);
	} finally {
		FileHelper.closeSteam(is, null);
	}
}
 
Example #25
Source File: VersionUpdater.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void getLastVersion(File controlpath){
	System.out.println("old version file path: " + controlpath.getAbsolutePath());
	String dayTag = "DayInPast";
	String versionTag = "LastDate";
	String name;
	
	/*
	this.setCvsControlPath(controlpath);
	*/
	SAXReader saxReader = new SAXReader();
	Document document = null;
	try{
		document = saxReader.read(this.cvsControlPath);
	}catch(org.dom4j.DocumentException dex){
		dex.printStackTrace();
	}
	Element rootElement = document.getRootElement();
	Iterator it = rootElement.elementIterator();
	while(it.hasNext()){
		Element element = (Element)it.next();
		name = element.getName();
		if ( name.equalsIgnoreCase(versionTag)){
			this.oldVersion = element.getText();
		}else if( name.equalsIgnoreCase(dayTag) ){
			this.daysInPast = Integer.valueOf(element.getText().trim()).intValue();

		}
	}
	
}
 
Example #26
Source File: RemoteArticleService.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
public void importArticle(String articleXml, Long channelId) {
    Document doc = XMLDocUtil.dataXml2Doc(articleXml);
    Element articleNode = (Element) doc.selectSingleNode("//ArticleInfo/Article");
    Article article = new Article();
    BeanUtil.setDataToBean(article, XMLDocUtil.dataNodes2Map(articleNode));
    
    Channel channel = channelDao.getEntity(channelId);
    article.setChannel(channel);
     
    //设置过期时间
    article.setOverdueDate(ArticleHelper.calculateOverDate(channel));
    
    articleDao.saveArticle(article);
}
 
Example #27
Source File: XmlClobType.java    From unitime with Apache License 2.0 5 votes vote down vote up
public Object assemble(Serializable cached, Object owner) throws HibernateException {
    	try {
            if (cached==null) return null;
    		ByteArrayInputStream in = new ByteArrayInputStream((byte[])cached); 
			SAXReader reader = new SAXReader();
//			GZIPInputStream gzipInput = new GZIPInputStream(in);
			Document document = reader.read(in);
//			gzipInput.close();
    		return document;
		} catch (DocumentException e) {
			throw new HibernateException(e.getMessage(),e);
//    	} catch (IOException e) {
//    		throw new HibernateException(e.getMessage(),e);
    	}
    }
 
Example #28
Source File: ExportXmlFile.java    From unitime with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
try {
	// Configure logging
       org.apache.log4j.BasicConfigurator.configure();
       
       // Configure hibernate
       HibernateUtil.configureHibernate(ApplicationProperties.getProperties());
       
       // Load academic session
       Session session = (Session)SessionDAO.getInstance().getSession().createQuery(
       		"from Session s where s.academicTerm || s.academicYear || s.academicInitiative = :session")
       		.setString("session", args[0]).uniqueResult();
       if (session == null)
       	throw new Exception("Session " + args[0] + " not found.");
       
       // Export an XML file
       Document document = DataExchangeHelper.exportDocument(args[1], session, ApplicationProperties.getProperties(), null);
       if (document==null)
       	throw new Exception("No XML document has been created.");
       
       FileOutputStream fos = new FileOutputStream(args[2]);
       try {
       	(new XMLWriter(fos,OutputFormat.createPrettyPrint())).write(document);
       	fos.flush();
       } finally {
       	fos.close();
          }
       
} catch (Exception e) {
	Logger.getLogger(ImportXmlFile.class).error("Error: " +e.getMessage(), e);
} finally {
       // Close hibernate
       HibernateUtil.closeHibernate();
}
  }
 
Example #29
Source File: VersionCheckerUtility.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void processResults( final String result ) {
  try {
    final SAXReader reader = new SAXReader();
    final Document templateDoc = reader.read( new ByteArrayInputStream( result.getBytes() ) );
    final List<UpdateInfo> updates = new ArrayList<UpdateInfo>();
    final List updateElements = templateDoc.getRootElement().selectNodes( "/vercheck/product/update" );//NON-NLS
    for ( int i = 0; i < updateElements.size(); i++ ) {
      final Element updateElement = (Element) updateElements.get( i );
      final String version = updateElement.attributeValue( "version" );//NON-NLS
      final String type = updateElement.attributeValue( "type" );//NON-NLS
      //final String os = updateElement.attributeValue("os");
      final String downloadUrl = updateElement.selectSingleNode( "downloadurl" ).getText();//NON-NLS
      final UpdateInfo info = new UpdateInfo( version, type, downloadUrl );
      updates.add( info );
    }

    if ( updates.isEmpty() ) {
      if ( forcePrompt ) {
        JOptionPane.showMessageDialog( parent,
          "No update is available at this time.", "Version Update Info",
          JOptionPane.INFORMATION_MESSAGE );
      }
      return;
    }

    if ( ( forcePrompt ||
      !updates.get( updates.size() - 1 ).getVersion().equals(
        WorkspaceSettings.getInstance().getLastPromptedVersionUpdate() ) ) ) {
      final UpdateInfo[] updateInfos = updates.toArray( new UpdateInfo[ updates.size() ] );
      VersionConfirmationDialog.performUpdateAvailable( parent, updateInfos, exitOnLaunch );
    }
  } catch ( Exception e ) {
    // we cannot give errors
    logger.error( "The version checker encountered an error", e );
    JOptionPane.showMessageDialog( parent,
      "No update is available at this time.", "Version Update Info",
      JOptionPane.INFORMATION_MESSAGE );
  }
}
 
Example #30
Source File: AbstractSolver.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public boolean restore(File folder, String puid, boolean removeFiles) {
    sLog.debug("restore(folder="+folder+","+puid+")");
    File inXmlFile = new File(folder,getType().getPrefix() + puid + BackupFileFilter.sXmlExtension);
    
    M model = null;
    try {
        if (isRunning()) stopSolver();
        disposeNoInherit(false);

        Document document = (new SAXReader()).read(inXmlFile);
        readProperties(document);
        
        model = createModel(getProperties());
        Progress.getInstance(model).addProgressListener(new ProgressWriter(System.out));
        setInitalSolution(model);
        initSolver();

        restureCurrentSolutionFromBackup(document);
        Progress.getInstance(model).setStatus(MSG.statusReady());
        
        if (removeFiles) {
            inXmlFile.delete();
        }
        
        return true;
    } catch (Exception e) {
        sLog.error(e.getMessage(),e);
        if (model!=null) Progress.removeInstance(model);
    }
    
    return false;
}