Java源码示例:org.springframework.ldap.core.ContextSource
示例1
/**
* @param contextSource
* @param groupSearchBase
*/
public AuthoritiesPopulator(ContextSource contextSource, String groupSearchBase, String adminRole,
String defaultRole) {
super(contextSource, groupSearchBase);
this.adminRoleAsAuthority = new SimpleGrantedAuthority(adminRole.toUpperCase(Locale.ROOT)); // spring will
// convert group names to uppercase by default
String[] defaultRoles = StringUtils.split(defaultRole, ",");
if (ArrayUtils.contains(defaultRoles, Constant.ROLE_MODELER)) {
this.defaultAuthorities.add(modelerAuthority);
this.defaultAuthorities.add(analystAuthority);
}
if (ArrayUtils.contains(defaultRoles, Constant.ROLE_ANALYST))
this.defaultAuthorities.add(analystAuthority);
}
示例2
public String uid2ext(String uid) {
String externalIdAttribute = ApplicationProperty.AuthenticationLdapIdAttribute.value();
if ("uid".equals(externalIdAttribute)) return uid; // Nothing to translate
try {
ContextSource source = (ContextSource)SpringApplicationContextHolder.getBean("unitimeLdapContextSource");
String query = ApplicationProperty.AuthenticationLdapLogin2UserId.value();
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", uid), new String[] {externalIdAttribute});
return user == null ? null : user.getStringAttribute(externalIdAttribute);
} catch (Exception e) {
sLog.warn("Unable to translate uid to " + externalIdAttribute + ": " + e.getMessage());
}
return null;
}
示例3
public String ext2uid(String externalUserId) {
String externalIdAttribute = ApplicationProperty.AuthenticationLdapIdAttribute.value();
if ("uid".equals(externalIdAttribute)) return externalUserId; // Nothing to translate
try {
ContextSource source = (ContextSource)SpringApplicationContextHolder.getBean("unitimeLdapContextSource");
String query = ApplicationProperty.AuthenticationLdapUserId2Login.value().replace("%", externalIdAttribute);
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", externalIdAttribute), new String[] {"uid"});
return user == null ? null : user.getStringAttribute("uid");
} catch (Exception e) {
sLog.warn("Unable to translate " + externalIdAttribute + " to uid: " + e.getMessage());
}
return null;
}
示例4
/**
* @param contextSource
* @param groupSearchBase
*/
public AuthoritiesPopulator(ContextSource contextSource, String groupSearchBase, String adminRole,
String defaultRole) {
super(contextSource, groupSearchBase);
this.adminRoleAsAuthority = new SimpleGrantedAuthority(adminRole.toUpperCase(Locale.ROOT)); // spring will
// convert group names to uppercase by default
String[] defaultRoles = StringUtils.split(defaultRole, ",");
if (ArrayUtils.contains(defaultRoles, Constant.ROLE_MODELER)) {
this.defaultAuthorities.add(modelerAuthority);
this.defaultAuthorities.add(analystAuthority);
}
if (ArrayUtils.contains(defaultRoles, Constant.ROLE_ANALYST))
this.defaultAuthorities.add(analystAuthority);
}
示例5
/**
* Set the ContextSource to work on. Even though the actual ContextSource
* sent to the LdapTemplate instance should be a
* {@link TransactionAwareContextSourceProxy}, the one sent to this method
* should be the target of that proxy. If it is not, the target will be
* extracted and used instead.
*
* @param contextSource
* the ContextSource to work on.
*/
public void setContextSource(ContextSource contextSource) {
if (contextSource instanceof TransactionAwareContextSourceProxy) {
TransactionAwareContextSourceProxy proxy = (TransactionAwareContextSourceProxy) contextSource;
this.contextSource = proxy.getTarget();
} else {
this.contextSource = contextSource;
}
if (contextSource instanceof AbstractContextSource) {
AbstractContextSource abstractContextSource = (AbstractContextSource) contextSource;
if(abstractContextSource.isAnonymousReadOnly()) {
throw new IllegalArgumentException(
"Compensating LDAP transactions cannot be used when context-source is anonymous-read-only");
}
}
}
示例6
/**
* Construct a SingleContextSource and execute the LdapOperationsCallback using the created instance.
* This makes sure the same connection will be used for all operations inside the LdapOperationsCallback,
* which is particularly useful when working with e.g. Paged Results as these typically require the exact
* same connection to be used for all requests involving the same cookie..
* The SingleContextSource instance will be properly disposed of once the operation has been completed.
*
* @param contextSource The target ContextSource to retrieve a DirContext from
* @param callback the callback to perform the Ldap operations
* @param useReadOnly if <code>true</code>, use the {@link org.springframework.ldap.core.ContextSource#getReadOnlyContext()}
* method on the target ContextSource to get the actual DirContext instance, if <code>false</code>,
* use {@link org.springframework.ldap.core.ContextSource#getReadWriteContext()}.
* @param ignorePartialResultException Used for populating this property on the created LdapTemplate instance.
* @param ignoreNameNotFoundException Used for populating this property on the created LdapTemplate instance.
* @return the result returned from the callback.
* @since 2.0
*/
public static <T> T doWithSingleContext(ContextSource contextSource,
LdapOperationsCallback<T> callback,
boolean useReadOnly,
boolean ignorePartialResultException,
boolean ignoreNameNotFoundException) {
SingleContextSource singleContextSource;
if (useReadOnly) {
singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
} else {
singleContextSource = new SingleContextSource(contextSource.getReadWriteContext());
}
LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);
ldapTemplate.setIgnorePartialResultException(ignorePartialResultException);
ldapTemplate.setIgnoreNameNotFoundException(ignoreNameNotFoundException);
try {
return callback.doWithLdapOperations(ldapTemplate);
} finally {
singleContextSource.destroy();
}
}
示例7
@Before
public void setUp() throws Exception {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.clearSynchronization();
}
contextSourceMock = mock(ContextSource.class);
contextMock = mock(DirContext.class);
transactionDefinitionMock = mock(TransactionDefinition.class);
transactionDataManagerMock = mock(CompensatingTransactionOperationManager.class);
renamingStrategyMock = mock(TempEntryRenamingStrategy.class);
tested = new ContextSourceTransactionManager();
tested.setContextSource(contextSourceMock);
tested.setRenamingStrategy(renamingStrategyMock);
}
示例8
@Test
public void verifyReferences() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-references.xml");
ContextSource outerContextSource = ctx.getBean(ContextSource.class);
AuthenticationSource authenticationSource = ctx.getBean(AuthenticationSource.class);
DirContextAuthenticationStrategy authenticationStrategy = ctx.getBean(DirContextAuthenticationStrategy.class);
Object baseEnv = ctx.getBean("baseEnvProps");
assertThat(outerContextSource).isNotNull();
assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue();
ContextSource contextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
assertThat(authenticationSource).isSameAs(getInternalState(contextSource, "authenticationSource"));
assertThat(authenticationStrategy).isSameAs(getInternalState(contextSource, "authenticationStrategy"));
assertThat(baseEnv).isEqualTo(getInternalState(contextSource, "baseEnv"));
}
示例9
@Test
public void supportsSpel() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-spel.xml");
ContextSource outerContextSource = ctx.getBean(ContextSource.class);
assertThat(outerContextSource).isNotNull();
assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue();
ContextSource contextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
assertThat(LdapUtils.newLdapName("dc=261consulting,dc=com")).isEqualTo(getInternalState(contextSource, "base"));
assertThat("uid=admin").isEqualTo(getInternalState(contextSource, "userDn"));
assertThat("apassword").isEqualTo(getInternalState(contextSource, "password"));
assertThat(new String[]{"ldap://localhost:389"}).isEqualTo((Object[]) getInternalState(contextSource, "urls"));
}
示例10
@Test
public void verifyParseWithDefaultTransactions() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-transactional-defaults.xml");
ContextSource outerContextSource = ctx.getBean(ContextSource.class);
PlatformTransactionManager transactionManager = ctx.getBean(PlatformTransactionManager.class);
assertThat(outerContextSource).isNotNull();
assertThat(transactionManager).isNotNull();
assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue();
ContextSource contextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
assertThat(transactionManager instanceof ContextSourceTransactionManager).isTrue();
Object delegate = getInternalState(transactionManager, "delegate");
assertThat(contextSource).isSameAs(getInternalState(delegate, "contextSource"));
TempEntryRenamingStrategy renamingStrategy =
(TempEntryRenamingStrategy) getInternalState(delegate, "renamingStrategy");
assertThat(renamingStrategy instanceof DefaultTempEntryRenamingStrategy).isTrue();
assertThat("_temp").isEqualTo(getInternalState(renamingStrategy, "tempSuffix"));
}
示例11
@Test
public void verifyParsePoolingSizeSet() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling-configured-poolsize.xml");
ContextSource outerContextSource = ctx.getBean(ContextSource.class);
assertThat(outerContextSource).isNotNull();
ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
assertThat(pooledContextSource).isNotNull();
GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool");
assertThat(objectPool.getMaxActive()).isEqualTo(10);
assertThat(objectPool.getMaxTotal()).isEqualTo(12);
assertThat(objectPool.getMaxIdle()).isEqualTo(11);
assertThat(objectPool.getMaxWait()).isEqualTo(13);
assertThat(objectPool.getMinIdle()).isEqualTo(14);
assertThat(objectPool.getWhenExhaustedAction()).isEqualTo((byte)0);
}
示例12
@Test
public void verifyParsePoolWithPlaceholders() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling-config-with-placeholders.xml");
ContextSource outerContextSource = ctx.getBean(ContextSource.class);
assertThat(outerContextSource).isNotNull();
ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
assertThat(pooledContextSource).isNotNull();
GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool");
assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(10);
assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(20);
assertThat(objectPool.getMaxWait()).isEqualTo(10);
assertThat(objectPool.getMaxTotal()).isEqualTo(11);
assertThat(objectPool.getMaxActive()).isEqualTo(15);
assertThat(objectPool.getMinIdle()).isEqualTo(16);
assertThat(objectPool.getMaxIdle()).isEqualTo(17);
assertThat(objectPool.getNumTestsPerEvictionRun()).isEqualTo(18);
}
示例13
@Test
public void verifyParsePool2WithPlaceholders() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling2-config-with-placeholders.xml");
ContextSource outerContextSource = ctx.getBean(ContextSource.class);
assertThat(outerContextSource).isNotNull();
ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
assertThat(pooledContextSource).isNotNull();
org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool =
(org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool");
assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(10);
assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(20);
assertThat(objectPool.getMaxWaitMillis()).isEqualTo(10);
assertThat(objectPool.getMaxTotal()).isEqualTo(11);
assertThat(objectPool.getMinIdlePerKey()).isEqualTo(12);
assertThat(objectPool.getMaxIdlePerKey()).isEqualTo(13);
assertThat(objectPool.getMaxTotalPerKey()).isEqualTo(14);
assertThat(objectPool.getNumTestsPerEvictionRun()).isEqualTo(18);
}
示例14
@Bean
public ContextSource getLdapContextSrc() {
LdapContextSource ldapContextSrc = new LdapContextSource();
ldapContextSrc.setUrl(ldapUrls);
ldapContextSrc.setUserDn(ldapManagerUserName);
ldapContextSrc.setPassword(ldapManagerPwd);
ldapContextSrc.setBase(ldapBase);
ldapContextSrc.afterPropertiesSet();
return ldapContextSrc;
}
示例15
@Bean
@ConditionalOnMissingBean
public ContextSource ldapContextSource() {
LdapContextSource source = new LdapContextSource();
source.setUserDn(this.properties.getUsername());
source.setPassword(this.properties.getPassword());
source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly());
source.setBase(this.properties.getBase());
source.setUrls(this.properties.determineUrls(this.environment));
source.setBaseEnvironmentProperties(
Collections.unmodifiableMap(this.properties.getBaseEnvironment()));
return source;
}
示例16
@Override
public UserInfo doLookup(String uid) throws Exception {
try {
ContextSource source = (ContextSource)SpringApplicationContextHolder.getBean("unitimeLdapContextSource");
String query = ApplicationProperty.AuthenticationLdapIdentify.value();
String idAttributeName = ApplicationProperty.AuthenticationLdapIdAttribute.value();
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", uid), new String[] {"uid", idAttributeName, "cn", "givenName", "sn", "mail"});
if (user == null || user.getStringAttribute(idAttributeName) == null)
return null;
UserInfo info = new UserInfo();
info.setExternalId(user.getStringAttribute(idAttributeName));
info.setUserName(user.getStringAttribute("uid"));
if (info.getUserName() == null) info.setUserName(uid);
info.setName(user.getStringAttribute("cn"));
info.setFirstName(user.getStringAttribute("givenName"));
info.setLastName(user.getStringAttribute("sn"));
info.setEmail(user.getStringAttribute("mail"));
if (info.getEmail() == null) {
String email = info.getUserName() + "@";
for (String x: user.getNameInNamespace().split(","))
if (x.startsWith("dc=")) email += (email.endsWith("@") ? "" : ".") + x.substring(3);
if (!email.endsWith("@")) info.setEmail(email);
}
return info;
} catch (Exception e) {
sLog.warn("Lookup for " + uid + " failed: " + e.getMessage());
}
return null;
}
示例17
/**
* @param contextSource
* @param groupSearchBase
*/
public AuthoritiesPopulator(ContextSource contextSource, String groupSearchBase, String adminRole, String defaultRole) {
super(contextSource, groupSearchBase);
this.adminRole = adminRole;
this.adminRoleAsAuthority = new SimpleGrantedAuthority(adminRole);
if (defaultRole.contains(Constant.ROLE_MODELER))
this.defaultAuthorities.add(modelerAuthority);
if (defaultRole.contains(Constant.ROLE_ANALYST))
this.defaultAuthorities.add(analystAuthority);
}
示例18
private static ContextSource getContextSource(String url, String username, String password) throws Exception {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(url);
contextSource.setUserDn(username);
contextSource.setPassword(password);
contextSource.setPooled(false);
contextSource.afterPropertiesSet();
return contextSource;
}
示例19
protected ContextSource createInstance() throws Exception {
LdapTestUtils.startEmbeddedServer(port,
defaultPartitionSuffix, defaultPartitionName);
if (contextSource == null) {
// If not explicitly configured, create a new instance.
LdapContextSource targetContextSource = new LdapContextSource();
if (baseOnTarget) {
targetContextSource.setBase(defaultPartitionSuffix);
}
targetContextSource.setUrl("ldap://localhost:" + port);
targetContextSource.setUserDn(principal);
targetContextSource.setPassword(password);
targetContextSource.setDirObjectFactory(dirObjectFactory);
targetContextSource.setPooled(pooled);
if (authenticationSource != null) {
targetContextSource.setAuthenticationSource(authenticationSource);
}
targetContextSource.afterPropertiesSet();
contextSource = targetContextSource;
}
Thread.sleep(1000);
if (baseOnTarget) {
LdapTestUtils.clearSubContexts(contextSource, LdapUtils.emptyLdapName());
}
else {
LdapTestUtils.clearSubContexts(contextSource, LdapUtils.newLdapName(defaultPartitionSuffix));
}
if (ldifFile != null) {
LdapTestUtils.loadLdif(contextSource, ldifFile);
}
return contextSource;
}
示例20
/**
* Clear the directory sub-tree starting with the node represented by the
* supplied distinguished name.
*
* @param contextSource the ContextSource to use for getting a DirContext.
* @param name the distinguished name of the root node.
* @throws NamingException if anything goes wrong removing the sub-tree.
*/
public static void clearSubContexts(ContextSource contextSource, Name name) throws NamingException {
DirContext ctx = null;
try {
ctx = contextSource.getReadWriteContext();
clearSubContexts(ctx, name);
} finally {
try {
ctx.close();
} catch (Exception e) {
// Never mind this
}
}
}
示例21
/**
* Load an Ldif file into an LDAP server.
*
* @param contextSource ContextSource to use for getting a DirContext to
* interact with the LDAP server.
* @param ldifFile a Resource representing a valid LDIF file.
* @throws IOException if the Resource cannot be read.
*/
public static void loadLdif(ContextSource contextSource, Resource ldifFile) throws IOException {
DirContext context = contextSource.getReadWriteContext();
try {
loadLdif(context, ldifFile);
} finally {
try {
context.close();
} catch (Exception e) {
// This is not the exception we are interested in.
}
}
}
示例22
/**
* Close the supplied context, but only if it is not associated with the
* current transaction.
*
* @param context
* the DirContext to close.
* @param contextSource
* the ContextSource bound to the transaction.
* @throws NamingException
*/
void doCloseConnection(DirContext context, ContextSource contextSource)
throws javax.naming.NamingException {
DirContextHolder transactionContextHolder = (DirContextHolder) TransactionSynchronizationManager
.getResource(contextSource);
if (transactionContextHolder == null
|| transactionContextHolder.getCtx() != context) {
log.debug("Closing context");
// This is not the transactional context or the transaction is
// no longer active - we should close it.
context.close();
} else {
log.debug("Leaving transactional context open");
}
}
示例23
private DirContext getTransactionAwareDirContextProxy(DirContext context,
ContextSource target) {
return (DirContext) Proxy
.newProxyInstance(DirContextProxy.class.getClassLoader(),
new Class[] {
LdapUtils
.getActualTargetClass(context),
DirContextProxy.class },
new TransactionAwareDirContextInvocationHandler(
context, target));
}
示例24
/**
* @param contextSource
* the contextSource to set
*/
public void setContextSource(ContextSource contextSource) {
if (contextSource == null) {
throw new IllegalArgumentException("contextSource may not be null");
}
this.contextSource = contextSource;
}
示例25
/**
* @param contextSource
* the contextSource to set
*/
public void setContextSource(ContextSource contextSource) {
if (contextSource == null) {
throw new IllegalArgumentException("contextSource may not be null");
}
this.contextSource = contextSource;
}
示例26
@Before
public void setUp() throws Exception {
contextSourceMock = mock(ContextSource.class);
ldapContextMock = mock(LdapContext.class);
dirContextMock = mock(DirContext.class);
tested = new TransactionAwareContextSourceProxy(contextSourceMock);
}
示例27
@Before
public void setUp() throws Exception {
dirContextMock = mock(DirContext.class);
contextSourceMock = mock(ContextSource.class);
operationManagerMock = mock(CompensatingTransactionOperationManager.class);
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.clearSynchronization();
}
}
示例28
@Before
public void setUp() throws Exception {
dirContextMock = mock(DirContext.class);
contextSourceMock = mock(ContextSource.class);
holder = new DirContextHolder(null, dirContextMock);
tested = new TransactionAwareDirContextInvocationHandler(null, null);
}
示例29
@Test
public void testSetContextSource_Proxy() {
TransactionAwareContextSourceProxy proxy = new TransactionAwareContextSourceProxy(contextSourceMock);
// Perform test
tested.setContextSource(proxy);
ContextSource result = tested.getContextSource();
// Verify result
assertThat(result).isSameAs(contextSourceMock);
}
示例30
@Before
public void setUp() throws Exception {
contextMock = mock(Context.class);
dirContextMock = mock(DirContext.class);
ldapContextMock = mock(LdapContext.class);
keyedObjectPoolMock = mock(KeyedObjectPool.class);
contextSourceMock = mock(ContextSource.class);
dirContextValidatorMock = mock(DirContextValidator.class);
}