Example usage for javax.naming NamingException getMessage

List of usage examples for javax.naming NamingException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.sdnmq.jms.FlowProgrammer.java

/**
 * JMS setup//from w ww. j a va2  s.  c om
 */
private boolean initMQ() {
    log.trace("Setting up JMS ...");

    Properties jndiProps = JNDIHelper.getJNDIProperties();

    Context ctx = null;
    try {
        ctx = new InitialContext(jndiProps);
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    QueueConnectionFactory queueFactory = null;
    try {
        queueFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory");
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        connection = queueFactory.createQueueConnection();
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    String queueName = System.getProperty(FLOWPROGRAMMER_QUEUE_PROPERTY, DEFAULT_FLOWPROGRAMMER_QUEUE_NAME);
    log.info("Using the following queue for flow programming requests: " + queueName);
    try {
        flowProgrammerQueue = (Queue) ctx.lookup(queueName);
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        receiver = session.createReceiver(flowProgrammerQueue);
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    log.trace("Setup JMS successfully");

    return true;
}

From source file:com.funambol.LDAP.security.LDAPMailUserProvisioningOfficer.java

/**
 * Return a S4J user if successful bind to ldap
 * null if user or password is wrong/*from  w  w  w .j av a 2s.  co m*/
 *      
 * TODO if I don't need to provision user on ldap,  I could avoid some of that stuff.. 
 * when binding, it retrieves imap/smtp server data to provision mail push
 * @param username
 * @param password
 * @return the {@link Sync4jUser} created from ldap fields
 */
public LDAPUser bindUserToLdap(String username, String password) {
    LDAPUser ldapUser = null;
    LdapManagerInterface ldapInterface = null;
    LdapManagerInterface ldapBindInterface = null;
    String userDN = null;
    /* TODO
     * this is now done creating an eventually authenticated context specified in 
     *  configuration file.
     *  moreover this context is shared between all ldap connections,
     *  so could be better defined at application server level 
     */
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        // use a bean configuration file
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(t.tmpLdapUrl, t.tmpBaseDn, getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // search the user binding with default ldap credential defined in the Officer.xml
            ldapInterface.setBaseDn(t.tmpBaseDn);
            SearchResult sr = ldapInterface.searchOneEntry(t.tmpUserSearch, new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr != null) {
                userDN = sr.getNameInNamespace().trim();
                log.info("binding with dn:" + userDN);
            } else {
                log.info("Username [" + username + "] not found");
                ldapInterface.close();
                return null;
            }
        } else { // use append
            userDN = "uid=" + username + "," + t.tmpBaseDn;
        }

        ldapInterface.close();
        ldapBindInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapBindInterface.init(t.tmpLdapUrl, userDN, userDN, password, false, false, null);
        SearchResult sr = ldapBindInterface.searchOneEntry("(objectclass=*)", getLdapAttributesToRetrieve(),
                SearchControls.OBJECT_SCOPE);

        if (sr != null) {
            ldapUser = new LDAPUser();
            ldapUser.setUsername(username);
            ldapUser.setPassword(password);

            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_EMAIL))) {
                ldapUser.setEmail(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_EMAIL)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_FIRSTNAME))) {
                ldapUser.setFirstname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_FIRSTNAME)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_LASTNAME))) {
                ldapUser.setLastname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_LASTNAME)));
            }

            // set attributes to be passed to LDAP and CalDAV connector
            ldapUser.setUserDn(userDN);
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_ADDRESSBOOK))) {
                ldapUser.setPsRoot(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_ADDRESSBOOK)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_CALENDAR))) {
                ldapUser.setCalUri(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_CALENDAR)));
            }

            // get server attributes from LDAP if not void
            if (getImapServer() == null && StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_IMAP))) {
                setImapServer(LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_IMAP)));
            }
            if (getSmtpServer() == null && StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_SMTP))) {
                setSmtpServer(LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_SMTP)));
            }

            if (Configuration.getConfiguration().isDebugMode()) {
                if (log.isTraceEnabled()) {
                    StringBuffer sb = new StringBuffer(64);
                    sb.append("psRoot: ").append(ldapUser.getPsRoot()).append("\n").append("calUri: ")
                            .append(ldapUser.getCalUri()).append("\n").append("imapServer: ")
                            .append(getImapServer()).append("\n").append("smtpServer: ")
                            .append(getSmtpServer());

                    log.trace(sb.toString());

                }
            }
        } else {
            ldapUser = null;
        }
        ldapBindInterface.close();

    } catch (SyncSourceException e1) {
        log.error("Can't instantiate context: " + e1.getMessage());
        ldapUser = null;
    } catch (NamingException e) {
        log.warn("Can't retrieve mailserver attributes from ldap: " + e.getMessage());
        ldapUser = null;
    } catch (LDAPAccessException e) {
        log.error("Can't instantiate context: " + e.getMessage());
        ldapUser = null;
    } finally {
        if (ldapInterface != null) {
            ldapInterface.close();
        }
        if (ldapBindInterface != null) {
            ldapBindInterface.close();
        }
    }
    return ldapUser;
}

From source file:org.wso2.carbon.appfactory.stratos.listeners.TenantStratosSubscriptionDurableSubscriber.java

/**
 * Subscribe as a durable subscriber to the topic.
 *
 * @throws AppFactoryEventException//from   w w w. j a v a 2s  . com
 */
public void subscribe() throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, AppFactoryConstants.ANDES_ICF);
    properties.put(AppFactoryConstants.CF_NAME_PREFIX + AppFactoryConstants.CF_NAME,
            Util.getTCPConnectionURL());
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, true);
    properties.put(AppFactoryConstants.TOPIC, topicName);
    try {
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(AppFactoryConstants.CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
        Topic topic;
        try {
            topic = (Topic) ctx.lookup(topicName);
        } catch (NamingException e) {
            topic = topicSession.createTopic(topicName);
        }
        topicSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
        topicSubscriber.setMessageListener(
                new TenantStratosSubscriptionMessageListener(topicConnection, topicSession, topicSubscriber));
        topicConnection.start();
        if (log.isDebugEnabled()) {
            log.debug("Durable Subscriber created for topic " + topicName + " with subscription id"
                    + subscriptionId);
        }
    } catch (NamingException e) {
        String errorMsg = "Failed to subscribe to topic:" + topicName + " due to " + e.getMessage();
        throw new AppFactoryEventException(errorMsg, e);
    } catch (JMSException e) {
        String errorMsg = "Failed to subscribe to topic:" + topicName + " due to " + e.getMessage();
        throw new AppFactoryEventException(errorMsg, e);
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java

protected InitialDirContext buildInitialDirContext(final Map<String, String> config, final int pageSize,
        final AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    final AuthenticationDiagnostic effectiveDiagnostic = diagnostic != null ? diagnostic
            : new AuthenticationDiagnostic();

    final String securityPrincipal = config.get(Context.SECURITY_PRINCIPAL);
    final String providerURL = config.get(Context.PROVIDER_URL);

    if (this.isSSLSocketFactoryRequired(config)) {
        final KeyStore trustStore = this.initTrustStore();
        ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName());
    }// w w w .j  ava  2 s . c  om

    try {
        // If a page size has been requested, use LDAP v3 paging
        if (pageSize > 0) {
            final InitialLdapContext ctx = new InitialLdapContext(new Hashtable<>(config), null);
            ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
            return ctx;
        } else {
            final InitialDirContext ret = new InitialDirContext(new Hashtable<>(config));
            final Object[] args = { providerURL, securityPrincipal };
            effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
            return ret;
        }
    } catch (final javax.naming.AuthenticationException ax) {
        final Object[] args1 = { securityPrincipal };
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);

        // wrong user/password - if we get this far the connection is O.K
        final Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.authentication", effectiveDiagnostic, args2, ax);
    } catch (final CommunicationException ce) {
        final Object[] args1 = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);

        final StringBuffer message = new StringBuffer();

        message.append(ce.getClass().getName() + ", " + ce.getMessage());

        Throwable cause = ce.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", effectiveDiagnostic, args, ce);
    } catch (final NamingException nx) {
        final Object[] args = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);

        final StringBuffer message = new StringBuffer();

        message.append(nx.getClass().getName() + ", " + nx.getMessage());

        Throwable cause = nx.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", effectiveDiagnostic, args1, nx);
    } catch (final IOException e) {
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);

        throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
    }
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public ServerPrinciple[] listServicePrinciples(String filter) throws DirectoryServerManagerException {

    ServerPrinciple[] serverNames = null;

    int maxItemLimit = Integer.parseInt(
            this.realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);

    if (filter.contains("?") || filter.contains("**")) {
        log.error("Invalid search character " + filter);
        throw new DirectoryServerManagerException(
                "Invalid character sequence entered for service principle search. Please enter valid sequence.");
    }/*from  w w w.j  a  v  a 2s .c  o m*/

    StringBuilder searchFilter;
    searchFilter = new StringBuilder(
            this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    StringBuilder buff = new StringBuilder();
    buff.append("(&").append(searchFilter).append("(")
            .append(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE).append("=").append(filter)
            .append(")").append(getServerPrincipleIncludeString()).append(")");

    String[] returnedAtts = { LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE,
            LDAPServerManagerConstants.LDAP_COMMON_NAME };
    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    try {
        dirContext = connectionSource.getContext();
        NamingEnumeration<SearchResult> answer = dirContext.search(searchBase, buff.toString(), searchCtls);
        List<ServerPrinciple> list = new ArrayList<ServerPrinciple>();
        int i = 0;
        while (answer.hasMoreElements() && i < maxItemLimit) {
            SearchResult sr = answer.next();
            if (sr.getAttributes() != null) {
                Attribute serverNameAttribute = sr.getAttributes()
                        .get(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE);
                Attribute serverDescription = sr.getAttributes()
                        .get(LDAPServerManagerConstants.LDAP_COMMON_NAME);
                if (serverNameAttribute != null) {

                    ServerPrinciple principle;
                    String serviceName;
                    String serverPrincipleFullName = (String) serverNameAttribute.get();

                    if (serverPrincipleFullName.toLowerCase(Locale.ENGLISH)
                            .contains(LDAPServerManagerConstants.KERBEROS_TGT)) {
                        continue;
                    }

                    if (serverPrincipleFullName.contains("@")) {
                        serviceName = serverPrincipleFullName.split("@")[0];
                    } else {
                        serviceName = serverPrincipleFullName;
                    }

                    if (serverDescription != null) {
                        principle = new ServerPrinciple(serviceName, (String) serverDescription.get());
                    } else {

                        principle = new ServerPrinciple(serviceName);
                    }

                    list.add(principle);
                    i++;
                }
            }
        }

        serverNames = list.toArray(new ServerPrinciple[list.size()]);
        Arrays.sort(serverNames);

    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new DirectoryServerManagerException("Unable to list service principles.", e);
    } catch (UserStoreException e) {
        log.error("Unable to retrieve LDAP connection context.", e);
        throw new DirectoryServerManagerException("Unable to list service principles.", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
    return serverNames;

}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

public PrivilegeEnum mapToPrivilege(Attributes attributes, String attributeName) {
    Attribute attributeValue = null;
    PrivilegeEnum privilege = null;/*  w  ww  .j av a2  s .com*/
    if (attributes != null && (attributeValue = attributes.get(attributeName)) != null) {
        try {
            String attributeString = String.valueOf(attributeValue.get()).toLowerCase(Locale.GERMAN);
            try {
                privilege = PrivilegeEnum.valueOf(attributeString.substring(4).toUpperCase(Locale.GERMAN));
            } catch (IllegalArgumentException iae) {
                LOG.log(Level.WARNING, "Name: {0}={1} - no such privilege",
                        new Object[] { attributeName, attributeString });
            }
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, "Can't convert LDAP Group " + attributeValue + " to DDB Privilege.",
                    ne.getMessage());
        }
    }
    return privilege;
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Closes a previously opened <i>LdapContext</i> and releases
 * any resources associated with naming enumerations used as
 * cursors into Active Directory result sets.
 *//*from  w w  w.  j  av a 2 s .c  om*/
public void close() {
    Logger appLogger = mAppMgr.getLogger(this, "close");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext != null) {
        try {
            mLdapContext.close();
        } catch (NamingException e) {
            String msgStr = String.format("LDAP Close Exception: %s", e.getMessage());
            appLogger.warn(msgStr);
        } finally {
            mLdapContext = null;
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

private InitialDirContext buildInitialDirContext(Hashtable<String, String> env, int pageSize,
        AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    String securityPrincipal = env.get(Context.SECURITY_PRINCIPAL);
    String providerURL = env.get(Context.PROVIDER_URL);

    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }/*from  w ww  .j  a v a2  s .com*/

    if (diagnostic == null) {
        diagnostic = new AuthenticationDiagnostic();
    }
    try {
        // If a page size has been requested, use LDAP v3 paging
        if (pageSize > 0) {
            InitialLdapContext ctx = new InitialLdapContext(env, null);
            ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
            return ctx;
        } else {
            InitialDirContext ret = new InitialDirContext(env);
            Object[] args = { providerURL, securityPrincipal };
            diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
            return ret;
        }
    } catch (javax.naming.AuthenticationException ax) {
        Object[] args1 = { securityPrincipal };
        Object[] args = { providerURL, securityPrincipal };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);

        // wrong user/password - if we get this far the connection is O.K
        Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.authentication", diagnostic, args2, ax);
    } catch (CommunicationException ce) {
        Object[] args1 = { providerURL };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);

        StringBuffer message = new StringBuffer();

        message.append(ce.getClass().getName() + ", " + ce.getMessage());

        Throwable cause = ce.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", diagnostic, args, cause);
    } catch (NamingException nx) {
        Object[] args = { providerURL };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);

        StringBuffer message = new StringBuffer();

        message.append(nx.getClass().getName() + ", " + nx.getMessage());

        Throwable cause = nx.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", diagnostic, args1, nx);
    } catch (IOException e) {
        Object[] args = { providerURL, securityPrincipal };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);

        throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
    }
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Opens a connection to Active Directory by establishing an initial LDAP
 * context.  The security principal and credentials are assigned the
 * account name and password parameters.
 *
 * @param anAcountDN Active Directory account name (DN format).
 * @param anAccountPassword Active Directory account password.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//* ww w  . j  a  v a 2  s. c  om*/
@SuppressWarnings("unchecked")
public void open(String anAcountDN, String anAccountPassword) throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "open");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    // LDAP Reference - http://docs.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html

    Hashtable<String, String> environmentalVariables = new Hashtable<String, String>();
    environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE);
    environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null));
    environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
    environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environmentalVariables.put(Context.SECURITY_PRINCIPAL, anAcountDN);
    environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);

    // Referral options: follow, throw, ignore (default)

    environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));

    // Authentication options: simple, DIGEST-MD5 CRAM-MD5

    environmentalVariables.put(Context.SECURITY_AUTHENTICATION, getPropertyValue("authentication", "simple"));

    try {
        mLdapContext = new InitialLdapContext(environmentalVariables, null);
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Context Error: %s", e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Gets an MQ message off a specified queue and returns it as an
 * <code>Object</code> to the requestor for further processing.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param responseQueue - The request queue name to put the message on
 * @param timeout - How long to wait for a connection or response
 * @param messageId - The JMS correlation ID of the message the response is associated with
 * @return <code>Object</code> - The serializable data returned by the MQ request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *//*from  w  w  w  .  j  av a  2s.  com*/
public static final synchronized Object getMqMessage(final String connName, final List<String> authData,
        final String responseQueue, final long timeout, final String messageId) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", responseQueue);
        DEBUGGER.debug("Value: {}", timeout);
        DEBUGGER.debug("Value: {}", messageId);
    }

    Connection conn = null;
    Session session = null;
    Object response = null;
    Context envContext = null;
    MessageConsumer consumer = null;
    ConnectionFactory connFactory = null;

    try {
        try {
            InitialContext initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

        // Create a Session
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        if (envContext != null) {
            try {
                consumer = session.createConsumer((Destination) envContext.lookup(responseQueue),
                        "JMSCorrelationID='" + messageId + "'");
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createQueue(responseQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            consumer = session.createConsumer(destination, "JMSCorrelationID='" + messageId + "'");
        }

        if (DEBUG) {
            DEBUGGER.debug("MessageConsumer: {}", consumer);
        }

        ObjectMessage message = (ObjectMessage) consumer.receive(timeout);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        if (message == null) {
            throw new UtilityException("Failed to retrieve message within the timeout specified.");
        }

        response = message.getObject();
        message.acknowledge();

        if (DEBUG) {
            DEBUGGER.debug("Object: {}", response);
        }
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return response;
}