Example usage for javax.naming Context INITIAL_CONTEXT_FACTORY

List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY

Introduction

In this page you can find the example usage for javax.naming Context INITIAL_CONTEXT_FACTORY.

Prototype

String INITIAL_CONTEXT_FACTORY

To view the source code for javax.naming Context INITIAL_CONTEXT_FACTORY.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the initial context factory to use.

Usage

From source file:pl.umk.mat.zawodyweb.ldap.LdapConnector.java

/**
 * Check user password and return that user
 *
 * Example of LDAP data:/*from w  w w.  jav a  2  s .  c o  m*/
 * <pre>
 * dn: uid=faramir,ou=People,ou=int,dc=mat,dc=uni,dc=torun,dc=pl
 * objectClass: top
 * objectClass: account
 * objectClass: posixAccount
 * objectClass: shadowAccount
 * objectClass: radiusprofile
 * objectClass: sambaSamAccount
 * dialupAccess: yes
 * uid: faramir
 * cn: Marek Nowicki
 * loginShell: /bin/tcsh
 * uidNumber: 30030
 * sambaSID: S-1-30030
 * gecos: Marek Nowicki, doktorant Info.
 * gidNumber: 160
 * homeDirectory: /studdok/faramir
 * radiusSimultaneousUse: 1</pre>
 * @param login login
 * @param pass user password
 * @return Users if user found and password is OK or null if anything failed
 */
public static Users retieveUser(String login, String pass) {
    if (pass == null || pass.isEmpty() || login == null || login.isEmpty() || login.contains(",")) {
        return null;
    }

    Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
    String dn = String.format("uid=%s,%s", login, baseDN);

    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, ldapURL);
    ldapEnv.put(Context.SECURITY_PRINCIPAL, dn);
    ldapEnv.put(Context.SECURITY_CREDENTIALS, pass);

    try {
        DirContext authContext = new InitialDirContext(ldapEnv);
        Attributes userAttributes = authContext.getAttributes(dn);

        if (userAttributes.get("uidNumber") == null) {
            return null;
        }

        Attribute cn = userAttributes.get("cn"); // commonName - eg. Marek Nowicki

        String name = ((String) cn.get());
        String firstName = name;
        String lastName = "(LDAP)";

        int index = name.lastIndexOf(" ");
        if (index > 0) {
            firstName = name.substring(0, index).trim();
            lastName = name.substring(index + 1).trim();
        }

        Users user = new Users();

        user.setLogin(login);
        user.setFirstname(firstName);
        user.setLastname(lastName);
        user.setEmail(login + emailSuffix);

        return user;
    } catch (AuthenticationException ex) {
    } catch (NamingException ex) {
    } catch (NullPointerException ex) {
    } catch (ClassCastException ex) {
    } catch (Exception ex) {
        log.fatal("LDAP Exception:", ex);
    }
    return null;
}

From source file:org.zanata.util.CleanDocumentStorageRule.java

public static String getDocumentStoragePath() {
    if (storagePath == null) {
        final Properties env = new Properties();

        // env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                org.jboss.naming.remote.client.InitialContextFactory.class.getName());
        long portOffset = Integer.parseInt(PropertiesHolder.getProperty("cargo.port.offset", "0"));
        String rmiPort = System.getenv("JBOSS_REMOTING_PORT");
        int rmiPortNum = rmiPort != null ? parseInt(rmiPort) : 4547;
        long realRmiPort = portOffset + rmiPortNum;
        String remoteUrl = "remote://localhost:" + realRmiPort;
        env.put(Context.PROVIDER_URL, remoteUrl);
        InitialContext remoteContext = null;
        try {/*w w w. j a  va  2 s . c o  m*/
            remoteContext = new InitialContext(env);
            storagePath = (String) remoteContext.lookup("zanata/files/document-storage-directory");
        } catch (NamingException e) {
            // wildfly uses 'http-remoting:' not 'remote:'
            String httpPort = System.getenv("JBOSS_HTTP_PORT");
            int httpPortNum = httpPort != null ? parseInt(httpPort) : 8180;
            long realHttpPort = httpPortNum + portOffset;
            String httpRemotingUrl = "http-remoting://localhost:" + realHttpPort;
            log.warn("Unable to access {}: {}; trying {}", remoteUrl, e.toString(), httpRemotingUrl);
            try {
                env.put(Context.PROVIDER_URL, httpRemotingUrl);
                remoteContext = new InitialContext(env);
                storagePath = (String) remoteContext.lookup("zanata/files/document-storage-directory");
            } catch (NamingException e1) {
                // fall back option:
                log.warn("Unable to access {}: {}", httpRemotingUrl, e.toString());
                URL testClassRoot = Thread.currentThread().getContextClassLoader()
                        .getResource("setup.properties");
                File targetDir = new File(testClassRoot.getPath()).getParentFile();
                storagePath = new File(targetDir, "zanata-documents").getAbsolutePath();
            }
        }
    }
    return storagePath;
}

From source file:org.wso2.carbon.metrics.jdbc.core.BaseReporterTest.java

@BeforeSuite
protected static void init() throws Exception {
    if (logger.isInfoEnabled()) {
        logger.info("Initializing the data source and populating data");
    }//  w w  w.jav  a 2s. c om
    // Setup datasource
    dataSource = JdbcConnectionPool.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "");
    template = new JdbcTemplate(dataSource);
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(new ClassPathResource("dbscripts/h2.sql"));
    populator.populate(dataSource.getConnection());

    // Create initial context
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
    InitialContext ic = new InitialContext();
    ic.createSubcontext("jdbc");
    ic.bind("jdbc/WSO2MetricsDB", dataSource);

    if (logger.isInfoEnabled()) {
        logger.info("Creating Metrics");
    }
    metrics = new Metrics(TestUtils.getConfigProvider("metrics.yaml"));
    metrics.activate();
    metricService = metrics.getMetricService();
    metricManagementService = metrics.getMetricManagementService();
}

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

private static DirContext getContext() 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_PRINCIPAL, rb.getString("rootDN"));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    return new InitialDirContext(env);
}

From source file:org.wso2.carbon.connector.ldap.LDAPUtils.java

protected static DirContext getDirectoryContext(MessageContext messageContext) throws NamingException {
    String providerUrl = LDAPUtils.lookupContextParams(messageContext, LDAPConstants.PROVIDER_URL);
    String securityPrincipal = LDAPUtils.lookupContextParams(messageContext, LDAPConstants.SECURITY_PRINCIPAL);
    String securityCredentials = LDAPUtils.lookupContextParams(messageContext,
            LDAPConstants.SECURITY_CREDENTIALS);
    boolean secureConnection = Boolean
            .valueOf(LDAPUtils.lookupContextParams(messageContext, LDAPConstants.SECURE_CONNECTION));
    boolean disableSSLCertificateChecking = Boolean
            .valueOf(LDAPUtils.lookupContextParams(messageContext, LDAPConstants.DISABLE_SSL_CERT_CHECKING));

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, LDAPConstants.COM_SUN_JNDI_LDAP_LDAPCTXFACTORY);
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
    if (secureConnection) {
        env.put(Context.SECURITY_PROTOCOL, LDAPConstants.SSL);
    }/* w ww  .j  a va  2  s  . c  o  m*/
    if (disableSSLCertificateChecking) {
        env.put(LDAPConstants.JAVA_NAMING_LDAP_FACTORY_SOCKET,
                LDAPConstants.ORG_WSO2_CARBON_CONNECTOR_SECURITY_MYSSLSOCKETFACTORY);
    }

    DirContext ctx = null;
    ctx = new InitialDirContext(env);
    return ctx;
}

From source file:org.apache.jackrabbit.ocm.spring.RepositoryUtil.java

/**
 * Register a new repository/*  w ww .j  ava 2 s  . c om*/
 *
 * @param repositoryName The repository unique name
 * @param configFile The JCR config file
 * @param homeDir The directory containing the complete repository settings (workspace, node types, ...)
 *
 * @throws RepositoryException when it is not possible to register the repository
 */
public static void registerRepository(String repositoryName, String configFile, String homeDir)
        throws RepositoryException {
    try {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory");
        env.put(Context.PROVIDER_URL, "localhost");
        InitialContext ctx = new InitialContext(env);

        RegistryHelper.registerRepository(ctx, repositoryName, configFile, homeDir, true);
    } catch (Exception e) {
        throw new RepositoryException(
                "Impossible to register the respository : " + repositoryName + " - config file : " + configFile,
                e);
    }

}

From source file:org.pepstock.jem.junit.test.springbatch.java.RestToBeExecuted.java

/**
 * //  w ww.  j a  va  2 s.  c om
 */
@ToBeExecuted
public void exec() {

    try {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "org.pepstock.jem.node.tasks.jndi.JemContextFactory");

        InitialContext context = new InitialContext(env);
        RestClient rest = (RestClient) context.lookup("JUNIT-REST-RESOURCE");
        System.err.println();
        System.err.println("*** REST XML");
        get(rest, MediaType.APPLICATION_XML);
        get(rest, MediaType.APPLICATION_JSON);
        get(rest, MediaType.APPLICATION_XML);
        get(rest, MediaType.APPLICATION_JSON);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    try {
        System.err.println();
        System.err.println("*** REST XML");
        get(restC, MediaType.APPLICATION_XML);
        get(restC, MediaType.APPLICATION_JSON);
        get(restC, MediaType.APPLICATION_XML);
        get(restC, MediaType.APPLICATION_JSON);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:jms.queue.TestQueueSender.java

public void init(PublisherConfig conf) throws NamingException, JMSException {
    String queueName = conf.getQueueName();
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, conf.getInitialContextFactory());
    properties.put(conf.getConnectionFactoryPrefix() + "." + conf.getConnectionFactoryName(),
            conf.getTCPConnectionURL());
    properties.put("queue." + queueName, queueName);
    InitialContext ctx = new InitialContext(properties);
    // Lookup connection factory
    QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(conf.getConnectionFactoryName());
    queueConnection = connFactory.createQueueConnection();
    queueConnection.start();//www . java2s.  c  om
    if (conf.isTransactional()) {
        queueSession = queueConnection.createQueueSession(true, 0);
    } else {
        queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    }
    //        Queue queue = (Queue)ctx.lookup(queueName);
    Queue queue = queueSession.createQueue(queueName);
    queueSender = queueSession.createSender(queue);
    config = conf;

}

From source file:org.apache.jmeter.protocol.jms.client.InitialContextFactory.java

/**
 * Look up the context from the local cache, creating it if necessary.
 * //from  ww  w  .  ja v  a  2  s.c  o m
 * @param initialContextFactory used to set the property {@link Context#INITIAL_CONTEXT_FACTORY}
 * @param providerUrl used to set the property {@link Context#PROVIDER_URL}
 * @param useAuth set <code>true</code> if security is to be used.
 * @param securityPrincipal used to set the property {@link Context#SECURITY_PRINCIPAL}
 * @param securityCredentials used to set the property {@link Context#SECURITY_CREDENTIALS}
 * @return the context, never <code>null</code>
 * @throws NamingException when creation of the context fails
 */
public static Context lookupContext(String initialContextFactory, String providerUrl, boolean useAuth,
        String securityPrincipal, String securityCredentials) throws NamingException {
    String cacheKey = createKey(Thread.currentThread().getId(), initialContextFactory, providerUrl,
            securityPrincipal, securityCredentials);
    Context ctx = MAP.get(cacheKey);
    if (ctx == null) {
        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        props.setProperty(Context.PROVIDER_URL, providerUrl);
        if (useAuth && securityPrincipal != null && securityCredentials != null
                && securityPrincipal.length() > 0 && securityCredentials.length() > 0) {
            props.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);
            props.setProperty(Context.SECURITY_CREDENTIALS, securityCredentials);
            log.info("authentication properties set");
        }
        try {
            ctx = new InitialContext(props);
        } catch (NoClassDefFoundError | Exception e) {
            throw new NamingException(e.toString());
        }
        // we want to return the context that is actually in the map
        // if it's the first put we will have a null result
        Context oldCtx = MAP.putIfAbsent(cacheKey, ctx);
        if (oldCtx != null) {
            // There was an object in map, destroy the temporary and return one in map (oldCtx)
            try {
                ctx.close();
            } catch (Exception e) {
                // NOOP
            }
            ctx = oldCtx;
        }
        // else No object in Map, ctx is the one
    }
    return ctx;
}

From source file:org.wso2.carbon.connector.integration.test.ejb2.Ejb2ConnectorIntegrationTest.java

/**
 * Set up the environment./*from  w  w w .j av  a 2 s. c  o  m*/
 */
@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
    init("ejb2-connector-1.0.1-SNAPSHOT");
    esbRequestHeadersMap.put("Accept-Charset", "UTF-8");
    esbRequestHeadersMap.put("Content-Type", "application/json");
    esbRequestHeadersMap.put("Accept", "application/json");
    p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
    p.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
    p.put(Context.PROVIDER_URL, "localhost");
    ctx = new InitialContext(p);
}