List of usage examples for org.dom4j Element getText
String getText();
From source file:com.zimbra.cs.dav.property.ResourceProperty.java
License:Open Source License
public ResourceProperty(Element elem) { this(elem.getQName()); mValue = elem.getText(); for (Object o : elem.elements()) { if (o instanceof Element) { mChildren.add((Element) o); }/*from w ww . java 2 s . c o m*/ } }
From source file:com.zimbra.cs.dav.resource.AbstractCalendarProxy.java
License:Open Source License
private Account hrefToAccount(DavContext ctxt, Element href) { String principalPath = href.getText(); DavResource principal = null;// w ww .j a va 2s .com try { principal = UrlNamespace.getPrincipalAtUrl(ctxt, principalPath); } catch (DavException e) { ZimbraLog.dav.warn("can't find principal at %s", principalPath); return null; } if (!(principal instanceof User)) { ZimbraLog.dav.warn("not a user principal path %s", principalPath); return null; } return ((User) principal).getAccount(); }
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);//from www . j a v a 2 s .co m 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:com.zimbra.cs.dav.service.DavServlet.java
License:Open Source License
private boolean isProxyRequest(DavContext ctxt, DavMethod m) throws IOException, DavException, ServiceException { Provisioning prov = Provisioning.getInstance(); ItemId target = null;//w w w .j av a 2 s. co m String extraPath = null; String requestPath = ctxt.getPath(); try { if (ctxt.getUser() == null) { return false; } if (requestPath == null || requestPath.length() < 2) { return false; } Account account = prov.getAccountByName(ctxt.getUser()); if (account == null) { return false; } Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(account); Pair<Folder, String> match = mbox.getFolderByPathLongestMatch(ctxt.getOperationContext(), Mailbox.ID_FOLDER_USER_ROOT, requestPath); Folder targetFolder = match.getFirst(); if (!(targetFolder instanceof Mountpoint)) { return false; } Mountpoint mp = (Mountpoint) targetFolder; target = new ItemId(mp.getOwnerId(), mp.getRemoteId()); extraPath = match.getSecond(); } catch (ServiceException e) { ZimbraLog.dav.debug("can't get path", e); return false; } // we don't proxy zero depth PROPFIND, and all PROPPATCH on mountpoints, // because the mountpoint object contains WebDAV properties that are // private to the user. // we also don't proxy DELETE on a mountpoint. if (extraPath == null && (m.getName().equals(PropFind.PROPFIND) && ctxt.getDepth() == DavContext.Depth.zero || m.getName().equals(PropPatch.PROPPATCH) || m.getName().equals(Delete.DELETE))) { return false; } String prefix = ctxt.getPath(); if (extraPath != null) { prefix = prefix.substring(0, prefix.indexOf(extraPath)); } prefix = HttpUtil.urlEscape(DAV_PATH + "/" + ctxt.getUser() + prefix); if (!prefix.endsWith("/")) { prefix += "/"; } // make sure the target account exists. Account acct = prov.getAccountById(target.getAccountId()); if (acct == null) { return false; } Server server = prov.getServer(acct); if (server == null) { return false; } // get the path to the target mail item AuthToken authToken = AuthProvider.getAuthToken(ctxt.getAuthAccount()); ZMailbox.Options zoptions = new ZMailbox.Options(authToken.toZAuthToken(), AccountUtil.getSoapUri(acct)); zoptions.setNoSession(true); zoptions.setTargetAccount(target.getAccountId()); zoptions.setTargetAccountBy(Key.AccountBy.id); ZMailbox zmbx = ZMailbox.getMailbox(zoptions); ZFolder f = zmbx.getFolderById("" + target.toString()); if (f == null) { return false; } String path = f.getPath(); String newPrefix = HttpUtil.urlEscape(DAV_PATH + "/" + acct.getName() + f.getPath()); if (ctxt.hasRequestMessage()) { // replace the path in <href> of the request with the path to the target mail item. Document req = ctxt.getRequestMessage(); for (Object hrefObj : req.getRootElement().elements(DavElements.E_HREF)) { if (!(hrefObj instanceof Element)) { continue; } Element href = (Element) hrefObj; String v = href.getText(); // prefix matching is not as straightforward as we have jetty redirect from /dav to /home/dav. href.setText(newPrefix + "/" + v.substring(v.lastIndexOf('/') + 1)); } } // build proxy request String url = getProxyUrl(ctxt.getRequest(), server, DAV_PATH) + HttpUtil.urlEscape("/" + acct.getName() + path + "/" + (extraPath == null ? "" : extraPath)); HttpState state = new HttpState(); authToken.encode(state, false, server.getAttr(Provisioning.A_zimbraServiceHostname)); HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); client.setState(state); HttpMethod method = m.toHttpMethod(ctxt, url); method.setRequestHeader(new Header(DavProtocol.HEADER_USER_AGENT, "Zimbra-DAV/" + BuildInfo.VERSION)); if (ZimbraLog.dav.isDebugEnabled()) { Enumeration<String> headers = ctxt.getRequest().getHeaderNames(); while (headers.hasMoreElements()) { String hdr = headers.nextElement(); if (!PROXY_REQUEST_HEADERS.contains(hdr) && !IGNORABLE_PROXY_REQUEST_HEADERS.contains(hdr)) { ZimbraLog.dav.debug( "Dropping header(s) with name [%s] from proxy request (not in PROXY_REQUEST_HEADERS)", hdr); } } } for (String h : PROXY_REQUEST_HEADERS) { String hval = ctxt.getRequest().getHeader(h); if (hval != null) { method.addRequestHeader(h, hval); } } int statusCode = HttpClientUtil.executeMethod(client, method); if (ZimbraLog.dav.isDebugEnabled()) { for (Header hval : method.getResponseHeaders()) { String hdrName = hval.getName(); if (!PROXY_RESPONSE_HEADERS.contains(hdrName) && !IGNORABLE_PROXY_RESPONSE_HEADERS.contains(hdrName)) { ZimbraLog.dav.debug("Dropping header [%s] from proxy response (not in PROXY_RESPONSE_HEADERS)", hval); } } } for (String h : PROXY_RESPONSE_HEADERS) { for (Header hval : method.getResponseHeaders(h)) { String hdrValue = hval.getValue(); if (DavProtocol.HEADER_LOCATION.equals(h)) { int pfxLastSlashPos = prefix.lastIndexOf('/'); int lastSlashPos = hdrValue.lastIndexOf('/'); if ((lastSlashPos > 0) && (pfxLastSlashPos > 0)) { hdrValue = prefix.substring(0, pfxLastSlashPos) + hdrValue.substring(lastSlashPos); ZimbraLog.dav.debug("Original [%s] from proxy response new value '%s'", hval, hdrValue); } } ctxt.getResponse().addHeader(h, hdrValue); } } ctxt.getResponse().setStatus(statusCode); ctxt.setStatus(statusCode); try (InputStream in = method.getResponseBodyAsStream()) { switch (statusCode) { case DavProtocol.STATUS_MULTI_STATUS: // rewrite the <href> element in the response to point to local mountpoint. try { Document response = W3cDomUtil.parseXMLToDom4jDocUsingSecureProcessing(in); Element top = response.getRootElement(); for (Object responseObj : top.elements(DavElements.E_RESPONSE)) { if (!(responseObj instanceof Element)) { continue; } Element href = ((Element) responseObj).element(DavElements.E_HREF); String v = href.getText(); v = URLDecoder.decode(v); // Bug:106438, because v contains URL encoded value(%40) for '@' the comparison fails if (v.startsWith(newPrefix)) { href.setText(prefix + v.substring(newPrefix.length() + 1)); } } if (ZimbraLog.dav.isDebugEnabled()) { ZimbraLog.dav.debug("PROXY RESPONSE:\n%s", new String(DomUtil.getBytes(response), "UTF-8")); } DomUtil.writeDocumentToStream(response, ctxt.getResponse().getOutputStream()); ctxt.responseSent(); } catch (XmlParseException e) { ZimbraLog.dav.warn("proxy request failed", e); return false; } break; default: if (in != null) { ByteUtil.copy(in, true, ctxt.getResponse().getOutputStream(), false); } ctxt.responseSent(); break; } return true; } }
From source file:com.zimbra.cs.dav.service.method.AclReports.java
License:Open Source License
private ArrayList<DavResource> getMatchingResources(DavContext ctxt, Element query) throws DavException, ServiceException { // needs to be /principals/users, or apply-to-principal-collection-set is set. ArrayList<DavResource> ret = new ArrayList<DavResource>(); boolean applyToPrincipalCollection = query.element(DavElements.E_APPLY_TO_PRINCIPAL_COLLECTION_SET) != null; String path = ctxt.getUri();//from w w w . j ava2 s .c o m if (!applyToPrincipalCollection && !path.startsWith(UrlNamespace.PRINCIPALS_PATH)) return ret; // apple hack to do user / resource search GalSearchType type = GalSearchType.all; String queryType = query.attributeValue("type"); if (queryType != null) { if (queryType.compareToIgnoreCase("INDIVIDUAL") == 0) type = GalSearchType.account; else if (queryType.compareToIgnoreCase("RESOURCE") == 0) type = GalSearchType.resource; } @SuppressWarnings("unchecked") List propSearch = query.elements(DavElements.E_PROPERTY_SEARCH); for (Object obj : propSearch) { if (!(obj instanceof Element)) continue; Element ps = (Element) obj; Element prop = ps.element(DavElements.E_PROP); Element match = ps.element(DavElements.E_MATCH); if (prop != null && match != null) { Element e = (Element) prop.elements().get(0); ret.addAll(getMatchingPrincipals(ctxt, e.getQName(), match.getText(), type)); } } return ret; }
From source file:com.zimbra.cs.dav.service.method.ExpandProperty.java
License:Open Source License
/** * @param rs - the requested resource// w w w. ja v a 2 s . c om * @param elem - specification of what should be expanded - either the top level {@code <DAV:expand-property>} * element or a descendant {@code <DAV:property>} element * @param resp - the target {@code <DAV:response>} element */ private void expandProperties(DavContext ctxt, DavResource rs, Element elem, Element resp) { rs.getProperty(DavElements.E_HREF).toElement(ctxt, resp, false); @SuppressWarnings("rawtypes") Iterator iter = elem.elementIterator(DavElements.E_PROPERTY); PropStat propstat = new PropStat(); while (iter.hasNext()) { Element property = (Element) iter.next(); Prop p = new Prop(property); ResourceProperty rp = rs.getProperty(p.getQName()); if (rp == null) { if (!ctxt.isBrief()) propstat.add(p.getQName(), null, HttpServletResponse.SC_NOT_FOUND); } else { @SuppressWarnings("rawtypes") Iterator subProps = property.elementIterator(); if (subProps.hasNext()) { PropStat sub = new PropStat(); sub.add(rp); Element subElem = DocumentHelper.createElement(DavElements.E_RESPONSE); sub.toResponse(ctxt, subElem, false); @SuppressWarnings("rawtypes") Iterator subPropstats = subElem.elementIterator(DavElements.E_PROPSTAT); while (subPropstats.hasNext()) { Element subPropstat = (Element) subPropstats.next(); Element status = subPropstat.element(DavElements.E_STATUS); if (!status.getText().equals(DavResponse.sStatusTextMap.get(HttpServletResponse.SC_OK))) continue; Element prop = subPropstat.element(DavElements.E_PROP); if (prop == null) continue; prop = prop.element(p.getQName()); if (prop == null) continue; @SuppressWarnings("rawtypes") Iterator hrefs = prop.elementIterator(DavElements.E_HREF); if (!hrefs.hasNext()) { propstat.add(rp); // need to say which property, even if the list is empty } else { while (hrefs.hasNext()) { Element href = (Element) hrefs.next(); String url = href.getText(); if (url == null) continue; try { url = URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { ZimbraLog.dav.warn("can't decode url %s", url, e); } try { DavResource target = UrlNamespace.getResourceAtUrl(ctxt, url); Element targetElem = DocumentHelper.createElement(DavElements.E_RESPONSE); expandProperties(ctxt, target, property, targetElem); propstat.add(rp.getName(), targetElem); } catch (DavException e) { ZimbraLog.dav.warn("can't find resource for " + url, e); } } } } } else { propstat.add(rp); } } } propstat.toResponse(ctxt, resp, false); }
From source file:com.zimbra.cs.dav.service.method.Lock.java
License:Open Source License
@Override public void handle(DavContext ctxt) throws DavException, IOException, ServiceException { LockMgr lockmgr = LockMgr.getInstance(); LockMgr.Lock lock = null;//from www.j av a 2s. c om if (ctxt.hasRequestMessage()) { DavContext.Depth depth = ctxt.getDepth(); if (depth == Depth.one) throw new DavException("invalid depth", HttpServletResponse.SC_BAD_REQUEST, null); String d = (depth == Depth.zero) ? "0" : depth.toString(); LockMgr.LockScope scope = LockScope.shared; LockMgr.LockType type = LockType.write; Document req = ctxt.getRequestMessage(); Element top = req.getRootElement(); if (!top.getName().equals(DavElements.P_LOCKINFO)) throw new DavException("msg " + top.getName() + " not allowed in LOCK", HttpServletResponse.SC_BAD_REQUEST, null); Element e = top.element(DavElements.E_LOCKSCOPE); @SuppressWarnings("unchecked") List<Element> ls = e.elements(); for (Element v : ls) { if (v.getQName().equals(DavElements.E_EXCLUSIVE)) scope = LockScope.exclusive; else if (v.getQName().equals(DavElements.E_SHARED)) scope = LockScope.shared; else throw new DavException("unrecognized scope element " + v.toString(), HttpServletResponse.SC_BAD_REQUEST, null); } e = top.element(DavElements.E_LOCKTYPE); @SuppressWarnings("unchecked") List<Element> lt = e.elements(); for (Element v : lt) { if (v.getQName().equals(DavElements.E_WRITE)) type = LockType.write; else throw new DavException("unrecognized type element " + v.toString(), HttpServletResponse.SC_BAD_REQUEST, null); } String owner; e = top.element(DavElements.E_OWNER); if (e != null && e.elementIterator(DavElements.E_HREF).hasNext()) { Element ownerElem = (Element) e.elementIterator(DavElements.E_HREF).next(); owner = ownerElem.getText(); } else { owner = ctxt.getAuthAccount().getName(); } lock = lockmgr.createLock(ctxt, owner, ctxt.getUri(), type, scope, d); ctxt.getResponse().addHeader(DavProtocol.HEADER_LOCK_TOKEN, lock.toLockTokenHeader()); } else { // refresh lock String token = ctxt.getRequest().getHeader(DavProtocol.HEADER_IF); if (token == null) { throw new DavException("no request body", HttpServletResponse.SC_BAD_REQUEST, null); } token = token.trim(); int len = token.length(); if (token.charAt(0) == '(' && token.charAt(len - 1) == ')') { token = token.substring(1, len - 1); } List<LockMgr.Lock> locks = lockmgr.getLocks(ctxt.getUri()); for (LockMgr.Lock l : locks) { if (l.token.equals(LockMgr.Lock.parseLockTokenHeader(token))) { l.extendExpiration(); lock = l; break; } } if (lock == null) { throw new DavException("Lock does not exist", HttpServletResponse.SC_PRECONDITION_FAILED, null); } } ctxt.getDavResponse().addProperty(ctxt, new LockDiscovery(lock)); ctxt.setStatus(HttpServletResponse.SC_OK); sendResponse(ctxt); }
From source file:condorclient.utilities.XMLHandler.java
public void parserXML(String strXML) { SAXReader reader = new SAXReader(); StringReader sr = new StringReader(strXML); InputSource is = new InputSource(sr); try {// w w w . jav a 2s.co m Document document = reader.read(is); Element root = document.getRootElement(); //get element List<Element> jobList = root.elements("Job"); List<Element> itemList = jobList.get(0).elements("item"); for (int i = 0; i < itemList.size(); i++) { Element element = itemList.get(i); String about = element.attributeValue("about"); System.out.println("about = " + about); //get all element List<Element> childList = element.elements(); for (int j = 0; j < childList.size(); j++) { Element e = childList.get(j); System.out.println(e.getName() + "=" + e.getText()); } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:condorclient.utilities.XMLHandler.java
public String getSendFilesDir() { SAXReader reader = new SAXReader(); Document doc = null;//from w ww. ja v a 2 s . c o m try { doc = reader.read(file); } catch (DocumentException ex) { Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex); } // XML?String String xmlStr = doc.asXML(); //System.out.println("xmlStr:" + xmlStr); StringReader sr = new StringReader(xmlStr); InputSource is = new InputSource(sr); String name = null; String path = null; try { Document document = reader.read(is); Element root = document.getRootElement(); //get element List<Element> jobList = root.elements("Job"); List<Element> itemList = jobList.get(0).elements("item"); Element element = itemList.get(0); List<Element> childList = element.elements(); Element eName = childList.get(0); Element ePath = childList.get(1); name = eName.getText(); path = ePath.getText(); System.out.println(eName.getName() + "=" + eName.getText()); System.out.println(ePath.getName() + "=" + ePath.getText()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } // return path + name; return path; }
From source file:condorclient.utilities.XMLHandler.java
public void parserXMLbyXPath(String strXML) { SAXReader reader = new SAXReader(); StringReader sr = new StringReader(strXML); InputSource is = new InputSource(sr); try {/*w w w . jav a 2s . com*/ Document document = reader.read(is); List list = document.selectNodes("/root/Job/item"); for (int i = 0; i < list.size(); i++) { Element e = (Element) list.get(i); System.out.println("item=" + e.attributeValue("about")); List list1 = e.selectNodes("./*"); for (int j = 0; j < list1.size(); j++) { Element e1 = (Element) list1.get(j); System.out.println(e1.getName() + "=" + e1.getText()); } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }