Example usage for javax.naming NamingException NamingException

List of usage examples for javax.naming NamingException NamingException

Introduction

In this page you can find the example usage for javax.naming NamingException NamingException.

Prototype

public NamingException(String explanation) 

Source Link

Document

Constructs a new NamingException with an explanation.

Usage

From source file:org.apache.naming.NamingContext.java

/**
 * Binds a name to an object. All intermediate contexts and the target 
 * context (that named by all but terminal atomic component of the name) 
 * must already exist./*from  w w  w  .  j a  v  a 2s  .c o m*/
 * 
 * @param name the name to bind; may not be empty
 * @param object the object to bind; possibly null
 * @param rebind if true, then perform a rebind (ie, overwrite)
 * @exception NameAlreadyBoundException if name is already bound
 * @exception InvalidAttributesException if object did not supply all 
 * mandatory attributes
 * @exception NamingException if a naming exception is encountered
 */
protected void bind(Name name, Object obj, boolean rebind) throws NamingException {

    checkWritable();

    while ((!name.isEmpty()) && (name.get(0).length() == 0))
        name = name.getSuffix(1);
    if (name.isEmpty())
        throw new NamingException(sm.getString("namingContext.invalidName"));

    NamingEntry entry = (NamingEntry) bindings.get(name.get(0));

    if (name.size() > 1) {
        if (entry == null) {
            throw new NameNotFoundException(sm.getString("namingContext.nameNotBound", name.get(0)));
        }
        if (entry.type == NamingEntry.CONTEXT) {
            if (rebind) {
                ((Context) entry.value).rebind(name.getSuffix(1), obj);
            } else {
                ((Context) entry.value).bind(name.getSuffix(1), obj);
            }
        } else {
            throw new NamingException(sm.getString("namingContext.contextExpected"));
        }
    } else {
        if ((!rebind) && (entry != null)) {
            throw new NamingException(sm.getString("namingContext.alreadyBound", name.get(0)));
        } else {
            // Getting the type of the object and wrapping it within a new
            // NamingEntry
            Object toBind = NamingManager.getStateToBind(obj, name, this, env);
            if (toBind instanceof Context) {
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT);
            } else if (toBind instanceof LinkRef) {
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF);
            } else if (toBind instanceof Reference) {
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE);
            } else if (toBind instanceof Referenceable) {
                toBind = ((Referenceable) toBind).getReference();
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE);
            } else {
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY);
            }
            bindings.put(name.get(0), entry);
        }
    }

}

From source file:org.apache.naming.NamingContext.java

/**
 * Throws a naming exception is Context is not writable.
 *//*from  www .  ja  va2s .c o  m*/
protected void checkWritable() throws NamingException {
    if (!isWritable())
        throw new NamingException(sm.getString("namingContext.readOnly"));
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

/**
 * This overrides the implementation of queryForAuthenticationInfo inside JndiLdapRealm.
 * In addition to calling the super method for authentication it also tries to validate
 * if this user has atleast one of the allowed roles for authentication. In case the property
 * allowedRolesForAuthentication is empty this check always returns true.
 *
 * @param token the submitted authentication token that triggered the authentication attempt.
 * @param ldapContextFactory factory used to retrieve LDAP connections.
 * @return AuthenticationInfo instance representing the authenticated user's information.
 * @throws NamingException if any LDAP errors occur.
 *//* w  w w .  j a  v a  2 s  .  c  om*/
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
        LdapContextFactory ldapContextFactory) throws NamingException {
    AuthenticationInfo info = super.queryForAuthenticationInfo(token, ldapContextFactory);
    // Credentials were verified. Verify that the principal has all allowedRulesForAuthentication
    if (!hasAllowedAuthenticationRules(info.getPrincipals(), ldapContextFactory)) {
        throw new NamingException("Principal does not have any of the allowedRolesForAuthentication");
    }
    return info;
}

From source file:org.dhatim.util.JNDIUtil.java

/**
 * Get the JNDI Context.//from w  w w  . j  av  a  2  s . co m
 * <p/>
 * Don't forget to close it when done!
 *
 * @param jndiProperties JNDI properties.
 * @return The context.
 * @throws javax.naming.NamingException Error getting context.
 */
public static Context getNamingContext(final Properties jndiProperties) throws NamingException {
    Context context;
    try {
        context = jndiProperties.isEmpty() ? new InitialContext() : new InitialContext(jndiProperties);
    } catch (NamingException e) {
        logger.error("NamingException while try to create initialContext. jndiProperties are " + jndiProperties,
                e);
        throw ((NamingException) new NamingException("Failed to load InitialContext: " + jndiProperties)
                .initCause(e));
    }
    if (context == null) {
        throw new NamingException("Failed to create JNDI context.  Check that '" + Context.PROVIDER_URL + "', '"
                + Context.INITIAL_CONTEXT_FACTORY + "', '" + Context.URL_PKG_PREFIXES
                + "' are correctly configured in the supplied JNDI properties.");
    }

    return context;
}

From source file:org.dhatim.util.JNDIUtil.java

/**
 * Lookup an object through the JNDI context.
 *
 * @param objectName     The name of the object to be looked up.
 * @param jndiProperties JNDI properties.
 * @param classLoaders   The {@link ClassLoader ClassLoaders) to be used during the lookup.
 * @return The object./* w  w  w .ja  v a  2s  .  c om*/
 * @throws NamingException Error getting object.
 */
public static Object lookup(final String objectName, final Properties jndiProperties,
        final ClassLoader[] classLoaders) throws NamingException {
    ClassLoader tcClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        for (ClassLoader classLoader : classLoaders) {
            Thread.currentThread().setContextClassLoader(classLoader);
            try {
                return JNDIUtil.lookup(objectName, jndiProperties);
            } catch (NamingException e) {
                logger.debug(
                        "NamingException while trying to lookup '" + objectName + "' using JNDI Properties '"
                                + jndiProperties + "', classloader used '" + classLoader + "'",
                        e);
                // Try the other ClassLoaders...
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(tcClassLoader);
    }

    throw new NamingException("JNDI lookup of Object [" + objectName + "] failed.");
}

From source file:org.eclipse.ecr.core.storage.sql.ra.PoolingRepositoryFactory.java

protected static ConnectionManager lookupConnectionManager() throws NamingException {
    InitialContext context = new InitialContext();
    int i = 0;/*from  ww w  . j a  va  2 s  .  c o m*/
    for (String name : CM_NAMES) {
        try {
            ConnectionManager connectionManager = (ConnectionManager) context.lookup(name);
            if (connectionManager != null) {
                if (i != 0) {
                    // put successful name first for next time
                    CM_NAMES[i] = CM_NAMES[0];
                    CM_NAMES[0] = name;
                }
                return connectionManager;
            }
        } catch (NamingException e) {
            // try next one
        }
        i++;
    }
    throw new NamingException("NuxeoConnectionManager not found in JNDI");
}

From source file:org.eclipse.ecr.runtime.transaction.TransactionHelper.java

/**
 * Looks up the User Transaction in JNDI.
 *
 * @return the User Transaction/*  www  .ja v  a  2  s  .c  om*/
 * @throws NamingException if not found
 */
public static UserTransaction lookupUserTransaction() throws NamingException {
    InitialContext context = new InitialContext();
    int i = 0;
    for (String name : UT_NAMES) {
        try {
            UserTransaction userTransaction = (UserTransaction) context.lookup(name);
            if (userTransaction != null) {
                if (i != 0) {
                    // put successful name first for next time
                    UT_NAMES[i] = UT_NAMES[0];
                    UT_NAMES[0] = name;
                }
                return userTransaction;
            }
        } catch (NamingException e) {
            // try next one
        }
        i++;
    }
    throw new NamingException("UserTransaction not found in JNDI");
}

From source file:org.eclipse.ecr.runtime.transaction.TransactionHelper.java

/**
 * Looks up the TransactionManager in JNDI.
 *
 * @return the TransactionManager/*from  www .  j  a  v a 2 s  .co m*/
 * @throws NamingException if not found
 */
public static TransactionManager lookupTransactionManager() throws NamingException {
    InitialContext context = new InitialContext();
    int i = 0;
    for (String name : TM_NAMES) {
        try {
            TransactionManager transactionManager = (TransactionManager) context.lookup(name);
            if (transactionManager != null) {
                if (i != 0) {
                    // put successful name first for next time
                    TM_NAMES[i] = TM_NAMES[0];
                    TM_NAMES[0] = name;
                }
                return transactionManager;
            }
        } catch (NamingException e) {
            // try next one
        }
        i++;
    }
    throw new NamingException("TransactionManager not found in JNDI");
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private LdapContext getLdapContext() throws NamingException, AuthenticationException {
    if (config == null) {
        throw new NamingException("LDAP not configured");
    }// w w  w. j  a va2  s. c  o m
    if (StringUtils.isBlank(config.getProviderUrl())) {
        throw new NamingException("No LDAP server available");
    }
    if (StringUtils.isBlank(config.getUsername()) || StringUtils.isBlank(config.getPassword())) {
        throw new AuthenticationException("No LDAP credentials available");
    }
    String ctxFactory = config.getCtxFactory();
    if (StringUtils.isBlank(ctxFactory)) {
        ctxFactory = DEFAULT_CONTEXT_FACTORY;
    }
    String authentication = config.getAuthentication();
    if (StringUtils.isBlank(authentication)) {
        authentication = SIMPLE_AUTHENTICATION;
    }

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ctxFactory);
    env.put(Context.PROVIDER_URL, config.getProviderUrl());
    env.put(Context.SECURITY_PRINCIPAL, config.getUsername());
    env.put(Context.SECURITY_CREDENTIALS, config.getPassword());
    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (StringUtils.isNotBlank(config.getReferral())) {
        env.put(Context.REFERRAL, config.getReferral());
    }
    if (config.getProviderUrl().startsWith(LDAPS_SCHEME)) {
        env.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$
        if (config.isSslNoVerify()) {
            env.put(JNDI_SOCKET_FACTORY, LDAPTrustAllSocketFactory.class.getName());
        }
    }
    // Gemini-specific properties
    env.put(JNDIConstants.BUNDLE_CONTEXT, FrameworkUtil.getBundle(LDAPClient.class).getBundleContext());

    // com.sun.jndi.ldap.LdapCtxFactory specific properties
    env.put(READ_TIMEOUT, DEFAULT_READ_TIMEOUT);
    env.put(USE_CONNECTION_POOLING, "true"); //$NON-NLS-1$

    // extremly ugly classloading workaround:
    // com.sun.jndi.ldap.LdapCtxFactory uses Class.forName() to load the socket factory, shame on them!
    InitialLdapContext ctx = null;
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(LDAPTrustAllSocketFactory.class.getClassLoader());
        ctx = new InitialLdapContext(env, null);
    } finally {
        if (classloader != null) {
            Thread.currentThread().setContextClassLoader(classloader);
        }
    }
    return ctx;
}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static Map getUserInfo(BehavioralContext ctx, String userName) throws NamingException {
    Map infoMap = null;//  w w w.  j a  v a2  s .c  om

    Configuration cfg = ctx.getConfig();
    // 
    String searchRelativeDc = cfg.getString(Constants.KEY_AD_USER_NODE_DN);
    String theFilter = LDAP_USER_SAMACCOUNTNAME + "=" + userName;
    List theAttrsList = new Vector(Arrays.asList(ldapUserAttrs));
    theAttrsList.addAll(Arrays.asList(ldapTopAttrs));

    int countLimit = 1000;
    int timeLimitMillis = 30000;
    boolean returnObject = false;
    boolean derefObj = true;

    SearchControls scs = new SearchControls(SearchControls.SUBTREE_SCOPE, countLimit, timeLimitMillis,
            (String[]) theAttrsList.toArray(new String[0]), returnObject, derefObj);

    DirContext rootCtx = getTsessAccountContext(ctx);

    try {
        log.debug("Search params name[" + searchRelativeDc + "] " + "filter[" + theFilter + "] controls[" + scs
                + "]");

        NamingEnumeration results = rootCtx.search(searchRelativeDc, theFilter, scs);

        if (results == null || !results.hasMore())
            throw new NamingException("User LDAP entry not found");

        SearchResult searchResult = ((SearchResult) results.next());
        if (searchResult == null)
            throw new NamingException("User LDAP entry not found");

        if (log.isTraceEnabled()) {
            logLdap(log, 0, 0, searchResult);
        }

        Attributes userLdapAttrs = searchResult.getAttributes();
        infoMap = new HashMap();
        for (Iterator attrIter = theAttrsList.iterator(); attrIter.hasNext();) {
            loadMap(infoMap, userLdapAttrs, (String) attrIter.next());
        }
    } finally {
        safeClose(rootCtx);
    }

    return infoMap;
}