I am using spring-kafka 2.2.8 to create a batch consumer and getting an exception when i deploy my consumer.
java.lang.ClassCastException: org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter cannot be cast to org.springframework.kafka.listener.MessageListener
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.AbstractKafkaListenerEndpoint.setupMessageListener(AbstractKafkaListenerEndpoint.java:455) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.AbstractKafkaListenerEndpoint.setupListenerContainer(AbstractKafkaListenerEndpoint.java:433) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.AbstractKafkaListenerContainerFactory.createListenerContainer(AbstractKafkaListenerContainerFactory.java:310) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.AbstractKafkaListenerContainerFactory.createListenerContainer(AbstractKafkaListenerContainerFactory.java:62) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.KafkaListenerEndpointRegistry.createListenerContainer(KafkaListenerEndpointRegistry.java:200) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.KafkaListenerEndpointRegistry.registerListenerContainer(KafkaListenerEndpointRegistry.java:172) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.KafkaListenerEndpointRegistry.registerListenerContainer(KafkaListenerEndpointRegistry.java:146) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.KafkaListenerEndpointRegistrar.registerAllEndpoints(KafkaListenerEndpointRegistrar.java:164) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.config.KafkaListenerEndpointRegistrar.afterPropertiesSet(KafkaListenerEndpointRegistrar.java:158) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.afterSingletonsInstantiated(KafkaListenerAnnotationBeanPostProcessor.java:263) ~[spring-kafka-2.2.7.RELEASE.jar!/:2.2.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:862) ~[spring-beans-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.1.7.RELEASE.jar!/:2.1.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:743) ~[spring-boot-2.1.7.RELEASE.jar!/:2.1.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:390) ~[spring-boot-2.1.7.RELEASE.jar!/:2.1.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) ~[spring-boot-2.1.7.RELEASE.jar!/:2.1.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.SpringApplication.run(SpringApplication.java:1214) ~[spring-boot-2.1.7.RELEASE.jar!/:2.1.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.SpringApplication.run(SpringApplication.java:1203) ~[spring-boot-2.1.7.RELEASE.jar!/:2.1.7.RELEASE]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at com.abc.xyz.yyy.kafka.integrationtestapi.Application.main(Application.java:10) ~[classes/:?]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_202]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_202]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_202]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_202]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) ~[app/:?]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) ~[app/:?]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.loader.Launcher.launch(Launcher.java:51) ~[app/:?]
2020-11-11T13:38:31.97-0500 [APP/PROC/WEB/0] OUT at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52) ~[app/:?]
Here is my consumer config
#Bean
public ConsumerFactory consumerFactory(){
return new DefaultKafkaConsumerFactory(consumerConfigs(),stringKeyDeserializer(), avroValueDeserializer());
}
#Bean
public RetryPolicy getRetryPolicy(){
SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(3);
return simpleRetryPolicy;
}
#Bean
public FixedBackOffPolicy getBackOffPolicy() {
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(100);
return backOffPolicy;
}
#Bean
public RetryTemplate getRetryTemplate(){
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(getRetryPolicy());
retryTemplate.setBackOffPolicy(getBackOffPolicy());
return retryTemplate;
}
#Bean
public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory(){
ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory();
factory.setConsumerFactory(consumerFactory());
factory.setBatchListener(true);
factory.setStatefulRetry(true);
factory.setRetryTemplate(getRetryTemplate());
return factory;
}
Now my question is,
Is it mandatory to setup ErrorHandler when i set retryTemplate? Or am i missing something else here which is causing this exception?
RetryTemplate is not supported for a batch listener (we don't know which record in the batch failed).
It's best to use a RetryTemplate directly in the listener for that case.
Like this...
#KafkaListener(...)
void listen(List<Foo> in) {
in.forEach(foo -> {
this.retryTemplate.execute(context -> {
// process the foo
}, context -> {
// retries exhausted - save somewhere and move on to the next
});
});
}
Starting with version 2.3.7, you can configure a RetryingBatchErrorHandler and the whole batch will be retried.
Starting with version 2.5, you can configure a RecoveringBatchErrorHandler where you can throw a special exception to the handler which record in the batch failed so only unprocessed records will be redelivered.
Related
When I run the app Butterknife binds ok, but in my Robolectric 3.0 test I'm getting the following exception:
java.lang.RuntimeException: Unable to bind views for com.elt.passsystem.fragment.residential.task.TaskInstanceGeneralFragment
at butterknife.ButterKnife.bind(ButterKnife.java:322)
at butterknife.ButterKnife.bind(ButterKnife.java:279)
at com.elt.passsystem.fragment.residential.task.TaskInstanceGeneralFragment.onCreateView(TaskInstanceGeneralFragment.java:75)
at android.support.v4.app.Fragment.$$robo$$performCreateView(Fragment.java:1974)
at android.support.v4.app.Fragment.performCreateView(Fragment.java)
at android.support.v4.app.FragmentManagerImpl.$$robo$$moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java)
at android.support.v4.app.FragmentManagerImpl.$$robo$$moveToState(FragmentManager.java:1252)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java)
at android.support.v4.app.BackStackRecord.$$robo$$run(BackStackRecord.java:742)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java)
at android.support.v4.app.FragmentManagerImpl.$$robo$$execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java)
at android.support.v4.app.FragmentManagerImpl$1.$$robo$$run(FragmentManager.java:517)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java)
at android.os.Handler.$$robo$$handleCallback(Handler.java:733)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.$$robo$$dispatchMessage(Handler.java:95)
at android.os.Handler.dispatchMessage(Handler.java)
at org.robolectric.shadows.ShadowMessageQueue.dispatchMessage(ShadowMessageQueue.java:130)
at org.robolectric.shadows.ShadowMessageQueue.access$100(ShadowMessageQueue.java:30)
at org.robolectric.shadows.ShadowMessageQueue$1.run(ShadowMessageQueue.java:95)
at org.robolectric.util.Scheduler.runOrQueueRunnable(Scheduler.java:230)
at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:85)
at org.robolectric.shadows.ShadowMessageQueue.enqueueMessage(ShadowMessageQueue.java:116)
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.robolectric.internal.bytecode.ShadowWrangler$ShadowMethodPlan.run(ShadowWrangler.java:437)
at android.os.MessageQueue.enqueueMessage(MessageQueue.java)
at android.os.Handler.$$robo$$enqueueMessage(Handler.java:626)
at android.os.Handler.enqueueMessage(Handler.java)
at android.os.Handler.$$robo$$sendMessageAtTime(Handler.java:595)
at android.os.Handler.sendMessageAtTime(Handler.java)
at android.os.Handler.$$robo$$sendMessageDelayed(Handler.java:566)
at android.os.Handler.sendMessageDelayed(Handler.java)
at android.os.Handler.$$robo$$post(Handler.java:326)
at android.os.Handler.post(Handler.java)
at android.support.v4.app.FragmentManagerImpl.$$robo$$enqueueAction(FragmentManager.java:1523)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java)
at android.support.v4.app.BackStackRecord.$$robo$$commitInternal(BackStackRecord.java:638)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java)
at android.support.v4.app.BackStackRecord.$$robo$$commit(BackStackRecord.java:617)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java)
at org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment(SupportFragmentTestUtil.java:22)
at com.elt.passsystem.fragment.residential.task.TestTaskInstanceGeneralFragment.setup(TestTaskInstanceGeneralFragment.java:75)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:65)
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.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1873)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:773)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:638)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:98)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:78)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:57)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
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.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.ClassCastException: com.elt.passsystem.widget.residential.ResidentialTaskContextView cannot be cast to com.elt.passsystem.widget.residential.ResidentialTaskContextView
at com.elt.passsystem.fragment.residential.task.TaskInstanceBaseFragment$$ViewBinder.bind(TaskInstanceBaseFragment$$ViewBinder.java:12)
at com.elt.passsystem.fragment.residential.task.TaskInstanceGenMedBaseFragment$$ViewBinder.bind(TaskInstanceGenMedBaseFragment$$ViewBinder.java:9)
at com.elt.passsystem.fragment.residential.task.TaskInstanceGenMedBaseFragment$$ViewBinder.bind(TaskInstanceGenMedBaseFragment$$ViewBinder.java:7)
at butterknife.ButterKnife.bind(ButterKnife.java:319)
... 85 more
java.lang.NullPointerException
at com.elt.passsystem.fragment.residential.task.TaskInstanceGenMedBaseFragment.addRadioGroupListener(TaskInstanceGenMedBaseFragment.java:74)
at com.elt.passsystem.fragment.residential.task.TaskInstanceGeneralFragment.onCreateView(TaskInstanceGeneralFragment.java:80)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at org.robolectric.shadows.ShadowMessageQueue.dispatchMessage(ShadowMessageQueue.java:130)
at org.robolectric.shadows.ShadowMessageQueue.access$100(ShadowMessageQueue.java:30)
at org.robolectric.shadows.ShadowMessageQueue$1.run(ShadowMessageQueue.java:95)
at org.robolectric.util.Scheduler.runOrQueueRunnable(Scheduler.java:230)
at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:85)
at org.robolectric.shadows.ShadowMessageQueue.enqueueMessage(ShadowMessageQueue.java:116)
at android.os.MessageQueue.enqueueMessage(MessageQueue.java)
at android.os.Handler.enqueueMessage(Handler.java:626)
at android.os.Handler.sendMessageAtTime(Handler.java:595)
at android.os.Handler.sendMessageDelayed(Handler.java:566)
at android.os.Handler.post(Handler.java:326)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1523)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:638)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:617)
at org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment(SupportFragmentTestUtil.java:22)
at com.elt.passsystem.fragment.residential.task.TestTaskInstanceGeneralFragment.setup(TestTaskInstanceGeneralFragment.java:75)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:65)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1873)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:773)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:638)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:98)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:78)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:57)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
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.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
The Test setup
#Before
public void setup() throws Exception {
Injector.getInstance().setComponent(
DaggerTestComponent.builder()
.mockGlobalConfigsModule(new MockGlobalConfigsModule(true))
.mockDataAccessModule(new MockDataAccessModule(true))
.jobManagerModule(new JobManagerModule(RuntimeEnvironment.application))
.build()
);
PowerMockito.mockStatic(LogCustom.class);
PowerMockito.doNothing().when(LogCustom.class, "v", Mockito.anyString(), Mockito.anyString());
fragment = new TaskInstanceGeneralFragment();
SupportFragmentTestUtil.startFragment(fragment, EpisodeOfCareDetailActivity.class);
completeRadioGroup = fragment.getView().findViewById(R.id.radio_group_complete);
reasonLinearLayout = fragment.getView().findViewById(R.id.linear_layout_reason);
}
The Fragment onCreateView
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.fragment_residential_activity_general, null, false);
try {
ButterKnife.bind(this, root);
} catch (Exception e) {
e.printStackTrace();
}
Please can someone help to fathom this out as I'd like to use butterknife and robolectric together.
PowerMock is quite often conflicting with Robolectric. The issue is resolved as author removed it from tests
I'm trying to make my Jpa repositories asynchronous, see https://github.com/spring-projects/spring-data-examples/tree/master/jpa/java8
Here's my code:
#Configuration
#EnableJpaRepositories(basePackages = "..")
#ComponentScan( {".."} )
#EnableJpaAuditing(..)
#EnableAsync
public class ServicesConfig {
...
}
public interface AsyncRegistrationRepository extends JpaRepository<Registration, Long> {
#Async
#Query("select r from Registration r")
CompletableFuture<List<Registration>> findAllAsync();
}
#Test
#Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testFindAllAsync() throws Exception {
asyncRegistrationRepository.save(randomRegistration(randomToken()));
asyncRegistrationRepository.save(randomRegistration(randomToken()));
asyncRegistrationRepository.save(randomRegistration(randomToken()));
final CompletableFuture<Void> future = asyncRegistrationRepository.findAllAsync().thenAccept(registrations -> {
assertThat(registrations.size()).isEqualTo(3);
registrations.forEach(registration -> LOG.debug(registration.toString()));
LOG.debug("finished");
});
while (!future.isDone()) {
LOG.debug("Waiting for the CompletableFuture to finish...");
TimeUnit.MILLISECONDS.sleep(500);
}
future.get();
}
But when I run my test, throws a NonUniqueResultException, and I don't really know why.. Here's the full stacktrace:
java.util.concurrent.ExecutionException: javax.persistence.NonUniqueResultException: result returns more than one elements
at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)
at net.twentyfourseven.registration.core.repository.AsyncRegistrationRepositoryTest.testFindAllAsync(AsyncRegistrationRepositoryTest.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:85)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:86)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:241)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
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:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: javax.persistence.NonUniqueResultException: result returns more than one elements
at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:492)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:362)
at com.sun.proxy.$Proxy74.getSingleResult(Unknown Source)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:206)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:78)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:100)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:91)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:413)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:391)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy70.findAllAsync(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:108)
at org.springframework.aop.interceptor.AsyncExecutionAspectSupport$CompletableFutureDelegate$1.get(AsyncExecutionAspectSupport.java:237)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
at java.lang.Thread.run(Thread.java:745)
I have to mention that I'm new to Java8 and maybe the problem is just, that I use the CompletableFuture in a wrong way. But in the link above, the test is working and mine is almost the same.
Thanks in advance for all ideas and suggestions!
P.S.: I'm using hibernate-entitymanager 5.0.0.Final, Spring 4.2.0.RELEASE, spring-data-jpa 1.8.2.RELEASE.
Hello I am working on Spring MVC application. Shiro is the security framework for my application. Now I want to write unit tests for my application. I am facing some issues with getting shiro's SecurityUtils class in my controllers while testing. I am pasting my code snippets below. I am re-using my bean definitions for both testing and development.
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.nsl.eds.domain.User;
#Controller
public class HomeController {
#RequestMapping({ "/", "/home" })
public String showHome(Model model) {
model.addAttribute("user",(User) SecurityUtils.getSubject().getPrincipal());
return "home";
}
}
This is my controller, and below is my Test class
#ContextConfiguration
(
{
//"classpath:beans.xml",
"file:src/main/webapp/WEB-INF/frontController-servlet.xml",
"file:src/main/webapp/WEB-INF/dao-definition.xml",
"file:src/main/webapp/WEB-INF/schemacrawler-context.xml",
"file:src/main/webapp/WEB-INF/security-settings.xml"
}
)
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
public class HomeControllerTest extends AbstractShiroTest {
#Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
private Subject subjectUnderTest;
protected MockHttpSession mockSession;
#Before public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
final Authenticate bean = (Authenticate)ctx.getBean("authenticate");
//1. Create a mock authenticated Subject instance for the test to run:
subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();//Mockito.mock(Subject.class);
//expect(subjectUnderTest.isAuthenticated()).andReturn(true);
mockSession = new MockHttpSession(ctx.getServletContext(),
subjectUnderTest.getSession().getId().toString());
//2. Bind the subject to the current thread:
setSubject(subjectUnderTest);
//bean.logon("User01", "User01", mockSession.getId());
//2. Bind the subject to the current thread:
setSubject(subjectUnderTest);
//perform test logic here. Any call to
//SecurityUtils.getSubject() directly (or nested in the
//call stack) will work properly.
}
#Test
public void testShowHome() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/home"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("/WEB-INF/views/home.jsp"))
.andExpect(model().attributeExists("user"));
}
#After
public void detachSubject()
{
subjectThreadState.clear();
}
}
With final Authenticate bean = (Authenticate)ctx.getBean("authenticate"); uncommented, My Stack trace is
org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.
at org.apache.shiro.SecurityUtils.getSecurityManager(SecurityUtils.java:123)
at com.nsl.eds.security.shiro.AbstractShiroTest.getSecurityManager(AbstractShiroTest.java:60)
at com.nsl.eds.web.home.HomeControllerTest.setUp(HomeControllerTest.java:54)
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:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
java.lang.NullPointerException
at com.nsl.eds.web.home.HomeControllerTest.detachSubject(HomeControllerTest.java:108)
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:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
With final Authenticate bean = (Authenticate)ctx.getBean("authenticate"); commented, My Stack trace is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'authenticate' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1168)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:281)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at com.nsl.eds.web.home.HomeControllerTest.setUp(HomeControllerTest.java:52)
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:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
java.lang.NullPointerException
at com.nsl.eds.web.home.HomeControllerTest.detachSubject(HomeControllerTest.java:108)
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:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Also I am having and shiro Abstract authentication class
public abstract class AbstractShiroTest {
protected static ThreadState subjectThreadState;
public AbstractShiroTest() {
}
protected void setSubject(Subject subject) {
clearSubject();
subjectThreadState = createThreadState(subject);
subjectThreadState.bind();
}
protected Subject getSubject() {
return SecurityUtils.getSubject();
}
protected ThreadState createThreadState(Subject subject) {
return new SubjectThreadState(subject);
}
/**
* Clears Shiro's thread state, ensuring the thread remains clean for future test execution.
*/
protected void clearSubject() {
doClearSubject();
}
private static void doClearSubject() {
if (subjectThreadState != null) {
subjectThreadState.clear();
subjectThreadState = null;
}
}
protected static void setSecurityManager(SecurityManager securityManager) {
SecurityUtils.setSecurityManager(securityManager);
}
protected static SecurityManager getSecurityManager() {
return SecurityUtils.getSecurityManager();
}
#AfterClass
public static void tearDownShiro() {
doClearSubject();
try {
SecurityManager securityManager = getSecurityManager();
LifecycleUtils.destroy(securityManager);
} catch (UnavailableSecurityManagerException e) {
//we don't care about this when cleaning up the test environment
//(for example, maybe the subclass is a unit test and it didn't
// need a SecurityManager instance because it was using only
// mock Subject instances)
}
setSecurityManager(null);
}
}
Can any body figure out the issue?
I solved this issue by mocking shiro's org.apache.shiro.mgt.SecurityManager.
#Before
public void setup(){
...
SecurityManager securityManger = mock(SecurityManager.class, RETURNS_DEEP_STUBS);
ThreadContext.bind(securityManger);
...
}
I am creating a web application using Ebay Java SDK. I have created a code to get session id using credentials. now it is working file if I run the java file. but if I want to call it from Servlet and deploy it on JBoss, then the same method stop working and give the parse stream exception nested by character conversion.
Regarding code following is the code I am using.
ApiContext apiContext = new ApiContext();
ApiCredential cred = apiContext.getApiCredential();
ApiAccount apiAccount = cred.getApiAccount();
apiAccount.setApplication(LabelConstants.PROD_APP_ID);
apiAccount.setCertificate(LabelConstants.PROD_CERT_ID);
apiAccount.setDeveloper(LabelConstants.PROD_DEV_ID);
apiContext.setApiServerUrl(LabelConstants.PROD_API_URL);
apiContext.setRuName(LabelConstants.PROD_RU_NAME);
GetSessionIDCall gsic = new GetSessionIDCall(apiContext);
gsic.setRuName(apiContext.getRuName());
try {
sessionId = gsic.getSessionID();
System.out.println(sessionId);
} catch (ApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SdkException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
17:22:23,255 WARNING [org.apache.cxf.phase.PhaseInterceptorChain] (http-localhost-127.0.0.1-8080-1) Interceptor for {urn:ebay:apis:eBLBaseComponents}eBayAPIInterfaceService#{urn:ebay:apis:eBLBaseComponents}GetSessionID has thrown exception, unwinding now: java.lang.RuntimeException: Couldn't parse stream.
at org.apache.cxf.staxutils.StaxUtils.createXMLStreamReader(StaxUtils.java:1178)
at org.apache.cxf.interceptor.StaxInInterceptor.handleMessage(StaxInInterceptor.java:104)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:795)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1626)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1493)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1401)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:648)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:531)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:461)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:364)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:317)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:88)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:134)
at com.sun.proxy.$Proxy44.getSessionID(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_67]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_67]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_67]
at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_67]
at com.ebay.sdk.ApiCall.callSOAP(Unknown Source) [ebaysdkcore.jar:]
at com.ebay.sdk.ApiCall.executeByApiName(Unknown Source) [ebaysdkcore.jar:]
at com.ebay.sdk.ApiCall.execute(Unknown Source) [ebaysdkcore.jar:]
at com.ebay.sdk.call.GetSessionIDCall.getSessionID(GetSessionIDCall.java:76) [ebaycalls.jar:]
at com.ba.label.conf.GetApiContext.getSessionId(GetApiContext.java:73) [classes:]
at com.ba.label.servlet.AuthServlet.doGet(AuthServlet.java:43) [classes:]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_67]
Caused by: com.ctc.wstx.exc.WstxIOException: Invalid UTF-8 start byte 0x8b (at char #2, byte #-1)
at com.ctc.wstx.stax.WstxInputFactory.doCreateSR(WstxInputFactory.java:536)
at com.ctc.wstx.stax.WstxInputFactory.createSR(WstxInputFactory.java:585)
at com.ctc.wstx.stax.WstxInputFactory.createSR(WstxInputFactory.java:610)
at com.ctc.wstx.stax.WstxInputFactory.createXMLStreamReader(WstxInputFactory.java:316)
at __redirected.__XMLInputFactory.createXMLStreamReader(__XMLInputFactory.java:139) [jboss-modules.jar:1.1.1.GA]
at org.apache.cxf.staxutils.StaxUtils.createXMLStreamReader(StaxUtils.java:1176)
... 42 more
Caused by: java.io.CharConversionException: Invalid UTF-8 start byte 0x8b (at char #2, byte #-1)
at com.ctc.wstx.io.UTF8Reader.reportInvalidInitial(UTF8Reader.java:303)
at com.ctc.wstx.io.UTF8Reader.read(UTF8Reader.java:189)
at com.ctc.wstx.io.ReaderBootstrapper.initialLoad(ReaderBootstrapper.java:250)
at com.ctc.wstx.io.ReaderBootstrapper.bootstrapInput(ReaderBootstrapper.java:133)
at com.ctc.wstx.stax.WstxInputFactory.doCreateSR(WstxInputFactory.java:531)
... 47 more
Can anyone explain how can I run the Ebay SDK on Servlet and container?
I had the same issue
yourcall.setEnableCompression(false);
worked for me
Looks like SBT classloading messes with Mockito.
project/Build.scala
import sbt._
import Keys._
import sbtassembly.Plugin._
import AssemblyKeys._
object Build extends Build {
lazy val root = project.in(file("."))
.settings(
name := "so-mockito",
compileOrder := CompileOrder.JavaThenScala,
libraryDependencies += "org.mockito" % "mockito-core" % "1.9.5"
)
.settings(buildSettings: _*)
.settings(assemblySettings: _*)
.settings(mainClass in assembly := Some("com.example.JavaMain"))
}
project/plugins.sbt
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.2")
src/main/java/com/example/Consumer.java
package com.example;
class Consumer {
interface Input {
String get();
}
private final Input input;
static Consumer create(Input input) {
return new Consumer(input);
}
private Consumer(Input input) {
this.input = input;
}
}
src/main/java/com/example/JavaMain.java
package com.example;
import static org.mockito.Mockito.*;
import static com.example.Consumer.*;
public class JavaMain {
public static void main(String[] args) {
final Input input = mock(Input.class);
System.out.println(String.format("[JavaMain] Created mock: '%s'", input));
}
}
sbt run yields the following exception:
[info] Running com.example.JavaMain
[error] (run-main-0) org.mockito.exceptions.base.MockitoException:
[error] Mockito cannot mock this class: interface com.example.Consumer$Input
[error] Mockito can only mock visible & non-final classes.
[error] If you're not sure why you're getting this error, please report to the mailing list.
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface com.example.Consumer$Input
Mockito can only mock visible & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
at com.example.JavaMain.main(JavaMain.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
Caused by: org.mockito.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:238)
at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxyClass(ClassImposterizer.java:110)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:62)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56)
at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51)
at org.mockito.Mockito.mock(Mockito.java:1243)
at org.mockito.Mockito.mock(Mockito.java:1120)
at com.example.JavaMain.main(JavaMain.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.mockito.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:385)
at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:220)
at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxyClass(ClassImposterizer.java:110)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:62)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56)
at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51)
at org.mockito.Mockito.mock(Mockito.java:1243)
at org.mockito.Mockito.mock(Mockito.java:1120)
at com.example.JavaMain.main(JavaMain.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
Caused by: java.lang.IllegalAccessError: class com.example.Consumer$Input$$EnhancerByMockitoWithCGLIB$$5997e3ec cannot access its superinterface com.example.Consumer$Input
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.mockito.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:385)
at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:220)
at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
at org.mockito.internal.creation.jmock.ClassImposterizer.createProxyClass(ClassImposterizer.java:110)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:62)
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56)
at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51)
at org.mockito.Mockito.mock(Mockito.java:1243)
at org.mockito.Mockito.mock(Mockito.java:1120)
at com.example.JavaMain.main(JavaMain.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
However, running with java or scala works as expected:
> sbt assembly && java -jar target/scala-2.10/so-mockito-assembly-0.1-SNAPSHOT.jar
[JavaMain] Created mock: 'Mock for Input, hashCode: 1317029026'
> sbt assembly && scala -cp target/scala-2.10/so-mockito-assembly-0.1-SNAPSHOT.jar 'com.example.JavaMain'
[JavaMain] Created mock: 'Mock for Input, hashCode: 1035091326'
Can anyone confirm (SBT 0.13.1)?
It works fine when the access modifier for the inner com.example.Consumer.Input interface becomes public as follows (note the public keyword for the interface):
package com.example;
class Consumer {
public interface Input {
String get();
}
private final Input input;
static Consumer create(Input input) {
return new Consumer(input);
}
private Consumer(Input input) {
this.input = input;
}
}
A sample sbt run with about before to know the versions, plugins and such.
$ sbt about run
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Loading project definition from /Users/jacek/sandbox/so/mockito/project
[info] Set current project to so-mockito (in build file:/Users/jacek/sandbox/so/mockito/)
[info] This is sbt 0.13.1
[info] The current project is {file:/Users/jacek/sandbox/so/mockito/}root 0.1-SNAPSHOT
[info] The current project is built against Scala 2.10.3
[info] Available Plugins: com.typesafe.sbt.SbtGit, com.typesafe.sbt.SbtProguard, growl.GrowlingTests, np.Plugin, com.timushev.sbt.updates.UpdatesPlugin, sbtassembly.Plugin
[info] sbt, sbt plugins, and build definitions are using Scala 2.10.3
[info] Running com.example.JavaMain
[JavaMain] Created mock: 'Mock for Input, hashCode: 256995217'
[success] Total time: 0 s, completed Jan 29, 2014 10:00:13 PM
BTW, in this particular build configuration using build.sbt might be a better choice as it'd become clearer.
build.sbt
import AssemblyKeys._
name := "so-mockito"
compileOrder := CompileOrder.JavaThenScala
libraryDependencies += "org.mockito" % "mockito-core" % "1.9.5"
sbtassembly.Plugin.buildSettings
sbtassembly.Plugin.assemblySettings
mainClass in assembly := Some("com.example.JavaMain")
I was beaten by a similar error when mocking flyway from scala code mock[org.flywaydb.core.Flyway] the test ran nicely through Intellij but through sbt test it raised:
java.lang.IllegalAccessError: tried to access class org.flywaydb.core.Flyway
for other googlers my solution was simply upgrading mockito core:
```
- "org.mockito" % "mockito-core" % "2.7.22",
+ "org.mockito" % "mockito-core" % "2.15.0",
```