Example usage for javax.naming.directory DirContext lookup

List of usage examples for javax.naming.directory DirContext lookup

Introduction

In this page you can find the example usage for javax.naming.directory DirContext lookup.

Prototype

public Object lookup(Name name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * LOCK Method.//from w  w  w .  ja  v  a  2s. c  o m
 *
 * @param req  Description of the Parameter
 * @param resp Description of the Parameter
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    WebdavServlet.LockInfo lock = new WebdavServlet.LockInfo();

    // Parsing lock request

    // Parsing depth header

    String depthStr = req.getHeader("Depth");

    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = INFINITY;
        }
    }

    // Parsing timeout header

    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        int commaPos = lockDurationStr.indexOf(",");
        // If multiple timeouts, just use the first
        if (commaPos != -1) {
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        }
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);

    int lockRequestType = LOCK_CREATION;

    Node lockInfoNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information

        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        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();
                if (nodeName.endsWith("lockscope")) {
                    lockScopeNode = currentNode;
                }
                if (nodeName.endsWith("locktype")) {
                    lockTypeNode = currentNode;
                }
                if (nodeName.endsWith("owner")) {
                    lockOwnerNode = currentNode;
                }
                break;
            }
        }

        if (lockScopeNode != null) {

            childList = lockScopeNode.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 tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    } else {
                        lock.scope = tempScope;
                    }
                    break;
                }
            }

            if (lock.scope == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            childList = lockTypeNode.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 tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1) {
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    } else {
                        lock.type = tempType;
                    }
                    break;
                }
            }

            if (lock.type == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.setQualifiedNames(false);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.owner = new String();
        }

    }

    String path = getRelativePath(req);

    lock.path = path;

    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    Enumeration locksList = null;

    if (lockRequestType == LOCK_CREATION) {

        // Generating lock id
        String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-"
                + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        String lockToken = md5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if ((exists) && (object instanceof DirContext) && (lock.depth == INFINITY)) {

            // Locking a collection (and all its member resources)

            // Checking if a child resource of this collection is
            // already locked
            Vector lockPaths = new Vector();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }

            if (!lockPaths.isEmpty()) {

                // One of the child paths was locked
                // We generate a multistatus error report

                Enumeration lockPathsList = lockPaths.elements();

                resp.setStatus(WebdavStatus.SC_CONFLICT);

                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();

                generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                        XMLWriter.OPENING);

                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement(null, "response", XMLWriter.OPENING);
                    generatedXML.writeElement(null, "href", XMLWriter.OPENING);
                    generatedXML.writeText((String) lockPathsList.nextElement());
                    generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
                    generatedXML.writeElement(null, "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " "
                            + WebdavStatus.getStatusText(WebdavStatus.SC_LOCKED));
                    generatedXML.writeElement(null, "status", XMLWriter.CLOSING);

                    generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
                }

                generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);

                Writer writer = resp.getWriter();
                writer.write(generatedXML.toString());
                writer.close();

                return;
            }

            boolean addLock = true;

            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {

                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {

                    if (currentLock.isExclusive()) {
                        resp.sendError(WebdavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            resp.sendError(WebdavStatus.SC_LOCKED);
                            return;
                        }
                    }

                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;

                }
            }

            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }
        } else {

            // Locking a single resource

            // Retrieving an already existing lock on that resource
            WebdavServlet.LockInfo presentLock = (WebdavServlet.LockInfo) resourceLocks.get(lock.path);
            if (presentLock != null) {

                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }

            } else {

                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);

                // Checking if a resource exists at this path
                exists = true;
                try {
                    object = resources.lookup(path);
                } catch (NamingException e) {
                    exists = false;
                }
                if (!exists) {

                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);

                    Vector lockNulls = (Vector) lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector();
                        lockNullResources.put(parentPath, lockNulls);
                    }

                    lockNulls.addElement(lock.path);

                }
                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
            }

        }

    }

    if (lockRequestType == LOCK_REFRESH) {

        String ifHeader = req.getHeader("If");
        if (ifHeader == null) {
            ifHeader = "";
        }

        // Checking resource locks

        WebdavServlet.LockInfo toRenew = (WebdavServlet.LockInfo) resourceLocks.get(path);
        Enumeration tokenList = null;
        if (lock != null) {

            // At least one of the tokens of the locks must have been given

            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = (String) tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }

        }

        // Checking inheritable collection locks

        Enumeration collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = (WebdavServlet.LockInfo) collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {

                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = (String) tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }

            }
        }

    }

    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.OPENING);

    lock.toXML(generatedXML);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.CLOSING);

    generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);

    resp.setStatus(WebdavStatus.SC_OK);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}

From source file:com.zeroio.webdav.WebdavServlet.java

/**
 * LOCK Method.//  ww  w .  j a va2 s .c  om
 *
 * @param context Description of the Parameter
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 */
protected void doLock(ActionContext context) throws ServletException, IOException {

    if (readOnly) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(context.getRequest())) {
        context.getResponse().sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    LockInfo lock = new LockInfo();

    // Parsing lock request

    // Parsing depth header

    String depthStr = context.getRequest().getHeader("Depth");

    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = INFINITY;
        }
    }
    // Parsing timeout header

    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = context.getRequest().getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        int commaPos = lockDurationStr.indexOf(",");
        // If multiple timeouts, just use the first
        if (commaPos != -1) {
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        }
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);

    int lockRequestType = LOCK_CREATION;

    Node lockInfoNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(context.getRequest().getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information

        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        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();
                if (nodeName.endsWith("lockscope")) {
                    lockScopeNode = currentNode;
                }
                if (nodeName.endsWith("locktype")) {
                    lockTypeNode = currentNode;
                }
                if (nodeName.endsWith("owner")) {
                    lockOwnerNode = currentNode;
                }
                break;
            }
        }

        if (lockScopeNode != null) {

            childList = lockScopeNode.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 tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    } else {
                        lock.scope = tempScope;
                    }
                    break;
                }
            }

            if (lock.scope == null) {
                // Bad request
                context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            childList = lockTypeNode.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 tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1) {
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    } else {
                        lock.type = tempType;
                    }
                    break;
                }
            }

            if (lock.type == null) {
                // Bad request
                context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.setQualifiedNames(false);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null) {
                // Bad request
                context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.owner = new String();
        }

    }

    String path = getRelativePath(context.getRequest());

    //Fix for MACOSX finder. Do not allow requests for files starting with a period
    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        return;
    }

    lock.path = path;

    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    Enumeration locksList = null;

    if (lockRequestType == LOCK_CREATION) {

        // Generating lock id
        String lockTokenStr = context.getRequest().getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + context.getRequest().getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-"
                + lock.tokens + "-" + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        String lockToken = md5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if ((exists) && (object instanceof DirContext) && (lock.depth == INFINITY)) {

            // Locking a collection (and all its member resources)

            // Checking if a child resource of this collection is
            // already locked
            Vector lockPaths = new Vector();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }

            if (!lockPaths.isEmpty()) {

                // One of the child paths was locked
                // We generate a multistatus error report

                Enumeration lockPathsList = lockPaths.elements();

                context.getResponse().setStatus(WebdavStatus.SC_CONFLICT);

                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();

                generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                        XMLWriter.OPENING);

                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement(null, "response", XMLWriter.OPENING);
                    generatedXML.writeElement(null, "href", XMLWriter.OPENING);
                    generatedXML.writeText((String) lockPathsList.nextElement());
                    generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
                    generatedXML.writeElement(null, "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " "
                            + WebdavStatus.getStatusText(WebdavStatus.SC_LOCKED));
                    generatedXML.writeElement(null, "status", XMLWriter.CLOSING);

                    generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
                }

                generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);

                Writer writer = context.getResponse().getWriter();
                writer.write(generatedXML.toString());
                writer.close();

                return;
            }

            boolean addLock = true;

            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {

                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {

                    if (currentLock.isExclusive()) {
                        context.getResponse().sendError(WebdavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            context.getResponse().sendError(WebdavStatus.SC_LOCKED);
                            return;
                        }
                    }

                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;

                }
            }

            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }
        } else {

            // Locking a single resource

            // Retrieving an already existing lock on that resource
            LockInfo presentLock = (LockInfo) resourceLocks.get(lock.path);
            if (presentLock != null) {

                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    context.getResponse().sendError(WebdavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }

            } else {

                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);

                // Checking if a resource exists at this path
                exists = true;
                try {
                    object = resources.lookup(path);
                } catch (NamingException e) {
                    exists = false;
                }
                if (!exists) {

                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);

                    Vector lockNulls = (Vector) lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector();
                        lockNullResources.put(parentPath, lockNulls);
                    }

                    //System.out.println("ADDED LOCK AT PATH: " + lock.path);
                    lockNulls.addElement(lock.path);

                }
                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                context.getResponse().addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
            }

        }

    }

    if (lockRequestType == LOCK_REFRESH) {

        String ifHeader = context.getRequest().getHeader("If");
        if (ifHeader == null) {
            ifHeader = "";
        }

        // Checking resource locks

        LockInfo toRenew = (LockInfo) resourceLocks.get(path);
        Enumeration tokenList = null;
        if (lock != null) {

            // At least one of the tokens of the locks must have been given

            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = (String) tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }

        }

        // Checking inheritable collection locks

        Enumeration collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = (LockInfo) collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {

                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = (String) tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }

            }
        }

    }

    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.OPENING);

    lock.toXML(generatedXML);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.CLOSING);

    generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);

    context.getResponse().setStatus(WebdavStatus.SC_OK);
    context.getResponse().setContentType("text/xml; charset=UTF-8");
    Writer writer = context.getResponse().getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * Deletes a collection.//from  w ww . j a va2  s . c  o m
 *
 * @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
 * @param req       Description of the Parameter
 */
private void deleteCollection(HttpServletRequest req, DirContext resources, String path, Hashtable errorList) {

    if (debug > 1) {
        System.out.println("Delete:" + path);
    }

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        errorList.put(path, new Integer(WebdavStatus.SC_FORBIDDEN));
        return;
    }

    String ifHeader = req.getHeader("If");
    if (ifHeader == null) {
        ifHeader = "";
    }

    String lockTokenHeader = req.getHeader("Lock-Token");
    if (lockTokenHeader == null) {
        lockTokenHeader = "";
    }

    Enumeration enum1 = null;
    try {
        enum1 = resources.list(path);
    } catch (NamingException e) {
        errorList.put(path, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        return;
    }

    while (enum1.hasMoreElements()) {
        NameClassPair ncPair = (NameClassPair) enum1.nextElement();
        String childName = path;
        if (!childName.equals("/")) {
            childName += "/";
        }
        childName += ncPair.getName();

        if (isLocked(childName, ifHeader + lockTokenHeader)) {

            errorList.put(childName, new Integer(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, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                    }
                }
            } catch (NamingException e) {
                errorList.put(childName, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            }
        }

    }

}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

/** 
 * Return xml element containing all of the subcontexts of the parent context with their attributes. 
 * @return tree xml./*  w w w .j av  a  2 s.  com*/
 */
private XmlBuilder getTree(DirContext parentContext, String context, ParameterResolutionContext prc,
        Map paramValueMap) {
    XmlBuilder contextElem = new XmlBuilder("context");
    contextElem.addAttribute("name", context);

    String[] subCtxList = getSubContextList(parentContext, context, prc);
    try {
        if (subCtxList.length == 0) {
            XmlBuilder attrs = attributesToXml(
                    parentContext.getAttributes(context, getAttributesReturnedParameter()));
            contextElem.addSubElement(attrs);
        } else {
            for (int i = 0; i < subCtxList.length; i++) {
                contextElem.addSubElement(
                        getTree((DirContext) parentContext.lookup(context), subCtxList[i], prc, paramValueMap));
            }
            contextElem.addSubElement(
                    attributesToXml(parentContext.getAttributes(context, getAttributesReturnedParameter())));
        }

    } catch (NamingException e) {
        storeLdapException(e, prc);
        log.error("Exception in operation [" + getOperation() + "]: ", e);
    }

    return contextElem;
}

From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java

private boolean isMemberOf(DirContext ctx, String dnUser, String dnGroup) throws NamingException {
    DirContext lookedContext = (DirContext) (ctx.lookup(dnGroup));
    Attribute attrs = lookedContext.getAttributes("").get("member");
    for (int i = 0; i < attrs.size(); i++) {
        String foundMember = (String) attrs.get(i);
        if (foundMember.equalsIgnoreCase(dnUser)) {
            return true;
        }/*from  ww w  . ja v  a 2 s.c  o m*/
    }
    return false;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @param req  Description of the Parameter
 * @param resp Description of the Parameter
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet-specified error occurs
 *///from w  ww  .  j a v  a  2  s. c  o m
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (readOnly) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    String path = getRelativePath(req);

    // Retrieve the Catalina context
    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    try {
        resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    if (exists) {
        boolean result = true;
        try {
            resources.unbind(path);
        } catch (NamingException e) {
            result = false;
        }
        if (result) {
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Get the readme file as a string./*from  w w w . ja va 2 s.  com*/
 *
 * @param directory Description of the Parameter
 * @return The readme value
 */
protected String getReadme(DirContext directory) {
    if (readmeFile != null) {
        try {
            Object obj = directory.lookup(readmeFile);

            if (obj != null && obj instanceof Resource) {
                StringWriter buffer = new StringWriter();
                InputStream is = ((Resource) obj).streamContent();
                copyRange(new InputStreamReader(is), new PrintWriter(buffer));

                return buffer.toString();
            }
        } catch (Throwable e) {
            ;
            /*
             *  Should only be IOException or NamingException
             *  can be ignored
             */
        }
    }

    return null;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Return the xsl template inputstream (if possible)
 *
 * @param directory Description of the Parameter
 * @return Description of the Return Value
 *//* ww w.java  2 s.co  m*/
protected InputStream findXsltInputStream(DirContext directory) {
    if (localXsltFile != null) {
        try {
            Object obj = directory.lookup(localXsltFile);
            if (obj != null && obj instanceof Resource) {
                InputStream is = ((Resource) obj).streamContent();
                if (is != null) {
                    return is;
                }
            }
        } catch (Throwable e) {
            ;
            /*
             *  Should only be IOException or NamingException
             *  can be ignored
             */
        }
    }

    /*
     *  Open and read in file in one fell swoop to reduce chance
     *  chance of leaving handle open.
     */
    if (globalXsltFile != null) {
        FileInputStream fis = null;

        try {
            File f = new File(globalXsltFile);
            if (f.exists()) {
                fis = new FileInputStream(f);
                byte b[] = new byte[(int) f.length()];
                /*
                 *  danger!
                 */
                fis.read(b);
                return new ByteArrayInputStream(b);
            }
        } catch (Throwable e) {
            log("This shouldn't happen (?)...", e);
            return null;
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (Throwable e) {
                ;
            }
        }
    }

    return null;
}

From source file:org.apache.catalina.util.ExtensionValidator.java

/**
 * Runtime validation of a Web Applicaiton.
 *
 * This method uses JNDI to look up the resources located under a 
 * <code>DirContext</code>. It locates Web Application MANIFEST.MF 
 * file in the /META-INF/ directory of the application and all 
 * MANIFEST.MF files in each JAR file located in the WEB-INF/lib 
 * directory and creates an <code>ArrayList</code> of 
 * <code>ManifestResorce<code> objects. These objects are then passed 
 * to the validateManifestResources method for validation.
 *
 * @param dirContext The JNDI root of the Web Application
 * @param context The context from which the Logger and path to the
 *                application//from   w ww.  j  a v a2s .c o  m
 *
 * @return true if all required extensions satisfied
 */
public static synchronized boolean validateApplication(DirContext dirContext, StandardContext context)
        throws IOException {

    String appName = context.getPath();
    ArrayList appManifestResources = new ArrayList();
    ManifestResource appManifestResource = null;
    // If the application context is null it does not exist and 
    // therefore is not valid
    if (dirContext == null)
        return false;
    // Find the Manifest for the Web Applicaiton
    InputStream inputStream = null;
    try {
        NamingEnumeration wne = dirContext.listBindings("/META-INF/");
        Binding binding = (Binding) wne.nextElement();
        if (binding.getName().toUpperCase().equals("MANIFEST.MF")) {
            Resource resource = (Resource) dirContext.lookup("/META-INF/" + binding.getName());
            inputStream = resource.streamContent();
            Manifest manifest = new Manifest(inputStream);
            inputStream.close();
            inputStream = null;
            ManifestResource mre = new ManifestResource(
                    sm.getString("extensionValidator.web-application-manifest"), manifest,
                    ManifestResource.WAR);
            appManifestResources.add(mre);
        }
    } catch (NamingException nex) {
        // Application does not contain a MANIFEST.MF file
    } catch (NoSuchElementException nse) {
        // Application does not contain a MANIFEST.MF file
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
                // Ignore
            }
        }
    }

    // Locate the Manifests for all bundled JARs
    NamingEnumeration ne = null;
    try {
        if (dirContext != null) {
            ne = dirContext.listBindings("WEB-INF/lib/");
        }
        while ((ne != null) && ne.hasMoreElements()) {
            Binding binding = (Binding) ne.nextElement();
            if (!binding.getName().toLowerCase().endsWith(".jar")) {
                continue;
            }
            Resource resource = (Resource) dirContext.lookup("/WEB-INF/lib/" + binding.getName());
            Manifest jmanifest = getManifest(resource.streamContent());
            if (jmanifest != null) {
                ManifestResource mre = new ManifestResource(binding.getName(), jmanifest,
                        ManifestResource.APPLICATION);
                appManifestResources.add(mre);
            }
        }
    } catch (NamingException nex) {
        // Jump out of the check for this application because it 
        // has no resources
    }

    return validateManifestResources(appName, appManifestResources);
}

From source file:org.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java

@Override
public String authenticate(String username, String password)
        throws BadCredentialsException, AuthenticationSystemException {

    // Mapper for user data if user is successfully authenticated
    AuthenticatedLdapEntryContextMapper<User> mapper = new AuthenticatedLdapEntryContextMapper<User>() {
        @Override// w  ww  .  j av  a  2s  .c  o m
        public User mapWithContext(DirContext dirContext, LdapEntryIdentification ldapEntryIdentification) {
            try {
                // User entry - extract attributes
                DirContextOperations dirContextOperations = (DirContextOperations) dirContext
                        .lookup(ldapEntryIdentification.getRelativeName());
                Attributes attributes = dirContextOperations.getAttributes();
                String emailAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_EMAIL);
                String firstNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_FIRST_NAME);
                String lastNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_LAST_NAME);
                String siteIdAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_SITE_ID);
                String groupNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_GROUP_NAME);
                Attribute emailAttrib = attributes.get(emailAttribName);
                Attribute firstNameAttrib = attributes.get(firstNameAttribName);
                Attribute lastNameAttrib = attributes.get(lastNameAttribName);
                Attribute siteIdAttrib = attributes.get(siteIdAttribName);
                Attribute groupNameAttrib = attributes.get(groupNameAttribName);

                User user = new User();
                user.setGroups(new ArrayList<>());
                user.setActive(1);
                user.setUsername(username);

                if (emailAttrib != null && emailAttrib.get() != null) {
                    user.setEmail(emailAttrib.get().toString());
                } else {
                    logger.error("No LDAP attribute " + emailAttribName + " found for username " + username
                            + ". User will not be imported into DB.");
                    return null;
                }
                if (firstNameAttrib != null && firstNameAttrib.get() != null) {
                    user.setFirstname(firstNameAttrib.get().toString());
                } else {
                    logger.warn("No LDAP attribute " + firstNameAttribName + " found for username " + username);
                }
                if (lastNameAttrib != null && lastNameAttrib.get() != null) {
                    user.setLastname(lastNameAttrib.get().toString());
                } else {
                    logger.warn("No LDAP attribute " + lastNameAttribName + " found for username " + username);
                }

                if (siteIdAttrib != null && siteIdAttrib.get() != null) {
                    Map<String, Object> params = new HashMap<>();
                    NamingEnumeration siteIdValues = siteIdAttrib.getAll();
                    while (siteIdValues.hasMore()) {
                        Object siteIdObj = siteIdValues.next();
                        if (siteIdObj != null) {
                            String[] siteIdAndGroupName = extractSiteIdAndGroupNameFromAttributeValue(
                                    siteIdObj.toString());

                            if (siteIdAndGroupName.length > 0) {
                                params.put("siteId", siteIdAndGroupName[0]);

                                SiteFeed siteFeed = siteFeedMapper.getSite(params);
                                if (siteFeed != null) {
                                    // Add groups, first the one that's specific to the site
                                    if (siteIdAndGroupName.length > 1) {
                                        addGroupToUser(user, siteIdAndGroupName[1], siteFeed);
                                    }

                                    extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib,
                                            siteFeed);
                                } else {
                                    logger.warn("Not site found for ID " + siteIdAndGroupName[0]);
                                }
                            }
                        }
                    }
                } else {
                    String defaultSiteId = studioConfiguration.getProperty(SECURITY_LDAP_DEFAULT_SITE_ID);

                    logger.debug("Assigning user " + username + " to default site " + defaultSiteId);

                    Map<String, Object> params = new HashMap<>();
                    params.put("siteId", defaultSiteId);

                    SiteFeed siteFeed = siteFeedMapper.getSite(params);
                    if (siteFeed != null) {
                        extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed);
                    } else {
                        logger.warn("No site found for default site ID " + defaultSiteId);
                    }
                }

                return user;
            } catch (NamingException e) {
                logger.error("Error getting details from LDAP for username " + username, e);

                return null;
            }
        }
    };

    // Create ldap query to authenticate user
    LdapQuery ldapQuery = query().where(studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_USERNAME))
            .is(username);
    User user;
    try {
        user = ldapTemplate.authenticate(ldapQuery, password, mapper);
    } catch (EmptyResultDataAccessException e) {
        logger.info("User " + username
                + " not found with external security provider. Trying to authenticate against studio database");
        // When user not found try to authenticate against studio database
        return super.authenticate(username, password);
    } catch (CommunicationException e) {
        logger.info("Failed to connect with external security provider. "
                + "Trying to authenticate against studio database");
        // When user not found try to authenticate against studio database
        return super.authenticate(username, password);
    } catch (AuthenticationException e) {
        logger.error("Authentication failed with the LDAP system", e);

        throw new BadCredentialsException();
    } catch (Exception e) {
        logger.error("Authentication failed with the LDAP system", e);

        throw new AuthenticationSystemException("Authentication failed with the LDAP system", e);
    }

    if (user != null) {
        // When user authenticated against LDAP, upsert user data into studio database
        if (super.userExists(username)) {
            try {
                boolean success = updateUserInternal(user.getUsername(), user.getFirstname(),
                        user.getLastname(), user.getEmail());
                if (success) {
                    ActivityService.ActivityType activityType = ActivityService.ActivityType.UPDATED;
                    Map<String, String> extraInfo = new HashMap<>();
                    extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER);
                    activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(),
                            activityType, ActivityService.ActivitySource.API, extraInfo);
                }
            } catch (UserNotFoundException e) {
                logger.error(
                        "Error updating user " + username + " with data from external authentication provider",
                        e);

                throw new AuthenticationSystemException(
                        "Error updating user " + username + " with data from external authentication provider",
                        e);
            }
        } else {
            try {
                boolean success = createUser(user.getUsername(), password, user.getFirstname(),
                        user.getLastname(), user.getEmail(), true);
                if (success) {
                    ActivityService.ActivityType activityType = ActivityService.ActivityType.CREATED;
                    Map<String, String> extraInfo = new HashMap<>();
                    extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER);
                    activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(),
                            activityType, ActivityService.ActivitySource.API, extraInfo);
                }
            } catch (UserAlreadyExistsException e) {
                logger.error("Error adding user " + username + " from external authentication provider", e);

                throw new AuthenticationSystemException(
                        "Error adding user " + username + " from external authentication provider", e);
            }
        }
        for (Group group : user.getGroups()) {
            try {
                upsertUserGroup(group.getSite(), group.getName(), user.getUsername());
            } catch (GroupAlreadyExistsException | SiteNotFoundException | UserNotFoundException
                    | UserAlreadyExistsException | GroupNotFoundException e) {
                logger.error("Failed to upsert user groups data from LDAP", e);
            }
        }

        String token = createToken(user);
        storeSessionTicket(token);
        storeSessionUsername(username);

        return token;
    } else {
        logger.error("Failed to retrieve LDAP user details");

        throw new AuthenticationSystemException("Failed to retrieve LDAP user details");
    }
}