|
| 1 | +package com.baeldung.ejb.client; |
| 2 | + |
| 3 | +import java.util.Properties; |
| 4 | + |
| 5 | +import javax.naming.Context; |
| 6 | +import javax.naming.InitialContext; |
| 7 | +import javax.naming.NamingException; |
| 8 | + |
| 9 | +import com.baeldung.ejb.tutorial.HelloWorld; |
| 10 | + |
| 11 | +public class EJBClient { |
| 12 | + |
| 13 | + public EJBClient() { |
| 14 | + } |
| 15 | + |
| 16 | + private Context context = null; |
| 17 | + |
| 18 | + public String getEJBRemoteMessage() { |
| 19 | + EJBClient main = new EJBClient(); |
| 20 | + try { |
| 21 | + // 1. Obtaining Context |
| 22 | + main.createInitialContext(); |
| 23 | + // 2. Generate JNDI Lookup name and caste |
| 24 | + HelloWorld helloWorld = main.lookup(); |
| 25 | + return helloWorld.getHelloWorld(); |
| 26 | + } catch (NamingException e) { |
| 27 | + e.printStackTrace(); |
| 28 | + return ""; |
| 29 | + } finally { |
| 30 | + try { |
| 31 | + main.closeContext(); |
| 32 | + } catch (NamingException e) { |
| 33 | + e.printStackTrace(); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public HelloWorld lookup() throws NamingException { |
| 39 | + |
| 40 | + // The app name is the EAR name of the deployed EJB without .ear suffix. |
| 41 | + // Since we haven't deployed the application as a .ear, the app name for |
| 42 | + // us will be an empty string |
| 43 | + final String appName = ""; |
| 44 | + final String moduleName = "remote"; |
| 45 | + final String distinctName = ""; |
| 46 | + final String beanName = "HelloWorld"; |
| 47 | + final String viewClassName = HelloWorld.class.getName(); |
| 48 | + final String toLookup = "ejb:" + appName + "/" + moduleName |
| 49 | + + "/" + distinctName + "/" + beanName + "!" + viewClassName; |
| 50 | + return (HelloWorld) context.lookup(toLookup); |
| 51 | + } |
| 52 | + |
| 53 | + public void createInitialContext() throws NamingException { |
| 54 | + Properties prop = new Properties(); |
| 55 | + prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); |
| 56 | + prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); |
| 57 | + prop.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080"); |
| 58 | + prop.put(Context.SECURITY_PRINCIPAL, "pritamtest"); |
| 59 | + prop.put(Context.SECURITY_CREDENTIALS, "iamtheki9g"); |
| 60 | + prop.put("jboss.naming.client.ejb.context", false); |
| 61 | + |
| 62 | + context = new InitialContext(prop); |
| 63 | + } |
| 64 | + |
| 65 | + public void closeContext() throws NamingException { |
| 66 | + if (context != null) { |
| 67 | + context.close(); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments