Example usage for javax.naming.directory InitialDirContext InitialDirContext

List of usage examples for javax.naming.directory InitialDirContext InitialDirContext

Introduction

In this page you can find the example usage for javax.naming.directory InitialDirContext InitialDirContext.

Prototype

public InitialDirContext(Hashtable<?, ?> environment) throws NamingException 

Source Link

Document

Constructs an initial DirContext using the supplied environment.

Usage

From source file:org.easy.ldap.LdapContextFactory.java

/**
 * @param enviroment//from  w  ww .  j  a v a  2  s .  co  m
 * @return
 * @throws NamingException
 */
public DirContext createContext(Hashtable<String, String> enviroment) throws NamingException {
    if (log.isDebugEnabled()) {
        log.debug("Creating context with enviroment settings of:");
        log.debug(enviroment.toString());
    }

    DirContext ctx = null;
    ctx = new InitialDirContext(enviroment);

    return ctx;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

private static DirContext getAuthContext(String userCN, String password, boolean dedicatedAdminUser)
        throws NamingException {
    ResourceBundle rb = ResourceBundle.getBundle("ldap");
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, rb.getString("url"));
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    if (dedicatedAdminUser) {
        env.put(Context.SECURITY_PRINCIPAL, rb.getString("bindDN"));
        env.put(Context.SECURITY_CREDENTIALS, rb.getString("bindPass"));
    } else {//from  w  ww .j a  va  2  s . c  o  m
        env.put(Context.SECURITY_PRINCIPAL, "cn=" + userCN + "," + rb.getString("peopleRoot"));
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    return new InitialDirContext(env);

}

From source file:org.pentaho.di.trans.steps.mailvalidator.MailValidation.java

private static ArrayList<String> getMX(String hostName) throws NamingException {
    // Perform a DNS lookup for MX records in the domain
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    DirContext ictx = new InitialDirContext(env);
    Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
    Attribute attr = attrs.get("MX");

    // if we don't have an MX record, try the machine itself
    if ((attr == null) || (attr.size() == 0)) {
        attrs = ictx.getAttributes(hostName, new String[] { "A" });
        attr = attrs.get("A");
        if (attr == null) {
            throw new NamingException(BaseMessages.getString(PKG, "MailValidator.NoMatchName", hostName));
        }//  ww w.  j  a v  a 2 s.co  m
    }

    // Huzzah! we have machines to try. Return them as an array list
    // NOTE: We SHOULD take the preference into account to be absolutely
    // correct. This is left as an exercise for anyone who cares.
    ArrayList<String> res = new ArrayList<String>();
    NamingEnumeration<?> en = attr.getAll();

    while (en.hasMore()) {
        String x = (String) en.next();
        String[] f = x.split(" ");
        if (f[1].endsWith(".")) {
            f[1] = f[1].substring(0, (f[1].length() - 1));
        }
        res.add(f[1]);
    }
    return res;
}

From source file:org.nuxeo.ecm.directory.ldap.dns.DNSServiceResolverImpl.java

protected DNSServiceResolverImpl() {
    /*/*from  w w w.j  ava2s  .  co  m*/
     * The expiry of the cache in minutes
     */
    int cacheExpiry = 10;
    try {
        cacheExpiry = Integer.parseInt(Framework.getProperty(DNS_CACHE_EXPIRY, "10"));
    } catch (NumberFormatException e) {
        log.warn("invalid value for property: " + DNS_CACHE_EXPIRY
                + ", falling back to default value of 10 minutes");
    }
    maxDelay = 1000 * 60 * cacheExpiry;

    Properties env = new Properties();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    try {
        context = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

/**
 * @see com.alfaariss.oa.api.idmapper.IIDMapper#map(java.lang.String)
 *//*from w ww  . j av  a 2s . c  om*/
public String map(String id) throws OAException {
    if (id == null)
        throw new IllegalArgumentException("Could not map: NULL");

    String sReturn = null;
    DirContext oDirContext = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment, e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        }

        try {
            if (_sIDAttribute == null) {//must be null, otherwise you can't do the inverse
                Name nameLdap = new LdapName(id);
                if (_sMapperAttribute != null)
                    return getAttributes(oDirContext, _sMapperAttribute, nameLdap);

                _logger.error("Can't map: no mapper attribute name configured");
                throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
            }

            sReturn = searchAttributes(oDirContext, _sIDAttribute, _sMapperAttribute, id);
        } catch (InvalidNameException e) {
            _logger.debug("Supplied id isn't a valid LdapName: " + id);
        }

    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not map id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after mapping id: " + id, e);
            }
        }
    }
    return sReturn;
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

public void init() {
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url + "/" + ldapBaseDN);
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    env.put(Context.SECURITY_PRINCIPAL, ldapLoginDN);
    env.put(Context.SECURITY_CREDENTIALS, ldapPassword);

    try {//www  . j  a  va 2  s.co m
        ctx = new InitialDirContext(env);
        log.info("Successfully created a Context");
    } catch (NamingException e) {
        log.error("Unable to create a Context", e);
    } catch (Exception e) {
        log.error("This should never come", e);
    }
}

From source file:py.una.pol.karaku.util.LDAPUtil.java

private DirContext createInitialDirContext() {

    Map<Object, String> env = new HashMap<Object, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, propertiesUtil.get(LDAP_SERVER_KEY) + "/" + propertiesUtil.get(LDAP_DN_KEY));
    env.put(Context.SECURITY_PRINCIPAL, propertiesUtil.get(LDAP_ADMIN_KEY));
    env.put(Context.SECURITY_CREDENTIALS, propertiesUtil.get(LDAP_ADMIN_PASS_KEY));

    try {//w  w w.  jav a 2s  . c o m
        return new InitialDirContext(new Hashtable<Object, String>(env));

    } catch (NamingException e) {
        throw new KarakuRuntimeException(e.getMessage(), e);
    }

}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapSecurityService.java

void activate(Map<?, ?> configuration) throws NamingException {
    this.url = (String) configuration.get(CONFIG_URL);
    this.baseDN = (String) configuration.get(CONFIG_BASE_DN);
    String managerDN = (String) configuration.get(CONFIG_MANAGER_DN);
    String managerPassword = (String) configuration.get(CONFIG_MANAGER_PASSWORD);

    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, url);

    if (managerDN != null) {
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.SECURITY_PRINCIPAL, managerDN);
        environment.put(Context.SECURITY_CREDENTIALS, managerPassword);
    } else//w  w w . jav  a  2s.c o  m
        environment.put(Context.SECURITY_AUTHENTICATION, "none");

    searchContext = new InitialDirContext(environment);
}

From source file:org.malaguna.cmdit.service.ldap.LDAPBase.java

public DirContext getDirContext() {
    DirContext ctx = null;// w  w w  .  jav  a 2 s  .  c om
    String cadena = "uid=" + user + "," + context;
    Hashtable<String, String> entorno = new Hashtable<String, String>();

    entorno.put(Context.PROVIDER_URL, server);
    entorno.put(Context.SECURITY_PRINCIPAL, cadena);
    entorno.put(Context.SECURITY_CREDENTIALS, password);
    entorno.put(Context.INITIAL_CONTEXT_FACTORY, initContext);

    try {
        ctx = new InitialDirContext(entorno);
    } catch (NamingException e) {
        logger.error(messages.getMessage("err.ldap.attribute", new Object[] { e }, Locale.getDefault()));
    }

    return ctx;
}

From source file:com.clustercontrol.port.protocol.ReachAddressDNS.java

/**
 * DNS????????/*from  w w  w .  ja  v  a  2 s .co m*/
 *
 * @param addressText
 * @return DNS
 */
/*
 * (non-Javadoc)
 *
 * @see
 * com.clustercontrol.port.protocol.ReachAddressProtocol#isRunning(java.
 * lang.String)
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);
        String addressStr = address.getHostAddress();
        if (address instanceof Inet6Address) {
            addressStr = "[" + addressStr + "]";
        }

        bufferOrg.append("Monitoring the DNS Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        props.put(Context.PROVIDER_URL, "dns://" + addressStr + ":" + m_portNo);
        props.put("com.sun.jndi.dns.timeout.initial", String.valueOf(m_timeout));
        props.put("com.sun.jndi.dns.timeout.retries", "1");

        InitialDirContext idctx = null;

        String hostname = HinemosPropertyUtil.getHinemosPropertyStr("monitor.port.protocol.dns", "localhost");
        m_log.debug("The hostname from which to retrieve attributes is " + hostname);

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");

                start = HinemosTime.currentTimeMillis();

                idctx = new InitialDirContext(props);
                Attributes attrs = idctx.getAttributes(hostname);

                end = HinemosTime.currentTimeMillis();

                bufferOrg.append("\n");
                NamingEnumeration<? extends Attribute> allAttr = attrs.getAll();
                while (allAttr.hasMore()) {
                    Attribute attr = allAttr.next();
                    bufferOrg.append("Attribute: " + attr.getID() + "\n");
                    NamingEnumeration<?> values = attr.getAll();
                    while (values.hasMore())
                        bufferOrg.append("Value: " + values.next() + "\n");
                }
                bufferOrg.append("\n");

                m_response = end - start;

                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = result + ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = result + ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = result + ("Response Time < 1ms");
                }

                retry = false;
                isReachable = true;

            } catch (NamingException e) {
                result = (e.getMessage() + "[NamingException]");
                retry = true;
                isReachable = false;
            } catch (Exception e) {
                result = (e.getMessage() + "[Exception]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                try {
                    if (idctx != null) {
                        idctx.close();
                    }
                } catch (NamingException e) {
                    m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(DNS/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}