Java 类javax.naming.directory.InitialDirContext 实例源码
项目:JenkinsHue
文件:LDAPManager.java
public User getUserForLoginName(String login) {
try {
InitialDirContext ctx = createContext();
User user = new User();
SearchResult next = getLDAPInformation(ctx, login.toLowerCase()).nextElement();
user.setLogin(login.toLowerCase());
user.setSurname(next.getAttributes().get("sn").get().toString());
user.setForename(next.getAttributes().get("givenName").get().toString());
user.setEmail(next.getAttributes().get("mail").get().toString().toLowerCase());
ctx.close();
return user;
} catch (Exception e) {
log.info("Login " + login + " nicht gefunden!");
}
return null;
}
项目:open-rmbt
文件:LookupService.java
String getDnsAttributes(String ip) {
try {
Hashtable<String, String> env = new Hashtable<>();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
// TODO don't specify ws1, instead use ns servers for s.maxmind.com
env.put("java.naming.provider.url", "dns://ws1.maxmind.com/");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(licenseKey + "." + ip
+ ".s.maxmind.com", new String[] { "txt" });
// System.out.println(attrs.get("txt").get());
String str = attrs.get("txt").get().toString();
return str;
} catch (NamingException e) {
// TODO fix this to handle exceptions
System.out.println("DNS error");
return null;
}
}
项目:DecompiledMinecraft
文件:ServerAddress.java
/**
* Returns a server's address and port for the specified hostname, looking up the SRV record if possible
*/
private static String[] getServerAddress(String p_78863_0_)
{
try
{
String s = "com.sun.jndi.dns.DnsContextFactory";
Class.forName("com.sun.jndi.dns.DnsContextFactory");
Hashtable hashtable = new Hashtable();
hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
hashtable.put("java.naming.provider.url", "dns:");
hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
DirContext dircontext = new InitialDirContext(hashtable);
Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
String[] astring = attributes.get("srv").get().toString().split(" ", 4);
return new String[] {astring[3], astring[2]};
}
catch (Throwable var6)
{
return new String[] {p_78863_0_, Integer.toString(25565)};
}
}
项目:BaseClient
文件:ServerAddress.java
/**
* Returns a server's address and port for the specified hostname, looking up the SRV record if possible
*/
private static String[] getServerAddress(String p_78863_0_)
{
try
{
String s = "com.sun.jndi.dns.DnsContextFactory";
Class.forName("com.sun.jndi.dns.DnsContextFactory");
Hashtable hashtable = new Hashtable();
hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
hashtable.put("java.naming.provider.url", "dns:");
hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
DirContext dircontext = new InitialDirContext(hashtable);
Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
String[] astring = attributes.get("srv").get().toString().split(" ", 4);
return new String[] {astring[3], astring[2]};
}
catch (Throwable var6)
{
return new String[] {p_78863_0_, Integer.toString(25565)};
}
}
项目:BaseClient
文件:ServerAddress.java
/**
* Returns a server's address and port for the specified hostname, looking up the SRV record if possible
*/
private static String[] getServerAddress(String p_78863_0_)
{
try
{
String s = "com.sun.jndi.dns.DnsContextFactory";
Class.forName("com.sun.jndi.dns.DnsContextFactory");
Hashtable hashtable = new Hashtable();
hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
hashtable.put("java.naming.provider.url", "dns:");
hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
DirContext dircontext = new InitialDirContext(hashtable);
Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
String[] astring = attributes.get("srv").get().toString().split(" ", 4);
return new String[] {astring[3], astring[2]};
}
catch (Throwable var6)
{
return new String[] {p_78863_0_, Integer.toString(25565)};
}
}
项目:unitimes
文件:LdapExternalUidLookup.java
public DirContext getDirContext() throws NamingException {
Hashtable<String,String> env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ctxFactory","com.sun.jndi.ldap.LdapCtxFactory"));
env.put(Context.PROVIDER_URL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider"));
env.put(Context.REFERRAL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.referral","ignore"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")!=null)
env.put("java.naming.ldap.version", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version"));
env.put(Context.SECURITY_AUTHENTICATION, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.security","simple"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")!=null)
env.put("java.naming.ldap.factory.socket",ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore")!=null)
System.setProperty("javax.net.ssl.keyStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore")!=null)
System.setProperty("javax.net.ssl.trustStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
System.setProperty("javax.net.ssl.keyStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStorePassword"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
System.setProperty("javax.net.ssl.trustStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")!=null)
System.setProperty("javax.net.ssl.trustStoreType", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType"));
return new InitialDirContext(env);
}
项目:unitimes
文件:LdapExternalUidTranslation.java
public DirContext getDirContext() throws NamingException {
Hashtable<String,String> env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ctxFactory","com.sun.jndi.ldap.LdapCtxFactory"));
env.put(Context.PROVIDER_URL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider"));
env.put(Context.REFERRAL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.referral","ignore"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")!=null)
env.put("java.naming.ldap.version", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version"));
env.put(Context.SECURITY_AUTHENTICATION, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.security","simple"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")!=null)
env.put("java.naming.ldap.factory.socket",ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore")!=null)
System.setProperty("javax.net.ssl.keyStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore")!=null)
System.setProperty("javax.net.ssl.trustStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
System.setProperty("javax.net.ssl.keyStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStorePassword"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
System.setProperty("javax.net.ssl.trustStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")!=null)
System.setProperty("javax.net.ssl.trustStoreType", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType"));
return new InitialDirContext(env);
}
项目:ChronoBike
文件:LdapUtil.java
public LdapUtil(String csUserId, String csPassword, String csServer)
{
try
{
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://"+csServer+"/");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, csUserId);
env.put(Context.SECURITY_CREDENTIALS, csPassword);
m_ctx = new InitialDirContext(env);
}
catch (NamingException e)
{
e.printStackTrace();
m_ctx = null ;
}
}
项目:parabuild-ci
文件:JNDIAuthenticator.java
/**
* Open (if necessary) and return a connection to the configured
* directory server for this Realm.
*
* @throws NamingException if a directory server error occurs
*/
private DirContext openContext() throws NamingException {
if (log.isDebugEnabled()) {
log.debug("opening context...");
}
final Hashtable environment = makeDirectoryContextEnvironment();
if (log.isDebugEnabled()) {
log.debug("environment: " + environment);
}
//noinspection UnnecessaryLocalVariable
final InitialDirContext initialDirContext = new InitialDirContext(environment);
if (log.isDebugEnabled()) {
log.debug("initialDirContext: " + initialDirContext);
}
return initialDirContext;
}
项目:openjdk-jdk10
文件:NamingManager.java
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new InitialDirContext() {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
项目:Android_Code_Arbiter
文件:JndiLdap.java
static boolean authenticate(String username, String password) {
try {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://ldap.example.com");
props.put(Context.REFERRAL, "ignore");
props.put(Context.SECURITY_PRINCIPAL, dnFromUser(username));
props.put(Context.SECURITY_CREDENTIALS, password);
new InitialDirContext(props);
return true;
} catch (NamingException e) {
return false;
}
}
项目:Android_Code_Arbiter
文件:JndiLdap.java
private static String dnFromUser(String username) throws NamingException {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://ldap.example.com");
props.put(Context.REFERRAL, "ignore");
InitialDirContext context = new InitialDirContext(props);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[]{"givenName", "sn"});
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answers = context.search("dc=People,dc=example,dc=com", "(uid=" + username + ")", ctrls);
SearchResult result = answers.next();
return result.getNameInNamespace();
}
项目:Backmemed
文件:ServerAddress.java
/**
* Returns a server's address and port for the specified hostname, looking up the SRV record if possible
*/
private static String[] getServerAddress(String p_78863_0_)
{
try
{
String s = "com.sun.jndi.dns.DnsContextFactory";
Class.forName("com.sun.jndi.dns.DnsContextFactory");
Hashtable<String, String> hashtable = new Hashtable();
hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
hashtable.put("java.naming.provider.url", "dns:");
hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
DirContext dircontext = new InitialDirContext(hashtable);
Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
String[] astring = attributes.get("srv").get().toString().split(" ", 4);
return new String[] {astring[3], astring[2]};
}
catch (Throwable var6)
{
return new String[] {p_78863_0_, Integer.toString(25565)};
}
}
项目:CustomWorldGen
文件:ServerAddress.java
/**
* Returns a server's address and port for the specified hostname, looking up the SRV record if possible
*/
private static String[] getServerAddress(String p_78863_0_)
{
try
{
String s = "com.sun.jndi.dns.DnsContextFactory";
Class.forName("com.sun.jndi.dns.DnsContextFactory");
Hashtable<String, String> hashtable = new Hashtable();
hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
hashtable.put("java.naming.provider.url", "dns:");
hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
DirContext dircontext = new InitialDirContext(hashtable);
Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
String[] astring = attributes.get("srv").get().toString().split(" ", 4);
return new String[] {astring[3], astring[2]};
}
catch (Throwable var6)
{
return new String[] {p_78863_0_, Integer.toString(25565)};
}
}
项目:openjdk9
文件:NamingManager.java
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new InitialDirContext() {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
项目:jk-util
文件:ADAuthenticator.java
/**
* Checks if is authenticed.
*
* @param host
* the host
* @param port
* the port
* @param userName
* the user name
* @param password
* the password
* @return true, if is authenticed
* @throws NamingException
* the naming exception
*/
public static boolean isAuthenticed(String host, int port, String userName, String password) throws NamingException {
log.info("isAuthenticed");
// Set up the environment for creating the initial context
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, userName + "@" + host);
log.info(env.toString());
env.put(Context.SECURITY_CREDENTIALS, password);
// Create the initial context
DirContext ctx = new InitialDirContext(env);
log.info("DirContext Init Succ");
boolean result = ctx != null;
if (ctx != null) {
log.info("Closing DirContext");
ctx.close();
}
return result;
}
项目:sonar-activedirectory
文件:ApacheDS.java
/**
* This seems to be required for objectClass posixGroup.
*/
private ApacheDS activateNis() throws Exception {
Preconditions.checkState(ldapServer.isStarted());
Attribute disabled = new BasicAttribute("m-disabled", "TRUE");
Attribute disabled2 = new BasicAttribute("m-disabled", "FALSE");
ModificationItem[] mods = new ModificationItem[] {
new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled),
new ModificationItem(DirContext.ADD_ATTRIBUTE, disabled2)
};
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, getUrl());
DirContext ctx = new InitialDirContext(env);
ctx.modifyAttributes("cn=nis,ou=schema", mods);
return this;
}
项目:reladomo
文件:JndiJdbcLdapDataSourceProvider.java
@Override
public DataSource createLdapDataSource(Properties loginProperties, String ldapName) throws NamingException
{
DataSource ds;
// borisv: this code stores all parameters in static baseEnvironment. So if you have multiple connections, next connection will get parameters from previous (unless overwriten by loginParamters).
loginProperties.put(USE_JNDI_JDBC_CONNECTION_POOL_KEY, "false");
if (loginProperties.getProperty(JAVA_NAMING_FACTORY_INITIAL) == null)
{
loginProperties.put(JAVA_NAMING_FACTORY_INITIAL, "com.sun.jndi.ldap.LdapCtxFactory");
}
InitialDirContext context = new JdbcInitialDirContext(loginProperties);
Enumeration propKeys = loginProperties.keys();
while(propKeys.hasMoreElements())
{
Object key = propKeys.nextElement();
context.addToEnvironment((String)key, loginProperties.get(key));
}
ds = (DataSource) context.lookup(ldapName);
return ds;
}
项目:arz-ngs
文件:DirContextPool.java
/**
* Er zeugt einen neuen Connectionpool.
*
* @param factory Die {@link PoolableObjectFactory}, die zum Erzeugen des Pools verwendet werden soll.
* @param uri Die URI, die für die Verbindungen im Pool verwendet soll.
* @param maxActive Die Zahl der maximal aktiven Verbindungen.
* @param maxIdle Die Zahl der maximalen Idle-Verbindungen.
* @param minIdle Die minimale Zahl der Idle-Verbindungen.
* @param whenExhaustedAction -
* @param maxWait -
* @param timeBetweenEvictionRuns -
* @param minEvictableIdleTime -
*/
public DirContextPool( PoolableObjectFactory<InitialDirContext> factory,
String uri,
int maxActive,
int maxIdle,
int minIdle,
byte whenExhaustedAction,
int maxWait,
long timeBetweenEvictionRuns,
long minEvictableIdleTime) {
super(factory);
setMaxActive(maxActive);
setMaxIdle(maxIdle);
setMinIdle(minIdle);
setWhenExhaustedAction(whenExhaustedAction);
setMaxWait(maxWait);
setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns);
setMinEvictableIdleTimeMillis(minEvictableIdleTime);
setTestOnBorrow(false);
setTestOnReturn(true);
setTestWhileIdle(false);
this.uri = uri;
}
项目:alfresco-mt-support
文件:EnhancedLDAPUserRegistry.java
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildUserSearcher(final String query)
{
LOGGER.debug("Building user searcher for query {}", query);
final SearchControls userSearchCtls = new SearchControls();
userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
userSearchCtls.setReturningAttributes(this.userKeys.getFirst());
// MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control
userSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0);
return (ctx) -> {
try
{
final NamingEnumeration<SearchResult> results = ctx.search(this.userSearchBase, query, userSearchCtls);
return results;
}
catch (final NamingException e)
{
throw new AlfrescoRuntimeException("Failed to import people.", e);
}
};
}
项目:alfresco-mt-support
文件:EnhancedLDAPUserRegistry.java
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildGroupSearcher(final String query)
{
LOGGER.debug("Building group searcher for query {}", query);
final SearchControls groupSearchCtls = new SearchControls();
groupSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
groupSearchCtls.setReturningAttributes(this.groupKeys.getFirst());
// MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control
groupSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0);
return (ctx) -> {
try
{
final NamingEnumeration<SearchResult> results = ctx.search(this.groupSearchBase, query, groupSearchCtls);
return results;
}
catch (final NamingException e)
{
throw new AlfrescoRuntimeException("Failed to import groups.", e);
}
};
}
项目:mdw
文件:LdapAdapter.java
/**
* Returns an LDAP connection based on the configured host, port and dn.
*/
@Override
protected Object openConnection() throws ConnectionException {
try {
String ldapHost = getAttributeValueSmart(LDAP_HOST);
String ldapPort = getAttributeValueSmart(LDAP_PORT);
String baseDn = getAttributeValueSmart(BASE_DN);;
String appCuid = getAttributeValueSmart(APP_CUID);
String appPassword = getAttributeValueSmart(APP_PASSWORD);
String ldapUrl = "ldap://" + ldapHost + ":" + ldapPort + "/" + baseDn;
Hashtable<String,String> env = new Hashtable<String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid=" + appCuid + ",ou=people," + baseDn);
env.put(Context.SECURITY_CREDENTIALS, appPassword);
return new InitialDirContext(env);
}
catch (Exception ex) {
throw new ConnectionException(ConnectionException.CONNECTION_DOWN, ex.getMessage(), ex);
}
}
项目:dorset-framework
文件:LdapUserServiceTest.java
@Test(expected = UserException.class)
public void testBadUsername() throws NamingException, UserException {
String userName = "testUsername";
Properties props = new Properties();
props.setProperty("userName", userName);
DirContext ctx = mock(InitialDirContext.class);
String[] userAttributes = mockUserAttributes();
LdapUserService lus = new LdapUserService(ctx, userAttributes);
NamingEnumeration<SearchResult> mockSearchResults = mock(NamingEnumeration.class);
when(ctx.search(any(String.class), any(String.class), any(SearchControls.class)))
.thenReturn(mockSearchResults);
lus.retrieve(props);
}
项目:vespa
文件:IPAddressVerifier.java
protected String reverseLookUp(String ipAddress) throws NamingException {
Hashtable<String, String> env = new Hashtable<>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
String attributeName = ipAddress;
DirContext ctx = new InitialDirContext(env);
Attributes attrs = ctx.getAttributes(attributeName, new String[]{"PTR"});
for (NamingEnumeration<? extends Attribute> ae = attrs.getAll(); ae.hasMoreElements(); ) {
Attribute attr = ae.next();
Enumeration<?> vals = attr.getAll();
if (vals.hasMoreElements()) {
String hostname = vals.nextElement().toString();
ctx.close();
return hostname.substring(0, hostname.length() - 1);
}
}
ctx.close();
return "";
}
项目:hadoop-EAR
文件:DNS.java
/**
* Returns the hostname associated with the specified IP address by the
* provided nameserver.
*
* @param hostIp
* The address to reverse lookup
* @param ns
* The host name of a reachable DNS server
* @return The host name associated with the provided IP
* @throws NamingException
* If a NamingException is encountered
* @deprecated Reliance on DNS is not preferred
*/
@Deprecated
public static String reverseDns(InetAddress hostIp, String ns)
throws NamingException {
//
// Builds the reverse IP lookup form
// This is formed by reversing the IP numbers and appending in-addr.arpa
//
String[] parts = hostIp.getHostAddress().split("\\.");
String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
+ parts[0] + ".in-addr.arpa";
DirContext ictx = new InitialDirContext();
Attributes attribute =
ictx.getAttributes("dns://" // Use "dns:///" if the default
+ ((ns == null) ? "" : ns) +
// nameserver is to be used
"/" + reverseIP, new String[] { "PTR" });
ictx.close();
return attribute.get("PTR").get().toString();
}
项目:keystone4j
文件:CRLVerifier.java
/**
* Downloads a CRL from given LDAP url, e.g.
* ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
*/
private static X509CRL downloadCRLFromLDAP(String ldapURL) throws CertificateException, NamingException, CRLException,
CertificateVerificationException {
Map<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapURL);
DirContext ctx = new InitialDirContext((Hashtable<String, String>) env);
Attributes avals = ctx.getAttributes("");
Attribute aval = avals.get("certificateRevocationList;binary");
byte[] val = (byte[]) aval.get();
if ((val == null) || (val.length == 0)) {
throw new CertificateVerificationException("Can not download CRL from: " + ldapURL);
} else {
InputStream inStream = new ByteArrayInputStream(val);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509CRL) cf.generateCRL(inStream);
}
}
项目:geoip
文件:LookupService.java
String getDnsAttributes(String ip) {
try {
Hashtable<String, String> env = new Hashtable<>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
// TODO don't specify ws1, instead use ns servers for s.maxmind.com
env.put("java.naming.provider.url", "dns://ws1.maxmind.com/");
DirContext context = new InitialDirContext(env);
try {
Attributes attrs = context.getAttributes(licenseKey + "." + ip + ".s.maxmind.com", new String[]{"txt"});
return attrs.get("txt").get().toString();
}
finally {
context.close();
}
}
catch (NamingException e) {
// TODO fix this to handle exceptions
System.out.println("DNS error");
return null;
}
}
项目:FOXopen
文件:LDAP.java
/**
* Create a new instance of an LDAP connection
*
* @param pServerURL URL of the LDAP server: ldap://example.com
* @param pUserDN User to authenticate with
* @param pPassword Password to authenticate with
*/
public LDAP(String pServerURL, String pUserDN, String pPassword)
throws NamingException
{
// Connect to LDAP server
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, pServerURL);
//Auth code
if (pUserDN != null) {
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, pUserDN);
env.put(Context.SECURITY_CREDENTIALS, pPassword);
}
mServerContext = new InitialDirContext(env);
}
项目:spring-boot-etcd
文件:EtcdClientAutoConfiguration.java
private List<String> discoverNodes(String serviceName) throws NamingException {
List<String> locations = new ArrayList<>();
Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
env.put("java.naming.provider.url", "dns:");
DirContext context = new InitialDirContext(env);
Attributes attributes = context.getAttributes(serviceName, new String[] { "SRV" });
for (NamingEnumeration<? extends Attribute> records = attributes.getAll(); records.hasMore();) {
Attribute record = records.next();
NamingEnumeration<String> values = (NamingEnumeration<String>) record.getAll();
while (values.hasMore()) {
String dns = values.next();
String[] split = dns.split(" ");
String host = split[3];
if (host.endsWith(".")) {
host = host.substring(0, host.length() - 1);
}
String location = "http://" + host + ":2379";
locations.add(location);
}
}
return locations;
}
项目:Lizard
文件:LookupService.java
String getDnsAttributes(String ip) {
try {
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
// TODO don't specify ws1, instead use ns servers for s.maxmind.com
env.put("java.naming.provider.url","dns://ws1.maxmind.com/");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(licenseKey + "." + ip + ".s.maxmind.com", new String[] {"txt"});
//System.out.println(attrs.get("txt").get());
String str = attrs.get("txt").get().toString();
return str;
}
catch(NamingException e) {
// TODO fix this to handle exceptions
System.out.println("DNS error");
return null;
}
}
项目:AvunaHTTPD-Java
文件:EmailRouter.java
private static String[] lookupMailHosts(String domainName) throws NamingException {
InitialDirContext iDirC = new InitialDirContext();
Attributes attributes = iDirC.getAttributes("dns:/" + domainName, new String[] { "MX" });
Attribute attributeMX = attributes.get("MX");
if (attributeMX == null) {
return (new String[] { domainName });
}
String[][] pvhn = new String[attributeMX.size()][2];
for (int i = 0; i < attributeMX.size(); i++) {
pvhn[i] = ("" + attributeMX.get(i)).split("\\s+");
}
Arrays.sort(pvhn, new Comparator<String[]>() {
public int compare(String[] o1, String[] o2) {
return (Integer.parseInt(o1[0]) - Integer.parseInt(o2[0]));
}
});
String[] sortedHostNames = new String[pvhn.length];
for (int i = 0; i < pvhn.length; i++) {
sortedHostNames[i] = pvhn[i][1].endsWith(".") ? pvhn[i][1].substring(0, pvhn[i][1].length() - 1) : pvhn[i][1];
}
return sortedHostNames;
}
项目:openshift-ping
文件:GetServicePort.java
private Set<DnsRecord> getDnsRecords(String serviceName) throws Exception {
Set<DnsRecord> dnsRecords = new TreeSet<DnsRecord>();
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
env.put(Context.PROVIDER_URL, "dns:");
env.put("com.sun.jndi.dns.recursion", "false");
// default is one second, but os skydns can be slow
env.put("com.sun.jndi.dns.timeout.initial", "2000");
// retries handled by DnsPing
//env.put("com.sun.jndi.dns.timeout.retries", "4");
DirContext ctx = new InitialDirContext(env);
Attributes attrs = ctx.getAttributes("_tcp." + serviceName, new String[]{"SRV"});
if (attrs == null) {
return dnsRecords;
}
NamingEnumeration<?> servers = attrs.get("SRV").getAll();
while (servers.hasMore()) {
DnsRecord record = DnsRecord.fromString((String)servers.next());
dnsRecords.add(record);
}
return dnsRecords;
}
项目:tempto
文件:DefaultLdapObjectEntryManager.java
private DirContext createContext(String ldapUrl, String ldapAdminDistinguishedName, String ldapAdminPassword)
{
Hashtable<String, String> environment = new Hashtable<>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, ldapUrl);
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, ldapAdminDistinguishedName);
environment.put(Context.SECURITY_CREDENTIALS, ldapAdminPassword);
try {
return new InitialDirContext(environment);
}
catch (NamingException e) {
throw new RuntimeException("Connection to LDAP server failed", e);
}
}
项目:report-cockpit-birt-web
文件:LdapServerTest.java
@Test
public void testJndiSun() throws NamingException {
Hashtable<String, String> contextParams = new Hashtable<>();
contextParams.put(Context.PROVIDER_URL, "ldap://ldap.xxx:389");
contextParams.put(Context.SECURITY_PRINCIPAL, USER_LDAP);
contextParams.put(Context.SECURITY_CREDENTIALS, PASSWORD_LDAP);
contextParams.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
DirContext dirContext = new InitialDirContext(contextParams);
Attributes attributes = dirContext.getAttributes("",
new String[] { "namingContexts" });
Attribute attribute = attributes.get("namingContexts");
NamingEnumeration<?> all = attribute.getAll();
while (all.hasMore()) {
String next = (String) all.next();
logger.info(next);
}
}
项目:msf4j
文件:LDAPUserStoreManager.java
private DirContext getInitialContext(String hostname, int port,
String username, String password)
throws NamingException {
String providerURL = "ldap://" + hostname + ":" + port;
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, providerURL);
if ((username != null) && (!username.equals(""))) {
props.put(Context.SECURITY_AUTHENTICATION, "simple");
props.put(Context.SECURITY_PRINCIPAL, username);
props.put(Context.SECURITY_CREDENTIALS, (password == null) ? "" : password);
}
return new InitialDirContext(props);
}
项目:daq-eclipse
文件:LDAPLoginModule.java
protected DirContext open() throws NamingException {
try {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, getLDAPPropertyValue(INITIAL_CONTEXT_FACTORY));
if (isLoginPropertySet(CONNECTION_USERNAME)) {
env.put(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
}
if (isLoginPropertySet(CONNECTION_PASSWORD)) {
env.put(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
}
env.put(Context.SECURITY_PROTOCOL, getLDAPPropertyValue(CONNECTION_PROTOCOL));
env.put(Context.PROVIDER_URL, getLDAPPropertyValue(CONNECTION_URL));
env.put(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(AUTHENTICATION));
context = new InitialDirContext(env);
} catch (NamingException e) {
log.error(e.toString());
throw e;
}
return context;
}
项目:gerrit
文件:Helper.java
private DirContext kerberosOpen(Properties env) throws LoginException, NamingException {
LoginContext ctx = new LoginContext("KerberosLogin");
ctx.login();
Subject subject = ctx.getSubject();
try {
return Subject.doAs(
subject,
new PrivilegedExceptionAction<DirContext>() {
@Override
public DirContext run() throws NamingException {
return new InitialDirContext(env);
}
});
} catch (PrivilegedActionException e) {
Throwables.throwIfInstanceOf(e.getException(), NamingException.class);
Throwables.throwIfInstanceOf(e.getException(), RuntimeException.class);
LdapRealm.log.warn("Internal error", e.getException());
return null;
} finally {
ctx.logout();
}
}
项目:dorset-framework
文件:LdapUserServiceTest.java
@Test(expected = UserException.class)
public void testBadUsername() throws NamingException, UserException {
String userName = "testUsername";
Properties props = new Properties();
props.setProperty("userName", userName);
DirContext ctx = mock(InitialDirContext.class);
String[] userAttributes = mockUserAttributes();
LdapUserService lus = new LdapUserService(ctx, userAttributes);
NamingEnumeration<SearchResult> mockSearchResults = mock(NamingEnumeration.class);
when(ctx.search(any(String.class), any(String.class), any(SearchControls.class)))
.thenReturn(mockSearchResults);
lus.retrieve(props);
}
项目:unitime
文件:LdapExternalUidLookup.java
public DirContext getDirContext() throws NamingException {
Hashtable<String,String> env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ctxFactory","com.sun.jndi.ldap.LdapCtxFactory"));
env.put(Context.PROVIDER_URL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider"));
env.put(Context.REFERRAL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.referral","ignore"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")!=null)
env.put("java.naming.ldap.version", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version"));
env.put(Context.SECURITY_AUTHENTICATION, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.security","simple"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")!=null)
env.put("java.naming.ldap.factory.socket",ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore")!=null)
System.setProperty("javax.net.ssl.keyStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore")!=null)
System.setProperty("javax.net.ssl.trustStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
System.setProperty("javax.net.ssl.keyStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStorePassword"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
System.setProperty("javax.net.ssl.trustStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword"));
if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")!=null)
System.setProperty("javax.net.ssl.trustStoreType", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType"));
return new InitialDirContext(env);
}