List of usage examples for javax.naming NamingException getMessage
public String getMessage()
From source file:com.flexive.ejb.beans.configuration.GlobalConfigurationEngineBean.java
/** * {@inheritDoc}//from w w w . java2s . com */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public DivisionData createDivisionData(int divisionId, String dataSource, String domainRegEx) { String dbVendor = "unknown"; String dbVersion = "unknown"; String dbDriverVersion = "unknown"; boolean available = false; Connection con = null; try { // lookup non-transactional datasource to avoid issues with the default JEE6 data source in Glassfish con = Database.getDataSource(dataSource + "NoTX").getConnection(); DatabaseMetaData dbmd = con.getMetaData(); dbVendor = dbmd.getDatabaseProductName(); dbVersion = dbmd.getDatabaseProductVersion(); dbDriverVersion = dbmd.getDriverName() + " " + dbmd.getDriverVersion(); available = true; } catch (NamingException e) { LOG.error("Failed to get datasource " + dataSource + " (flagged inactive)"); } catch (SQLException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to get database meta information: " + e.getMessage(), e); } } finally { Database.closeObjects(GlobalConfigurationEngineBean.class, con, null); } return new DivisionData(divisionId, available, dataSource, domainRegEx, dbVendor, dbVersion, dbDriverVersion); }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoToken.java
private KeyStore getKeystore(final String type, final String path, final char[] authCode) throws KeyStoreException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, FileNotFoundException, IOException { final KeyStore result; if (TYPE_PKCS12.equalsIgnoreCase(type) || TYPE_INTERNAL.equalsIgnoreCase(type)) { result = KeyStore.getInstance("PKCS12", "BC"); } else {//w w w . j a va 2 s . co m result = KeyStore.getInstance("JKS"); } InputStream in = null; try { if (!TYPE_INTERNAL.equalsIgnoreCase(type)) { if (path == null) { throw new FileNotFoundException("Missing property " + KeystoreCryptoToken.KEYSTOREPATH + "."); } in = new FileInputStream(path); } else { // load data from internal worker data... final byte[] keystoreData = getWorkerSession() .getKeystoreData(new AdminInfo("Internal", null, null), this.workerId); if (keystoreData != null) { in = new ByteArrayInputStream(keystoreData); } } result.load(in, authCode); } catch (NamingException e) { throw new KeyStoreException("Failed to get worker session: " + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { LOG.error("Error closing file", ex); } } } return result; }
From source file:ldap.LdapApi.java
/** * getUser() - returns the user from the ldap directory * add email address to the login that is sent by the user * javax.naming.directory does not recognize any other attributes other * than email for searching for users in ldap directory *///from w w w . jav a2 s .c om private Entry getMyUser(String login, DirContext context, SearchUtility searcher) { Entry user = null; try { // for isro.ldif purposes attach the email address now for searching // as uid is not unique. String email = login + "@isac.gov.in"; user = searcher.getUser(LdapConstants.ldapAttrMail, email, context); } catch (NamingException e) { throw new LdapException("getUser NamingException" + e.getMessage(), e); } if (user == null) { logger.info("USER DOES NOT EXIST"); return null; } else { return user; } }
From source file:ldap.LdapApi.java
/** * open the directory connection./*from w ww . j a v a 2 s . c om*/ * @throws LdapException */ public LdapApi() { searchBase = null; try { context = openDirectoryConnection(); } catch (NamingException e) { throw new LdapException("openDirectoryConnection() NamingException" + e.getMessage(), e); } if (context == null) { logger.info("new LdapApi() context is null"); throw new LdapException("new LdapApi() context is null"); } }
From source file:ldap.LdapApi.java
/** * getLdapUsers() returns users based on certain criteria * @param searchDn - searchDn base/*from w w w . j a v a 2 s. c om*/ * @param attrList - attrList * @return List - users list * @throws LdapException */ public List getLdapUsers(String searchDn, String[] attrList) throws LdapException { try { SearchUtility searcher = getSearcher(searchDn); List<Entry> users = null; try { users = searcher.getUsers(searchBase, context); if (users == null) { logger.info("users are null."); } else { logger.info("users are not null."); } } catch (NamingException e) { throw new LdapException("getUsers(searchBase, context) exception" + e.getMessage(), e); } return getAttrUsersList(searcher, attrList, users); } catch (LdapException e1) { throw new LdapException("getSearcher(searchDn) exception " + e1.getMessage(), e1); } }
From source file:org.apache.wiki.auth.user.JDBCUserDatabase.java
/** * @see org.apache.wiki.auth.user.UserDatabase#initialize(org.apache.wiki.WikiEngine, * java.util.Properties)/*from w ww . j ava 2s . com*/ */ public void initialize(WikiEngine engine, Properties props) throws NoRequiredPropertyException, WikiSecurityException { String userTable; String role; String roleTable; String jndiName = props.getProperty(PROP_DB_DATASOURCE, DEFAULT_DB_JNDI_NAME); try { Context initCtx = new InitialContext(); Context ctx = (Context) initCtx.lookup("java:comp/env"); m_ds = (DataSource) ctx.lookup(jndiName); // Prepare the SQL selectors userTable = props.getProperty(PROP_DB_TABLE, DEFAULT_DB_TABLE); m_email = props.getProperty(PROP_DB_EMAIL, DEFAULT_DB_EMAIL); m_fullName = props.getProperty(PROP_DB_FULL_NAME, DEFAULT_DB_FULL_NAME); m_lockExpiry = props.getProperty(PROP_DB_LOCK_EXPIRY, DEFAULT_DB_LOCK_EXPIRY); m_loginName = props.getProperty(PROP_DB_LOGIN_NAME, DEFAULT_DB_LOGIN_NAME); m_password = props.getProperty(PROP_DB_PASSWORD, DEFAULT_DB_PASSWORD); m_uid = props.getProperty(PROP_DB_UID, DEFAULT_DB_UID); m_wikiName = props.getProperty(PROP_DB_WIKI_NAME, DEFAULT_DB_WIKI_NAME); m_created = props.getProperty(PROP_DB_CREATED, DEFAULT_DB_CREATED); m_modified = props.getProperty(PROP_DB_MODIFIED, DEFAULT_DB_MODIFIED); m_attributes = props.getProperty(PROP_DB_ATTRIBUTES, DEFAULT_DB_ATTRIBUTES); m_findAll = "SELECT * FROM " + userTable; m_findByEmail = "SELECT * FROM " + userTable + " WHERE " + m_email + "=?"; m_findByFullName = "SELECT * FROM " + userTable + " WHERE " + m_fullName + "=?"; m_findByLoginName = "SELECT * FROM " + userTable + " WHERE " + m_loginName + "=?"; m_findByUid = "SELECT * FROM " + userTable + " WHERE " + m_uid + "=?"; m_findByWikiName = "SELECT * FROM " + userTable + " WHERE " + m_wikiName + "=?"; // The user insert SQL prepared statement m_insertProfile = "INSERT INTO " + userTable + " (" + m_uid + "," + m_email + "," + m_fullName + "," + m_password + "," + m_wikiName + "," + m_modified + "," + m_loginName + "," + m_attributes + "," + m_created + ") VALUES (?,?,?,?,?,?,?,?,?)"; // The user update SQL prepared statement m_updateProfile = "UPDATE " + userTable + " SET " + m_uid + "=?," + m_email + "=?," + m_fullName + "=?," + m_password + "=?," + m_wikiName + "=?," + m_modified + "=?," + m_loginName + "=?," + m_attributes + "=?," + m_lockExpiry + "=? " + "WHERE " + m_loginName + "=?"; // Prepare the role insert SQL roleTable = props.getProperty(PROP_DB_ROLE_TABLE, DEFAULT_DB_ROLE_TABLE); role = props.getProperty(PROP_DB_ROLE, DEFAULT_DB_ROLE); m_insertRole = "INSERT INTO " + roleTable + " (" + m_loginName + "," + role + ") VALUES (?,?)"; m_findRoles = "SELECT * FROM " + roleTable + " WHERE " + m_loginName + "=?"; // Prepare the user delete SQL m_deleteUserByLoginName = "DELETE FROM " + userTable + " WHERE " + m_loginName + "=?"; // Prepare the role delete SQL m_deleteRoleByLoginName = "DELETE FROM " + roleTable + " WHERE " + m_loginName + "=?"; // Prepare the rename user/roles SQL m_renameProfile = "UPDATE " + userTable + " SET " + m_loginName + "=?," + m_modified + "=? WHERE " + m_loginName + "=?"; m_renameRoles = "UPDATE " + roleTable + " SET " + m_loginName + "=? WHERE " + m_loginName + "=?"; } catch (NamingException e) { log.error("JDBCUserDatabase initialization error: " + e.getMessage()); throw new NoRequiredPropertyException(PROP_DB_DATASOURCE, "JDBCUserDatabase initialization error: " + e.getMessage()); } // Test connection by doing a quickie select Connection conn = null; try { conn = m_ds.getConnection(); PreparedStatement ps = conn.prepareStatement(m_findAll); ps.close(); } catch (SQLException e) { log.error("DB connectivity error: " + e.getMessage()); throw new WikiSecurityException("DB connectivity error: " + e.getMessage(), e); } finally { try { if (conn != null) conn.close(); } catch (Exception e) { } } log.info("JDBCUserDatabase initialized from JNDI DataSource: " + jndiName); // Determine if the datasource supports commits try { conn = m_ds.getConnection(); DatabaseMetaData dmd = conn.getMetaData(); if (dmd.supportsTransactions()) { m_supportsCommits = true; conn.setAutoCommit(false); log.info("JDBCUserDatabase supports transactions. Good; we will use them."); } } catch (SQLException e) { log.warn("JDBCUserDatabase warning: user database doesn't seem to support transactions. Reason: " + e.getMessage()); } finally { try { if (conn != null) conn.close(); } catch (Exception e) { } } }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * This method will perform multiple queries into Active Directory * in order to resolve what groups a user is a member of. The * logic will identify nested groups and add them to the table. * <p>//from w w w . j a va 2 s . co m * The LDAP_ACCOUNT_NAME field must be populated in the user bag * prior to invoking this method. Any site specific fields can be * assigned to the user bag will be included in the attribute query. * </p> * <p> * Any site specific fields can be assigned to the group bag will * be included in the attribute query. * </p> * * @param aUserBag Active Directory user attributes. * @param aGroupBag Active Directory group attributes. * * @return Table of groups that the user is a member of. * * @throws NSException Thrown if an LDAP naming exception is occurs. */ @SuppressWarnings("StringConcatenationInsideStringBufferAppend") public DataTable loadUserGroupsByAccountName(DataBag aUserBag, DataBag aGroupBag) throws NSException { byte[] objectSid; DataBag groupBag; Attribute responseAttribute; String fieldName, fieldValue; Logger appLogger = mAppMgr.getLogger(this, "loadUserGroupsByAccountName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } // First, we will populate our user bag so that we can obtain the distinguished name. loadUserByAccountName(aUserBag); // Now we will use the DN to find all of the groups the user is a member of. String distinguishedName = aUserBag.getValueAsString(LDAP_DISTINGUISHED_NAME); if (StringUtils.isEmpty(distinguishedName)) distinguishedName = getPropertyValue("user_searchbasedn", null); // Next, we will initialize our group membership table. DataTable memberTable = new DataTable(aUserBag); memberTable.setName(String.format("%s Group Membership", aUserBag.getValueAsString(LDAP_COMMON_NAME))); // The next logic section will query AD for all of the groups the user is a member // of. Because we are following tokenGroups, we will gain access to nested groups. String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null); SearchControls userSearchControls = new SearchControls(); userSearchControls.setSearchScope(SearchControls.OBJECT_SCOPE); StringBuffer groupsSearchFilter = null; String ldapAttrNames[] = { "tokenGroups" }; userSearchControls.setReturningAttributes(ldapAttrNames); try { NamingEnumeration<?> userSearchResponse = mLdapContext.search(distinguishedName, "(objectClass=user)", userSearchControls); if ((userSearchResponse != null) && (userSearchResponse.hasMoreElements())) { groupsSearchFilter = new StringBuffer(); groupsSearchFilter.append("(|"); SearchResult userSearchResult = (SearchResult) userSearchResponse.next(); Attributes userResultAttributes = userSearchResult.getAttributes(); if (userResultAttributes != null) { try { for (NamingEnumeration<?> searchResultAttributesAll = userResultAttributes .getAll(); searchResultAttributesAll.hasMore();) { Attribute attr = (Attribute) searchResultAttributesAll.next(); for (NamingEnumeration<?> namingEnumeration = attr.getAll(); namingEnumeration .hasMore();) { objectSid = (byte[]) namingEnumeration.next(); groupsSearchFilter.append("(objectSid=" + objectSidToString2(objectSid) + ")"); } groupsSearchFilter.append(")"); } } catch (NamingException e) { String msgStr = String.format("LDAP Listing Member Exception: %s", e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } } userSearchResponse.close(); // Finally, we will query each group in the search filter and add it to the table. SearchControls groupSearchControls = new SearchControls(); groupSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; int attrCount = aGroupBag.count(); String[] groupsReturnedAtts = new String[attrCount]; for (DataField complexField : aGroupBag.getFields()) { fieldName = complexField.getName(); groupsReturnedAtts[field++] = fieldName; } groupSearchControls.setReturningAttributes(groupsReturnedAtts); NamingEnumeration<?> groupSearchResponse = mLdapContext.search(groupSearchBaseDN, groupsSearchFilter.toString(), groupSearchControls); while ((groupSearchResponse != null) && (groupSearchResponse.hasMoreElements())) { SearchResult groupSearchResult = (SearchResult) groupSearchResponse.next(); Attributes groupResultAttributes = groupSearchResult.getAttributes(); if (groupResultAttributes != null) { groupBag = new DataBag(aGroupBag); for (DataField complexField : groupBag.getFields()) { fieldName = complexField.getName(); responseAttribute = groupResultAttributes.get(fieldName); if (responseAttribute != null) { if (fieldName.equals(LDAP_OBJECT_SID)) { objectSid = (byte[]) responseAttribute.get(); fieldValue = objectSidToString2(objectSid); } else fieldValue = (String) responseAttribute.get(); if (StringUtils.isNotEmpty(fieldValue)) complexField.setValue(fieldValue); } } memberTable.addRow(groupBag); } } if (groupSearchResponse != null) groupSearchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", distinguishedName, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return memberTable; }
From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java
private NamingEnumeration getBasicNamingEnumeration(String userid, String password, String filter, SearchControls searchControls, Hashtable env) throws NamingException, Exception { String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " getNamingEnumeration() "; log.debug(m + ">"); NamingEnumeration ne = null;// www.ja v a 2 s .c om try { DirContext ctx; try { ctx = new InitialDirContext(env); } catch (NamingException th) { String msg = "exception getting ldap context"; if (LOG_STACK_TRACES) { log.error(m + msg, th); } else { log.error(m + msg + " " + th.getMessage()); } throw th; } if (ctx == null) { log.error(m + "unexpected null ldap context"); throw new NamingException(""); } try { ne = ctx.search(BASE, filter, searchControls); } catch (NamingException th) { String msg = "exception getting ldap enumeration"; if (LOG_STACK_TRACES) { log.error(m + msg, th); } else { log.error(m + msg + " " + th.getMessage()); } throw th; } if (ne == null) { log.error(m + "unexpected null ldap enumeration"); throw new NamingException(""); } } finally { log.debug(m + "< " + ne); } return ne; }
From source file:org.glite.ce.monitor.holder.NotificationHolder.java
/** * This method is used by a scheduled execution of this class.The operations * performed are:<br>//from w ww.j a va 2 s . c om * 1) For each registered subscription a control is made to verify if this * is expired. If this is the case the subscription is unregistered.<br> * 2) If the subscription is not expired or paused then the query is * processed on the event, then actions on notification are performed based * on the query processing results, and finally the consumer or purchaser * registered for that notification is notified. <br> */ public void run() { while (!exit) { List<SubscriptionPersistent> subscriptionList = this.getSubscriptions(); long tmpTS = System.currentTimeMillis(); for (SubscriptionPersistent subscription : subscriptionList) { URI consumerURI = null; try { java.net.URI tmpURI = subscription.getMonitorConsumerURL(); consumerURI = new URI(tmpURI.toString()); } catch (URI.MalformedURIException mEx) { logger.error(mEx.getMessage(), mEx); } if (consumerURI == null) { eraseSubscription(subscription, "consumer URL not found!"); continue; } if (subscription.isExpired()) { eraseSubscription(subscription, "the subscription is expired!"); continue; } if (subscription.isPaused()) { continue; } try { logger.debug("[name=" + this.name + "] - processing subscription id " + subscription.getId()); Topic topic = subscription.getTopic(); Policy policy = subscription.getPolicy(); if (policy == null) { continue; } SensorEventArrayList event = topicHolder.getEvents(topic.getName(), subscription.getSubscriberId(), subscription.getSubscriberGroup()); logger.debug("[name=" + this.name + "] - found " + event.size() + " events"); CEMonitorConsumerStub.Notification notification = new CEMonitorConsumerStub.Notification(); notification.setExpirationTime(subscription.getExpirationTime()); CEMonitorConsumerStub.Topic newTopic = new CEMonitorConsumerStub.Topic(); newTopic.setName(topic.getName()); if (topic.getDialect() != null && topic.getDialect().length > 0) { Dialect[] dialect = topic.getDialect(); CEMonitorConsumerStub.Dialect[] newDialect = new CEMonitorConsumerStub.Dialect[dialect.length]; for (int x = 0; x < dialect.length; x++) { newDialect[x] = new CEMonitorConsumerStub.Dialect(); newDialect[x].setName(dialect[x].getName()); newDialect[x].setQueryLanguage(dialect[x].getQueryLanguage()); } newTopic.setDialect(newDialect); } notification.setTopic(newTopic); notification.setEvent(null); notification.setConsumerURL(consumerURI); while (event.size() > 0) { SensorEventArrayList subEventList = event.drain(EVN_PAGE_SIZE); processPolicy(subEventList, policy, notification, subscription); if (notification.getEvent().length > 0) { logger.info("[name=" + this.name + "] - sending notification (containing " + notification.getEvent().length + " events) to " + consumerURI.toString()); if (logger.isDebugEnabled()) { printNotification(subscription, subEventList); } Properties sslConfig = this.getSSLParameters(subscription.getCredentialFile(), subscription.getPassphrase()); CANLAXIS2SocketFactory.setCurrentProperties(sslConfig); CEMonitorConsumerStub consumer = new CEMonitorConsumerStub(consumerURI.toString()); CEMonitorConsumerStub.Notify msg = new CEMonitorConsumerStub.Notify(); msg.setNotification(notification); consumer.notify(msg); logger.info("[name=" + this.name + "] - [done]"); } else { logger.info("[name=" + this.name + "] - the notification doesn't contains messages to be notified! [aborted]"); } if (subscription.getMaxRetryCount() != -1) { subscription.resetRetryCount(); try { this.removeSubscription(subscription); this.subscriptionRegistry.update(subscription); this.addSubscription(subscription); } catch (Throwable th) { logger.error(th.getMessage(), th); } } } } catch (NamingException e) { logger.error("[name=" + this.name + "] - NamingException occurred: subscription id = " + subscription.getId() + " consumer URL = " + subscription.getMonitorConsumerURL() + " message error = " + e.getMessage()); } catch (IOException e) { logger.error("[name=" + this.name + "] - IOException occurred: subscription id = " + subscription.getId() + " consumer URL = " + subscription.getMonitorConsumerURL() + " message error = " + e.getMessage()); if (subscription.getMaxRetryCount() != -1) { int retries = subscription.decrRetryCount(); logger.info("[name=" + this.name + "] - decrementing the retry count to " + retries + " for the subscription id = " + subscription.getId() + "; consumer URL = " + subscription.getMonitorConsumerURL() + "; message error = " + e.getMessage()); if (retries == 0) { eraseSubscription(subscription, "retry count = 0"); } else { try { this.removeSubscription(subscription); this.subscriptionRegistry.update(subscription); this.addSubscription(subscription); } catch (Throwable th) { logger.error(th.getMessage(), th); } } } } catch (Exception e) { logger.error("[name=" + this.name + "] - Exception catched: subscriptionId = " + subscription.getId() + " consumer URL = " + subscription.getMonitorConsumerURL() + " message error = " + e.getMessage() + ". Follow the Stack trace:", e); } } try { long waitTime = rate - System.currentTimeMillis() + tmpTS; if (waitTime > 0) { logger.debug("[name=" + this.name + "] - sleeping " + waitTime); Thread.sleep(waitTime); } else { logger.warn("Notifications overlapping"); } } catch (InterruptedException intEx) { logger.info("[name=" + this.name + "] - destroyed"); } } }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Obtain the DistinguishedName for a given user logon name. *@param ctx is the ldap context to use./*w w w. j av a 2 s .c o m*/ *@param userName (Domain Logon Name) is the user name or identifier. *@param searchBase (Full Domain Name for the search ie: DC=qa-ad-76,DC=metacarta,DC=com) *@return DistinguishedName for given domain user logon name. * (Should throws an exception if user is not found.) */ protected String getDistinguishedName(LdapContext ctx, String userName, String searchBase, String userACLsUsername) throws ManifoldCFException { String returnedAtts[] = { "distinguishedName" }; String searchFilter = "(&(objectClass=user)(" + userACLsUsername + "=" + userName + "))"; SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(returnedAtts); //Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); try { NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { String dn = attrs.get("distinguishedName").get().toString(); return dn; } } return null; } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } }