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.wso2.carbon.uuf.core.API.java

/**
 * Returns the result of the method invocation of the best matched OSGi service.
 *
 * @param serviceClassName  service class name
 * @param serviceMethodName method name/*ww w.j av a  2  s  .  c  om*/
 * @param args              method arguments
 * @return
 */
public static Object callOSGiService(String serviceClassName, String serviceMethodName, Object... args) {
    Object serviceInstance;
    InitialContext initialContext;
    try {
        initialContext = new InitialContext();
    } catch (NamingException e) {
        throw new UUFException(
                "Cannot create the JNDI initial context when calling OSGi service '" + serviceClassName + "'.");
    }

    try {
        serviceInstance = initialContext.lookup("osgi:service/" + serviceClassName);
    } catch (NamingException e) {
        throw new UUFException(
                "Cannot find any OSGi service registered with the name '" + serviceClassName + "'.");
    }

    try {
        return MethodUtils.invokeMethod(serviceInstance, serviceMethodName, args);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("Cannot find any method with the signature '" + serviceMethodName
                + "(" + joinClassNames(args) + ")' in OSGi service '" + serviceInstance.getClass().getName()
                + "' with service class '" + serviceClassName + "'.");
    } catch (Exception e) {
        throw new UUFException("Invoking method '" + serviceMethodName + "(" + joinClassNames(args)
                + ")' on OSGi service '" + serviceInstance.getClass().getName() + "' with service class '"
                + serviceClassName + "' failed.", e);
    }
}

From source file:org.pepstock.jem.jppf.ExecuteManager.java

/**
 * Merges the output results of all task, only if all tasks ended correctly
 *  // www . ja v  a 2  s.c  om
 * @param results list of tasks ended
 * @throws NamingException 
 * @throws IOException 
 * @throws Exception if any exception occurs
 */
private static void mergeExecutionResults(final List<JPPFTask> results)
        throws JPPFMessageException, NamingException, IOException {
    // sorts to be sure
    // task are ordered by position
    Collections.sort(results, new Comparator<JPPFTask>() {
        @Override
        public int compare(JPPFTask o1, JPPFTask o2) {
            return o1.getPosition() - o2.getPosition();
        }
    });
    // process the results. If there is any exception, throws it
    for (JPPFTask task : results) {
        // if the task execution resulted in an exception
        if (task.getException() != null) {
            LogAppl.getInstance().emit(JPPFMessage.JEMJ005E, task.getId(), task.getException().getMessage());
            throw new JPPFMessageException(JPPFMessage.JEMJ005E, task.getException(), task.getId(),
                    task.getException().getMessage());
        }
    }

    LogAppl.getInstance().emit(JPPFMessage.JEMJ024I);

    // gets merge data description
    String mergedDataDescription = JPPFConfiguration.getProperties()
            .getProperty(Keys.JEM_MERGED_DATA_DESCRIPTION);
    InitialContext ic = ContextUtils.getContext();
    // gets outputstream by JNDI
    Object object = ic.lookup(mergedDataDescription);
    OutputStream os = (OutputStream) object;
    BufferedOutputStream bos = new BufferedOutputStream(os);
    try {
        // scans for merging
        for (JPPFTask task : results) {
            // gets temporary file written by task
            File file = TEMPORARY_FILES.get(task.getPosition());
            // reads and writes data
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileUtils.copyFile(file, baos);
            bos.write(baos.toByteArray());

            LogAppl.getInstance().emit(JPPFMessage.JEMJ025I, file.getAbsolutePath(), baos.size());
            baos.close();
        }
        LogAppl.getInstance().emit(JPPFMessage.JEMJ026I);
    } finally {
        // close
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}

From source file:org.jbpm.bpel.integration.jms.IntegrationControl.java

private static Context getJmsContext(InitialContext initialContext) {
    Context jmsContext;//from  ww w .ja v a2s . co m
    try {
        jmsContext = (Context) initialContext.lookup(JMS_CONTEXT);
        log.debug("retrieved jms context: " + JMS_CONTEXT);
    } catch (NamingException e) {
        log.debug("jms context not found: " + JMS_CONTEXT);
        jmsContext = initialContext;
        log.debug("fell back on initial context");
    }
    return jmsContext;
}

From source file:org.xsystem.sql2.http.PageServlet2.java

public static <T> T getJndiResource(String path, Class<T> type) {
    try {/*from w  ww .  j a  v  a  2s .  com*/
        InitialContext cxt = new InitialContext();

        Object ret = cxt.lookup(path);

        return (T) ret;
    } catch (NamingException ex) {
        throw new Error(ex);
    }
}

From source file:org.hyperic.hq.plugin.tomcat.JBossUtil.java

public static MBeanServerConnection getMBeanServerConnection(Properties config)
        throws NamingException, RemoteException {
    MBeanServerConnection adaptor;

    Properties props = new Properties();

    for (int i = 0; i < NAMING_PROPS.length; i++) {
        props.setProperty(NAMING_PROPS[i][0], NAMING_PROPS[i][1]);
    }//from   w w w.j a v  a2s.  c o  m

    props.putAll(config);
    props.put("java.naming.provider.url", config.get("jmx.url"));

    if (props.getProperty(Context.SECURITY_PRINCIPAL) != null) {
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    }

    InitialContext ctx = new InitialContext(props);

    try {
        Object o = ctx.lookup(props.getProperty(PROP_NAMING_CONNECTOR));
        log.debug("=> " + Arrays.asList(o.getClass().getInterfaces()));
        adaptor = (MBeanServerConnection) o;
    } finally {
        ctx.close();
    }

    return adaptor;
}

From source file:org.kie.server.integrationtests.shared.KieServerBaseIntegrationTest.java

protected static KieServicesConfiguration createKieServicesJmsConfiguration() {
    try {/*  w  w w. j  a  v a 2 s .  c o  m*/
        InitialContext context = TestConfig.getInitialRemoteContext();

        Queue requestQueue = (Queue) context.lookup(TestConfig.getRequestQueueJndi());
        Queue responseQueue = (Queue) context.lookup(TestConfig.getResponseQueueJndi());
        ConnectionFactory connectionFactory = (ConnectionFactory) context
                .lookup(TestConfig.getConnectionFactory());

        KieServicesConfiguration jmsConfiguration = KieServicesFactory.newJMSConfiguration(connectionFactory,
                requestQueue, responseQueue, TestConfig.getUsername(), TestConfig.getPassword());

        return jmsConfiguration;
    } catch (Exception e) {
        throw new RuntimeException("Failed to create JMS client configuration!", e);
    }
}

From source file:com.jaspersoft.jasperserver.war.common.JasperServerUtil.java

public static Connection getJSDatabaseConnection()
        throws ClassNotFoundException, SQLException, NamingException {
    boolean sqlExcpn = false;
    Connection con = null;// w  w  w  . ja v a2  s. co  m
    try {
        InitialContext cxt = new InitialContext();
        DataSource ds = (DataSource) cxt.lookup(JasperServerConstImpl.getJSDataSrc());
        con = ds.getConnection();
        if (log.isDebugEnabled()) {
            log.debug(
                    "getConnection successful at com.jaspersoft.jasperserver.war.common.JasperServerUtil.getJSDatabaseConnection");
        }
        return con;
    } catch (Exception _ex) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "getConnection FAILED at com.jaspersoft.jasperserver.war.common.JasperServerUtil.getJSDatabaseConnection: "
                            + _ex.getMessage());
        }
        if (log.isErrorEnabled())
            log.error(_ex, _ex);
        sqlExcpn = true;
    } finally {
        if (sqlExcpn) {
            Class.forName(JasperServerConstImpl.getJSConnector());
            con = DriverManager.getConnection(JasperServerConstImpl.getJSUrl(),
                    JasperServerConstImpl.getJSDbUser(), JasperServerConstImpl.getJSDbPasswd());
            return con;
        }
    }
    return con;
}

From source file:com.openkm.jcr.JCRUtils.java

/**
 * Get JCR Session// w  w w .  ja  v  a 2 s.c  o  m
 */
public static Session getSession()
        throws javax.jcr.LoginException, javax.jcr.RepositoryException, DatabaseException {
    Object obj = null;

    try {
        InitialContext ctx = new InitialContext();
        Subject subject = (Subject) ctx.lookup("java:comp/env/security/subject");
        obj = Subject.doAs(subject, new PrivilegedAction<Object>() {
            public Object run() {
                Session s = null;

                try {
                    s = DirectRepositoryModule.getRepository().login();
                } catch (javax.jcr.LoginException e) {
                    return e;
                } catch (javax.jcr.RepositoryException e) {
                    return e;
                }

                return s;
            }
        });
    } catch (NamingException e) {
        throw new javax.jcr.LoginException(e.getMessage());
    }

    if (obj instanceof javax.jcr.LoginException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.RepositoryException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.Session) {
        Session session = (javax.jcr.Session) obj;
        log.debug("#{} - {} Create session {} from {}", new Object[] { ++sessionCreationCount, ++activeSessions,
                session, StackTraceUtils.whoCalledMe() });
        DirectAuthModule.loadUserData(session);
        return session;
    } else {
        return null;
    }
}

From source file:com.ikon.module.jcr.stuff.JCRUtils.java

/**
 * Get JCR Session/*from  www  .  j a  va2  s  . c  o  m*/
 */
public static Session getSession()
        throws javax.jcr.LoginException, javax.jcr.RepositoryException, DatabaseException {
    Subject subject = null;
    Object obj = null;

    // Resolve subject
    // Subject userSubject=(Subject)PolicyContext.getContext("javax.security.auth.Subject.container");
    if (EnvironmentDetector.isServerJBoss()) {
        try {
            InitialContext ctx = new InitialContext();
            subject = (Subject) ctx.lookup("java:/comp/env/security/subject");
            ctx.close();
        } catch (NamingException e) {
            throw new javax.jcr.LoginException(e.getMessage());
        }
    } else if (EnvironmentDetector.isServerTomcat()) {
        subject = Subject.getSubject(AccessController.getContext());
    }

    // Obtain JCR session
    if (subject != null) {
        obj = Subject.doAs(subject, new PrivilegedAction<Object>() {
            public Object run() {
                Session s = null;

                try {
                    s = JcrRepositoryModule.getRepository().login();
                } catch (javax.jcr.LoginException e) {
                    return e;
                } catch (javax.jcr.RepositoryException e) {
                    return e;
                }

                return s;
            }
        });
    }

    // Validate JCR session
    if (obj instanceof javax.jcr.LoginException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.RepositoryException) {
        throw (javax.jcr.RepositoryException) obj;
    } else if (obj instanceof javax.jcr.Session) {
        Session session = (javax.jcr.Session) obj;
        log.debug("#{} - {} Create session {} from {}", new Object[] { ++sessionCreationCount, ++activeSessions,
                session, StackTraceUtils.whoCalledMe() });
        JcrAuthModule.loadUserData(session);
        return session;
    } else {
        return null;
    }
}

From source file:org.firstopen.singularity.util.JMSUtil.java

public static void deliverMessageToTopic(String host, String topicName, String xml) {
    log.debug("IntegrationMod.deliverMessageToQueue queueName = " + topicName + " and doc = " + xml);

    char test = topicName.charAt(0);

    if (test == '/')
        topicName = topicName.substring(1);

    try {/* ww  w. ja  v  a  2s . c  o  m*/

        InitialContext context = JNDIUtil.getInitialContext(host);

        Connection connection = null;
        Session session = null;
        MessageProducer publisher = null;
        ConnectionFactory tcf = (ConnectionFactory) context.lookup("ConnectionFactory");

        Topic topic = (Topic) context.lookup(topicName);

        connection = tcf.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        publisher = session.createProducer(topic);

        TextMessage message = session.createTextMessage();

        log.debug("message value is -> " + xml);

        message.setText(xml);

        publisher.send(message);

    } catch (Exception e) {
        log.error("unable to send message on topic", e);
    } finally {

    }
}