List of usage examples for org.dom4j.io OutputFormat createCompactFormat
public static OutputFormat createCompactFormat()
From source file:com.tedi.engine.XMLOutput.java
License:Open Source License
/** * Handles functionality of formatting and writing document. * /* ww w . j a va 2 s . c om*/ * @param doc * The document * @return the cleaned document. * @throws Exception */ private String cleanDocument(Document doc) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Cleaning the document object."); } String docStr = ""; // --COMMENTED OUT 10-10-2005 // JBG---------------------------------------------------------------------------------- // if (dtd != null && dtd.length()>0) { // xmlUtils.setDocument(doc); // try { // AbstractSchemaDescriptor schema = // AbstractSchemaDescriptor.createDescriptor(absoluteDTD_URL.toString()); // schema.processSchema(doc.getRootElement().getName()); // xmlUtils.setSchema(schema); // xmlUtils.cleanDocument(); // } // catch (Exception e) { // execResults.addMessage(ExecutionResults.M_WARNING, // ExecutionResults.J2EE_TARGET_ERR, // "Error removing optional attributes/elements: " + e.getMessage()); // } // } // ---------------------------------------------------------------------------------------------------------------- cleanElement(doc.getRootElement()); StringWriter sw = new StringWriter(); OutputFormat format = isCompact ? OutputFormat.createCompactFormat() : OutputFormat.createPrettyPrint(); format.setExpandEmptyElements(false); XMLWriter writer = new XMLWriter(sw, format); writer.setMaximumAllowedCharacter(127); writer.write(doc); writer.close(); docStr = sw.toString(); if (isSuppressDocType && doc.getDocType() != null) { int ndx = docStr.indexOf("<" + doc.getRootElement().getName()); docStr = docStr.substring(ndx); } return docStr; }
From source file:com.thinkberg.moxo.dav.PropFindHandler.java
License:Apache License
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { SAXReader saxReader = new SAXReader(); try {/*from w ww . jav a 2 s.co m*/ Document propDoc = saxReader.read(request.getInputStream()); // log(propDoc); Element propFindEl = propDoc.getRootElement(); Element propEl = (Element) propFindEl.elementIterator().next(); String propElName = propEl.getName(); List<String> requestedProperties = new ArrayList<String>(); boolean ignoreValues = false; if (TAG_PROP.equals(propElName)) { for (Object id : propEl.elements()) { requestedProperties.add(((Element) id).getName()); } } else if (TAG_ALLPROP.equals(propElName)) { requestedProperties = DavResource.ALL_PROPERTIES; } else if (TAG_PROPNAMES.equals(propElName)) { requestedProperties = DavResource.ALL_PROPERTIES; ignoreValues = true; } FileObject object = getResourceManager().getFileObject(request.getPathInfo()); if (object.exists()) { // respond as XML encoded multi status response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); response.setStatus(SC_MULTI_STATUS); Document multiStatusResponse = getMultiStatusRespons(object, requestedProperties, getBaseUrl(request), getDepth(request), ignoreValues); //log(multiStatusResponse); // write the actual response XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat()); writer.write(multiStatusResponse); writer.flush(); writer.close(); } else { log("!! " + object.getName().getPath() + " NOT FOUND"); response.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (DocumentException e) { log("!! inavlid request: " + e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.thinkberg.moxo.dav.PropPatchHandler.java
License:Apache License
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = getResourceManager().getFileObject(request.getPathInfo()); try {/*from ww w . ja va2s. com*/ LockManager.getInstance().checkCondition(object, getIf(request)); } catch (LockException e) { if (e.getLocks() != null) { response.sendError(SC_LOCKED); } else { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); } return; } SAXReader saxReader = new SAXReader(); try { Document propDoc = saxReader.read(request.getInputStream()); // log(propDoc); response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); response.setStatus(SC_MULTI_STATUS); if (object.exists()) { Document resultDoc = DocumentHelper.createDocument(); Element multiStatusResponse = resultDoc.addElement("multistatus", "DAV:"); Element responseEl = multiStatusResponse.addElement("response"); try { URL url = new URL(getBaseUrl(request), URLEncoder.encode(object.getName().getPath(), "UTF-8")); log("!! " + url); responseEl.addElement("href").addText(url.toExternalForm()); } catch (Exception e) { e.printStackTrace(); } Element propstatEl = responseEl.addElement("propstat"); Element propEl = propstatEl.addElement("prop"); Element propertyUpdateEl = propDoc.getRootElement(); for (Object elObject : propertyUpdateEl.elements()) { Element el = (Element) elObject; if ("set".equals(el.getName())) { for (Object propObject : el.elements()) { setProperty(propEl, object, (Element) propObject); } } else if ("remove".equals(el.getName())) { for (Object propObject : el.elements()) { removeProperty(propEl, object, (Element) propObject); } } } propstatEl.addElement("status").addText(DavResource.STATUS_403); // log(resultDoc); // write the actual response XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat()); writer.write(resultDoc); writer.flush(); writer.close(); } else { log("!! " + object.getName().getPath() + " NOT FOUND"); response.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (DocumentException e) { log("!! inavlid request: " + e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.thinkberg.webdav.PropFindHandler.java
License:Apache License
/** * Handle a PROPFIND request.//from w ww . j a v a 2s. com * * @param request the servlet request * @param response the servlet response * @throws IOException if there is an error that cannot be handled normally */ public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { SAXReader saxReader = new SAXReader(); try { Document propDoc = saxReader.read(request.getInputStream()); logXml(propDoc); Element propFindEl = propDoc.getRootElement(); for (Object propElObject : propFindEl.elements()) { Element propEl = (Element) propElObject; if (VALID_PROPFIND_TAGS.contains(propEl.getName())) { FileObject object = VFSBackend.resolveFile(request.getPathInfo()); if (object.exists()) { // respond as XML encoded multi status response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); response.setStatus(SC_MULTI_STATUS); Document multiStatusResponse = getMultiStatusResponse(object, propEl, getBaseUrl(request), getDepth(request)); logXml(multiStatusResponse); // write the actual response XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat()); writer.write(multiStatusResponse); writer.flush(); writer.close(); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } break; } } } catch (DocumentException e) { LOG.error("invalid request: " + e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.thinkberg.webdav.PropPatchHandler.java
License:Apache License
/** * Handle a PROPPATCH request./*from www .j av a2 s . com*/ * * @param request the servlet request * @param response the servlet response * @throws IOException if there is an error that cannot be handled normally */ public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = VFSBackend.resolveFile(request.getPathInfo()); try { if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } } catch (LockException e) { response.sendError(SC_LOCKED); return; } catch (ParseException e) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } if (object.exists()) { SAXReader saxReader = new SAXReader(); try { Document propDoc = saxReader.read(request.getInputStream()); logXml(propDoc); Element propUpdateEl = propDoc.getRootElement(); List<Element> requestedProperties = new ArrayList<Element>(); for (Object elObject : propUpdateEl.elements()) { Element el = (Element) elObject; String command = el.getName(); if (AbstractDavResource.TAG_PROP_SET.equals(command) || AbstractDavResource.TAG_PROP_REMOVE.equals(command)) { for (Object propElObject : el.elements()) { for (Object propNameElObject : ((Element) propElObject).elements()) { Element propNameEl = (Element) propNameElObject; requestedProperties.add(propNameEl); } } } } // respond as XML encoded multi status response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); response.setStatus(SC_MULTI_STATUS); Document multiStatusResponse = getMultiStatusResponse(object, requestedProperties, getBaseUrl(request)); logXml(multiStatusResponse); // write the actual response XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat()); writer.write(multiStatusResponse); writer.flush(); writer.close(); } catch (DocumentException e) { LOG.error("invalid request: " + e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST); } } else { LOG.error(object.getName().getPath() + " NOT FOUND"); response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.webarch.common.io.xml.XMLEditor.java
License:Apache License
public boolean save(File outPutFile, Document document, boolean lineAble) { boolean flag = true; XMLWriter writer = null;/* w w w.j av a 2 s . c o m*/ OutputStreamWriter outputStream = null; try { outputStream = new OutputStreamWriter(new FileOutputStream(outPutFile), DAFAULT_CHARSET); final OutputFormat format = OutputFormat.createCompactFormat();//? format.setNewlines(lineAble); writer = new XMLWriter(outputStream, format); writer.write(document); writer.flush(); outputStream.close(); writer.close(); } catch (Exception ex) { log.error("?xml", ex); flag = false; } finally { try { if (null != writer) { writer.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException e) { log.error("?xml:", e); } } return flag; }
From source file:com.zimbra.cs.dav.resource.MailItemResource.java
License:Open Source License
@Override public void patchProperties(DavContext ctxt, java.util.Collection<Element> set, java.util.Collection<QName> remove) throws DavException, IOException { List<QName> reqProps = new ArrayList<QName>(); for (QName n : remove) { mDeadProps.remove(n);// w ww . j a v a 2s .com reqProps.add(n); } for (Element e : set) { QName name = e.getQName(); if (name.equals(DavElements.E_DISPLAYNAME) && (type == MailItem.Type.FOLDER || type == MailItem.Type.MOUNTPOINT)) { // rename folder try { String val = e.getText(); String uri = getUri(); Mailbox mbox = getMailbox(ctxt); mbox.rename(ctxt.getOperationContext(), mId, type, val, mFolderId); setProperty(DavElements.P_DISPLAYNAME, val); UrlNamespace.addToRenamedResource(getOwner(), uri, this); UrlNamespace.addToRenamedResource(getOwner(), uri.substring(0, uri.length() - 1), this); } catch (ServiceException se) { ctxt.getResponseProp().addPropError(DavElements.E_DISPLAYNAME, new DavException(se.getMessage(), DavProtocol.STATUS_FAILED_DEPENDENCY)); } mDeadProps.remove(name); continue; } else if (name.equals(DavElements.E_CALENDAR_COLOR) && (type == MailItem.Type.FOLDER || type == MailItem.Type.MOUNTPOINT)) { // change color String colorStr = e.getText(); Color color = new Color(colorStr.substring(0, 7)); byte col = (byte) COLOR_LIST.indexOf(colorStr); if (col >= 0) color.setColor(col); try { Mailbox mbox = getMailbox(ctxt); mbox.setColor(ctxt.getOperationContext(), new int[] { mId }, type, color); } catch (ServiceException se) { ctxt.getResponseProp().addPropError(DavElements.E_CALENDAR_COLOR, new DavException(se.getMessage(), DavProtocol.STATUS_FAILED_DEPENDENCY)); } mDeadProps.remove(name); continue; } else if (name.equals(DavElements.E_SUPPORTED_CALENDAR_COMPONENT_SET)) { // change default view @SuppressWarnings("unchecked") List<Element> elements = e.elements(DavElements.E_COMP); boolean isTodo = false; boolean isEvent = false; for (Element element : elements) { Attribute attr = element.attribute(DavElements.P_NAME); if (attr != null && CalComponent.VTODO.name().equals(attr.getValue())) { isTodo = true; } else if (attr != null && CalComponent.VEVENT.name().equals(attr.getValue())) { isEvent = true; } } if (isEvent ^ isTodo) { // we support a calendar collection of type event or todo, not both or none. Type type = (isEvent) ? Type.APPOINTMENT : Type.TASK; try { Mailbox mbox = getMailbox(ctxt); mbox.setFolderDefaultView(ctxt.getOperationContext(), mId, type); // Update the view for this collection. This collection may get cached if display name is modified. // See UrlNamespace.addToRenamedResource() if (this instanceof Collection) { ((Collection) this).view = type; } } catch (ServiceException se) { ctxt.getResponseProp().addPropError(name, new DavException(se.getMessage(), DavProtocol.STATUS_FAILED_DEPENDENCY)); } } else { ctxt.getResponseProp().addPropError(name, new DavException.CannotModifyProtectedProperty(name)); } continue; } mDeadProps.put(name, e); reqProps.add(name); } String configVal = ""; if (mDeadProps.size() > 0) { org.dom4j.Document doc = org.dom4j.DocumentHelper.createDocument(); Element top = doc.addElement(CONFIG_KEY); for (Map.Entry<QName, Element> entry : mDeadProps.entrySet()) top.add(entry.getValue().detach()); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputFormat format = OutputFormat.createCompactFormat(); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); configVal = new String(out.toByteArray(), "UTF-8"); if (configVal.length() > PROP_LENGTH_LIMIT) for (Map.Entry<QName, Element> entry : mDeadProps.entrySet()) ctxt.getResponseProp().addPropError(entry.getKey(), new DavException("prop length exceeded", DavProtocol.STATUS_INSUFFICIENT_STORAGE)); } Mailbox mbox = null; try { mbox = getMailbox(ctxt); mbox.lock.lock(); Metadata data = mbox.getConfig(ctxt.getOperationContext(), CONFIG_KEY); if (data == null) { data = new Metadata(); } data.put(Integer.toString(mId), configVal); mbox.setConfig(ctxt.getOperationContext(), CONFIG_KEY, data); } catch (ServiceException se) { for (QName qname : reqProps) ctxt.getResponseProp().addPropError(qname, new DavException(se.getMessage(), HttpServletResponse.SC_FORBIDDEN)); } finally { if (mbox != null) mbox.lock.release(); } }
From source file:cz.mzk.editor.server.fedora.utils.DocumentSaver.java
License:Open Source License
private static OutputFormat chooseOutputFormat(PrintType printType) { switch (printType) { case COMPACT: return OutputFormat.createCompactFormat(); case PRETTY://from w w w .j av a 2s . co m return OutputFormat.createPrettyPrint(); default: return OutputFormat.createCompactFormat(); } }
From source file:de.codecentric.multitool.xml.XmlLibrary.java
License:Apache License
/** * Konvertiert ein XML-Document in einen XML-String * /*from w ww . j a v a2s . co m*/ * | ${xmlString} = | Get Xml From String | ${xmlDoc} | */ public String getStringFromXml(Document document) throws IOException { OutputFormat format = OutputFormat.createCompactFormat(); format.setSuppressDeclaration(true); StringWriter writer = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(writer, format); xmlWriter.write(document); return writer.toString(); }
From source file:de.innovationgate.wgpublisher.WGACore.java
License:Open Source License
private void initDefaultSerializer() { Dom4JDriver driver = new Dom4JDriver(); OutputFormat format = OutputFormat.createCompactFormat(); format.setSuppressDeclaration(true); driver.setOutputFormat(format);/*from www. j a va 2s . c o m*/ _defaultSerializer = new XStream(driver); _defaultSerializer.setClassLoader(getLibraryLoader()); _defaultSerializer.alias("tmloption", TMLOption.class); _defaultSerializer.alias("version", Version.class); _defaultSerializer.alias("portletState", TMLPortletState.class); _defaultSerializer.registerConverter(ExpressionEngineFactory.getTMLScriptEngine()); // DOM4J Objects _defaultSerializer.registerConverter(new SingleValueConverter() { public boolean canConvert(Class arg0) { return org.dom4j.Element.class.isAssignableFrom(arg0); } public Object fromString(String arg0) { try { org.dom4j.Document doc = DocumentHelper.parseText(arg0); return doc.getRootElement(); } catch (DocumentException e) { Logger.getLogger("wga.ajax") .error("Exception deserializing DOM4J Element from TMLPortlet.SessionContext", e); return ""; } } public String toString(Object arg0) { Element elem = (Element) arg0; return elem.asXML(); } }); // Serialize TMLContext to their context path. All other info is dropped. Deserialize to a TMLContext.Serialized. _defaultSerializer.registerConverter(new SingleValueConverter() { @SuppressWarnings("rawtypes") @Override public boolean canConvert(Class arg0) { return TMLContext.class.isAssignableFrom(arg0); } @Override public String toString(Object arg0) { try { TMLContext cx = (TMLContext) arg0; return cx.getpath(); } catch (WGAPIException e) { throw new RuntimeException("Exception serializing TMLContext", e); } } @Override public Object fromString(String arg0) { return new TMLContext.Serialized(arg0); } }); // Version object _defaultSerializer.registerConverter(new SingleValueConverter() { public boolean canConvert(Class arg0) { return Version.class.isAssignableFrom(arg0); } public Object fromString(String arg0) { return new Version(arg0); } public String toString(Object arg0) { return ((Version) arg0).toString(); } }); // GSON data structures _defaultSerializer.registerConverter(new SingleValueConverter() { private Gson _gson = new GsonBuilder().create(); @Override public boolean canConvert(Class arg0) { return JsonElement.class.isAssignableFrom(arg0); } @Override public Object fromString(String arg0) { return new JsonParser().parse(arg0); } @Override public String toString(Object arg0) { return _gson.toJson((JsonElement) arg0); } }); // Serialize types not meant to be serialized to empty string, deserialize to null _defaultSerializer.registerConverter(new SingleValueConverter() { public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) { return DEFAULT_SERIALIZER_NONSERIALIZABLE_TYPES.contains(clazz); } public Object fromString(String arg0) { return null; } public String toString(Object arg0) { return ""; } }); }