List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:org.wso2.carbon.appfactory.s4.integration.DomainMappingManagementService.java
/** * Resolve CNAME and A records for the given {@code hostname}. * * @param domain hostname to be resolved. * @param environmentConfigs environment configuration * @return {@link com.google.common.collect.Multimap} of resolved dns entries. This {@link com.google.common.collect.Multimap} will contain the resolved * "CNAME" and "A" records from the given {@code hostname} * @throws AppFactoryException if error occurred while the operation *//*from ww w .j a v a 2 s.c o m*/ public Multimap<String, String> resolveDNS(String domain, Hashtable<String, String> environmentConfigs) throws AppFactoryException, DomainMappingVerificationException { // result mutimap of dns records. Contains the cname and records resolved by the given hostname // ex: CNAME => foo.com,bar.com // A => 192.1.2.3 , 192.3.4.5 Multimap<String, String> dnsRecordsResult = ArrayListMultimap.create(); Attributes dnsRecords; boolean isARecordFound = false; boolean isCNAMEFound = false; try { if (log.isDebugEnabled()) { log.debug("DNS validation: resolving DNS for " + domain + " " + "(A/CNAME)"); } DirContext context = new InitialDirContext(environmentConfigs); String[] dnsRecordsToCheck = new String[] { DNS_A_RECORD, DNS_CNAME_RECORD }; dnsRecords = context.getAttributes(domain, dnsRecordsToCheck); } catch (NamingException e) { String msg = "DNS validation: DNS query failed for: " + domain + ". Error occurred while configuring " + "directory context."; log.error(msg, e); throw new AppFactoryException(msg, e); } try { // looking for for A records Attribute aRecords = dnsRecords.get(DNS_A_RECORD); if (aRecords != null && aRecords.size() > 0) { // if an A record exists NamingEnumeration aRecordHosts = aRecords.getAll(); // get all resolved A entries String aHost; while (aRecordHosts.hasMore()) { isARecordFound = true; aHost = (String) aRecordHosts.next(); dnsRecordsResult.put(DNS_A_RECORD, aHost); if (log.isDebugEnabled()) { log.debug("DNS validation: A record found: " + aHost); } } } // looking for CNAME records Attribute cnameRecords = dnsRecords.get(DNS_CNAME_RECORD); if (cnameRecords != null && cnameRecords.size() > 0) { // if CNAME record exists NamingEnumeration cnameRecordHosts = cnameRecords.getAll(); // get all resolved CNAME entries for hostname String cnameHost; while (cnameRecordHosts.hasMore()) { isCNAMEFound = true; cnameHost = (String) cnameRecordHosts.next(); if (cnameHost.endsWith(".")) { // Since DNS records are end with "." we are removing it. // For example real dns entry for www.google.com is www.google.com. cnameHost = cnameHost.substring(0, cnameHost.lastIndexOf('.')); } dnsRecordsResult.put(DNS_CNAME_RECORD, cnameHost); if (log.isDebugEnabled()) { log.debug("DNS validation: recurring on CNAME record towards host " + cnameHost); } dnsRecordsResult.putAll(resolveDNS(cnameHost, environmentConfigs)); // recursively resolve cnameHost } } if (!isARecordFound && !isCNAMEFound && log.isDebugEnabled()) { log.debug("DNS validation: No CNAME or A record found for domain: '" + domain); } return dnsRecordsResult; } catch (NamingException ne) { String msg = "DNS validation: DNS query failed for: " + domain + ". Provided domain: " + domain + " might be a " + "non existing domain."; // we are logging this as warn messages since this is caused, due to an user error. For example if the // user entered a rubbish custom url(Or a url which is, CNAME record is not propagated at the // time of adding the url), then url validation will fail but it is not an system error log.warn(msg, ne); throw new DomainMappingVerificationException(msg, ne); } }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
private DirContext createBindUserDirContext(final String userDn, final Object password) throws NamingException { if (null != userBindDirContextCreator) { return userBindDirContextCreator.createBindUserDirContext(userDn, password); }/*from ww w.j av a2 s . c om*/ Hashtable environment = getEnvironment(); environment.put(Context.SECURITY_PRINCIPAL, userDn); environment.put(Context.SECURITY_CREDENTIALS, password); return new InitialDirContext(environment); }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
@SuppressWarnings("unchecked") public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { super.initialize(subject, callbackHandler, sharedState, options); initializeOptions(options);/*from w ww . j a v a 2s .c o m*/ try { _rootContext = new InitialDirContext(getEnvironment()); } catch (NamingException ex) { LOG.error("Naming error", ex); throw new IllegalStateException("Unable to establish root context: " + ex.getMessage()); } }
From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java
boolean isLdapValid(final Credentials credentials) throws RepositoryException { LdapUser ldapUser = getLdapAuthData(credentials); if (ldapUser != null) { Hashtable<String, String> authEnv = new Hashtable<String, String>(11); //String dn = "uid=" + ldapUser.getUserName() + "," + ldapBase; String dn = StringUtils.replace(ldapBase, "${userName}", ldapUser.getUserName()); authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); authEnv.put(Context.PROVIDER_URL, ldapUrl); authEnv.put(Context.SECURITY_AUTHENTICATION, ldapAuthenticationType); authEnv.put(Context.SECURITY_PRINCIPAL, dn); authEnv.put(Context.SECURITY_CREDENTIALS, ldapUser.getPassword()); try {//from w w w .ja va2 s. c om DirContext ctx = new InitialDirContext(authEnv); Attributes attributes = ctx.getAttributes(dn); ldapUser.setAttributes(attributes); return true; } catch (AuthenticationException authEx) { return false; } catch (NamingException namEx) { throw new RepositoryException("Ldap Error:" + namEx.getExplanation()); } } // no authdata, not valid return false; }
From source file:net.spfbl.core.Server.java
@SuppressWarnings("unchecked") public static void initDNS() throws NamingException { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); env.put("com.sun.jndi.dns.timeout.initial", "3000"); env.put("com.sun.jndi.dns.timeout.retries", "1"); if (DNS_PROVIDER != null) { env.put("java.naming.provider.url", "dns://" + DNS_PROVIDER); }//from w ww .j av a 2 s . co m INITIAL_DIR_CONTEXT = new InitialDirContext(env); }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * This method uses JNDI to look up an address in DNS and return its name * //from www.j a va 2 s . co m * @param addr * * @return the host name associated with the address or null if lookup isn't possible or there is * no host name for this address */ public static String reverseDNS(InetAddress addr) { byte[] addrBytes = addr.getAddress(); // reverse the address suitable for reverse lookup String lookup = ""; for (int index = addrBytes.length - 1; index >= 0; index--) { lookup = lookup + (addrBytes[index] & 0xff) + '.'; } lookup += "in-addr.arpa"; // System.out.println("Looking up: " + lookup); try { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(lookup, new String[] { "PTR" }); for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) { Attribute attr = (Attribute) ae.next(); for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { Object elem = vals.nextElement(); if ("PTR".equals(attr.getID()) && elem != null) { return elem.toString(); } } } ctx.close(); } catch (Exception e) { // ignored } return null; }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
/** * Retrieves the DirContext from the JNDI environment and sets the <code>providerURL</code> back to <code>ldapProviderURL</code> if specified. * @throws ParameterException //from w w w . jav a 2s .c o m * */ protected synchronized DirContext loopkupDirContext(Map paramValueMap) throws NamingException, ParameterException { DirContext dirContext; if (jndiEnv == null) { Hashtable newJndiEnv = getJndiEnv(); //newJndiEnv.put("com.sun.jndi.ldap.trace.ber", System.err);//ldap response in log for debug purposes if (getLdapProviderURL() != null) { //Overwriting the (realm)providerURL if specified in configuration newJndiEnv.put("java.naming.provider.url", getLdapProviderURL()); } if (principalParameterFound) { newJndiEnv.put(Context.SECURITY_PRINCIPAL, paramValueMap.get("principal")); newJndiEnv.put(Context.SECURITY_CREDENTIALS, paramValueMap.get("credentials")); } if (isUsePooling()) { // Enable connection pooling newJndiEnv.put("com.sun.jndi.ldap.connect.pool", "true"); //see http://java.sun.com/products/jndi/tutorial/ldap/connect/config.html // newJndiEnv.put("com.sun.jndi.ldap.connect.pool.maxsize", "20" ); // newJndiEnv.put("com.sun.jndi.ldap.connect.pool.prefsize", "10" ); // newJndiEnv.put("com.sun.jndi.ldap.connect.pool.timeout", "300000" ); } else { // Disable connection pooling newJndiEnv.put("com.sun.jndi.ldap.connect.pool", "false"); } if (log.isDebugEnabled()) log.debug("created environment for LDAP provider URL [" + newJndiEnv.get("java.naming.provider.url") + "]"); dirContext = (DirContext) new InitialDirContext(newJndiEnv); if (!principalParameterFound) { jndiEnv = newJndiEnv; } } else { dirContext = (DirContext) new InitialDirContext(jndiEnv); } return dirContext; // return (DirContext) dirContextTemplate.lookup(""); // return copy to be thread-safe }
From source file:org.akaza.openclinica.controller.SystemController.java
public HashMap<String, Object> getLdapModule(StudyBean studyBean) { String enabled = CoreResources.getField("ldap.enabled"); String ldapHost = CoreResources.getField("ldap.host"); String username = CoreResources.getField("ldap.userDn"); String password = CoreResources.getField("ldap.password"); String result = ""; Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapHost); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, username); // replace with user DN env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = null;/*from ww w. j a v a2 s. co m*/ try { ctx = new InitialDirContext(env); result = "ACTIVE"; } catch (Exception e) { result = "INACTIVE"; } HashMap<String, String> mapMetadata = new HashMap<>(); mapMetadata.put("ldap.host", ldapHost); HashMap<String, Object> mapWebService = new HashMap<>(); mapWebService.put("enabled", enabled.equalsIgnoreCase("true") ? "True" : "False"); mapWebService.put("status", result); mapWebService.put("metadata", mapMetadata); HashMap<String, Object> mapModule = new HashMap<>(); mapModule.put("Ldap", mapWebService); return mapModule; }
From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java
/** * @param contextEnv Environment properties to build a {@link InitialDirContext} * @since 6.0//from w w w. j a va 2s. co m */ public void checkLdapConnection(Hashtable<Object, Object> contextEnv) throws NamingException { DirContext dirContext = new InitialDirContext(contextEnv); dirContext.close(); }