Fail to connect to server when creating an EJBClient - java

I have an EJB Client as follow:
public class EJBTestClient {
public static void main(String[] args) throws NamingException {
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put(Context.PROVIDER_URL,"http-remoting://localhost:8080"); // create a context passing these properties Context ctx = new InitialContext(jndiProps);
jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
InitialContext context = new InitialContext(jndiProps);
System.out.println("Context lookup finished");
MyFirstEJBRemote proxy = (MyFirstEJBRemote) context.lookup("MyFirstEJB/Remote");
System.out.println(proxy.getClass().toString());
System.out.println(proxy.getDescription());
proxy.doSomething();
}
}
but when I run the program it showed an Exception javax.naming.CommunicationException: Failed to connect to any server. Servers tried: [http-remoting://127.0.0.1:8080 (java.io.IOException: JBREM000202: Abrupt close on Remoting connection 0c05035f to /127.0.0.1:8080 of endpoint "config-based-naming-client-endpoint" <2ce1483d>)]
And my EJB Container named EJBTestApp which contains MyFirstEJB Stateless Session Bean and MyFirstEJBRemote Interface:
#Stateless
#Remote
public class MyFirstEJB implements MyFirstEJBRemote {
private Logger log = Logger.getLogger(MyFirstEJB.class);
/**
* Default constructor.
*/
public MyFirstEJB() {
// TODO Auto-generated constructor stub
}
#Override
public void doSomething() {
log.info("doSomething() has been call");
}
#Override
public String getDescription() {
return "getDescription() has returned some values";
}
}
And this EJB Container is deployed on Wildfly 10 under localhost:8080. Can anyone help me how to solve this problem

Try to set
jndiProps.put(jboss.naming.client.ejb.context, true);
Add the libraries from wildfly10directory/bin/client to the project
If doesn't working, try to set lookup to:
MyFirstEJBRemote proxy = (MyFirstEJBRemote) context.lookup("MyFirstEJB/BeanName!path_to_package_remote_bean");

Related

Init servlet instantly after the embedded jetty server starts

I need to run my own logic after the jetty embedded server starts. I'm not starting it from the main class due to classloader issues. An ideal solution seemed to be running my server logic from a servlet initialization. But the init function and also the constructor is not called after the jetty server start. An instance of the servlet is being created during the first HTTP request. Is it possible to tell jetty to initialize my servlet instantly or do I really need to load all classes with my custom classloader and then start the jetty server?
This is the main class:
public class ServerLauncher {
public static void main(String[] args) {
JettyServerLauncher.launchHttp("target/server.war", "0.0.0.0", 8080);
// Starting my own logic here is causing classloader issues, because WebSocket classes are loaded by other classloader than my classes, that is the reason why I moved it into the servlet
}
}
This is my jetty embedded server launcher:
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.plus.webapp.EnvConfiguration;
import org.eclipse.jetty.plus.webapp.PlusConfiguration;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.webapp.*;
import java.io.File;
public class JettyServerLauncher {
private static boolean isHttps;
private static File keyStoreFile;
private static String warPath;
private static String host;
private static int httpPort;
private static int httpsPort;
private static String keyStorePath;
private static String keyStorePass;
private static boolean needClientAuth;
public static void launchHttp(String warPath, String host, int httpPort) {
JettyServerLauncher.isHttps = false;
JettyServerLauncher.warPath = warPath;
JettyServerLauncher.host = host;
JettyServerLauncher.httpPort = httpPort;
launch();
}
public static void launchHttps(String warPath, String host, String keyStorePath, String keyStorePass, int httpPort, int httpsPort, boolean needClientAuth) {
JettyServerLauncher.isHttps = true;
JettyServerLauncher.warPath = warPath;
JettyServerLauncher.host = host;
JettyServerLauncher.httpPort = httpPort;
JettyServerLauncher.httpsPort = httpsPort;
JettyServerLauncher.keyStorePath = keyStorePath;
JettyServerLauncher.keyStorePass = keyStorePass;
JettyServerLauncher.needClientAuth = needClientAuth;
launch();
}
private static void launch() {
Server server = null;
try {
System.out.println("Initializing jetty server...");
if (isHttps) loadKeyStores(keyStorePath);
// Create jetty server
server = new Server(httpPort);
// Setup connectors
Connector httpConnector = createHttpConnector(server, host, httpPort, httpsPort);
if (isHttps) {
Connector httpsConnector = createHttpsConnector(server, host, httpsPort, keyStoreFile, keyStorePass, needClientAuth);
server.setConnectors(new Connector[]{httpConnector, httpsConnector});
} else {
server.setConnectors(new Connector[]{httpConnector});
}
// Add handlers for requests to collection of handlers
HandlerCollection handlers = new ContextHandlerCollection();
//handlers.addHandler(new SecuredRedirectHandler());
handlers.addHandler(createWebApp(warPath));
server.setHandler(handlers);
server.dump();
System.out.println("Starting jetty websocket and web server...");
server.start();
server.join();
} catch (Throwable t) {
t.printStackTrace();
System.err.println("Server initialization failed!");
System.out.println("Stopping the server...");
try {
server.stop();
} catch (Exception ignored) {}
}
}
private static WebAppContext createWebApp(String warPath) {
WebAppContext webApp = new WebAppContext();
webApp.setContextPath("/");
webApp.setWar(new File(warPath).getAbsolutePath());
webApp.setThrowUnavailableOnStartupException(true);
// Enable support for JSR-356 javax.websocket
webApp.setAttribute("org.eclipse.jetty.websocket.jsr356", Boolean.TRUE);
// Jetty will scan project for configuration files... This is very important for loading websocket endpoints by annotation automatically
webApp.setConfigurations(new Configuration[] {
new AnnotationConfiguration(),
new WebInfConfiguration(),
new WebXmlConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new EnvConfiguration(),
new PlusConfiguration(),
new JettyWebXmlConfiguration()
});
return webApp;
}
private static Connector createHttpConnector(Server server, String host, int httpPort, int httpsPort) {
HttpConfiguration httpConf = new HttpConfiguration();
httpConf.setSendServerVersion(false);
if (isHttps) httpConf.setSecurePort(httpsPort);
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConf));
connector.setPort(httpPort);
connector.setHost(host);
return connector;
}
private static Connector createHttpsConnector(Server server, String host, int httpsPort, File keyStoreFile, String keyStorePass, boolean needClientAuth) {
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath(keyStoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword(keyStorePass);
sslContextFactory.setNeedClientAuth(needClientAuth);
// Setup HTTPS Configuration
HttpConfiguration httpsConf = new HttpConfiguration();
httpsConf.setSendServerVersion(false);
httpsConf.setSecureScheme("https");
httpsConf.setSecurePort(httpsPort);
httpsConf.setOutputBufferSize(32768);
httpsConf.setRequestHeaderSize(8192);
httpsConf.setResponseHeaderSize(8192);
httpsConf.addCustomizer(new SecureRequestCustomizer()); // adds ssl info to request object
// Establish the HTTPS ServerConnector
ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConf));
httpsConnector.setPort(httpsPort);
httpsConnector.setHost(host);
return httpsConnector;
}
private static void loadKeyStores(String keyStorePath) {
keyStoreFile = new File(keyStorePath);
if (!keyStoreFile.exists()) {
throw new RuntimeException("Key store file does not exist on path '"+keyStoreFile.getAbsolutePath()+"'");
}
}
}
This is my servlet:
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
#WebServlet(displayName = "MyServlet", urlPatterns = { "/*" })
public class MyServlet extends HttpServlet {
#Override
public void init() {
// start new Thread with my server logic here (avoid classloader issues)
// but at least one HTTP request is needed to start it from this place
}
#Override
public void destroy() {}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
// handle http requests
}
}
I found this on google, but I don't know how to use it in my case. https://www.eclipse.org/lists/jetty-users/msg02109.html
Thank you for your help.
If you just want the servlet to init on startup, then use the annotation ...
#WebServlet(
displayName = "MyServlet",
urlPatterns = { "/*" },
loadOnStartup = 1
)
Alternatively, you could register a javax.servlet.ServletContextListener that does the contextInitialized(ServletContextEvent sce) behavior you need.
Tip: if you define a custom the ServletContextListener for embedded use, you can just add it to the WebAppContext from outside of the WAR you are using.
Example:
webApp.getServletHandler()
.addListener(new ListenerHolder(MyContextListener.class));
Also, this block of code is wrong and shows you copy/pasted from an old code snippet (this technique is from circa Jetty 9.0.0 thru 9.2.16)
webApp.setConfigurations(new Configuration[] {
new AnnotationConfiguration(),
new WebInfConfiguration(),
new WebXmlConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new EnvConfiguration(),
new PlusConfiguration(),
new JettyWebXmlConfiguration()
});
In Jetty 9.4.x you never directly configure the webApp.setConfigurations() like that, use the Configuration.ClassList defined on the server instead ...
From: 9.4.44.v20210927 - embedded/LikeJettyXml.java
Configuration.ClassList classlist = Configuration.ClassList
.setServerDefault(server);
classlist.addAfter(
"org.eclipse.jetty.webapp.FragmentConfiguration",
"org.eclipse.jetty.plus.webapp.EnvConfiguration",
"org.eclipse.jetty.plus.webapp.PlusConfiguration");
classlist.addBefore(
"org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
"org.eclipse.jetty.annotations.AnnotationConfiguration");
Starting in Jetty 10.0.0, you never specify the Configuration classes, or their order, as the existence of the support JAR is enough, and internally in Jetty 10 the order is resolved properly.
But if you need to add Configurations (due to non-standard deployment concerns where the Java ServiceLoader doesn't work), then you still configure the additional Configurations on the server object (but without worrying about the correct order for those configurations)
From 10.0.7 - embedded/demos/LikeJettyXml.java
Configurations.setServerDefault(server).add(
new EnvConfiguration(),
new PlusConfiguration(),
new AnnotationConfiguration()
);

Mapping commonj work manager with weblogic work manager fails with NameNotFoundException

I have a (weblogic) singleton service that uses the commonj workManagerTaskExecutor to execute a task. I also have a work manager defined in my weblogic console with the name MyWorkManager. Now I am trying to map the commonj Work manager to the work manager in Weblogic so that I can use it in the workManagerTaskExecutor. But lookup of this workmanager fails in my application code with NameNotFoundException unable to find the workmanager.
I tried iterating through the initial context object and couldn't find the workmanager registered in it either.
I am using Weblogic 10.3 and am completely new to this. What am I doing wrong? please help me out.
public class MySingletonService implements weblogic.cluster.singleton.SingletonService {
private ApplicationContext applicationContext;
private void loadApplicationContext() {
applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
}
public MySingletonService() {
System.out.println("MySingletonService Object Initialized...");
}
public void activate() {
try {
loadApplicationContext();
Runnable xy = new Runnable() {
public void run() {
if (applicationContext != null) {
runSomething();
} else {
System.out.println("Application context is not initialized");
}
}
};
InitialContext ic = new InitialContext();
WorkManager wm = (WorkManager)ic.lookup("java:comp/env/wm/MyWorkManager"); // this fails
WorkManagerTaskExecutor taskExecutor = new WorkManagerTaskExecutor();
taskExecutor.setWorkManager(wm);
taskExecutor.execute(xy);
}
catch (Exception ex) {
ex.printStackTrace();
deactivate();
throw new RuntimeException("MySingletonService.activate()",ex);
}
}
public void deactivate() {
doSomething();
}
}
weblogic-application.xml
<work-manager>
<name>wm/MyWorkManager</name>
</work-manager>
web.xml
<resource-ref>
<res-ref-name>wm/MyWorkManager</res-ref-name>
<res-type>commonj.work.WorkManager</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

Injecting objects into jersey ressources

Can't figure out how to make an object created at jersey-server start accessible in jersey resources. Basically, what i want to do is to inject a Database context into jersey resources.
JerseyServer:
public boolean startServer(String keyStoreServer, String trustStoreServer) {
//Check if GraphDb is setup
if (gdbLogic == null) {
//FIXME - maybe throw an exception here?
return false;
}
// create a resource config that scans for JAX-RS resources and providers
// in org.developer_recommender.server package
final org.glassfish.jersey.server.ResourceConfig rc = new org.glassfish.jersey.server.ResourceConfig().packages("org.developer_recommender.server").register(createMoxyJsonResolver());
WebappContext context = new WebappContext("context");
ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
//TODO: value setzen
registration.setInitParameter("jersey.config.server.provider.packages", "org.developer_recommender.server.service;org.developer_recommender.server.auth");
registration.setInitParameter(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, SecurityFilter.class.getName());
SSLContextConfigurator sslContext = new SSLContextConfigurator();
sslContext.setKeyStoreFile(keyStoreServer);
sslContext.setTrustStoreFile(trustStoreServer);
//TODO -
sslContext.setKeyStorePass("123456");
sslContext.setTrustStorePass("123456");
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
HttpServer server = null;
try{
SSLEngineConfigurator sslec = new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(true);
server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI()/*URI.create(BASE_URI)*/, rc, true , sslec);
System.out.println("Jersey app started. Try out " + BASE_URI);
context.deploy(server);
return true;
} catch(Exception e ){
System.out.println(e.getMessage());
}
return false;
Service:
public class Service {
#Inject
protected GDBLogic gbdLogic;
}
So i want the instance of GDBLogic in startServer to be accessible in Jersey Resources. Any advice on how to achieve this?
I don't want to use a static field for GDBLogic to achieve this, cause we will have a minimum of two different Database configurations.
You need to set up the instance binding in order to get the injection to work. You can do that by adding an HK2 abstract binder to your resource config:
final ResourceConfig rc = new ResourceConfig()
.packages("org.developer_recommender.server")
.register(createMoxyJsonResolver())
.register(new AbstractBinder()
{
#Override
protected void configure()
{
bind(gdbLogic).to(GDBLogic.class);
}
});

MBeans operaciones error Weblogic

I'm trying to make an Mbeans which can change a few parameters in runtime but when trying to invoke an operation the following error occurs:
java.rmi.UnmarshalException: Error unmarshaling return; nested exception is: java.lang.ClassNotFoundException: weblogic.management.NoAccessRuntimeException > (no security manager: RMI class loader disabled)
I am using weblogic y jconsole.
code:
public class MyMBeanListener extends ApplicationLifecycleListener {
public void postStart(weblogic.application.ApplicationLifecycleEvent p1) {
try {
ObjectName mymbean =
new ObjectName("monitor:Name=MyMonitor,Type=MyMonitorMBean");
InitialContext ctx = new InitialContext();
MBeanServer server = (MBeanServer)ctx.lookup("java:comp/jmx/runtime");
MyMonitor monitor = new MyMonitor();
server.registerMBean(monitor, mymbean);
System.out.println(" MBean registered successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
public interface MyMonitorMBean {
public void setMessage(String msg);
}
public class MyMonitor implements MyMonitorMBean {
private String _con;
#Override
public synchronized void setMessage(String msg) {
_con = msg;
}
}
If you put Weblogic's JARs in your classpath it should work or at least you will get rid of the ClassNotFoundException
I would put weblogic.jar or wlfullclient.jar (if you have it), try running JConsole in a way similar to this:
jconsole -J-Djava.class.path="Weblogic Lib Folder\weblogic.jar"

Remote Connect to Jboss Application-Server - NamingIOException cause by ClassNotFound

First of all this is my first question on StackOverflow and I'm an Intern in a Company in Germany, so My English is a little broken and my Knowledge might be limited.
I Try to connectio to a Jboss 6.1.0 eap remotely.
I'm using Eclipse as IDE for the EJB and the EAR but I run the Jboss form cmd
My ejb3 definition look like that:
package de.jack;
import javax.ejb.Remote;
#Remote
public interface TestServiceRemote {
public void sayRemote();
}
package de.jack;
import javax.ejb.Stateless;
/**
* Session Bean implementation class TestService
*/
#Stateless
public class TestService implements TestServiceRemote {
public TestService() { }
public void sayRemote() {
System.out.println("\n\nHello");
}
}
After gernerating the .ear file I deploy them in the JBoss AS and all that works fine
I can view them in the browser under localhost:9990 and check that they are deployed
Now to the Part where I fail - the Client:
public static void main(String argv[]){
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
props.put(Context.PROVIDER_URL, "remote://localhost:4447");
props.put(Context.SECURITY_PRINCIPAL, "jack");
props.put(Context.SECURITY_CREDENTIALS, "katze");
props.put("jboss.naming.client.ejb.context", true);
// create a context passing these properties
InitialContext context;
Object test = null;
try {
context = new InitialContext(props);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
try {
test =
context.lookup("ConnectorBean/TestService!de.jack.TestServiceRemote");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
On Run I get the exception:
org.jboss.naming.remote.protocol.NamingIOException: Failed to lookup [Root exception is java.io.IOException: java.lang.ClassNotFoundException: de.jack.TestServiceRemote]
at org.jboss.naming.remote.client.ClientUtil.namingException(ClientUtil.java:49)
at org.jboss.naming.remote.protocol.v1.Protocol$1.execute(Protocol.java:104)
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1.lookup(RemoteNamingStoreV1.java:95)
at org.jboss.naming.remote.client.HaRemoteNamingStore$1.operation(HaRemoteNamingStore.java:245)
...
I not sure what exactly I did wrong
one reason could be that I do not have admin-rights on the maschine or I mixed up the properties on Client side
Sorry for my bad english and I'm very thankful for any help!
modify TestService class
#Stateless
#Remote(TestServiceRemote.class)
public class TestService implements TestServiceRemote {
public TestService() { }
public void sayRemote() {
System.out.println("\n\nHello");
}
}
ensure remote client has a reference of TestServiceRemote.class
change lookup jndi name
// The app name is the application name of the deployed EJBs. This is typically the ear name
// without the .ear suffix. However, the application name could be overridden in the application.xml of the
// EJB deployment on the server.
// Since we haven't deployed the application as a .ear, the app name for us will be an empty string
final String appName = "";
// This is the module name of the deployed EJBs on the server. This is typically the jar name of the
// EJB deployment, without the .jar suffix, but can be overridden via the ejb-jar.xml
// In this example, we have deployed the EJBs in a jboss-as-ejb-remote-app.jar, so the module name is
// jboss-as-ejb-remote-app
final String moduleName = "jboss-as-ejb-remote-app";
// AS7 allows each deployment to have an (optional) distinct name. We haven't specified a distinct name for
// our EJB deployment, so this is an empty string
final String distinctName = "";
// The EJB name which by default is the simple class name of the bean implementation class
final String beanName = TestService.class.getSimpleName();
// the remote view fully qualified class name
final String viewClassName = TestServiceRemote.class.getName();
String jndiName= "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName;
TestServiceRemote service = (TestServiceRemote)context.lookup(jndiName);
Detail please reffer: https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI
Server log should show correct global JNDI name for the bean. It should be like foo/EJB-NAME/remote. Then you need change it in context.lookup("ConnectorBean/TestService!de.jack.TestServiceRemote").
Please check -
http://docs.jboss.org/ejb3/docs/tutorial/1.0.7/html/JNDI_Bindings.html

Categories