Search in sources :

Example 26 with NameClassPair

use of javax.naming.NameClassPair in project aries by apache.

the class ServiceRegistryContextTest method checkThreadRetrievedViaListMethod.

/**
 * Check that the NamingEnumeration passed in has another element, which represents a java.lang.Thread
 * @param serviceList
 * @throws NamingException
 */
private void checkThreadRetrievedViaListMethod(NamingEnumeration<NameClassPair> serviceList) throws NamingException {
    assertTrue("The repository was empty", serviceList.hasMoreElements());
    NameClassPair ncp = serviceList.next();
    assertNotNull("We didn't get a service back from our lookup :(", ncp);
    assertNotNull("The object from the SR was null", ncp.getClassName());
    assertEquals("The service retrieved was not of the correct type", "java.lang.Thread", ncp.getClassName());
    assertEquals("osgi:service/java.lang.Runnable/(rubbish=smelly)", ncp.getName().toString());
}
Also used : NameClassPair(javax.naming.NameClassPair)

Example 27 with NameClassPair

use of javax.naming.NameClassPair in project platformlayer by platformlayer.

the class ITOpenLdapService method testLdap.

private void testLdap(String ldapUrl, Secret adminPassword) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    String sp = "com.sun.jndi.ldap.LdapCtxFactory";
    env.put(Context.INITIAL_CONTEXT_FACTORY, sp);
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,dc=test,dc=platformlayer,dc=org");
    env.put(Context.SECURITY_CREDENTIALS, adminPassword.plaintext());
    DirContext ctx = new InitialDirContext(env);
    NamingEnumeration results = ctx.list("dc=test,dc=platformlayer,dc=org");
    while (results.hasMore()) {
        NameClassPair sr = (NameClassPair) results.next();
        System.out.println(sr.getNameInNamespace());
    }
    ctx.close();
}
Also used : Hashtable(java.util.Hashtable) NameClassPair(javax.naming.NameClassPair) NamingEnumeration(javax.naming.NamingEnumeration) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 28 with NameClassPair

use of javax.naming.NameClassPair in project Payara by payara.

the class WebdavStatus method copyResource.

/**
 * Copy a collection.
 *
 * @param resources Resources implementation to be used
 * @param errorList Hashtable containing the list of errors which occurred
 * during the copy operation
 * @param source Path of the resource to be copied
 * @param dest Destination path
 */
private boolean copyResource(DirContext resources, Hashtable<String, Integer> errorList, String source, String dest) {
    if (debug > 1)
        log("Copy: " + source + " To: " + dest);
    Object object = null;
    try {
        object = resources.lookup(source);
    } catch (NamingException e) {
    // Ignore
    }
    if (object instanceof DirContext) {
        try {
            resources.createSubcontext(dest);
        } catch (NamingException e) {
            errorList.put(dest, WebdavStatus.SC_CONFLICT);
            return false;
        }
        try {
            NamingEnumeration<NameClassPair> enumeration = resources.list(source);
            while (enumeration.hasMoreElements()) {
                NameClassPair ncPair = enumeration.nextElement();
                String childDest = dest;
                if (!"/".equals(childDest))
                    childDest += "/";
                childDest += ncPair.getName();
                String childSrc = source;
                if (!"/".equals(childSrc))
                    childSrc += "/";
                childSrc += ncPair.getName();
                copyResource(resources, errorList, childSrc, childDest);
            }
        } catch (NamingException e) {
            errorList.put(dest, WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
    } else {
        if (object instanceof Resource) {
            try {
                resources.bind(dest, object);
            } catch (NamingException e) {
                errorList.put(source, WebdavStatus.SC_INTERNAL_SERVER_ERROR);
                return false;
            }
        } else {
            errorList.put(source, WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
    }
    return true;
}
Also used : NameClassPair(javax.naming.NameClassPair) Resource(org.apache.naming.resources.Resource) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext)

Example 29 with NameClassPair

use of javax.naming.NameClassPair in project Payara by payara.

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);
    if (path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }
    // Propfind depth
    int depth = INFINITY;
    // Propfind type
    int type = FIND_ALL_PROP;
    String depthStr = req.getHeader("Depth");
    if (depthStr == null) {
        depth = INFINITY;
    } else {
        switch(depthStr) {
            case "0":
                depth = 0;
                break;
            case "1":
                depth = 1;
                break;
            case "infinity":
                depth = INFINITY;
                break;
            default:
                break;
        }
    }
    Node propNode = null;
    if (req.getInputStream().available() > 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;
                    default:
                        break;
                }
            }
        } catch (SAXException | IOException e) {
        // Something went wrong - use the defaults.
        }
    }
    // Properties which are to be displayed.
    List<String> properties = new ArrayList<>();
    if (type == FIND_BY_PROPERTY && propNode != 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 = nodeName.indexOf(':') != -1 ? nodeName.substring(nodeName.indexOf(':') + 1) : nodeName;
                    // href is a live property which is handled differently
                    properties.add(propertyName);
                    break;
                default:
                    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);
            List<String> currentLockNullResources = lockNullResources.get(parentPath);
            if (currentLockNullResources != null) {
                for (String lockNullPath : currentLockNullResources) {
                    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(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);
                        parseLockNullProperties(req, generatedXML, lockNullPath, type, properties);
                        generatedXML.writeElement(null, "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(null, "multistatus" + generateNamespaceDeclarations(), 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<>();
        stack.push(path);
        // Stack of the objects one level below
        Stack<String> stackBelow = new Stack<>();
        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);
                List<String> currentLockNullResources = lockNullResources.get(lockPath);
                if (currentLockNullResources != null) {
                    for (String lockNullPath : currentLockNullResources) {
                        parseLockNullProperties(req, generatedXML, lockNullPath, type, properties);
                    }
                }
            }
            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;
                stackBelow = new Stack<>();
            }
            generatedXML.sendData();
        }
    }
    generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
    generatedXML.sendData();
}
Also used : InputSource(org.xml.sax.InputSource) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) DirContext(javax.naming.directory.DirContext) Document(org.w3c.dom.Document) XMLWriter(org.apache.catalina.util.XMLWriter) SAXException(org.xml.sax.SAXException) NamingException(javax.naming.NamingException) NodeList(org.w3c.dom.NodeList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) NameClassPair(javax.naming.NameClassPair)

Example 30 with NameClassPair

use of javax.naming.NameClassPair in project Payara by payara.

the class WebdavStatus method deleteCollection.

/**
 * Deletes a collection.
 *
 * @param resources 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 resources, String path, Hashtable<String, Integer> errorList) {
    if (debug > 1)
        log("Delete:" + path);
    if (path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) {
        errorList.put(path, 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;
    try {
        enumeration = resources.list(path);
    } catch (NamingException e) {
        errorList.put(path, WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    while (enumeration.hasMoreElements()) {
        NameClassPair ncPair = enumeration.nextElement();
        String childName = path;
        if (!"/".equals(childName))
            childName += "/";
        childName += ncPair.getName();
        if (isLocked(childName, ifHeader + lockTokenHeader)) {
            errorList.put(childName, WebdavStatus.SC_LOCKED);
        } else {
            try {
                Object object = resources.lookup(childName);
                if (object instanceof DirContext) {
                    deleteCollection(req, resources, childName, errorList);
                }
                try {
                    resources.unbind(childName);
                } catch (NamingException e) {
                    if (!(object instanceof DirContext)) {
                        // If it's not a collection, then it's an unknown
                        // error
                        errorList.put(childName, WebdavStatus.SC_INTERNAL_SERVER_ERROR);
                    }
                }
            } catch (NamingException e) {
                errorList.put(childName, WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }
}
Also used : NameClassPair(javax.naming.NameClassPair) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext)

Aggregations

NameClassPair (javax.naming.NameClassPair)59 NamingException (javax.naming.NamingException)27 DirContext (javax.naming.directory.DirContext)19 Test (org.junit.Test)17 HashSet (java.util.HashSet)13 Context (javax.naming.Context)11 InitialContext (javax.naming.InitialContext)10 Hashtable (java.util.Hashtable)9 NamingEnumeration (javax.naming.NamingEnumeration)8 InitialDirContext (javax.naming.directory.InitialDirContext)8 IOException (java.io.IOException)7 FileNotFoundException (java.io.FileNotFoundException)5 HashMap (java.util.HashMap)5 Resource (org.apache.naming.resources.Resource)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 OutputStreamWriter (java.io.OutputStreamWriter)4 Vector (java.util.Vector)4 CompositeName (javax.naming.CompositeName)4 File (java.io.File)3