use of javax.naming.NameClassPair in project tomcat70 by apache.
the class DefaultServlet method renderXml.
/**
* Return an InputStream to an HTML representation of the contents
* of this directory.
*
* @param contextPath Context path to which our internal paths are
* relative
*/
protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, Source xsltSource) throws IOException, ServletException {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<listing ");
sb.append(" contextPath='");
sb.append(contextPath);
sb.append("'");
sb.append(" directory='");
sb.append(cacheEntry.name);
sb.append("' ");
sb.append(" hasParent='").append(!cacheEntry.name.equals("/"));
sb.append("'>");
sb.append("<entries>");
try {
// Render the directory entries within this directory
NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name);
// rewriteUrl(contextPath) is expensive. cache result for later reuse
String rewrittenContextPath = rewriteUrl(contextPath);
while (enumeration.hasMoreElements()) {
NameClassPair ncPair = enumeration.nextElement();
String resourceName = ncPair.getName();
String trimmed = resourceName;
if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile))
continue;
if ((cacheEntry.name + trimmed).equals(contextXsltFile))
continue;
CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName);
if (!childCacheEntry.exists) {
continue;
}
sb.append("<entry");
sb.append(" type='").append((childCacheEntry.context != null) ? "dir" : "file").append("'");
sb.append(" urlPath='").append(rewrittenContextPath).append(rewriteUrl(cacheEntry.name + resourceName)).append((childCacheEntry.context != null) ? "/" : "").append("'");
if (childCacheEntry.resource != null) {
sb.append(" size='").append(renderSize(childCacheEntry.attributes.getContentLength())).append("'");
}
sb.append(" date='").append(childCacheEntry.attributes.getLastModifiedHttp()).append("'");
sb.append(">");
sb.append(RequestUtil.filter(trimmed));
if (childCacheEntry.context != null)
sb.append("/");
sb.append("</entry>");
}
} catch (NamingException e) {
// Something went wrong
throw new ServletException("Error accessing resource", e);
}
sb.append("</entries>");
String readme = getReadme(cacheEntry.context);
if (readme != null) {
sb.append("<readme><![CDATA[");
sb.append(readme);
sb.append("]]></readme>");
}
sb.append("</listing>");
// Prevent possible memory leak. Ensure Transformer and
// TransformerFactory are not loaded from the web application.
ClassLoader original;
if (Globals.IS_SECURITY_ENABLED) {
PrivilegedGetTccl pa = new PrivilegedGetTccl();
original = AccessController.doPrivileged(pa);
} else {
original = Thread.currentThread().getContextClassLoader();
}
try {
if (Globals.IS_SECURITY_ENABLED) {
PrivilegedSetTccl pa = new PrivilegedSetTccl(DefaultServlet.class.getClassLoader());
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(DefaultServlet.class.getClassLoader());
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xmlSource = new StreamSource(new StringReader(sb.toString()));
Transformer transformer = tFactory.newTransformer(xsltSource);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
StreamResult out = new StreamResult(osWriter);
transformer.transform(xmlSource, out);
osWriter.flush();
return (new ByteArrayInputStream(stream.toByteArray()));
} catch (TransformerException e) {
throw new ServletException("XSL transformer error", e);
} finally {
if (Globals.IS_SECURITY_ENABLED) {
PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(original);
}
}
}
use of javax.naming.NameClassPair in project tomcat70 by apache.
the class WebdavStatus method deleteCollection.
/**
* Deletes a collection.
*
* @param dirContext Resources implementation associated with the context
* @param path Path to the collection to be deleted
* @param errorList Contains the list of the errors which occurred
*/
private void deleteCollection(HttpServletRequest req, DirContext dirContext, String path, Hashtable<String, Integer> errorList) {
if (debug > 1)
log("Delete:" + path);
// Prevent deletion of special subdirectories
if (isSpecialPath(path)) {
errorList.put(path, Integer.valueOf(WebdavStatus.SC_FORBIDDEN));
return;
}
String ifHeader = req.getHeader("If");
if (ifHeader == null)
ifHeader = "";
String lockTokenHeader = req.getHeader("Lock-Token");
if (lockTokenHeader == null)
lockTokenHeader = "";
Enumeration<NameClassPair> enumeration = null;
try {
enumeration = dirContext.list(path);
} catch (NamingException e) {
errorList.put(path, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
return;
}
while (enumeration.hasMoreElements()) {
NameClassPair ncPair = enumeration.nextElement();
String childName = path;
if (!childName.equals("/"))
childName += "/";
childName += ncPair.getName();
if (isLocked(childName, ifHeader + lockTokenHeader)) {
errorList.put(childName, Integer.valueOf(WebdavStatus.SC_LOCKED));
} else {
try {
Object object = dirContext.lookup(childName);
if (object instanceof DirContext) {
deleteCollection(req, dirContext, childName, errorList);
}
try {
dirContext.unbind(childName);
} catch (NamingException e) {
if (!(object instanceof DirContext)) {
// If it's not a collection, then it's an unknown
// error
errorList.put(childName, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
}
}
} catch (NamingException e) {
errorList.put(childName, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
}
}
}
}
use of javax.naming.NameClassPair in project tomcat70 by apache.
the class WebdavStatus method doPropfind.
/**
* PROPFIND Method.
*/
protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!listings) {
// Get allowed methods
StringBuilder methodsAllowed = determineMethodsAllowed(resources, req);
resp.addHeader("Allow", methodsAllowed.toString());
resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
return;
}
String path = getRelativePath(req);
if (path.endsWith("/"))
path = path.substring(0, path.length() - 1);
// Properties which are to be displayed.
Vector<String> properties = null;
// Propfind depth
int depth = maxDepth;
// Propfind type
int type = FIND_ALL_PROP;
String depthStr = req.getHeader("Depth");
if (depthStr == null) {
depth = maxDepth;
} else {
if (depthStr.equals("0")) {
depth = 0;
} else if (depthStr.equals("1")) {
depth = 1;
} else if (depthStr.equals("infinity")) {
depth = maxDepth;
}
}
Node propNode = null;
if (req.getContentLength() > 0) {
DocumentBuilder documentBuilder = getDocumentBuilder();
try {
Document document = documentBuilder.parse(new InputSource(req.getInputStream()));
// Get the root element of the document
Element rootElement = document.getDocumentElement();
NodeList childList = rootElement.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
Node currentNode = childList.item(i);
switch(currentNode.getNodeType()) {
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE:
if (currentNode.getNodeName().endsWith("prop")) {
type = FIND_BY_PROPERTY;
propNode = currentNode;
}
if (currentNode.getNodeName().endsWith("propname")) {
type = FIND_PROPERTY_NAMES;
}
if (currentNode.getNodeName().endsWith("allprop")) {
type = FIND_ALL_PROP;
}
break;
}
}
} catch (SAXException e) {
// Something went wrong - bad request
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
} catch (IOException e) {
// Something went wrong - bad request
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
return;
}
}
if (type == FIND_BY_PROPERTY) {
properties = new Vector<String>();
// propNode must be non-null if type == FIND_BY_PROPERTY
@SuppressWarnings("null") NodeList childList = propNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
Node currentNode = childList.item(i);
switch(currentNode.getNodeType()) {
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE:
String nodeName = currentNode.getNodeName();
String propertyName = null;
if (nodeName.indexOf(':') != -1) {
propertyName = nodeName.substring(nodeName.indexOf(':') + 1);
} else {
propertyName = nodeName;
}
// href is a live property which is handled differently
properties.addElement(propertyName);
break;
}
}
}
boolean exists = true;
Object object = null;
try {
object = resources.lookup(path);
} catch (NamingException e) {
exists = false;
int slash = path.lastIndexOf('/');
if (slash != -1) {
String parentPath = path.substring(0, slash);
Vector<String> currentLockNullResources = lockNullResources.get(parentPath);
if (currentLockNullResources != null) {
Enumeration<String> lockNullResourcesList = currentLockNullResources.elements();
while (lockNullResourcesList.hasMoreElements()) {
String lockNullPath = lockNullResourcesList.nextElement();
if (lockNullPath.equals(path)) {
resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
resp.setContentType("text/xml; charset=UTF-8");
// Create multistatus object
XMLWriter generatedXML = new XMLWriter(resp.getWriter());
generatedXML.writeXMLHeader();
generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING);
parseLockNullProperties(req, generatedXML, lockNullPath, type, properties);
generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);
generatedXML.sendData();
return;
}
}
}
}
}
if (!exists) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
return;
}
resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
resp.setContentType("text/xml; charset=UTF-8");
// Create multistatus object
XMLWriter generatedXML = new XMLWriter(resp.getWriter());
generatedXML.writeXMLHeader();
generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING);
if (depth == 0) {
parseProperties(req, generatedXML, path, type, properties);
} else {
// The stack always contains the object of the current level
Stack<String> stack = new Stack<String>();
stack.push(path);
// Stack of the objects one level below
Stack<String> stackBelow = new Stack<String>();
while ((!stack.isEmpty()) && (depth >= 0)) {
String currentPath = stack.pop();
parseProperties(req, generatedXML, currentPath, type, properties);
try {
object = resources.lookup(currentPath);
} catch (NamingException e) {
continue;
}
if ((object instanceof DirContext) && (depth > 0)) {
try {
NamingEnumeration<NameClassPair> enumeration = resources.list(currentPath);
while (enumeration.hasMoreElements()) {
NameClassPair ncPair = enumeration.nextElement();
String newPath = currentPath;
if (!(newPath.endsWith("/")))
newPath += "/";
newPath += ncPair.getName();
stackBelow.push(newPath);
}
} catch (NamingException e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
return;
}
// Displaying the lock-null resources present in that
// collection
String lockPath = currentPath;
if (lockPath.endsWith("/"))
lockPath = lockPath.substring(0, lockPath.length() - 1);
Vector<String> currentLockNullResources = lockNullResources.get(lockPath);
if (currentLockNullResources != null) {
Enumeration<String> lockNullResourcesList = currentLockNullResources.elements();
while (lockNullResourcesList.hasMoreElements()) {
String lockNullPath = lockNullResourcesList.nextElement();
parseLockNullProperties(req, generatedXML, lockNullPath, type, properties);
}
}
}
if (stack.isEmpty()) {
depth--;
stack = stackBelow;
stackBelow = new Stack<String>();
}
generatedXML.sendData();
}
}
generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);
generatedXML.sendData();
}
use of javax.naming.NameClassPair in project activemq-artemis by apache.
the class SaslKrb5LDAPSecurityTest method testRunning.
@Test
public void testRunning() throws Exception {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
DirContext ctx = new InitialDirContext(env);
HashSet<String> set = new HashSet<>();
NamingEnumeration<NameClassPair> list = ctx.list("ou=system");
while (list.hasMore()) {
NameClassPair ncp = list.next();
set.add(ncp.getName());
}
Assert.assertTrue(set.contains("uid=admin"));
Assert.assertTrue(set.contains("ou=users"));
Assert.assertTrue(set.contains("ou=groups"));
Assert.assertTrue(set.contains("ou=configuration"));
Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));
ctx.close();
}
use of javax.naming.NameClassPair in project activemq-artemis by apache.
the class LDAPSecurityTest method testRunning.
@Test
public void testRunning() throws Exception {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
DirContext ctx = new InitialDirContext(env);
HashSet<String> set = new HashSet<>();
NamingEnumeration<NameClassPair> list = ctx.list("ou=system");
while (list.hasMore()) {
NameClassPair ncp = list.next();
set.add(ncp.getName());
}
Assert.assertTrue(set.contains("uid=admin"));
Assert.assertTrue(set.contains("ou=users"));
Assert.assertTrue(set.contains("ou=groups"));
Assert.assertTrue(set.contains("ou=configuration"));
Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));
ctx.close();
}
Aggregations