Example usage for javax.naming InitialContext lookup

List of usage examples for javax.naming InitialContext lookup

Introduction

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

Prototype

public Object lookup(Name name) throws NamingException 

Source Link

Usage

From source file:org.enhydra.jdbc.standard.StandardXADataSource.java

public Object getObjectInstance(Object refObj, Name name, Context nameCtx, Hashtable env) throws Exception {

    super.getObjectInstance(refObj, name, nameCtx, env);
    Reference ref = (Reference) refObj;
    InitialContext ictx = new InitialContext(env);
    this.setTransactionManagerName((String) ref.get("transactionManagerName").getContent());
    if (this.transactionManagerName != null) {
        try {/*w w w.  j  a v a 2s  .c  om*/
            this.setTransactionManager((TransactionManager) ictx.lookup(this.transactionManagerName));
        } catch (NamingException e) {
            // ignore, TransactionManager might be set later enlisting the XAResouce on the Transaction
        }
    }
    log.debug("StandardXADataSource:getObjectInstance: instance created");
    return this;
}

From source file:org.codehaus.stomp.jms.ProtocolConverter.java

public ProtocolConverter(InitialContext initialContext, ConnectionFactory connectionFactory,
        XAConnectionFactory xaConnectionFactory, TcpTransport outputHandler) throws NamingException {
    this.noneXAConnectionFactory = connectionFactory;
    this.xaConnectionFactory = xaConnectionFactory;
    this.tcpTransport = outputHandler;
    this.initialContext = initialContext;
    tm = (TransactionManager) initialContext.lookup("java:/TransactionManager");
    outputHandler.setProtocolConverter(this);
}

From source file:de.mpg.escidoc.pubman.multipleimport.ImportProcess.java

/**
 * @param inputStream/*from   w  w w .j  a v a  2  s . c o  m*/
 * @param format
 */
private void initialize(String name, String fileName, File file, Format format, ContextRO escidocContext,
        AccountUserVO user, boolean rollback, DuplicateStrategy duplicateStrategy,
        Map<String, String> configuration) {
    log.startItem("import_process_initialize");
    try {
        log.setMessage(name);
        log.setContext(escidocContext.getObjectId());
        log.setFormat(format.getName());
        this.name = name;
        this.fileName = fileName;
        this.format = format;
        this.escidocContext = escidocContext;
        this.user = user;
        this.transformation = new TransformationBean();
        this.file = file;
        this.rollback = rollback;
        this.duplicateStrategy = duplicateStrategy;
        InitialContext context = new InitialContext();
        this.itemValidating = (ItemValidating) context
                .lookup("java:global/pubman_ear/validation/ItemValidatingBean");
        this.xmlTransforming = (XmlTransforming) context
                .lookup("java:global/pubman_ear/common_logic/XmlTransformingBean");
        this.pubItemDepositing = (PubItemDepositing) context
                .lookup("java:global/pubman_ear/pubman_logic/PubItemDepositingBean");
        this.search = (Search) context.lookup("java:global/pubman_ear/search/SearchBean");
        this.itemContentModel = PropertyReader
                .getProperty("escidoc.framework_access.content-model.id.publication");
        this.configuration = configuration;
    } catch (Exception e) {
        log.addDetail(ErrorLevel.FATAL, "import_process_initialization_failed");
        log.addDetail(ErrorLevel.FATAL, e);
        fail();
    }
    log.finishItem();
}

From source file:org.rhq.enterprise.server.remote.RemoteSafeInvocationHandler.java

public Object invoke(InvocationRequest invocationRequest) throws Throwable {

    if (invocationRequest == null) {
        throw new IllegalArgumentException("InvocationRequest was null.");
    }/* w w w. j  av a2s.  c  o  m*/

    String methodName = null;
    boolean successful = false; // we will flip this to true when we know we were successful
    Object result = null;
    long time = System.currentTimeMillis();

    try {
        InitialContext ic = new InitialContext();

        NameBasedInvocation nbi = ((NameBasedInvocation) invocationRequest.getParameter());
        if (null == nbi) {
            throw new IllegalArgumentException("InvocationRequest did not supply method.");
        }

        methodName = nbi.getMethodName();
        String[] methodInfo = methodName.split(":");

        // Lookup the remote first, if it doesn't exist exit with error.
        // This prevents remote clients from accessing the locals.
        String jndiName = "rhq/" + methodInfo[0];
        Object target = ic.lookup(jndiName + "/remote");
        target = ic.lookup(jndiName + "/local");

        String[] signature = nbi.getSignature();
        int signatureLength = signature.length;
        Class<?>[] sig = new Class[signatureLength];
        for (int i = 0; i < signatureLength; i++) {
            sig[i] = getClass(signature[i]);
        }

        Method m = target.getClass().getMethod(methodInfo[1], sig);
        result = m.invoke(target, nbi.getParameters());
        successful = true;
    } catch (InvocationTargetException e) {
        log.error("Failed to invoke remote request", e);
        return new WrappedRemotingException(e.getTargetException());
    } catch (Exception e) {
        log.error("Failed to invoke remote request", e);
        return new WrappedRemotingException(e);
    } finally {
        if (result != null) {
            // set the strategy guiding how the return information is serialized
            ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION);

            // scrub the return data if Hibernate proxies
            try {
                HibernateDetachUtility.nullOutUninitializedFields(result,
                        HibernateDetachUtility.SerializationType.SERIALIZATION);
            } catch (Exception e) {
                log.error("Failed to null out uninitialized fields", e);
                this.metrics.addData(methodName, System.currentTimeMillis() - time, false);

                return new WrappedRemotingException(e);
            }
        }

        // want to calculate this after the hibernate util so we take that into account too
        long executionTime = System.currentTimeMillis() - time;
        this.metrics.addData(methodName, executionTime, successful);
        if (log.isDebugEnabled()) {
            log.debug("Remote request [" + methodName + "] execution time (ms): " + executionTime);
        }
    }

    return result;
}

From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java

private Properties loadJndiProperties(String jndiResourceName) {
    Properties props = null;// w  ww .j  a  v  a  2s . c om
    InitialContext ic;
    try {
        ic = new InitialContext();
        Object o = ic.lookup(jndiResourceName);

        if (o != null) {
            if (o instanceof Properties) {
                props = (Properties) o;
            } else {
                System.err.println("shiftone resource is not java.util.Properites type!!");
            }
        }
    } catch (NamingException e) {
        log("Unable to process your jndi properties name. Your proxy will not work" + jndiResourceName, e);
    }
    return props;

}

From source file:org.wso2.carbon.attachment.mgt.core.datasource.impl.BasicDataSourceManager.java

private DataSource lookupInJNDI(String remoteObjectName) throws NamingException {
    InitialContext ctx = null;
    try {/*from w  w w  . j  a  va2s.com*/
        if (dataSourceConfig.getDataSourceJNDIRepoInitialContextFactory() != null
                && dataSourceConfig.getDataSourceJNDIRepoProviderURL() != null) {
            Properties jndiProps = new Properties();

            jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                    dataSourceConfig.getDataSourceJNDIRepoInitialContextFactory());
            jndiProps.setProperty(Context.PROVIDER_URL, dataSourceConfig.getDataSourceJNDIRepoProviderURL());

            ctx = new InitialContext(jndiProps);
        } else {
            ctx = new InitialContext();
        }
        return (DataSource) ctx.lookup(remoteObjectName);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception ex1) {
                log.error("Error closing JNDI connection.", ex1);
            }
        }

    }
}

From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java

/**
 * Publish message to given JMS queue/*  w  w  w  . j a  v a  2s . c  o m*/
 *
 * @param nameOfQueue queue name
 * @param userName username
 * @param accessKey access key
 * @param jmsType jms type
 * @param jmsCorrelationID message correlation id
 * @param numberOfMessages number of messages to publish
 * @param message message body
 * @param deliveryMode delivery mode
 * @param priority message priority
 * @param expireTime message expire time
 * @throws QueueManagerException
 */
private void send(String nameOfQueue, String userName, String accessKey, String jmsType,
        String jmsCorrelationID, int numberOfMessages, String message, int deliveryMode, int priority,
        long expireTime) throws QueueManagerException {
    QueueConnectionFactory connFactory;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    QueueSender queueSender = null;
    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, Utils.getTCPConnectionURL(userName, accessKey));
        properties.put(QUEUE_NAME_PREFIX + nameOfQueue, nameOfQueue);
        properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
        InitialContext ctx = new InitialContext(properties);
        connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        Queue queue = (Queue) ctx.lookup(nameOfQueue);
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        queueConnection.start();
        TextMessage textMessage = queueSession.createTextMessage();
        if (queueSender != null && textMessage != null) {
            if (jmsType != null) {
                textMessage.setJMSType(jmsType);
            }
            if (jmsCorrelationID != null) {
                textMessage.setJMSCorrelationID(jmsCorrelationID);
            }

            if (message != null) {
                textMessage.setText(message);
            } else {
                textMessage.setText("Type message here..");
            }

            for (int i = 0; i < numberOfMessages; i++) {
                queueSender.send(textMessage, deliveryMode, priority, expireTime);
            }
        }
    } catch (FileNotFoundException | NamingException | UnknownHostException | XMLStreamException
            | JMSException e) {
        throw new QueueManagerException("Unable to send message.", e);
    } finally {
        try {
            if (queueConnection != null) {
                queueConnection.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue connection", e);
        }
        try {
            if (queueSession != null) {
                queueSession.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue session", e);
        }
        try {
            if (queueSender != null) {
                queueSender.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue sender", e);
        }
    }
}

From source file:org.betaconceptframework.astroboa.engine.service.security.AstroboaLogin.java

private void initializeExternalIdentityStore(String identityStoreLocation) throws FailedLoginException {
    try {//w  ww .j  a va  2s  . co m
        InitialContext context = new InitialContext();

        //First check to see if initial context has been initiated at all
        Hashtable<?, ?> env = context.getEnvironment();
        String initialContextFactoryName = env != null ? (String) env.get(Context.INITIAL_CONTEXT_FACTORY)
                : null;

        if (StringUtils.isNotBlank(initialContextFactoryName)) {

            Object serviceReference = context.lookup(identityStoreLocation);

            if (!(serviceReference instanceof IdentityStore)) {
                if (!identityStoreLocation.endsWith("/local")) {
                    //JNDIName is provided by the user and the object it references is not an instance of IdentityStore.
                    //It is probably an instance of NamingContext which is on top of a local or remote service
                    //Since JNDIName does not end with "/local" , try to locate the local service under the returned NamingContext
                    identityStore = (IdentityStore) context.lookup(identityStoreLocation + "/local");
                } else {
                    throw new Exception("JNDI Name " + identityStoreLocation
                            + " refers to an object whose type is not IdentityStore. Unable to locate. External Identity Store ");
                }
            } else {
                identityStore = (IdentityStore) serviceReference;
            }
            //TODO: It may also be the case another login to the identity store must be done

        } else {
            throw new Exception(
                    "Initial Context Factory Name is blank therefore no initial context is configured, thus any lookup will result in exception."
                            + "External Identity Store " + identityStoreLocation);
        }

    } catch (Exception e) {
        logger.error("", e);
        throw new FailedLoginException("During connection to external Identity Store " + identityStoreLocation);
    }

}

From source file:com.krminc.phr.security.PHRRealm.java

private boolean createDS() {
    if (ds != null)
        return true;

    try {/*from  ww w .  java  2 s . c  o  m*/
        InitialContext ctx = new InitialContext();

        if (ctx == null) {
            log("JNDI problem, Cannot get Initial Context.");
            return false;
        }

        ds = (com.sun.appserv.jdbc.DataSource) ctx.lookup(jdbcResource);

        if (ds == null) {
            log("Unable to lookup datasource.");
            return false;
        }
    } catch (Exception e) {
        log("Exception encountered in database connection initialization.");
        log(e.getMessage());
        return false;
    }
    return true;
}

From source file:com.adaptris.core.SharedComponentListTest.java

public void testRemoveService_unbindsJNDI() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());//from   w  w w.  j  a  v a  2  s  .  co m

    MockService mockService = new MockService();

    adapter.getSharedComponents().addService(mockService);
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        start(adapter);
        Service lookedup = (Service) initialContext.lookup("adapter:comp/env/" + mockService.getUniqueId());
        assertNotNull(lookedup);
        assertEquals(mockService.getUniqueId(), lookedup.getUniqueId());
        adapter.getSharedComponents().removeService(mockService.getUniqueId());
        try {
            initialContext.lookup("adapter:comp/env/" + mockService.getUniqueId());
            fail();
        } catch (NamingException expected) {
        }
    } finally {
        stop(adapter);
    }
}