Provider<HttpSession> not getting injected - gwt

I am using gwt dispatch to communicate and get data from server to client.
In order to get user specific data I want to store the user object in httpsession and access application specific data from servlet context
but when I inject Provider<HttpSession> when the handler execute is called but the dispatchservlet the provider is null i.e it does not get injected.
following is the code from my action handler
#Inject
Provider<HttpSession> provider;
public ReadEntityHandler() {
}
#Override
public EntityResult execute(ReadEntityAction arg0, ExecutionContext arg1) throws DispatchException {
HttpSession session = null;
if (provider == null)
System.out.println("httpSession is null..");
else {
session = provider.get();
System.out.println("httpSession not null..");
}
System.out.println("reached execution");
return null;
}
and my Dispatch servlet
#Singleton
public class ActionDispatchServlet extends RemoteServiceServlet implements StandardDispatchService {
private Dispatch dispatch;
private Dispatch dispatch;
#Inject ReadEntityHandler readEntityHandler;
public ActionDispatchServlet() {
InstanceActionHandlerRegistry registry = new DefaultActionHandlerRegistry();
registry.addHandler(readEntityHandler);
dispatch = new SimpleDispatch(registry);
}
#Override
public Result execute(Action<?> action) throws DispatchException {
try {
return dispatch.execute(action);
}
catch (RuntimeException e) {
log("Exception while executing " + action.getClass().getName() + ": " + e.getMessage(), e);
throw e;
}
}
}
when I try to inject the ReadEntityHandler it throws the following exception
[WARN] failed guiceFilter
com.google.inject.ProvisionException: Guice provision errors:
1) Error injecting constructor, java.lang.NullPointerException
at com.ensarm.wikirealty.server.service.ActionDispatchServlet.<init>(ActionDispatchServlet.java:22)
at com.ensarm.wikirealty.server.service.ActionDispatchServlet.class(ActionDispatchServlet.java:22)
while locating com.ensarm.wikirealty.server.service.ActionDispatchServlet
1 error
at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:834)
at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:856)
at com.google.inject.servlet.ServletDefinition.init(ServletDefinition.java:74)
at com.google.inject.servlet.ManagedServletPipeline.init(ManagedServletPipeline.java:84)
at com.google.inject.servlet.ManagedFilterPipeline.initPipeline(ManagedFilterPipeline.java:106)
at com.google.inject.servlet.GuiceFilter.init(GuiceFilter.java:168)
at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:593)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1220)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:513)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448)
at com.google.gwt.dev.shell.jetty.JettyLauncher$WebAppContextWithReload.doStart(JettyLauncher.java:468)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.handler.RequestLogHandler.doStart(RequestLogHandler.java:115)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:222)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:672)
at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:509)
at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1068)
at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:811)
at com.google.gwt.dev.DevMode.main(DevMode.java:311)
Caused by: java.lang.NullPointerException
at net.customware.gwt.dispatch.server.DefaultActionHandlerRegistry.addHandler(DefaultActionHandlerRegistry.java:21)
at com.ensarm.wikirealty.server.service.ActionDispatchServlet.<init>(ActionDispatchServlet.java:24)
at com.ensarm.wikirealty.server.service.ActionDispatchServlet$$FastClassByGuice$$e0a28a5d.newInstance(<generated>)
at com.google.inject.internal.cglib.reflect.FastConstructor.newInstance(FastConstructor.java:40)
at com.google.inject.internal.DefaultConstructionProxyFactory$1.newInstance(DefaultConstructionProxyFactory.java:58)
at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:84)
at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:200)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:43)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:878)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.Scopes$1$1.get(Scopes.java:64)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:825)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:871)
at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:821)
... 25 more

You create instance of ReadEntityHandler registry.addHandler(new ReadEntityHandler()); himself not by container.Provider<HttpSession> provider; is null
Try:
#Inject
public ActionDispatchServlet(ReadEntityHandler handler) {
InstanceActionHandlerRegistry registry = new DefaultActionHandlerRegistry();
registry.addHandler(handler);
dispatch = new SimpleDispatch(registry);
}

Caused by: java.lang.NullPointerException
at net.customware.gwt.dispatch.server.DefaultActionHandlerRegistry.addHandler(DefaultActionHandlerRegistry.java:21)
Is it possible that DefaultActionHandlerRegistry has a bug in it at line 21, and that the error is happening there? I don't see the code for that class, so it isn't clear if this is the cause of your issue, or just a symptom.

Related

Class not found when trying to return List from consumeEvent in Quarkus

When I try to return a Uni with a typed java.util.List in Quarkus in dev mode, i get a ClassNotFound exception. I have read about Quarkus using different class loaders in different profiles, but I don't see that I do anything fancy.
Here's the sender
#Query("offers")
public Uni<List<OfferResponse>> getOffers(#PathParam("category") Integer categoryId) {
OfferRequest event = new OfferRequest();
event.setCategoryId(categoryId);
Uni<List<OfferResponse>> offers = bus.<List<OfferResponse>>request(OfferRequest.ADDRESS, event).onItem().transform(Message::body);
return offers;
}
And here's the consumer
#ConsumeEvent(OfferRequest.ADDRESS)
public Uni<List<OfferResponse>> onOfferQuery(OfferRequest request) {
List<KelkooOffer> offers = getOffers(request.getCategoryId());
List<OfferResponse> responses = new ArrayList<OfferResponse>();
for (KelkooOffer offer : offers) {
responses.add(offer.getEventResponse());
}
return Uni.createFrom().item(responses);
}
The bean I'm trying to return is just a POJO
and the error message
2021-08-18 11:11:16,186 ERROR [io.qua.run.Application] (Quarkus Main Thread) Failed to start application (with profile dev): java.lang.ClassNotFoundException: java.util.List<se.bryderi.events.OfferResponse>
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:405)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:405)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at io.quarkus.deployment.steps.VertxProcessor$build609260703.deploy_0(VertxProcessor$build609260703.zig:142)
at io.quarkus.deployment.steps.VertxProcessor$build609260703.deploy(VertxProcessor$build609260703.zig:40)
at io.quarkus.runner.ApplicationImpl.doStart(ApplicationImpl.zig:784)
at io.quarkus.runtime.Application.start(Application.java:101)
at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:101)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:66)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:42)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:119)
at io.quarkus.runner.GeneratedMain.main(GeneratedMain.zig:29)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.quarkus.runner.bootstrap.StartupActionImpl$1.run(StartupActionImpl.java:98)
at java.base/java.lang.Thread.run(Thread.java:829)
I get the same result if I run the dev profile or if I run the packaged fast-jar.
Happy for any hint that will point me in the right direction
There is a limitation of the Vert.x EventBus which prevents to encode/decode lists or sets directly.
You could create a wrapper for your OfferResponse list:
import java.util.AbstractList;
import java.util.List;
public class OfferResponseList extends AbstractList<OfferResponse> {
private List<OfferResponse> wrapped;
private OfferResponseList(List<OfferResponse> wrapped) {
this.wrapped = wrapped;
}
public static OfferResponseList wrap(List<OfferResponse> list) {
return new OfferResponseList(list);
}
#Override
public OfferResponse get(int index) {
return wrapped.get(index);
}
#Override
public int size() {
return wrapped.size();
}
}
Then transform your consumer to:
#ConsumeEvent(OfferRequest.ADDRESS)
public Uni<OfferResponseList> onOfferQuery(OfferRequest request) {
List<KelkooOffer> offers = getOffers(request.getCategoryId());
List<OfferResponse> responses = new ArrayList<OfferResponse>();
for (KelkooOffer offer : offers) {
responses.add(offer.getEventResponse());
}
// Notice the call to OfferResponseList.wrap here
return Uni.createFrom().item(OfferResponseList.wrap(responses));
}
That's it. Quarkus will register a codec for OfferResponseList automatically.
On the client side, you do not need to change your code:
#Query("offers")
public Uni<List<OfferResponse>> getOffers(#PathParam("category") Integer categoryId) {
OfferRequest event = new OfferRequest();
event.setCategoryId(categoryId);
// You can use Uni<List<OfferResponse>> or Uni<OfferResponseList>
Uni<List<OfferResponse>> offers = bus.<List<OfferResponse>>request(OfferRequest.ADDRESS, event).onItem().transform(Message::body);
return offers;
}

Task not serializable : Spark

My spark job is throwing Task not serializable at runtime. Can anyone tell me if what i am doing wrong here?
#Component("loader")
#Slf4j
public class LoaderSpark implements SparkJob {
private static final int MAX_VERSIONS = 1;
private final AppProperties props;
public LoaderSpark(
final AppProperties props
) {
this.props = props;
}
#Override
public void run(SparkSession spark, final String... args) throws IOException {
HBaseUtil hBaseUtil = new HBaseUtil(props);
byte[][] prefixes = new byte[][]{toBytes("document"),
toBytes("dataSource"),
toBytes("hold:")};
Filter filter = new MultipleColumnPrefixFilter(prefixes);
Scan scan = new Scan();
scan.addFamily(toBytes("data"));
scan.setCaching(100000);
scan.setMaxVersions(MAX_VERSIONS);
scan.setFilter(filter);
JavaRDD<TestMethod> mapFileJavaRDD
= hBaseUtil.createScanRdd(spark, "TestTable", scan).mapPartitions(tuple -> {
return StreamUtils.asStream(tuple)
.map(this::extractResult)
.filter(Objects::nonNull)
.iterator();
});
Dataset<TestMethod> testDataset = spark.createDataset(mapFileJavaRDD.rdd(), bean(TestMethod.class));
testDataset.limit(100);
}
private TestMethod extractResult(Tuple2<ImmutableBytesWritable, Result> resultTuple) {
TestMethod.TestMethodBuilder testBuilder = TestMethod.builder();
Result result;
result = resultTuple._2();
CdfParser cdfParser = new CdfParser();
List<String> holdingId = new ArrayList<>();
testBuilder.dataSource(Bytes.toString(result.getValue(Bytes.toBytes("data"),
Bytes.toBytes("dataSource"))));
testBuilder.document(cdfParser.fromXml(result.getValue(Bytes.toBytes("data"),
Bytes.toBytes("document"))));
NavigableMap<byte[], byte[]> familyMap = result.getFamilyMap(Bytes.toBytes("data"));
for (byte[] bQunitifer : familyMap.keySet()) {
if (Bytes.toString(bQunitifer).contains("hold:")) {
LOG.info(Bytes.toString(bQunitifer));
holdingId.add(Bytes.toString(bQunitifer));
}
}
testBuilder.holding(holdingId);
return testBuilder.build();
}
}
HERE is the stacktrace:
2020-04-29 12:48:59,837 INFO [Thread-4]o.a.s.d.y.ApplicationMaster: Unregistering ApplicationMaster with FAILED (diag message: User class threw exception: java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:787)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:768)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322)
at org.oclc.googlelinks.spark.SpringSparkJob.main(SpringSparkJob.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$2.run(ApplicationMaster.scala:694)
Caused by: org.apache.spark.SparkException: Task not serializable
at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:393)
at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
at org.apache.spark.SparkContext.clean(SparkContext.scala:2326)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:798)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:797)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
at org.apache.spark.rdd.RDD.mapPartitions(RDD.scala:797)
at org.apache.spark.api.java.JavaRDDLike$class.mapPartitions(JavaRDDLike.scala:155)
at org.apache.spark.api.java.AbstractJavaRDDLike.mapPartitions(JavaRDDLike.scala:45)
at org.oclc.googlelinks.spark.job.LoaderSpark.run(LoaderSpark.java:79)
at org.oclc.googlelinks.spark.SpringSparkJob.run(SpringSparkJob.java:79)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784)
... 8 more
try adding getter and setters for props
public void setProps(AppProperties props) {
this.props = props;
}
public AppProperties getProps() {
return props;
}
Just make the function extractResult static . In order to call a static method, you don’t need to serialize the class, you need the declaring class to be reachable by the classloader (and it is the case, as the jar archives can be shared among driver and workers).
Thanks to https://www.nicolaferraro.me/2016/02/22/using-non-serializable-objects-in-apache-spark/

The web application [ROOT] appears to have started a thread named [pollingConfigurationSource] but has failed to stop it. Memory leak

Hi i am getting memory leak error while running project. I am using spring boot + quards scheduler + liquibase + postgreSQL 9.6. These are technologies we are using.
Error:
12018-10-15 11:43:19.005 WARN [billing,,,] 19152 --- [ost-startStop-1] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [pollingConfigurationSource] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
sun.misc.Unsafe.park(Native Method)
java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1074)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.lang.Thread.run(Thread.java:748)
and my configuration code is:
package com.xyz.api;
#Slf4j
#XyzService
#EnableWebSecurity
#EnableResourceServer
#EnableGlobalMethodSecurity( prePostEnabled = true )
public class BApplication extends ResourceServerConfigurerAdapter implements WebMvcConfigurer
{
public static void main( String[] args )
{
SpringApplication.run( BApplication.class, args );
}
#Override
public void configure( ResourceServerSecurityConfigurer resources )
{
resources.resourceId( "xxxx" );
}
#Override
public void configure( HttpSecurity http ) throws Exception
{
http.authorizeRequests()
.antMatchers( "/" ).permitAll()
.antMatchers( "/docs/**" ).permitAll()
.antMatchers( "/actuator/health" ).permitAll() // can we tighten this up?
.anyRequest().authenticated(); //individual services use annotations
}
#Override
public void addViewControllers( ViewControllerRegistry registry )
{
registry.addViewController( "/" ).setViewName( "forward:/docs/index.html" );
}
#Bean
public Clock clock()
{
return Clock.systemUTC();
}
#Bean
public RestTemplate restTemplate( RestTemplateBuilder builder )
{
return builder.build();
}
}
Actually this work fine earlier but suddenly it give error at deployment. Help me out to solve this issue.
I also referred: Memory Leak Issue with spring-cloud-starter-hystrix and spring-cloud-starter-archaius integration
But not getting any solution on this.

Is it possible to create myown interface (with implementation) to extend neo4j GraphRepository?

I am trying to create an interface extends GraphRepository. Looks like this is impossible. The problem is when I run the smoke test, require a default constructor for CustomerGraphRepositoryImpl. Anybody can help? Thanks. Interface as following:
#NoRepositoryBean
public interface CustomerGraphRepository<T> extends GraphRepository<T> {
public T findNode(Long id);
}
Implementation:
#Repository
public class CustomerGraphRepositoryImpl<T> extends NodeGraphRepositoryImpl<T> implements CustomerGraphRepository<T>{
public CustomerGraphRepositoryImpl(Class<T> clazz, Neo4jTemplate template) {
super(clazz, template);
// TODO Auto-generated constructor stub
}
#Override
public T findNode(Long id) {
try {
return createEntity(getById(id));
} catch (DataRetrievalFailureException e) {
return null;
}
}
protected T createEntity(Node node){
try{
return template.createEntityFromStoredType(node, null);
}
catch(ClassCastException e){
return null;
}
}
}
The failure trace as follows:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
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.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customGraphRepositoryImpl' defined in file [pratice/dao/util/CustomGraphRepositoryImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [pratice.dao.util.CustomGraphRepositoryImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: pratice.dao.util.CustomGraphRepositoryImpl.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1007)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [pratice.dao.util.CustomGraphRepositoryImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: pratice.dao.util.CustomGraphRepositoryImpl.<init>()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:83)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1000)
... 41 more
Caused by: java.lang.NoSuchMethodException: pratice.dao.util.CustomGraphRepositoryImpl.<init>()
at java.lang.Class.getConstructor0(Class.java:2800)
at java.lang.Class.getDeclaredConstructor(Class.java:2043)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78)
... 42 more

Handling REST Exception

I'm using a REST service with CXF that does a GET request with an int parameter.
#Path("parkingservice")
public interface ParkingService {
/**
* #param id
* #return
*/
#GET
#Path("/parkings/{id}/parkingState")
#Produces(MediaType.APPLICATION_JSON)
ParkingState getStatus(#PathParam("id") int id);
}
I call my service this way :
http://domain.com:8087/services/rest/parkingservice/parkings/2805/parkingState
When I put a number, it works, but when I put a String, I have this exception :
WARNING: javax.ws.rs.NotFoundException: java.lang.NumberFormatException: For input string: "dd"
at org.apache.cxf.jaxrs.utils.InjectionUtils.handleParameter(InjectionUtils.java:322)
at org.apache.cxf.jaxrs.utils.InjectionUtils.createParameterObject(InjectionUtils.java:845)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromUriParam(JAXRSUtils.java:1041)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.createHttpParameterValue(JAXRSUtils.java:733)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:708)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:655)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:238)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:99)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:271)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:203)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:137)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:158)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:243)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:168)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:219)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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:680)
Caused by: java.lang.NumberFormatException: For input string: "dd"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.valueOf(Integer.java:554)
at org.apache.cxf.common.util.PrimitiveUtils.read(PrimitiveUtils.java:60)
at org.apache.cxf.jaxrs.utils.InjectionUtils.handleParameter(InjectionUtils.java:310)
... 34 more
I'd like to avoid having this exception no matter what type I give..or to find a way to handle this exception with a message like "please provide a good Id"
Thanks a lot
Add an exception mapper to your rest layer. Code goes something like this :
package com.cxf.util;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class CustomExceptionMapper implements
ExceptionMapper<NotFoundException> {
public CustomExceptionMapper () {
}
#Override
public Response toResponse(NotFoundException arg0) {
//your logic and return accordingly
return Response.serverError().build();
}
}
And you if you are using Spring to maintain your service beans and cxf configuration then add this mapper as a bean under jaxrs:providers tag, where jaxrs is this : xmlns:jaxrs="http://cxf.apache.org/jaxrs"
Whenever your application will throw notfoundexception it will go in this class.
Second option is that you can take this parameter as String then parse it in your try catch block. On NumberformatException return 400 status code. Since you have a custom POJO as return, you can take a object of HttpServletResponse from org.apache.cxf.jaxrs.ext.MessageContext and set status in it. Below is a dummy code:
public class RestServiceImpl implements RestService{
#Context
MessageContext context;
public CustomPojo getData(String id){
HttpServletResponse httpResponse = context.getHttpServletResponse();
try{
}catch(NumberFormatException e){
httpResponse.setStatusCode(400);
}
}
}
Use the below signature for getStatus method, this would work both ways.
ParkingState getStatus(#PathParam("id") String id);
Your getStatus(#PathParam("id") int id); takes integer as an argument and you are trying to pass String instead of int, that's why it's throwing an exception of NumberFormatException.
You have to handle it,or make a Check is the incoming value is int if not then so a message "please provide a valid input".