Java Code Examples for javax.naming.NamingException

The following examples show how to use javax.naming.NamingException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: tomcatsrc   Source File: JNDIRealm.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Prepare for the beginning of active use of the public methods of this
 * component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {

    // Check to see if the connection to the directory can be opened
    try {
        open();
    } catch (NamingException e) {
        // A failure here is not fatal as the directory may be unavailable
        // now but available later. Unavailability of the directory is not
        // fatal once the Realm has started so there is no reason for it to
        // be fatal when the Realm starts.
        containerLog.error(sm.getString("jndiRealm.open"), e);
    }

    super.startInternal();
}
 
Example 2
Source Project: fiat   Source File: LdapUserRolesProvider.java    License: Apache License 2.0 6 votes vote down vote up
public List<Pair<String, Role>> mapFromAttributes(Attributes attrs) throws NamingException {
  String group = attrs.get(configProps.getGroupRoleAttributes()).get().toString();
  Role role = new Role(group).setSource(Role.Source.LDAP);
  List<Pair<String, Role>> member = new ArrayList<>();
  for (NamingEnumeration<?> members = attrs.get(configProps.getGroupUserAttributes()).getAll();
      members.hasMore(); ) {
    try {
      String user =
          String.valueOf(configProps.getUserDnPattern().parse(members.next().toString())[0]);
      member.add(Pair.of(user, role));
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
  return member;
}
 
Example 3
Source Project: cloudstack   Source File: ADLdapUserManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context, Long domainId) throws NamingException {
    if (StringUtils.isBlank(groupName)) {
        throw new IllegalArgumentException("ldap group name cannot be blank");
    }

    String basedn = _ldapConfiguration.getBaseDn(domainId);
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes(domainId));

    NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName, domainId), searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result, domainId));
    }
    return users;
}
 
Example 4
Source Project: tomee   Source File: ResourcesJsonTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws OpenEJBException, NamingException, IOException {
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();

    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));

    final AppModule app = new AppModule(ResourcesJsonTest.class.getClassLoader(), ResourcesJsonTest.class.getSimpleName());

    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new SingletonBean(ConfiguredThroughJSonBean.class));
    app.getEjbModules().add(new EjbModule(ejbJar));
    app.getEjbModules().iterator().next().getAltDDs().put("resources.json", getClass().getClassLoader().getResource("appresource.resources.json"));

    assembler.createApplication(config.configureApplication(app));

    final Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
    properties.setProperty("openejb.embedded.initialcontext.close", "destroy");

    // some hack to be sure to call destroy()
    context = new InitialContext(properties);

    bean = (ConfiguredThroughJSonBean) context.lookup("ConfiguredThroughJSonBeanLocalBean");
}
 
Example 5
Source Project: product-ei   Source File: AndesJMSConsumer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new JMS consumer with a given configuration.
 *
 * @param config         The configuration.
 * @param createConsumer Creates the connection, session and receiver.
 * @throws NamingException
 * @throws JMSException
 */
public AndesJMSConsumer(AndesJMSConsumerClientConfiguration config, boolean createConsumer)
        throws NamingException, JMSException {
    super(config);
    receivedMessageCount = new AtomicLong(0);

    // Sets the configuration
    this.consumerConfig = config;

    if (createConsumer) {
        if (ExchangeType.QUEUE == this.consumerConfig.getExchangeType()) {
            this.createQueueConnection();

        } else if (ExchangeType.TOPIC == this.consumerConfig.getExchangeType()) {
            this.createTopicConnection();
        }
    }
}
 
Example 6
@Test
public void testModifyAttributesWithException() {
	String dn = "cn=Some Person,ou=company1,ou=Sweden";
	try {
		// Perform test
		dummyDao.modifyAttributesWithException(dn, "Updated lastname", "Updated description");
		fail("DummyException expected");
	}
	catch (DummyException expected) {
		assertThat(true).isTrue();
	}

	// Verify result - check that the operation was properly rolled back
	Object result = ldapTemplate.lookup(dn, new AttributesMapper() {
		public Object mapFromAttributes(Attributes attributes) throws NamingException {
			assertThat(attributes.get("sn").get()).isEqualTo("Person");
			assertThat(attributes.get("description").get()).isEqualTo("Sweden, Company1, Some Person");
			return new Object();
		}
	});

	assertThat(result).isNotNull();
}
 
Example 7
@SuppressWarnings("unchecked")
public void testSyncUserWithLdapNamingException() throws Exception {
    addLdapOrganizationSetting();
    VOUserDetails user1 = initTestUser();
    user1.setEMail("[email protected]");
    user1.setRealmUserId(user1.getUserId());
    userToReturnByLdap = user1;
    idMgmt.importLdapUsers(Collections.singletonList(user1), MP_ID);
    user1 = retrieveUser(user1.getUserId());

    doThrow(new NamingException()).when(ldapService).search(
            any(Properties.class), anyString(), anyString(),
            any(ILdapResultMapper.class), anyBoolean());
    try {
        idMgmt.notifyOnLoginAttempt(user1, true);
        fail();
    } catch (EJBException ex) {
        verify(connectorMock, times(1))
                .ensureAllMandatoryLdapPropertiesPresent();
    }
}
 
Example 8
Source Project: hibersap   Source File: JCAContext.java    License: Apache License 2.0 6 votes vote down vote up
private ConnectionFactory getConnectionFactory(final String jndiName) {
    try {
        final InitialContext initialContext = new InitialContext();
        final Object object = initialContext.lookup(jndiName);

        if (object == null) {
            throw new HibersapException("Name not bound: " + jndiName);
        }

        if (!(object instanceof ConnectionFactory)) {
            throw new HibersapException("Object bound under " + jndiName + " is no ConnectionFactory");
        }

        return (ConnectionFactory) object;
    } catch (final NamingException e) {
        throw new HibersapException("JNDI lookup:", e);
    }
}
 
Example 9
Source Project: product-ei   Source File: MixedQueueTopicTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create subscribers for the second queue.
 *
 * @throws AndesClientException
 * @throws JMSException
 * @throws IOException
 * @throws NamingException
 * @throws AndesClientConfigurationException
 */
private void createQueue2Subscribers() throws AndesClientException, JMSException, IOException, NamingException,
        AndesClientConfigurationException {
    AndesJMSConsumerClientConfiguration queue2ConsumerBroker1Config =
            new AndesJMSConsumerClientConfiguration(broker1.getHostName(),
                    broker1.getPort(), ExchangeType.QUEUE, queueName2);
    queue2ConsumerBroker1Config.setPrintsPerMessageCount(printPerMessageCount);

    AndesJMSConsumerClientConfiguration queue2ConsumerBroker2Config =
            new AndesJMSConsumerClientConfiguration(broker2.getHostName(),
                    broker2.getPort(), ExchangeType.QUEUE, queueName2);
    queue2ConsumerBroker2Config.setPrintsPerMessageCount(printPerMessageCount);

    Set<AndesClient> queue2Subscribers = new HashSet<>();
    AndesClient queue2ConsumerBroker1 = new AndesClient(queue2ConsumerBroker1Config, true);
    queue2Subscribers.add(queue2ConsumerBroker1);

    AndesClient queue2ConsumerBroker2 = new AndesClient(queue2ConsumerBroker2Config, true);
    queue2Subscribers.add(queue2ConsumerBroker2);

    subscribers.put(queueName2, queue2Subscribers);
}
 
Example 10
Source Project: tomee   Source File: RealmInWebAppForEjbRemoteTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void lookup() throws NamingException
{
    if ("true".equals(SystemInstance.get().getProperty("embedded"))) { /// tomee webapp is not deployed so skipping
        return;
    }

    final Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
    p.put(Context.PROVIDER_URL, "http://" + webapp.getHost() + ":" + webapp.getPort() + "/tomee/ejb");
    p.put(Context.SECURITY_PRINCIPAL, "tom");
    p.put(Context.SECURITY_CREDENTIALS, "ee");
    p.put("openejb.authentication.realmName", "realm-test"); // webapp name to force login using the matching realm
    final Context ctx = new InitialContext(p);
    final Simple myBean = Simple.class.cast(ctx.lookup("java:global/realm-test/SimpleEJB!" + Simple.class.getName()));
    assertEquals("tom", myBean.name());
}
 
Example 11
Source Project: cxf   Source File: LdapCertificateRepo.java    License: Apache License 2.0 6 votes vote down vote up
protected List<X509Certificate> getCertificatesFromLdap(String tmpRootDN, String tmpFilter, String tmpAttrName) {
    try {
        List<X509Certificate> certificates = new ArrayList<>();
        NamingEnumeration<SearchResult> answer = ldapSearch.searchSubTree(tmpRootDN, tmpFilter);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute attribute = attrs.get(tmpAttrName);
            if (attribute != null) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(
                        (byte[]) attribute.get()));
                certificates.add(certificate);
            }
        }
        return certificates;
    } catch (CertificateException | NamingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 12
Source Project: qpid-jms   Source File: ActiveMQAdmin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void createConnectionFactory(String name) {
    try {
        final ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + port);
        context.bind(name, factory);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
public Object removeFromEnvironment(String propName) throws NamingException {
    if (TraceCarol.isDebugJndiCarol()) {
        TraceCarol.debugJndiCarol("LmiInitialContext.removeFromEnvironment(\"" + propName + "\")");
    }
    if (lmiEnv == null) return null;
    return lmiEnv.remove(propName);
}
 
Example 14
Source Project: tomee   Source File: OpenEjbContainer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String getName(final String name) throws NamingException {
    if ("inject".equals(name)) {
        return name;
    }

    if (!name.startsWith("java:")) {
        throw new NameNotFoundException("Name must be in java: namespace");
    }

    return name.substring("java:".length());
}
 
Example 15
Source Project: jdk8u60   Source File: Connections.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves a PooledConnection from this list of connections.
 * Use an existing one if one is idle, or create one if the list's
 * max size hasn't been reached. If max size has been reached, wait
 * for a PooledConnection to be returned, or one to be removed (thus
 * not reaching the max size any longer).
 *
 * @param timeout if > 0, msec to wait until connection is available
 * @param factory creates the PooledConnection if one needs to be created
 *
 * @return A non-null PooledConnection
 * @throws NamingException PooledConnection cannot be created, because this
 * thread was interrupted while it waited for an available connection,
 * or if it timed out while waiting, or the creation of a connection
 * resulted in an error.
 */
synchronized PooledConnection get(long timeout,
    PooledConnectionFactory factory) throws NamingException {
    PooledConnection conn;
    long start = (timeout > 0 ? System.currentTimeMillis() : 0);
    long waittime = timeout;

    d("get(): before");
    while ((conn = getOrCreateConnection(factory)) == null) {
        if (timeout > 0 && waittime <= 0) {
            throw new CommunicationException(
                "Timeout exceeded while waiting for a connection: " +
                timeout + "ms");
        }
        try {
            d("get(): waiting");
            if (waittime > 0) {
                wait(waittime);  // Wait until one is released or removed
            } else {
                wait();
            }
        } catch (InterruptedException e) {
            throw new InterruptedNamingException(
                "Interrupted while waiting for a connection");
        }
        // Check whether we timed out
        if (timeout > 0) {
            long now = System.currentTimeMillis();
            waittime = timeout - (now - start);
        }
    }

    d("get(): after");
    return conn;
}
 
Example 16
Source Project: liberty-bikes   Source File: GameRound.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private ManagedScheduledExecutorService executor() {
    try {
        return InitialContext.doLookup("java:comp/DefaultManagedScheduledExecutorService");
    } catch (NamingException e) {
        log("Unable to obtain ManagedScheduledExecutorService");
        e.printStackTrace();
        return null;
    }
}
 
Example 17
Source Project: herd-mdl   Source File: LdapUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * delete ldap AD group with provided group name
 *
 * @param groupName ldap AD group name to delete
 * @throws NamingException
 */
public static void deleteAdGroup(String groupName) throws NamingException {
    LOGGER.info(String.format("Remove AD group: %s", groupName));
    DirContext ldapContext = getLdapContext(User.getLdapAdminUser());
    String groupDn = constructGroupDn(groupName, OU_GROUPS);
    ldapContext.unbind(groupDn);
}
 
Example 18
Source Project: carbon-apimgt   Source File: JMSConnectionFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Lookup a Destination using this JMS CF definitions and JNDI name
 *
 * @param destinationName JNDI name of the Destionation
 * @return JMS Destination for the given JNDI name or null
 */
public Destination getDestination(String destinationName) {
    try {
        return JMSUtils.lookupDestination(context, destinationName, parameters.get(JMSConstants.PARAM_DEST_TYPE));
    } catch (NamingException e) {
        handleException("Error looking up the JMS destination with name " + destinationName
                        + " of type " + parameters.get(JMSConstants.PARAM_DEST_TYPE), e);
    }

    // never executes but keeps the compiler happy
    return null;
}
 
Example 19
Source Project: iaf   Source File: LoginFilter.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isMemberOf(DirContext ctx, String dnUser, String dnGroup) throws NamingException {
	DirContext lookedContext = (DirContext) (ctx.lookup(dnGroup));
	Attribute attrs = lookedContext.getAttributes("").get("member");
	for (int i = 0; i < attrs.size(); i++) {
		String foundMember = (String) attrs.get(i);
		if (foundMember.equalsIgnoreCase(dnUser)) {
			return true;
		}
	}
	return false;
}
 
Example 20
Source Project: logging-log4j2   Source File: JmsManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    while (!shutdown) {
        try {
            sleep(configuration.getReconnectIntervalMillis());
            reconnect();
        } catch (final InterruptedException | JMSException | NamingException e) {
            logger().debug("Cannot reestablish JMS connection to {}: {}", configuration, e.getLocalizedMessage(),
                    e);
        } finally {
            latch.countDown();
        }
    }
}
 
Example 21
public NamingEnumeration<SearchResult> search(String name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filterExpr, args,
                                     cons);
}
 
Example 22
Source Project: cxf   Source File: LdapUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue,
    String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
            public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(
            new EqualsFilter("objectclass", objectClass)).and(
                    new EqualsFilter(filterAttributeName, filterAttributeValue));

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((Map<?, ?>)result.get(0));
    }

    return ldapAttributes;
}
 
Example 23
Source Project: cloudstack   Source File: LdapUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> getAttributeValues(final Attributes attributes, final String attributeName) throws NamingException {
    ArrayList<String> memberships = new ArrayList<>();
    final Attribute attribute = attributes.get(attributeName);
    if (attribute != null) {
        NamingEnumeration<?> values = attribute.getAll();
        while(values.hasMore()) {
            memberships.add(String.valueOf(values.next()));
        }
    }
    return memberships;
}
 
Example 24
Source Project: apiman   Source File: BasicAuthLDAPTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void injectEntry(LdifEntry entry) throws Exception {
    if (entry.isChangeAdd()) {
        service.getAdminSession().add(
                new DefaultServerEntry(service.getSchemaManager(), entry.getEntry()));
    } else if (entry.isChangeModify()) {
        service.getAdminSession().modify(entry.getDn(), entry.getModificationItems());
    } else {
        String message = I18n.err(I18n.ERR_117, entry.getChangeType());
        throw new NamingException(message);
    }
}
 
Example 25
Source Project: proarc   Source File: ProarcInitializer.java    License: GNU General Public License v3.0 5 votes vote down vote up
private DataSource initProarcDb() {
    try {
        DataSource proarcSource = DbUtils.getProarcSource();
        daoFactory = new EmpireDaoFactory(EmpireConfiguration.postgres(proarcSource));
        daoFactory.init();
        return proarcSource;
    } catch (NamingException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 26
Source Project: spring-ldap   Source File: DirContextAdapterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddAttributeValueInUpdateMode() throws NamingException {
	tested.setUpdateMode(true);
	tested.addAttributeValue("abc", "123");

	// Perform test
	Attributes attrs = tested.getAttributes();
	assertThat(attrs.get("abc")).isNull();

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(1);
	Attribute attribute = modificationItems[0].getAttribute();
	assertThat(attribute.getID()).isEqualTo("abc");
	assertThat(attribute.get()).isEqualTo("123");
}
 
Example 27
Source Project: olat   Source File: LDAPLoginManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Find the user dn with its uid
 * 
 * @param uid
 * @param ctx
 * @return user's dn
 */
private String searchUserDN(final String uid, final DirContext ctx) {
    if (ctx == null) {
        return null;
    }

    final List<String> ldapBases = LDAPLoginModule.getLdapBases();
    final String objctClass = LDAPLoginModule.getLdapUserObjectClass();
    final String[] serachAttr = { "dn" };

    final String ldapUserIDAttribute = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))";
    final SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(serachAttr);

    String userDN = null;
    for (final String ldapBase : ldapBases) {
        try {
            final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
            while (enm.hasMore()) {
                final SearchResult result = enm.next();
                userDN = result.getNameInNamespace();
            }
            if (userDN != null) {
                break;
            }
        } catch (final NamingException e) {
            log.error("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e);
        }
    }

    return userDN;
}
 
Example 28
public Object excecute(final String username, final String password)
{
  try {
    ctx = ldapConnector.createContext(username, password);
  } catch (final NamingException ex) {
    log.error("While trying to connect LDAP initally: " + ex.getMessage(), ex);
    throw new RuntimeException(ex);
  }
  return internalExcecute();
}
 
Example 29
Source Project: spring-ldap   Source File: PagedSearchITest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void prepareTestedData() throws IOException, NamingException {
    LdapTestUtils.cleanAndSetup(
            contextSource,
            LdapUtils.newLdapName("ou=People"),
            new ClassPathResource("/setup_data.ldif"));
}
 
Example 30
Source Project: tomcatsrc   Source File: JNDIRealm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Use the distinguished name to locate the directory
 * entry for the user with the specified username and
 * return a User object; otherwise return <code>null</code>.
 *
 * @param context The directory context
 * @param username The username
 * @param attrIds String[]containing names of attributes to
 * @param dn Distinguished name of the user
 * retrieve.
 *
 * @exception NamingException if a directory server error occurs
 */
protected User getUserByPattern(DirContext context,
                                String username,
                                String[] attrIds,
                                String dn)
    throws NamingException {

    // If no attributes are requested, no need to look for them
    if (attrIds == null || attrIds.length == 0) {
        return new User(username, dn, null, null,null);
    }

    // Get required attributes from user entry
    Attributes attrs = null;
    try {
        attrs = context.getAttributes(dn, attrIds);
    } catch (NameNotFoundException e) {
        return null;
    }
    if (attrs == null)
        return null;

    // Retrieve value of userPassword
    String password = null;
    if (userPassword != null)
        password = getAttributeValue(userPassword, attrs);

    String userRoleAttrValue = null;
    if (userRoleAttribute != null) {
        userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
    }

    // Retrieve values of userRoleName attribute
    ArrayList<String> roles = null;
    if (userRoleName != null)
        roles = addAttributeValues(userRoleName, attrs, roles);

    return new User(username, dn, password, roles, userRoleAttrValue);
}