Example usage for javax.naming.directory DirContext unbind

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

Introduction

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

Prototype

public void unbind(Name name) throws NamingException;

Source Link

Document

Unbinds the named object.

Usage

From source file:com.ktds.ldap.populator.LdapTestUtils.java

/**
 * Clear the directory sub-tree starting with the node represented by the
 * supplied distinguished name.//from  w  w w.jav  a 2  s  . c  o  m
 *
 * @param ctx  The DirContext to use for cleaning the tree.
 * @param name the distinguished name of the root node.
 * @throws NamingException if anything goes wrong removing the sub-tree.
 */
public static void clearSubContexts(DirContext ctx, Name name) throws NamingException {

    NamingEnumeration enumeration = null;
    try {
        enumeration = ctx.listBindings(name);
        while (enumeration.hasMore()) {
            Binding element = (Binding) enumeration.next();
            Name childName = LdapUtils.newLdapName(element.getName());
            childName = LdapUtils.prepend(childName, name);

            try {
                ctx.unbind(childName);
            } catch (ContextNotEmptyException e) {
                clearSubContexts(ctx, childName);
                ctx.unbind(childName);
            }
        }
    } catch (NamingException e) {
        LOGGER.debug("Error cleaning sub-contexts", e);
    } finally {
        try {
            enumeration.close();
        } catch (Exception e) {
            // Never mind this
        }
    }
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Removes the user from the underlying identity provider.
 *
 * @param username this is the user that will be permanently removed
 * @throws PortalServiceException for any errors encountered
 *///  w w w. jav a  2s . co  m
public void removeUser(String username) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        List<String> roles = findRoles(username);
        for (String existingRole : roles) {
            removeRoleAssignment(ctx, username, existingRole);
        }
        ctx.unbind(MessageFormat.format(userDNPattern, username));
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to get groups.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public void removeRole(String roleName, DirContext context) throws MappingException {

    String groupName = findGroupName(roleName);

    try {/*from   w  w w.ja  v  a 2 s .  c o  m*/

        String dn = "cn=" + groupName + "," + this.groupsDn;

        context.unbind(dn);

        log.info("deleted group with dn:'{}", dn);

    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);

    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public void removeAllRoles(DirContext context) throws MappingException {
    //all mapped roles
    Collection<String> groups = ldapRoleMapperConfiguration.getLdapGroupMappings().keySet();

    try {/*  w  w w.ja  v  a 2 s.c om*/
        for (String groupName : groups) {

            String dn = "cn=" + groupName + "," + this.groupsDn;

            context.unbind(dn);

            log.debug("deleted group with dn:'{}", dn);
        }

    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);

    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }
}

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

/**
 * Delete a resource./*  w ww .java2 s  .  c  o m*/
 *
 * @param path      Path of the resource which is to be deleted
 * @param req       Servlet request
 * @param resp      Servlet response
 * @param setStatus Should the response status be set on
 *                  successful completion
 * @return Description of the Return Value
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus)
        throws ServletException, IOException {

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

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

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

    if (isLocked(path, ifHeader + lockTokenHeader)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return false;
    }

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

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

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

    if (!exists) {
        resp.sendError(WebdavStatus.SC_NOT_FOUND);
        return false;
    }

    boolean collection = (object instanceof DirContext);

    if (!collection) {
        try {
            resources.unbind(path);
        } catch (NamingException e) {
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
    } else {

        Hashtable errorList = new Hashtable();

        deleteCollection(req, resources, path, errorList);
        try {
            resources.unbind(path);
        } catch (NamingException e) {
            errorList.put(path, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        }

        if (!errorList.isEmpty()) {

            sendReport(req, resp, errorList);
            return false;
        }
    }
    if (setStatus) {
        resp.setStatus(WebdavStatus.SC_NO_CONTENT);
    }
    return true;
}

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

/**
 * Deletes a collection.//from  w ww . j  ava  2 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

private String performOperationDelete(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;//from   w w w. ja  v a  2 s  . c o m
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Delete attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Delete value: ***");
                    } else {
                        log.debug("Delete value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.REMOVE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   16 LDAP_NO_SUCH_ATTRIBUTE Indicates that the attribute specified in the modify or compare operation does not exist in the entry.
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 16 - No Such Attribute...
                    //   [LDAP: error code 32 - No Such Object...
                    // AD:
                    //   [LDAP: error code 16 - 00002085: AtrErr: DSID-03151F03, #1...
                    if (e.getMessage().startsWith("[LDAP: error code 16 - ")
                            || e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_DELETE;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            dirContext.unbind(entryName);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
            // Sun:
            //   [LDAP: error code 32 - No Such Object...
            if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                if (log.isDebugEnabled())
                    log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                return DEFAULT_RESULT_DELETE;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(
                        "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }
}

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 a2 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.projectforge.business.ldap.LdapDao.java

public void delete(final DirContext ctx, final T obj) throws NamingException {
    final String dn = buildDn(null, obj);
    log.info("Delete " + getObjectClass() + ": " + dn + ": " + getLogInfo(obj));
    ctx.unbind(dn);
}

From source file:org.springframework.ldap.core.LdapTemplate.java

private void doUnbind(final Name dn) {
    executeReadWrite(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            ctx.unbind(dn);
            return null;
        }//w w  w .java  2s.c o  m
    });
}