Java Code Examples for javax.naming.InitialContext

The following are top voted examples for showing how to use javax.naming.InitialContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: BibliotecaPS   File: DataSourceTest.java   Source Code and License 9 votes vote down vote up
/**
 * This method is separated from the rest of the example since you normally
 * would NOT register a JDBC driver in your code. It would likely be
 * configered into your naming and directory service using some GUI.
 * 
 * @throws Exception
 *             if an error occurs
 */
private void registerDataSource() throws Exception {
    this.tempDir = File.createTempFile("jnditest", null);
    this.tempDir.delete();
    this.tempDir.mkdir();
    this.tempDir.deleteOnExit();

    com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, this.tempDir.toURI().toString());
    this.ctx = new InitialContext(env);
    assertTrue("Naming Context not created", this.ctx != null);
    ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    ds.setUrl(dbUrl); // from BaseTestCase
    this.ctx.bind("_test", ds);
}
 
Example 2
Project: tomcat7   File: TestNamingContext.java   Source Code and License 8 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        Object obj = ctx.lookup("java:comp/env/bug50351");
        TesterObject to = (TesterObject) obj;
        out.print(to.getFoo());
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 3
Project: nifi-jms-jndi   File: JNDIConnectionFactoryProvider.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an instance of the {@link ConnectionFactory} from the provided 'CONNECTION_FACTORY_IMPL'.
 */
private void createConnectionFactoryInstance(ConfigurationContext context) {
    String connectionFactoryImplName = getContextValue(context, CONNECTION_FACTORY_IMPL);
    Properties env = new Properties();

    try {
        env.put(InitialContext.INITIAL_CONTEXT_FACTORY, connectionFactoryImplName);
        env.put(InitialContext.PROVIDER_URL, getContextValue(context, BROKER_URI));

        InitialContext initialContext = new InitialContext(env);
        this.connectionFactory = (ConnectionFactory) initialContext.lookup(context.getProperty(JNDI_CF_LOOKUP).evaluateAttributeExpressions().getValue());
        if (logger.isDebugEnabled())
            logger.debug("Connection factory is created");
    } catch (Exception e) {
        throw new IllegalStateException("Failed to load and/or instantiate class 'com.solacesystems.jndi.SolJNDIInitialContextFactory'", e);
    }
}
 
Example 4
Project: oscm   File: HibernateEventListener.java   Source Code and License 6 votes vote down vote up
private void handleIndexing(Object entity,
        ModificationType modType) {
    if (entity instanceof DomainObject<?>) {
        if (hibernateIndexer == null) {
            try {
                Properties p = new Properties();
                p.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.apache.openejb.client.LocalInitialContextFactory");
                Context context = new InitialContext(p);
                hibernateIndexer = (HibernateIndexer) context
                        .lookup(HibernateIndexer.class.getName());
            } catch (NamingException e) {
                throw new SaaSSystemException("Service lookup failed!", e);
            }
        }
        hibernateIndexer.handleIndexing((DomainObject<?>) entity, modType);
    }
}
 
Example 5
Project: lemon   File: SMTPAppenderBase.java   Source Code and License 6 votes vote down vote up
private Session lookupSessionInJNDI() {
    addInfo("Looking up javax.mail.Session at JNDI location ["
            + jndiLocation + "]");

    try {
        Context initialContext = new InitialContext();
        Object obj = initialContext.lookup(jndiLocation);

        return (Session) obj;
    } catch (Exception e) {
        addError("Failed to obtain javax.mail.Session from JNDI location ["
                + jndiLocation + "]");

        return null;
    }
}
 
Example 6
Project: cloud-ariba-partner-flow-extension-ext   File: EcmServiceProvider.java   Source Code and License 6 votes vote down vote up
private static EcmService initEcmService() {
	LOGGER.debug(DEBUG_INITIALIZING_ECM_SERVICE);

	EcmService ecmService;
	try {
		InitialContext initialContext = new InitialContext();
		ecmService = (EcmService) initialContext.lookup(ECM_SERVICE_NAME);
	} catch (NamingException e) {
		String errorMessage = MessageFormat.format(ERROR_LOOKING_UP_THE_ECM_SERVICE_FAILED, ECM_SERVICE_NAME);
		LOGGER.error(errorMessage, e);
		throw new RuntimeException(errorMessage, e);
	}

	LOGGER.debug(DEBUG_ECM_SERVICE_INITIALIZED);
	return ecmService;
}
 
Example 7
Project: dbg-amqp-dispatch-workshop   File: DateRequest.java   Source Code and License 6 votes vote down vote up
public DateRequest() throws NamingException {
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
    System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
    System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd HH:mm:ss Z");
    System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");

    try {
        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        properties.setProperty("connectionfactory.connection", String.format(
                "amqp://%s:%d?amqp.idleTimeout=30000",
                "localhost",
                5672));
        properties.setProperty("queue.time", "/time");
        properties.setProperty("queue.date", "/date");
        properties.setProperty("queue.response", UUID.randomUUID().toString());
        this.context = new InitialContext(properties);
    } catch (NamingException ex) {
        LOGGER.error("Unable to proceed with broadcast receiver", ex);
        throw ex;
    }
}
 
Example 8
Project: dbg-amqp-dispatch-workshop   File: TimeRequest.java   Source Code and License 6 votes vote down vote up
public TimeRequest() throws NamingException {
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
    System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
    System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd HH:mm:ss Z");
    System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");

    try {
        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        properties.setProperty("connectionfactory.connection", String.format(
                "amqp://%s:%d?amqp.idleTimeout=30000",
                "localhost",
                5672));
        properties.setProperty("queue.time", "/time");
        properties.setProperty("queue.date", "/date");
        properties.setProperty("queue.response", UUID.randomUUID().toString());
        this.context = new InitialContext(properties);
    } catch (NamingException ex) {
        LOGGER.error("Unable to proceed with broadcast receiver", ex);
        throw ex;
    }
}
 
Example 9
Project: dbg-amqp-dispatch-workshop   File: Service.java   Source Code and License 6 votes vote down vote up
public Service() throws NamingException {
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
    System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
    System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd HH:mm:ss Z");
    System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");

    try {
        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        properties.setProperty("connectionfactory.connection", String.format(
                "amqp://%s:%d?amqp.idleTimeout=30000&jms.forceAsyncSend=true",
                "localhost",
                5672));
        properties.setProperty("queue.time", "/time");
        properties.setProperty("queue.date", "/date");
        this.context = new InitialContext(properties);
    } catch (NamingException ex) {
        LOGGER.error("Unable to proceed with broadcast receiver", ex);
        throw ex;
    }
}
 
Example 10
Project: flume-release-1.7.0   File: TestJMSSource.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testStartConsumerCreateThrowsException() throws Exception {
  when(consumerFactory.create(any(InitialContext.class), any(ConnectionFactory.class),
                              anyString(), any(JMSDestinationType.class),
                              any(JMSDestinationLocator.class), anyString(), anyInt(), anyLong(),
                              any(JMSMessageConverter.class), any(Optional.class),
                              any(Optional.class))).thenThrow(new RuntimeException());
  source.configure(context);
  source.start();
  try {
    source.process();
    Assert.fail();
  } catch (FlumeException expected) {

  }
}
 
Example 11
Project: jboss-eap7.1-playground   File: MultipleServerWildFlyConfigURIClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws NamingException {
	checkArgs(args);

	// Set I_C_F with properties and use wildfly-config.xml to set the server URI and credentials
	Properties p = new Properties();
	p.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
	InitialContext ic = new InitialContext(p);
	
	Simple proxy = (Simple) ic.lookup("ejb:EAP71-PLAYGROUND-server/ejb/SimpleBean!" + Simple.class.getName());
	log.fine("Proxy is : " + proxy);
	
	HashSet<String> serverList = new HashSet<>();
	
	for (int i = 0; i < 20; i++) {
		serverList.add(proxy.getJBossServerName());
	}
	
	if(serverList.size() > 1) {
		log.info("Server should be part of a cluster or multiple URL's as the invocation was executed on the following servers : " + serverList);
	}else if(serverList.size() == 1) {
		log.warning("Server is not part of a cluster with multiple nodes, or did not have multiple PROVIDER URL's, as the invocation was executed on a single server : " + new ArrayList<String>(serverList).get(0));
	}else{
		throw new RuntimeException("Unexpected result, no server list!");
	}
}
 
Example 12
Project: cli-java   File: AocConnectionManager.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an object using qpid/amq initial context factory.
 *
 * @param className can be any of the qpid/amq supported JNDI properties:
 *                  connectionFactory, queue, topic, destination.
 * @param address   of the connection or node to create.
 */
protected Object createJMSProviderObject(String className, String address) {
    /* Name of the object is the same as class of the object */
    String name = className;
    properties.setProperty(className + "." + name, address);

    Object jmsProviderObject = null;
    try {
        Context context = new InitialContext(properties);
        jmsProviderObject = context.lookup(name);
        context.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return jmsProviderObject;
}
 
Example 13
Project: jboss-eap7.1-playground   File: DelegateBean.java   Source Code and License 6 votes vote down vote up
@RolesAllowed({"Application"})
@Override
public void checkApplicationUser4DedicatedConnection(String localUserName, String remoteUserName) throws NamingException {
    Principal caller = context.getCallerPrincipal();
    
    if(!localUserName.equals(caller.getName())) {
    	log.severe("Given user name '" + localUserName + "' not equal to real use name '" + caller.getName() + "'");
    }else{
    	log.info("Expected user '" + localUserName + "'. Try to invoke remote SimpleBean with user '" + remoteUserName + "'");
    	Properties p = new Properties();
		p.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
		p.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
		
		p.put(Context.SECURITY_PRINCIPAL, remoteUserName);
		p.put(Context.SECURITY_CREDENTIALS, remoteUserName);

    	InitialContext ic = new InitialContext(p);
    	Simple localProxy = (Simple)ic.lookup("ejb:EAP71-PLAYGROUND-server/ejb/SimpleBean!" + Simple.class.getName());
    	if (!localProxy.checkApplicationUser(remoteUserName)) {
    		log.severe("Remote bean was not invoked with the correct user!");
    		throw new RuntimeException("Remote bean was not invoked with the correct user!");
    	}
    	
    }
    return;
}
 
Example 14
Project: oscm   File: APPTemplateServiceFactory.java   Source Code and License 6 votes vote down vote up
public static APPTemplateService getInstance() {
    try {
        Properties p = new Properties();
        p.setProperty (Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");

        InitialContext context = new InitialContext(p);
        Object lookup = context.lookup(JNDI_NAME);
        if (!APPTemplateService.class.isAssignableFrom(lookup.getClass())) {
            throw new IllegalStateException(
                "Failed to look up APPlatformService. The returned service is not implementing correct interface");
        }
        return (APPTemplateService) lookup;
    } catch (NamingException e) {
        logger.error("Service lookup failed: " + JNDI_NAME);
        throw new IllegalStateException(
            "No valid platform service available", e);
    }
}
 
Example 15
Project: message-broker   File: ConsumersRestApiTest.java   Source Code and License 6 votes vote down vote up
@Parameters({"admin-username", "admin-password", "broker-hostname", "broker-port"})
@Test
public void testSpecificConsumerRetrieval(String username, String password,
                                          String hostname, String port) throws Exception {
    String queueName = "testSpecificConsumerRetrieval";

    // Create a durable queue using a JMS client
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(username, password, hostname, port)
            .withQueue(queueName)
            .build();

    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    QueueConnection connection = connectionFactory.createQueueConnection();
    connection.start();

    QueueSession queueSession = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    Queue queue = queueSession.createQueue(queueName);
    QueueReceiver receiver = queueSession.createReceiver(queue);

    HttpGet getAllConsumers = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
                                          + "/" + queueName + "/consumers");

    CloseableHttpResponse response = client.execute(getAllConsumers);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
    String body = EntityUtils.toString(response.getEntity());

    ConsumerMetadata[] consumers = objectMapper.readValue(body, ConsumerMetadata[].class);

    Assert.assertTrue(consumers.length > 0, "Number of consumers returned is incorrect.");

    int id = consumers[0].getId();
    HttpGet getConsumer = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH + "/"
                                              + queueName + "/consumers/" + id);

    response = client.execute(getConsumer);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
    String consumerString = EntityUtils.toString(response.getEntity());
    ConsumerMetadata consumerMetadata = objectMapper.readValue(consumerString, ConsumerMetadata.class);

    Assert.assertEquals(consumerMetadata.getId().intValue(), id, "incorrect message id");

    receiver.close();
    queueSession.close();
    connection.close();
}
 
Example 16
Project: tomcat7   File: TestTomcat.java   Source Code and License 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException {

    String name = null;

    try {
        javax.naming.Context initCtx = new InitialContext();
        javax.naming.Context envCtx =
                (javax.naming.Context) initCtx.lookup("java:comp/env");
        name = (String) envCtx.lookup(JNDI_ENV_NAME);
    } catch (NamingException e) {
        throw new IOException(e);
    }

    res.getWriter().write("Hello, " + name);
}
 
Example 17
Project: tomcat7   File: TestNamingContext.java   Source Code and License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        Object obj1 = ctx.lookup("java:comp/env/list/foo");
        Object obj2 = ctx.lookup("java:comp/env/list/foo");
        if (obj1 == obj2) {
            out.print("EQUAL");
        } else {
            out.print("NOTEQUAL");
        }
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 18
Project: jboss-eap7.1-playground   File: DelegateClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws NamingException {
	checkArgs(args);
	
	Properties p = new Properties();
	
	p.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
	p.put(Context.PROVIDER_URL, "http-remoting://localhost:9080");
	
	p.put(Context.SECURITY_PRINCIPAL, "delegateUser");
	p.put(Context.SECURITY_CREDENTIALS, "delegateUser");
	InitialContext ic = new InitialContext(p);
	
	Delegate proxy = (Delegate) ic.lookup("ejb:EAP71-PLAYGROUND-MainServer-icApp/ejb/DelegateBean!" + Delegate.class.getName());
	proxy.checkApplicationUser4DedicatedConnection("delegateUser", "delegateUserR");
	
	ic.close();
}
 
Example 19
Project: the-vigilantes   File: DataSourceTest.java   Source Code and License 6 votes vote down vote up
/**
 * This method is separated from the rest of the example since you normally
 * would NOT register a JDBC driver in your code. It would likely be
 * configered into your naming and directory service using some GUI.
 * 
 * @throws Exception
 *             if an error occurs
 */
private void registerDataSource() throws Exception {
    this.tempDir = File.createTempFile("jnditest", null);
    this.tempDir.delete();
    this.tempDir.mkdir();
    this.tempDir.deleteOnExit();

    com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, this.tempDir.toURI().toString());
    this.ctx = new InitialContext(env);
    assertTrue("Naming Context not created", this.ctx != null);
    ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    ds.setUrl(dbUrl); // from BaseTestCase
    this.ctx.bind("_test", ds);
}
 
Example 20
Project: solace-integration-guides   File: BasicTopicStreamingSample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        final Hashtable<String, String> jmsEnv = new Hashtable<>();
        jmsEnv.put(InitialContext.INITIAL_CONTEXT_FACTORY, "com.solacesystems.jndi.SolJNDIInitialContextFactory");
        jmsEnv.put(InitialContext.PROVIDER_URL, "smf://192.168.56.101");
        jmsEnv.put(Context.SECURITY_PRINCIPAL, "[email protected]_vpn");
        jmsEnv.put(Context.SECURITY_CREDENTIALS, "password");

        env.addSource(new JMSTopicSource<String>(jmsEnv,
                "flink_cf",
                "flink/topic",
                new JMSTextTranslator()))
                .print();

        env.execute();
    }
 
Example 21
Project: solace-integration-guides   File: BasicQueueStreamingSample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        final Hashtable<String, String> jmsEnv = new Hashtable<>();
        jmsEnv.put(InitialContext.INITIAL_CONTEXT_FACTORY, "com.solacesystems.jndi.SolJNDIInitialContextFactory");
        jmsEnv.put(InitialContext.PROVIDER_URL, "smf://192.168.56.101");
        jmsEnv.put(Context.SECURITY_PRINCIPAL, "[email protected]_vpn");
        jmsEnv.put(Context.SECURITY_CREDENTIALS, "password");

        env.addSource(new JMSQueueSource<String>(jmsEnv,
                "flink_cf",
                "flink_queue",
                new JMSTextTranslator()))
                .print();

        env.execute();
    }
 
Example 22
Project: keycloak-health-checks   File: DatabaseHealthIndicator.java   Source Code and License 6 votes vote down vote up
@Override
public HealthStatus check() {

  try {
    InitialContext ic = new InitialContext();
    DataSource dataSource = (DataSource) ic.lookup(jndiName);

    try (Connection connection = dataSource.getConnection()) {

      try (Statement statement = connection.createStatement()) {
        if (statement.execute(healthQuery)) {
          return reportUp();
        }
      }
    }
  } catch (Exception ex) {
    return reportDown().withAttribute("message", ex.getMessage());
  }

  return reportDown();
}
 
Example 23
Project: asura   File: JNDIConnectionProvider.java   Source Code and License 6 votes vote down vote up
private void init() {

        if (!isAlwaysLookup()) {
            Context ctx = null;
            try {
                ctx = (props != null) ? new InitialContext(props) : new InitialContext(); 

                datasource = (DataSource) ctx.lookup(url);
            } catch (Exception e) {
                getLog().error(
                        "Error looking up datasource: " + e.getMessage(), e);
            } finally {
                if (ctx != null) {
                    try { ctx.close(); } catch(Exception ignore) {}
                }
            }
        }
    }
 
Example 24
Project: lams   File: JNDIConnectionProvider.java   Source Code and License 6 votes vote down vote up
private void init() {

        if (!isAlwaysLookup()) {
            Context ctx = null;
            try {
                ctx = (props != null) ? new InitialContext(props) : new InitialContext(); 

                datasource = (DataSource) ctx.lookup(url);
            } catch (Exception e) {
                getLog().error(
                        "Error looking up datasource: " + e.getMessage(), e);
            } finally {
                if (ctx != null) {
                    try { ctx.close(); } catch(Exception ignore) {}
                }
            }
        }
    }
 
Example 25
Project: oscm   File: APPCommunicationServiceBeanTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setup() throws Exception {

    // container.enableInterfaceMocking(true);
    if (!NamingManager.hasInitialContextFactoryBuilder()) {
        NamingManager
                .setInitialContextFactoryBuilder(new TestNamingContextFactoryBuilder());
    }
    InitialContext initialContext = new InitialContext();
    Properties properties = new Properties();
    properties.put("mail.smtp.from", "[email protected]");
    mailMock = Session.getInstance(properties);
    initialContext.bind("java:openejb/Resource/" + DEFAULT_MAIL_RESOURCE, mailMock);
    configurationService = mock(APPConfigurationServiceBean.class);
    commService = spy(new APPCommunicationServiceBean());
    commService.configService = configurationService;
    doNothing().when(commService).transportMail(
            Matchers.any(MimeMessage.class));
}
 
Example 26
Project: lucene-demo   File: JdbcUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 获取连接,使用数据库连接池
 * @param jndi 配置在tomcat的context.xml里面的东西
 * @return 创建的连接对象
 */
public Connection getConnection(String jndi)
{
	try
	{
		log.debug("开始尝试连接数据库!");
		Context context=new InitialContext();
		DataSource dataSource=(DataSource)context.lookup("java:comp/env/"+jndi);
		con=dataSource.getConnection();
		log.debug("连接成功!");
	}
	catch (Exception e)
	{
		log.error("连接数据库失败!", e);
	}
	return con;
}
 
Example 27
Project: oscm   File: APPlatformServiceFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves an <code>APPlatformService</code> instance.
 * 
 * @return the service instance
 */
public static APPlatformService getInstance() {
    try {

        Properties p = new Properties();
        p.setProperty (Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");

        InitialContext context = new InitialContext(p);
        Object lookup = context.lookup(JNDI_NAME);
        if (!APPlatformService.class.isAssignableFrom(lookup.getClass())) {
            throw new IllegalStateException(
                    "Failed to look up APPlatformService. The returned service is not implementing correct interface");
        }
        return (APPlatformService) lookup;
    } catch (NamingException e) {
        logger.error("Service lookup failed: " + JNDI_NAME);
        throw new IllegalStateException(
                "No valid platform service available", e);
    }
}
 
Example 28
Project: lams   File: OpenEjbFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Crete a new EJB instance using OpenEJB.
 * 
 * @param obj The reference object describing the DataSource
 */
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
                                Hashtable environment)
    throws Exception {

    Object beanObj = null;

    if (obj instanceof EjbRef) {

        Reference ref = (Reference) obj;

        String factory = DEFAULT_OPENEJB_FACTORY;
        RefAddr factoryRefAddr = ref.get("openejb.factory");
        if (factoryRefAddr != null) {
            // Retrieving the OpenEJB factory
            factory = factoryRefAddr.getContent().toString();
        }

        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);

        RefAddr linkRefAddr = ref.get("openejb.link");
        if (linkRefAddr != null) {
            String ejbLink = linkRefAddr.getContent().toString();
            beanObj = (new InitialContext(env)).lookup(ejbLink);
        }

    }

    return beanObj;

}
 
Example 29
Project: nifi-jms-jndi   File: CommonTest.java   Source Code and License 5 votes vote down vote up
static ConnectionFactory buildJmsJndiConnectionFactory() throws Exception {
    Properties env =new Properties();
    env.setProperty(Context.PROVIDER_URL, "vm://localhost?broker.persistent=false");
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
    
    InitialContext initialContext = new InitialContext(env);
    // Lookup ConnectionFactory.
    ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory");  
    return connectionFactory;
   
}
 
Example 30
Project: EJB-CON-DTO   File: Utilidades.java   Source Code and License 5 votes vote down vote up
public static Object getEJBRemote(String nameEJB, String iface) throws Exception {

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        props.put(Context.PROVIDER_URL, "http://localhost:7001");
        try {
            Context ctx = new InitialContext(props);
            String lookup = nameEJB + "#" + iface;
            System.out.println("Lookup: " + lookup);
            return ctx.lookup(lookup);
        } catch (Exception ex) {
            throw new Exception("No se encontro el EJB: '"+nameEJB+"'.");
        }
        
}
 
Example 31
Project: rapidminer   File: DatabaseHandler.java   Source Code and License 5 votes vote down vote up
public static DatabaseHandler getConnectedDatabaseHandler(Operator operator) throws OperatorException, SQLException {
    Process process = operator.getProcess();
    switch(operator.getParameterAsInt("define_connection")) {
        case 0:
            String repositoryName = null;
            if(process != null) {
                RepositoryLocation entry = process.getRepositoryLocation();
                if(entry != null) {
                    repositoryName = entry.getRepositoryName();
                }
            }

            ConnectionEntry entry1 = DatabaseConnectionService.getConnectionEntry(operator.getParameterAsString("connection"), repositoryName, process != null?process.getRepositoryAccessor():null);
            if(entry1 == null) {
                throw new UserError(operator, 318, new Object[]{operator.getParameterAsString("connection")});
            }

            return getConnectedDatabaseHandler(entry1);
        case 1:
        default:
            return getConnectedDatabaseHandler(operator.getParameterAsString("database_url"), operator.getParameterAsString("username"), operator.getParameterAsString("password"));
        case 2:
            String jndiName = operator.getParameterAsString("jndi_name");

            try {
                InitialContext e = new InitialContext();
                DataSource source = (DataSource)e.lookup(jndiName);
                return getHandler(source.getConnection());
            } catch (NamingException var7) {
                throw new OperatorException("Failed to lookup \'" + jndiName + "\': " + var7, var7);
            }
    }
}
 
Example 32
Project: Mastering-Java-EE-Development-with-WildFly   File: BeanCallingOtherBeans.java   Source Code and License 5 votes vote down vote up
public Ejb21StateLocal getEjb21StateLocal() {
	try {
		InitialContext jndiContext = new InitialContext();
		Ejb21StateLocalHome sessionHome = (Ejb21StateLocalHome) jndiContext.lookup("java:comp/env/injected2");
		return sessionHome.create();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 33
Project: Mastering-Java-EE-Development-with-WildFly   File: RemotingNamingTestCase.java   Source Code and License 5 votes vote down vote up
private void createInitialContext() throws NamingException {
	Properties prop = new Properties();

	prop.put(INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
	prop.put(PROVIDER_URL, "http-remoting://127.0.0.1:8080");
	prop.put(SECURITY_PRINCIPAL, "admin");
	prop.put(SECURITY_CREDENTIALS, "secret123!");
	prop.put("jboss.naming.client.ejb.context", true);

	context = new InitialContext(prop);
}
 
Example 34
Project: openjdk-jdk10   File: RMIConnectorServer.java   Source Code and License 5 votes vote down vote up
/**
 * Bind a stub to a registry.
 * @param jndiUrl URL of the stub in the registry, extracted
 *        from the <code>JMXServiceURL</code>.
 * @param attributes A Hashtable containing environment parameters,
 *        built from the Map specified at this object creation.
 * @param rmiServer The object to bind in the registry
 * @param rebind true if the object must be rebound.
 **/
void bind(String jndiUrl, Hashtable<?, ?> attributes,
          RMIServer rmiServer, boolean rebind)
    throws NamingException, MalformedURLException {
    // if jndiURL is not null, we nust bind the stub to a
    // directory.
    InitialContext ctx =
        new InitialContext(attributes);

    if (rebind)
        ctx.rebind(jndiUrl, rmiServer);
    else
        ctx.bind(jndiUrl, rmiServer);
    ctx.close();
}
 
Example 35
Project: ralasafe   File: DataSourceProviderJndiImpl.java   Source Code and License 5 votes vote down vote up
public void setup( Properties prop ) {
	this.prop=prop;
	String jndiName=prop.getProperty( "jndiName" );
	try {
		InitialContext ctx=new InitialContext();
		dataSource=(javax.sql.DataSource) ctx.lookup( jndiName );
	} catch( NamingException e ) {
		e.printStackTrace();
		throw new RuntimeException( e );
	}
}
 
Example 36
Project: drinkwater-java   File: JndiSqlDataStoreTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldApplyMigrations() throws Exception {

    //bind the datasources
    DataSource migrationdataSource = pg.getPostgresDatabase();
    DataSource userdataSource = pg.getPostgresDatabase();

    //bind to context
    Context ctx = new InitialContext();
    ctx.bind("java:test/datasources/migrationDS", migrationdataSource);
    ctx.bind("java:test/datasources/testDS", userdataSource);

    try (DrinkWaterApplication app = DrinkWaterApplication.create("jndi-datastore-test",
            options().use(JndiDataStoreConfiguration.class).autoStart())) {

        JndiSqlDataStore store = app.getStore("test");
        store.executeNoQuery("INSERT INTO contact(id, first_name, last_name) VALUES (2 , 'Jean-Marc', 'Canon');");

        try (Connection c = store.getConnection()) {
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery("SELECT * from contact");
            assertTrue(rs.next());
            assertEquals(2, rs.getInt(1));
            assertFalse(rs.next());
        }
    }
}
 
Example 37
Project: flume-release-1.7.0   File: JMSMessageConsumerFactory.java   Source Code and License 5 votes vote down vote up
JMSMessageConsumer create(InitialContext initialContext, ConnectionFactory connectionFactory,
    String destinationName, JMSDestinationType destinationType,
    JMSDestinationLocator destinationLocator, String messageSelector, int batchSize,
    long pollTimeout, JMSMessageConverter messageConverter,
    Optional<String> userName, Optional<String> password) {
  return new JMSMessageConsumer(initialContext, connectionFactory, destinationName,
      destinationLocator, destinationType, messageSelector, batchSize, pollTimeout,
      messageConverter, userName, password);
}
 
Example 38
Project: lams   File: JNDIConnectionProvider.java   Source Code and License 5 votes vote down vote up
public Connection getConnection() throws SQLException {
    Context ctx = null;
    try {
        Object ds = this.datasource;

        if (ds == null || isAlwaysLookup()) {
            ctx = (props != null) ? new InitialContext(props): new InitialContext(); 

            ds = ctx.lookup(url);
            if (!isAlwaysLookup()) {
                this.datasource = ds;
            }
        }

        if (ds == null) {
            throw new SQLException( "There is no object at the JNDI URL '" + url + "'");
        }

        if (ds instanceof XADataSource) {
            return (((XADataSource) ds).getXAConnection().getConnection());
        } else if (ds instanceof DataSource) { 
            return ((DataSource) ds).getConnection();
        } else {
            throw new SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
        }
    } catch (Exception e) {
        this.datasource = null;
        throw new SQLException(
                "Could not retrieve datasource via JNDI url '" + url + "' "
                        + e.getClass().getName() + ": " + e.getMessage());
    } finally {
        if (ctx != null) {
            try { ctx.close(); } catch(Exception ignore) {}
        }
    }
}
 
Example 39
Project: drinkwater-java   File: MockInitialContextFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldThrowExceptionbecauseNotBound()  {

    assertThatThrownBy(() -> {
        Context ctx = new InitialContext();
        Object result = ctx.lookup("hello");
    }).isInstanceOf(NamingException.class).hasMessageContaining("hello");

}
 
Example 40
Project: lams   File: JndiServiceImpl.java   Source Code and License 5 votes vote down vote up
private void cleanUp(InitialContext initialContext) {
	try {
		initialContext.close();
	}
	catch ( NamingException e ) {
		LOG.unableToCloseInitialContext(e.toString());
	}
}