本文整理汇总了Java中javax.naming.InitialContext类的典型用法代码示例。如果您正苦于以下问题:Java InitialContext类的具体用法?Java InitialContext怎么用?Java InitialContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
InitialContext类属于javax.naming包,在下文中一共展示了InitialContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: registerDataSource
import javax.naming.InitialContext; //导入依赖的package包/类
/**
* 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);
}
示例2: doGet
import javax.naming.InitialContext; //导入依赖的package包/类
@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);
}
}
示例3: createConnectionFactoryInstance
import javax.naming.InitialContext; //导入依赖的package包/类
/**
* 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);
}
}
示例4: handleIndexing
import javax.naming.InitialContext; //导入依赖的package包/类
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);
}
}
示例5: lookupSessionInJNDI
import javax.naming.InitialContext; //导入依赖的package包/类
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;
}
}
示例6: initEcmService
import javax.naming.InitialContext; //导入依赖的package包/类
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;
}
示例7: DateRequest
import javax.naming.InitialContext; //导入依赖的package包/类
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;
}
}
示例8: TimeRequest
import javax.naming.InitialContext; //导入依赖的package包/类
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;
}
}
示例9: Service
import javax.naming.InitialContext; //导入依赖的package包/类
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;
}
}
示例10: testStartConsumerCreateThrowsException
import javax.naming.InitialContext; //导入依赖的package包/类
@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) {
}
}
示例11: main
import javax.naming.InitialContext; //导入依赖的package包/类
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!");
}
}
示例12: createJMSProviderObject
import javax.naming.InitialContext; //导入依赖的package包/类
/**
* 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;
}
示例13: checkApplicationUser4DedicatedConnection
import javax.naming.InitialContext; //导入依赖的package包/类
@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;
}
示例14: getInstance
import javax.naming.InitialContext; //导入依赖的package包/类
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);
}
}
示例15: testSpecificConsumerRetrieval
import javax.naming.InitialContext; //导入依赖的package包/类
@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();
}