类javax.naming.NamingException源码实例Demo

下面列出了怎么用javax.naming.NamingException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: tomcatsrc   文件: JNDIRealm.java
/**
 * 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();
}
 
源代码2 项目: fiat   文件: LdapUserRolesProvider.java
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;
}
 
源代码3 项目: cloudstack   文件: ADLdapUserManagerImpl.java
@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;
}
 
源代码4 项目: tomee   文件: ResourcesJsonTest.java
@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");
}
 
源代码5 项目: product-ei   文件: AndesJMSConsumer.java
/**
 * 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();
        }
    }
}
 
@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();
}
 
@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();
    }
}
 
源代码8 项目: hibersap   文件: JCAContext.java
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);
    }
}
 
源代码9 项目: product-ei   文件: MixedQueueTopicTestCase.java
/**
 * 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);
}
 
源代码10 项目: tomee   文件: RealmInWebAppForEjbRemoteTest.java
@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());
}
 
源代码11 项目: cxf   文件: LdapCertificateRepo.java
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);
    }
}
 
源代码12 项目: qpid-jms   文件: ActiveMQAdmin.java
@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);
    }
}
 
public Object removeFromEnvironment(String propName) throws NamingException {
    if (TraceCarol.isDebugJndiCarol()) {
        TraceCarol.debugJndiCarol("LmiInitialContext.removeFromEnvironment(\"" + propName + "\")");
    }
    if (lmiEnv == null) return null;
    return lmiEnv.remove(propName);
}
 
源代码14 项目: tomee   文件: OpenEjbContainer.java
@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());
}
 
源代码15 项目: jdk8u60   文件: Connections.java
/**
 * 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;
}
 
源代码16 项目: liberty-bikes   文件: GameRound.java
private ManagedScheduledExecutorService executor() {
    try {
        return InitialContext.doLookup("java:comp/DefaultManagedScheduledExecutorService");
    } catch (NamingException e) {
        log("Unable to obtain ManagedScheduledExecutorService");
        e.printStackTrace();
        return null;
    }
}
 
源代码17 项目: herd-mdl   文件: LdapUtil.java
/**
 * 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);
}
 
源代码18 项目: carbon-apimgt   文件: JMSConnectionFactory.java
/**
 * 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;
}
 
源代码19 项目: iaf   文件: LoginFilter.java
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;
}
 
源代码20 项目: logging-log4j2   文件: JmsManager.java
@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();
        }
    }
}
 
源代码21 项目: hottub   文件: ContinuationDirContext.java
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);
}
 
源代码22 项目: cxf   文件: LdapUtils.java
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;
}
 
源代码23 项目: cloudstack   文件: LdapUtils.java
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;
}
 
源代码24 项目: apiman   文件: BasicAuthLDAPTest.java
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);
    }
}
 
源代码25 项目: proarc   文件: ProarcInitializer.java
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);
    }
}
 
源代码26 项目: spring-ldap   文件: DirContextAdapterTest.java
@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");
}
 
源代码27 项目: olat   文件: LDAPLoginManagerImpl.java
/**
 * 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;
}
 
源代码28 项目: projectforge-webapp   文件: LdapTemplate.java
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();
}
 
源代码29 项目: spring-ldap   文件: PagedSearchITest.java
@Before
public void prepareTestedData() throws IOException, NamingException {
    LdapTestUtils.cleanAndSetup(
            contextSource,
            LdapUtils.newLdapName("ou=People"),
            new ClassPathResource("/setup_data.ldif"));
}
 
源代码30 项目: tomcatsrc   文件: JNDIRealm.java
/**
 * 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);
}
 
 类所在包
 同包方法