List of usage examples for javax.naming NamingException NamingException
public NamingException(String explanation)
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Modifies attributes of an entry.//from w w w. ja v a 2 s.c o m * * @param dn the Dn * @param modificationItems the modification items * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ public void modifyEntry(final String dn, final ModificationItem[] modificationItems, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { if (connection.isReadOnly()) { monitor.reportError( new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName()))); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // create modify context LdapContext modCtx = context.newInstance(controls); // use "throw" as we handle referrals manually modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW); // perform modification modCtx.modifyAttributes(getSaveJndiName(dn), modificationItems); } catch (ReferralException re) { try { ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo); Referral referral = newReferralsInfo.getNextReferral(); if (referral != null) { Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral, monitor, this); if (referralConnection != null) { List<String> urls = new ArrayList<>(referral.getLdapUrls()); String referralDn = new LdapUrl(urls.get(0)).getDn().getName(); referralConnection.getConnectionWrapper().modifyEntry(referralDn, modificationItems, controls, monitor, newReferralsInfo); } else { canceled = true; } } return; } catch (NamingException ne) { namingException = ne; } catch (LdapURLEncodingException e) { namingException = new NamingException(e.getMessage()); } } catch (NamingException ne) { namingException = ne; } for (IJndiLogger logger : getJndiLoggers()) { logger.logChangetypeModify(connection, dn, modificationItems, controls, namingException); } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (NamingException ne) { monitor.reportError(ne); } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Creates an entry.//from w ww. j av a 2 s. co m * * @param dn the entry's Dn * @param attributes the entry's attributes * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ public void createEntry(final String dn, final Attributes attributes, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { if (connection.isReadOnly()) { monitor.reportError( new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName()))); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // create modify context LdapContext modCtx = context.newInstance(controls); // use "throw" as we handle referrals manually modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW); // create entry modCtx.createSubcontext(getSaveJndiName(dn), attributes); } catch (ReferralException re) { try { ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo); Referral referral = newReferralsInfo.getNextReferral(); if (referral != null) { Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral, monitor, this); if (referralConnection != null) { List<String> urls = new ArrayList<>(referral.getLdapUrls()); String referralDn = new LdapUrl(urls.get(0)).getDn().getName(); referralConnection.getConnectionWrapper().createEntry(referralDn, attributes, controls, monitor, newReferralsInfo); } else { canceled = true; } } } catch (NamingException ne) { namingException = ne; } catch (LdapURLEncodingException e) { namingException = new NamingException(e.getMessage()); } } catch (NamingException ne) { namingException = ne; } for (IJndiLogger logger : getJndiLoggers()) { logger.logChangetypeAdd(connection, dn, attributes, controls, namingException); } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (NamingException ne) { monitor.reportError(ne); } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Deletes an entry.//from w ww. j av a2 s .c om * * @param dn the Dn of the entry to delete * @param controls the controls * @param monitor the progress monitor * @param referralsInfo the referrals info */ public void deleteEntry(final String dn, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { if (connection.isReadOnly()) { monitor.reportError( new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName()))); return; } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // create modify context LdapContext modCtx = context.newInstance(controls); // use "throw" as we handle referrals manually modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW); // delete entry modCtx.destroySubcontext(getSaveJndiName(dn)); } catch (ReferralException re) { try { ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo); Referral referral = newReferralsInfo.getNextReferral(); if (referral != null) { Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral, monitor, this); if (referralConnection != null) { List<String> urls = new ArrayList<>(referral.getLdapUrls()); String referralDn = new LdapUrl(urls.get(0)).getDn().getName(); referralConnection.getConnectionWrapper().deleteEntry(referralDn, controls, monitor, newReferralsInfo); } else { canceled = true; } } } catch (NamingException ne) { namingException = ne; } catch (LdapURLEncodingException e) { namingException = new NamingException(e.getMessage()); } } catch (NamingException ne) { namingException = ne; } for (IJndiLogger logger : getJndiLoggers()) { logger.logChangetypeDelete(connection, dn, controls, namingException); } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (NamingException ne) { monitor.reportError(ne); } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
private void doConnect(final StudioProgressMonitor monitor) throws NamingException { context = null;//from ww w. j av a2 s . co 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.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
private void doBind(final StudioProgressMonitor monitor) throws NamingException { if (context != null && isConnected) { // setup authentication methdod authMethod = AUTHMETHOD_NONE;// www . j a va 2 s.com if (connection.getConnectionParameter() .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SIMPLE) { authMethod = AUTHMETHOD_SIMPLE; } else if (connection.getConnectionParameter() .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5) { authMethod = AUTHMETHOD_DIGEST_MD5; saslRealm = connection.getConnectionParameter().getSaslRealm(); } else if (connection.getConnectionParameter() .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_CRAM_MD5) { authMethod = AUTHMETHOD_CRAM_MD5; } else if (connection.getConnectionParameter() .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI) { authMethod = AUTHMETHOD_GSSAPI; } // No Authentication if (authMethod == AUTHMETHOD_NONE) { bindPrincipal = ""; //$NON-NLS-1$ bindCredentials = ""; //$NON-NLS-1$ } else { // setup credentials IAuthHandler authHandler = ConnectionCorePlugin.getDefault().getAuthHandler(); if (authHandler == null) { NamingException namingException = new NamingException(Messages.model__no_auth_handler); monitor.reportError(Messages.model__no_auth_handler, namingException); throw namingException; } ICredentials credentials = authHandler.getCredentials(connection.getConnectionParameter()); if (credentials == null) { CancelException cancelException = new CancelException(); monitor.setCanceled(true); monitor.reportError(Messages.model__no_credentials, cancelException); throw cancelException; } if (credentials.getBindPrincipal() == null || credentials.getBindPassword() == null) { NamingException namingException = new NamingException(Messages.model__no_credentials); monitor.reportError(Messages.model__no_credentials, namingException); throw namingException; } bindPrincipal = credentials.getBindPrincipal(); bindCredentials = credentials.getBindPassword(); } InnerRunnable runnable = new InnerRunnable() { public void run() { try { context.removeFromEnvironment(Context.SECURITY_AUTHENTICATION); context.removeFromEnvironment(Context.SECURITY_PRINCIPAL); context.removeFromEnvironment(Context.SECURITY_CREDENTIALS); context.removeFromEnvironment(JAVA_NAMING_SECURITY_SASL_REALM); context.addToEnvironment(Context.SECURITY_AUTHENTICATION, authMethod); // SASL options if (connection.getConnectionParameter() .getAuthMethod() == AuthenticationMethod.SASL_CRAM_MD5 || connection.getConnectionParameter() .getAuthMethod() == AuthenticationMethod.SASL_DIGEST_MD5 || connection.getConnectionParameter() .getAuthMethod() == AuthenticationMethod.SASL_GSSAPI) { // Request quality of protection switch (connection.getConnectionParameter().getSaslQop()) { case AUTH: context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH.getValue()); break; case AUTH_INT: context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH_INT.getValue()); break; case AUTH_CONF: context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH_CONF.getValue()); break; } // Request mutual authentication if (connection.getConnectionParameter().isSaslMutualAuthentication()) { context.addToEnvironment(Sasl.SERVER_AUTH, "true"); //$NON-NLS-1$ } else { context.removeFromEnvironment(Sasl.SERVER_AUTH); } // Request cryptographic protection strength switch (connection.getConnectionParameter().getSaslSecurityStrength()) { case HIGH: context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.HIGH.getValue()); break; case MEDIUM: context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.MEDIUM.getValue()); break; case LOW: context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.LOW.getValue()); break; } } // Bind if (connection.getConnectionParameter() .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI) { // GSSAPI doGssapiBind(this); } else { // no GSSAPI context.addToEnvironment(Context.SECURITY_PRINCIPAL, bindPrincipal); context.addToEnvironment(Context.SECURITY_CREDENTIALS, bindCredentials); if (connection.getConnectionParameter() .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5 && StringUtils.isNotEmpty(saslRealm)) { context.addToEnvironment(JAVA_NAMING_SECURITY_SASL_REALM, saslRealm); } context.reconnect(context.getConnectControls()); } } 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$ } } else { throw new NamingException(NO_CONNECTION); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
private void checkConnectionAndRunAndMonitor(final InnerRunnable runnable, final StudioProgressMonitor monitor) throws NamingException { // check connection if (!isConnected || context == null) { doConnect(monitor);/*w w w . j ava2 s.c om*/ doBind(monitor); } if (context == null) { throw new NamingException(NO_CONNECTION); } // loop for reconnection for (int i = 0; i <= 1; i++) { runAndMonitor(runnable, monitor); // check reconnection if (i == 0 && ((runnable.getException() instanceof CommunicationException) || (runnable.getException() instanceof ServiceUnavailableException) || (runnable.getException() instanceof InsufficientResourcesException))) { doConnect(monitor); doBind(monitor); runnable.reset(); } else { break; } } }
From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportLdifRunnable.java
/** * Imports the LDIF record./* w ww . j a v a 2 s . com*/ * * @param browserConnection the browser connection * @param record the LDIF record * @param updateIfEntryExists the update if entry exists flag * @param monitor the progress monitor * * @throws NamingException the naming exception * @throws LdapInvalidDnException */ static void importLdifRecord(IBrowserConnection browserConnection, LdifRecord record, boolean updateIfEntryExists, StudioProgressMonitor monitor) throws NamingException, LdapInvalidDnException { if (!record.isValid()) { throw new NamingException( BrowserCoreMessages.bind(BrowserCoreMessages.model__invalid_record, record.getInvalidString())); } String dn = record.getDnLine().getValueAsString(); if (record instanceof LdifContentRecord || record instanceof LdifChangeAddRecord) { LdifAttrValLine[] attrVals; IEntry dummyEntry; if (record instanceof LdifContentRecord) { LdifContentRecord attrValRecord = (LdifContentRecord) record; attrVals = attrValRecord.getAttrVals(); try { dummyEntry = ModelConverter.ldifContentRecordToEntry(attrValRecord, browserConnection); } catch (LdapInvalidDnException e) { monitor.reportError(e); return; } } else { LdifChangeAddRecord changeAddRecord = (LdifChangeAddRecord) record; attrVals = changeAddRecord.getAttrVals(); try { dummyEntry = ModelConverter.ldifChangeAddRecordToEntry(changeAddRecord, browserConnection); } catch (LdapInvalidDnException e) { monitor.reportError(e); return; } } Attributes jndiAttributes = new BasicAttributes(); for (LdifAttrValLine attrVal : attrVals) { String attributeName = attrVal.getUnfoldedAttributeDescription(); Object realValue = attrVal.getValueAsObject(); if (jndiAttributes.get(attributeName) != null) { jndiAttributes.get(attributeName).add(realValue); } else { jndiAttributes.put(attributeName, realValue); } } browserConnection.getConnection().getConnectionWrapper().createEntry(dn, jndiAttributes, getControls(record), monitor, null); if (monitor.errorsReported() && updateIfEntryExists && monitor.getException() instanceof NameAlreadyBoundException) { // creation failed with Error 68, now try to update the existing entry monitor.reset(); ModificationItem[] mis = ModelConverter.entryToReplaceModificationItems(dummyEntry); browserConnection.getConnection().getConnectionWrapper().modifyEntry(dn, mis, getControls(record), monitor, null); } } else if (record instanceof LdifChangeDeleteRecord) { LdifChangeDeleteRecord changeDeleteRecord = (LdifChangeDeleteRecord) record; browserConnection.getConnection().getConnectionWrapper().deleteEntry(dn, getControls(changeDeleteRecord), monitor, null); } else if (record instanceof LdifChangeModifyRecord) { LdifChangeModifyRecord modifyRecord = (LdifChangeModifyRecord) record; LdifModSpec[] modSpecs = modifyRecord.getModSpecs(); ModificationItem[] mis = new ModificationItem[modSpecs.length]; for (int ii = 0; ii < modSpecs.length; ii++) { LdifModSpecTypeLine modSpecType = modSpecs[ii].getModSpecType(); LdifAttrValLine[] attrVals = modSpecs[ii].getAttrVals(); Attribute attribute = new BasicAttribute(modSpecType.getUnfoldedAttributeDescription()); for (int x = 0; x < attrVals.length; x++) { attribute.add(attrVals[x].getValueAsObject()); } if (modSpecType.isAdd()) { mis[ii] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attribute); } else if (modSpecType.isDelete()) { mis[ii] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute); } else if (modSpecType.isReplace()) { mis[ii] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute); } } browserConnection.getConnection().getConnectionWrapper().modifyEntry(dn, mis, getControls(modifyRecord), monitor, null); } else if (record instanceof LdifChangeModDnRecord) { LdifChangeModDnRecord modDnRecord = (LdifChangeModDnRecord) record; if (modDnRecord.getNewrdnLine() != null && modDnRecord.getDeloldrdnLine() != null) { String newRdn = modDnRecord.getNewrdnLine().getValueAsString(); boolean deleteOldRdn = modDnRecord.getDeloldrdnLine().isDeleteOldRdn(); Dn newDn; if (modDnRecord.getNewsuperiorLine() != null) { newDn = new Dn(newRdn, modDnRecord.getNewsuperiorLine().getValueAsString()); } else { Dn dnObject = new Dn(dn); Dn parent = dnObject.getParent(); newDn = new Dn(newRdn, parent.getName()); } browserConnection.getConnection().getConnectionWrapper().renameEntry(dn, newDn.toString(), deleteOldRdn, getControls(modDnRecord), monitor, null); } } }
From source file:org.apache.jmeter.protocol.jms.client.InitialContextFactory.java
/** * Look up the context from the local cache, creating it if necessary. * //from w ww. j a v a 2s. com * @param initialContextFactory used to set the property {@link Context#INITIAL_CONTEXT_FACTORY} * @param providerUrl used to set the property {@link Context#PROVIDER_URL} * @param useAuth set <code>true</code> if security is to be used. * @param securityPrincipal used to set the property {@link Context#SECURITY_PRINCIPAL} * @param securityCredentials used to set the property {@link Context#SECURITY_CREDENTIALS} * @return the context, never <code>null</code> * @throws NamingException when creation of the context fails */ public static Context lookupContext(String initialContextFactory, String providerUrl, boolean useAuth, String securityPrincipal, String securityCredentials) throws NamingException { String cacheKey = createKey(Thread.currentThread().getId(), initialContextFactory, providerUrl, securityPrincipal, securityCredentials); Context ctx = MAP.get(cacheKey); if (ctx == null) { Properties props = new Properties(); props.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); props.setProperty(Context.PROVIDER_URL, providerUrl); if (useAuth && securityPrincipal != null && securityCredentials != null && securityPrincipal.length() > 0 && securityCredentials.length() > 0) { props.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal); props.setProperty(Context.SECURITY_CREDENTIALS, securityCredentials); log.info("authentication properties set"); } try { ctx = new InitialContext(props); } catch (NoClassDefFoundError | Exception e) { throw new NamingException(e.toString()); } // we want to return the context that is actually in the map // if it's the first put we will have a null result Context oldCtx = MAP.putIfAbsent(cacheKey, ctx); if (oldCtx != null) { // There was an object in map, destroy the temporary and return one in map (oldCtx) try { ctx.close(); } catch (Exception e) { // NOOP } ctx = oldCtx; } // else No object in Map, ctx is the one } return ctx; }
From source file:org.apache.jmeter.protocol.jms.client.InitialContextFactory.java
/** * Initialize the JNDI initial context//from w w w .java 2 s . co m * * @param useProps * if true, create a new InitialContext; otherwise use the other * parameters to call * {@link #lookupContext(String, String, boolean, String, String)} * @param initialContextFactory * name of the initial context factory (ignored if * <code>useProps</code> is <code>true</code>) * @param providerUrl * url of the provider to use (ignored if <code>useProps</code> * is <code>true</code>) * @param useAuth * <code>true</code> if auth should be used, <code>false</code> * otherwise (ignored if <code>useProps</code> is * <code>true</code>) * @param securityPrincipal * name of the principal to (ignored if <code>useProps</code> is * <code>true</code>) * @param securityCredentials * credentials for the principal (ignored if * <code>useProps</code> is <code>true</code>) * @return the context, never <code>null</code> * @throws NamingException * when creation of the context fails */ public static Context getContext(boolean useProps, String initialContextFactory, String providerUrl, boolean useAuth, String securityPrincipal, String securityCredentials) throws NamingException { if (useProps) { try { return new InitialContext(); } catch (NoClassDefFoundError | Exception e) { throw new NamingException(e.toString()); } } else { return lookupContext(initialContextFactory, providerUrl, useAuth, securityPrincipal, securityCredentials); } }
From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java
public LdapExpandedAuthenticator() throws NamingException, ConfigurationException { String authURL = null;/*from ww w .ja va 2 s.c o m*/ try { authURL = AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_URL, DEFAULT_URL); } catch (ConfigurationException ce) { logger.error("Configuration exception occurred retrieving: " + Property.JUDDI_AUTHENTICATOR_URL); throw new NamingException( Property.JUDDI_AUTHENTICATOR_URL + " missing from config or config is not available."); } init(authURL); }