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() throws NamingException 

Source Link

Document

Constructs an initial context.

Usage

From source file:com.silverpeas.jcrutil.security.jaas.TestAccessAuthentified.java

@BeforeClass
public static void loadSpringContext() throws Exception {
    SimpleMemoryContextFactory.setUpAsInitialContext();
    context = new ClassPathXmlApplicationContext("classpath:/spring-jaas.xml", "classpath:/spring-domains.xml");
    BasicDaoFactory.getInstance().setApplicationContext(context);
    repository = context.getBean("repository", JackrabbitRepository.class);
    Reader reader = new InputStreamReader(
            TestAccessAuthentified.class.getClassLoader().getResourceAsStream("silverpeas-jcr.txt"),
            Charsets.UTF_8);/*  w w  w .  j  a v a2  s  .c o m*/
    try {
        SilverpeasRegister.registerNodeTypes(reader);
    } finally {
        IOUtils.closeQuietly(reader);
    }
    datasource = context.getBean("jpaDataSource", BasicDataSource.class);
    InitialContext ic = new InitialContext();
    /*ic.rebind(JNDINames.DATABASE_DATASOURCE, datasource);
    ic.rebind(JNDINames.ADMIN_DATASOURCE, datasource);*/
    System.out.println(" -> node types registered");
}

From source file:de.micromata.genome.util.runtime.LocalSettingsEnv.java

private static LocalSettingsEnv createJndiLocalSettingsEnv() {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    Context initialContext;/*w  w  w. j  a  v a 2  s.  co  m*/
    try {
        try {
            initialContext = new InitialContext();
            initialContext.lookup("java:");
        } catch (NameNotFoundException | NoInitialContextException ex) {
            log.info("No initialContext. Create own context");
            JndiMockupNamingContextBuilder contextBuilder = new JndiMockupNamingContextBuilder();
            InitialContextFactory initialContextFactory = contextBuilder.createInitialContextFactory(env);
            initialContext = initialContextFactory.getInitialContext(env);
            contextBuilder.activate();

        }
        LocalSettingsEnv localSettingsEnv = localSettingsEnvSupplier.apply(initialContext);
        log.info("Jndi LocalSettingsEnv intialized: " + JndiDumper.getJndiDump());
        return localSettingsEnv;
    } catch (NamingException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:de.mpg.escidoc.services.edoc.PubManImport.java

public PubManImport(String fileName, String username, String password) throws Exception {
    userHandle = AdminHelper.loginUser(username, password);
    this.fileName = fileName;
    InitialContext context = new InitialContext();
    validating = (ItemValidating) context.lookup(ItemValidating.SERVICE_NAME);
}

From source file:binky.reportrunner.ui.actions.datasource.SaveDataSource.java

private void populateJNDINames() throws NamingException {
    String ident = "";
    Context ctx = (Context) new InitialContext().lookup("java:comp/env");
    this.jndiNames = this.listJNDINames(ctx, ident);
}

From source file:com.wso2telco.dep.verificationhandler.verifier.DatabaseUtils.java

/**
 * Initialize am data source./* ww w .j  a va 2s. c  om*/
 *
 * @throws NamingException the naming exception
 */
public static void initializeAMDataSource() throws NamingException {
    if (amDatasource != null) {
        return;
    }

    String amDataSourceName = "jdbc/WSO2AM_DB";

    if (amDataSourceName != null) {
        try {
            Context ctx = new InitialContext();
            amDatasource = (DataSource) ctx.lookup(amDataSourceName);
        } catch (NamingException e) {
            log.error(e);
            throw e;
        }

    }
}

From source file:com.silverpeas.admin.SpacesAndComponentsTest.java

@BeforeClass
public static void setUpClass() throws Exception {
    SimpleMemoryContextFactory.setUpAsInitialContext();
    context = new ClassPathXmlApplicationContext(
            new String[] { "spring-admin-spacecomponents-embbed-datasource.xml", "spring-domains.xml" });
    dataSource = context.getBean("jpaDataSource", DataSource.class);
    organizationController = context.getBean(OrganizationController.class);
    admin = context.getBean(Admin.class);
    InitialContext ic = new InitialContext();
    ic.rebind("jdbc/Silverpeas", dataSource);
    DBUtil.getInstanceForTest(dataSource.getConnection());
}

From source file:com.legstar.host.server.EngineHolder.java

/**
 * This method initializes the work manager used by the engine. We will
 * first attempt to lookup the work manager from the JNDI location
 * specified in the engine config file. If not specified, or unable to load,
 * we will use the default work manager.
 *///  w  w w  .  j av  a 2 s . c o m
private static void initializeWorkManager() {
    LOG.debug("Initializing Work Manager.");
    String workMgrLocation = sConfig.getWorkManagerJNDILocation();
    if (workMgrLocation != null && workMgrLocation.length() > 0) {
        try {
            InitialContext ic = new InitialContext();
            sWorkManager = (WorkManager) ic.lookup(workMgrLocation);
        } catch (Exception e) {
            sWorkManager = null;
        }
    } else {
        sWorkManager = null;
    }

    if (sWorkManager == null) {
        int threadPoolSize = sConfig.getThreadPoolSize();
        sExecutor = Executors.newFixedThreadPool(threadPoolSize);
        sWorkManager = new WorkManagerImpl(sExecutor);
    }
}

From source file:com.haulmont.multitenancy.TenantsRoutingDatasource.java

@Override
public void afterPropertiesSet() throws Exception {
    dataSources = new ConcurrentHashMap<>();
    defaultDataSource = createDataSource(defaultDbAddress);

    try {/* w  w  w  .  j a v a2 s.  co m*/
        Context context = new InitialContext();
        String path = AppContext.getProperty(jndiNameAppProperty);
        if (path == null)
            throw new IllegalStateException("Property " + jndiNameAppProperty + " is not set");
        context.bind(path, this);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Puts an MQ message on a specified queue and returns the associated
 * correlation ID for retrieval upon request.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param requestQueue - The request queue name to put the message on
 * @param targetHost - The target host for the message
 * @param value - The data to place on the request. MUST be <code>Serialiable</code>
 * @return <code>String</code> - the JMS correlation ID associated with the message
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *///from   w w w  . java  2  s .co  m
public static final synchronized String sendMqMessage(final String connName, final List<String> authData,
        final String requestQueue, final String targetHost, final Serializable value) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", requestQueue);
        DEBUGGER.debug("Value: {}", targetHost);
        DEBUGGER.debug("Value: {}", value);
    }

    Connection conn = null;
    Session session = null;
    Context envContext = null;
    InitialContext initCtx = null;
    MessageProducer producer = null;
    ConnectionFactory connFactory = null;

    final String correlationId = RandomStringUtils.randomAlphanumeric(64);

    if (DEBUG) {
        DEBUGGER.debug("correlationId: {}", correlationId);
    }

    try {
        try {
            initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

        // Create a Session
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        // Create a MessageProducer from the Session to the Topic or Queue
        if (envContext != null) {
            try {
                producer = session.createProducer((Destination) envContext.lookup(requestQueue));
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createTopic(requestQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            producer = session.createProducer(destination);
        }

        if (producer == null) {
            throw new JMSException("Failed to create a producer object");
        }

        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        if (DEBUG) {
            DEBUGGER.debug("MessageProducer: {}", producer);
        }

        ObjectMessage message = session.createObjectMessage(true);
        message.setJMSCorrelationID(correlationId);
        message.setStringProperty("targetHost", targetHost);

        if (DEBUG) {
            DEBUGGER.debug("correlationId: {}", correlationId);
        }

        message.setObject(value);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        producer.send(message);
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return correlationId;
}