List of usage examples for javax.naming Context PROVIDER_URL
String PROVIDER_URL
To view the source code for javax.naming Context PROVIDER_URL.
Click Source Link
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
private void doConnect(final StudioProgressMonitor monitor) throws NamingException { context = null;//from w ww .ja v a 2 s .c o m isConnected = true; // setup connection parameters String host = connection.getConnectionParameter().getHost(); int port = connection.getConnectionParameter().getPort(); long timeout = connection.getConnectionParameter().getTimeout(); useLdaps = connection.getConnectionParameter() .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.LDAPS; useStartTLS = connection.getConnectionParameter() .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.START_TLS; environment = new Hashtable<>(); Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences(); final boolean validateCertificates = preferences .getBoolean(ConnectionCoreConstants.PREFERENCE_VALIDATE_CERTIFICATES); String ldapCtxFactory = preferences.getString(ConnectionCoreConstants.PREFERENCE_LDAP_CONTEXT_FACTORY); environment.put(Context.INITIAL_CONTEXT_FACTORY, ldapCtxFactory); environment.put(JAVA_NAMING_LDAP_VERSION, "3"); //$NON-NLS-1$ // timeouts /* * Don't use a timeout when using ldaps: JNDI throws a SocketException when setting a timeout on SSL connections. * See https://bugs.openjdk.java.net/browse/JDK-8173451 */ if (!useLdaps) { if (timeout < 0) { timeout = 0; } environment.put(COM_SUN_JNDI_LDAP_CONNECT_TIMEOUT, Long.toString(timeout)); //$NON-NLS-1$ } environment.put(COM_SUN_JNDI_DNS_TIMEOUT_INITIAL, "2000"); //$NON-NLS-1$ environment.put(COM_SUN_JNDI_DNS_TIMEOUT_RETRIES, "3"); //$NON-NLS-1$ // ldaps:// if (useLdaps) { environment.put(Context.PROVIDER_URL, LdapUrl.LDAPS_SCHEME + host + ':' + port); environment.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$ // host name verification is done in StudioTrustManager environment.put(JAVA_NAMING_LDAP_FACTORY_SOCKET, validateCertificates ? StudioSSLSocketFactory.class.getName() : DummySSLSocketFactory.class.getName()); } else { environment.put(Context.PROVIDER_URL, LdapUrl.LDAP_SCHEME + host + ':' + port); } if (binaryAttributes != null) { setBinaryAttributes(binaryAttributes); } InnerRunnable runnable = new InnerRunnable() { public void run() { try { context = new InitialLdapContext(environment, null); if (useStartTLS) { try { StartTlsResponse tls = (StartTlsResponse) context .extendedOperation(new StartTlsRequest()); // deactivate host name verification at this level, // host name verification is done in StudioTrustManager tls.setHostnameVerifier((hostname, session) -> true); if (validateCertificates) { tls.negotiate(StudioSSLSocketFactory.getDefault()); } else { tls.negotiate(DummySSLSocketFactory.getDefault()); } } catch (Exception e) { namingException = new NamingException(e.getMessage() != null ? e.getMessage() : "Error while establishing TLS session"); //$NON-NLS-1$ namingException.setRootCause(e); context.close(); } } } catch (NamingException ne) { namingException = ne; } } }; runAndMonitor(runnable, monitor); if (runnable.getException() != null) { throw runnable.getException(); } else if (context != null) { // all OK } else { throw new NamingException("???"); //$NON-NLS-1$ } }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * Creates the directory context configuration. * /*from www . jav a 2 s . co m*/ * @param loginId * the user principal ID to use when establishing the connection * @param loginPassword * the password credentials to use when establishing the connection * @param isConnectionRetry * if true, the alternate URL will be employed * @return Hashtable<String,String> */ protected Hashtable<String, String> getDirectoryContextEnvironment(String loginId, String loginPassword, boolean isConnectionRetry) { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory); if (!isConnectionRetry) { env.put(Context.PROVIDER_URL, connectionUrl); } else if (alternateUrl != null) { env.put(Context.PROVIDER_URL, alternateUrl); } if (loginId != null) { env.put(Context.SECURITY_PRINCIPAL, loginId); } if (loginPassword != null) { env.put(Context.SECURITY_CREDENTIALS, loginPassword); } if (securityAuthentication != null) { env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication); } if (connectionProtocol != null) { env.put(Context.SECURITY_PROTOCOL, connectionProtocol); } if (referralStrategy != null) { env.put(Context.REFERRAL, referralStrategy); } if (connectionTimeout > 0) { env.put("com.sun.jndi.ldap.connect.timeout", connectionTimeout + ""); } return env; }
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Does a subtree search for an element given a pattern. Only the first * element found is considered, and all references are searched in order * until either a match is found or no more references are left to search. * @param ldap//from w w w . jav a 2 s .c om * A prepared LDAP context. * @param pattern * The search pattern. Must not include the character '*' or the * substring '\2a' to prevent possible LDAP exploits. * @return The element's relative DN, or <code>null</code> if none was * found. <code>null</code> is also returned if the search pattern * contains an illegal character or substring. * @throws BackendException * If there was a problem accessing the backend. Typical causes * include timeouts. */ private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException { // Check pattern for illegal content. String[] illegals = { "*", "\\2a" }; for (int i = 0; i < illegals.length; i++) { if (pattern.indexOf(illegals[i]) > -1) return null; } // The context provider URL, for later logging. String url = "unknown backend"; // Start counting the (milli)seconds and prepare for timeouts. long searchStart = System.currentTimeMillis(); JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket); NamingEnumeration results; try { // Remember the URL, for later logging. url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL); interruptTask.setURL(url); // Start timeout interruptor and perform the search. Timer interruptTimer = new Timer(); interruptTimer.schedule(interruptTask, (1000 * myTimeout)); results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout, new String[] {}, false, false)); interruptTimer.cancel(); if (!results.hasMore()) return null; } catch (TimeLimitExceededException e) { // The search timed out. log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket); return null; } catch (SizeLimitExceededException e) { // The search returned too many results. log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket); return null; } catch (NameNotFoundException e) { // Element not found. Possibly non-existing reference. log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary? return null; } catch (AuthenticationException e) { // Search failed authentication; check non-anonymous search config. try { final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL); final String errorMessage; if ((searchUser == null) || searchUser.equals("")) errorMessage = "Anonymous search failed authentication on " + url; else errorMessage = "Could not authenticate search user " + searchUser + " on " + url; log.logDebug(errorMessage, mySessionTicket); throw new BackendException(errorMessage, e); } catch (NamingException f) { // Should not happen! log.logCritical("Unable to read LDAP environment", mySessionTicket, f); throw new BackendException("Unable to read LDAP environment", f); } } catch (NamingException e) { // Did we interrupt the search ourselves? if (interruptTask.finished()) { final long elapsed = System.currentTimeMillis() - searchStart; log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms", mySessionTicket); throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms; connection terminated"); } // All other exceptions. log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e); return null; } // We just found at least one element. Did we get an ambigious result? SearchResult entry = null; try { entry = (SearchResult) results.next(); String buffer = new String(); while (results.hasMoreElements()) buffer = buffer + ", " + ((SearchResult) results.next()).getName(); if (!buffer.equals("")) log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName() + buffer + "]", mySessionTicket); // TODO: Throw BackendException, or a subclass, or just (as now) // pick the first and hope for the best? buffer = null; } catch (NamingException e) { throw new BackendException("Unable to read search results", e); } return entry.getName(); // Relative DN (to the reference). }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided * username and credential.// w w w .j av a 2s . c o m * * @return the Initial Ldap Context to be used to perform searches, etc. * @throws NamingException LDAP binding error. */ protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential) throws NamingException { Properties env = new Properties(); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory()); env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication()); env.setProperty(Context.PROVIDER_URL, getProviderUrl()); env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol())); // Set defaults for key values if they are missing String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (factoryName == null) { factoryName = "com.sun.jndi.ldap.LdapCtxFactory"; env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName); } String authType = env.getProperty(Context.SECURITY_AUTHENTICATION); if (authType == null) env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); String protocol = env.getProperty(Context.SECURITY_PROTOCOL); String providerURL = getProviderUrl(); // Use localhost if providerUrl not set if (providerURL == null) { providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389"); } else { // In case user configured provided URL if (providerURL.startsWith("ldaps")) { protocol = "ssl"; env.setProperty(Context.SECURITY_PROTOCOL, "ssl"); } } env.setProperty(Context.PROVIDER_URL, providerURL); if (securityPrincipal != null && !"".equals(securityPrincipal)) env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal); if (securityCredential != null && !"".equals(securityCredential)) env.put(Context.SECURITY_CREDENTIALS, securityCredential); // always follow referrals transparently env.put(Context.REFERRAL, "follow"); // Logon into LDAP server if (logger.isDebugEnabled()) logger.debug("Logging into LDAP server, env=" + env); InitialLdapContext ctx = new InitialLdapContext(env, null); if (logger.isDebugEnabled()) logger.debug("Logged into LDAP server, " + ctx); return ctx; }
From source file:com.adaptris.core.SharedComponentListTest.java
private JmsConnection createPtpConnection(String uniqueId) throws PasswordException { JmsConnection c = new JmsConnection(); StandardJndiImplementation jndi = new StandardJndiImplementation(); jndi.setJndiName("Connection_Factory_To_Lookup"); KeyValuePairSet kvps = jndi.getJndiParams(); kvps.addKeyValuePair(new KeyValuePair(Context.SECURITY_PRINCIPAL, "Administrator")); kvps.addKeyValuePair(new KeyValuePair(Context.SECURITY_CREDENTIALS, "Administrator")); kvps.addKeyValuePair(new KeyValuePair("com.sonicsw.jndi.mfcontext.domain", "Domain1")); kvps.addKeyValuePair(/*from ww w. j ava2 s . c o m*/ new KeyValuePair(Context.INITIAL_CONTEXT_FACTORY, "com.sonicsw.jndi.mfcontext.MFContextFactory")); jndi.getJndiParams().addKeyValuePair(new KeyValuePair(Context.PROVIDER_URL, "tcp://localhost:2506")); c.setVendorImplementation(jndi); if (!isEmpty(uniqueId)) { c.setUniqueId(uniqueId); } return c; }
From source file:hermes.browser.HermesBrowser.java
/** * Initialise the underlying Hermes that we're gonna do all our work with * /*from ww w .ja v a 2 s.c o m*/ * @throws HermesException * @throws NamingException */ public void loadConfig() throws NamingException, HermesException { Properties props = new Properties(); Context oldContext = context; HermesConfig oldConfig = null; props.put(Context.INITIAL_CONTEXT_FACTORY, HermesInitialContextFactory.class.getName()); props.put(Context.PROVIDER_URL, getCurrentConfigURL()); props.put("hermes.loader", JAXBHermesLoader.class.getName()); log.debug("props=" + props); Iterator listeners = null; if (loader != null) { listeners = loader.getConfigurationListeners(); oldConfig = loader.getConfig(); } if (oldConfig != null) { Set naming = new HashSet(); naming.addAll(oldConfig.getNaming()); for (Iterator iter = naming.iterator(); iter.hasNext();) { NamingConfig oldNaming = (NamingConfig) iter.next(); loader.notifyNamingRemoved(oldNaming); } } context = new InitialContext(props); loader = (HermesLoader) context.lookup(HermesContext.LOADER); if (listeners != null) { while (listeners.hasNext()) { loader.addConfigurationListener((HermesConfigurationListener) listeners.next()); } } if (oldContext != null) { for (NamingEnumeration iter = oldContext.listBindings(""); iter.hasMoreElements();) { Binding binding = (Binding) iter.next(); try { if (oldContext.lookup(binding.getName()) instanceof Hermes) { Hermes hermes = (Hermes) oldContext.lookup(binding.getName()); Hermes newHermes = null; try { newHermes = (Hermes) context.lookup(hermes.getId()); } catch (NamingException e) { // NOP } if (newHermes == null) { loader.notifyHermesRemoved(hermes); } } } catch (NamingException ex) { // NOP } } } if (!firstLoad) { closeWatches(); final ArrayList tmpList = new ArrayList(); tmpList.addAll(loader.getConfig().getWatch()); loader.getConfig().getWatch().clear(); for (Iterator iter = tmpList.iterator(); iter.hasNext();) { WatchConfig wConfig = (WatchConfig) iter.next(); createWatch(wConfig); } } setTitle("HermesJMS - " + TextUtils.crumble(getCurrentConfigURL(), 100)); }
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Creates a new connection to a given backend provider URL. * @param url// w w w .j a v a 2 s . co m * The backend provider URL. * @return The opened backend connection. * @throws NamingException * If unable to connect to the provider given by * <code>url</code>. */ private InitialLdapContext connect(final String url) throws NamingException { // Prepare connection. Hashtable<String, String> env = new Hashtable<String, String>(defaultEnv); env.put(Context.PROVIDER_URL, url); return new InitialLdapContext(env, null); }
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 {/* w w w .j a v a 2 s. co m*/ 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:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
/** * get the context for connection/*from ww w .ja va 2 s. c o m*/ * * @return */ @SuppressWarnings("unchecked") public Hashtable getEnvironment() { Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, _contextFactory); String url = null; if (_providerUrl != null) { url = _providerUrl; } else { if (_hostname != null) { url = "ldap://" + _hostname + "/"; if (_port != 0) { url += ":" + _port + "/"; } LOG.warn("Using hostname and port. Use providerUrl instead: " + url); } } env.put(Context.PROVIDER_URL, url); if (_authenticationMethod != null) { env.put(Context.SECURITY_AUTHENTICATION, _authenticationMethod); } if (_bindDn != null) { env.put(Context.SECURITY_PRINCIPAL, _bindDn); } if (_bindPassword != null) { env.put(Context.SECURITY_CREDENTIALS, _bindPassword); } env.put("com.sun.jndi.ldap.read.timeout", Long.toString(_timeoutRead)); env.put("com.sun.jndi.ldap.connect.timeout", Long.toString(_timeoutConnect)); // Set the SSLContextFactory to implementation that validates cert subject if (url != null && url.startsWith("ldaps") && _ldapsVerifyHostname) { try { URI uri = new URI(url); HostnameVerifyingSSLSocketFactory.setTargetHost(uri.getHost()); env.put("java.naming.ldap.factory.socket", "com.dtolabs.rundeck.jetty.jaas.HostnameVerifyingSSLSocketFactory"); } catch (URISyntaxException e) { throw new RuntimeException(e); } } return env; }
From source file:org.lsc.jndi.JndiServices.java
/** * Return the LDAP schema./*from ww w . java 2s.co m*/ * * @param attrsToReturn * list of attribute names to return (or null for all * 'standard' attributes) * @return the map of name => attribute * @throws NamingException * thrown if something goes wrong (bad */ @SuppressWarnings("unchecked") public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException { Map<String, List<String>> attrsResult = new HashMap<String, List<String>>(); // connect to directory Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment(); String baseUrl = (String) props.get(Context.PROVIDER_URL); baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/')); props.put(Context.PROVIDER_URL, baseUrl); DirContext schemaCtx = new InitialLdapContext(props, null); // find schema entry SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningAttributes(new String[] { "subschemaSubentry" }); NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc); SearchResult sr = null; Attribute subschemaSubentry = null; String subschemaSubentryDN = null; if (schemaDnSR.hasMore()) { sr = schemaDnSR.next(); } if (sr != null) { subschemaSubentry = sr.getAttributes().get("subschemaSubentry"); } if (subschemaSubentry != null && subschemaSubentry.size() > 0) { subschemaSubentryDN = (String) subschemaSubentry.get(); } if (subschemaSubentryDN != null) { // get schema attributes from subschemaSubentryDN Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN, attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" }); if (schemaAttrs != null) { for (String attr : attrsToReturn) { Attribute schemaAttr = schemaAttrs.get(attr); if (schemaAttr != null) { attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll())); } } } } return attrsResult; }