List of usage examples for javax.naming.directory BasicAttributes BasicAttributes
public BasicAttributes()
From source file:net.e2.bw.servicereg.ldap.ServiceInstanceLdapService.java
/** {@inheritDoc} */ @Override/*from www . ja v a 2 s.c om*/ public ServiceInstance createServiceInstance(ServiceInstance service) { Objects.requireNonNull(service, "Invalid service instance"); Objects.requireNonNull(service.getServiceInstanceId(), "Service instance ID must be specified"); Objects.requireNonNull(service.getOrganizationId(), "Organization ID must be specified"); Objects.requireNonNull(service.getSpecificationId(), "Service specification ID must be specified"); Objects.requireNonNull(service.getName(), "Service instance name must be specified"); CachedServiceInstance existingSpec = getCachedServiceInstance(service.getServiceInstanceId()); if (existingSpec != null) { throw new RuntimeException( "A service instance already exists with the ID " + service.getServiceInstanceId()); } BasicAttributes attrs = new BasicAttributes(); attrs.put(createAttribute("objectClass", getConfig().getServiceInstanceObjectClasses().split(","))); attrs.put(createAttribute("cn", service.getName())); attrs.put(createAttribute("uid", service.getServiceInstanceId())); attrs.put(createAttribute("serviceOrganization", getGroupDN(service.getOrganizationId()))); attrs.put(createAttribute("serviceSpecification", getServiceSpecificationDN(service.getSpecificationId()))); if (service.getSummary() != null) { attrs.put(createAttribute("description", service.getSummary())); } byte[] coverage = compressCoverage(service.getCoverage()); if (coverage != null) { attrs.put(createBinaryAttribute("serviceCoverage", coverage)); } if (service.getEndpoints() != null && service.getEndpoints().size() > 0) { String[] endpoints = toEndpointArray(service.getEndpoints()); attrs.put(createAttribute("serviceEndpoint", endpoints)); } // Create the service instance in LDAP String serviceDN = getServiceInstanceDN(service.getServiceInstanceId()); try { ldapServerService.addEntry(serviceDN, attrs); } catch (NamingException e) { log.error("Failed creating service instance " + service.getServiceInstanceId(), e); throw new RuntimeException("Failed creating service instance " + service.getServiceInstanceId(), e); } // Return (and cache) the newly created service instance. return getServiceInstance(service.getServiceInstanceId()); }
From source file:org.easy.ldap.AdminServiceImpl.java
@Override public void addRole(String tenantId, String role) { try {// w ww. ja v a 2 s. c o m Attributes attributes = new BasicAttributes(); //get OU name for roles default is "Roles" Attribute cnAttr = new BasicAttribute(RdnType.CN.toString(), role); String roleRdnName = environment.getProperty(PropertyNames.ROLES_RDN); roleRdnName = roleRdnName.replace(RdnType.OU.toString() + "=", ""); Attribute ouAttr = new BasicAttribute(RdnType.OU.toString(), roleRdnName); //atleast one uniqueMember is required. String highestRole = environment.getProperty(PropertyNames.HIGHEST_ROLE); Attribute defaultMember = new BasicAttribute(RdnType.UNIQUE_MEMBER.toString(), ldapDao.getContextFactory().getNamingFactory().createRoleDn(tenantId, highestRole).toString()); // Add these to the container attributes.put(NamingFactory.getRoleObjectClasses()); attributes.put(cnAttr); attributes.put(ouAttr); attributes.put(defaultMember); LdapName rolesDn = namingFactory.createRolesDn(tenantId); Rdn roleRdn = namingFactory.createRoleRdn(role); ldapDao.createSubContext(rolesDn, roleRdn, attributes); } catch (InvalidNameException e) { log.error(e); throw new java.lang.RuntimeException(e); } catch (RuntimeException e) { log.error(e); throw new java.lang.RuntimeException(e); } }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Creates a new principal in a previously configured KDC * <p/>//from w ww . j a va2 s .c o m * The implementation is specific to a particular type of KDC. * * @param principal a String containing the principal to add * @param password a String containing the password to use when creating the principal * @param service a boolean value indicating whether the principal is to be created as a service principal or not * @return an Integer declaring the generated key number * @throws KerberosOperationException */ @Override public Integer createPrincipal(String principal, String password, boolean service) throws KerberosOperationException { if (!isOpen()) { throw new KerberosOperationException("This operation handler has not been opened"); } if (principal == null) { throw new KerberosOperationException("principal is null"); } if (password == null) { throw new KerberosOperationException("principal password is null"); } DeconstructedPrincipal deconstructedPrincipal = createDeconstructPrincipal(principal); String realm = deconstructedPrincipal.getRealm(); if (realm == null) { realm = ""; } Map<String, Object> context = new HashMap<String, Object>(); context.put("normalized_principal", deconstructedPrincipal.getNormalizedPrincipal()); context.put("principal_name", deconstructedPrincipal.getPrincipalName()); context.put("principal_primary", deconstructedPrincipal.getPrimary()); context.put("principal_instance", deconstructedPrincipal.getInstance()); context.put("realm", realm); context.put("realm_lowercase", realm.toLowerCase()); context.put("password", password); context.put("is_service", service); context.put("container_dn", this.principalContainerDn); context.put("principal_digest", DigestUtils.sha1Hex(deconstructedPrincipal.getNormalizedPrincipal())); Map<String, Object> data = processCreateTemplate(context); Attributes attributes = new BasicAttributes(); String cn = null; if (data != null) { for (Map.Entry<String, Object> entry : data.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if ("unicodePwd".equals(key)) { if (value instanceof String) { try { attributes.put(new BasicAttribute("unicodePwd", String.format("\"%s\"", password).getBytes("UTF-16LE"))); } catch (UnsupportedEncodingException ue) { throw new KerberosOperationException("Can not encode password with UTF-16LE", ue); } } } else { Attribute attribute = new BasicAttribute(key); if (value instanceof Collection) { for (Object object : (Collection) value) { attribute.add(object); } } else { attribute.add(value); if ("cn".equals(key) && (value != null)) { cn = value.toString(); } } attributes.put(attribute); } } } if (cn == null) { cn = deconstructedPrincipal.getNormalizedPrincipal(); } try { Name name = new CompositeName().add(String.format("cn=%s,%s", cn, principalContainerDn)); ldapContext.createSubcontext(name, attributes); } catch (NamingException ne) { throw new KerberosOperationException("Can not create principal : " + principal, ne); } return 0; }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
protected void updateSuffix(DirContext dirContext) { String ldapSuffix = getLDAPSuffix(); NamingEnumeration<SearchResult> namingEnum = null; try {/*from w w w . j a v a 2s. c o m*/ try { String dn = ldapSuffix; Attributes attributes = new BasicAttributes(); Attribute objclass = new BasicAttribute("objectclass"); objclass.add("organization"); objclass.add("dcObject"); attributes.put(objclass); attributes.put("dc", "tolven"); attributes.put("o", "myOrg"); dirContext.createSubcontext(dn, attributes); logger.info("Executed a createSubContext LDAP schema for " + ldapSuffix); } catch (NamingException ex) { //For some reason the search can fail, when the suffix is available, and when not available // The only certainty is to attempt to create it for now } } finally { if (namingEnum != null) { try { namingEnum.close(); } catch (NamingException ex) { throw new RuntimeException("Could not close the naming enumeration for the ldap suffix schema", ex); } } } }
From source file:CreateCorbaSchema.java
/** * Inserts object class definitions from RFC 2714 into the schema. * * This method maps the LDAP schema definitions in RFC 2714 onto the * proprietary attributes required by the Active Directory schema. * * The resulting object class definitions differ from those of RFC 2714 * in the following ways://from w ww . j a v a2 s . c om * * - Abstract and auxiliary classes are now defined as structural. * - The corbaObject class now inherits from corbaContainer. * - The corbaObjectReference class now inherits from corbaObject. * * The effect of these differences is that CORBA object references * cannot be mixed-in with other directory entries, they may only be * stored as stand-alone entries. * * The reason for these differences is due to the way auxiliary classes * are supported in Active Directory. Only the names of structural * classes (not auxiliary) may appear in the object class attribute of * an entry. Therefore, the abstract and auxiliary classes in the CORBA * schema definition is re-defined as structural. */ protected void insertADObjectClasses(DirContext rootCtx, DirContext schemaCtx) throws NamingException { System.out.println(" [inserting new object class definitions ...]"); String dn = schemaCtx.getNameInNamespace(); String attrID; attrID = new String("corbaContainer"); Attributes attrs1 = new BasicAttributes(); attrs1.put(new BasicAttribute("cn", attrID)); attrs1.put(new BasicAttribute("objectClass", "classSchema")); attrs1.put(new BasicAttribute("defaultHidingValue", "FALSE")); attrs1.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.10")); attrs1.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs1.put(new BasicAttribute("mustContain", "cn")); attrs1.put(new BasicAttribute("objectClassCategory", "1")); attrs1.put(new BasicAttribute("systemOnly", "FALSE")); attrs1.put(new BasicAttribute("subclassOf", "top")); attrs1.put(new BasicAttribute("possSuperiors", "top")); //any superior attrs1.put(new BasicAttribute("description", "Container for a CORBA object")); schemaCtx.createSubcontext("cn=" + attrID, attrs1); System.out.println(" [" + attrID + "]"); flushADSchemaMods(rootCtx); // corbaObject relys on corbaContainer attrID = new String("corbaObject"); Attributes attrs2 = new BasicAttributes(); attrs2.put(new BasicAttribute("cn", attrID)); attrs2.put(new BasicAttribute("objectClass", "classSchema")); attrs2.put(new BasicAttribute("defaultHidingValue", "FALSE")); attrs2.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.9")); attrs2.put(new BasicAttribute("lDAPDisplayName", attrID)); Attribute coMay = new BasicAttribute("mayContain"); coMay.add("corbaRepositoryId"); coMay.add("description"); attrs2.put(coMay); attrs2.put(new BasicAttribute("objectClassCategory", "1")); attrs2.put(new BasicAttribute("systemOnly", "FALSE")); attrs2.put(new BasicAttribute("subclassOf", "corbaContainer")); attrs2.put(new BasicAttribute("description", "CORBA object representation")); schemaCtx.createSubcontext("cn=" + attrID, attrs2); System.out.println(" [" + attrID + "]"); flushADSchemaMods(rootCtx); // corbaObjectReference relys on corbaObject attrID = new String("corbaObjectReference"); Attributes attrs3 = new BasicAttributes(); attrs3.put(new BasicAttribute("cn", attrID)); attrs3.put(new BasicAttribute("objectClass", "classSchema")); attrs3.put(new BasicAttribute("defaultHidingValue", "FALSE")); attrs3.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.11")); attrs3.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs3.put(new BasicAttribute("mustContain", "corbaIor")); attrs3.put(new BasicAttribute("objectClassCategory", "1")); attrs3.put(new BasicAttribute("systemOnly", "FALSE")); attrs3.put(new BasicAttribute("subclassOf", "corbaObject")); attrs3.put(new BasicAttribute("description", "CORBA interoperable object reference")); schemaCtx.createSubcontext("cn=" + attrID, attrs3); System.out.println(" [" + attrID + "]"); flushADSchemaMods(rootCtx); // finally }
From source file:org.easy.ldap.LdapDao.java
/** * @param rootDn//from w w w . j av a 2s .c o m * @param type * @return */ public List<String> findRdnValue(LdapName rootDn, RdnType type) { NamingEnumeration<SearchResult> result = null; List<String> out = new ArrayList<String>(0); DirContext ctx = null; try { ctx = contextFactory.createContext(rootDn.toString()); Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(type.toString())); result = ctx.search("", attributes); while (result.hasMore()) { attributes = result.next().getAttributes(); out.add(attributes.get(type.toString()).get().toString()); } } catch (NamingException e) { throw new RuntimeException(type.toString() + "," + rootDn.toString(), e); } finally { if (contextFactory != null) contextFactory.closeContext(ctx); } return out; }
From source file:ldap.SearchUtility.java
/** * This returns a list of all users that match the particular attribute value. * Often this will be a single user, in which case the list will only contain one value. If * you know this is the case, use the 'getUser()' form of this method instead. * @param attrType/*from w w w .ja v a 2 s. c o m*/ * @param attrValue * @return * @throws NamingException */ public List<Entry> getUsers(String attrType, String attrValue, DirContext context) throws NamingException { logger.info("getUsers(attrType,attrValue,context)"); List<Entry> users = new ArrayList<Entry>(); Attributes atts = new BasicAttributes(); atts.put(attrType, attrValue); //NamingEnumeration<SearchResult> userResults = context.search(new LdapName(Config.SEARCH_BASE_DN), attrType + "={0}", new String[] {attrValue}, getSearchControls()); NamingEnumeration<SearchResult> userResults = context.search(new LdapName(LdapConstants.ldapSearchBaseDn), attrType + "={0}", new String[] { attrValue }, getSearchControls()); while (userResults.hasMore()) { SearchResult userResult = userResults.next(); users.add(new Entry(userResult)); } return users; }
From source file:ldap.ActiveLoginImpl.java
/** * This does a light copy of an attributes list (such as a UserAccount, if we need to modify it but * want to keep the original userAccount) * @param oldAtts// w w w. jav a 2 s . c o m * @return a light copy of the original attributes list. */ public Attributes copyAttributes(Attributes oldAtts) { BasicAttributes atts = new BasicAttributes(); NamingEnumeration attList = oldAtts.getAll(); while (attList.hasMoreElements()) // shouldn't throw an exception, so use normal enumeration methods { Attribute att = (Attribute) attList.nextElement(); atts.put(att); } return atts; }
From source file:org.easy.ldap.AdminServiceImpl.java
@Override public void deleteRole(String tenantId, String role) { try {/* ww w .j a va2s.com*/ LdapName roleDn = namingFactory.createRoleDn(tenantId, role); LdapName rolesDn = namingFactory.createRolesDn(tenantId); Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(RdnType.UNIQUE_MEMBER.toString(), roleDn)); List<String> grantedRoles = ldapDao.findRdnValues(rolesDn, attributes, RdnType.CN); for (String grantedRole : grantedRoles) { LdapName grantedRoleDn = namingFactory.createRoleDn(tenantId, grantedRole); ldapDao.removeRdn(roleDn, RdnType.UNIQUE_MEMBER, grantedRoleDn.toString()); } Rdn roleRdn = namingFactory.createRoleRdn(role); ldapDao.deleteSubContext(rolesDn, roleRdn); } catch (NamingException e) { log.error(e); throw new java.lang.RuntimeException(e); } }
From source file:org.mule.transport.ldap.util.DSManager.java
public synchronized void start(final boolean allowAnon) throws Exception { if (running) { logger.debug("start() called while already running"); if (checkSocketNotConnected()) { logger.debug("start() forced"); } else {// ww w . j a v a 2s .c o m logger.debug("DS is already running, stop it, then start it."); try { stop(); } catch (final Exception e) { // TODO: handle exception } // throw new IllegalStateException("DS already running on port " // + port); } } logger.debug("DS is starting ..."); port = 10389; directoryService = new DefaultDirectoryService(); directoryService.setShutdownHookEnabled(false); // directoryService.getChangeLog().setEnabled(true); directoryService.setAllowAnonymousAccess(allowAnon); socketAcceptor = new SocketAcceptor(null); ldapService = new LdapService(); ldapService.setSocketAcceptor(socketAcceptor); ldapService.setDirectoryService(directoryService); ldapService.setIpPort(port); // ldapService.setIpAddress("gkar.kerb.de"); // ldapService.setAccessControlEnabled(false); // ldapService.setShutdownHookEnabled(false); ldapService.setAllowAnonymousAccess(allowAnon); // ldapService.getLdapsConfiguration().setIpPort(10636); // ldapService.getLdapsConfiguration().setEnabled(true); // ldapService.getLdapsConfiguration().setLdapsCertificateFile(new // File("src/test/resources/ldaps-server-cert.jks")); // ldapService.getLdapsConfiguration().setIpPort(10636); setupSaslMechanisms(ldapService); // S ldapSService = new LdapService(); ldapSService.setSocketAcceptor(socketAcceptor); ldapSService.setDirectoryService(directoryService); ldapSService.setIpPort(10636); ldapSService.setEnableLdaps(true); setupSaslMechanisms(ldapSService); // ldapSService.setConfidentialityRequired(true); ldapSService.setConfidentialityRequired(true); // ldapService.setIpAddress("gkar.kerb.de"); // ldapService.setAccessControlEnabled(false); // ldapService.setShutdownHookEnabled(false); ldapSService.setAllowAnonymousAccess(allowAnon); // ldapService.getLdapsConfiguration().setIpPort(10636); // ldapService.getLdapsConfiguration().setEnabled(true); // ldapService.getLdapsConfiguration().setLdapsCertificateFile(new // File("src/test/resources/ldaps-server-cert.jks")); // ldapService.getLdapsConfiguration().setIpPort(10636); setupSaslMechanisms(ldapSService); doDelete(directoryService.getWorkingDirectory()); directoryService.startup(); // java.security.cert.X509Certificate cert = // TlsKeyGenerator.getCertificate(directoryService.getAdminSession().lookup(new // LdapDN("uid=admin,ou=system")).getOriginalEntry()); final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream("src/test/resources/truststore_2.jks"), "changeit".toCharArray()); // java.security.cert.X509Certificate testcert = // (java.security.cert.X509Certificate) ks.getCertificate("test"); // logger.debug(testcert); // directoryService.getAdminSession().lookup(new // LdapDN("uid=admin,ou=system")).getOriginalEntry().put("userCertificate",testcert.getEncoded()); // logger.debug("type: "+testcert.getType()); final java.security.cert.X509Certificate cert = TlsKeyGenerator.getCertificate( directoryService.getAdminSession().lookup(new LdapDN("uid=admin,ou=system")).getOriginalEntry()); ks.setCertificateEntry("apachetmp", cert); final File tmpKs = new File("target/truststore_tmp.jks"); if (tmpKs.exists()) { boolean del = tmpKs.delete(); if (!del) { logger.error("Unable to delete " + tmpKs.getAbsolutePath()); // throw new Exception("Unable to delete // "+tmpKs.getAbsolutePath()); } } ks.store(new FileOutputStream("target/truststore_tmp.jks"), "changeit".toCharArray()); logger.debug(cert); // TODO shouldn't this be before calling configureLdapServer() ??? ldapService.addExtendedOperationHandler(new StartTlsHandler()); ldapService.addExtendedOperationHandler(new StoredProcedureExtendedOperationHandler()); ldapService.start(); ldapSService.addExtendedOperationHandler(new StartTlsHandler()); // ldapSService.add( new LdapsInitializer() ); ldapSService.addExtendedOperationHandler(new StoredProcedureExtendedOperationHandler()); ldapSService.start(); // dn: uid=admin,ou=system setContexts(ServerDNConstants.ADMIN_SYSTEM_DN, "secret"); setUpPartition(); importLdif(IOUtils.getResourceAsStream("examplecom.ldif", this.getClass())); final Attributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("userCertificate", "")); // sysRoot.modifyAttributes("uid=admin",LdapContext.REPLACE_ATTRIBUTE,attrs); logger.debug(rootDSE.getAuthenticatedPrincipal()); logger.debug(rootDSE.getAuthenticationLevel()); logger.debug(rootDSE.getEffectivePrincipal()); logger.debug(rootDSE.toString()); running = true; logger.debug("DS now started!"); }