I want to convert csv file to xml - apache-camel

I want to convert csv file to xml and i want to send the converted xml file to a queue in activemq..Is there any sample code or any reference websites or blogs please help to find sample code for this program..

Use the Bindy and Xstream components. From http://workingwithqueues.blogspot.ch/2012/07/converting-csv-to-xml-with-camel-bindy.html (with a JMS endpoint instead of a file endpoint):
DataFormat bindy = new BindyCsvDataFormat("com.package.dto");
from("file://TEST?fileName=Employee.csv")
.unmarshal(bindy)
.marshal()
.xstream()
.to("jms:queue:FOO.BAR");
For connecting to JMS have a look at the JMS and ActiveMQ components.

package org.mycompany.conversion;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Greeting {
#XmlElementWrapper(name = "Person")
#XmlElement(name = "persons")
private List<Person> persons;
public List<Person> getPerson() {
return persons;
}
public void setPerson(List<Person> persons) {
this.persons = persons;
}
}
========================================================================================
package org.mycompany.conversion;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#CsvRecord(separator = ",")
public class Person {
#DataField(pos = 1)
#XmlElement
private int id;
#DataField(pos = 2)
#XmlElement
private String name;
#DataField(pos = 3)
#XmlElement
private int age;
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
======================================================================================
package org.mycompany.conversion;
import javax.xml.bind.JAXBContext;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.DataFormat;
public class CsvConversion {
public static void main(String[] args) throws Exception {
JaxbDataFormat xmlDataFormat = new JaxbDataFormat();
JAXBContext con = JAXBContext.newInstance(Greeting.class);
xmlDataFormat.setContext(con);
DataFormat bindy = new BindyCsvDataFormat(Person.class);
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:src/main/data/in/csv?noop=true").split().tokenize("\n").unmarshal(bindy)
// constanr(true):-aggregate all using same expression
.aggregate(constant(true), new AttachAggregation())
//mandatory after aggregate
.completionTimeout(100)//end after this gives problem
.marshal(xmlDataFormat).log("xml body is ${body}")
.to("file:src/main/data/in/xml?fileName=convertedXml.xml");// .aggregate(new
// AttachAggreagation());
}
});
context.start();
Thread.sleep(5000);
}
}
=========================================================================================
package org.mycompany.conversion;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
public class AttachAggregation implements AggregationStrategy {
List<Person> list = new ArrayList();
Greeting gre = new Greeting();
#Override
//person-address
// greeting-user
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
Person newBody1 = newExchange.getIn().getBody(Person.class);
list.add(newBody1);
return newExchange;
} else {
Person newBody2 = newExchange.getIn().getBody(Person.class);
list.add(newBody2);
gre.setPerson(list);
oldExchange.getIn().setBody(gre);
return oldExchange;
}
}
}

Related

Remove item from a RecyclerView list based on status of a checkbox

I have a list application what is uses RecyclerView.
Each line has got a button, a checkbox and 2 textview.
All object is defined the RecyclerView clas, but I would like to check the checkbox status in the Main class and evaluate the status and remove the item from the list and from the SharedPreferences where the checkbox is checked
Main class is here:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
}
#Override
public void onItemClick(View view, int position) {
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
At now the item is removed when the whole line is touched. I would like to exchange to if only the Checkbox is "true".
At now the remove method is in the public void onItemClick(View view, int position) function.
I would like to put the content of the OnItemClick method to "if" part of CheckBox status.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
holder.myTextView.setText(meta_data);
holder.subtext.setText(meta_subdata +" "+ meta_subdata2);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = holder.myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView myTextView, subtext;
public Button add;
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done = itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
if(adapter.done.isChecked())should work I think, but I got null opbject reference exception.
Maybe the problem is that the checkbox is in the RecyclerView layout and not in Main class layout, but I am not sure.
Is it possible to handle the Checkbox methods from other class, and if yes, then where should I improve the code?

Not able to read data from Firebase Database in Android Studio

I have an application that is getting price,title etc. data from website. I get data with using jsoup with html parsing. I use a different class for html parsing. I also added membership system from Firebase Authentication to my application. Each user have different product lists. Products are located with user id in database. I want app to get values from database table but it gets titles of tables. My problem is getting titles from database table.
You can see the problem at this photo.
You can see another class at this photo
How can i get values ?
package com.example.lkuygulama;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class UrunEklemeActivity extends AppCompatActivity {
FirebaseDatabase firebaseDatabase;
DatabaseReference reference;
private String userId;
private FirebaseAuth.AuthStateListener mAuthlistener;
public ArrayList<String> goster = new ArrayList<String>();
ListView view;
ArrayAdapter<String> arrayAdapter;
public Button aramam,bildirim,liste;
private FirebaseAuth mAuth;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_urun_ekleme);
Urun urun = new Urun();
bildirim=(Button) findViewById(R.id.bildirimButon);
liste = (Button) findViewById(R.id.urunListeButon);
view=(ListView)findViewById(R.id.listele);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,goster);
view.setAdapter(arrayAdapter);
mAuthlistener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = mAuth.getCurrentUser();
userId = user.getUid();
}
};
tanimla();
listele();
bildirim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gonderBildirim();
}
});
}
private void tanimla() {
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference();
}
private void listele() {
reference.child("urunler").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String valeu =dataSnapshot.getKey();
goster.add(valeu);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void gonderBildirim() {
Intent intent = new Intent(this, BildirimActivity.class);
startActivity(intent);
}
private void gonderAra() {
Intent intent = new Intent(this,AramaActivity.class);
startActivity(intent);
}
private void gonderListe() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
You should use getValue(String.class).
Like this :
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String valeu =dataSnapshot.getValue(String.class);
goster.add(valeu);
arrayAdapter.notifyDataSetChanged();
}
I recommend addListenerForSingleValueEvent instead of addChildEventListener.

TestNg+ExtentReport: Null Pointer exception while executing 2 classes through testng.xml --when I use Extent report in #BeforeSuite

ExtentReports report;
ExtentTest logger;
Code runs correct for 1 class but throws null pointer exception for 2nd class when I use Extent report
1. I initialized in #BeforeSuite
2. Then Initialized in #BeforeMethod
3. In testng.xml there are 2 classes Class1 & Class2
4. On execution of testng.xml - All #Test of class1 runs completely but Class2 throws null pointer exception error when it reads in BeforeMethod(Initialized as mentioned in step2)
Extent report has been initialized in Testbase class and created getter for it so that other class can read it
Note: When I change BeforeSuite to BeforeClass i.e initialization of is done in BeforeClass then It runs fine but it produces extent report of only class1.
Also I am using Aftermethod to Flush the report and quit driver. Any solution to get rid of this null pointer exception
Below is the complete code
1. TestBase Class
package sampletestproject;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.chrome.ChromeDriver;
import
org.openqa.selenium.firefox.FirefoxDriver;
import
org.openqa.selenium.support.PageFactory;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeSuite;
public class TestBasee {
private ExtentReports report;
public WebDriver driverObj;
public Homepagee homeObj;
#BeforeSuite (alwaysRun = true)
public void beforeTest(){
System.out.println("In #BeforeSuite");
report = new ExtentReports("G:\\ExtentReport"+fn_GetTimeStamp()+".html");
System.out.println("Out #BeforeSuite");
}
#AfterClass(alwaysRun = true)
public void tearDown(ITestContext context) throws IOException, InterruptedException{
System.out.println("#AfterClass In tear down");
ITestNGMethod[] tngMethods = context.getAllTestMethods();
int i=1;
for(ITestNGMethod tng: tngMethods){
String methodName = "Method"+i+": "+ tng.getMethodName();
i++;
System.out.println(methodName);
}
}
public static String fn_GetTimeStamp() {
DateFormat DF = DateFormat.getDateTimeInstance();
String DateVal = DF.format(new Date());
DateVal = DateVal.replaceAll("/", "_");
DateVal = DateVal.replaceAll(",", "_");
DateVal = DateVal.replaceAll(":", "_");
DateVal = DateVal.replaceAll(" ", "_");
return DateVal;
}
/******************** Open Site **************************/
public Homepagee gm_OpenApp(String BrowserName, String URL) throws Exception {
System.out.println("In gm_OpenAp Method");
System.out.println(BrowserName+" -- "+URL);
gm_LaunchBrowser(BrowserName);
Thread.sleep(2000);
gm_OpenURL(URL);
Thread.sleep(2000);
homeObj = PageFactory.initElements(driverObj, Homepagee.class);
return homeObj;
}
public void gm_OpenURL(String URL) {
driverObj.get(URL);
}
public void gm_LaunchBrowser(String browserName) throws Exception{
// Launch Chrome browser
if (browserName.equalsIgnoreCase("CH") == true) {
System.setProperty("webdriver.chrome.driver", "MasterFiles\\Drivers\\ChromeDriver\\Chromedriver_win32_v2.38\\chromedriver.exe");
driverObj = new ChromeDriver();
}
// Launch Firefox browser
else if (browserName.equalsIgnoreCase("FF") == true) {
System.setProperty("webdriver.gecko.driver", "MasterFiles\\Drivers\\GeckoDriver\\64Bit\\v20\\geckodriver.exe");
driverObj = new FirefoxDriver();
}
driverObj.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driverObj.manage().timeouts().pageLoadTimeout(250, TimeUnit.SECONDS);
driverObj.manage().window().maximize();
}
/****************TAKE SCREENSHOT*****************/
public String gm_setScreenshotPath_forExtentReporting(String elementName, String resultStatus) {
System.out.println("In gm_setScreenshotPath_forExtentReporting");
System.out.println(elementName + "--" + resultStatus);
String screenshotPath = "G:\\QA\\AutomationTools\\Selenium\\WorkspaceMars1\\1.2hp.com.automationprac\\TestReports\\ExtentReport\\Screenshots\\"+ resultStatus + "\\" + elementName + "_" + fn_GetTimeStamp() + ".png";
return screenshotPath;
}
public void gm_TakeSnapshot(String destFilePath) throws IOException, InterruptedException {
TakesScreenshot tss = (TakesScreenshot) driverObj;
File srcfileobj = tss.getScreenshotAs(OutputType.FILE);
File destFileObj = new File(destFilePath);
FileUtils.copyFile(srcfileobj, destFileObj);
}
public ExtentReports getReport() {
return report;
}
public void setReport(ExtentReports report) {
this.report = report;
}
}
2. SignIn -Page Object
package sampletestproject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class SignInPagee extends TestBasee{
#FindBy(xpath = "//div[#id = 'center_column']/h1")
public static WebElement PageHeading_SignIn_txt;
#FindBy(xpath = "//h3[contains(text(), 'Already registered?')]")
public static WebElement SectionHeading_SignIn_txt;
public SignInPagee(WebDriver driverObj){
this.driverObj = driverObj;
}
}
3. Homepage - PageObject
package sampletestproject;
import java.io.IOException;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import
org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import
org.openqa.selenium.support.PageFactory;
import
org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import
import com.google.common.base.Function;
public class Homepagee extends TestBasee {
public Homepagee(WebDriver driverObj){
this.driverObj = driverObj;
}
public SignInPagee navigateToSignInPage(){
System.out.println("In navigateToSignInPage");
driverObj.navigate().to("http://automationpractice.com/index.php?controller=authentication&back=my-account");
SignInPagee signInPageObj = PageFactory.initElements(driverObj, SignInPagee.class);
return signInPageObj;
}
}
4. HomepageTest -Testpage
package sampletestproject;
import java.lang.reflect.Method;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class HomepageeTest extends TestBasee {
//ExtentReports report;
ExtentTest logger;
String elementName;
String Comment;
String actualResult;
String expectedResult;
#BeforeMethod(alwaysRun = true)
#Parameters({ "Browser", "URL"})
public void getBrowser(Method method, String Browser, String URL) throws Exception{
logger = getReport().startTest((this.getClass().getSimpleName()+"::"+method.getName()), method.getName());
logger.assignAuthor("VK");
logger.assignCategory("HomePage - Smoketesting and TextTesting--Live");
homeObj = gm_OpenApp(Browser, URL);
}
#AfterMethod (alwaysRun = true)
public void publishReport_SIP(ITestResult result) throws Exception{
System.out.println("publishReport_SIP");
String resultStatus = null;
if(result.getStatus() == ITestResult.FAILURE){
resultStatus = "FAILED";
String screenshot_Path = gm_setScreenshotPath_forExtentReporting(elementName, resultStatus);
gm_TakeSnapshot(screenshot_Path);
String image = logger.addScreenCapture(screenshot_Path);
logger.log(LogStatus.FAIL, Comment, image);
}else{
resultStatus = "PASSED";
String screenshot_Path = gm_setScreenshotPath_forExtentReporting(elementName, resultStatus);
gm_TakeSnapshot(screenshot_Path);
System.out.println("screenshot_Path: "+screenshot_Path);
String image = logger.addScreenCapture(screenshot_Path);
logger.log(LogStatus.PASS, Comment, image);
}
getReport().endTest(logger);
getReport().flush();
System.out.println("closing now_SIP.");
driverObj.quit();
}
//"********Validation of SignIn Link********");
#Test(priority=0, groups = {"Smoke"})
public void validateHeaderSignInLink_HP() throws Exception{
System.out.println("In validateHeaderSignInLink Method_HP");
elementName = "SignInLink";
Comment = "validateHeaderSignInLink";
actualResult = "http://automationpractice.com/index.php?controller=authentication&back=my-account";
expectedResult = "http://automationpractice.com/index.php?controller=authentication&back=my-account";
Assert.assertEquals(actualResult, expectedResult);
System.out.println("Out of validateHeaderSignInLink method_HP");
}
//"********Validation of GetSavingNow Button********");
#Test (priority = 1, groups = {"Smoke"})
public void validateGetSavingNowButton_HP() throws Exception{
System.out.println("In validateGetSavingNowButton Method_HP");
elementName = "GETSAVINGSNOWButton";
Comment = "validateGetSavingNowButton";
expectedResult = "http://automationpractice.com/index.php";
actualResult = "http://automationpractice.com/index.php";
Assert.assertEquals(actualResult, expectedResult);
System.out.println("Out of validateGetSavingNowButton method_HP");
}
#Test (priority = 2, groups = {"UITest"})
//"********Validation of SearchBox********");
public void validateSearchField_HP() throws Exception{
System.out.println("In validateSearchField Method_HP");
elementName = "FadedShortSleeveTshirts_lnktxt";
Comment = "validateSearchField";
actualResult = "Faded Short Sleeve T-shirtss"; //Just to produce a failed result
expectedResult = "Faded Short Sleeve T-shirts";
Assert.assertEquals(actualResult, expectedResult);
System.out.println("Out of validateSearchField method_HP");
}
#Test (priority = 3, enabled = true, groups = {"Smoke", "UITest"})
//"********Validation of Slider1********");
public void validateHomepageSlider1_HP() throws Exception{
System.out.println("In validateHomepageSlider1 Method_HP");
elementName = "Homepage Slider1";
Comment = "validateHomepageSlider1";
actualResult = "https://www.prestashop.com/en?utm_source=v16_homeslider";
expectedResult = "https://www.prestashop.com/en?utm_source=v16_homeslider";
Assert.assertEquals(actualResult, expectedResult);
System.out.println("Out of validateHomepageSlider1 method_HP");
}
}
5. SignIntest Class- Testpage
package sampletestproject;
import java.lang.reflect.Method;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import
com.relevantcodes.extentreports.ExtentTest;
import
com.relevantcodes.extentreports.LogStatus;
public class SignInnTest extends TestBasee{
SignInPagee lognObj;
ExtentTest logger;
String elementName;
String Comment;
String expectedResult;
String actualResult;
#BeforeMethod(alwaysRun = true)
#Parameters({ "Browser", "URL"})
public void getBrowser(Method method, String Browser, String URL) throws Exception{
logger = getReport().startTest((this.getClass().getSimpleName()+"::"+method.getName()), method.getName());
logger.assignAuthor("VK");
logger.assignCategory("SignInpage - Smoketesting and TextTesting--Live");
homeObj = gm_OpenApp(Browser, URL);
lognObj = homeObj.navigateToSignInPage();
}
#AfterMethod (alwaysRun = true)
public void publishReport_SIP(ITestResult result) throws Exception{
System.out.println("publishReport_SIP");
String resultStatus = null;
if(result.getStatus() == ITestResult.FAILURE){
resultStatus = "FAILED";
String screenshot_Path = gm_setScreenshotPath_forExtentReporting(elementName, resultStatus);
gm_TakeSnapshot(screenshot_Path);
String image = logger.addScreenCapture(screenshot_Path);
logger.log(LogStatus.FAIL, Comment, image);
}else{
resultStatus = "PASSED";
String screenshot_Path = gm_setScreenshotPath_forExtentReporting(elementName, resultStatus);
gm_TakeSnapshot(screenshot_Path);
System.out.println("screenshot_Path: "+screenshot_Path);
String image = logger.addScreenCapture(screenshot_Path);
logger.log(LogStatus.PASS, Comment, image);
}
getReport().endTest(logger);
getReport().flush();
System.out.println("closing now_SIP.");
driverObj.quit();
}
#Test (priority = 0, groups = {"Smoke""})
public void validateSignInPage_PageHeading_SIP() throws Exception{
System.out.println("In validateSignInPage_PageHeading Method_SIP");
elementName = "SignIn_PageHeading_txt";
Comment = "validatePageHeading_SignInpage";
actualResult = "AUTHENTICATION";
expectedResult = "AUTHENTICATION";
Assert.assertEquals(actualResult, expectedResult); //Here test will pass
System.out.println("Out of validateSignInPageHeading method_SIP");
}
#Test (groups = {"UITest"}, dependsOnMethods = { "validateSignInPage_PageHeading_SIP" })
public void validateSignInPage_SignInSectionHeading_SIP() throws Exception{
System.out.println("In validateSignInPage_SignInSectionHeading Method_SIP");
elementName = "SignInPage_SignInSectionHeading_txt";
Comment = "validateSectionHeading_SignInpage";
actualResult = "ALREADY REGISTERED1?";
expectedResult = "ALREADY REGISTERED?";
Assert.assertEquals(actualResult, expectedResult); //Here Test will fail as actual not equal to expected
System.out.println("Out of validateSignInPage_SignInSectionHeading method_SIP");
}
}
6.testng.xml
suite name="Test" parallel = "tests" thread-count = "1">
<test name="CHTest" >
<parameter name="Browser" value="CH" ></parameter>
<parameter name="URL" value="http://automationpractice.com/index.php"></parameter>
<groups><run>
<include name="Smoke"/>
<include name="UITest"/>
</run></groups>
<classes>
<class name= "sampletestproject.SignInnTest" />
<class name= "sampletestproject.HomepageeTest"/>
</classes></test></suite>
I would say it's better to use a threadlocal here or an implementation similar to for managing tests and similar one for ExtentReports:
https://github.com/anshooarora/extentreports-java/blob/master/src/test/java/com/aventstack/extentreports/common/ExtentTestManager.java
Also, if you see the examples section of the docs, you already have a barebones ExtentTestNGReportBuilder example which you can use without creating any custom code like here.
The issue you are facing is due to pricinciples of Java and managaging instances than of ExtentReports. If you want a single report for all your classes then make sure there is always 1 instance only for the entire run. Prevent any behavior which recreates the instances which in your case happens - each class resets the report variable thus resetting the ExtentReports instance.
Moreover, I would recommend using ITestListener in such cases and an example of that is shown below so to separate reporting from your test code:
public class ExtentITestListener
implements ITestListener {
private static final ExtentReports EXTENT = Extent.getInstance();
private static ThreadLocal<ExtentTest> methodTest = new ThreadLocal<ExtentTest>();
private static ThreadLocal<ExtentTest> dataProviderTest = new ThreadLocal<>();
#Override
public synchronized void onStart(ITestContext context) { }
#Override
public synchronized void onFinish(ITestContext context) {
EXTENT.flush();
}
#Override
public synchronized void onTestStart(ITestResult result) {
String methodName = result.getMethod().getMethodName();
if (result.getParameters().length>0) {
if (methodTest.get() != null && methodTest.get().getModel().getName().equals(methodName)) { }
else {
createTest(result);
}
String paramName = Arrays.asList(result.getParameters()).toString();
ExtentTest paramTest = methodTest.get().createNode(paramName);
dataProviderTest.set(paramTest);
} else {
createTest(result);
}
}
private void createTest(ITestResult result) {
String methodName = result.getMethod().getMethodName();
ExtentTest test = EXTENT.createTest(methodName);
methodTest.set(test);
String[] groups = result.getMethod().getGroups();
if (groups.length > 0) {
Arrays.asList(groups)
.forEach(x -> methodTest.get().assignCategory(x));
}
}
#Override
public synchronized void onTestSuccess(ITestResult result) {
getTest(result).pass("Test passed");
}
private ExtentTest getTest(ITestResult result) {
ExtentTest t = result.getParameters() != null && result.getParameters().length>0
? dataProviderTest.get()
: methodTest.get();
return t;
}
#Override
public synchronized void onTestFailure(ITestResult result) {
getTest(result).fail(result.getThrowable());
}
#Override
public synchronized void onTestSkipped(ITestResult result) {
getTest(result).skip(result.getThrowable());
}
#Override
public synchronized void onTestFailedButWithinSuccessPercentage(ITestResult result) { }
}
I have also faced the same issue while executing the 2 classes from the testNG.xml file. I found that the ExtentReport variable gets null after running #AfterMethod annotation that's why it's returning null pointer exception while running test cases from another class.
The solution that worked for me is by making ExtentReport variable as Static so that it creates a single copy of extent report variable and while running multiple classes you won't get that error.
For ex: static ExtentReports reports;
Let me know if the issue still persists.

JDO + RequestFactory - entity versioning

I was trying to set-up a really trivial RequestFactory example, but I failed. I persist entities in to my datastore just find, however when trying to pull them out again, i get a
com.google.web.bindery.requestfactory.server.UnexpectedException: The persisted entity with id aglub19hcHBfaWRyCgsSBFVzZXIYBAw has a null version
So first of all this is my JPO annotated entity class. At the end you find to static function for RequestFactory to call, and a non-static member function which will become an InstanceRequest.
package com.test.server;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Version;
import javax.jdo.annotations.VersionStrategy;
#PersistenceCapable(identityType = IdentityType.APPLICATION)
#Version(strategy = VersionStrategy.VERSION_NUMBER, column = "VERSION", extensions = { #Extension(vendorName = "datanucleus", key = "field-name", value = "version") })
public class User {
public User() {
}
public User(String name) {
this.name = name;
}
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
#Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
private String id;
#Persistent
#Column(name = "version")
private Integer version;
#Persistent
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static final PersistenceManager persistenceManager() {
return PMF.get().getPersistenceManager();
}
#SuppressWarnings("unchecked")
public static List<User> findAllUsers() {
PersistenceManager pm = persistenceManager();
try {
String query = "SELECT FROM " + User.class.getName();
List<User> objects = (List<User>) pm.newQuery(query).execute();
objects.size(); // This is the workaround to retrieve all objects
return objects;
} finally {
pm.close();
}
}
public static User findUser(String id) {
PersistenceManager pm = persistenceManager();
try {
User u = pm.getObjectById(User.class, id);
return u;
} finally {
pm.close();
}
}
public void persist() {
PersistenceManager pm = persistenceManager();
try {
pm.makePersistent(this);
} finally {
pm.close();
}
}
}
The RequestFactory interface itself is really simple
package com.test.shared;
import com.google.web.bindery.requestfactory.shared.RequestFactory;
public interface UserOrderRequestFactory extends RequestFactory {
UserRequest userRequest();
}
so is the corresponding RequestContext
package com.test.shared;
import java.util.List;
import com.google.web.bindery.requestfactory.shared.InstanceRequest;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.Service;
import com.google.web.bindery.requestfactory.shared.Request;
import com.test.server.User;
#Service(User.class)
public interface UserRequest extends RequestContext {
Request<List<UserProxy>> findAllUsers();
InstanceRequest<UserProxy, Void> persist();
}
Here is the proxy of user for the client side
package com.test.shared;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.EntityProxyId;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
#ProxyFor(com.test.server.User.class)
public interface UserProxy extends EntityProxy {
EntityProxyId<UserProxy> stableId();
String getName();
void setName(String name);
}
and finally my onModuleLoad() which first persists a user and then gets a list of all users.
public void onModuleLoad() {
final EventBus eventBus = new SimpleEventBus();
requestFactory = GWT.create(UserOrderRequestFactory.class);
requestFactory.initialize(eventBus);
UserRequest userRequest = requestFactory.userRequest();
UserProxy user = userRequest.create(UserProxy.class);
user.setName("Luigi");
userRequest.persist().using(user).fire( new Receiver<Void>()
{
#Override
public void onSuccess(Void arg0)
{
GWT.log("User persisted.");
}
});
userRequest = requestFactory.userRequest();
Request<List<UserProxy>> findAllUsersRequest = userRequest.findAllUsers();
findAllUsersRequest.fire( new Receiver<List<UserProxy>>() {
#Override
public void onSuccess(List<UserProxy> list) {
for(UserProxy u: list) {
GWT.log(u.getName());
}
}
});
Any input is welcome. I would be happy to receive any advice on this.
Thank you in advance.
While JPA seems to do this automatically it seems to be my job to advance the version counter in JDO. I added the following code to my persist routine in User.java
// JPA #Version does this automatically, but JDO #Version is not working like that. Not sure why.
if (version == null) {
version = 0l;
}
version++;
I am not sure if it matters but the #Version column = "VERSION" does not match the #Column(name = "version").
However GAE does not really have 'columns' as such and you can just ignore them by removing the column = "" and the #Column.
See http://gae-java-persistence.blogspot.com.au/2009/10/optimistic-locking-with-version.html

Save gwt entities to google application engine datastore with jdo, using rpc

Hello iam new to GWT framework. I want to persist my domain objects/entities to google application engine datastore using rpc. A simple implementation to test if i can make multiple rpc calls ( greetServer() , saveStudent() )
Student
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.gwt.user.client.rpc.IsSerializable;
#PersistenceCapable
public class Student implements IsSerializable {
private static final long serialVersionUID = 1L;
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
#Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
private int studentId;
#Persistent private String firstName;
#Persistent private String lastName;
public Student(){}
public Student(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public int getStudentId() {
return studentId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
GreetingService (default code generated by Eclipse IDE)
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String greetServer(String name) throws IllegalArgumentException;
**String saveStudent(Student s) throws IllegalArgumentException;**
}
GreetingServiceAsync
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GreetingServiceAsync {
void greetServer(String input, AsyncCallback<String> callback)
throws IllegalArgumentException;
**void saveStudent(Student s, AsyncCallback<String> callback)
throws IllegalArgumentException;**
}
GreetingServiceImpl
import javax.jdo.PersistenceManager;
import com.d.client.GreetingService;
import com.d.client.Student;
import com.d.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
#SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
public String greetServer(String input) throws IllegalArgumentException
...
String serverInfo = getServletContext().getServerInfo();
String userAgent = getThreadLocalRequest().getHeader("User-Agent");
...
}
#Override
public String saveStudent(Student s) throws IllegalArgumentException {
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.makePersistent(s);
return "student save - ok";
}
}
PMF
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
public final class PMF {
private static final PersistenceManagerFactory pmfInstance = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
private PMF() {
}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
EntryPoint
...
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
greetingService.greetServer("greet",
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
}
public void onSuccess(String result) {
//Show success message
}
});
greetingService.saveStudent(new Student("kostas","trichas"),
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
}
public void onSuccess(String result) {
//Show success message
}
});
...
Is the above implementation correct? I deployed this sample application to gae and it did not persisted the object student (you can browse the entities at gae datastore viewer)
check it please:
http://gwtgaedatastore.appspot.com
Change your int studentID to Long id to get it working
This works with your original code (ie., Long id):
#Extension (vendorName="jpox", key="key-auto-increment" ,value="true")
Or, change id to String and your orig code works.
I could not get Long PK to work with datanucleus using gae.pk-id.

Resources