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:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

public DummyLDAPServiceImpl() throws Exception {
    File workingDirectory = new File("target/working-server");
    workingDirectory.mkdirs();//from w  ww. j ava  2s  .  co m

    doDelete(workingDirectory);

    // Initialize the LDAP service
    service = new DefaultDirectoryService();
    service.setWorkingDirectory(workingDirectory);

    // first load the schema
    initSchemaPartition();

    // then the system partition
    // this is a MANDATORY partition
    Partition systemPartition = addPartition("system", ServerDNConstants.SYSTEM_DN);
    service.setSystemPartition(systemPartition);

    // Disable the ChangeLog system
    service.getChangeLog().setEnabled(false);

    // Create a new partition
    Partition partition = addPartition("eXoTestPartition", "dc=exoplatform,dc=org");

    // Index some attributes on the partition
    addIndex(partition, "objectClass", "ou", "uid");

    service.setShutdownHookEnabled(false);

    service.startup();

    // Inject the eXo root entry if it does not already exist
    if (!service.getAdminSession().exists(partition.getSuffixDn())) {
        DN dnExo = new DN("dc=exoplatform,dc=org");
        ServerEntry entryExo = service.newEntry(dnExo);
        entryExo.add("objectClass", "top", "domain", "extensibleObject");
        entryExo.add("dc", "exoplatform");
        service.getAdminSession().add(entryExo);
    }

    port = AvailablePortFinder.getNextAvailable(1024);
    server = new LdapServer();
    server.setTransports(new TcpTransport(port));
    server.setDirectoryService(service);
    server.start();

    // server launched and configured

    // configuration of client side
    env.put(DirectoryService.JNDI_KEY, service);
    env.put(Context.PROVIDER_URL, "");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());

    // Add the new schema needed for COR-293
    addNewSchema();
}

From source file:nl.nn.adapterframework.ldap.LdapFindMemberPipe.java

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind,
        boolean recursiveSearch) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {/*from ww  w  .jav a2s . c o  m*/
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}

From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java

public String authenticate(String authorizedName, String cred)
        throws AuthenticationException, FatalErrorException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }/*from   w  w  w .  java2s. c o m*/

    boolean isLdapUser = false;

    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        logger.error("config exception! " + authorizedName, ex);
    }

    try {
        env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory"));
        env.put(Context.SECURITY_AUTHENTICATION,
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple"));

        env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389
        String format = String.format(
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_LDAP_EXPANDED_STR),
                authorizedName);

        env.put(Context.SECURITY_PRINCIPAL, format);
        env.put(Context.SECURITY_CREDENTIALS, cred);
        ctx = new InitialLdapContext(env, null);
        isLdapUser = true;
        logger.info(authorizedName + " is authenticated");

    } catch (ConfigurationException e) {
        logger.error(authorizedName + " is not authenticated", e);
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } catch (NamingException e) {
        logger.error(authorizedName + " is not authenticated");
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Context close failure " + e);
        }
    }

    if (isLdapUser) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, authorizedName);
            if (publisher == null) {
                logger.warn("Publisher was not found, adding the publisher in on the fly.");
                publisher = new Publisher();
                publisher.setAuthorizedName(authorizedName);
                publisher.setIsAdmin("false");
                publisher.setIsEnabled("true");
                publisher.setMaxBindingsPerService(MaxBindingsPerService);
                publisher.setMaxBusinesses(MaxBusinesses);
                publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
                publisher.setMaxTmodels(MaxTmodels);
                publisher.setPublisherName("Unknown");
                em.persist(publisher);
                tx.commit();
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } else {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    return authorizedName;
}

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

/**
 * Can probably be done more elegant too.
 *
 * @param userDN   real dn to the user.//from   w ww  .  j  a va2s . co m
 * @param password the user's password
 * @return
 */
public boolean checkAuthentication(String userDN, String password) {
    if (password.trim().equals(""))
        return false;
    DirContext ctx2 = null;
    try {
        // See if the user authenticates.
        Hashtable env = new Hashtable();
        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, userDN);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put("com.sun.jndi.ldap.connect.timeout", "10000");
        // Specify timeout to be 10 seconds, only on non SSL since SSL connections
        // break with a timeout.
        ctx2 = new InitialDirContext(env);
        log.info("Successfully logged in... " + userDN);
    } catch (Exception e) {
        log.error("Exception during login", e);
        return false;
    }

    finally {
        try {
            ctx2.close();
        } catch (NamingException ignore) {
        }
    }

    return true;
}

From source file:io.pivotal.poc.gemfire.gtx.jndi.SimpleNamingContextBuilder.java

/**
 * Simple InitialContextFactoryBuilder implementation,
 * creating a new SimpleNamingContext instance.
 * @see SimpleNamingContext//www .  ja  va 2  s  .  c o  m
 */
@Override
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) {
    if (activated == null && environment != null) {
        Object icf = environment.get(Context.INITIAL_CONTEXT_FACTORY);
        if (icf != null) {
            Class<?> icfClass;
            if (icf instanceof Class) {
                icfClass = (Class<?>) icf;
            } else if (icf instanceof String) {
                icfClass = ClassUtils.resolveClassName((String) icf, getClass().getClassLoader());
            } else {
                throw new IllegalArgumentException("Invalid value type for environment key ["
                        + Context.INITIAL_CONTEXT_FACTORY + "]: " + icf.getClass().getName());
            }
            if (!InitialContextFactory.class.isAssignableFrom(icfClass)) {
                throw new IllegalArgumentException("Specified class does not implement ["
                        + InitialContextFactory.class.getName() + "]: " + icf);
            }
            try {
                return (InitialContextFactory) icfClass.newInstance();
            } catch (Throwable ex) {
                throw new IllegalStateException("Cannot instantiate specified InitialContextFactory: " + icf,
                        ex);
            }
        }
    }

    // Default case...
    return new InitialContextFactory() {
        @Override
        @SuppressWarnings("unchecked")
        public Context getInitialContext(Hashtable<?, ?> environment) {
            return new SimpleNamingContext("", boundObjects, (Hashtable<String, Object>) environment);
        }
    };
}

From source file:com.joseflavio.iperoxo.IpeRoxo.java

/**
 * Inicia a {@link DataSource} e a {@link EntityManagerFactory}.
 *///from  w  w w .  j a v a2s  .c  om
private static void executarFonteDeDados() throws IOException, NamingException {

    if (Boolean.parseBoolean(getPropriedade("DataSource.Enable"))) {
        log.info(getMensagem(null, "Log.Iniciando.DataSource"));
    } else {
        return;
    }

    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(getPropriedade("DataSource.Driver"));
    dataSource.setUrl(getPropriedade("DataSource.URL"));
    dataSource.setUsername(getPropriedade("DataSource.Username"));
    dataSource.setPassword(getPropriedade("DataSource.Password"));
    dataSource.setInitialSize(Integer.parseInt(getPropriedade("DataSource.InitialSize")));
    dataSource.setMaxTotal(Integer.parseInt(getPropriedade("DataSource.MaxTotal")));
    dataSource.setMinIdle(Integer.parseInt(getPropriedade("DataSource.MinIdle")));
    dataSource.setMaxIdle(Integer.parseInt(getPropriedade("DataSource.MaxIdle")));
    dataSource.setTestOnCreate(Boolean.parseBoolean(getPropriedade("DataSource.TestOnCreate")));
    dataSource.setTestWhileIdle(Boolean.parseBoolean(getPropriedade("DataSource.TestWhileIdle")));
    dataSource.setTestOnBorrow(Boolean.parseBoolean(getPropriedade("DataSource.TestOnBorrow")));
    dataSource.setTestOnReturn(Boolean.parseBoolean(getPropriedade("DataSource.TestOnReturn")));

    Context contexto = new InitialContext();
    try {
        contexto.bind("FONTE", dataSource);
    } finally {
        contexto.close();
    }

    while (true) {
        try (Connection con = getConnection()) {
            break;
        } catch (Exception e) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException f) {
            }
        }
    }

    if (Boolean.parseBoolean(getPropriedade("DataSource.JPA.Enable"))) {
        log.info(getMensagem(null, "Log.Iniciando.JPA"));
    } else {
        return;
    }

    emf = Persistence.createEntityManagerFactory("JPA");

    try {
        emf.createEntityManager().close();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

}

From source file:com.clican.pluto.common.util.JndiUtils.java

/**
 * Look up the object with the specified JNDI name in the JNDI server.
 * //from  w w  w .  j a  va  2  s.  co  m
 * @param jndiName
 *            the JNDI name specified
 * @return the object bound with the name specified, null if this method
 *         fails
 */
public static Object lookupObject(String jndiName) {
    Context ctx = null;
    try {
        Hashtable<String, String> ht = new Hashtable<String, String>();
        // If a special JNDI initial context factory was specified in the
        // constructor, then use it.
        if (jndiInitialContextFactory != null) {
            ht.put(Context.INITIAL_CONTEXT_FACTORY, jndiInitialContextFactory);
        }
        ctx = new InitialContext(ht);
        Object obj = null;
        try {
            obj = ctx.lookup(jndiName);
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.info(
                        "Lookup for an object from Non-Serializable JNDI (relookup from Serializable JNDI) using the JNDI name ["
                                + jndiName + "] : ");
            }
            obj = NonSerializableFactory.lookup(jndiName);
        }

        if (log.isDebugEnabled()) {
            log.debug("JNDI lookup with path [" + jndiName + "] returned object [" + obj + "].");
        }
        return obj;
    } catch (NamingException ex) {
        log.debug("Failed to lookup for an object using the JNDI name [" + jndiName + "] : " + ex);
        return null;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException ne) {
                log.error("Close context error:", ne);
            }
        }
    }
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Creates a DirContext with the applications configuration settings.
 * @return a DirContext/*from  w ww . j  a  v  a 2  s  .co  m*/
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public DirContext createDirContext() throws NamingException {
    final Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.SECURITY_PRINCIPAL, BIND_USERNAME);
    env.put(Context.SECURITY_CREDENTIALS, BIND_PASSWORD);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    if (IS_LDAP_SSLTLS) {
        env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory");
    }
    return new InitialDirContext(env);
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Protected constructor. Creates an initial default context environment and
 * adds support for referrals, a fix for OpenSSL aliases, and enables SSL as
 * default.//  w  w w. ja v a2  s  .  c om
 * @param sessionTicket
 *            The session ticket for this instance, used when logging. May
 *            be <code>null</code> (which is treated as an empty string)
 *            or an empty string.
 * @param timeout
 *            The number of seconds before a connection attempt through this
 *            backend times out.
 * @param ssl
 *            <code>true</code> if SSL is to be used, otherwise
 *            <code>false</code>.
 * @param usernameAttributeName
 *            The name of the attribute holding the username. Cannot be
 *            <code>null</code>.
 * @param guessedAttributeName
 *            If we search but cannot find a user element (for example, if
 *            it is not searchable), we will guess that the (R)DN starts
 *            with the substring
 *            <code><i>guessedAttributeName</i>=<i>usernamePrefix</i></code>,
 *            where <code><i>usernamePrefix</i></code> is the part of the
 *            username preceding the 'at' character. Cannot be
 *            <code>null</code>.
 * @throws IllegalArgumentException
 *             If <code>timeout</code> is less than zero.
 * @throws NullPointerException
 *             If <code>guessedAttributeName</code> or
 *             <code>usernameAttribute</code> is <code>null</code>.
 */
protected JNDIBackend(final String sessionTicket, final int timeout, final boolean ssl,
        final String usernameAttributeName, final String guessedAttributeName)
        throws IllegalArgumentException, NullPointerException {

    // Assignments, with sanity checks.
    if (usernameAttributeName == null)
        throw new NullPointerException("Username attribute name cannot be NULL");
    usernameAttribute = usernameAttributeName;
    if (guessedAttributeName == null)
        throw new NullPointerException("Guessed attribute name cannot be NULL");
    guessedAttribute = guessedAttributeName;
    if (timeout < 0)
        throw new IllegalArgumentException("Timeout must be greater than zero");
    myTimeout = timeout;
    mySessionTicket = sessionTicket;
    if (mySessionTicket == null)
        mySessionTicket = "";

    // Create initial context environment.
    defaultEnv = new Hashtable<String, String>();
    defaultEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    // To catch referrals.
    defaultEnv.put(Context.REFERRAL, "throw");

    // Due to OpenSSL problems.
    defaultEnv.put("java.naming.ldap.derefAliases", "never");

    // Use LDAP v3.
    defaultEnv.put("java.naming.ldap.version", "3");

    // Add timeout value for connection attempts (not searches).
    defaultEnv.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(1000 * timeout));

    // Should we enable SSL?
    if (ssl)
        defaultEnv.put(Context.SECURITY_PROTOCOL, "ssl");

}

From source file:test.integ.be.fedict.performance.TestPKIPerformanceTest.java

@Test
public void testPki() throws Exception {

    LOG.debug("performance test using test PKI");

    // get test PKI information
    if (interactive) {
        testPkiPath = JOptionPane.showInputDialog("Please give the test PKI base URL");
    } else {/*from   ww w .j  a  v  a  2  s.  c o  m*/
        testPkiPath = PKI_PATH;
    }
    testPKI = TestPKI.load(testPkiPath);

    // initialize test framework
    List<PerformanceData> performance = new LinkedList<PerformanceData>();
    List<MemoryData> memory = new LinkedList<MemoryData>();
    PerformanceData currentPerformance = new PerformanceData();
    performance.add(currentPerformance);
    long nextIntervalT = System.currentTimeMillis() + INTERVAL_SIZE;

    // initialize JBoss monitoring for memory usage
    String jnpLocation = "jnp://" + HOST + ":1099";
    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
    environment.put(Context.PROVIDER_URL, jnpLocation);
    rmi = (MBeanServerConnection) new InitialContext(environment).lookup("jmx/invoker/RMIAdaptor");

    if (interactive) {
        new PerformanceWorkingFrame(this);
    }

    // used to generate our certificates
    DateTime notBefore = new DateTime().minusYears(10);
    DateTime notAfter = new DateTime().plusYears(10);
    KeyPair testKeyPair = TestUtils.generateKeyPair();
    List<CAConfiguration> leaves = testPKI.getLeaves();
    Random random = new Random();

    // operate
    this.startTime = new DateTime();
    while (this.run) {

        try {
            List<X509Certificate> certificateChain = getCertificateChain(testKeyPair, leaves, random, notBefore,
                    notAfter);

            // initialize XKMS2 client
            XKMS2Client client = new XKMS2Client(XKMS_LOCATION);
            client.validate("performance", certificateChain);
            currentPerformance.inc();
            this.count++;

        } catch (ValidationFailedException e) {

            if (e.getReasons().get(0).equals(XKMSConstants.KEY_BINDING_REASON_REVOCATION_STATUS_URI)) {
                LOG.debug("revoked");
                currentPerformance.incRevoked();
                this.revokedCount++;
            } else {
                LOG.error("Validation failed: " + e.getReasons().get(0));
                currentPerformance.incFailures();
            }

        } catch (Exception e) {
            LOG.error("error: " + e.getMessage(), e);
            currentPerformance.incFailures();
        } finally {

            if (System.currentTimeMillis() > nextIntervalT) {

                memory.add(new MemoryData(getFreeMemory(), getMaxMemory(), getTotalMemory()));

                currentPerformance = new PerformanceData();
                nextIntervalT = System.currentTimeMillis() + INTERVAL_SIZE;
                performance.add(currentPerformance);
                this.intervalCount++;

                if (!interactive) {
                    DateTime now = new DateTime();
                    if (now.isAfter(startTime.plusMinutes(minutes))) {
                        this.run = false;
                    }
                }

            }
        }
    }

    // add last performance
    performance.add(currentPerformance);

    if (interactive) {
        // show result
        PerformanceResultDialog dialog = new PerformanceResultDialog(
                new PerformanceResultsData(INTERVAL_SIZE, performance, this.expectedRevokedCount, memory));
        while (dialog.isVisible()) {
            Thread.sleep(1000);
        }
    } else {
        // write results to file for later
        PerformanceResultDialog.writeResults(
                new PerformanceResultsData(INTERVAL_SIZE, performance, expectedRevokedCount, memory));
    }
}