Apache Camel Multicast CBR not working with a processor after multicatsing - multicast

I am completely clueless of what I am doing wrong. Below are the 2 code snippets that works. But if I need to place the processor of snippet-2 in snippet-1 it doesn't work. How can I find out the reason?
Working snippet -1
from("file:inbox")
.multicast()
.to("seda:a")
.choice()
.when(header("foo").isEqualTo("one"))
.to("log:org.apache.camel.DeadLetterChannel?level=error")
.otherwise()
.to("file://d://log//camel//output1<file:///d://log//camel//output1>")
.to("seda:b")
.choice()
.when(header("foo").isEqualTo("one"))
.to("log:org.apache.camel.DeadLetterChannel?level=error")
.otherwise()
.to("file://d://log//camel//output2<file:///d://log//camel//output2>");
Working snippet -2
from("file:inbox")
.multicast()
.process(new MutlicastRecoveryProcessor (“output1”))
.to ("file://d://log//camel//output1<file:///d://log//camel//output1>")
. process(new MutlicastRecoveryProcessor (“output2”))
.to("file://d://log//camel//output2<file:///d://log//camel//output2>");
class MutlicastRecoveryProcessor implements Processor {
private String endpointSeqID;
public MutlicastRecoveryProcessor(String endpointSeqID) {
this.endpointSeqID = endpointSeqID;
}
#Override
public void process(Exchange exchange) throws Exception {
if (“output1”.equals(this.endpointSeqID)) {
exchange.getIn().setHeader(“foo”,”one”);
}
}
}
Non Working snippet -1
from("file:inbox")
.multicast()
.process(new MutlicastRecoveryProcessor (“output1”))
.to("seda:a")
.choice()
.when(header("foo").isEqualTo("one"))
.to("log:org.apache.camel.DeadLetterChannel?level=error")
.otherwise()
.to("file://d://log//camel//output1<file:///d://log//camel//output1>")
.process(new MutlicastRecoveryProcessor (“output2”))
.to("seda:b")
.choice()
.when(header("foo").isEqualTo("one"))
.to("log:org.apache.camel.DeadLetterChannel?level=error")
.otherwise()
.to("file://d://log//camel//output2<file:///d://log//camel//output2>");
class MutlicastRecoveryProcessor implements Processor {
private String endpointSeqID;
public MutlicastRecoveryProcessor(String endpointSeqID) {
this.endpointSeqID = endpointSeqID;
}
#Override
public void process(Exchange exchange) throws Exception {
if (“output1”.equals(this.endpointSeqID)) {
exchange.getIn().setHeader(“foo”,”one”);
}
}
}

Something like this finally worked.
class MutlicastRecoveryProcessor implements Processor {
private String endpointSeq;
public MutlicastRecoveryProcessor(String endpointSeq) {
this.endpointSeq = endpointSeq;
}
#Override
public void process(Exchange exchange) throws Exception {
if ("output1".equals(this.endpointSeq)) {
exchange.getIn().setHeader("foo", "one");
} else {
System.out.println("endpoint " + this.endpointSeq);
}
}
}
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure() {
from("file://d://log//camel").convertBodyTo(String.class)
.multicast().to("seda:a", "seda:b");
from("seda:a")
.process(new MutlicastRecoveryProcessor("output1"))
.choice()
.when(header("foo").isEqualTo("one"))
.to("log:org.apache.camel.DeadLetterChannel?level=error")
.otherwise().to("file://c://log//camel//output1");
from("seda:b")
.process(new MutlicastRecoveryProcessor("output2"))
.choice()
.when(header("foo").isEqualTo("one"))
.to("log:org.apache.camel.DeadLetterChannel?level=error")
.otherwise().to("file://d://log//camel//output2");
}
});

Related

Mocking a method inside my test class

Android Studio 2.3
I have the following method I want to test inside my model class:
public class RecipeListModelImp implements RecipeListModelContract {
private Subscription subscription;
private RecipesAPI recipesAPI;
private RecipeSchedulers recipeSchedulers;
#Inject
public RecipeListModelImp(#NonNull RecipesAPI recipesAPI, #NonNull RecipeSchedulers recipeSchedulers) {
this.recipesAPI = Preconditions.checkNotNull(recipesAPI);
this.recipeSchedulers = Preconditions.checkNotNull(recipeSchedulers);
}
#Override
public void getRecipesFromAPI(final RecipeGetAllListener recipeGetAllListener) {
subscription = recipesAPI.getAllRecipes()
.subscribeOn(recipeSchedulers.getBackgroundScheduler())
.observeOn(recipeSchedulers.getUIScheduler())
.subscribe(new Subscriber<List<Recipe>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
recipeGetAllListener.onRecipeGetAllFailure(e.getMessage());
}
#Override
public void onNext(List<Recipe> recipe) {
recipeGetAllListener.onRecipeGetAllSuccess(recipe);
}
});
}
#Override
public void shutdown() {
if(subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
}
Inside my test class I am testing like this:
public class RecipeListModelImpTest {
#Mock Subscription subscription;
#Mock RecipesAPI recipesAPI;
#Mock RecipeListModelContract.RecipeGetAllListener recipeGetAllListener;
#Mock List<Recipe> recipes;
#Inject RecipeSchedulers recipeSchedulers;
private RecipeListModelContract recipeListModel;
#Before
public void setup() {
TestBusbyComponent testBusbyComponent = DaggerTestBusbyComponent.builder()
.mockRecipeSchedulersModule(new MockRecipeSchedulersModule())
.build();
testBusbyComponent.inject(RecipeListModelImpTest.this);
MockitoAnnotations.initMocks(RecipeListModelImpTest.this);
recipeListModel = new RecipeListModelImp(recipesAPI, recipeSchedulers);
}
#Test(expected = NullPointerException.class)
public void testShouldThrowExceptionOnNullParameter() {
recipeListModel = new RecipeListModelImp(null, null);
}
#Test
public void testRecipeListModelShouldNotBeNull() {
assertNotNull(recipeListModel);
}
#Test
public void testShouldGetRecipesFromAPI() {
when(recipesAPI.getAllRecipes()).thenReturn(Observable.just(recipes));
recipeListModel.getRecipesFromAPI(recipeGetAllListener);
verify(recipesAPI, times(1)).getAllRecipes();
verify(recipeGetAllListener, times(1)).onRecipeGetAllSuccess(recipes);
verify(recipeGetAllListener, never()).onRecipeGetAllFailure(anyString());
}
#Test
public void testShouldFailToGetRecipesFromAPI() {
when(recipesAPI.getAllRecipes())
.thenReturn(Observable.<List<Recipe>>error(
new Throwable(new RuntimeException("Failed to get recipes"))));
recipeListModel.getRecipesFromAPI(recipeGetAllListener);
verify(recipesAPI, times(1)).getAllRecipes();
verify(recipeGetAllListener, times(1)).onRecipeGetAllFailure(anyString());
verify(recipeGetAllListener, never()).onRecipeGetAllSuccess(recipes);
}
#Test
public void testShouldShutdown() {
when(subscription.isUnsubscribed()).thenReturn(false);
final Field subscriptionField;
try {
subscriptionField = recipeListModel.getClass().getDeclaredField("subscription");
subscriptionField.setAccessible(true);
subscriptionField.set(recipeListModel, subscription);
} catch(NoSuchFieldException e) {
e.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
recipeListModel.shutdown();
verify(subscription, times(1)).unsubscribe();
}
}
However, the problem is the Subscription in my model class is always null so will never enter the if blook. Is there any way to test this with using Mockito or spys?
Many thanks for any suggestions,
You should for testing recipeListModel class, where you have shutdown() method , set mock into this class.
If you don't have set method for subscription in recipeListModel , or constructor param.... ),you can set mock object with reflection like :
#Test
public void testShouldShutdown() {
Subscription subscription = mock(Subscription.class);
when(subscription.isUnsubscribed()).thenReturn(false);
Field subscriptionField = recipeListModel.getClass().getDeclaredField("subscription");
subscriptionField.setAccessible(true);
subscriptionField.set(recipeListModel, subscriptionMock);
recipeListModel.shutdown();
verify(subscription, times(1)).unsubscribe();
}
after your update :
if you can't change way of creation , you should mock it like (full way of creation) , i don't know your api , so it's just idea:
Subscription subscription = mock(Subscription.class);
when(subscription.isUnsubscribed()).thenReturn(false);
// preparation mock for create Subscription
//for recipesAPI.getAllRecipes()
Object mockFor_getAllRecipes = mock(....);
when(recipesAPI.getAllRecipes()).thenReturn(mockFor_getAllRecipes );
//for subscribeOn(recipeSchedulers.getBackgroundScheduler())
Object mockFor_subscribeOn = mock();
when(mockFor_getAllRecipes.subscribeOn(any())).thenReturn(mockFor_subscribeOn);
//for .observeOn(recipeSchedulers.getUIScheduler())
Object mockFor_observeOn = mock();
when(mockFor_subscribeOn .observeOn(any())).thenReturn(observeOn);
// for .subscribe
when(observeOn.subscribe(any()).thenReturn(subscription);

How to combine Retrofit 2 with Realm and RxJava

I want to save retrofit responses to realm on the background thread then pass it to the UI Thread, but its a bit tricky since Realm is very touchy with threads. so the code would look like something like this, please submit your edits to all better solutions :)
restApi.userRealmList()
.doOnNext(userRealmModels -> {
if (userRealmModels != null){
mRealm = Realm.getInstance(mContext);
mRealm.asObservable()
.map(realm -> mRealm.copyToRealmOrUpdate(userEntity))
.subscribe(new Subscriber<Object>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
e.printStackTrace();
}
#Override
public void onNext(Object o) {
Log.d("RealmManager", "user added!");
}
});
}})
.map(userEntityDataMapper::transformAll)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<User>>() {
#Override
public void onCompleted() {
hideViewLoading();
}
#Override
public void onError(Throwable e) {
hideViewLoading();
showErrorMessage(new DefaultErrorBundle((Exception) e));
showViewRetry();
}
#Override
public void onNext(List<User> users) {
showUsersCollectionInView(users);
}
});
You code doesn't look like it can compile? E.g. what is userEntity. Also your copyToRealmOrUpdate isn't inside an transaction, so that will also crash, but it has nothing to do with threads.
If you want to save some data as a side-effect before sending it to the UI, you should be able to do the following:
restApi.userRealmList()
.doOnNext(userRealmModels -> {
if (userRealmModels != null) {
Realm realm = Realm.getInstance(mContext);
realm.beginTransaction();
realm.copyToRealmOrUpdate(userRealmModels);
realm.commitTransaction();
realm.close();
}})
.map(userEntityDataMapper::transformAll)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<User>>() {
#Override
public void onCompleted() {
hideViewLoading();
}
#Override
public void onError(Throwable e) {
hideViewLoading();
showErrorMessage(new DefaultErrorBundle((Exception) e));
showViewRetry();
}
#Override
public void onNext(List<User> users) {
showUsersCollectionInView(users);
}
});

LinkedHashMap issue... Anyone help me out

While executing this test case, following error I'm facing...
Please anyone suggests me in overcoming this issue.
AbortedJobImportTest
testAbortedJobAddedSuccessfullyToExcludedRun
Unknown entity: java.util.LinkedHashMap
org.hibernate.MappingException: Unknown entity: java.util.LinkedHashMap
at com.rsa.test.crawler.CrawlerTestBase.setUp(CrawlerTestBase.groovy:42)
at com.rsa.test.crawler.AbortedJobImportTest.setUp(AbortedJobImportTest.groovy:19)
/*
***
CrawlerTestBase
public class CrawlerTestBase extends GroovyTestCase {
static transactional = false;
def productsModel;
protected JenkinsJobCrawlerDTO jenkinsCrawlerDTO;
def jenkinsJobService;
def httpClientService;
def sessionFactory;
def productModelsService;
protected String JENKINS_URL = "http://10.101.43.253:8080/jenkins/";
protected String JENKINS_JOB_CONSTANT= "job";
protected String JUNIT_TEST_PARAMETERS = "type=junit";
protected String CUSTOM_JUNIT_SELENIUM_TEST_PARAMETERS = "type=selenium,outputfile=Custom-junit-report*";
protected String DEFAULT_PRODUCT = "AM";
public void setUp(){
deleteDataFromTables();
Date date = new Date();
productsModel = new ProductModel(product:DEFAULT_PRODUCT,jenkinsServers:"10.101.43.253",date:date);
if (productsModel.validate()) {
productsModel.save(flush:true);
log.info("Added entry for prodct model for "+DEFAULT_PRODUCT);
}
else {
productsModel.errors.allErrors.each { log.error it }
}
jenkinsCrawlerDTO = new JenkinsJobCrawlerDTO();
productModelsService.reinitialise();
sessionFactory.currentSession.save(flush:true);
sessionFactory.currentSession.clear();
}
public void tearDown(){
deleteDataFromTables();
}
protected void deleteDataFromTables(){
Set<String> tablesToDeleteData = new HashSet<String>();
tablesToDeleteData.add("ExcludedJenkinsRuns");
tablesToDeleteData.add("TestRuns");
tablesToDeleteData.add("ProductModel");
tablesToDeleteData.add("SystemEvents");
tablesToDeleteData.add("JenkinsJobsToCrawl");
tablesToDeleteData.add("TestSuitesInViewList");
tablesToDeleteData.add("JenkinsJobsToCrawl");
(ApplicationHolder.application.getArtefacts("Domain") as List).each {
if(tablesToDeleteData.contains(it.getName())){
log.info("Deleting data from ${it.getName()}");
it.newInstance().list()*.delete()
}
}
sessionFactory.currentSession.flush();
sessionFactory.currentSession.clear();
}
public void oneTimeSetUp(){
}
public void oneTimeTearDown(){
}
}
AbortedJobImportTest
public class AbortedJobImportTest extends CrawlerTestBase {
private String jobUrl = JENKINS_URL+JENKINS_JOB_CONSTANT+"/am-java-source-build/69/";
#Before
public void setUp() {
super.setUp();
jenkinsCrawlerDTO.setJobUrl(jobUrl);
}
#After
public void cleanup() {
super.tearDown();
}
#Test
public void testAbortedJobAddedSuccessfullyToExcludedRun() {
int countBeforeImport = ExcludedJenkinsRuns.count();
jenkinsJobService.handleTestResults(jobUrl,JUNIT_TEST_PARAMETERS);
int countAfterImport = ExcludedJenkinsRuns.count();
Assert.assertEquals(countBeforeImport+1, countAfterImport);
ExcludedJenkinsRuns excludedRun = ExcludedJenkinsRuns.findByJobNameLike(jenkinsCrawlerDTO.jobName);
Assert.assertNotNull(excludedRun);
Assert.assertEquals(jobUrl, excludedRun.jobUrl);
Assert.assertEquals(jenkinsCrawlerDTO.jobName, excludedRun.jobName);
Assert.assertEquals(jenkinsCrawlerDTO.jenkinsServer, excludedRun.jenkinsServer);
Assert.assertEquals(jenkinsCrawlerDTO.buildNumber.toInteger(), excludedRun.buildNumber);
Assert.assertEquals("Build Aborted", excludedRun.exclusionReason);
}
}
*/
I cant figure out the issue in this code. Can anyone help me?
While executing this test case, following error I'm facing...
Please anyone suggests me in overcoming this issue.
It means that you try to put a LinkedHashMap in constructor of Product Model but there is no constructor with LinkedHashMap parameter.
I guess the problem is your Unit Test. The Model constructor will be added by grails framework. You aren`t running grails framework in your Unit Test, because you use GroovyTestCase instead of Spock.
Lock here https://grails.github.io/grails-doc/3.0.5/guide/single.html#unitTesting

how to use xjc without using command prompt

Hi friends,
I want to generate Jaxb pojo classes using xjc by java code not by using command prompt how i will use it.
public static void main(String [] args) throws FileNotFoundException
{
try
{
JAXBContext jc = JAXBContext.newInstance(new Class[] {com.bcbsks.testjb.Report.class});
Unmarshaller um = jc.createUnmarshaller();
Report myJAXBObject = (Report)um.unmarshal(new java.io.FileInputStream("report.xsd"));
}
catch( UnmarshalException ue )
{
ue.printStackTrace();
}
catch( JAXBException je )
{
je.printStackTrace();
}
}
I know that given code is wrong but i want to use any other code for generating pojo classes.
Try:
com.sun.tools.xjc.Driver.run(String[], XJCListener)
Where the String[] are the parameters passed to the XJC command the the implementation of XJCListener looks something like the following:
public class Listener extends XJCListener {
private ConsoleErrorReporter cer = new ConsoleErrorReporter(System.err);
private String generatedPackagePath = null;
public void generatedFile(String fileName, int count, int total) {
message(fileName);
if (this.generatedPackagePath == null) {
this.generatedPackagePath = fileName.substring(0, fileName.lastIndexOf(File.separator));
}
}
public String getGeneratedPackagePath() {
return generatedPackagePath;
}
public void message(String msg) {
System.out.println(msg);
}
public void error(SAXParseException exception) {
cer.error(exception);
}
public void fatalError(SAXParseException exception) {
cer.fatalError(exception);
}
public void warning(SAXParseException exception) {
cer.warning(exception);
}
public void info(SAXParseException exception) {
cer.info(exception);
}
}

proxy pattern no suitable methods found to override? Help i'm not sure what just went wrong

This is all in the form...
namespace Proxy_Pattern
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double bankAmount = 1000.00;
private void btnCheck_Click(object sender, EventArgs e)
{
double amount;
amount = double.Parse(txtAmount.Text);
CheckProxy cp =new CheckProxy();
cp.CheckTransactionRequest(amount);
lbltotal.Text = bankAmount.ToString();
}
private void btnCreditCard_Click(object sender, EventArgs e)
{
}
}
abstract class BankSubject
{
public abstract void CreditTransactionRequest(double amount);
public abstract void CheckTransactionRequest(double amount);
}
class RealBankSubject : BankSubject
{
double bank;
public RealBankSubject(double m_bacc)
{
bank = m_bacc;
}
public override void CreditTransactionRequest(double num)
{
bank -= num;
}
public override void CheckTransactionRequest(double num)
{
bank += num;
}
}
Does not implement inherited abstract members.... but why?
class CreditCardProxy : BankSubject
{
RealBankSubject realSubject;
double amount;
public CreditCardProxy (double m_bacc)
{
amount = m_bacc ;
}
no suitable method to override?... how is this an error? I have a method right here?
public override void CreditTransactionRequest()
{
if (realSubject == null)
{
realSubject = new RealBankSubject(amount);
}
realSubject.CreditTransactionRequest(amount);
}
public override void CheckTransactionRequest()
{
}
}
class CheckProxy : BankSubject
{
RealBankSubject realSubject;
double amount;
public override void CreditTransactionRequest()
{
}
public override void CheckTransactionRequest()
{
if (realSubject == null)
{
realSubject = new RealBankSubject(amount);
}
realSubject.CheckTransactionRequest(amount);
}
}
}
In your proxy, you are not specifying the amount as a parameter to the method:
public override void CreditTransactionRequest();
So it cannot override
public abstract void CreditTransactionRequest(double amount);
as the method signature doesn't not match
CreditTransactionRequest in CreditCardProxy does not take any arguments but CreditTransactionRequest in BankSubject does. This is why you can not override the method the signatures do not match.

Resources