Example usage for javax.naming InitialContext InitialContext

List of usage examples for javax.naming InitialContext InitialContext

Introduction

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

Prototype

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

Source Link

Document

Constructs an initial context using the supplied environment.

Usage

From source file:org.dspace.services.email.EmailServiceImpl.java

@Override
public void init() {
    // See if there is already a Session in our environment
    String sessionName = cfg.getProperty("mail.session.name");
    if (null == sessionName) {
        sessionName = "Session";
    }/*from  w w  w.  ja v  a 2 s.  co  m*/
    try {
        InitialContext ctx = new InitialContext(null);
        session = (Session) ctx.lookup("java:comp/env/mail/" + sessionName);
    } catch (NamingException ex) {
        logger.warn("Couldn't get an email session from environment:  {}", ex.getMessage());
    }

    if (null != session) {
        logger.info("Email session retrieved from environment.");
    } else { // No Session provided, so create one
        logger.info("Initializing an email session from configuration.");
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        String host = cfg.getProperty("mail.server");
        if (null != host) {
            props.put("mail.host", cfg.getProperty("mail.server"));
        }
        String port = cfg.getProperty("mail.server.port");
        if (null != port) {
            props.put("mail.smtp.port", port);
        }

        if (null == cfg.getProperty("mail.server.username")) {
            session = Session.getInstance(props);
        } else {
            props.put("mail.smtp.auth", "true");
            session = Session.getInstance(props, this);
        }

        // Set extra configuration properties
        String extras = cfg.getProperty("mail.extraproperties");
        if ((extras != null) && (!"".equals(extras.trim()))) {
            String arguments[] = extras.split(",");
            String key, value;
            for (String argument : arguments) {
                key = argument.substring(0, argument.indexOf('=')).trim();
                value = argument.substring(argument.indexOf('=') + 1).trim();
                props.put(key, value);
            }
        }
    }
}

From source file:com.manning.junitbook.ch14.ejbs.TestAdministratorEJB.java

/**
 * @see TestCase#setUp()//from   ww w.  j a  v a2 s.co m
 */
public void setUp() throws Exception {
    Properties properties = new Properties();
    properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
    properties.put("java.naming.factory.url.pkgs", "org.jboss.naming rg.jnp.interfaces");

    InitialContext ctx = new InitialContext(properties);

    administrator = (IAdministratorLocal) ctx
            .lookup("ch14-cactus-ear-cactified/" + AdministratorBean.class.getSimpleName() + "/local");

    Connection conn = getConnection();

    Statement s = conn.createStatement();

    s.execute("DROP TABLE USERS IF EXISTS");

    s.execute("CREATE TABLE USERS(ID INT, NAME VARCHAR(40))");

    PreparedStatement psInsert = conn.prepareStatement("INSERT INTO USERS VALUES (?, ?)");

    psInsert.setInt(1, 1);
    psInsert.setString(2, "User 1");
    psInsert.executeUpdate();

    psInsert.setInt(1, 2);
    psInsert.setString(2, "User 2");
    psInsert.executeUpdate();
}

From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library 
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up the JNDI context 
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("topic.TOPIC", "BasicTopic");
    hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1");
    hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2");
    hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);

    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up the topic
    Destination topic = (Destination) context.lookup("TOPIC");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side seperately with minimal clutter
    {//from ww w  .j  a va2s.c om
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(topic);

        // Send messaGES
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    // Look up the subscription (pretending it's a queue)
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3");

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

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

/**
 * Bind the resource manager instance to the JNDI directory.
 * <p>/*from  w  ww. j av a  2  s  .  c  o m*/
 * This method will use the full JNDI path provided for the resource
 * manager, and will create if necessary the individual segments of that
 * path.
 * 
 * @param jndiName
 *            The full JNDI path at which the resource manager instance will
 *            be bound in the JNDI directory. JNDI clients can use that path
 *            to obtain the resource manager instance.
 * @param obj
 *            The object to be bound.
 * @return <b>true</b> if the resource manager was successfully bound to
 *         JNDI using the provided path; otherwise <b>false</b>.
 * 
 * @see #unbind(String)
 */
public static boolean bind(String jndiName, Object obj) {
    if (log.isDebugEnabled()) {
        log.debug("Binding object [" + obj + "] in JNDI at path [" + jndiName + "].");
    }
    Context ctx = null;

    try {
        // Create a binding that is local to this host only.
        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);
        }
        // Turn off binding replication .
        // ht.put(WLContext.REPLICATE_BINDINGS, "false");
        ctx = new InitialContext(ht);

        String[] arrJndiNames = jndiName.split("/");
        String subContext = "";

        for (int i = 0; i < arrJndiNames.length - 1; i++) {
            subContext = subContext + "/" + arrJndiNames[i];
            try {
                ctx.lookup(subContext);
            } catch (NameNotFoundException e) {
                ctx.createSubcontext(subContext);
            }

        }

        if (obj instanceof Serializable || jndiInitialContextFactory != null) {
            ctx.bind(jndiName, obj);
        } else {
            NonSerializableFactory.bind(jndiName, obj);
        }
    } catch (NamingException ex) {
        log.error("An error occured while binding [" + jndiName + "] to JNDI:", ex);
        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException ne) {
                log.error("Close context error:", ne);
            }
        }
    }
    return true;
}

From source file:gov.nih.nci.cagrid.caarray.service.CaArraySvcImpl.java

private synchronized InitialContext getContext() throws NamingException {
    if (context == null) {
        try {//from w ww. ja  v a  2 s.co m
            final Properties jndiProp = new Properties();
            jndiProp.load(
                    CaArraySvcImpl.class.getResourceAsStream("/gov/nih/nci/cagrid/caarray/jndi.properties"));
            if (jndiProp.getProperty("java.naming.factory.initial") == null
                    || jndiProp.getProperty("java.naming.factory.url.pkgs") == null
                    || jndiProp.getProperty("java.naming.provider.url") == null) {
                throw new IllegalArgumentException(
                        "Unable to find all required properties in jndi.properties file.");
            }
            context = new InitialContext(jndiProp);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
    return context;
}

From source file:com.vnet.demo.service.azure.servicebus.AzureServiceBusServiceFactory.java

public AzureServiceBusService create() {
    if (this.azureServiceBusService == null) {
        try {/*ww  w .j a va  2 s  .  com*/
            PropertiesFactoryBean properties = SpringUtil.getBean(PropertiesFactoryBean.class);
            this.username = (String) properties.getObject().get("azure.servicebus.username");
            this.password = (String) properties.getObject().get("azure.servicebus.password");
            this.host = (String) properties.getObject().get("azure.servicebus.host");
            String defaultQueue = (String) properties.getObject().get("azure.servicebus.queue");

            String connectionString = "amqps://" + username + ":" + encode(password) + "@" + host;
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY,
                    "org.apache.qpid.amqp_1_0.jms.jndi.PropertiesFileInitialContextFactory");
            env.put("connectionfactory.ServiceBusConnectionFactory", connectionString);

            Context context = new InitialContext(env);
            ConnectionFactory connectionFactory = (ConnectionFactory) context
                    .lookup("ServiceBusConnectionFactory");
            azureServiceBusService = new AzureServiceBusService(connectionFactory, defaultQueue);
        } catch (NamingException | IOException e) {
            e.printStackTrace();
        }
        ;
    }
    return this.azureServiceBusService;
}

From source file:vn.com.vndirect.api.service.SpringAMQP.java

@SuppressWarnings({ "unchecked", "rawtypes" })
protected Context createJndiContext() throws Exception {
    Properties properties = new Properties();

    // jndi.properties is optional
    InputStream in = getClass().getClassLoader().getResourceAsStream("jndi.properties");
    if (in != null) {
        properties.load(in);/*  w  w  w  .j a v a  2 s.  c  o m*/
    } else {
        properties.put("java.naming.factory.initial", "org.apache.camel.util.jndi.CamelInitialContextFactory");
    }
    return new InitialContext(new Hashtable(properties));
}

From source file:it.unipmn.di.dcs.sharegrid.web.model.StandardEnvironment.java

private Context getContext() throws NamingException {
    if (this.envCtx == null) {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, ManagementContextFactory.class.getName());
        //env.put(Context.PROVIDER_URL, "");
        //env.put(Context.OBJECT_FACTORIES, "foo.bar.ObjFactory");
        //System.err.println( "INITIAL_CONTEXT_FACTORY: " + Context.INITIAL_CONTEXT_FACTORY );//XXX
        //System.err.println( "URL_PKG_PREFIXES: " + Context.URL_PKG_PREFIXES );//XXX
        env.put(Context.URL_PKG_PREFIXES, ManagementContextFactory.class.getName());

        //System.err.println("ENV URI: " + envUri);//XXX
        Context ctx = new InitialContext(env);
        if (ctx != null) {
            //System.err.println("CONTEXT NOT NULL");//XXX
            String[] parts = this.envUri.split("/");
            Context[] ctxs = new Context[parts.length + 1];
            ctxs[0] = ctx;/*  ww w  .  j a  v  a  2s .com*/
            int i = 1;
            for (String envPart : parts) {
                //System.err.println("ENV PART: " + envPart);//XXX
                ctxs[i] = (Context) this.getOrCreateSubcontext(envPart, ctxs[i - 1]);
                i++;
            }
            this.envCtx = (Context) this.getOrCreateSubcontext(this.envUri, ctx);
            //System.err.println("ENV CONTEXT: " + this.envCtx);//XXX

            //Properties properties = new Properties();
            //properties.put( "driverClassName", "com.mysql.jdbc.Driver" );
            //properties.put( "url", "jdbc:mysql://localhost:3306/sharegrid" );
            //properties.put( "username", "root" );
            //properties.put( "password", "" );
            //javax.sql.DataSource dataSource = org.apache.commons.dbcp.BasicDataSourceFactory.createDataSource( properties );
            //this.envCtx.rebind( "jdbc/mysql", dataSource );
        }
    }

    return this.envCtx;
}

From source file:br.com.upic.camel.ldap.LdapEndpoint.java

@Override
protected void onExchange(final Exchange exchange) throws Exception {
    LOG.info("Setting up the context");

    final Hashtable<String, String> conf = new Hashtable<String, String>();

    LOG.debug("Initial Context Factory = " + initialContextFactory);

    conf.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);

    LOG.debug("Provider URL = " + providerUrl);

    conf.put(Context.PROVIDER_URL, providerUrl);

    LOG.debug("Security Authentication = " + securityAuthentication);

    conf.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);

    final Message in = exchange.getIn();

    final String user = in.getHeader(HEADER_USER, String.class);

    LOG.debug("User = " + user);

    conf.put(Context.SECURITY_PRINCIPAL, user);

    final String password = in.getHeader(HEADER_PASSWORD, String.class);

    LOG.debug("Password = " + password);

    conf.put(Context.SECURITY_CREDENTIALS, password);

    LOG.info("Authenticating in directory");

    final Message out = exchange.getOut();

    try {//from   w  w  w .ja  v a2s.  c om
        new InitialContext(conf);

        out.setBody(true);
    } catch (final AuthenticationException e) {
        LOG.error(e.getMessage(), e);

        out.setBody(false);
    }

}

From source file:it.unipmn.di.dcs.sharegrid.web.management.ManagementEnv.java

/** Initialized the JNDI. */
protected void initJNDI() throws ManagementException {
    try {//  www .j av a2  s  . c o  m
        this.ctxFactoryBuild = new ManagementContextFactoryBuilder();
        NamingManager.setInitialContextFactoryBuilder(this.ctxFactoryBuild);
        NamingManager.setObjectFactoryBuilder(this.ctxFactoryBuild);

        // Initial environment with various properties
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, ManagementContextFactory.class.getName());
        //env.put(Context.PROVIDER_URL, "");
        //env.put(Context.OBJECT_FACTORIES, "foo.bar.ObjFactory");
        env.put(Context.URL_PKG_PREFIXES, ManagementContextFactory.class.getPackage().getName());

        this.initCtx = new InitialContext(env);
        Context javaCompCtx = (Context) this.getOrCreateSubcontext("java:comp", initCtx);
        if (javaCompCtx == null) {
            throw new ManagementException("JNDI problem. Cannot get java:comp context from InitialContext.");
        }
        Context envCtx = (Context) this.getOrCreateSubcontext("env", javaCompCtx);
        if (envCtx == null) {
            throw new ManagementException("JNDI problem. Cannot get env context from java:comp context.");
        }
        Context jdbcCtx = (Context) this.getOrCreateSubcontext("jdbc", envCtx);
        if (jdbcCtx == null) {
            throw new ManagementException("JNDI problem. Cannot get jdbc context from java:comp/env context.");
        }

        // Create the DataSource

        //Properties properties = new Properties();
        //properties.put( "driverClassName", "com.mysql.jdbc.Driver" );
        //properties.put( "url", "jdbc:mysql://localhost:3306/DB" );
        //properties.put( "username", "username" );
        //properties.put( "password", "********" );
        //
        //DataSource dataSource = BasicDataSourceFactory.createDataSource( properties );
        //initContext.bind( "java:comp/env/jdbc/db", dataSource );

        //Reference ref = new Reference( "javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory", null ); 
        //ref.add(new StringRefAddr("driverClassName", "com.mysql.jdbc.Driver"));
        //ref.add(new StringRefAddr("url", "jdbc:mysql://localhost:3306/sharegrid"));
        //ref.add(new StringRefAddr("username", "root"));
        //ref.add(new StringRefAddr("password", ""));
        //initCtx.rebind( "java:comp/env/jdbc/mysql", ref );
        java.util.Properties properties = new java.util.Properties();
        properties.put("driverClassName", "com.mysql.jdbc.Driver");
        properties.put("url", "jdbc:mysql://localhost:3306/sharegrid");
        properties.put("username", "root");
        properties.put("password", "");
        javax.sql.DataSource dataSource = org.apache.commons.dbcp.BasicDataSourceFactory
                .createDataSource(properties);
        initCtx.rebind("java:comp/env/jdbc/mysql", dataSource);

    } catch (Exception ex) {
        throw new ManagementException("JNDI problem.", ex);
    }
}