Search in sources :

Example 51 with DirContext

use of javax.naming.directory.DirContext 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;
    }
    // Properties which are to be displayed.
    Vector<String> properties = null;
    // Propfind depth
    int depth = INFINITY;
    // Propfind type
    int type = FIND_ALL_PROP;
    String depthStr = req.getHeader("Depth");
    if (depthStr == null) {
        depth = INFINITY;
    } else {
        if ("0".equals(depthStr)) {
            depth = 0;
        } else if ("1".equals(depthStr)) {
            depth = 1;
        } else if ("infinity".equals(depthStr)) {
            depth = INFINITY;
        }
    }
    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 e) {
        // Something went wrong - use the defaults.
        } catch (IOException e) {
        // Something went wrong - use the defaults.
        }
    }
    if (type == FIND_BY_PROPERTY) {
        properties = new Vector<String>();
        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;
                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);
            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(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<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(null, "multistatus", XMLWriter.CLOSING);
    generatedXML.sendData();
}
Also used : InputSource(org.xml.sax.InputSource) Enumeration(java.util.Enumeration) NamingEnumeration(javax.naming.NamingEnumeration) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) DirContext(javax.naming.directory.DirContext) Document(org.w3c.dom.Document) XMLWriter(org.apache.catalina.util.XMLWriter) SAXException(org.xml.sax.SAXException) Stack(java.util.Stack) DocumentBuilder(javax.xml.parsers.DocumentBuilder) NameClassPair(javax.naming.NameClassPair) NamingException(javax.naming.NamingException) Vector(java.util.Vector)

Example 52 with DirContext

use of javax.naming.directory.DirContext in project Payara by payara.

the class WebdavStatus method doLock.

/**
 * LOCK Method.
 */
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;
    }
    LockInfo lock = new LockInfo();
    // Parsing lock request
    // Parsing depth header
    String depthStr = req.getHeader("Depth");
    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if ("0".equals(depthStr)) {
            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 = Integer.parseInt(lockDurationStr.substring(7));
        } else {
            if ("infinity".equalsIgnoreCase(lockDurationStr)) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = Integer.parseInt(lockDurationStr);
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + lockDuration * 1000L;
    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 (IOException e) {
        lockRequestType = LOCK_REFRESH;
    } catch (SAXException 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;
                default:
                    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;
                    default:
                        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;
                    default:
                        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;
                    default:
                        break;
                }
            }
            if (lock.owner == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.owner = "";
        }
    }
    String path = getRelativePath(req);
    lock.path = path;
    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }
    Enumeration<LockInfo> 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;
        byte[] digestBytes = null;
        synchronized (md5Helper) {
            digestBytes = md5Helper.digest(lockTokenStr.getBytes(Charset.defaultCharset()));
        }
        String lockToken = new String(md5Encoder.encode(digestBytes));
        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<String> lockPaths = new Vector<String>();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = 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 = 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<String> 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(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()) {
                LockInfo currentLock = 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
            LockInfo presentLock = 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<String> lockNulls = lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector<String>();
                        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
        LockInfo toRenew = resourceLocks.get(path);
        Enumeration<String> 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 = tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }
        }
        // Checking inheritable collection locks
        Enumeration<LockInfo> collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {
                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = 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();
}
Also used : InputSource(org.xml.sax.InputSource) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) DirContext(javax.naming.directory.DirContext) Document(org.w3c.dom.Document) XMLWriter(org.apache.catalina.util.XMLWriter) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) NamingException(javax.naming.NamingException) Vector(java.util.Vector) DOMWriter(org.apache.catalina.util.DOMWriter) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) XMLWriter(org.apache.catalina.util.XMLWriter) DOMWriter(org.apache.catalina.util.DOMWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 53 with DirContext

use of javax.naming.directory.DirContext 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, Integer.valueOf(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, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }
    } else {
        if (object instanceof Resource) {
            try {
                resources.bind(dest, object);
            } catch (NamingException e) {
                errorList.put(source, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                return false;
            }
        } else {
            errorList.put(source, Integer.valueOf(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 54 with DirContext

use of javax.naming.directory.DirContext in project Payara by payara.

the class HostConfig method checkContextLastModified.

/**
 * Check deployment descriptors last modified date.
 */
protected void checkContextLastModified() {
    if (!(host instanceof Deployer))
        return;
    Deployer deployer = (Deployer) host;
    String[] contextNames = deployer.findDeployedApps();
    for (int i = 0; i < contextNames.length; i++) {
        String contextName = contextNames[i];
        Context context = deployer.findDeployedApp(contextName);
        if (!(context instanceof Lifecycle))
            continue;
        try {
            DirContext resources = context.getResources();
            if (resources == null) {
                // the context
                continue;
            }
            ResourceAttributes webXmlAttributes = (ResourceAttributes) resources.getAttributes("/WEB-INF/web.xml");
            ResourceAttributes webInfAttributes = (ResourceAttributes) resources.getAttributes("/WEB-INF");
            long newLastModified = webXmlAttributes.getLastModified();
            long webInfLastModified = webInfAttributes.getLastModified();
            Long lastModified = webXmlLastModified.get(contextName);
            if (lastModified == null) {
                webXmlLastModified.put(contextName, Long.valueOf(newLastModified));
            } else {
                if (lastModified.longValue() != newLastModified) {
                    if (newLastModified > (webInfLastModified + 5000)) {
                        webXmlLastModified.remove(contextName);
                        restartContext(context);
                    } else {
                        webXmlLastModified.put(contextName, Long.valueOf(newLastModified));
                    }
                }
            }
        } catch (NamingException e) {
            // Ignore
            ;
        }
        Long lastModified = contextXmlLastModified.get(contextName);
        String configBase = configBase().getPath();
        String configFileName = context.getConfigFile();
        if (configFileName != null) {
            File configFile = new File(configFileName);
            if (!configFile.isAbsolute()) {
                configFile = new File(System.getProperty("catalina.base"), configFile.getPath());
            }
            long newLastModified = configFile.lastModified();
            if (lastModified == null) {
                contextXmlLastModified.put(contextName, Long.valueOf(newLastModified));
            } else {
                if (lastModified.longValue() != newLastModified) {
                    contextXmlLastModified.remove(contextName);
                    String fileName = configFileName;
                    if (fileName.startsWith(configBase)) {
                        fileName = fileName.substring(configBase.length() + 1);
                        try {
                            deployed.remove(fileName);
                            if (host.findChild(contextName) != null) {
                                ((Deployer) host).remove(contextName);
                            }
                        } catch (Throwable t) {
                            String msg = MessageFormat.format(rb.getString(LogFacade.ERROR_UNDEPLOYING_JAR_FILE_EXCEPTION), fileName);
                            log.log(Level.SEVERE, msg, t);
                        }
                        deployApps();
                    }
                }
            }
        }
    }
    // Check for WAR modification
    if (isUnpackWARs()) {
        File appBase = appBase();
        if (!appBase.exists() || !appBase.isDirectory())
            return;
        String[] files = appBase.list();
        for (int i = 0; i < files.length; i++) {
            if (files[i].endsWith(".war")) {
                File dir = new File(appBase, files[i]);
                Long lastModified = warLastModified.get(files[i]);
                long dirLastModified = dir.lastModified();
                if (lastModified == null) {
                    warLastModified.put(files[i], Long.valueOf(dir.lastModified()));
                } else if (dirLastModified > lastModified.longValue()) {
                    // The WAR has been modified: redeploy
                    String expandedDir = files[i];
                    int period = expandedDir.lastIndexOf(".");
                    if (period >= 0)
                        expandedDir = expandedDir.substring(0, period);
                    File expanded = new File(appBase, expandedDir);
                    String contextPath = "/" + expandedDir;
                    if (contextPath.equals("/ROOT"))
                        contextPath = "";
                    if (dirLastModified > expanded.lastModified()) {
                        try {
                            // Undeploy current application
                            deployed.remove(files[i]);
                            deployed.remove(expandedDir + ".xml");
                            if (host.findChild(contextPath) != null) {
                                ((Deployer) host).remove(contextPath, false);
                                ExpandWar.deleteDir(expanded);
                            }
                        } catch (Throwable t) {
                            String msg = MessageFormat.format(rb.getString(LogFacade.ERROR_UNDEPLOYING_JAR_FILE_EXCEPTION), files[i]);
                            log.log(Level.SEVERE, msg, t);
                        }
                        deployApps();
                    }
                    // the last modified values
                    if (host.findChild(contextPath) != null) {
                        webXmlLastModified.remove(contextPath);
                        warLastModified.put(files[i], Long.valueOf(dir.lastModified()));
                    }
                }
            }
        }
    }
}
Also used : DirContext(javax.naming.directory.DirContext) DirContext(javax.naming.directory.DirContext) ResourceAttributes(org.apache.naming.resources.ResourceAttributes) NamingException(javax.naming.NamingException) JarFile(java.util.jar.JarFile)

Example 55 with DirContext

use of javax.naming.directory.DirContext in project Payara by payara.

the class StandardContext method getResourcePaths.

/**
 * Return a Set containing the resource paths of resources member of the
 * specified collection. Each path will be a String starting with
 * a "/" character. The returned set is immutable.
 */
@Override
public Set<String> getResourcePaths(String path) {
    // Validate the path argument
    if (path == null) {
        return null;
    }
    if (!path.startsWith("/")) {
        String msg = MessageFormat.format(rb.getString(LogFacade.INCORRECT_PATH), path);
        throw new IllegalArgumentException(msg);
    }
    path = RequestUtil.normalize(path);
    if (path == null)
        return (null);
    DirContext resources = null;
    if (alternateDocBases == null || alternateDocBases.isEmpty()) {
        resources = getResources();
    } else {
        AlternateDocBase match = AlternateDocBase.findMatch(path, alternateDocBases);
        if (match != null) {
            resources = ContextsAdapterUtility.unwrap(match.getResources());
        } else {
            // None of the url patterns for alternate doc bases matched
            resources = getResources();
        }
    }
    if (resources != null) {
        return (getResourcePathsInternal(resources, path));
    }
    return (null);
}
Also used : AlternateDocBase(org.glassfish.grizzly.http.server.util.AlternateDocBase) WARDirContext(org.apache.naming.resources.WARDirContext) BaseDirContext(org.apache.naming.resources.BaseDirContext) ProxyDirContext(org.apache.naming.resources.ProxyDirContext) DirContext(javax.naming.directory.DirContext) WebDirContext(org.apache.naming.resources.WebDirContext) FileDirContext(org.apache.naming.resources.FileDirContext)

Aggregations

DirContext (javax.naming.directory.DirContext)111 NamingException (javax.naming.NamingException)51 InitialDirContext (javax.naming.directory.InitialDirContext)43 SearchResult (javax.naming.directory.SearchResult)27 SearchControls (javax.naming.directory.SearchControls)24 Attributes (javax.naming.directory.Attributes)21 Attribute (javax.naming.directory.Attribute)17 IOException (java.io.IOException)16 NamingEnumeration (javax.naming.NamingEnumeration)16 Hashtable (java.util.Hashtable)14 Test (org.junit.Test)14 DistinguishedName (org.springframework.ldap.core.DistinguishedName)11 ProxyDirContext (org.apache.naming.resources.ProxyDirContext)10 WebDirContext (org.apache.naming.resources.WebDirContext)9 ArrayList (java.util.ArrayList)8 BaseDirContext (org.apache.naming.resources.BaseDirContext)8 FileDirContext (org.apache.naming.resources.FileDirContext)8 WARDirContext (org.apache.naming.resources.WARDirContext)8 Name (javax.naming.Name)7 BasicAttribute (javax.naming.directory.BasicAttribute)7