The workmanager is defined in admin console with minimum 1 and 5 as pool size. the web app is with following configurations.
Web.xml
<web-app id="RestController" metadata-complete="true" version="3.0" 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">
<servlet>
<servlet-name>rest-controller</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest-controller</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Application-Context.xml
`<!-- Empty. I moved all the servlet related entities from here -->`
rest-Controller-servlet.xml
<context:component-scan base-package="com.package.main-pack" />
<task:annotation-driven executor="taskExecutor"/>
<mvc:annotation-driven />
<task:executor id="taskExecutor" pool-size="5" />
RestController.java
#RequestMapping(value = "/reportFake", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
#Override
public List<String> searchFake() {
List<String> stringArr = new ArrayList<String>();
for (String folder : foldername) {
Future<String> result = reportLookup.doParallelFake(folder);
try {
while (true) {
if (result.isDone()) {
stringArr.add(result.get());
Logger.debug(RestController.class,
"Executed and Returned");
break;
}
}
} catch (InterruptedException e) {
Logger.error(RestController.class, e.getMessage());
} catch (ExecutionException e) {
Logger.error(RestController.class, e.getMessage());
}
}
return stringArr;
}
ReportLookupExecutor.java
#Service("reportLookup")
public class ReportLookupExecutor implements ReportLookupIntf {
#Async("taskExecutor")
#Async("taskExecutor")
#Override
public Future<String> doParallelFake(String folder) {
logger.debug("Execute method asynchronously - "
+ Thread.currentThread().getName());
try {
Thread.sleep(5000);
return new AsyncResult<String>("Folder Name :: " + folder);
} catch (InterruptedException e) {
logger.error(e);
}
return null;
}
Output
[11/4/15 12:41:24:349 EST] 0000014d SystemOut O [DEBUG] 04 Nov 12:41:24 PM taskExecutor-1 Execute method asynchronously - taskExecutor-1
[11/4/15 12:41:29:365 EST] 0000007b SystemOut O [DEBUG] 04 Nov 12:41:29 PM WebContainer : 3 Executed and Returned
[11/4/15 12:41:29:366 EST] 0000014e SystemOut O [DEBUG] 04 Nov 12:41:29 PM taskExecutor-2 Execute method asynchronously - taskExecutor-2
[11/4/15 12:41:34:365 EST] 0000007b SystemOut O [DEBUG] 04 Nov 12:41:34 PM WebContainer : 3 Executed and Returned
Now, I've tried to follow this link.
I manually threw an exception to check the stack-trace and found that it is being run by ibm.asynchbeans and is duly intercepted by Spring. Here is a snippet from the stack-trace.
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:97)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:314)
at java.util.concurrent.FutureTask.run(FutureTask.java:149)
at org.springframework.scheduling.commonj.DelegatingWork.run(DelegatingWork.java:61)
at com.ibm.ws.asynchbeans.J2EEContext.run(J2EEContext.java:1178)
at com.ibm.ws.asynchbeans.WorkWithExecutionContextImpl.go(WorkWithExecutionContextImpl.java:199)
at com.ibm.ws.asynchbeans.CJWorkItemImpl.run(CJWorkItemImpl.java:236)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)
Would appreciate any help.
OK! Finally I was able to make it run. The solution is to make all the number of calls to the async method before getting the first value of future. I was able to do this by creating a List of Future objects. This is how the final calling class looks.
RestController.java
#RequestMapping(value = "/reportFake", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
#Override
public List<String> searchFake() throws InterruptedException,
ExecutionException {
List<Future<String>> futureArr = new ArrayList<Future<String>>();
for (String folder : new String[] { "One", "Two", "Three", "Four" }) {
futureArr.add(reportLookup.doParallelFake(folder));
}
List<String> stringArr = new ArrayList<String>();
for (Future<String> future : futureArr) {
stringArr.add(future.get());
}
return stringArr;
}
Related
Given error:
INFO: Starting service Catalina Feb 15, 2016 2:23:09 PM
org.apache.catalina.core.StandardEngine startInternal INFO: Starting
Servlet Engine: Apache Tomcat/8.0.23 Feb 15, 2016 2:23:09 PM
org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation
using [SHA1PRNG] took [116] milliseconds. Feb 15, 2016 2:23:09 PM
org.apache.catalina.core.ContainerBase startInternal SEVERE: A child
container failed during start java.util.concurrent.ExecutionException:
org.apache.catalina.LifecycleException: Failed to start component
[StandardEngine[Catalina].StandardHost[localhost].StandardContext[/storyboard]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122) at
java.util.concurrent.FutureTask.get(FutureTask.java:192) at
org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:917)
at
org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745) Caused by:
org.apache.catalina.LifecycleException: Failed to start component
[StandardEngine[Catalina].StandardHost[localhost].StandardContext[/storyboard]]
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 6 more Caused by: java.lang.NoClassDefFoundError:
com/j256/ormlite/support/ConnectionSource at
java.lang.Class.getDeclaredFields0(Native Method) at
java.lang.Class.privateGetDeclaredFields(Class.java:2575) at
java.lang.Class.getDeclaredFields(Class.java:1908) at
org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
at
org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:256)
at
org.apache.catalina.startup.WebAnnotationSet.loadApplicationListenerAnnotations(WebAnnotationSet.java:86)
at
org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:63)
at
org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:334)
at
org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:774)
at
org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
at
org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at
org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5066)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more Caused by: java.lang.ClassNotFoundException:
com.j256.ormlite.support.ConnectionSource at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157)
... 20 more
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<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_3_1.xsd" version="3.1">
<servlet>
<servlet-name>UploadImage</servlet-name>
<servlet-class>com.home.storyboard.UploadServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UploadCanvas</servlet-name>
<servlet-class>com.home.storyboard.UploadCanvas</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadImage</servlet-name>
<url-pattern>/uploadimage</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UploadCanvas</servlet-name>
<url-pattern>/uploadcanvas</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>StoryServlet</servlet-name>
<servlet-class>com.home.storyboard.StoryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StoryServlet</servlet-name>
<url-pattern>/StoryServlet</url-pattern>
</servlet-mapping>
<listener>
<description>ServletContextListener</description>
<listener-class>com.home.storyboard.StartupListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
StartupListener
package com.home.storyboard;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import java.sql.SQLException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.home.storyboard.DAOdb;
public class StartupListener implements ServletContextListener{
private final static String DATABASE_URL = "jdbc:sqlite:testdb.db";
ConnectionSource connectionSource = null;
#Override
public void contextInitialized(ServletContextEvent sce) {
try {
// create our data-source for the database
connectionSource = new JdbcConnectionSource(DATABASE_URL);
DAOdb db = new DAOdb(connectionSource);
sce.getServletContext().setAttribute("db", db);
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
// destroy the data source which should close underlying connections
DAOdb db = (DAOdb)sce.getServletContext().getAttribute("db");
db.close();
}
}
DAOdb class
package com.home.storyboard;
import java.sql.SQLException;
import java.util.List;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.table.TableUtils;
import com.j256.ormlite.support.ConnectionSource;
public class DAOdb {
// we are using the in-memory H2 database
private final ConnectionSource connectionSource;
private Dao<User, Integer> userDAO;
private Dao<Profile,Integer> profileDAO;
private Dao<Story, Integer> storyDAO;
private String lastError;
public DAOdb(ConnectionSource connectionSource){
this.connectionSource=connectionSource;
try{
userDAO = DaoManager.createDao(connectionSource, User.class);
TableUtils.createTable(connectionSource, User.class);
profileDAO = DaoManager.createDao(connectionSource, Profile.class);
TableUtils.createTable(connectionSource, Profile.class);
storyDAO = DaoManager.createDao(connectionSource, Story.class);
TableUtils.createTable(connectionSource, Story.class);
}catch(SQLException e){
lastError = e.getMessage().toString();
}
}
/**
* DAO Functions to fetch data
*/
public void addStory(Story S) {
try{
storyDAO.create(S);
lastError = null;
} catch (Exception e) {
lastError = e.getMessage().toString();
}
}
public List<Story> getStoriesbyUsername(String username) {
String uname =username;
List<Story> storyList = null;
User user = getUserbyUsername(uname);
Integer uid =user.getId();
try{
GenericRawResults<String[]> stories = storyDAO.queryRaw(
"select count(*) from stories where userid = uid");
// there should be 1 result
List<String[]> results = stories.getResults();
// the results array should have 1 value
Integer usercount = results.size();
// this should print the number of orders that have this account-id
if(usercount<=0){
lastError="'No story exists by username'+' '+ username";
}else{
storyList = storyDAO.queryBuilder()
.where()
.eq(Story.USERID_FIELD_NAME, uid)
.query();
}
}catch(SQLException e){
lastError = e.getMessage().toString();
}
return storyList;
}
}
Your question is far too long and involved. The important part of it is this caused by exception:
java.lang.ClassNotFoundException: com.j256.ormlite.support.ConnectionSource at ...
For some reason your application does not have the ConnectionSource class. Maybe you are not including both the ORMLite JDBC as well as core jar? Make sure to follow the getting started documentation which talks about this:
Users that are connecting to SQL databases via JDBC connections will need to download the ormlite-jdbc-4.48.jar and ormlite-core-4.48.jar files. For use with Android applications, you should download the ormlite-android-4.48.jar and ormlite-core-4.48.jar files instead. For either JDBC or Android you will also need the ormlite-core release which has the ORMLite backend implementations.
If you are using a war, find the jar location and make sure both ORMLite jars are there. If you already have the core in your application then I'm not sure what is going wrong.
Hope this helps.
Class not found exception was resolved after uploading Ormlite core and Ormlite jdbc jars in the lib/ext folder of Java JRE. This is not the optimum solution. But for now it works for me.
I've created a Spring MVC portlets project and I'm trying to implement IPC between two of my portlets (SenderPortlet and ConsumerPortlet).
Everything works fine but I need to initialize a bean model that I put in session so I've used SessionAttributes annotation and ModelAttribute annotation on the method that initialize the bean. I have two states:
Before putting ModelAttribute annotation:
Everything works fine. I mean IPC.
After putting ModelAttribute annotation: An exception is thrown when I click on the action that fire the IPC sender event: org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public void com.test.SenderController.myAction(org.springframework.web.bind.support.SessionStatus,javax.portlet.ActionResponse)]; nested exception is java.lang.IllegalStateException: Current request is not of type [javax.portlet.RenderRequest]: com.liferay.portlet.ActionRequestImpl#127e27ff
Note that myAction is the method on which the action is mapped. This methd sets the IPC event. Here is its signature:
#ActionMapping("action")
public void myAction(SessionStatus status, ActionResponse response)
{
// some code...
}
I can not understand why this exception is fired since I add the modelAttribute annotation.
Can you please help me on this ?
Many thanks.
regards,
EDIT 1 More code
ConsumerPortlet.java
#Controller(value = "ConsumerPortlet")
#SessionAttributes( value="products" )
#RequestMapping("VIEW")
public class ConsumerPortlet {
#RequestMapping
public String handleRenderRequest(RenderRequest request, RenderResponse response, Model model) {
try {
//some code
return "page";
}
#ModelAttribute("products")
public List<ProductBean> initilizeProduct(RenderRequest renderRequest){
//some code
return productList;
}
#EventMapping(value ="{http://liferay.com/events}myEvent")
public void processEvent(EventRequest request, EventResponse response) throws PortletException, IOException {
javax.portlet.Event event = request.getEvent();
String testValue = (String) event.getValue();
System.out.println("IPC test value: "+testValue);
}
SenderPortlet.java
#Controller(value = "SenderPortlet")
#SessionAttributes( value="products" )
#RequestMapping("VIEW")
public class SenderPortlet {
#RequestMapping
public String handleRenderRequest(RenderRequest request,
RenderResponse response, Model model) {
return "page2";
}
#ModelAttribute("products")
public List<ProductBean> initilizeProduct(RenderRequest renderRequest){
PortletSession ps = renderRequest.getPortletSession();
List<ProductBean> productList = (List<ProductBean>) ps.getAttribute("products",PortletSession.APPLICATION_SCOPE);
return productList;
}
#ActionMapping("myAction")
public void myAction(SessionStatus status,
ActionResponse response)
{
QName qname = new QName("http://liferay.com/events", "myEvent", "x");
response.setEvent(qname, "test-value sent");
status.setComplete();
}
portlet.xml
<portlet>
<portlet-name>sender</portlet-name>
<portlet-class>
org.springframework.web.portlet.DispatcherPortlet
</portlet-class>
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/sender-portlet.xml</value>
</init-param>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>
<portlet-info>
<title>Sender</title>
</portlet-info>
<supported-publishing-event>
<qname xmlns:x="http://liferay.com/events">x:myEvent</qname>
</supported-publishing-event>
</portlet>
<portlet>
<portlet-name>consumer</portlet-name>
<portlet-class>
org.springframework.web.portlet.DispatcherPortlet
</portlet-class>
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/consumer-portlet.xml</value>
</init-param>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>
<portlet-info>
<title>Consumer</title>
</portlet-info>
<supported-processing-event>
<qname xmlns:x="http://liferay.com/events">x:myEvent</qname>
</supported-processing-event>
</portlet>
<event-definition>
<qname xmlns:x="http://liferay.com/events">x:myEvent</qname>
<value-type>java.lang.String</value-type>
</event-definition>
liferay-portlet.xml
<portlet>
<portlet-name>sender</portlet-name>
<icon>/icon.png</icon>
<instanceable>true</instanceable>
<header-portlet-css>/css/test.css</header-portlet-css>
<footer-portlet-javascript>/js/test.js</footer-portlet-javascript>
</portlet>
<portlet>
<portlet-name>consumer</portlet-name>
<icon>/icon.png</icon>
<instanceable>true</instanceable>
<header-portlet-css>/css/test.css</header-portlet-css>
<footer-portlet-javascript>/js/test.js</footer-portlet-javascript>
</portlet>
Liferay 6.2.10.12
Spring 3.0.7.RELEASE
As the method expecting the RenderRequest instead of ActionRequest, it is throwing that error. The below code might solve the problem or you can use generic Reuqest/Response i.e PortletRequest and PortletResponse
public void myAction(#ModelAttribute("products") List<ProductBean> productList, SessionStatus status,
ActionResponse response)
{
QName qname = new QName("http://liferay.com/events", "myEvent", "x");
response.setEvent(qname, "test-value sent");
status.setComplete();
}
I migrated my cometd from 2 to 3 and come across some problem:
Handshake never succeed, and there's no error messages.
I tried all I can do but still in vain.
Here's my Code:
ConfigurationServlet:
#Override
public void init() throws ServletException {
logger.info("start prepare echoService...");
// Grab the Bayeux object
BayeuxServer bayeuxServer = (BayeuxServer) getServletContext().getAttribute(BayeuxServer.ATTRIBUTE);
bayeuxServer.createChannelIfAbsent(NODE_CHANNEL, new ServerChannel.Initializer() { //1030829 change createIfAbsend to createChannelIfAbsent
#Override
public void configureChannel(ConfigurableServerChannel channel) {
channel.setPersistent(true);
}
});
EchoService echoService = new EchoService(bayeuxServer);
logger.info("...prepare echoService done");
}
EchoService:
public EchoService(BayeuxServer bayeuxServer) {
super(bayeuxServer, "echo");
//for what?
logger.info("=============enter echoService constructor=============");
addService("/echo", "processEcho");
addService(CometdProperties.COMETD_CHANNEL_WEB, "processReq");
logger.info("=============leaving echoService constructor=============");
isEchoServiceStarted = true;
}
public void processEcho(ServerSession remote, ServerMessage message) {
remote.deliver(getServerSession(), "/echo", message.getData());
}
public void processReq(ServerSession remote, ServerMessage message) {
//do something...
}
InitConnect in my client:
public boolean initConnect(String channel, ClientSessionChannel.MessageListener ml) {
HClogger.info("=============initConnect=============Listener:" + ml);
HttpClient httpClient = new HttpClient();
try {
httpClient.start();
} catch (Exception ex) {
HClogger.error(ex.toString());
if(connCnt<10){//Retry 9 times.
connCnt++;
return initConnect(channel,ml);
}
return false;
}
HClogger.info("*********************************try connect to server...");
Map<String, Object> options = new HashMap<>();
ClientTransport longPool = new LongPollingTransport(options, httpClient);
bayeuxClient = new BayeuxClient(CometdProperties.COMETD_DEFAULTURL, longPool);
bayeuxClient.handshake();
boolean handshaken = bayeuxClient.waitFor(10000, BayeuxClient.State.CONNECTED);
if (handshaken) {
HClogger.info("connected to server ok...");
bayeuxClient.getChannel(channel).subscribe(ml);
HClogger.info("subscribed to " + channel + " channel.");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
HClogger.error("Error when sleep after subscribe.", ex);
}
HClogger.info("=============HandleClient subscribe done.=============");
return true;
} else {
HClogger.info("=============HandleClient handshake fail.=============");
if(connCnt<10){//Retry 9 times.
connCnt++;
return initConnect(channel,ml);
}
return false;
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>cometd</servlet-name>
<servlet-class>org.cometd.server.CometDServlet</servlet-class>
<init-param>
<param-name>timeout</param-name>
<param-value>300000</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet>
<servlet-name>ConfigurationServlet</servlet-name>
<servlet-class>org.astri.ims.ccs.webcommand.ConfigurationServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ConfigurationServlet</servlet-name>
<url-pattern>/ConfigurationServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>cometd</servlet-name>
<url-pattern>/cometd/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
And here's what I add in my lib:
bayeux-api-3.0.1.jar
cometd-java-client-3.0.1.jar
cometd-java-common-3.0.1.jar
cometd-java-server-2.0.1.jar
jackson-mapper-asl-1.9.12.jar
javax.servlet-3.1.jar
jetty-client-9.2.2v20140723.jar
jetty-http-9.2.2v20140723.jar
jetty-io-9.2.2v20140723.jar
jetty-jmx-9.2.2v20140723.jar
jetty-server-9.2.2v20140723.jar
jetty-servlet-9.2.2v20140723.jar
jetty-util-9.2.2v20140723.jar
jetty-util-ajax-9.2.2v20140723.jar
Is there anything wrong in my code or configuration?
Update
I added a listener to the meta_channel, and I got this while handshaking:
{"id":"3","failure":{"message":{"id":"3","supportedConnectionTypes":["long-polling"],"channel":"/meta/handshake","version":"1.0"},"exception":"java.util.concurrent.TimeoutException: Total timeout elapsed","connectionType":"long-polling"},"subscription":null,"successful":false,"channel":"/meta/handshake"}
It turns out there is a bug in glassfish4.
Thanks for #sbordet who investigate and find out what's going on.
For detail information, please visit here.
For those who want to use CometD3, Jetty is suggested container.
For those who have no choice but to use glassfish, Cometd2.X works.
I've tried with cometd2.9.1, 3.0.0 and 3.0.1 in glassfish4, the result is
2.9.1 works in glassfish4 while 3.0.0 and 3.0.1 not.
i have a JSF app and for some reasons i need to refresh the page on browser back button.I tried implementing the solution given in Force JSF to refresh page / view / form when opened via link or back button by BalusC ,the only difference is that my app runs with servlet version 2.5 so i did the mapping in web.xml as below
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
javax.faces.STATE_SAVING_METHOD
client
javax.faces.CONFIG_FILES
/WEB-INF/faces-config.xml
com.sun.faces.config.ConfigureListener
javax.faces.PROJECT_STAGE
Production
javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE
true
login.xhtml
FacesServlet
javax.faces.webapp.FacesServlet
1
FacesServlet
/faces/
FacesServlet
.jsf
FacesServlet
.faces
FacesServlet
.xhtml
SessionUtil
SessionUtil
com.gaic.lpsr.utilclasses.SessionUtil
SessionUtil
/SessionUtil
<filter>
<filter-name>cacheFilter</filter-name>
<filter-class>com.gaic.lpsr.utilclasses.NoCacheFilter.java</filter-class>
</filter>
<filter-mapping>
<filter-name>cacheFilter</filter-name>
<servlet-name>FacesServlet</servlet-name>
</filter-mapping>
My filter class is
public class NoCacheFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(req, res);
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
// ...
}
I have included the jar servlet-api-2.5.jar.When i try to deploy app in tomcat server(version 6.0.29) i am getting the below error.
SEVERE: Exception starting filter cacheFilter
java.lang.ClassNotFoundException: com.gaic.lpsr.utilclasses.NoCacheFilter.java
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:269)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:422)
at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:115)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4001)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4651)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445)
at org.apache.catalina.core.StandardService.start(StandardService.java:519)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Please guide me how to fix this problem.
Did silly mistake in web.xml :).Solved by removing .java extension in filter mapping
<filter-class>com.gaic.lpsr.utilclasses.NoCacheFilter</filter-class>
Help!
Trying to implement Protocol Buffers via Rest (Jersey), but get this exception.
class com.util.ProtobufMessageBodyReader
class com.util.ProtobufMessageBodyWriter
Jul 6, 2010 3:43:37 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-9102
Jul 6, 2010 3:43:37 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 45485 ms
Jul 6, 2010 3:49:00 PM org.apache.catalina.connector.CoyoteAdapter convertURI
SEVERE: Invalid URI encoding; using HTTP default
Jul 6, 2010 3:49:00 PM com.sun.jersey.spi.container.ContainerRequest getEntity
SEVERE: A message body reader for Java type, class com.example.tutorial.ProfileRequestProto$ProfileRequest, and MIME media type, application/x-protobuf, was not found
I loaded ProtobufMessageBodyReader/Writer in the Apache ContextLoader.
From the log above, it seems Tomcat found the class but it apparent it fails when it reads
#Consumes("application/x-protobuf")
Here is ProtobufMessageBodyReader
#Provider
#Component
#Consumes("application/x-protobuf")
public class ProtobufMessageBodyReader implements MessageBodyReader<Message> {
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Message.class.isAssignableFrom(type);
}
public Message readFrom(Class<Message> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
try {
Method newBuilder = type.getMethod("newBuilder");
GeneratedMessage.Builder<?> builder = (GeneratedMessage.Builder<?>) newBuilder.invoke(type);
return builder.mergeFrom(entityStream).build();
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
#Override
public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2) {
// TODO Auto-generated method stub
return false;
}
And here is ProtobufMessageBodyWriter
#Provider
#Component
#Produces("application/x-protobuf")
public class ProtobufMessageBodyWriter implements MessageBodyWriter<Message> {
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Message.class.isAssignableFrom(type);
}
public long getSize(Message m, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return m.getSerializedSize();
}
public void writeTo(Message m, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,Object> httpHeaders,OutputStream entityStream) throws IOException, WebApplicationException {
entityStream.write(m.toByteArray());
}
Here is the code from client :
URL url = new URL(URL);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setDoInput(true);
http.setDoOutput(true);
http.setUseCaches(false);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-protobuf");
http.setRequestProperty("Accept", "application/x-protobuf");
DataOutputStream stream = new DataOutputStream(http.getOutputStream ());
if(contentType.equals("application/x-protobuf")) {
ProfileRequest.Builder profile = ProfileRequest.newBuilder();
profile.setName("John");
profile.setId("123");
profile.build().writeTo(http.getOutputStream());
}
stream.flush();
stream.close();
And here is the code from server
#POST
#Consumes("application/x-protobuf")
public byte[] processProtoRequest(ProfileRequest protoRequest) {
byte[] result = null;
ProfileRequest.Builder profile = ProfileRequest.newBuilder();
profile.mergeFrom(protoRequest);
result = getProfileProtoResponse(profile);
}catch(Exception e){
}
return result;
}
I cannot figure out what is the problem.
Is there anything with Jersey config? Or something is wrong when I sent protocol request via HTTP?
Any help will be appreciate it.
Thanks
You mostly nailed the issue yourself already I think:
and MIME media type, application/x-protobuf, was not found
[...]
From the log above, it seems Tomcat found the class but it apparent it fails when it reads
#Consumes("application/x-protobuf")
The media types supported by Jersey (or rather JSR-311/JAX-RS) out of the box are defined in class MediaType. To resolve your issue it might be enough to define an appropriate media type for application/x-protobuf, see thread [Jersey] MediaType-s? for a discussion and samples regarding this.
I just met the same problem on my maven+jersey+protobuf project,and I am using tomcat 6. to me the problems is that the Provider Class the tomcat hasn't found.
After I solve this problem the tomcat 6.0 shows like this :
Deploying configuration descriptor jerseydemo2.xml
一月 26, 2015 11:13:41 上午 com.sun.jersey.api.core.WebAppResourceConfig init
信息: Scanning for root resource and provider classes in the Web app resource paths:
/WEB-INF/lib
/WEB-INF/classes
一月 26, 2015 11:13:41 上午 com.sun.jersey.api.core.ScanningResourceConfig logClasses
信息: Root resource classes found:
class sample.hello.resources.AddressBookResource
一月 26, 2015 11:13:41 上午 com.sun.jersey.api.core.ScanningResourceConfig logClasses
信息: Provider classes found:
class sample.pb.ProtobufMessageBodyReader
class sample.pb.ProtobufMessageBodyWriter
一月 26, 2015 11:13:41 上午 com.sun.jersey.server.impl.application.WebApplicationImpl initiate
信息: Initiating Jersey application, version 'Jersey: 1.2-SNAPSHOT 01/27/2010 01:47 AM'
before it showed the Provider classes not found.
my problems is that the web.xml file has set the specific path for the tomcat to find all the resouces. now I have changed it like this:
<?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_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
hope it helps you !