Why the following code (dukeetf2 ) of websocket does not work? - java

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.

Related

Stateless Bean is null

It was working earlier when I was jersey 1.1. But now it says this.userBean is null.
Apart from that there is one warning in the log related com.sun.faces.flow.FlowDiscoveryCDIHelper is deprecated from CDI 1.1!
logs:
08:30:45,161 INFO [org.jboss.as.server.deployment] (MSC service thread 1-4) WFLYSRV0027: Starting deployment of "ejb2.war" (runtime-name: "ejb2.war")
08:30:45,753 INFO [org.jboss.weld.deployer] (MSC service thread 1-3) WFLYWELD0003: Processing weld deployment ejb2.war
08:30:45,783 INFO [org.jboss.as.ejb3.deployment] (MSC service thread 1-3) WFLYEJB0473: JNDI bindings for session bean named 'UserSessionBean' in deployment unit 'deployment "ejb2.war"' are as follows:
java:global/ejb2/UserSessionBean!com.enovate.assignment.ejb2.UserSessionBeanLocal
java:app/ejb2/UserSessionBean!com.enovate.assignment.ejb2.UserSessionBeanLocal
java:module/UserSessionBean!com.enovate.assignment.ejb2.UserSessionBeanLocal
java:global/ejb2/UserSessionBean
java:app/ejb2/UserSessionBean
java:module/UserSessionBean
08:30:45,845 INFO [io.jaegertracing.internal.JaegerTracer] (MSC service thread 1-3) No shutdown hook registered: Please call close() manually on application shutdown.
08:30:45,999 INFO [io.smallrye.metrics] (MSC service thread 1-3) MicroProfile: Metrics activated (SmallRye Metrics version: 2.4.2)
08:30:46,008 WARN [org.jboss.weld.Bootstrap] (MSC service thread 1-3) WELD-000146: BeforeBeanDiscovery.addAnnotatedType(AnnotatedType<?>) used for class com.sun.faces.flow.FlowDiscoveryCDIHelper is deprecated from CDI 1.1!
08:30:46,210 INFO [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 126) Initializing Mojarra 2.3.14.SP01 for context '/ejb2'
08:30:47,353 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 126) WFLYUT0021: Registered web context: '/ejb2' for server 'default-server'
08:30:47,440 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) WFLYSRV0016: Replaced deployment "ejb2.war" with deployment "ejb2.war"
08:30:47,448 INFO [org.jboss.as.repository] (DeploymentScanner-threads - 2) WFLYDR0002: Content removed from location C:\Users\teoti\Desktop\office\wildfly-21.0.2.Final\standalone\data\content\15\e071e0f42a2e0339da8b4d636a6496c5b1146e\content
08:33:05,177 ERROR [io.undertow.request] (default task-1) UT005023: Exception handling request to /ejb2/webapi/register: javax.servlet.ServletException: java.lang.NullPointerException: Cannot invoke "com.enovate.assignment.ejb2.UserSessionBeanLocal.isUserPresent(String)" because "this.userBean" is null
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.enovate.assignment.ejb2</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
services:
import javax.ejb.EJB;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("")
public class Service
{
#EJB
UserSessionBeanLocal userBean;
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("register")
public Response register(#FormParam("userName") final String name, #FormParam("userPassword") final String pass, #FormParam("userEmail") String email)
{
if (userBean.isUserPresent(email))
return Response.ok("Email already registered!!").build();
userBean.addUser(new User(name, email, pass));
return Response.ok("Registered!!").build();
}
}
UserSessionBean:
import java.util.ArrayList;
import javax.ejb.Stateless;
#Stateless
public class UserSessionBean implements UserSessionBeanLocal
{
static ArrayList<User> usersList = new ArrayList<User>();
static int userCount = 0;
User u = null;
public boolean isUserPresent(final String email)
{
return usersList.stream().anyMatch(d -> d.getEmail().equals(email));
}
public void addUser(User newUser)
{
usersList.add(newUser);
userCount++;
}
}
User:
public class User
{
private String name;
private String password;
private String email;
User(final String name, final String email, final String password)
{
this.name = name;
this.email = email;
this.password = password;
}
...
}
I thought it would work fine but I don't know how it is null. Maybe is related to CDI warning of log or something related to newer version of jersey or #EJB not working. I also tried adding beans.xml file.
Any help is appreciated
The reason was something related to Non-managed bean. And I can not use #EJB to initialize the bean, I have to use Jndi lookup way like this inside function:
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("register")
public Response register(#FormParam("userName") final String name, #FormParam("userPassword") final String pass, #FormParam("userEmail") String email)
{
UserSessionBeanLocal userBean = null;
try
{
InitialContext ic = new InitialContext();
userBean = (UserSessionBeanLocal)ic.lookup("java:global/ejb/UserSessionBean!com.demo.ejb.UserSessionBeanLocal");
} catch (NamingException e)
{
e.printStackTrace();
}
...
If you only want to use #EJB this might work:
I was using jersey in the project and I feels like there is some problem with jersey libraries.
So I deleted all the dependency inside the dependecies below build from the pom.xml and update the project
Added to javaee-api-8.0.jar file to the classpath
Clear the everything inside the web-app (everything)
Added root resource file by extending javax.ws.rs.core.Application like here and it worked

Cannot upload my Web Applicartion in Jboss7 EAP7 EAP

I must to test this web app, but when I try to deploy on JBoss 7 EAP this is the error, maybe I forgot something?
This is the exception that the application throws:
Cannot upload deployment: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL" =>
"org.jboss.msc.service.StartException in service jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL: WFLYSRV0153:
Failed to process phase INSTALL of deployment \"WebAppGuestbooks.war\" Caused by:
org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0041: Component class it.matteo.nesea.ejb.GuestDao for
component GuestDao has errors:
WFLYJPA0033: Can't find a persistence unit named null in deployment
\"WebAppGuestbooks.war\""},"WFLYCTL0180: Services with missing/unavailable dependencies" =>
["jboss.deployment.unit.\"WebAppGuestbooks.war\".weld.weldClassIntrospector is missing
[jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]","jboss.deployment.unit.\"WebAppGuestbooks.war\".batch.environment
is missing [jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]"]}
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="GuestbookPU" transaction-type="JTA">
<class>it.matteo.nesea.dao.jpa</class>
<properties>
<property name="javax.persistence.jdbc.url" value="$objectdb/db/guests.odb"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
this is the Ejb GuestDAO:
package it.matteo.nesea.ejb;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import it.matteo.nesea.dao.jpa.Guest;
#Stateless
public class GuestDao {
// Injected database connection:
#PersistenceContext private EntityManager em;
// Stores a new guest:
public void persist(Guest guest) {
em.persist(guest);
}
// Retrieves all the guests:
public List<Guest> getAllGuests() {
TypedQuery<Guest> query = em.createQuery(
"SELECT g FROM Guest g ORDER BY g.id", Guest.class);
return query.getResultList();
}
}
this is Jpa POJO Class Guest:
package it.matteo.nesea.dao.jpa;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Guest implements Serializable {
private static final long serialVersionUID = 1L;
// Persistent Fields:
#Id
#GeneratedValue
Long id;
private String name;
private Date signingDate;
// Constructors:
public Guest() {
}
public Guest(String name) {
this.name = name;
this.signingDate = new Date(System.currentTimeMillis());
}
// String Representation:
#Override
public String toString() {
return name + " (signed on " + signingDate + ")";
}
}
This is a Servlet GuestServlet:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.matteo.nesea.dao.jpa.Guest;
import it.matteo.nesea.ejb.GuestDao;
#WebServlet(name="GuestServlet", urlPatterns={"/guest"})
public class GuestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Injected DAO EJB:
#EJB GuestDao guestDao;
#Override
protected void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Display the list of guests:
request.setAttribute("guests", guestDao.getAllGuests());
request.getRequestDispatcher("/guest.jsp").forward(request, response);
}
#Override
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle a new guest:
String name = request.getParameter("name");
if (name != null)
guestDao.persist(new Guest(name));
// Display the list of guests:
doGet(request, response);
}
}
This is a JSP Page:
<%#page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#page import="java.util.*,it.matteo.nesea.dao.jpa.Guest"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JPA Guest Book Web Application</title>
</head>
<body>
<form method="POST" action="guest">
Name: <input type="text" name="name" />
<input type="submit" value="Add" />
</form>
<hr><ol> <%
#SuppressWarnings("unchecked")
List<Guest> guests = (List<Guest>)request.getAttribute("guests");
if (guests != null) {
for (Guest guest : guests) { %>
<li> <%= guest %> </li> <%
}
} %>
</ol></hr>
</body>
This is the path of Project
Your persistence.xml file is in the wrong place. The JPA uses a convention to find your persistence.xml so you have put the file in the right place.
According to the Oracle docs:
The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit.
If you package the persistent unit as a set of classes in an EJB JAR file, persistence.xml should be put in the EJB JAR’s META-INF directory.
If you package the persistence unit as a set of classes in a WAR file, persistence.xml should be located in the WAR file’s WEB-INF/classes/META-INF directory.
In your case when the persistence.xml file is in src/META-INF/ (if you use MAVEN the path is src/resources/META-INF) its going to be packaged in your war in the WEB-INF/classes/META-INF folder, funcioning as the root of the persistence unit.

Spring websocket in embedded tomcat 8.0.21

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

java wicket error!

This is my code,
package com.mywicketapp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.extensions.ajax.markup
.html.autocomplete.AutoCompleteTextField;
public class HomePage extends WebPage
{
public HomePage()
{
Form form = new Form("form");
add(form);
final AutoCompleteTextField field =
new AutoCompleteTextField("auto", new Model(""))
{
protected Iterator getChoices(String input)
{
if (Strings.isEmpty(input))
{
return Collections.EMPTY_LIST.iterator();
}
List choices = new ArrayList(10);
Locale[] locales = Locale.getAvailableLocales();
for (int i = 0; i < locales.length; i++)
{
final Locale locale = locales[i];
final String country = locale.getDisplayCountry();
if (country.toUpperCase().startsWith(input.toUpperCase()))
{
choices.add(country);
if (choices.size() == 10)
{
break;
}
}
}
return choices.iterator();
}
};
form.add(field);
final Label label = new
Label("selectedValue", field.getModel());
label.setOutputMarkupId(true);
form.add(label);
field.add(new AjaxFormSubmitBehavior(form, "onchange")
{
protected void onSubmit(AjaxRequestTarget target)
{
target.addComponent(label);
}
#Override
protected void onError(AjaxRequestTarget target)
{
}
});
}
}
This is my application code:
package com.mywicketapp;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application. If you want to run this application without deploying, run the Start class.
*
* #see com.mywicketapp.Start#main(String[])
*/
public class WicketApplication extends WebApplication
{
/**
* Constructor
*/
public WicketApplication()
{
}
/**
* #see org.apache.wicket.Application#getHomePage()
*/
public Class<HomePage> getHomePage(){
return HomePage.class;
}
}
Some html:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
The textfield below will autocomplete country names
<br><hr>
<form wicket:id="form">
Selected value is: <span wicket:id="selectedValue"></span>
<br/>
Country: <input type="text" wicket:id="auto" size="20"/>
</form>
</body>
</html>
And the error:
- log - Logging to org.slf4j.impl.Log4jLoggerAdapter(org.mortbay.log) via org.mortbay.log.Slf4jLog
>>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP
INFO - log - jetty-6.1.25
INFO - log - NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
WARN - log - failed wicket.mywicketapp: java.lang.ClassCastException: wicket.extensions.Initializer cannot be cast to org.apache.wicket.IInitializer
ERROR - log - Failed startup of context org.mortbay.jetty.webapp.WebAppContext#66e7b3f2{/,src/main/webapp}
java.lang.ClassCastException: wicket.extensions.Initializer cannot be cast to org.apache.wicket.IInitializer
at org.apache.wicket.Application.addInitializer(Application.java:864)
at org.apache.wicket.Application.load(Application.java:938)
at org.apache.wicket.Application.initializeComponents(Application.java:715)
at org.apache.wicket.protocol.http.WicketFilter.init(WicketFilter.java:732)
at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:662)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1272)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:489)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.mywicketapp.Start.main(Start.java:43)
INFO - log - Started SelectChannelConnector#0.0.0.0:8080
Looks to me like you have a version incompatibility problem... Check to make sure that the version of wicket-extensions that you're using is compatible with your wicket version. The wicket.extensions.Initializer that's getting loaded and causing the exception is surely getting loaded up by your AutoCompleteTextField.

How to use EJB 3.1 DI in Servlet ? (Could not inject session bean by #EJB from web application)

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.

Categories