Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration hasMoreElements.

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

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

/**
 * PROPFIND Method./*from  ww  w. ja  va 2s. c  o  m*/
 *
 * @param context Description of the Parameter
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
protected void doPropfind(ActionContext context) throws ServletException, IOException {

    String path = getRelativePath(context.getRequest());
    //fix for windows clients
    if (path.equals("/files")) {
        path = "";
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    // Properties which are to be displayed.
    Vector properties = null;
    // Propfind depth
    int depth = INFINITY;
    // Propfind type
    int type = FIND_ALL_PROP;

    String depthStr = context.getRequest().getHeader("Depth");
    if (depthStr == null) {
        depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            depth = 0;
        } else if (depthStr.equals("1")) {
            depth = 1;
        } else if (depthStr.equals("infinity")) {
            depth = INFINITY;
        }
    }

    /*
     *  Read the request xml and determine all the properties
     */

    /*
    Node propNode = 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();
      NodeList childList = rootElement.getChildNodes();
      for (int i = 0; i < childList.getLength(); i++) {
        Node currentNode = childList.item(i);
        switch (currentNode.getNodeType()) {
          case Node.TEXT_NODE:
    break;
          case Node.ELEMENT_NODE:
    if (currentNode.getNodeName().endsWith("prop")) {
      type = FIND_BY_PROPERTY;
      propNode = currentNode;
    }
    if (currentNode.getNodeName().endsWith("propname")) {
      type = FIND_PROPERTY_NAMES;
    }
    if (currentNode.getNodeName().endsWith("allprop")) {
      type = FIND_ALL_PROP;
    }
    break;
        }
      }
    } catch (Exception e) {
      // Most likely there was no content : we use the defaults.
      // TODO : Enhance that !
      e.printStackTrace(System.out);
    }
            
    if (type == FIND_BY_PROPERTY) {
      properties = new Vector();
      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;
        }
      }
    }
    */
    // Properties have been determined
    // Retrieve the resources

    Connection db = null;
    boolean exists = true;
    boolean status = true;
    Object object = null;
    ModuleContext resources = null;
    StringBuffer xmlsb = new StringBuffer();
    try {
        db = this.getConnection(context);
        resources = getCFSResources(db, context);
        if (resources == null) {
            context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        object = resources.lookup(db, path);
    } catch (NamingException e) {
        //e.printStackTrace(System.out);
        exists = false;
        int slash = path.lastIndexOf('/');
        if (slash != -1) {
            String parentPath = path.substring(0, slash);
            Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath);
            if (currentLockNullResources != null) {
                Enumeration lockNullResourcesList = currentLockNullResources.elements();
                while (lockNullResourcesList.hasMoreElements()) {
                    String lockNullPath = (String) lockNullResourcesList.nextElement();
                    if (lockNullPath.equals(path)) {
                        context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
                        context.getResponse().setContentType("text/xml; charset=UTF-8");
                        // Create multistatus object
                        XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
                        generatedXML.writeXMLHeader();
                        generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                                XMLWriter.OPENING);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                        generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
                        generatedXML.sendData();
                        //e.printStackTrace(System.out);
                        return;
                    }
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace(System.out);
        context.getResponse().sendError(SQLERROR, e.getMessage());
        status = false;
    } finally {
        this.freeConnection(db, context);
    }

    if (!status) {
        return;
    }

    if (!exists) {
        context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    }

    context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
    context.getResponse().setContentType("text/xml; charset=UTF-8");
    // Create multistatus object
    ////System.out.println("Creating Multistatus Object");

    XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    //System.out.println("Depth: " + depth);
    if (depth == 0) {
        parseProperties(context, resources, generatedXML, path, type, properties);
    } else {
        // The stack always contains the object of the current level
        Stack stack = new Stack();
        stack.push(path);
        // Stack of the objects one level below
        Stack stackBelow = new Stack();

        while ((!stack.isEmpty()) && (depth >= 0)) {
            String currentPath = (String) stack.pop();
            if (!currentPath.equals(path)) {
                parseProperties(context, resources, generatedXML, currentPath, type, properties);
            }
            try {
                db = this.getConnection(context);
                object = resources.lookup(db, currentPath);
            } catch (NamingException e) {
                continue;
            } catch (SQLException e) {
                //e.printStackTrace(System.out);
                context.getResponse().sendError(SQLERROR, e.getMessage());
                status = false;
            } finally {
                this.freeConnection(db, context);
            }

            if (!status) {
                return;
            }

            if ((object instanceof ModuleContext) && depth > 0) {
                // Get a list of all the resources at the current path and store them
                // in the stack
                try {
                    NamingEnumeration enum1 = resources.list(currentPath);
                    int count = 0;
                    while (enum1.hasMoreElements()) {
                        NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                        String newPath = currentPath;
                        if (!(newPath.endsWith("/"))) {
                            newPath += "/";
                        }
                        newPath += ncPair.getName();
                        stackBelow.push(newPath);
                        count++;
                    }
                    if (currentPath.equals(path) && count == 0) {
                        // This directory does not have any files or folders.
                        parseProperties(context, resources, generatedXML, properties);
                    }
                } catch (NamingException e) {
                    //e.printStackTrace(System.out);
                    context.getResponse().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 currentLockNullResources = (Vector) lockNullResources.get(lockPath);
                if (currentLockNullResources != null) {
                    Enumeration lockNullResourcesList = currentLockNullResources.elements();
                    while (lockNullResourcesList.hasMoreElements()) {
                        String lockNullPath = (String) lockNullResourcesList.nextElement();
                        System.out.println("Lock null path: " + lockNullPath);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                    }
                }
            }
            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;
                stackBelow = new Stack();
            }
            xmlsb.append(generatedXML.toString());
            //System.out.println("xml : " + generatedXML.toString());
            generatedXML.sendData();
        }
    }

    generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
    xmlsb.append(generatedXML.toString());
    generatedXML.sendData();
    //System.out.println("xml: " + xmlsb.toString());
}

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

/**
 * Copy a collection./*from w  ww . j a  v  a 2s .c  o m*/
 *
 * @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
 * @param thisSystem Description of the Parameter
 * @param db         Description of the Parameter
 * @return Description of the Return Value
 * @throws SQLException          Description of the Exception
 * @throws FileNotFoundException Description of the Exception
 */
private boolean copyResource(ActionContext context, SystemStatus thisSystem, Connection db,
        ModuleContext resources, Hashtable errorList, String source, String dest)
        throws SQLException, FileNotFoundException {

    if (debug > 1) {
        System.out.println("Copy: " + source + " To: " + dest);
    }

    Object object = null;
    try {
        object = resources.lookup(thisSystem, db, source);
    } catch (NamingException e) {
        e.printStackTrace(System.out);
    }

    if (object instanceof ModuleContext) {
        try {
            resources.createSubcontext(thisSystem, db, dest);
        } catch (NamingException e) {
            e.printStackTrace(System.out);
            errorList.put(dest, new Integer(WebdavStatus.SC_CONFLICT));
            return false;
        }

        try {
            //System.out.println("Listing resources at path: " + source);
            //System.out.println("OBJECT: " + object);
            object = resources.lookup(thisSystem, db, source);
            NamingEnumeration enum1 = resources.list(source);
            while (enum1.hasMoreElements()) {
                //System.out.println("COPYING CHILD CONTEXT.........................");
                NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                String childDest = dest;
                if (!childDest.equals("/")) {
                    childDest += "/";
                }
                childDest += ncPair.getName();
                String childSrc = source;
                if (!childSrc.equals("/")) {
                    childSrc += "/";
                }
                childSrc += ncPair.getName();
                copyResource(context, thisSystem, db, resources, errorList, childSrc, childDest);
            }
        } catch (NamingException e) {
            e.printStackTrace(System.out);
            errorList.put(dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }

    } else {

        if (object instanceof Resource) {
            try {
                Object resource = resources.copyResource(thisSystem, db, dest, object);
                if (resource != null) {
                    processInsertHook(context, resource);
                }
            } catch (NamingException e) {
                errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                return false;
            } catch (IOException io) {
                errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                return false;
            }
        } else {
            errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }
    }
    return true;
}

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

/**
 * PROPFIND Method.//from   w  w  w .ja va2  s . co m
 *
 * @param context Description of the Parameter
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 */
protected void doPropfind(ActionContext context) throws ServletException, IOException {

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

    //fix for windows clients
    if (path.equals("/files")) {
        path = "";
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        //Fix for MACOSX finder. Do not allow requests for files starting with a period
        return;
    }
    //System.out.println("METHOD PROPFIND....PATH: " + path);
    // Properties which are to be displayed.
    Vector properties = null;
    // Propfind depth by default 1 for performance reasons
    int depth = 1;
    // Propfind type
    int type = FIND_ALL_PROP;

    String depthStr = context.getRequest().getHeader("Depth");
    if (depthStr == null) {
        depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            depth = 0;
        } else if (depthStr.equals("1")) {
            depth = 1;
        } else if (depthStr.equals("infinity")) {
            depth = INFINITY;
        }
    }

    /*
     *  Read the request xml and determine all the properties
     */
    Node propNode = 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();
        NodeList childList = rootElement.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                if (currentNode.getNodeName().endsWith("prop")) {
                    type = FIND_BY_PROPERTY;
                    propNode = currentNode;
                }
                if (currentNode.getNodeName().endsWith("propname")) {
                    type = FIND_PROPERTY_NAMES;
                }
                if (currentNode.getNodeName().endsWith("allprop")) {
                    type = FIND_ALL_PROP;
                }
                break;
            }
        }
    } catch (Exception e) {
        // Most likely there was no content : we use the defaults.
        // TODO : Enhance that !
        //e.printStackTrace(System.out);
    }

    if (type == FIND_BY_PROPERTY) {
        properties = new Vector();
        if (!properties.contains("creationdate")) {
            //If the request did not contain creationdate property then add this to requested properties
            //to make the information available for clients
            properties.addElement("creationdate");
        }
        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;
            }
        }
    }

    // Properties have been determined
    // Retrieve the resources

    Connection db = null;
    boolean exists = true;
    boolean status = true;
    Object current = null;
    Object child = null;
    ModuleContext resources = null;
    SystemStatus thisSystem = null;
    StringBuffer xmlsb = new StringBuffer();
    try {
        db = this.getConnection(context);
        resources = getCFSResources(db, context);
        if (resources == null) {
            context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        thisSystem = this.getSystemStatus(context);
        current = resources.lookup(thisSystem, db, path);
        if (current instanceof ModuleContext) {
            //System.out.println( ((ModuleContext) current).toString());
        }
    } catch (NamingException e) {
        //e.printStackTrace(System.out);
        exists = false;
        int slash = path.lastIndexOf('/');
        if (slash != -1) {
            String parentPath = path.substring(0, slash);
            Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath);
            if (currentLockNullResources != null) {
                Enumeration lockNullResourcesList = currentLockNullResources.elements();
                while (lockNullResourcesList.hasMoreElements()) {
                    String lockNullPath = (String) lockNullResourcesList.nextElement();
                    if (lockNullPath.equals(path)) {
                        context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
                        context.getResponse().setContentType("text/xml; charset=UTF-8");
                        // Create multistatus object
                        XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
                        generatedXML.writeXMLHeader();
                        generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                                XMLWriter.OPENING);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                        generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
                        generatedXML.sendData();
                        //e.printStackTrace(System.out);
                        return;
                    }
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace(System.out);
        context.getResponse().sendError(CFS_SQLERROR, e.getMessage());
        status = false;
    } finally {
        this.freeConnection(db, context);
    }

    if (!status) {
        return;
    }

    if (!exists) {
        context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    }

    context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
    context.getResponse().setContentType("text/xml; charset=UTF-8");
    // Create multistatus object
    ////System.out.println("Creating Multistatus Object");

    XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    //System.out.println("Depth: " + depth);
    if (depth == 0) {
        parseProperties(context, resources, generatedXML, path, type, properties);
    } else {
        // The stack always contains the object of the current level
        Stack stack = new Stack();
        stack.push(path);
        // Stack of the objects one level below
        Stack stackBelow = new Stack();

        while ((!stack.isEmpty()) && (depth >= 0)) {
            String currentPath = (String) stack.pop();
            try {
                if (!currentPath.equals(path)) {
                    //object at url currentPath not yet looked up. so perform lookup at url currentPath
                    child = resources.lookup(currentPath);
                    parseProperties(context, resources, generatedXML, currentPath, type, properties);
                }
            } catch (NamingException e) {
                e.printStackTrace(System.out);
                continue;
            }

            if (!status) {
                return;
            }

            if ((current instanceof ModuleContext) && depth > 0) {
                // Get a list of all the resources at the current path and store them
                // in the stack
                try {
                    NamingEnumeration enum1 = ((ModuleContext) current).list("");
                    int count = 0;
                    while (enum1.hasMoreElements()) {
                        NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                        String newPath = currentPath;
                        if (!(newPath.endsWith("/"))) {
                            newPath += "/";
                        }
                        newPath += ncPair.getName();
                        //System.out.println("STACKING CHILD: " + newPath);
                        stackBelow.push(newPath);
                        count++;
                    }
                    if (currentPath.equals(path) && count == 0) {
                        // This directory does not have any files or folders.
                        //System.out.println("DIRECTORY HAS NO FILES OR FOLDERS...");
                        parseProperties(context, resources, generatedXML, properties);
                    }
                } catch (NamingException e) {
                    //e.printStackTrace(System.out);
                    context.getResponse().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 currentLockNullResources = (Vector) lockNullResources.get(lockPath);
                if (currentLockNullResources != null) {
                    Enumeration lockNullResourcesList = currentLockNullResources.elements();
                    while (lockNullResourcesList.hasMoreElements()) {
                        String lockNullPath = (String) lockNullResourcesList.nextElement();
                        System.out.println("Lock null path: " + lockNullPath);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                    }
                }
            }
            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;
                stackBelow = new Stack();
            }
            xmlsb.append(generatedXML.toString());
            //System.out.println("xml : " + generatedXML.toString());
            generatedXML.sendData();
        }
    }

    Iterator locks = lockNullResources.keySet().iterator();
    while (locks.hasNext()) {
        String lockpath = (String) locks.next();
        //System.out.println("LOCK PATH: " + lockpath);
    }

    generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
    xmlsb.append(generatedXML.toString());
    generatedXML.sendData();
    //System.out.println("xml: " + xmlsb.toString());
}

From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java

private boolean doBind(String sUserID, String sPassword) throws OAException, UserException {
    StringBuffer sbTemp = null;/*  ww  w. j a  v a  2s  .com*/
    DirContext oDirContext = null;
    String sQuery = null;
    String sRelUserDn = null;
    boolean bResult = false;
    NamingEnumeration enumSearchResults = null;

    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl);
    htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver);
    htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (_bSSL) {
        htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    if (_sPrincipalDn.length() <= 0)
    // If no principal dn is known, we do a simple binding
    {
        String sEscUserID = JNDIUtil.escapeDN(sUserID);
        _logger.debug("Escaped user: " + sEscUserID);
        sbTemp = new StringBuffer(_sUserDn);
        sbTemp.append('=');
        sbTemp.append(sEscUserID);
        sbTemp.append(", ");
        sbTemp.append(_sBaseDn);
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());

        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            // If supplied credentials are invalid or when authentication fails
            // while accessing the directory or naming service.
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            // If communication with the directory or naming service fails.
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            // The initial dir context could not be created.
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {

            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e);
            }
        }
    } else //search through the subtree
    {
        // 1 - Try to bind to LDAP using the security principal's DN and its password
        htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
        } catch (AuthenticationException eA) {
            _logger.warn("Could not bind to LDAP server", eA);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 2 - Search through the context for user's DN relative to the base DN
        sQuery = resolveSearchQuery(sUserID);

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);

        try {
            enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope);
        } catch (NamingException eN) {
            _logger.warn("User id not found in password backend for user: " + sUserID, eN);
            throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        } finally {
            try {

                oDirContext.close();
                oDirContext = null;

            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e);
            }
        }

        try {
            if (!enumSearchResults.hasMoreElements()) {
                StringBuffer sb = new StringBuffer("User '");
                sb.append(sUserID);
                sb.append("' not found during LDAP search. The filter was: '");
                sb.append(sQuery);
                sb.append("'");
                _logger.warn(sb.toString());
                throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
            }

            SearchResult searchResult = (SearchResult) enumSearchResults.next();
            sRelUserDn = searchResult.getName();
            if (sRelUserDn == null) {
                _logger.warn("no user dn was returned for '" + sUserID + "'.");
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
        } catch (NamingException eN) {

            _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 3 - Bind user using supplied credentials
        sbTemp = new StringBuffer(sRelUserDn);
        sbTemp.append(",");
        sbTemp.append(_sBaseDn);

        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {
            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e);
            }
        }
    }
    return bResult;
}

From source file:net.spfbl.core.Analise.java

public static TreeSet<String> getIPSet(String hostname) {
    TreeSet<String> ipSet = new TreeSet<String>();
    try {/*ww  w .j  av  a  2s .  c  o  m*/
        Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" });
        if (attributesA != null) {
            Enumeration enumerationA = attributesA.getAll();
            while (enumerationA.hasMoreElements()) {
                Attribute attributeA = (Attribute) enumerationA.nextElement();
                NamingEnumeration enumeration = attributeA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv4.isValidIPv4(address)) {
                        address = SubnetIPv4.normalizeIPv4(address);
                        ipSet.add(address);
                    }
                }
            }
        }
        Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" });
        if (attributesAAAA != null) {
            Enumeration enumerationAAAA = attributesAAAA.getAll();
            while (enumerationAAAA.hasMoreElements()) {
                Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement();
                NamingEnumeration enumeration = attributeAAAA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv6.isValidIPv6(address)) {
                        address = SubnetIPv6.normalizeIPv6(address);
                        ipSet.add(address);
                    }
                }
            }
        }
    } catch (NameNotFoundException ex) {
        return null;
    } catch (NamingException ex) {
        // Ignore.
    }
    return ipSet;
}

From source file:net.spfbl.core.Analise.java

public static TreeSet<String> getIPv4Set(String hostname) {
    TreeSet<String> ipv4Set = new TreeSet<String>();
    try {/*from  w  w  w .  java2s . co m*/
        Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" });
        if (attributesA != null) {
            Enumeration enumerationA = attributesA.getAll();
            while (enumerationA.hasMoreElements()) {
                Attribute attributeA = (Attribute) enumerationA.nextElement();
                NamingEnumeration enumeration = attributeA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv4.isValidIPv4(address)) {
                        address = SubnetIPv4.normalizeIPv4(address);
                        ipv4Set.add(address);
                    }
                }
            }
        }
    } catch (NameNotFoundException ex) {
        return null;
    } catch (NamingException ex) {
        // Ignore.
    }
    return ipv4Set;
}

From source file:net.spfbl.core.Analise.java

public static TreeSet<String> getIPv6Set(String hostname) {
    TreeSet<String> ipv6Set = new TreeSet<String>();
    try {/*from ww w  .  j  a  v  a  2  s. co  m*/
        Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" });
        if (attributesAAAA != null) {
            Enumeration enumerationAAAA = attributesAAAA.getAll();
            while (enumerationAAAA.hasMoreElements()) {
                Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement();
                NamingEnumeration enumeration = attributeAAAA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv6.isValidIPv6(address)) {
                        address = SubnetIPv6.normalizeIPv6(address);
                        ipv6Set.add(address);
                    }
                }
            }
        }
    } catch (NameNotFoundException ex) {
        return null;
    } catch (NamingException ex) {
        // Ignore.
    }
    return ipv6Set;
}

From source file:net.spfbl.core.Reverse.java

public static boolean hasValidNameServers(String hostname) throws NamingException {
    if ((hostname = Domain.normalizeHostname(hostname, false)) == null) {
        return false;
    } else {/*from  w ww  . j  av  a2s .co m*/
        try {
            Attributes attributesNS = Server.getAttributesDNS(hostname, new String[] { "NS" });
            if (attributesNS != null) {
                Enumeration enumerationNS = attributesNS.getAll();
                while (enumerationNS.hasMoreElements()) {
                    Attribute attributeNS = (Attribute) enumerationNS.nextElement();
                    NamingEnumeration enumeration = attributeNS.getAll();
                    while (enumeration.hasMoreElements()) {
                        String ns = (String) enumeration.next();
                        if (Domain.isHostname(ns)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        } catch (NameNotFoundException ex) {
            return false;
        }
    }
}

From source file:net.spfbl.core.Reverse.java

public static TreeSet<String> getAddressSet(String hostname) throws NamingException {
    if ((hostname = Domain.normalizeHostname(hostname, false)) == null) {
        return null;
    } else {// w ww . j  a  v a  2  s.c  o  m
        TreeSet<String> ipSet = new TreeSet<String>();
        Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" });
        if (attributesA != null) {
            Enumeration enumerationA = attributesA.getAll();
            while (enumerationA.hasMoreElements()) {
                Attribute attributeA = (Attribute) enumerationA.nextElement();
                NamingEnumeration enumeration = attributeA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv4.isValidIPv4(address)) {
                        address = SubnetIPv4.normalizeIPv4(address);
                        ipSet.add(address);
                    }
                }
            }
        }
        Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" });
        if (attributesAAAA != null) {
            Enumeration enumerationAAAA = attributesAAAA.getAll();
            while (enumerationAAAA.hasMoreElements()) {
                Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement();
                NamingEnumeration enumeration = attributeAAAA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv6.isValidIPv6(address)) {
                        address = SubnetIPv6.normalizeIPv6(address);
                        ipSet.add(address);
                    }
                }
            }
        }
        return ipSet;
    }
}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'.
 * The user repository must be queried for this because the password is never retrieved from the repository 
 * and the User object does not contain it.  
 * /*from w  ww. j  a v  a  2s.  co  m*/
 */
public boolean isPasswordStored(String userId) throws RepositoryException {
    if (StringUtils.isBlank(userId)) {
        logger.debug("Insufficient data for getting user info.");
        throw new IllegalArgumentException();
    }
    String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))";

    final String PASSWD_ATTR_NAME = "userPassword";
    boolean passwordStored = false;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(1);
    ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            if (attrs.get(PASSWD_ATTR_NAME) != null)
                passwordStored = true;
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }

    return passwordStored;
}