javax.naming.NamingException Java Examples

The following examples show how to use javax.naming.NamingException. 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 File: JNDIRealm.java    From tomcatsrc with 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 File: ADLdapUserManagerImpl.java    From cloudstack with 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 #3
Source File: ResourcesJsonTest.java    From tomee with 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 #4
Source File: AndesJMSConsumer.java    From product-ei with 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 #5
Source File: ContextSourceAndHibernateTransactionManagerNamespaceITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: IdentityServiceBeanLdapWithDbIT.java    From development with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: JCAContext.java    From hibersap with 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 #8
Source File: MixedQueueTopicTestCase.java    From product-ei with 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 #9
Source File: RealmInWebAppForEjbRemoteTest.java    From tomee with 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 #10
Source File: LdapUserRolesProvider.java    From fiat with 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 #11
Source File: LdapCertificateRepo.java    From cxf with 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 File: LdapUtils.java    From cxf with 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 #13
Source File: OpenEjbContainer.java    From tomee with 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 #14
Source File: LdapUtil.java    From herd-mdl with 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 #15
Source File: JMSConnectionFactory.java    From carbon-apimgt with 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 #16
Source File: right_LmiInitialContext_1.6.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: GameRound.java    From liberty-bikes with 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 #18
Source File: JmsManager.java    From logging-log4j2 with 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 #19
Source File: ActiveMQAdmin.java    From qpid-jms with 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 #20
Source File: ContinuationDirContext.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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 #21
Source File: right_LmiInitialContext_1.6.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public Name composeName(Name name, Name prefix) throws NamingException {
    if (TraceCarol.isDebugJndiCarol()) {
        TraceCarol.debugJndiCarol("LmiInitialContext.composeName(" + name + "," + prefix + ")");
    }
    Name result = (Name) (prefix.clone());
    result.addAll(name);
    return result;
}
 
Example #22
Source File: PagedSearchITest.java    From spring-ldap with 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 #23
Source File: LdapUtils.java    From cloudstack with 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 File: BasicAuthLDAPTest.java    From apiman with 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 File: ProarcInitializer.java    From proarc with 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 File: TestMailer.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private void send(List<File> attachments, boolean highPriority) throws NamingException {
	final String toAddress = "test";
	final String subject = "test subject";
	final String message = "test message";
	try {
		mailer.send(toAddress, subject, message, attachments, highPriority);
	} catch (final MessagingException e) {
		assertNotNull("ok", e);
	}
}
 
Example #27
Source File: DirContextAdapterTest.java    From spring-ldap with 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 #28
Source File: LDAPLoginManagerImpl.java    From olat with 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 #29
Source File: JNDIRealm.java    From tomcatsrc with 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);
}
 
Example #30
Source File: LdapTemplate.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
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();
}