use of org.dom4j.io.XMLWriter in project uPortal by Jasig.
the class RDBMDistributedLayoutStore method getExportLayoutDom.
private org.dom4j.Element getExportLayoutDom(IPerson person, IUserProfile profile) {
if (!this.layoutExistsForUser(person)) {
return null;
}
org.dom4j.Document layoutDoc = null;
try {
final Document layoutDom = this._safeGetUserLayout(person, profile);
person.setAttribute(Constants.PLF, layoutDom);
layoutDoc = this.reader.get().read(layoutDom);
} catch (final Throwable t) {
final String msg = "Unable to obtain layout & profile for user '" + person.getUserName() + "', profileId " + profile.getProfileId();
throw new RuntimeException(msg, t);
}
if (logger.isDebugEnabled()) {
// Write out this version of the layout to the log for dev purposes...
final StringWriter str = new StringWriter();
final XMLWriter xml = new XMLWriter(str, new OutputFormat(" ", true));
try {
xml.write(layoutDoc);
xml.close();
} catch (final Throwable t) {
throw new RuntimeException("Failed to write the layout for user '" + person.getUserName() + "' to the DEBUG log", t);
}
logger.debug("Layout for user: {}\n{}", person.getUserName(), str.getBuffer().toString());
}
if (isLayoutCorrupt(layoutDoc)) {
logger.warn("Layout for user: {} is corrupt; layout structures will not be exported.", person.getUserName());
return null;
}
/*
* Clean up the DOM for export.
*/
// (1) Add structure & theme attributes...
final int structureStylesheetId = profile.getStructureStylesheetId();
this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, structureStylesheetId, "structure");
final int themeStylesheetId = profile.getThemeStylesheetId();
this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, themeStylesheetId, "theme");
// (2) Remove locale info...
final Iterator<org.dom4j.Attribute> locale = (Iterator<org.dom4j.Attribute>) layoutDoc.selectNodes("//@locale").iterator();
while (locale.hasNext()) {
final org.dom4j.Attribute loc = locale.next();
loc.getParent().remove(loc);
}
// (3) Scrub unnecessary channel information...
for (final Iterator<org.dom4j.Element> orphanedChannels = (Iterator<org.dom4j.Element>) layoutDoc.selectNodes("//channel[@fname = '']").iterator(); orphanedChannels.hasNext(); ) {
// These elements represent UP_LAYOUT_STRUCT rows where the
// CHAN_ID field was not recognized by ChannelRegistryStore;
// best thing to do is remove the elements...
final org.dom4j.Element ch = orphanedChannels.next();
ch.getParent().remove(ch);
}
final List<String> channelAttributeWhitelist = Arrays.asList(new String[] { "fname", "unremovable", "hidden", "immutable", "ID", "dlm:plfID", "dlm:moveAllowed", "dlm:deleteAllowed" });
final Iterator<org.dom4j.Element> channels = (Iterator<org.dom4j.Element>) layoutDoc.selectNodes("//channel").iterator();
while (channels.hasNext()) {
final org.dom4j.Element oldCh = channels.next();
final org.dom4j.Element parent = oldCh.getParent();
final org.dom4j.Element newCh = this.fac.createElement("channel");
for (final String aName : channelAttributeWhitelist) {
final org.dom4j.Attribute a = (org.dom4j.Attribute) oldCh.selectSingleNode("@" + aName);
if (a != null) {
newCh.addAttribute(a.getQName(), a.getValue());
}
}
parent.elements().add(parent.elements().indexOf(oldCh), newCh);
parent.remove(oldCh);
}
// (4) Convert internal DLM noderefs to external form (pathrefs)...
for (final Iterator<org.dom4j.Attribute> origins = (Iterator<org.dom4j.Attribute>) layoutDoc.selectNodes("//@dlm:origin").iterator(); origins.hasNext(); ) {
final org.dom4j.Attribute org = origins.next();
final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef((String) person.getAttribute(IPerson.USERNAME), org.getValue(), layoutDoc.getRootElement());
if (dlmPathref != null) {
// Change the value only if we have a valid pathref...
org.setValue(dlmPathref.toString());
} else {
if (logger.isWarnEnabled()) {
logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", org.getUniquePath(), person.getAttribute(IPerson.USERNAME), org.getValue());
}
}
}
for (final Iterator<org.dom4j.Attribute> it = (Iterator<org.dom4j.Attribute>) layoutDoc.selectNodes("//@dlm:target").iterator(); it.hasNext(); ) {
final org.dom4j.Attribute target = it.next();
final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef((String) person.getAttribute(IPerson.USERNAME), target.getValue(), layoutDoc.getRootElement());
if (dlmPathref != null) {
// Change the value only if we have a valid pathref...
target.setValue(dlmPathref.toString());
} else {
if (logger.isWarnEnabled()) {
logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", target.getUniquePath(), person.getAttribute(IPerson.USERNAME), target.getValue());
}
}
}
for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layoutDoc.selectNodes("//dlm:*/@name").iterator(); names.hasNext(); ) {
final org.dom4j.Attribute n = names.next();
if (n.getValue() == null || n.getValue().trim().length() == 0) {
// don't send a false WARNING.
continue;
}
final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef((String) person.getAttribute(IPerson.USERNAME), n.getValue(), layoutDoc.getRootElement());
if (dlmPathref != null) {
// Change the value only if we have a valid pathref...
n.setValue(dlmPathref.toString());
// These *may* have fnames...
if (dlmPathref.getPortletFname() != null) {
n.getParent().addAttribute("fname", dlmPathref.getPortletFname());
}
} else {
if (logger.isWarnEnabled()) {
logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", n.getUniquePath(), person.getAttribute(IPerson.USERNAME), n.getValue());
}
}
}
// Remove synthetic Ids, but from non-fragment owners only...
if (!this.isFragmentOwner(person)) {
// (5) Remove dlm:plfID...
for (final Iterator<org.dom4j.Attribute> plfid = (Iterator<org.dom4j.Attribute>) layoutDoc.selectNodes("//@dlm:plfID").iterator(); plfid.hasNext(); ) {
final org.dom4j.Attribute plf = plfid.next();
plf.getParent().remove(plf);
}
// (6) Remove database Ids...
for (final Iterator<org.dom4j.Attribute> ids = (Iterator<org.dom4j.Attribute>) layoutDoc.selectNodes("//@ID").iterator(); ids.hasNext(); ) {
final org.dom4j.Attribute a = ids.next();
a.getParent().remove(a);
}
}
return layoutDoc.getRootElement();
}
use of org.dom4j.io.XMLWriter in project mybatis-daoj by HuQingmiao.
the class XmlUtil method write.
/**
* 将XML文档写入指定的文件.
*
* @param document XML文档
* @param fileName 文件名
* @param format 输出格式, 参考常量XmlUtil.FORMAT_GBK_PRETTY,
* XmlUtil.FORMAT_UTF_PRETTY等
* @throws java.io.IOException
*/
public static void write(Document document, String fileName, OutputFormat format) throws IOException {
XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
writer.write(document);
writer.flush();
writer.close();
}
use of org.dom4j.io.XMLWriter in project tdi-studio-se by Talend.
the class ComponentFolderManager method writeXMLContent.
/**
* DOC slanglois Comment method "writeXMLContent".
*
* @param iFile
* @param document
* @param enCode
* @throws CoreException
*/
private void writeXMLContent(IFile iFile, Document document, String enCode) throws CoreException {
PrintWriter pw = null;
XMLWriter writer = null;
byte[] byteArray = null;
// get xml content as inputstream
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = tf.newTransformer();
} catch (TransformerConfigurationException e1) {
// e1.printStackTrace();
org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
}
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, enCode);
//$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
ByteArrayOutputStream sw = new ByteArrayOutputStream();
pw = new PrintWriter(sw);
StreamResult result = new StreamResult(pw);
try {
transformer.transform(source, result);
} catch (TransformerException e1) {
// e1.printStackTrace();
org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
}
try {
sw.flush();
} catch (IOException e1) {
// e1.printStackTrace();
org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
} finally {
if (pw != null) {
pw.close();
}
}
byteArray = sw.toByteArray();
// format the xml content
SAXReader saxReader = new SAXReader();
org.dom4j.Document dom4jDocument = null;
try {
dom4jDocument = saxReader.read(new ByteArrayInputStream(byteArray));
} catch (DocumentException e1) {
// e1.printStackTrace();
org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
}
/** format the output like the webBrowser */
OutputFormat format = OutputFormat.createPrettyPrint();
/** give the xml encoding */
format.setEncoding(enCode);
sw = new ByteArrayOutputStream();
try {
writer = new XMLWriter(sw, format);
} catch (UnsupportedEncodingException e1) {
// e1.printStackTrace();
org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
}
try {
writer.write(dom4jDocument);
writer.flush();
} catch (IOException e1) {
// e1.printStackTrace();
org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
// e.printStackTrace();
org.talend.componentdesigner.exception.ExceptionHandler.process(e);
}
}
}
byteArray = sw.toByteArray();
// write content
iFile.setContents(new ByteArrayInputStream(byteArray), true, false, null);
}
use of org.dom4j.io.XMLWriter in project cpsolver by UniTime.
the class IdConvertor method save.
/**
* Save id conversion file.
* @param file id file to save
*/
public void save(File file) {
file.getParentFile().mkdirs();
Document document = DocumentHelper.createDocument();
Element root = document.addElement("id-convertor");
synchronized (iConversion) {
for (Map.Entry<String, HashMap<String, String>> entry : iConversion.entrySet()) {
String type = entry.getKey();
HashMap<String, String> conversion = entry.getValue();
Element convEl = root.addElement(type);
for (Map.Entry<String, String> idConv : conversion.entrySet()) {
convEl.addElement("conv").addAttribute("old", idConv.getKey()).addAttribute("new", idConv.getValue());
}
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
(new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
fos.flush();
fos.close();
fos = null;
} catch (Exception e) {
sLogger.error("Unable to save id conversions, reason: " + e.getMessage(), e);
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
use of org.dom4j.io.XMLWriter in project cpsolver by UniTime.
the class Test method saveInfoToXML.
/** Save solution info as XML
* @param solution current solution
* @param extra solution extra info
* @param file file to write
**/
public static void saveInfoToXML(Solution<Request, Enrollment> solution, Map<String, String> extra, File file) {
FileOutputStream fos = null;
try {
Document document = DocumentHelper.createDocument();
document.addComment("Solution Info");
Element root = document.addElement("info");
TreeSet<Map.Entry<String, String>> entrySet = new TreeSet<Map.Entry<String, String>>(new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
return e1.getKey().compareTo(e2.getKey());
}
});
entrySet.addAll(solution.getExtendedInfo().entrySet());
if (extra != null)
entrySet.addAll(extra.entrySet());
for (Map.Entry<String, String> entry : entrySet) {
root.addElement("property").addAttribute("name", entry.getKey()).setText(entry.getValue());
}
fos = new FileOutputStream(file);
(new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
fos.flush();
fos.close();
fos = null;
} catch (Exception e) {
sLog.error("Unable to save info, reason: " + e.getMessage(), e);
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
Aggregations