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:com.photon.phresco.ldap.impl.LDAPManagerImpl.java

@Override
public User authenticate(Credentials credentials) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method LDAPManagerImpl.authenticate(Credentials credentials)");
    }/*from  www .  ja v  a 2  s  . c  o  m*/
    String userName = credentials.getUsername();
    String passwordEncoded = credentials.getPassword();
    byte[] decodedBytes = Base64.decodeBase64(passwordEncoded);
    String password = new String(decodedBytes);
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfig.getLdapContextFactory());
    env.put(Context.PROVIDER_URL, ldapConfig.getLdapUrl());
    env.put(Context.SECURITY_PRINCIPAL, getUserPrincipal(userName));
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext dc = null;
    try {
        dc = new InitialDirContext(env);
        if (isDebugEnabled) {
            S_LOGGER.debug("authenticate() Login Success for " + userName);
        }
        return getUser(credentials, dc);
    } catch (Exception e) {
        e.printStackTrace();
        if (isDebugEnabled) {
            S_LOGGER.debug("authenticate() Login Failed for " + userName);
        }
        return new User();
    } finally {
        try {
            if (dc != null) {
                dc.close();
            }
        } catch (NamingException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:de.micromata.genome.util.runtime.jndi.JndiDumper.java

public static void register() {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
            "de.micromata.genome.util.runtime.jndi.SimpleNamingContextFactory");
    //    env.put(Context.INITIAL_CONTEXT_FACTORY,
    //        "com.sun.jndi.rmi.registry.RegistryContextFactory");
}

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

public DirContext getDirContext() {
    DirContext ctx = null;/*from w w w  .  j a  v a 2  s  . c  o m*/
    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:hsa.awp.common.naming.TestLdapDirectoryAdapter.java

/**
 * Adds expectations for context configuration to the adapter.
 *
 * @throws Exception if something went wrong.
 *///from   ww  w .j av a2 s .co  m
private void mockExpectConfiguration() throws Exception {

    mockery.checking(new Expectations() {
        {
            oneOf(directoryContext).addToEnvironment(Context.INITIAL_CONTEXT_FACTORY,
                    "com.sun.jndi.ldap.LdapCtxFactory");

            oneOf(directoryContext).addToEnvironment(Context.PROVIDER_URL,
                    ldapConfig.getProperty("naming.providerURL"));

            oneOf(directoryContext).addToEnvironment(Context.SECURITY_PRINCIPAL,
                    ldapConfig.getProperty("naming.securityPrincipal"));

            oneOf(directoryContext).addToEnvironment(Context.SECURITY_CREDENTIALS,
                    ldapConfig.getProperty("naming.securityCredentials"));

            oneOf(directoryContext).addToEnvironment(Context.SECURITY_PROTOCOL,
                    ldapConfig.getProperty("naming.securityProtocol"));

            oneOf(directoryContext).addToEnvironment(Context.SECURITY_AUTHENTICATION,
                    ldapConfig.getProperty("naming.securityAuthentication"));
        }
    });
}

From source file:com.dianping.cat.system.page.login.service.SessionManager.java

public SessionManager() {
    super();//from  ww  w.  jav a 2 s  . c o m
    AuthType type = AuthType.valueOf(CatPropertyProvider.INST.getProperty("CAT_AUTH_TYPE", "ADMIN_PWD"));
    switch (type) {
    case NOP:
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();
                return new Token(account, account);
            }
        };
        break;
    case LDAP:
        final String ldapUrl = CatPropertyProvider.INST.getProperty("CAT_LDAP_URL", null);
        if (StringUtils.isBlank(ldapUrl)) {
            throw new IllegalArgumentException("required CAT_LDAP_URL");
        }
        final String userDnTpl = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DN_TPL", null);
        if (StringUtils.isBlank(userDnTpl)) {
            throw new IllegalArgumentException("required CAT_LDAP_USER_DN_TPL");
        }
        final String userDisplayAttr = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DISPLAY_ATTR", null);
        final Pattern pattern = Pattern.compile("\\{0}");
        final Matcher userDnTplMatcher = pattern.matcher(userDnTpl);
        final String[] attrs = userDisplayAttr == null ? null : new String[] { userDisplayAttr };
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                final String account = credential.getAccount();
                final String pwd = credential.getPassword();
                if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
                    return null;
                }
                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);// LDAP server
                String userDn = userDnTplMatcher.replaceAll(account);
                env.put(Context.SECURITY_PRINCIPAL, pwd);
                env.put(Context.SECURITY_CREDENTIALS, pwd);
                try {
                    InitialLdapContext context = new InitialLdapContext(env, null);
                    final String baseDn = context.getNameInNamespace();
                    if (userDn.endsWith(baseDn)) {
                        userDn = userDn.substring(0, userDn.length() - baseDn.length() - 1);
                    }
                    String displayName = null;
                    if (attrs != null) {
                        final Attributes attributes = context.getAttributes(userDn, attrs);
                        if (attributes.size() > 0) {
                            displayName = attributes.getAll().next().get().toString();
                        }
                    }

                    return new Token(account, displayName == null ? account : displayName);
                } catch (Exception e) {
                    Cat.logError(e);
                    return null;
                }
            }

        };
        break;
    case ADMIN_PWD:
        final String p = CatPropertyProvider.INST.getProperty("CAT_ADMIN_PWD", "admin");

        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();

                if ("admin".equals(account) && p.equals(credential.getPassword())) {
                    return new Token(account, account);
                }
                return null;
            }

        };
        break;
    }
}

From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageSender.java

public QueueMessageSender(String connectionString, String hostName, String port, String userName,
        String password, String queueName, AtomicInteger messageCounter, int numOfMessagesToSend,
        int delayBetweenMessages, String filePath, int printNumberOfMessagesPer, boolean isToPrintEachMessage,
        Long jmsExpiration) {//w  ww.  j a v a 2 s .  c o  m

    this.hostName = hostName;
    this.port = port;
    this.connectionString = connectionString;
    this.messageCounter = messageCounter;
    this.queueName = queueName;
    this.numOfMessagesToSend = numOfMessagesToSend;
    this.delay = delayBetweenMessages;
    this.filePath = filePath;
    if (filePath != null && !filePath.equals("")) {
        readFromFile = true;
    }
    this.printNumberOfMessagesPer = printNumberOfMessagesPer;
    this.isToPrintEachMessage = isToPrintEachMessage;
    this.jmsExpiration = jmsExpiration;

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
    properties.put("queue." + queueName, queueName);

    log.info("getTCPConnectionURL(userName,password) = " + getTCPConnectionURL(userName, password));

    try {
        InitialContext ctx = new InitialContext(properties);
        // Lookup connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        queueConnection.start();
        queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        // Send message
        Queue queue = (Queue) ctx.lookup(queueName);
        queueSender = queueSession.createSender(queue);

    } catch (NamingException e) {
        log.error("Error while looking up for queue", e);
    } catch (JMSException e) {
        log.error("Error while initializing queue connection", e);
    }

}

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

/**
 * Get a repository/*w  w  w. java2  s. c o m*/
 *
 * @param repositoryName The repository name
 * @return a JCR repository reference
 *
 * @throws RepositoryException when it is not possible to get the repository.
 *         Before calling this method, the repository has to be registered (@see RepositoryUtil#registerRepository(String, String, String)
 */
public static Repository getRepository(String repositoryName) 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);

        Repository repository = (Repository) ctx.lookup(repositoryName);
        return repository;
    } catch (Exception e) {
        throw new RepositoryException("Impossible to get the repository : " + repositoryName, e);
    }
}

From source file:org.wso2.mb.integration.common.clients.operations.topic.TopicMessagePublisher.java

public TopicMessagePublisher(String connectionString, String hostName, String port, String userName,
        String password, String topicName, AtomicInteger messageCounter, int numOfMessagesToSend,
        int delayBetweenMessages, String filePath, int printNumberOfMessagesPer, boolean isToPrintEachMessage,
        long jmsExpiration) {

    this.hostName = hostName;
    this.port = port;
    this.connectionString = connectionString;
    this.messageCounter = messageCounter;
    this.topicName = topicName;
    this.numOfMessagesToSend = numOfMessagesToSend;
    this.delay = delayBetweenMessages;
    this.filePath = filePath;
    if (filePath != null && !filePath.equals("")) {
        readFromFile = true;/*from w  w  w . j  a  v  a  2s  .co m*/
    }
    this.printNumberOfMessagesPer = printNumberOfMessagesPer;
    this.isToPrintEachMessage = isToPrintEachMessage;

    this.jmsExpiration = jmsExpiration;

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
    properties.put("topic." + topicName, topicName);

    try {
        InitialContext ctx = new InitialContext(properties);
        // Lookup connection factory
        TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx.lookup(CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(true, TopicSession.SESSION_TRANSACTED);

        // Send message
        Topic topic = (Topic) ctx.lookup(topicName);
        topicPublisher = topicSession.createPublisher(topic);

    } catch (NamingException e) {
        log.error("Error while looking up for topic", e);
    } catch (JMSException e) {
        log.error("Error while initializing topic connection", e);
    }

}

From source file:com.heliumv.factory.BaseCall.java

private Context getInitialContext() throws NamingException {
    Context env = (Context) new InitialContext().lookup("java:comp/env");
    String namingFactory = (String) env.lookup(Context.INITIAL_CONTEXT_FACTORY);
    String urlProvider = (String) env.lookup(Context.PROVIDER_URL);

    log.debug("namingFactory = {" + namingFactory + "}");
    log.debug("urlProvider = {" + urlProvider + "}");

    Hashtable<String, String> environment = new Hashtable<String, String>();

    environment.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory);
    environment.put(Context.PROVIDER_URL, urlProvider);
    return new InitialContext(environment);
}

From source file:org.apache.axis2.transport.jms.JMSConnectionFactoryManager.java

/**
 * Get the JMS connection factory that matches the given properties, i.e. referring to
 * the same underlying connection factory. Used by the JMSSender to determine if already
 * available resources should be used for outgoing messages
 *
 * @param props a Map of connection factory JNDI properties and name
 * @return the JMS connection factory or null if no connection factory compatible
 *         with the given properties exists
 *//*from  w ww. j  av  a 2 s .  c o m*/
public JMSConnectionFactory getJMSConnectionFactory(Map<String, String> props) {
    for (JMSConnectionFactory cf : connectionFactories.values()) {
        Map<String, String> cfProperties = cf.getParameters();

        if (equals(props.get(JMSConstants.PARAM_CONFAC_JNDI_NAME),
                cfProperties.get(JMSConstants.PARAM_CONFAC_JNDI_NAME))
                && equals(props.get(Context.INITIAL_CONTEXT_FACTORY),
                        cfProperties.get(Context.INITIAL_CONTEXT_FACTORY))
                && equals(props.get(Context.PROVIDER_URL), cfProperties.get(Context.PROVIDER_URL))
                && equals(props.get(Context.SECURITY_PRINCIPAL), cfProperties.get(Context.SECURITY_PRINCIPAL))
                && equals(props.get(Context.SECURITY_CREDENTIALS),
                        cfProperties.get(Context.SECURITY_CREDENTIALS))) {
            return cf;
        }
    }
    return null;
}