List of usage examples for javax.naming NamingException getMessage
public String getMessage()
From source file:org.teiid.rhq.admin.DQPManagementView.java
/** * @param mcVdb/*from www . j a va2s.c o m*/ * @return count * @throws Exception */ private int getErrorCount(ProfileServiceConnection connection, String vdbName) { ManagedComponent mcVdb = null; try { mcVdb = ProfileServiceUtil.getManagedComponent(connection, new org.jboss.managed.api.ComponentType( PluginConstants.ComponentType.VDB.TYPE, PluginConstants.ComponentType.VDB.SUBTYPE), vdbName); } catch (NamingException e) { final String msg = "NamingException in getVDBStatus(): " + e.getExplanation(); //$NON-NLS-1$ LOG.error(msg, e); } catch (Exception e) { final String msg = "Exception in getVDBStatus(): " + e.getMessage(); //$NON-NLS-1$ LOG.error(msg, e); } // Get models from VDB int count = 0; ManagedProperty property = mcVdb.getProperty("models"); //$NON-NLS-1$ CollectionValueSupport valueSupport = (CollectionValueSupport) property.getValue(); MetaValue[] metaValues = valueSupport.getElements(); for (MetaValue value : metaValues) { GenericValueSupport genValueSupport = (GenericValueSupport) value; ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport.getValue(); // Get any model errors/warnings MetaValue errors = managedObject.getProperty("errors").getValue(); //$NON-NLS-1$ if (errors != null) { CollectionValueSupport errorValueSupport = (CollectionValueSupport) errors; MetaValue[] errorArray = errorValueSupport.getElements(); count += errorArray.length; } } return count; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@Override public DocumentModel getEntryFromSource(String id, boolean fetchReferences) throws DirectoryException { try {/*from www . j a v a 2 s .com*/ SearchResult result = getLdapEntry(id, true); if (result == null) { return null; } return ldapResultToDocumentModel(result, id, fetchReferences); } catch (NamingException e) { throw new DirectoryException("getEntry failed: " + e.getMessage(), e); } }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Loads user credential information for the supplied user from the LDAP server. * * @param key the user id of the user for whom credential information is to be retrieved. * @return the credentials associated with the supplied user. * @throws SSOIdentityException fatal exception obtaining user credentials *///from w ww . jav a2 s. c o m public Credential[] loadCredentials(CredentialKey key, CredentialProvider cp) throws SSOIdentityException { try { if (!(key instanceof CredentialKey)) { throw new SSOIdentityException("Unsupported key type : " + key.getClass().getName()); } List credentials = new ArrayList(); HashMap credentialResultSet = selectCredentials(((SimpleUserKey) key).getId()); Iterator i = credentialResultSet.keySet().iterator(); while (i.hasNext()) { String cName = (String) i.next(); Object cValue = (Object) credentialResultSet.get(cName); Credential c = cp.newCredential(cName, cValue); credentials.add(c); } return (Credential[]) credentials.toArray(new Credential[credentialResultSet.size()]); } catch (NamingException e) { throw new SSOIdentityException( "Error obtaining credentials for user : " + key + " (" + e.getMessage() + ")", e); } }
From source file:org.forgerock.openidm.repo.jdbc.impl.JDBCRepoService.java
/** * Initializes the JDBC Repository Service with the supplied configuration * //w w w . j a va 2 s .c o m * @param config the configuration object * @param bundleContext the bundle context * @throws InvalidException */ void init(JsonValue config, BundleContext bundleContext) throws InvalidException { try { String enabled = config.get("enabled").asString(); if ("false".equals(enabled)) { logger.debug("JDBC repository not enabled"); throw new RuntimeException("JDBC repository not enabled."); } JsonValue connectionConfig = config.get(CONFIG_CONNECTION).isNull() ? config : config.get(CONFIG_CONNECTION); maxTxRetry = connectionConfig.get("maxTxRetry").defaultTo(5).asInteger().intValue(); // Data Source configuration jndiName = connectionConfig.get(CONFIG_JNDI_NAME).asString(); String jtaName = connectionConfig.get(CONFIG_JTA_NAME).asString(); if (jndiName != null && jndiName.trim().length() > 0) { // Get DB connection via JNDI logger.info("Using DB connection configured via Driver Manager"); InitialContext ctx = null; try { ctx = new InitialContext(); } catch (NamingException ex) { logger.warn("Getting JNDI initial context failed: " + ex.getMessage(), ex); } if (ctx == null) { throw new InvalidException( "Current platform context does not support lookup of repository DB via JNDI. " + " Configure DB initialization via direct " + CONFIG_DB_DRIVER + " configuration instead."); } useDataSource = true; ds = (DataSource) ctx.lookup(jndiName); // e.g. "java:comp/env/jdbc/MySQLDB" } else if (!StringUtils.isBlank(jtaName)) { // e.g. osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/openidm) OsgiName lookupName = OsgiName.parse(jtaName); Object service = ServiceUtil.getService(bundleContext, lookupName, null, true); if (service instanceof DataSource) { useDataSource = true; ds = (DataSource) service; } else { throw new RuntimeException("DataSource can not be retrieved for: " + jtaName); } } else { // Get DB Connection via Driver Manager dbDriver = connectionConfig.get(CONFIG_DB_DRIVER).asString(); if (dbDriver == null || dbDriver.trim().length() == 0) { throw new InvalidException( "Either a JNDI name (" + CONFIG_JNDI_NAME + "), " + "or a DB driver lookup (" + CONFIG_DB_DRIVER + ") needs to be configured to connect to a DB."); } dbUrl = connectionConfig.get(CONFIG_DB_URL).required().asString(); user = connectionConfig.get(CONFIG_USER).required().asString(); password = connectionConfig.get(CONFIG_PASSWORD).defaultTo("").asString(); logger.info("Using DB connection configured via Driver Manager with Driver {} and URL", dbDriver, dbUrl); try { Class.forName(dbDriver); } catch (ClassNotFoundException ex) { logger.error("Could not find configured database driver " + dbDriver + " to start repository ", ex); throw new InvalidException( "Could not find configured database driver " + dbDriver + " to start repository ", ex); } Boolean enableConnectionPool = connectionConfig.get("enableConnectionPool").defaultTo(Boolean.FALSE) .asBoolean(); if (null == sharedDataSource) { Dictionary<String, String> serviceParams = new Hashtable<String, String>(1); serviceParams.put("osgi.jndi.service.name", "jdbc/openidm"); sharedDataSource = bundleContext.registerService(DataSource.class.getName(), DataSourceFactory.newInstance(connectionConfig), serviceParams); } if (enableConnectionPool) { ds = DataSourceFactory.newInstance(connectionConfig); useDataSource = true; logger.info("DataSource connection pool enabled."); } else { logger.info("No DataSource connection pool enabled."); } } // Table handling configuration String dbSchemaName = connectionConfig.get(CONFIG_DB_SCHEMA).defaultTo(null).asString(); JsonValue genericQueries = config.get("queries").get("genericTables"); int maxBatchSize = connectionConfig.get(CONFIG_MAX_BATCH_SIZE).defaultTo(100).asInteger(); tableHandlers = new HashMap<String, TableHandler>(); //TODO Make safe the database type detection DatabaseType databaseType = DatabaseType.valueOf( connectionConfig.get(CONFIG_DB_TYPE).defaultTo(DatabaseType.ANSI_SQL99.name()).asString()); JsonValue defaultMapping = config.get("resourceMapping").get("default"); if (!defaultMapping.isNull()) { defaultTableHandler = getGenericTableHandler(databaseType, defaultMapping, dbSchemaName, genericQueries, maxBatchSize); logger.debug("Using default table handler: {}", defaultTableHandler); } else { logger.warn("No default table handler configured"); } // Default the configuration table for bootstrap JsonValue defaultTableProps = new JsonValue(new HashMap()); defaultTableProps.put("mainTable", "configobjects"); defaultTableProps.put("propertiesTable", "configobjectproperties"); defaultTableProps.put("searchableDefault", Boolean.FALSE); GenericTableHandler defaultConfigHandler = getGenericTableHandler(databaseType, defaultTableProps, dbSchemaName, genericQueries, 1); tableHandlers.put("config", defaultConfigHandler); JsonValue genericMapping = config.get("resourceMapping").get("genericMapping"); if (!genericMapping.isNull()) { for (String key : genericMapping.keys()) { JsonValue value = genericMapping.get(key); if (key.endsWith("/*")) { // For matching purposes strip the wildcard at the end key = key.substring(0, key.length() - 1); } TableHandler handler = getGenericTableHandler(databaseType, value, dbSchemaName, genericQueries, maxBatchSize); tableHandlers.put(key, handler); logger.debug("For pattern {} added handler: {}", key, handler); } } JsonValue explicitQueries = config.get("queries").get("explicitTables"); JsonValue explicitMapping = config.get("resourceMapping").get("explicitMapping"); if (!explicitMapping.isNull()) { for (Object keyObj : explicitMapping.keys()) { JsonValue value = explicitMapping.get((String) keyObj); String key = (String) keyObj; if (key.endsWith("/*")) { // For matching purposes strip the wildcard at the end key = key.substring(0, key.length() - 1); } TableHandler handler = getMappedTableHandler(databaseType, value, value.get("table").required().asString(), value.get("objectToColumn").required().asMap(), dbSchemaName, explicitQueries, maxBatchSize); tableHandlers.put(key, handler); logger.debug("For pattern {} added handler: {}", key, handler); } } } catch (RuntimeException ex) { logger.warn("Configuration invalid, can not start JDBC repository.", ex); throw new InvalidException("Configuration invalid, can not start JDBC repository.", ex); } catch (NamingException ex) { throw new InvalidException("Could not find configured jndiName " + jndiName + " to start repository ", ex); } catch (InternalServerErrorException ex) { throw new InvalidException("Could not initialize mapped table handler, can not start JDBC repository.", ex); } Connection testConn = null; try { // Check if we can get a connection testConn = getConnection(); testConn.setAutoCommit(true); // Ensure we do not implicitly start transaction isolation } catch (Exception ex) { logger.warn("JDBC Repository start-up experienced a failure getting a DB connection: " + ex.getMessage() + ". If this is not temporary or resolved, Repository operation will be affected.", ex); } finally { if (testConn != null) { try { testConn.close(); } catch (SQLException ex) { logger.warn("Failure during test connection close ", ex); } } } }
From source file:org.wso2.carbon.event.input.adapter.jms.internal.util.JMSListener.java
private boolean checkJMSConnection(JMSTaskManager stm) { Connection connection = null; boolean connectionEstablished = false; Hashtable<String, String> jmsProperties = stm.getJmsProperties(); try {// w w w.ja v a 2 s. co m ConnectionFactory jmsConFactory = null; try { jmsConFactory = JMSUtils.lookup(new InitialContext(stm.getJmsProperties()), ConnectionFactory.class, stm.getConnFactoryJNDIName()); } catch (NamingException e) { log.error("Error looking up connection factory : " + stm.getConnFactoryJNDIName() + "using JNDI properties : " + jmsProperties, e); } connection = JMSUtils.createConnection(jmsConFactory, jmsProperties.get(JMSConstants.PARAM_JMS_USERNAME), jmsProperties.get(JMSConstants.PARAM_JMS_PASSWORD), stm.isJmsSpec11(), stm.isQueue(), stm.isSubscriptionDurable(), stm.getDurableSubscriberClientId()); connectionEstablished = connection != null; } catch (JMSException ignore) { // we silently ignore this as a JMSException can be expected when connection is not available } finally { if (connectionEstablished) { try { connection.close(); } catch (JMSException e) { log.debug("Error while closing established Test JMS connection: " + e.getMessage(), e); } } } return connectionEstablished; }
From source file:com.flexive.core.Database.java
/** * Retrieve data source for global configuration table, regardless * of the current request's division id. * * @return a database connection//from ww w .j av a2s .c om * @throws SQLException if no connection could be retrieved */ public static synchronized DataSource getGlobalDataSource() throws SQLException { // Try to obtain a connection if (globalDataSource != null) { return globalDataSource; } try { final Context c = EJBLookup.getInitialContext(); for (String path : getPossibleJndiNames(DS_GLOBAL_CONFIG)) { try { if (LOG.isDebugEnabled()) { LOG.debug("Trying JNDI path " + path + "..."); } globalDataSource = (DataSource) c.lookup(path); if (LOG.isInfoEnabled()) { LOG.info("Found global datasource under JNDI path " + path); } break; } catch (NamingException e) { // try next path } } if (globalDataSource == null) { //try the weird geronimo logic as last resort Object o = null; try { o = EJBLookup.getInitialContext().lookup( "jca:/console.dbpool/flexiveConfiguration/JCAManagedConnectionFactory/flexiveConfiguration"); globalDataSource = (DataSource) o.getClass().getMethod("$getResource").invoke(o); } catch (NoSuchMethodException e) { if (o instanceof DataSource) return (DataSource) o; String sErr = "Unable to retrieve Connection to [" + DS_GLOBAL_CONFIG + "]: JNDI resource is no DataSource and method $getResource not found!"; LOG.error(sErr); throw new SQLException(sErr); } catch (NamingException e) { // not bound, try next path } catch (Exception e) { final String msg = "Unable to retrieve Connection to [" + DS_GLOBAL_CONFIG + "]: " + e.getMessage(); LOG.error(msg); throw new SQLException(msg); } } if (globalDataSource == null) { globalDataSource = tryGetDefaultDataSource(c, GlobalConfigurationEngineBean.DEFAULT_DS_CONFIG, new DefaultGlobalDataSourceInitializer()); } if (globalDataSource == null) { final String msg = "Unable to retrieve Connection to [" + DS_GLOBAL_CONFIG + "]: no datasource found in JNDI"; LOG.error(msg); throw new SQLException(msg); } return globalDataSource; } catch (NamingException exc) { String msg = "Naming Exception, unable to retrieve Connection to [" + DS_GLOBAL_CONFIG + "]: " + exc.getMessage(); LOG.error(msg); throw new SQLException(msg); } }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
public boolean abort() throws LoginException { try {/*from w w w . java 2 s .c o m*/ _rootContext.close(); } catch (NamingException e) { throw new LoginException("error closing root context: " + e.getMessage()); } return super.abort(); }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
public boolean commit() throws LoginException { try {/*w w w . j a v a 2 s .com*/ _rootContext.close(); } catch (NamingException e) { throw new LoginException("error closing root context: " + e.getMessage()); } if (_userFirstName != null) getSubject().getPrincipals().add(new LdapFirstNamePrincipal(_userFirstName)); if (_userLastName != null) getSubject().getPrincipals().add(new LdapLastNamePrincipal(_userLastName)); if (_userEmail != null) getSubject().getPrincipals().add(new LdapEmailPrincipal(_userEmail)); return super.commit(); }
From source file:ldap.LdapApi.java
/** * getLdapUsers() returns users based on certain criteria * @param searchDn - searchDn base//from w w w. j av a2s .c o m * @param attrList - searchDn base * @param startChar - start character to search for Users with alphabets * @param endChar - end character to search for Users with alphabets * @param pageSize - the number of users to return * @param pageNumber - the number of the page * (for example (A, C) or (A,A) * @return List - of matching, sorted users * @throws LdapException */ public List getLdapUsers(String searchDn, String[] attrList, char startChar, char endChar, int pageSize, int pageNumber) throws LdapException { logger.info("searchDn = " + searchDn); //logger.info("attrList = " + attrList); try { SearchUtility searcher = getSearcher(searchDn); try { List<Entry> users = searcher.getUsers(searchBase, startChar, endChar, pageSize, pageNumber, context); return getAttrUsersList(searcher, attrList, users); } catch (NamingException e) { throw new LdapException( "getUsers(searchBase, startChar, endChar, pageSize, pageNumber, context) exception, searchDn=" + searchDn + " startChar=" + startChar + " endChar=" + endChar + " pageSize=" + pageSize + " pageNumber=" + pageNumber + e.getMessage(), e); } } catch (Exception e1) { throw new LdapException("getSearcher(searchDn)" + e1.getMessage(), e1); } }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
@Override public <T> List<T> search(Class<T> clazz, String filter) { if (null == filter) { return null; }// ww w . j a va2 s. c o m LogUtils.debug(LOG, "search " + clazz.getName() + " with filter=" + filter); SearchControls ctrl = new SearchControls(); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); ctrl.setReturningAttributes(EntityMetaData.getDefinedAttrNames(clazz)); List<T> retVal = new ArrayList<T>(); try { NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl); while (results.hasMore()) { try { SearchResult result = results.next(); T entity = null; if (sessionCache.containsKey(result.getNameInNamespace())) { // guarantee the reference integrity for one search result entity = (T) sessionCache.get(result.getNameInNamespace()); } else { entity = fromAttributesToEntity(clazz, result.getAttributes()); sessionCache.put(result.getNameInNamespace(), entity); } retVal.add(entity); } catch (NamingException e) { LogUtils.error(LOG, "Unable to construct the entity", e); } } } catch (NamingException e) { throw new SessionException(e.getMessage(), e); } return retVal; }