java.lang.ClassNotFoundException: org.hibernate.criterion.Projection - eclipse

Good Morning, please i don't know how to resolve that exception, i'm using ApcheTomcat 7 under eclipse and that exception is thrown everytime i run my servlet, here's my servlet for more clarity:
package servlets;
import java.util.*;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.*;
#WebServlet("/AdminServlt")
public class AdminServlt extends HttpServlet {
private static final long serialVersionUID = 1L;
CarHome carDao;
public void init(ServletConfig config) throws ServletException{
carDao = new CarHome();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
populateAdminView(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
public void populateAdminView(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
ArrayList productsList = (ArrayList) carDao.extractAdminAttributes();
HttpSession session = request.getSession(true);
session.setAttribute("product_list",productsList);
RequestDispatcher rd = request.getRequestDispatcher("Admin.jsp");
rd.forward(request, response);
}
}
and here's CarHome.java
package dao;
import java.util.ArrayList;
import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.*;
import entity.*;
public class CarHome {
private static final Log log = LogFactory.getLog(CarHome.class);
private final SessionFactory sessionFactory = getSessionFactory();
public List extractAdminAttributes() {
log.debug("Extracting car attributes for administrator view");
try {
ArrayList results = (ArrayList) sessionFactory
.getCurrentSession()
.createCriteria("pojo.Car")
.setProjection(
Projections.projectionList()
.add(Projections.property("carDesc"))
.add(Projections.property("price"))
.add(Projections.property("quantity")));
return results;
} catch (RuntimeException re) {
log.error("find by admin view failed");
throw re;
}
}
}
here's the stacktrace of the exception
java.lang.ClassNotFoundException: org.hibernate.criterion.Projection
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
servlets.AdminServlt.init(AdminServlt.java:31)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)

i have solved my problem it was very simple, the main reason is that the hibernate.cor.jar file wasn't in the lib folder under the web-content of the application when i put it there it works fine

I was facing the same issue but in my case i re-ordered the hibernate-cor.jar on the top using eclipse
chose the project --> right click -->build path -->order tab -->chose the hibernate-cor.jar click top

Related

Facing HTTP 415 Unsupported Media Type from JAX-RS client when using MessageBodyReader

I am new to RESTFul wit JAX-RS and learning. I am facing problem only when i request from JAX-RS client application. Its working fine from post plugin. But when i am changing the #Consumes("myformat/xml") with "application/xml" then its working. Below is the code.
MessageBodyReader:
package com.memorynotfound.jaxrs.chunked;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
#Provider
#Consumes("myformat/xml")
public class UserMessageBodyReader implements MessageBodyReader<User> {
public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
if (arg0.equals(User.class))
return true;
else
return false;
}
public User readFrom(Class<User> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
MultivaluedMap<String, String> arg4, InputStream arg5) throws IOException, WebApplicationException {
return new User(1, "Jphn Doe");
}
}
Resource:
package com.memorynotfound.jaxrs.chunked;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
#Path("/users")
public class UserResource {
#POST
#Consumes("myformat/xml")
public User getUser(User user) {
return user;
}
}
Client code:
package com.restfulexample.client.messagebodyreader;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
public class MessageBodyReader {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
User user = new User(1, "Jphn Doe");
User postedUser = client.target("http://localhost:9090/message-body-reader/api/users").request("myformat/xml")
.post(Entity.xml(user), User.class);
System.out.println(postedUser.getId() + " " + postedUser.getName());
}
}
Found the solution with the below code...
Client client = ClientBuilder.newClient().register(UserMessageBodyReader.class)
.register(UserMessageBodyWriter.class);
We have to register both MessageBodyReader and Writer with the client.

Kafka streams NoClassDefFoundError ByteBufferInputStream

I am trying the following Kafka stream sample code.
http://kafka.apache.org/0110/documentation/streams/tutorial
import java.io.*;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.json.JSONObject;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStreamBuilder;
#WebServlet("/KafkaStreamsTest")
public class KafkaStreamsTest extends HttpServlet {
/**
*
*/
private final String topic = "testtopic";
private final String streamouttopic = "streamtesttopic";
public static final String CLIENT_ID = "SampleStreamProducer";
JSONObject jsonObject;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
}
// Do the same thing for GET and POST requests
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
System.out.println("Server called");
Properties props = new Properties();
props.put("bootstrap.servers", "localhost");
props.put("group.id", CLIENT_ID);
props.put(StreamsConfig.APPLICATION_ID_CONFIG, CLIENT_ID);
props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
KStreamBuilder builder = new KStreamBuilder();
builder.stream(topic).to(streamouttopic);
final KafkaStreams streams = new KafkaStreams(builder, props);
final CountDownLatch latch = new CountDownLatch(1);
// attach shutdown handler to catch control-c
Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
#Override
public void run() {
streams.close();
latch.countDown();
}
});
try {
streams.start();
latch.await();
} catch (Throwable e) {
System.exit(1);
}
System.exit(0);
}
}
When I run this, I am getting error as
Exception in thread "StreamThread-1" java.lang.NoClassDefFoundError: org/apache/kafka/common/record/ByteBufferInputStream
Could someone guide me what could the reason? I have kafka-clients-0.11.0.0-cp1.jar, kafka-streams-0.10.0.0.jar and other required JAR files included in this Eclipse project.

WELD-001408 Unsatisfied dependencies

I have a very famous error, but I can't solve it.
I'm trying to run arqullian test for my application.
I've done everything according to the official documentation.
The long search for solution to the problem given nothing.
16:49:42,713 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.deployment.unit."test.war".WeldService: org.jboss.msc.service.StartException in service jboss.deployment.unit."test.war".WeldService: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Sender] with qualifiers [#Default] at injection point [[field] #Inject com.test.test2.ejb.AppManagerBean.sender]
at org.jboss.as.weld.services.WeldService.start(WeldService.java:83)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_13]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_13]
at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_13]
Caused by: org.jboss.weld.exceptions.DeploymentException:
WELD-001408 Unsatisfied dependencies for type [Sender] with qualifiers [#Default]
at injection point [[field] #Inject com.test.test2.ejb.AppManagerBean.sender]
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:275)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:244)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:107)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:127)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:346)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:331)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:366)
at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:83)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:76)
... 5 more
My test class:
package com.highstreetlabs.wlcome.rest;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.test.test2.ejb.AppManager;
import com.test.test2.ejb.Storage;
import com.test.test2model.Customer;
import com.test.test2.rest.model.ProximityModel;
import com.test.test2.util.EntityManagerProducer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.json.simple.parser.ParseException;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.ejb.EJB;
import javax.inject.Inject;
#RunWith(Arquillian.class)
public class CustomerCollectionResourceTest {
#Deployment
public static WebArchive createTestArchive() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(CustomerCollectionResource.class, EntityManagerProducer.class,
AppManager.class, Storage.class,
ParseException.class, Sender.class)
.addPackage(Customer.class.getPackage())
.addPackage(Result.class.getPackage())
.addPackage(NotFoundException.class.getPackage())
.addPackage(CustomerPhotoResource.class.getPackage())
.addPackage(ProximityModel.class.getPackage())
.addAsResource("import.sql")
.addAsManifestResource(EmptyAsset.INSTANCE, "META-INF/beans.xml")
.addAsManifestResource("test-ds.xml", "test-ds.xml");
}
#Inject
CustomerCollectionResource resource;
#EJB
AppManager manager;
#Test
public void testList() throws Exception {
resource = new CustomerCollectionResource();
resource.list(null);
}
}
AppManagerBean.java
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.google.common.base.Strings;
import com.test.test2.json.JacksonObjectMapperProvider;
import com.test.test2.model.*;
import com.test.test2.rest.HttpStatusException;
import com.test.test2.rest.NotFoundException;
import com.test.test2.rest.model.ProximityModel;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.Asynchronous;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.*;
import javax.persistence.criteria.*;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.List;
/**
* Stateless EJB bean containing entire business logic implementation
*/
#Local(AppManager.class)
#Stateless
public class AppManagerBean implements AppManager {
public static final String
GCM_ENTER_ACTION = "enter",
GCM_EXIT_ACTION = "exit",
PARAM_DATA_JSON = "proximityModel",
PARAM_CUSTOMER_ID = "customerId",
PARAM_ACTION = "action";
#Inject
EntityManager em;
#Inject
Sender sender;
....
}
And finally class for test CustomerCollectionResource
#Path("customer/")
#RequestScoped
public class CustomerCollectionResource {
final static int CACHEABLE_SECONDS = 0;
#EJB
private AppManager manager;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response list(#QueryParam("email") String email) {
final List<Customer> entities = manager.listCustomers(email);
if(entities.size() == 0)
throw new NotFoundException("There is no any customer");
ListModel<ListItem> result = new ListModel<ListItem>(entities.size());
result.itemType = ListItem.MEDIA_TYPE;
final UriBuilder itemLink = UriBuilder.fromResource(CustomerResource.class);
for (Customer entity : entities) {
result.add(new ListItem(entity.getName(), itemLink.build(entity.getId())));
}
CacheControl cc = new CacheControl();
cc.setMaxAge(CACHEABLE_SECONDS);
cc.setPrivate(true);
return Response.ok(result).cacheControl(cc).build();
}
}
Sender Producer
public class GcmSenderProducer {
#Resource String senderId;
#Produces public Sender getSender() {
return new Sender(senderId);
}
}
Yes, I also think the GcmSenderProducer is missing so the Sender class cannot be injected propperly since it looks like it has no no-arg constructor and I guess the constructor.

Why I receive error when use Cover As in Eclipse and not with Junit?

I use Eclipse with eCobertura
I have a little project with a Controller (SpringMVC).
I created a test (JUnit).
When I run the test from JUnit (in Eclipse IDE) all is right but when I run the command (from menu) I receive an error
My controller :
package ec.europa.eu.nwi.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* #author LEBRUJA
*/
#Controller
public class AvailibilityController {
/**
* #param request
* #return mav
*/
#RequestMapping(value = "/available")
public final ModelAndView available(final HttpServletRequest request) {
final ModelAndView mav = new ModelAndView("available", "sample",
new String("availability on 0.0.1"));
return mav;
}
}
My Test :
package ec.europa.eu.nwi.web.controller.test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.ModelAndViewAssert;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import ec.europa.eu.nwi.web.controller.AvailibilityController;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:spring-servlet.xml"})
public final class AvalibilityControllerTest {
private transient MockHttpServletRequest request;
private transient MockHttpServletResponse response;
#Autowired
private RequestMappingHandlerAdapter handlerAdapter;
#Autowired
private RequestMappingHandlerMapping handlerMapping;
private static final Logger LOGGER = LoggerFactory.getLogger(AvalibilityControllerTest.class);
#Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
#After
public void tearDown() throws Exception {
LOGGER.debug("TearDown");
}
#Test
public void testAvailable() {
LOGGER.debug("Start testAvailable1");
LOGGER.debug("Test only availibility of the apps");
final AvailibilityController avc = new AvailibilityController();
final Object mav = avc.available(request);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(mav instanceof ModelAndView);
ModelAndViewAssert.assertAndReturnModelAttributeOfType((ModelAndView)mav, "sample", String.class);
ModelAndViewAssert.assertModelAttributeAvailable((ModelAndView)mav, "sample");
ModelAndViewAssert.assertModelAttributeValue((ModelAndView)mav, "sample", "availability on 0.0.1");
ModelAndViewAssert.assertViewName((ModelAndView)mav, "available");
final BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(true);
LOGGER.debug("End testAvailable1");
}
#Test
public void testAvailable1() throws Exception {
LOGGER.debug("Start testAvailable");
LOGGER.debug("Test only availibility of the apps");
request.setMethod("GET");
request.setRequestURI("/available.html");
Object handler = handlerMapping.getHandler(request).getHandler();
LOGGER.debug("Get the Model and View");
ModelAndView modelAndView = handlerAdapter.handle(request, response,handler);
Assert.assertEquals("availability on 0.0.1", modelAndView.getModel().get("sample"));
Assert.assertTrue(modelAndView.getModel().containsKey("sample"));
LOGGER.debug("End testAvailable");
}
}
If I run with JUnit (Run As Junit), all is right but when I run Cover As .. JUnit I receive the error.
The error :
I filtered the class (from exclude configuration in Eclipse Coverage Configuration).
If I removed the filter, the junit code is marked in red
I don't understand the error.
Thanks a lot
I had
<aop:aspectj-autoproxy proxy-target-class="true" />
In my applicationContext.xml and it is running fine now
Thanks a lot

How can I redirect to another page in Servlet using response.sendRedirect() method?

**loginServlet.java**
package com.anil.apps;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String uid=request.getParameter("userid");
String password=request.getParameter("pwd");
if(uid.equals("Anil")&&password.equals("missinlx")){
//out.println("welcome "+uid);
response.sendRedirect("welcomeUser?userid="+uid);
}
else{
out.println("invalid username or password");
}
}
}
**WelcomeUserServlet.java**
package com.anil.apps;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("<html><body><h1>Welcome " +uid+ "</h1></body></html>");
}
}
what is wrong with my code?? I want to redirect the page to welcomeUser.java page using response.sendRedirect() method.
As I am new to servlet please help me out of it. please tell me the whole format for the page redirection in Servlets.
GET parameters are not turned in to variables automatically. You need to add this to the top of your doGet method in the WelcomeUserServlet:
String uid = request.getParameter("userId");
Making that class look like this:
public class WelcomeUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uid = request.getParameter("userId");
PrintWriter out=response.getWriter();
out.println("<html><body><h1>Welcome " +uid+ "</h1></body></html>");
}
}
You are using the wrong argument for the sendRedirect method
You should use a complete path like
response.sendRedirect("some/path/here/to/"+welcomeUser?userid="+uid)
Or better
response.sendRedirect(response.encodeURL(response.getContextPath()+"welcomeUser?userid="+uid))
Or use a request dispatcher which knows the structure of your project and does not need a full path
request.getRequestDispatcher("welcomeUser?userid="+uid).forward(request,response)