The method addAnnotatedClass(Class<demo>) is undefined for the type Configuration - hibernate-annotations

The method addAnnotatedClass(Class) is undefined for the type Configuration
I am trying to insert data into data base using Hibernate in my Dynamic web project . Annotations are used instead of XML file. But i am getting a compilation error "The method addAnnotatedClass(Class) is undefined for the type Configuration" .How will i solve it ?
package pak;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory factory= new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(demo.class).buildSessionFactory();
Session session=factory.getCurrentSession();
try{
demo obj=new demo("name1","name2","name3");
session.beginTransaction();
session.save(obj);
session.getTransaction().commit();
}finally{
factory.close();
}
}
}
i want to know that, what is the cause compilation error "The method addAnnotatedClass(Class) is undefined for the type Configuration" and how to solve it

Most probably you have forgotten to Annotate the demo class that you want to import there:
You should declare Annotations before you use that class.

Related

No exception of type DataAccessException can be thrown; an exception type must be a subclass of Throwable

My source code like below.
It has a error, "No exception of type DataAccessException can be thrown; an exception type must be a subclass of Throwable".
I can't understand why the error ocurrs.
let me know. thx.
package com.sds.afi.cosmos.cmm.db.impl;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.stereotype.Repository;
import com.sds.afi.cosmos.cmm.db.MainDao;
#Repository
//#SuppressWarnings("unchecked") // 부적절한 컴파일러의 경고를 제거
public class MainDaoImpl extends SqlMapClientDaoSupport implements MainDao {
#Autowired
private SqlMapClientTemplate sqlMapClientTemplate;
#SuppressWarnings("unchecked")
#Override
public List<HashMap> getUserInfo() throws DataAccessException {
List<HashMap> lists;
lists = sqlMapClientTemplate.queryForList("common.getList");
return lists;
}
}
This can happen if some class in the type-hierarchy of the exception is not on the class-path. In that case, its not possible to verify whether the exception really extends Throwable, whether it is a checked one or not, etc. Hence the errors. e.g superclass of Dataaccessexception : NestedRuntimeException may be missing from the class-path as it is in a differnt jar i.e. spring-core.
Your DataAccessException is not a subclass of Throwable class (extends Throwable). It should be, and without this inheritance, your code is not compilable with the current throws clause.
Here is an example: http://www.osix.net/modules/article/?id=754
I had this same issue when I upgraded to 5.X.X version. I have added Spring-core.jar file and it worked fine for me. Just adding this here because it may help some one. Spring txn jar , dao jar and spring core are must.
This means that in your getUserInfo() method there is no code that throws that exception. So just remove the throws clause from your method declaration.
I was facing same problem.
What I have done wrong was I have created Exception class(by mistake) of my own.
In other programs I was trying to extend Exception class(default) but complier(eclipse)was loading user defined Exception class giving me same error.
So please make sure you are not overriding any default class.

HTTP status code 500 for NotFoundException

I'm developing an application with RESTEasy and JBOSS 5.1.
For specific situations, I have to return 404 error (not found).
In the sources, I'm using
import org.jboss.resteasy.spi.NotFoundException;
throw new NotFoundException(...);
The problem is that, in the header response, I have
Status Code: 500 internal server error
even if in the body the exception is:
org.jboss.resteasy.spi.UnhandledException: org.jboss.resteasy.spi.NotFoundException
This is a normal behavior? It's not possible to return Status Code: 404?
I encounter some problem. I found the root cause. The built-in exception handle is only occur in resteasy newest version build 2.3.1 GA. If you upgrade to this version.You can get the expected result.
It does seem a bit strange that RestEASY does not handle the NotFoundException out of the box. It should, according to the docs:
Resteasy has a set of built-in exceptions that are thrown by it when it encounters errors during dispatching or marshalling.
Anyways, you can work around it by adding an ExceptionMapper:
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.spi.NotFoundException;
import org.junit.Assert;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ExceptionTest {
#Path("/")
public static class Service {
#GET
public String notFound() throws NotFoundException {
throw new NotFoundException("");
}
}
public static class FailureExceptionMapper implements ExceptionMapper<NotFoundException> {
#Override
public Response toResponse(NotFoundException exception) {
return Response.status(exception.getErrorCode()).build();
}
}
#Test
public void test() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getProviderFactory().addExceptionMapper(new FailureExceptionMapper());
dispatcher.getRegistry().addSingletonResource(new Service());
MockHttpRequest request = MockHttpRequest.get("/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals(404, response.getStatus());
}
}
I believe that instead of throwing an exception you should use:
import javax.ws.rs.core.Response;
return Response.status(404).build();
in your rest method when you need to return a not found.
regards.
Maybe a custom javax.servlet.Filter can help.

Using Jackson JSON Views without annotating original bean class

Is there any way that I can use Jackson JSON Views or something like it, without having to annotate the original bean class? I'm looking for some kind of runtime/dynamic configuration to let me do something similar.
My bean is an #Entity packaged in a JAR that may be shared by multiple projects. I'm trying to avoid touching and re-packaging the shared JAR because of UI changes in the consuming projects.
Ideally I'd like to do something like
jsonViewBuilder = createViewBuilder(View.class);
jsonViewBuilder.addProperty("property1");
jsonViewBuilder.addProperty("property2");
to replace
Bean {
#JsonView(View.class)
String property1;
#JsonView(View.class)
String property2;
}
Any ideas?
Underlying environment: Spring 3.0, Spring MVC and Glassfish 3.1.1.
How about using the Mix-In feature?
http://wiki.fasterxml.com/JacksonMixInAnnotations
http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonView;
public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
mapper.getSerializationConfig().addMixInAnnotations(Bar.class, BarMixIn.class);
mapper.setSerializationConfig(mapper.getSerializationConfig().withView(Expose.class));
System.out.println(mapper.writeValueAsString(new Bar()));
// output: {"b":"B"}
}
}
class Bar
{
String a = "A";
String b = "B";
}
abstract class BarMixIn
{
#JsonView(Expose.class)
String b;
}
// Used only as JsonView marker.
// Could use any existing class, like Object, instead.
class Expose {}

RestEasy ExceptionMapper not catching the exceptions

I'm throwing an exception MyCustomException from my application. (EJB Layer)
I've an exception mapper in web service layer which looks like following -
package net.webservices;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import net.common.MyCustomException;
#Provider
public class EJBExceptionMapper implements
ExceptionMapper<net.common.MyCustomException> {
public Response toResponse(MyCustomException exception) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
I've registered my mapper in web.xml of the web service layer as following -
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>net.webservices.EJBExceptionMapper</param-value>
</context-param>
The EJBExceptionMapper is not catching the MyCustomException. But instead its being caught by the catch block of the web service implementation.
What could be the problem?
Note: I don't want to register my ExceptionMapper manually using getProviderFactory().addExceptionMapper()
I don't know why your solution doesn't work (but I've never used RESTeasy, only Jersey). In any case, it would probably be simpler to extend WebApplicationException. That way, you don't have to register a provider:
public class MyCustomException extends WebApplicationException {
public MyCustomException() {
super(Response.status(Response.Status.BAD_REQUEST).build());
}
}
You need to throw exception (of type MyCustomException ) in the catch block and add a "Throws MyCustomException" to the method signature

Cant mock static functions with powermock-easymock-testng (non-maven project)

To tell you first, i have tried and tried it again and now i need some help
Heres my code
package staticPkg;
public class Static {
public static final String staticMethod() {
System.out.println("Static method called");
return "Static called";
}
}
package staticPkg;
public class TargetClass {
Static staticClass;
public String callHere() {
return Static.staticMethod();
}
}
package staticPkg;
import org.easymock.EasyMock;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.IObjectFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
#PrepareForTest({Static.class})
public class TestClass {
Static staticClass = null;
#ObjectFactory
public IObjectFactory getObjectFactory() {
System.out.println("got object factory");
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
#BeforeMethod
public void setup() {
System.out.println("print me");
PowerMock.mockStatic(Static.class);
staticClass = PowerMock.createMock(Static.class);
}
#Test
public void testMe() {
EasyMock.expect(Static.staticMethod()).andReturn("Mock called").anyTimes();
PowerMock.replay(Static.class,staticClass);
TargetClass tc = new TargetClass();
String output = tc.callHere();
PowerMock.verify(Static.class,staticClass);
System.out.println(output);
}
}
And heres the log
[Parser] Running:
C:\MockWorkspace\Mock\temp-testng-customsuite.xml
got object factory
print me
Static method called
FAILED: testMe
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:521)
at org.easymock.EasyMock.expect(EasyMock.java:499)
at staticPkg.TestClass.testMe(TestClass.java:46)
... Removed 22 stack frames
===============================================
staticPkg.TestClass
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Mock
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Help please, i have tried a variety of solutions, can't get it done.
Please can anyone try this code and correct it for success?
I get error in EasyMock.expect ...............
Got a work around at http://blogs.bytecode.com.au/glen/2006/10/12/doing-bytecode-kungfu-with-javassist.html
And it works
But wait..........I am stuck again
My testcase works fine when runs alone, but when run with Ant, it gives problem. Might be other test cases of different files are interfering.
I got the same error, when my individual test case was using #PrepareTest & easymock/powermock
[testng] ====================STATIC CALLED===========================
[testng] javassist.CannotCompileException: by java.lang.LinkageError: loader (instance of sun/misc/Launcher$AppClass
Loader): attempted duplicate class definition for name: "com/symantec/mobius/aggregator/submission/SubmissionFactory"
[testng] at javassist.ClassPool.toClass(ClassPool.java:1085)
[testng] at javassist.ClassPool.toClass(ClassPool.java:1028)
[testng] at javassist.ClassPool.toClass(ClassPool.java:986)
[testng] at javassist.CtClass.toClass(CtClass.java:1110)
Try extending from PowerMockTestCase. The TestNG support will also be updated in next version of PowerMock (1.4.9).
I faced this same issue, and struggled a lot. Finally, found the following solution:
Another alternative is to set the object-factory to org.powermock.modules.testng.PowerMockObjectFactory in the TestNG suite.xml. Here is a sample suite file:
<suite name="dgf" verbose="10" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
<test name="dgf">
<classes>
<class name="com.example.ClientTest"/>
</classes>
</test>
</suite>
Of course, you can also extend your test case from PowerMockTestCase as told by Johan.
Mock all the static methods in static class before proceeding to mock the static method. Try with this:
#Test
public void testMe() {
PowerMock.mockStatic(Static.class);
EasyMock.expect(Static.staticMethod()).andReturn("Mock called").anyTimes();
PowerMock.replay(Static.class,staticClass);
TargetClass tc = new TargetClass();
String output = tc.callHere();
PowerMock.verify(Static.class,staticClass);
System.out.println(output);
}