I want to create a WebSocket based on an example. The only spin is that I'm running my application in embedded tomcat.
package com.test.websocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
public class WebSocketTest extends AbstractWebSocketHandler {
private static Logger logger = LoggerFactory.getLogger(WebSocketTest.class);
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.debug("Recieved websocket message: " + message);
session.sendMessage(new TextMessage("thanks"));
}
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
logger.info("WebSocket connection established!");
}
#Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
logger.info("WebSocket connection closed!");
}
}
Configuration(websocket.spring.xml):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd">
<websocket:handlers>
<websocket:mapping path="/socket" handler="webSocketHandler"/>
</websocket:handlers>
<bean id="webSocketHandler" class="com.test.websocket.WebSocketTest"/>
</beans>
Servlet mapping is at /websocket/*
From the log It seems like the spring-websocket is initialized successfully however I'm getting this error, when I try to connect to the websocket.
Servlet.service() for servlet [spring-websocket] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.socket.server.HandshakeFailureException: Uncaught failure for request http://localhost:9876/websocket/socket; nested exception is java.lang.IllegalArgumentException: No 'javax.websocket.server.ServerContainer' ServletContext attribute. Are you running in a Servlet container that supports JSR-356?] with root cause
Dependencies are: tomcat-embed-core, tomcat-embed-websocket, tomcat-juli and because of (Spring websocket example - error - Are you running in a Servlet container that supports J SR-356?) javax.websocket-api and tomcat-websocket
What am I missing?
Thanks in advance!
Maybe i found a solution to your problem.
You need to use WsSci servlet container initializer to the embedded tomcat context:
context.addServletContainerInitializer(new WsSci(), null);
https://github.com/spring-projects/spring-boot/issues/439
Related
Exception in thread "main"
org.springframework.beans.factory.BeanDefinitionStoreException: I/O
failure during classpath scanning; nested exception is
org.springframework.core.NestedIOException: ASM ClassReader failed to
parse class file - probably due to a new Java class file version that
isn't supported yet: class path resource
[springanotaciones/ComercialExp.class]; nested exception is
java.lang.IllegalArgumentException: Unsupported class file major
version 60
package springanotaciones;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class play {
public static void main(String[] args) {
ClassPathXmlApplicationContext contexto = new
ClassPathXmlApplicationContext("applicationContext.xml");
Empleado pipi = contexto.getBean("comercial", Empleado.class);
System.out.println(pipi.setInforme());
}
}
package springanotaciones;
public interface Empleado {
public String setTarea();
public String setInforme();
}
package springanotaciones;
import org.springframework.stereotype.Component;
#Component("comercial")
public class ComercialExp implements Empleado {
#Override
public String setTarea() {
return"vender y vernder";
}
#Override
public String setInforme() {
return"El comercial genero un informe";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
">
<context:component-scan base-package="springanotaciones"></context:component-scan>
</beans>
Right,the problem was the JDK16ยก
finally I change de JDK 16 for the JDK 14 for this project and is working, maybe this help someone in the future.
Sorry for my inglish.
I have downloaded dukeetf2 tutorial of oracle but it does not work (when I run it nothing happens although it is supposed to update the page every second). It seems the browser is sending the requests but does not update the page as I have the following results in console.
SEVERE: in init
INFO: Initializing EJB.
INFO: JTS5014: Recoverable JTS instance, serverId = [100]
INFO: WEB0671: Loading application [org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT] at [/dukeetf2]
INFO: CORE10010: Loading application org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT done in 6,908 ms
INFO: GlassFish Server Open Source Edition 3.1.2.2 (5) startup time : Felix (2,692ms), startup services(117,706ms), total(120,398ms)
INFO: JMX005: JMXStartupService had Started JMXConnector on JMXService URL service:jmx:rmi://Workstation9:8686/jndi/rmi://Workstation9:8686/jmxrmi
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
INFO: WEB0169: Created HTTP listener [http-listener-1] on host/port [0.0.0.0:8080]
INFO: Grizzly Framework 1.9.50 started in: 2ms - bound to [0.0.0.0:8080]
INFO: [2] timers deleted for id: 90756774797901824
INFO: EJB5181:Portable JNDI names for EJB PriceVolumeBean: [java:global/org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT/PriceVolumeBean, java:global/org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT/PriceVolumeBean!javaeetutorial.web.dukeetf2.PriceVolumeBean]
SEVERE: in init
INFO: Initializing EJB.
INFO: WEB0671: Loading application [org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT] at [/dukeetf2]
INFO: org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT was successfully deployed in 348 milliseconds.
INFO: WEB0169: Created HTTP listener [http-listener-2] on host/port [0.0.0.0:8181]
INFO: Grizzly Framework 1.9.50 started in: 3ms - bound to [0.0.0.0:8181]
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
.....
I have downloaded the dependencies and currently have, javaee-api-7.0.jar, activation-1.1.jar and javax.mail-1.5.0.jar in my dependencies directory.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>websocket</artifactId>
<groupId>org.glassfish.javaeetutorial</groupId>
<version>7.0.4-SNAPSHOT</version>
</parent>
<groupId>org.glassfish.javaeetutorial</groupId>
<artifactId>dukeetf2</artifactId>
<packaging>war</packaging>
<name>dukeetf2</name>
</project>
index.html
<!DOCTYPE html>
<html>
<head>
<title>Duke's WebSocket ETF</title>
<link rel="stylesheet" type="text/css" href="resources/css/default.css" />
<script type="text/javascript">
var wsocket;
function connect() {
wsocket = new WebSocket("ws://localhost:8080/dukeetf2/dukeetf");
wsocket.onmessage = onMessage;
}
function onMessage(evt) {
var arraypv = evt.data.split(",");
document.getElementById("price").innerHTML = arraypv[0];
document.getElementById("volume").innerHTML = arraypv[1];
}
window.addEventListener("load", connect, false);
</script>
</head>
<body>
<h1>Duke's WebSocket ETF</h1>
<table>
<tr>
<td width="100">Ticker</td>
<td align="center">Price</td>
<td id="price" style="font-size:24pt;font-weight:bold;">--.--</td>
</tr>
<tr>
<td style="font-size:18pt;font-weight:bold;" width="100">DKEJ</td>
<td align="center">Volume</td>
<td id="volume" align="right">--</td>
</tr>
</table>
</body>
</html>
ETFEndpoint.java
package javaeetutorial.web.dukeetf2;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/* WebSocket version of the dukeetf example */
#ServerEndpoint("/dukeetf")
public class ETFEndpoint {
private static final Logger logger = Logger.getLogger("ETFEndpoint");
/* Queue for all open WebSocket sessions */
static Queue<Session> queue = new ConcurrentLinkedQueue<>();
/* PriceVolumeBean calls this method to send updates */
public static void send(double price, int volume) {
System.err.println("in send");
String msg = String.format("%.2f, %d", price, volume);
try {
/* Send updates to all open WebSocket sessions */
for (Session session : queue) {
session.getBasicRemote().sendText(msg);
logger.log(Level.INFO, "Sent: {0}", msg);
}
} catch (IOException e) {
logger.log(Level.INFO, e.toString());
}
}
#OnOpen
public void openConnection(Session session) {
System.err.println("in open connection");
/* Register this connection in the queue */
queue.add(session);
logger.log(Level.INFO, "Connection opened.");
}
#OnClose
public void closedConnection(Session session) {
System.err.println("in closed connection");
/* Remove this connection from the queue */
queue.remove(session);
logger.log(Level.INFO, "Connection closed.");
}
#OnError
public void error(Session session, Throwable t) {
System.err.println("in error");
/* Remove this connection from the queue */
queue.remove(session);
logger.log(Level.INFO, t.toString());
logger.log(Level.INFO, "Connection error.");
}
}
PriceVolumeBean.java
package javaeetutorial.web.dukeetf2;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
/* Updates price and volume information every second */
#Startup
#Singleton
public class PriceVolumeBean {
/* Use the container's timer service */
#Resource TimerService tservice;
private Random random;
private volatile double price = 100.0;
private volatile int volume = 300000;
private static final Logger logger = Logger.getLogger("PriceVolumeBean");
#PostConstruct
public void init() {
/* Intialize the EJB and create a timer */
System.err.println("in init");
logger.log(Level.INFO, "Initializing EJB.");
random = new Random();
tservice.createIntervalTimer(1000, 1000, new TimerConfig());
}
#Timeout
public void timeout() {
System.err.println("in timeout");
/* Adjust price and volume and send updates */
price += 1.0*(random.nextInt(100)-50)/100.0;
volume += random.nextInt(5000) - 2500;
ETFEndpoint.send(price, volume);
}
}
For those who wants to know how I've downloaded it, I used this address and "svn export" command.
As you mentioned, you used Glassfish Server 3.1 that is not compatible with Java EE 7. You should use Glassfish 4.0 server to run above WebSocket example. WebSocket has introduced with Java EE 7.
To know how to run this example. Go to this tutorial.
I start learn AOP with spring framework 3.1.2. But I have trouble. In Beans.xml context file i wrote:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<bean id = "audience" class="com.MySpring.Audience"></bean>
<aop:config>
<aop:aspect ref="audience">
<aop:pointcut id="performance" expression="execution(* com.MySpring.Performer.perform(..))"/>
<aop:before pointcut-ref="performance" method="seatDown"/>
<aop:before pointcut-ref="performance" method="turnOffPhone"/>
<aop:after-returning pointcut-ref="performance" method="applauz"/>
<aop:after-throwing pointcut-ref="performance" method="demandRefund"/>
</aop:aspect>
</aop:config>
</beans>
And Java class
public class AOPTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext(
"Beans.xml");
}
}
// ///
class Audience {
public void seatDown() {
out.println("Seat down");
}
public void turnOffPhone() {
out.println("Turn Off Phone");
}
public void applauz() {
out.println("Aplauz");
}
public void demandRefund() {
out.println("We have money back");
}
}
////
interface Performer{
void perform();
}
But in error console i see:
Description Resource Path Location Type
Error occured processing XML 'class path resource [org/aopalliance/aop/Advice.class] cannot be opened because it does not exist'. See Error Log for more details Beans.xml /AnnotationsWiring/src line 11 Spring Beans Problem
And second error:
Description Resource Path Location Type
Error occured processing XML 'org/springframework/aop/aspectj/AspectJMethodBeforeAdvice'. See Error Log for more details Beans.xml /AOP/src line 12 Spring Beans Problem
I guess you are learning spring using examples from spring in action. In fact, you are missing a com.springsource.org.apoalliance.jar file, which is not included in org.springframework.aop.jar(though i don't know why).
Please download it at: http://sourceforge.net/projects/aopalliance/files/aopalliance/
You have the Caused by: java.lang.ClassNotFoundException: org.aopalliance.aop.Advice because you don't include the jar into your classpath.
I 've designed a db application, but need to handle the exception connecting to db using spring aop, classes i 've are shown below
LoginInterface.java
LoginInterface(){
ApplicationContext context = new ClassPathXmlApplicationContext("LoginApp.xml");
Login login = (Login) context.getBean("Login");
login.loginMethod(username,password);
}
Login.java
{
loginMethod(String username, char[] pwd) throws ClassNOtFoundException, SQLException{
...
}
}
LoginProfiler.java
package dbapp;
import java.sql.SQLException;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.JoinPoint;
#Aspect
public class LoginProfiler {
#Pointcut("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void loginMethod(){}
#Around("loginMethod()")
public void handleException(final ProceedingJoinPoint pJoinPoint )throws Throwable{
try{
pJoinPoint.proceed();
}catch(Exception e) {
if((e.getCause().toString()).contains("UnknownHostException") ){
System.out.println("Unknown Host ");
}else if((e.getCause().toString()).contains("ConnectException")){
System.out.println("Connection Problem ");
}
}
}
}
LoginApp.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-destroy-method="destroy"
default-init-method="afterPropertiesSet"
default-autowire="byName">
<!-- Enable the #AspectJ support -->
<aop:aspectj-autoproxy />
<bean id="LoginProfiler" class="dbapp.LoginProfiler" />
<bean id="Login" class="dbapp.Login" />
</beans>
I've got the following Exception
Erg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Login' defined in class path resource [LoginApp.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at
..
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:315)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:206)
at
Try this.
#Aspect
public class LoginProfiler {
#Pointcut("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void loginMethod(){}
#AfterThrowing("loginMethod()")
public void handleException(final JoinPoint joinPoint){
System.out.println("Am able to Handle");
}
}
or
#Aspect
public class LoginProfiler {
#AfterThrowing("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void handleException(final JoinPoint joinPoint){
System.out.println("Am able to Handle");
}
}
Also it would be better if you spend some time learning about spring-aop. From your question it looks like you really don't understand AOP. You are trying to cut and paste from some sample code.
I am tying to merging web application(gwt, jpa) to an separate 2 application(business login in ejb/jpa and web client in gwt). Currently i can`t inject my beans from web application (simple servlet)
I am using glassfish v3.
module limbo(ejb jar) is in dependency of module lust (war).
If I use lust with compiler output of limbo everything work perfect (if ejb in web application and the are deploying together as one application).
Have I messed some container configuration ?
Here is my steps:
I have some limbo.jar (ejb-jar) deployed to ejb container. I do not use any ejb-jar.xml, only annotations.
package ua.co.inferno.limbo.persistence.beans;
import javax.ejb.Remote;
#Remote
public interface IPersistentServiceRemote {
ArrayList<String> getTerminalACPList();
ArrayList<String> getBoxACPList();
ArrayList<String> getCNPList();
ArrayList<String> getCNSList();
String getProductNamebyID(int boxid);
ArrayList<String> getRegionsList(String lang);
long getSequence();
void persistEntity (Object ent);
}
package ua.co.inferno.limbo.persistence.beans;
import ua.co.inferno.limbo.persistence.entitis.EsetChSchemaEntity;
import ua.co.inferno.limbo.persistence.entitis.EsetKeyActionsEntity;
#Local
public interface IPersistentService {
ArrayList<String> getTerminalACPList();
ArrayList<String> getBoxACPList();
ArrayList<String> getCNPList();
ArrayList<String> getCNSList();
String getProductNamebyID(int boxid);
ArrayList<String> getRegionsList(String lang);
long getSequence();
long persistPurchaseBox(EsetRegPurchaserEntity rp);
void removePurchaseTempBox(EsetRegPurchaserTempEntity rpt);
EsetRegionsEntity getRegionsById(long rid);
void persistEntity (Object ent);
}
package ua.co.inferno.limbo.persistence.beans;
import ua.co.inferno.limbo.persistence.entitis.EsetChSchemaEntity;
import ua.co.inferno.limbo.persistence.entitis.EsetKeyActionsEntity;
import ua.co.inferno.limbo.persistence.entitis.EsetRegBoxesEntity;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless(name = "PersistentService")
public class PersistentServiceEJB
implements
IPersistentService, IPersistentServiceRemote{
#PersistenceContext(unitName = "Limbo")
EntityManager em;
public PersistentServiceEJB() {
}
.........
}
Than i trying to use PersistentService session bean(included in limbo.jar) from web application in lust.war (the limbo.jar & lust.war is not in ear)
package ua.co.lust;
import ua.co.inferno.limbo.persistence.beans.IPersistentService;
import javax.ejb.EJB;
import javax.servlet.ServletException;
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(name = "ServletTest",
urlPatterns = {"/"})
public class ServletTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
service(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
service(request, response);
}
#EJB
private IPersistentService pService;
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hi = pService.getCNPList().toString();
System.out.println("testBean.hello method returned: " + hi);
System.out.println("In MyServlet::init()");
System.out.println("all regions" + pService.getRegionsList("ua"));
System.out.println("all regions" + pService.getBoxACPList());
}
}
web.xm
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>ServletTest</servlet-name>
<servlet-class>ua.co.lust.ServletTest</servlet-class>
</servlet>
</web-app>
When servelt is loading i ge 404 eror (The requested resource () is not available.)
And errors in logs :
global
Log Level
SEVERE
Logger
global
Name-Value Pairs
{_ThreadName=Thread-1, _ThreadID=31}
Record Number
1421
Message ID
Complete Message
Class [ Lua/co/inferno/limbo/persistence/beans/IPersistentService; ] not found. Error while loading [ class ua.co.lust.ServletTest ]
javax.enterprise.system.tools.deployment.org.glassfish.deployment.common
Log Level
WARNING
Logger
javax.enterprise.system.tools.deployment.org.glassfish.deployment.common
Name-Value Pairs
{_ThreadName=Thread-1, _ThreadID=31}
Record Number
1422
Message ID
Error in annotation processing
Complete Message
java.lang.NoClassDefFoundError: Lua/co/inferno/limbo/persistence/beans/IPersistentService;
ejb jar was deployed with this info log :
Log Level
INFO
Logger
javax.enterprise.system.container.ejb.com.sun.ejb.containers
Name-Value Pairs
{_ThreadName=Thread-1, _ThreadID=26}
Record Number
1436
Message ID
Glassfish-specific (Non-portable) JNDI names for EJB PersistentService
Complete Message
[ua.co.inferno.limbo.persistence.beans.IPersistentServiceRemote#ua.co.inferno.limbo.persistence.beans.IPersistentServiceRemote, ua.co.inferno.limbo.persistence.beans.IPersistentServiceRemote]
Log Level
INFO
Logger
javax.enterprise.system.tools.admin.org.glassfish.deployment.admin
Name-Value Pairs
{_ThreadName=Thread-1, _ThreadID=26}
Record Number
1445
Message ID
Complete Message
limbo was successfully deployed in 610 milliseconds.
Do i nee to add some additional configuration in a case of injections from others application?
Some ideas?
in a case of #Remote
package ua.co.lust;
import ua.co.inferno.limbo.persistence.beans.PersistentServiceRemote;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
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(name = "ServletTest",
urlPatterns = {"/"})
public class WebTestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
service(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
service(request, response);
}
// #EJB
// private PersistentServiceRemote pService; <<-- DI not working :( - same errs as with Local interface (class not found)
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Context ctx = null;
try {
ctx = new InitialContext();
PersistentServiceRemote pService =
(PersistentServiceRemote) ctx.lookup("java:global/limbo/PersistentServiceBean!ua.co.inferno.limbo.persistence.beans.PersistentServiceRemote");
String hi = pService.getCNPList().toString();
System.out.println("testBean.hello method returned: " + hi);
System.out.println("In MyServlet::init()");
System.out.println("all regions" + pService.getRegionsList("ua"));
System.out.println("all regions" + pService.getBoxACPList());
} catch (NamingException e) {
e.printStackTrace();
}
}
}
Log :
Log Level
SEVERE
Logger
javax.enterprise.system.std.com.sun.enterprise.v3.services.impl
Name-Value Pairs
{_ThreadName=Thread-1, _ThreadID=32}
Record Number
1963
Message ID
javax.naming.NamingException
Complete Message
Lookup failed for 'java:global/limbo/PersistentServiceBean!ua.co.inferno.limbo.persistence.beans.PersistentServiceRemote' in SerialContext [Root exception is javax.naming.NamingException: ejb ref resolution error for remote business
interfaceua.co.inferno.limbo.persistence.beans.PersistentServiceRemote [Root exception is java.lang.ClassNotFoundException: ua.co.inferno.limbo.persistence.beans.PersistentServiceRemote]] at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:442) at
javax.naming.InitialContext.lookup(InitialContext.java:392) at javax.naming.InitialContext.lookup(InitialContext.java:392) at
ua.co.lust.WebTestServlet.service(WebTestServlet.java:45) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at
com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipel
ine.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at
org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) Caused by: javax.naming.NamingException: ejb ref resolution error for remote business interfaceua.co.inferno.limbo.persistence.beans.PersistentServiceRemote [Root exception is java.lang.ClassNotFoundException: ua.co.inferno.limbo.persistence.beans.PersistentServiceRemote] at com.sun.ejb.EJBUtils.lookupRemote30BusinessObject(EJBUtils.java:430) at
com.sun.ejb.containers.RemoteBusinessObjectFactory.getObjectInstance(RemoteBusinessObjectFac
tory.java:70) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304) at
com.sun.enterprise.naming.impl.SerialContext.getObjectInstance(SerialContext.java:472) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:437) ... 28 more
Caused by: java.lang.ClassNotFoundException: ua.co.inferno.limbo.persistence.beans.PersistentServiceRemote at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:188) at org.glassfish.web.loader.WebappClassLoader.findClass(WebappClassLoader.java:959) at
org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1430) at com.sun.ejb.EJBUtils.getBusinessIntfClassLoader(EJBUtils.java:678) at
com.sun.ejb.EJBUtils.loadGeneratedRemoteBusinessClasses(EJBUtils.java:459) at com.sun.ejb.EJBUtils.lookupRemote30BusinessObject(EJBUtils.java:410) ... 32 more
Info deploy log
Log Level
INFO
Logger
javax.enterprise.system.container.ejb.com.sun.ejb.containers
Name-Value Pairs
{_ThreadName=Thread-1, _ThreadID=11}
Record Number
1899
Message ID
Portable JNDI names for EJB PersistentServiceBean
Complete Message
[java:global/limbo/PersistentServiceBean!ua.co.inferno.limbo.persistence.beans.PersistentServiceRemote, java:global/limbo/PersistentServiceBean!ua.co.inferno.limbo.persistence.beans.PersistentServiceLocal]
Do I need include my ejb jar into WEB=INF/lib if I am using Remote business logic call?
Why DI not working in a case of remote?
and it work prefect if I include
compile output from limbo module and
provide :
PersistentServiceRemote pService =
(PersistentServiceRemote) ctx.lookup("java:global/lust/PersistentServiceBean!ua.co.inferno.limbo.persistence.beans.PersistentServiceRemote");
Why I couldn`t look up for the PersistentServiceRemote (Remote interface of PersistentServiceBean ) for another web application ?
By sample`s code from glassfish It should work (.
Any ideas?
Ok. So as Pascal said. We need to package remote interface in webapp. We can use Local interface injection in different application. If you need use Local interface you need to include ejb jar in your application. Current design - package remote interface to webapp
If you don't deploy your ejb-jar as a lib of your war (i.e. under WEB-INF/lib), I don't think you'll be able to use the Local interface (and you'll have to package the remote interface in your webapp).
PS: you don't really need the web.xml here.