Example usage for javax.naming.directory DirContext close

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

Introduction

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

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this context.

Usage

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

@Override
public void testEnded(String host) {
    for (Map.Entry<String, DirContext> entry : ldapContexts.entrySet()) {
        DirContext dc = entry.getValue();
        try {//from w w  w. j  av a2 s .co m
            log.warn("Tidying old Context for thread: " + entry.getKey());
            dc.close();
        } catch (NamingException ignored) {
            // ignored
        }
    }
    ldapContexts.clear();
}

From source file:org.apache.openaz.xacml.admin.view.components.LDAPPIPConfigurationComponent.java

protected void testLDAPConnection() {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, this.textFieldFactory.getValue());
    env.put(Context.PROVIDER_URL, this.textFieldProviderURL.getValue());
    env.put(Context.SECURITY_PRINCIPAL, this.textFieldPrincipal.getValue());
    env.put(Context.SECURITY_CREDENTIALS, this.textFieldCredentials.getValue());

    String auth = this.comboBoxAuthentication.getValue().toString();
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    ////from   w  w w. ja va 2  s.  co m
    // Do we need to do anything?
    //
    /*
    if (auth.equals(LDAP_AUTH_ANONYMOUS)) {
               
    } else if (auth.equals(LDAP_AUTH_SIMPLE)) {
               
    } else if (auth.equals(LDAP_AUTH_SASL)) {
               
    }
    */

    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true)
                .show(Page.getCurrent());
    } catch (NamingException e) {
        logger.error(e);
        new Notification("Connection Failed", "<br/>" + e.getLocalizedMessage(), Type.ERROR_MESSAGE, true)
                .show(Page.getCurrent());
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException idontcare) { //NOPMD
        }
    }
}

From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java

public void getAttributes(PIPRequest pipRequest, PIPFinder pipFinder, StdMutablePIPResponse mutablePIPResponse,
        LDAPResolver ldapResolver) throws PIPException {
    /*/*  w  w w . ja  v  a2 s.  c o  m*/
     * Check with the resolver to get the base string
     */
    String stringBase = ldapResolver.getBase(this, pipRequest, pipFinder);
    if (stringBase == null) {
        this.logger.warn(this.getName() + " does not handle " + pipRequest.toString());
        return;
    }

    /*
     * Get the filter string
     */
    String stringFilter = ldapResolver.getFilterString(this, pipRequest, pipFinder);

    /*
     * Check the cache
     */
    Cache<String, PIPResponse> cache = this.getCache();
    String cacheKey = stringBase + "::" + (stringFilter == null ? "" : stringFilter);
    if (cache != null) {
        PIPResponse pipResponse = cache.getIfPresent(cacheKey);
        if (pipResponse != null) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Returning cached response: " + pipResponse);
            }
            mutablePIPResponse.addAttributes(pipResponse.getAttributes());
            return;
        }
    }
    /*
     * Not in the cache, so set up the LDAP query session
     */
    DirContext dirContext = null;
    PIPResponse pipResponse = null;
    try {
        /*
         * Create the DirContext
         */
        dirContext = new InitialDirContext(this.ldapEnvironment);

        /*
         * Set up the search controls
         */
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(this.ldapScope);

        /*
         * Do the search
         */
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(stringBase, stringFilter,
                searchControls);
        if (namingEnumeration != null && namingEnumeration.hasMore()) {
            while (namingEnumeration.hasMore()) {
                List<Attribute> listAttributes = ldapResolver.decodeResult(namingEnumeration.next());
                if (listAttributes != null && listAttributes.size() > 0) {
                    mutablePIPResponse.addAttributes(listAttributes);
                }
            }
        }
        /*
         * Put in the cache
         */
        if (cache != null) {
            cache.put(cacheKey, pipResponse);
        }
    } catch (NamingException ex) {
        this.logger.error("NamingException creating the DirContext: " + ex.getMessage(), ex);
    } finally {
        if (dirContext != null) {
            try {
                dirContext.close();
            } catch (Exception ex) {
                this.logger.warn("Exception closing DirContext: " + ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.apache.syncope.fit.core.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    DerSchemaTO orig = schemaService.read(SchemaType.DERIVED, "displayProperty");
    DerSchemaTO modified = SerializationUtils.clone(orig);
    modified.setExpression("icon + '_' + show");

    GroupTO groupTO = GroupITCase.getSampleTO("lastGroup");
    try {//from ww w . java 2s . co m
        schemaService.update(SchemaType.DERIVED, modified);

        // 0. create group
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getResources().clear();

        groupTO = createGroup(groupTO).getEntity();
        assertNotNull(groupTO);

        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPriority(0);

        for (ProvisionTO provision : newLDAP.getProvisions()) {
            provision.getVirSchemas().clear();
        }

        MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).get().getMapping();

        ItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntAttrName("displayProperty");
        connObjectKey.setPurpose(MappingPurpose.PROPAGATION);
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        ItemTO description = new ItemTO();
        description.setIntAttrName("key");
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.PROPAGATION);
        mapping.add(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. update group and give the resource created above
        GroupPatch patch = new GroupPatch();
        patch.setKey(groupTO.getKey());
        patch.getResources().add(
                new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value("new-ldap").build());

        groupTO = updateGroup(patch).getEntity();
        assertNotNull(groupTO);

        // 3. update the group
        GroupPatch groupPatch = new GroupPatch();
        groupPatch.setKey(groupTO.getKey());
        groupPatch.getPlainAttrs().add(attrAddReplacePatch("icon", "anotherIcon"));

        groupTO = updateGroup(groupPatch).getEntity();
        assertNotNull(groupTO);

        // 4. check that a single group exists in LDAP for the group created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + groupTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        schemaService.update(SchemaType.DERIVED, orig);
        if (groupTO.getKey() != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.apache.syncope.fit.core.reference.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    GroupTO groupTO = null;/* w w  w .j a  v  a 2 s .  c o m*/
    try {
        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPrimary(true);

        MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).getMapping();

        MappingItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntMappingType(IntMappingType.GroupDerivedSchema);
        connObjectKey.setIntAttrName("displayProperty");
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        MappingItemTO description = new MappingItemTO();
        description.setIntMappingType(IntMappingType.GroupKey);
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.BOTH);
        mapping.add(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. create a group and give the resource created above
        groupTO = getSampleTO("lastGroup" + getUUIDString());
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getDerAttrs().add(attrTO("displayProperty", null));
        groupTO.getResources().clear();
        groupTO.getResources().add("new-ldap");

        groupTO = createGroup(groupTO);
        assertNotNull(groupTO);

        // 3. update the group
        GroupMod groupMod = new GroupMod();
        groupMod.setKey(groupTO.getKey());
        groupMod.getPlainAttrsToRemove().add("icon");
        groupMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon"));

        groupTO = updateGroup(groupMod);
        assertNotNull(groupTO);

        // 4. check that a single group exists in LDAP for the group created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + groupTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        if (groupTO != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.apache.syncope.fit.core.reference.RoleITCase.java

@Test
public void issueSYNCOPE632() {
    RoleTO roleTO = null;/*from   www  .  j  a  va 2s .  co  m*/
    try {
        // 1. create new LDAP resource having account id mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPrimary(true);
        MappingItemTO accountId = newLDAP.getRmapping().getAccountIdItem();
        accountId.setIntMappingType(IntMappingType.RoleDerivedSchema);
        accountId.setIntAttrName("displayProperty");
        newLDAP.getRmapping().setAccountIdItem(accountId);
        newLDAP.getRmapping().setAccountLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        MappingItemTO description = new MappingItemTO();
        description.setIntMappingType(IntMappingType.RoleId);
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.BOTH);
        newLDAP.getRmapping().addItem(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. create a role and give the resource created above
        roleTO = buildRoleTO("lastRole");
        roleTO.getRPlainAttrTemplates().add("icon");
        roleTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        roleTO.getRPlainAttrTemplates().add("show");
        roleTO.getPlainAttrs().add(attrTO("show", "true"));
        roleTO.getRDerAttrTemplates().add("displayProperty");
        roleTO.getDerAttrs().add(attrTO("displayProperty", null));
        roleTO.getResources().clear();
        roleTO.getResources().add("new-ldap");

        roleTO = createRole(roleTO);
        assertNotNull(roleTO);

        // 3. update the role
        RoleMod roleMod = new RoleMod();
        roleMod.setKey(roleTO.getKey());
        roleMod.getPlainAttrsToRemove().add("icon");
        roleMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon"));

        roleTO = updateRole(roleMod);
        assertNotNull(roleTO);

        // 4. check that a single group exists in LDAP for the role created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + roleTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        if (roleTO != null) {
            roleService.delete(roleTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.apereo.portal.ldap.ContextSourceLdapServerImpl.java

/**
 * @see org.apereo.portal.ldap.ILdapServer#releaseConnection(javax.naming.directory.DirContext)
 *///from   w  ww.java 2  s .c  o  m
public void releaseConnection(DirContext conn) {
    try {
        conn.close();
    } catch (NamingException ne) {
        this.logger.warn("An exception occured while closing DirContext='" + conn + "'", ne);
    }
}

From source file:org.ballerinalang.auth.ldap.util.LdapUtils.java

/**
 * Closes the directory context./*  w ww  .  ja  v a2  s .c  o  m*/
 *
 * @param dirContext directory context needs be closed
 * @throws NamingException if a naming exception is encountered
 */
public static void closeContext(DirContext dirContext) throws NamingException {
    if (dirContext != null) {
        dirContext.close();
    }
}

From source file:org.easy.ldap.LdapDao.java

public void updateRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;

    try {/*from   w  w  w  .j ava2s .  co  m*/
        ctx = contextFactory.createContext(rootDn.toString());

        ModificationItem[] modifications = new ModificationItem[1];

        Attribute attribute = new BasicAttribute(type.toString(), rdnValue);

        modifications[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute);

        ctx.modifyAttributes("", modifications);

    }

    catch (NamingException e) {
        throw new RuntimeException(type.toString() + "=" + rdnValue + "," + rootDn.toString(), e);
    }

    finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.debug(e);
            }
        }
    }
}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn//from  w  ww .j  a v  a 2s. c o m
 * @param type
 * @param rdnValue
 */
public void addRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());

        ModificationItem[] modifications = new ModificationItem[1];

        Attribute attribute = new BasicAttribute(type.toString(), rdnValue);

        modifications[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attribute);

        ctx.modifyAttributes("", modifications);

    }

    catch (NamingException e) {
        throw new RuntimeException(e);
    }

    finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.debug(e);
            }
        }
    }

}