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:ldap.Entry.java

public int compareTo(Object o) {
    Entry compareMe = (Entry) o;// w  w w  . j  a v  a 2 s .  c o m

    try {
        //String name1 = getValue(Config.USER_NAMING_ATT);
        //String name2 = compareMe.getValue(Config.USER_NAMING_ATT);
        String name1 = getValue(LdapConstants.ldapAttrUid);
        String name2 = compareMe.getValue(LdapConstants.ldapAttrUid);
        return name1.compareTo(name2);
    } catch (NamingException e) {
        logger.info("Unexpected Exception while sorting users: " + e.getMessage());
        return 0;
    }
}

From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java

public Set<UserCredentials> loadUsersByRole(RoleCode roleCode) {
    Role role = roleDao.getByRoleCode(roleCode);

    String groupFilter = createGroupFilter(roleCode);

    Set<UserCredentials> userCredentials = new HashSet<UserCredentials>();

    try {/*from  w  w  w.  ja  v  a2  s.co  m*/
        Attributes attrs = contextSource.getReadOnlyContext().getAttributes(groupFilter);
        Attribute memAttr = attrs.get(Constants.LDAP_GROUP_UNIQUE_MEMBER);

        NamingEnumeration<?> elements = memAttr.getAll();
        while (elements.hasMoreElements()) {
            DistinguishedName dn = new DistinguishedName((String) elements.nextElement());
            String userName = dn.getValue(Constants.LDAP_UID);
            DirContextOperations dir = searchForUser(userName);
            String email = dir.getStringAttribute("mail");
            UserCredentials user = getUserFromDatabase(userName);
            user.setEmail(email);
            userCredentials.add(user);
        }

    } catch (NamingException e) {
        log.error(e.getMessage());
    }

    return userCredentials;
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 *//* w w  w .j  av a2s.  c o  m*/
public void contextInitialized(final ServletContextEvent sContextEvent) {
    final String methodName = SecurityServiceListener.CNAME
            + "#contextInitialized(final ServletContextEvent sContextEvent)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletContextEvent: {}", sContextEvent);
    }

    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ServletContext sContext = sContextEvent.getServletContext();
    final ClassLoader classLoader = SecurityServiceListener.class.getClassLoader();

    if (DEBUG) {
        DEBUGGER.debug("ServletContext: {}", sContext);
        DEBUGGER.debug("ClassLoader: {}", classLoader);
    }

    try {
        if (sContext != null) {
            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSLOGGING_FILE)) {
                System.err.println("Logging configuration not found. No logging enabled !");
            } else {
                DOMConfigurator.configure(Loader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSLOGGING_FILE)));
            }

            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSCONFIG_FILE)) {
                xmlURL = classLoader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSCONFIG_FILE));

            } else {
                ERROR_RECORDER.error("System configuration not found. Shutting down !");

                throw new SecurityServiceException(
                        "System configuration file location not provided by application. Cannot continue.");
            }

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

            if (xmlURL != null) {
                context = JAXBContext.newInstance(SecurityConfigurationData.class);
                marshaller = context.createUnmarshaller();
                configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

                SecurityServiceListener.svcBean.setConfigData(configData);

                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(SecurityServiceConstants.DS_CONTEXT);

                DAOInitializer.configureAndCreateAuthConnection(
                        new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                        false, SecurityServiceListener.svcBean);

                Map<String, DataSource> dsMap = new HashMap<String, DataSource>();

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    dsMap.put(mgr.getDsName(), (DataSource) envContext.lookup(mgr.getDataSource()));
                }

                SecurityServiceListener.svcBean.setDataSources(dsMap);
            } else {
                throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
            }
        } else {
            throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
        }
    } catch (NamingException nx) {
        ERROR_RECORDER.error(nx.getMessage(), nx);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
    } catch (JAXBException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);
    }
}

From source file:ldap.Entry.java

public String toString() {
    try {/*from   w  w  w  . j a  va  2  s . c  o m*/
        StringBuffer result = new StringBuffer();
        result.append("name:").append(getStringName()).append("\n");
        Enumeration<String> attNames = getIDs();
        while (attNames.hasMoreElements()) {
            String id = attNames.nextElement();
            //result.append("\tatt ").append(id).append(": ");
            result.append(id).append(":");
            String[] vals = getValues(id);
            if (vals.length == 1)
                result.append(vals[0]).append("\n");
            else {
                for (String val : vals)
                    //result.append("\n\t").append(val);
                    result.append(val);
                //result.append("\n");
            }
        }
        return result.toString();
    } catch (NamingException e) {
        return "unable to list attribute due to exception: " + e.getMessage(); // very rare
    }
}

From source file:org.sonatype.nexus.ldap.internal.connector.DefaultLdapConnector.java

private void closeContext(LdapContext context) {
    try {/*  ww w.  j a  va  2s.  co  m*/
        if (context != null) {
            context.close();
        }
    } catch (NamingException e) {
        this.log.debug("Error closing connection: " + e.getMessage(), e);
    }
}

From source file:com.clustercontrol.port.protocol.ReachAddressDNS.java

/**
 * DNS????????/*from   ww w .  ja  v a  2  s. c  om*/
 *
 * @param addressText
 * @return DNS
 */
/*
 * (non-Javadoc)
 *
 * @see
 * com.clustercontrol.port.protocol.ReachAddressProtocol#isRunning(java.
 * lang.String)
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);
        String addressStr = address.getHostAddress();
        if (address instanceof Inet6Address) {
            addressStr = "[" + addressStr + "]";
        }

        bufferOrg.append("Monitoring the DNS Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        props.put(Context.PROVIDER_URL, "dns://" + addressStr + ":" + m_portNo);
        props.put("com.sun.jndi.dns.timeout.initial", String.valueOf(m_timeout));
        props.put("com.sun.jndi.dns.timeout.retries", "1");

        InitialDirContext idctx = null;

        String hostname = HinemosPropertyUtil.getHinemosPropertyStr("monitor.port.protocol.dns", "localhost");
        m_log.debug("The hostname from which to retrieve attributes is " + hostname);

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");

                start = HinemosTime.currentTimeMillis();

                idctx = new InitialDirContext(props);
                Attributes attrs = idctx.getAttributes(hostname);

                end = HinemosTime.currentTimeMillis();

                bufferOrg.append("\n");
                NamingEnumeration<? extends Attribute> allAttr = attrs.getAll();
                while (allAttr.hasMore()) {
                    Attribute attr = allAttr.next();
                    bufferOrg.append("Attribute: " + attr.getID() + "\n");
                    NamingEnumeration<?> values = attr.getAll();
                    while (values.hasMore())
                        bufferOrg.append("Value: " + values.next() + "\n");
                }
                bufferOrg.append("\n");

                m_response = end - start;

                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = result + ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = result + ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = result + ("Response Time < 1ms");
                }

                retry = false;
                isReachable = true;

            } catch (NamingException e) {
                result = (e.getMessage() + "[NamingException]");
                retry = true;
                isReachable = false;
            } catch (Exception e) {
                result = (e.getMessage() + "[Exception]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                try {
                    if (idctx != null) {
                        idctx.close();
                    }
                } catch (NamingException e) {
                    m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(DNS/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:edu.internet2.middleware.subject.provider.ESCOJNDISourceAdapter.java

/**
 * Creates a subject with a custom implementation.
 * //from   w w w.j av a  2 s .c o m
 * @param attrs
 *            The attributes associated to the subject.
 * @return The Subject.
 */
private Subject createSubject(final Attributes attrs) {
    String subjectName = "";
    String subjectID = "";
    String description = "";
    try {
        Attribute attribute = attrs.get(this.subjectIDAttributeName);
        if (attribute == null) {
            LOGGER.error("The LDAP attribute \"" + this.subjectIDAttributeName + "\" does not have a value. "
                    + "It is beging used as the Grouper special attribute \"SubjectID\".");
            return null;
        }
        subjectID = (String) attribute.get();
        attribute = attrs.get(this.nameAttributeName);
        if (attribute == null) {
            LOGGER.error("The LDAP attribute \"" + this.nameAttributeName + "\" does not have a value. z"
                    + "It is being used as the Grouper special attribute \"name\".");
            return null;
        }
        subjectName = (String) attribute.get();
        attribute = attrs.get(this.descriptionAttributeName);
        if (attribute == null) {
            LOGGER.error("The LDAP attribute \"" + this.descriptionAttributeName + "\" does not have a value. "
                    + "It is being used as the Grouper special attribute \"description\".");
        } else {
            description = (String) attribute.get();
        }
    } catch (NamingException ex) {
        LOGGER.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }

    return new ESCOJNDISubject(subjectID, subjectName, description, this.getSubjectType(), this);

}

From source file:org.wso2.carbon.appfactory.userstore.OTAppFactoryUserStore.java

@Override
public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {
    String[] userNames = new String[0];

    if (maxItemLimit == 0) {
        return userNames;
    }//from   w w  w.j  a v a2 s .  com

    int givenMax = Integer
            .parseInt(realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));

    if (maxItemLimit < 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

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

    if (filter.contains("?") || filter.contains("**")) {
        throw new UserStoreException(
                "Invalid character sequence entered for user serch. Please enter valid sequence.");
    }

    StringBuffer searchFilter = null;
    searchFilter = new StringBuffer(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    StringBuffer buff = new StringBuffer();
    buff.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=").append(filter)
            .append("))");

    String serviceNameAttribute = "sn";
    String mailAttribute = "mail";
    String returnedAtts[] = { userNameProperty, serviceNameAttribute, mailAttribute };

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

                /*
                 * If this is a service principle, just ignore and iterate rest of the array.
                 * The entity is a service if value of surname is Service
                 */
                Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute);

                if (attrSurname != null) {
                    String serviceName = (String) attrSurname.get();
                    if (serviceName != null
                            && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                        continue;
                    }
                }

                if (attr != null) {
                    String name = (String) attr.get();
                    //append the domain if exist
                    String domain = userRealm.getRealmConfiguration()
                            .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                    if (domain != null) {
                        domain = domain + "/";
                        name = domain + name;
                    }
                    list.add(name);
                    i++;
                }
            }
        }
        userNames = list.toArray(new String[list.size()]);
        //get secondary user lists
        UserStoreManager secUserManager = this.getSecondaryUserStoreManager();
        if (secUserManager != null) {
            String[] secUserNames = secUserManager.listUsers(filter, maxItemLimit);
            allUserNames = UserCoreUtil.combineArrays(userNames, secUserNames);
        } else {
            allUserNames = userNames;
        }
        Arrays.sort(allUserNames);
    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return allUserNames;
}

From source file:org.nuxeo.ecm.core.jms.CoreEventPublisher.java

/**
 * Retrieves a new JMS Connection from the pool.
 *
 * @return a <code>QueueConnection</code>
 * @throws JMSException if the connection could not be retrieved
 *//*  w ww.java  2 s . com*/
private TopicConnection getTopicConnection() throws JMSException {
    try {
        return getTopicConnectionFactory().createTopicConnection();
    } catch (NamingException e) {
        log.error("Failed too lookup topic connection factory", e);
        throw new JMSException("Failed to lookup topic connection factory: " + e.getMessage());
    }
}

From source file:org.ballerinalang.auth.ldap.nativeimpl.Authenticate.java

@Override
public void execute(Context context) {
    BMap<String, BValue> authStore = ((BMap<String, BValue>) context.getRefArgument(0));
    String userName = context.getStringArgument(0);
    byte[] credential = context.getStringArgument(1).getBytes(Charset.forName(LdapConstants.UTF_8_CHARSET));
    connectionSource = (LdapConnectionContext) authStore.getNativeData(LdapConstants.LDAP_CONNECTION_SOURCE);
    ldapConnectionContext = (DirContext) authStore.getNativeData(LdapConstants.LDAP_CONNECTION_CONTEXT);
    ldapConfiguration = (CommonLdapConfiguration) authStore.getNativeData(LdapConstants.LDAP_CONFIGURATION);
    LdapUtils.setServiceName((String) authStore.getNativeData(LdapConstants.ENDPOINT_INSTANCE_ID));

    if (LdapUtils.isNullOrEmptyAfterTrim(userName)) {
        context.setReturnValues(new BBoolean(false));
        throw new BallerinaException("username or credential value is empty or null.");
    }/*from w w  w .j a  va2 s .  c om*/

    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Authenticating user " + userName);
        }
        String name = LdapUtils.getNameInSpaceForUsernameFromLDAP(userName.trim(), ldapConfiguration,
                this.ldapConnectionContext);
        if (name != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authenticating with " + name);
            }
            boolean bValue = this.bindAsUser(name, credential);
            context.setReturnValues(new BBoolean(bValue));
        } else {
            context.setReturnValues(new BBoolean(false));
        }
    } catch (NamingException e) {
        LOG.error("Cannot bind user : " + userName, e);
        context.setReturnValues(new BBoolean(false));
    } catch (UserStoreException e) {
        LOG.error(e.getMessage(), e);
        context.setReturnValues(new BBoolean(false));
    } finally {
        LdapUtils.removeServiceName();
    }
}