I'm getting the following error when I run my flow:
java.lang.IllegalArgumentException: Step Requesting Stellar to execute the escrow. not found in progress tracker.
at net.corda.core.utilities.ProgressTracker.setCurrentStep(ProgressTracker.kt:140) ~[corda-core-4.3.jar:?]
at com.finablr.money.loyalty.wallet.flows.RevokeCustomToken.call(RevokeCustomToken.java:139) ~[wallet-workflows-0.1.jar:?]
at com.finablr.money.loyalty.wallet.flows.RevokeCustomToken.call(RevokeCustomToken.java:36) ~[wallet-workflows-0.1.jar:?]
at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:270) ~[corda-node-4.3.jar:?]
at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:46) ~[corda-node-4.3.jar:?]
at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) ~[quasar-core-0.7.10-jdk8.jar:0.7.10]
at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) ~[quasar-core-0.7.10-jdk8.jar:0.7.10]
at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) ~[quasar-core-0.7.10-jdk8.jar:0.7.10]
at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) ~[quasar-core-0.7.10-jdk8.jar:0.7.10]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[?:1.8.0_222]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:1.8.0_222]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) ~[?:1.8.0_222]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[?:1.8.0_222]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[?:1.8.0_222]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[?:1.8.0_222]
at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:63) ~[corda-node-4.3.jar:?]
Even though I do have that step defined inside my flow:
private final Step STELLAR_EXECUTE_ESCROW = new Step("Requesting Stellar to execute the escrow.");
private final ProgressTracker progressTracker = new ProgressTracker(
STELLAR_EXECUTE_ESCROW
);
// Inside the call() method.
// Checkpoint workflow to replay from here in case of node failure.
sleep(Duration.ofMillis(1));
// Request Stellar to execute the escrow.
progressTracker.setCurrentStep(STELLAR_EXECUTE_ESCROW);
Flow tests didn't throw that error, it only happened on Google cloud; not sure whether check-pointing the flow is causing that or not.
Are you saying the issue was unique to google cloud? You didn't have this issue when running locally?
I'd double-check how you've defined the progressTracker.
Here's the highlights on a progresstracker definition from a code sample I've got handy.
public class YoFlow extends FlowLogic<SignedTransaction> {
private static final ProgressTracker.Step CREATING = new ProgressTracker.Step("Creating a new Yo!");
private static final ProgressTracker.Step SIGNING = new ProgressTracker.Step("Signing the Yo!");
private static final ProgressTracker.Step VERIFYING = new ProgressTracker.Step("Verfiying the Yo!");
private static final ProgressTracker.Step FINALISING = new ProgressTracker.Step("Sending the Yo!") {
#Nullable
#Override
public ProgressTracker childProgressTracker() {
return FinalityFlow.tracker();
}
};
ProgressTracker progressTracker = new ProgressTracker(
CREATING,
SIGNING,
VERIFYING,
FINALISING
);
#Nullable
#Override
public ProgressTracker getProgressTracker() {
return progressTracker;
}
private final Party target;
public YoFlow(Party target) {
this.target = target;
}
#Suspendable
#Override
public SignedTransaction call() throws FlowException {
progressTracker.setCurrentStep(CREATING);
As another possibility, make sure you're overriding the progress tracker methods, if you don't then you can't call the flow over SSH due to an obscure corda bug.
See https://docs.corda.net/docs/corda-os/4.4/shell.html#limitations
"Flows cannot be run unless they override the progress tracker"
Related
Ive implemented a KafkaConsumerFactory in which for the errors (Retryable error) I throw the exception. I want these exceptions to be printed an a proper logging format like sflf4j(LOGGER.ERROR) and not print on the console.
The ask is I want to print the errors in a proper log format instead of throwing in console with a huge stacktrace.
Below is the code snippet for KakaConsumerConfigFactory.java that has DLT Implementation to process and push error records to DLT topic.
package org.abc;
import org.apache.kafka.common.TopicPartition;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.kafka.ConcurrentKafkaListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.util.backoff.FixedBackOff;
import com.azure.cosmos.CosmosException;
import com.azure.spring.data.cosmos.exception.CosmosAccessException;
import com.fasterxml.jackson.core.JsonProcessingException;
#Configuration
public class KafkaListenerConfig {
#Bean(name = "kafkaListenerContainerFactory")
public ConcurrentKafkaListenerContainerFactory<Object, Object> kafkaListenerContainerFactory(
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
ConsumerFactory<Object, Object> kafkaConsumerFactory, KafkaTemplate<Object, Object> template) {
ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
configurer.configure(factory, kafkaConsumerFactory);
var recoverer = new DeadLetterPublishingRecoverer(template,
(record, ex) -> new TopicPartition("abc_dlt", record.partition()));
var errorHandler = getDLTDetails(recoverer);
factory.setCommonErrorHandler(errorHandler);
return factory;
}
#Bean(name = "kafkaListenerContainerFactoryForDLT")
public ConcurrentKafkaListenerContainerFactory<Object, Object> kafkaListenerContainerFactoryForDLT(
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
ConsumerFactory<Object, Object> kafkaConsumerFactory, KafkaTemplate<Object, Object> template) {
ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
configurer.configure(factory, kafkaConsumerFactory);
var errorHandler = new DefaultErrorHandler(new FixedBackOff(3, 2));
factory.setCommonErrorHandler(errorHandler);
factory.getContainerProperties().setIdleEventInterval(70000L);
return factory;
}
private DefaultErrorHandler getDLTDetails(DeadLetterPublishingRecoverer recoverer) {
var errorHandler = new DefaultErrorHandler(recoverer, new FixedBackOff(3, 2));
errorHandler.addNotRetryableExceptions(JsonProcessingException.class);
errorHandler.addRetryableExceptions(DBException.class, DataAccessException.class);//Sample db exceptions
errorHandler.setCommitRecovered(true);
return errorHandler;
}
}
Below is the class in which the error is throw from listener.java
#Component
public class Listener {
#Autowired
private LogUtil log; //Custom logger
public Listener (final LogUtil log) {
this.log= log;
}
#KafkaListener(id = "hub_topic", topics = "hub_topic", groupId = "hub_topic_0", containerFactory = "kafkaListenerContainerFactory", clientIdPrefix = "hub_topic")
public void listen(ConsumerRecord<String, String> consumerRecord, Acknowledgment ack) {
log.printLog("INFO",consumerRecord.value());
saveToDB(consumerRecord.value()); //Method to persist obtained request to Database Columns //: id, String Payload-Consumer record
ack.acknowledge();
}
}
You can prevent the stack trace logs by setting the error handler's logLevel property to TRACE.
Then, subclass the error hander and do whatever logging you want do yourself after calling the super class methods.
EDIT
For example:
#Bean
CommonErrorHandler eh() {
DefaultErrorHandler eh = new DefaultErrorHandler((rec, ex) -> {
System.out.println("Recovered " + KafkaUtils.format(rec));
}, new FixedBackOff(3000L, 2)) {
#Override
public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records,
Consumer<?, ?> consumer, MessageListenerContainer container) {
try {
super.handleRemaining(thrownException, records, consumer, container);
// log record was recovered
}
catch (RuntimeException ex) {
// log retrying or recovery failed
throw ex;
}
}
};
eh.setLogLevel(Level.TRACE);
return eh;
}
I'll try to develop simple web service.
In order to make test data, i create test class.
However, in this class, there is error that service classes are not autowired.
help me.
Why it is not autoried?
This is error message.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 42 more
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:53)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:451)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$c4ca4a4e.CGLIB$defaultServletHandlerMapping$26(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$c4ca4a4e$$FastClassBySpringCGLIB$$3fa44495.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:355)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$c4ca4a4e.defaultServletHandlerMapping(<generated>)
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.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 43 more
This is my test class.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = AppInitializer.class)
public class createTestData {
#Autowired
private UserService userService;
#Autowired
private ReadabilityService readabilityService;
#Test
#Transactional
public void createTestData()
{
.....
testData.setUser(userService.findByUsername("test1"));
.....
}
}
This is configuration class.
package com.websystique.springmvc.configuration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import com.websystique.springmvc.service.UserService;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.websystique.springmvc")
public class AppConfig extends WebMvcConfigurerAdapter{
/**
* Configure ViewResolvers to deliver preferred views.
*/
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
/**
* Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
*/
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
/**
* Configure Converter to be used.
* In our example, we need a converter to convert string values[Roles] to UserProfiles in newUser.jsp
*/
#Override
public void addFormatters(FormatterRegistry registry) {
}
/**
* Configure MessageSource to lookup any validation/error message in internationalized property files
*/
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Order(Ordered.HIGHEST_PRECEDENCE)
#Bean
CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return filter;
}
/**Optional. It's only required when handling '.' in #PathVariables which otherwise ignore everything after last '.' in #PathVaidables argument.
* It's a known bug in Spring [https://jira.spring.io/browse/SPR-6164], still present in Spring 4.1.7.
* This is a workaround for this issue.
*/
#Override
public void configurePathMatch(PathMatchConfigurer matcher) {
matcher.setUseRegisteredSuffixPatternMatch(true);
}
}
help me
Have you read the stacktrace? Which indicates you are trying to load web based classes in a now web based test. Read the documentation on how to be able to test web based things
This question already has answers here:
No WebApplicationContext found: no ContextLoaderListener registered?
(2 answers)
Closed 5 years ago.
I have the typical application Spring with Hibernate using annotation based configuration (Spring 4 MVC+Hibernate 4+MySQL+Maven integration ).
Here my class:
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class AppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet(
"dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
The content above resembles the content of web.xml as we are using the front-controller DispatherServler, assigning the mapping (url-pattern in xml) and instead of providing the path to spring configuration file(spring-servlet.xml) , here we are registering the Configuration Class.
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:252)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I've upload the same war to another tomcat 7 and it works ! and in my tomcat other applications like http://localhost:8080/examples/ works well, as well. Strange
public class AppInitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext webApplicationContext = null;
webApplicationContext = new AnnotationConfigWebApplicationContext();
webApplicationContext.setConfigLocation("//write the package name pointing to configuration classes
like webApplicationConfig and RootWebApplicationConfig classes//");
DispatcherServlet dispatcherServlet = null;
dispatcherServlet = new DispatcherServlet(webApplicationContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", dispatcherServlet);
servlet.addMapping("*.mvc");
servlet.setLoadOnStartup(2);
}
}
I just explain how to do this using custom class and implement interface.
I try my best to solve this question,i have only five month experience in spring-mvc and not done this custom spring servlet mapping in practicle.
I hope my post is help you.
Maven configuration:Add any spring mvc version dependency
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
Custom Initializer class
public class AppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("eu.kielczewski.example.config");
return context;
}
Configuration classes
#Configuration
#ComponentScan(basePackages = "eu.kielczewski.example")
public class AppConfig {
}
I have seen this error happening when there is a JAR dependencies problem or a lack of dependencies. If you are in Eclipse sometimes I lose my Maven dependencies. You can check this by doing right click in the project, go to Deployment Assembly and make sure that Maven Dependencies is there. If not click Add and select Maven Dependencies.
Try to add ContextLoaderListener to your ServletContext, here:
conteiner.addListener(new ContextLoaderListener(ctx));
Hi I have a strange problem,
I'am following this Tutorial (http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/) and at step 5, configurting initializer class there are two ways of doing that:
1 with WebAppInitializer (my code below)
public class SpindleSpringWebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(AppConfig.class);
appContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
With AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer (my code here)
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
This is my AppConfig.java
#Configuration
#EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
The Thing is that when I use the first method everything works, but when I use the second one i get 404 (description The requested resource is not available). I have no other errors and I have no idea how to debug this. I wouldn't bother but I'm trying to implement Spring Security to the code and as I understand the secon type of initializer is the preffered type nowdays.
I'm using Maven, STS, Pivotal tc Servert Developer Edition. Thanks for any feedback.
The problem is solved. Target folder still held web.xml and context.xml files. Deleting target folder and reinstalling the app was the right thing to do
I am trying to call when someone tap or click on a number which in a TextView.
I have added permission in Android AndroidMainfest.xml
<uses-permission android:name="android.permission.CALL_PHONE" />
Also I have set the TextView android:clickable="true"
I am very new in Android development so please Help me.
I am sorry for my bad English.
Here is My code AboutDeveloper.java
package com.rupomkhondaker.sonalibank;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class AboutDeveloper extends Fragment {
public AboutDeveloper(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final TextView tv_phone = (TextView)getActivity().findViewById(R.id.devMobile);
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String phone_no= tv_phone.getText().toString().replaceAll(":", "");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+phone_no));
startActivity(callIntent);
}
});
View rootView = inflater.inflate(R.layout.fragment_developer, container, false);
return rootView;
}
}
ERROR LOG
09-20 20:28:05.852 622-622/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.rupomkhondaker.sonalibank.AboutDeveloper.onCreateView(AboutDeveloper.java:22)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
at android.app.BackStackRecord.run(BackStackRecord.java:635)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Replace your code by this code and tell me what is the output.
public class AboutDeveloper extends Fragment {
public AboutDeveloper(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_developer, container, false);
final TextView tv_phone = (TextView)v.findViewById(R.id.devMobile);
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try
{
String uri = "tel:"+tv_phone.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
}
catch(Exception e) {
Toast.makeText(getActivity(),"Your call has failed...",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
return v;
}
Since you were getting
java.lang.NullPointerException
at com.rupomkhondaker.sonalibank.AboutDeveloper.onCreateView(AboutDeveloper.java:22)
it meant that it was not able to find the view element.