Strange exception using Jersey with embedded Jetty - rest

I have created an embedded Jetty application which utilizes Jersey in order to implement several RESTful services. I am using some standard code as described here in Stack Overflow as well as other websites:
public static void main(String[] args)
{
Server server = new Server(8080);
ServletContextHandler ctx = new ServletContextHandler(
ServletContextHandler.SESSIONS);
ctx.setContextPath("/");
ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer.class", "/*");
holder.setInitOrder(0);
holder.setInitParameter("jersey.config.server.provider.classnames",
RestfulClass.class.getCanonicalName());
server.setHandler(ctx);
try
{
server.start();
server.join();
}
catch(Exception exe)
{
exe.printStackTrace();
}
}
I've used all the recommended jar files, and several other jar files that the various blogs and sites failed to mention. When running the Jetty application, I get the following exception:
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer.class
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:86)
at org.eclipse.jetty.servlet.BaseHolder.doStart(BaseHolder.java:95)
<several lines omitted for brevty>
Caused by: javax.servlet.UnavailableException: org.glassfish.jersey.servlet.ServletContainer.class
at org.eclipse.jetty.servlet.BaseHolder.doStart(BaseHolder.java:102)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:361)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:874)
... 11 more
It is the "UnavailableException" that I do not understand. The ServletContainer class is actually in one of the Jar files (in jersey-container-servlet-core.jar, to be precise), but for some reason it is identified as "unavailable". This is causing a class that is actually in a referenced Jar file to be "not found"!
Can anyone tell me what is causing this UnavailableException and (more importantly) how I can prevent it from being thrown?
Someone please advise...

ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer.class", "/*");
You are using a String for the class name. When doing this, you don't use the .class suffix. That at only when you want to get the actual Class object. You have two options
Remove the .class from the String
ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer", "/*");
Remove the "" (double quotes) and just use the Class object1.
ServletHolder holder = ctx.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
1 - See addServlet(Class, String)

Related

Why the error is displayed as java.lang.ClassNotFoundException: for the following groovy code?

class First {
public First() {
super()
// TODO Auto-generated constructor stub
}
static void main(String s)
{
print('Hii');
}
}
After running the code in eclipse using Groovy Console option the following exception is being shown.
java.lang.ClassNotFoundException: groovy.ui.Console
at org.codehaus.groovy.tools.RootLoader.findClass(RootLoader.java:179)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.codehaus.groovy.tools.RootLoader.loadClass(RootLoader.java:151)
at java.lang.ClassLoader.loadClass(Unknown Source)
Nothing wrong with the code. Groovy Console dependencies are not included by default with Groovy 2.5+ You can use Groovy 2.4 which bundles groovy-all or run as Java Application since you have a class with a main method.

Endpoints API generation error when using Guava

We are using Appengine Endpoints Java with Guava and when Function is used inside an endpoint method the API generator returns an exception.
Function is NOT part of the method signature. Its just used inside the method to transform a list. Comment out this body part and it generates OK.
Guava sure is in the classpath, and other parts of the application uses it normally.
I'm not sure its related to Guava or any outside API would give the same error.
The method:
#ApiMethod(
httpMethod = "GET",
name = "ledgers.accountgroups.get",
path="ledgers/{ledgerId}/accountgroups")
public Collection<IAccountGroup> listAccountGroups(#Named("ledgerId") String ledgerId, User user) throws Exception {
collaboratorDAO.assertCollaboratorOn(ledgerId, user);
List<Group> groups = accountGroupsDAO.getAccountGroups(ledgerId);
List<IAccountGroup> transformedGroups = Lists.transform(groups, new Function<Group, IAccountGroup>() {
#Override
public IAccountGroup apply(Group group) {
return group.createClient();
}
});
return transformedGroups;
}
The exception:
INFO: Successfully processed ./war/WEB-INF/appengine-web.xml
interface com.google.api.server.spi.config.Api
interface com.google.api.server.spi.config.Api
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Function
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2436)
at java.lang.Class.getDeclaredMethods(Class.java:1793)
at com.google.api.server.spi.MethodHierarchyReader.addServiceMethods(MethodHierarchyReader.java:174)
at com.google.api.server.spi.MethodHierarchyReader.readMethodHierarchyIfNecessary(MethodHierarchyReader.java:44)
at com.google.api.server.spi.MethodHierarchyReader.getEndpointOverrides(MethodHierarchyReader.java:99)
at com.google.api.server.spi.config.annotationreader.ApiConfigAnnotationReader.readEndpointMethods(ApiConfigAnnotationReader.java:215)
at com.google.api.server.spi.config.annotationreader.ApiConfigAnnotationReader.loadEndpointMethods(ApiConfigAnnotationReader.java:92)
at com.google.api.server.spi.config.ApiConfigLoader.loadConfiguration(ApiConfigLoader.java:55)
at com.google.api.server.spi.tools.AnnotationApiConfigGenerator.generateConfigObjects(AnnotationApiConfigGenerator.java:237)
at com.google.api.server.spi.tools.AnnotationApiConfigGenerator.generateConfig(AnnotationApiConfigGenerator.java:185)
at com.google.api.server.spi.tools.GenApiConfigAction.genApiConfig(GenApiConfigAction.java:78)
at com.google.api.server.spi.tools.GetClientLibAction.getClientLib(GetClientLibAction.java:66)
at com.google.api.server.spi.tools.GetClientLibAction.execute(GetClientLibAction.java:49)
at com.google.api.server.spi.tools.EndpointsTool.execute(EndpointsTool.java:66)
at com.google.api.server.spi.tools.EndpointsTool.main(EndpointsTool.java:92)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 16 more
It's very simple not to use Guava at this point, and it works. I just want to know why this is happening as I need a more have use of Guava in other parts.
Update:
I think it the same problem as:
Google Cloud Endpoints doesn't know about the Work class from Objectify 4 Transaction, causing ClassNotFoundException
Any tips?
Thanks!

com.mysql.jdbc.Driver not found when trying to add SQL features in Jitsi

I'm coding on Jitsi using Eclipse: I have to use JDBC to connect to MySQL database, so I've imported java.sql.* in my MainFrame class and I've included mysql-connector-java-5.1.18.jar into "Java Build Path" -> "Libraries".
When I run the project, I've this error:
IOException in readRegistry: java.io.EOFException
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver not found by [76]
at org.apache.felix.framework.ModuleImpl.findClassOrResourceByDelegation(ModuleImpl.java:787)
at org.apache.felix.framework.ModuleImpl.access$400(ModuleImpl.java:71)
at org.apache.felix.framework.ModuleImpl$ModuleClassLoader.loadClass(ModuleImpl.java:1768)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at net.java.sip.communicator.impl.gui.main.MainFrame.init(MainFrame.java:301)
at net.java.sip.communicator.impl.gui.main.MainFrame.<init>(MainFrame.java:239)
at net.java.sip.communicator.impl.gui.UIServiceImpl.loadApplicationGui(UIServiceImpl.java:133)
at net.java.sip.communicator.impl.gui.GuiActivator.start(GuiActivator.java:129)
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
at org.apache.felix.framework.Felix.activateBundle(Felix.java:1827)
at org.apache.felix.framework.Felix.startBundle(Felix.java:1744)
at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1148)
at org.apache.felix.framework.StartLevelImpl.run(StartLevelImpl.java:264)
at java.lang.Thread.run(Unknown Source)
I've created another project separated from Jitsi and I've tested my code following the same procedure (including java.sql.*; , adding the library), but the "new" project works fine and I can connect to my database, Jitsi doesn't.
Source:
import java.sql.*;
public class SQLFirstTime {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/cdcol";
Connection con = DriverManager.getConnection(url,"user", "pass");
// ...
con.close();
} catch(SQLException sqlEx) {
System.out.println("Errore SQL");
sqlEx.printStackTrace();
} catch(ClassNotFoundException cnfEx) {
System.out.println("Class NOT FOUND!");
cnfEx.printStackTrace();
}
}
}
Thanks,
also if i'm using Ant to build the project how can I include the JDBC library?

Getting exception in initializing log4j files

When trying to initialize hibernate from configuration file, I get NullPointerException ..
Root cause is shown as
Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException))
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:543)
I have all the logging related jars and properties files in class path.
My hibernate initialization code is :
private static final SessionFactory sessionFactory;
private static final ThreadLocal<Session> hibernateSession=new ThreadLocal<Session>();
static{
try{
sessionFactory=new Configuration().configure("llhs_hibernate.cfg.xml").buildSessionFactory();
System.out.println("done");
}catch (HibernateException he){
he.printStackTrace();
throw new ExceptionInInitializerError(he);
}catch (Exception e){
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
Simple java classes does not complain about log related error, for example following java class does not complain ..It properly initializes and writes to logs folder
public class MetadataService implements Serializable {
private static final Logger logger = LogManager.getLogger(MetadataService.class);
private static final long serialVersionUID = 1L;
public MetaData getMetaData(){
logger.info("Info");
try {
//some code here
} catch (Exception e1) {
logger.error("Error");
}
return metaData;
}
Since it works for stand alone Java class and not for class doing hibernate initialization --I am more perplexed ..Any pointer? Detailed trace
java.lang.ExceptionInInitializerError
at com.llhs.persistence.impl.db.hibernate.utils.HibernateUtils.<clinit>(HibernateUtils.java:17)
at com.llhs.persistence.impl.hibernate.HibernateDbImplTest.addStudentDetails(HibernateDbImplTest.java:61)
at com.llhs.persistence.impl.hibernate.HibernateDbImplTest.testAddFindStudentDetails(HibernateDbImplTest.java:128)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException(Caused by java.lang.NullPointerException))
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:543)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:235)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:209)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:351)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:126)
... 26 more
Caused by: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException)
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:397)
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:529)
... 30 more
Caused by: java.lang.NullPointerException
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:374)
... 31 more
There is alignment issue while posting trace, sorry abt that, not able to correct that one..
Finally, I was able to solve this. As later guessed it turned out to be an eclipse configuration. In eclipse 3.7, code name indigo, the way libs were being added to the classpath caused this issue ..
First way:
Debug Configurations->classpath->bootstarp entries, if Add libs added by selecting "Add Jars" options, THIS DOES NOT Work.
Correct WAY:
Define a classpath variable from window->preferences->java->buildpath->classpath variable, say HIBERNATE_LIBS and point it ti libs folder
Now, got to Debug Configurations->classpath->bootstarp entries, select "Advanced option" and add the class path variable. This FIXED the issue.
I guess this is specific to 3.7, as I upgraded the eclipse version and started getting this issue, First way still works in eclipse 3.2

'#{customer.all}' Error reading 'all' on type com.corejsf.CustomerBean] with root cause java.lang.NullPointerException

I googled but can't find a solution for this. It is from Core JSF 3rd.
I did:
1) Included JSF Mojarra in Build path.
2) Included MySQL JDBC driver in Build path.
3) Copied MySQL JDBC driver to Tomcat "lib" folder and "ext" JDK folder.
4) I tested JDBC driver with a small Java app and it succeeded.
CustomerBean from corejsf source code:
public class CustomerBean {
#Resource(name="jdbc/corejsf")
private DataSource source;
public ResultSet getAll() throws SQLException {
Connection conn = source.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM Customers");
// return ResultSupport.toResult(result);
CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl();
// or use an implementation from your database vendor
crs.populate(result);
return crs;
} finally {
conn.close();
}
}
}
Error:
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/DatabaseTest] threw exception [/index.jsp(12,3) '#{customer.all}' Error reading 'all' on type com.corejsf.CustomerBean] with root cause
java.lang.NullPointerException
at com.corejsf.CustomerBean.getAll(CustomerBean.java:18)
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 javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:554)
at javax.faces.component.UIData.getDataModel(UIData.java:1248)
at javax.faces.component.UIData.setRowIndex(UIData.java:447)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:823)
at javax.faces.component.UIData.encodeBegin(UIData.java:937)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1611)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1613)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at com.sun.faces.application.view.JspViewHandlingStrategy.doRenderView(JspViewHandlingStrategy.java:420)
at com.sun.faces.application.view.JspViewHandlingStrategy.renderView(JspViewHandlingStrategy.java:209)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
You need to configure a JNDI datasource with the name jdbc/corejsf in Tomcat.
I suspect that datasource is not injected, since nothing in your class path interprets the #Resource annotation. As far as I know, #Resource is an EJB annotation, but Tomcat is no EJB container. Try looking up the datasource programatically.