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: 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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
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 35
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 36
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 37
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 38
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 39
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());
	}
}
 
Example 40
Project: lams   File: WorkManagerThreadExecutor.java   Source Code and License 5 votes vote down vote up
public void initialize() {
    try {
        this.workManager = (WorkManager) new InitialContext().lookup(workManagerName);
    } catch (NamingException e) {
        throw new IllegalStateException("Could not locate WorkManager: " + e.getMessage(), e);
    }
}
 
Example 41
Project: oscm   File: EJBServiceAccess.java   Source Code and License 5 votes vote down vote up
@Override
public <T> T getService(Class<T> clazz) {
    try {
        Properties p = new Properties();
        p.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");
        Context context = new InitialContext(p);
        T service = clazz.cast(context.lookup(clazz.getName()));
        return service;
    } catch (NamingException e) {
        throw new SaaSSystemException("Service lookup failed!", e);
    }
}
 
Example 42
Project: asura   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 43
Project: apache-tomcat-7.0.73-with-comment   File: OpenEjbFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new EJB instance using OpenEJB.
 * 
 * @param obj The reference object describing the DataSource
 */
@Override
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 44
Project: message-broker   File: QueueConsumerTest.java   Source Code and License 5 votes vote down vote up
@Parameters({ "broker-port"})
@Test
public void testConsumerProducerWithAutoAck(String port) throws Exception {
    String queueName = "testConsumerProducerWithAutoAck";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", port)
            .withQueue(queueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // publish 100 messages
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(producerSession.createTextMessage("Test message " + i));
    }
    producerSession.close();

    // Consume published messages
    Session subscriberSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = consumer.receive(5000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
    }

    connection.close();
}
 
Example 45
Project: message-broker   File: ConsumersRestApiTest.java   Source Code and License 5 votes vote down vote up
@Parameters({"admin-username", "admin-password", "broker-hostname", "broker-port"})
@Test
public void testRetrieveConsumerList(String username, String password,
                                     String hostname, String port) throws Exception {
    String queueName = "testSpecificQueueRetrieval";


    // 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 receiver1 = queueSession.createReceiver(queue);
    QueueReceiver receiver2 = queueSession.createReceiver(queue);

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

    CloseableHttpResponse response = client.execute(httpGet);
    String body = EntityUtils.toString(response.getEntity());

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

    Assert.assertEquals(consumers.length, 2, "Number of consumers returned is incorrect.");

    receiver1.close();
    receiver2.close();
    queueSession.close();
    connection.close();
}
 
Example 46
Project: lams   File: JndiServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Object locate(String jndiName) {
	final InitialContext initialContext = buildInitialContext();
	final Name name = parseName( jndiName, initialContext );
	try {
		return initialContext.lookup( name );
	}
	catch ( NamingException e ) {
		throw new JndiException( "Unable to lookup JNDI name [" + jndiName + "]", e );
	}
	finally {
		cleanUp( initialContext );
	}
}
 
Example 47
Project: monarch   File: ContextJUnitTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  Hashtable table = new Hashtable();
  table.put(Context.INITIAL_CONTEXT_FACTORY,
      "org.apache.geode.internal.jndi.InitialContextFactoryImpl");
  initialContext = new InitialContext(table);
  initialContext.bind("java:gf/env/datasource/oracle", "a");
  gemfireContext = (Context) initialContext.lookup("java:gf");
  envContext = (Context) gemfireContext.lookup("env");
  dataSourceContext = (Context) envContext.lookup("datasource");
}
 
Example 48
Project: lams   File: WebAppServletContextFactoryTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests that the new mechanism for configuring a launcher from a 
 * servlet context works.
 * 
 * @throws NamingException a problem with the test
 */
public void testConfiguredContext() throws NamingException
{
    JdbcMigrationLauncherFactory launcherFactory = new JdbcMigrationLauncherFactory();
    MockServletContext sc = new MockServletContext();
    
    String dbType = "mysql";
    String sysName = "testSystem";
    
    sc.setInitParameter("migration.systemname", sysName);
    sc.setInitParameter("migration.readonly", "true");
    sc.setInitParameter("migration.databasetype", dbType);
    sc.setInitParameter("migration.patchpath", "patches");
    sc.setInitParameter("migration.datasource", "java:comp/env/jdbc/testsource");
    
    MockDataSource ds = new MockDataSource();
    InitialContext context = new InitialContext();
    context.bind("java:comp/env/jdbc/testsource", ds);
    ServletContextEvent sce = new ServletContextEvent(sc);
    JdbcMigrationLauncher launcher = null;
    try
    {
        launcher = launcherFactory.createMigrationLauncher(sce);
    } 
    catch (MigrationException e)
    {
        e.printStackTrace();
        fail("There should not have been an exception");
    }

    JdbcMigrationContext jdbcContext = 
        (JdbcMigrationContext) launcher.getContexts().keySet().iterator().next();
    assertEquals(dbType, jdbcContext.getDatabaseType().getDatabaseType());
    assertEquals(sysName, jdbcContext.getSystemName());
    assertEquals(true, launcher.isReadOnly());
}
 
Example 49
Project: tomcat7   File: OpenEjbFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new EJB instance using OpenEJB.
 * 
 * @param obj The reference object describing the DataSource
 */
@Override
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 50
Project: oscm   File: OpenStackControllerTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void setup(TestContainer container) throws Exception {

    platformService = mock(APPlatformService.class);
    enableJndiMock();
    context = new InitialContext();
    context.bind(APPlatformService.JNDI_NAME, platformService);
    container.addBean(new OpenStackController());
    controller = container.get(APPlatformController.class);
}
 
Example 51
Project: oscm   File: SubscriptionAgent.java   Source Code and License 5 votes vote down vote up
/**
 * Get the OSCM task queue
 * 
 * @param context
 *            a JNDI context
 * @return the task queue
 */
private Queue getJmsQueue(InitialContext context) {
    try {
        Object lookup = context.lookup(JMS_QUEUE_JNDI_NAME);
        return Queue.class.cast(lookup);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 52
Project: ats-framework   File: JmsClient.java   Source Code and License 5 votes vote down vote up
public JmsClient( final InitialContext context, final String defaultConnectionFactoryName,
                  final String brokerURI ) throws NamingException {

    this.context = new InitialContext(context.getEnvironment());
    this.defaultConnectionFactoryName = defaultConnectionFactoryName;
    this.brokerURI = brokerURI;
    if (this.brokerURI != null) {
        this.context.addToEnvironment(Context.PROVIDER_URL, this.brokerURI);
    }
}
 
Example 53
Project: uroborosql   File: DataSourceConnectionSupplierImpl.java   Source Code and License 5 votes vote down vote up
/**
 * ネーミングコンテキストから指定された名前のオブジェクトをLookupする
 * @param dataSourceName データソース名
 * @return Lookupで取得したデータソース
 * @exception UroborosqlRuntimeException データソースが見つからなかった場合
 */
private static DataSource getNewDataSource(final String dataSourceName) {
	try {
		Context context = new InitialContext();
		return (DataSource) context.lookup(dataSourceName);
	} catch (NamingException ex) {
		throw new UroborosqlRuntimeException("DataSource[" + dataSourceName + "] can not be acquired.", ex);
	}
}
 
Example 54
Project: jdk8u-jdk   File: HelloServer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    int retryCount = 0;
    while (retryCount < MAX_RETRY) {
        try {
            //HelloServer.set("SETTING TEST ITL");
            // Step 1: Instantiate the Hello servant
            HelloImpl helloRef = new HelloImpl();

            // Step 2: Publish the reference in the Naming Service
            // using JNDI API
            Context initialNamingContext = new InitialContext();
            initialNamingContext.rebind("HelloService", helloRef);

            System.out.println("Hello Server: Ready...");
            break;
        } catch (Exception e) {
            System.out.println("Server initialization problem: " + e);
            e.printStackTrace();
            retryCount++;
            try {
                Thread.sleep(ONE_SECOND);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }
}
 
Example 55
Project: asura   File: EJBInvokerJob.java   Source Code and License 5 votes vote down vote up
private InitialContext getInitialContext(JobDataMap jobDataMap)
    throws NamingException {
    Hashtable params = new Hashtable(2);
    
    String initialContextFactory =
        jobDataMap.getString(INITIAL_CONTEXT_FACTORY);
    if (initialContextFactory != null) {
        params.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    }
    
    String providerUrl = jobDataMap.getString(PROVIDER_URL);
    if (providerUrl != null) {
        params.put(Context.PROVIDER_URL, providerUrl);
    }

    String principal = jobDataMap.getString(PRINCIPAL);
    if ( principal != null ) {
        params.put( Context.SECURITY_PRINCIPAL, principal );
    }

    String credentials = jobDataMap.getString(CREDENTIALS);
    if ( credentials != null ) {
        params.put( Context.SECURITY_CREDENTIALS, credentials );
    }

    return (params.size() == 0) ? new InitialContext() : new InitialContext(params);
}
 
Example 56
Project: solace-integration-guides   File: JMSTopicSource.java   Source Code and License 5 votes vote down vote up
@Override
public void run(SourceContext<OUT> sourceContext) throws Exception {
    InitialContext jndiContext = new InitialContext(_jmsEnv);
    ConnectionFactory factory = (ConnectionFactory) jndiContext.lookup(_cfName);
    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(_topicName));
    connection.start();
    while(true) {
        Message msg = consumer.receive();
        sourceContext.collect(_deserializer.translate(msg));
        msg.acknowledge();
    }
}
 
Example 57
Project: loyalty-level   File: LoyaltyLevel.java   Source Code and License 5 votes vote down vote up
/** Connect to the server, and lookup the managed resources. 
 * @throws JMSException */
public void initialize() throws NamingException {
	System.out.println("Getting the InitialContext");
	InitialContext context = new InitialContext();

	//lookup our JMS objects
	System.out.println("Looking up our JMS resources");
	queueCF = (QueueConnectionFactory) context.lookup(NOTIFICATION_QCF);
	queue = (Queue) context.lookup(NOTIFICATION_Q);

	initialized = true;
	System.out.println("Initialization completed successfully!");
}
 
Example 58
Project: parabuild-ci   File: HibernateService.java   Source Code and License 5 votes vote down vote up
public void stop() {
	log.info("stopping service");
	try {
		InitialContext context = NamingHelper.getInitialContext( getProperties() );
		( (SessionFactory) context.lookup(boundName) ).close();
		//context.unbind(boundName);
	}
	catch (Exception e) {
		log.warn("exception while stopping service", e);
	}
}
 
Example 59
Project: jmsclient   File: AbstractJMSClient.java   Source Code and License 5 votes vote down vote up
protected Properties getJndiConfig()
{
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
    env.put(InitialContext.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
    // need to try redundant connection attempts in the format below.
    // env.put(Context.PROVIDER_URL, "remote://<s1>:<p1>,remote://<s2>:<p2>");
    env.put(Context.PROVIDER_URL, providerUrl);

    return env;
}
 
Example 60
Project: asura   File: JmsHelper.java   Source Code and License 5 votes vote down vote up
public static InitialContext getInitialContext(final JobDataMap jobDataMap) throws NamingException
{
    
    Hashtable params = new Hashtable(2);
    
    String initialContextFactory =
        jobDataMap.getString(INITIAL_CONTEXT_FACTORY);

    if (initialContextFactory != null) {
        params.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    }
    
    String providerUrl = jobDataMap.getString(PROVIDER_URL);
    if (providerUrl != null) {
        params.put(Context.PROVIDER_URL, providerUrl);
    }

    String principal = jobDataMap.getString(PRINCIPAL);
    if ( principal != null ) {
        params.put( Context.SECURITY_PRINCIPAL, principal );
    }

    String credentials = jobDataMap.getString(CREDENTIALS);
    if ( credentials != null ) {
        params.put( Context.SECURITY_CREDENTIALS, credentials );
    }

    if (params.size() == 0) {
        return new InitialContext();
    } else {
        return new InitialContext(params);
    }
    
}