cant get BIRT to work with POJO - java

I am new to java and reporting tool BIRT, I am trying to create a simple report using Pojo in Birt but I can't get it to work I create my java classes in other project and generate a jar file after that I use it to create a data source but when I try to create a data set it doesnt work, I couldn't select classes to proceed
package com.test.pojoproject;
import java.io.Serializable;
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String address;
public Person(){
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.test.pojoproject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Main implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static List<Person> list = new ArrayList<Person>();
public static void main(String[] args) {
Main.generateData();
Main.getList();
// display created list
//list.forEach(person -> System.out.println(person.getName()));
}
public static void generateData(){
List<Person> list = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
Person person = new Person();
person.setId(i+1);
person.setName("person " + (i+1));
person.setAddress("address " + (i+1));
list.add(person);
}
Main.list = list;
}
public static List<Person> getList(){
return Main.list;
}
}

I found a solution BIRT needs to use a class withe methodes open, next and close I will post my dataset class below
package com.test.pojoproject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class PersonDataSet {
public Iterator<Person> itr;
public List<Person> getPersons() {
List<Person> persons = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
Person person = new Person();
person.setId(i+1);
person.setName("person " + (i+1));
person.setAddress("address " + (i+1));
persons.add(person);
}
return persons;
}
public void open(Object obj, Map<String,Object> map) {
}
public Object next() {
if (itr == null)
itr = getPersons().iterator();
if (itr.hasNext())
return itr.next();
return null;
}
public void close() {
}
}

Related

iterator() method automatically invoke

Im new to Collection java, and sorry if the questions are so basic.
While debugging a piece of codes in Shipment class. If return value in iterator() is null the test case is failed, but if returning values is products.iterator the test case is passed. So, I supposed that the iterator() method is automatically invoked when running the hasItem() in ShipmentTest class. But the strange is that it was invoked without calling from test file, like normal code
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
// do something....
}
and the return type of hasItem() not return values related to iterator...
Anyone has experienced this case, can help share your ideas?
Here are the codes:
ShipmentTest class
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
public class ShipmentTest {
private Shipment shipment = new Shipment();
Product door = new Product("Door", 22);
Product windows = new Product("Windows", 10);
#Test
public void shouldAddItems() throws Exception {
shipment.add(door);
shipment.add(windows);
assertThat(shipment, hasItem(door));
}
}
Shipment class
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Shipment implements Iterable<Product> {
private static final int LIGHT_VAN_MAX_WEIGHT = 20;
private List<Product> products = new ArrayList<>();
#Override
public Iterator<Product> iterator() {
return products.iterator();
}
public void add(Product p) {
products.add(p);
}
}
Product class
public class Product {
private final String name;
private final int weight;
public Product(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
#Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", weight=" + weight +
'}';
}
}
Yes, in order to test whether a collection contains an item, IsCollectionContaining.hasItem calls iterator(). That's a perfectly normal part of dealing with any Iterable. (How else could it tell whether the shipment contains a particular item?)

Replace lambda with method reference containing new keyword

List<Employee> empListObjDeepCopy = empListRef.stream().map(inv -> new Employee(inv)).collect(Collectors.toList());
How to replace this (inv -> new Employee(inv)) lambda with Method reference.
Full Code reference:
package org.learn.copy;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DeepCopy {
public static void main(String[] args){
Employee emp = new Employee();
emp.setName("Hello");
emp.setRollNumber("12345");
Employee emp1 = new Employee();
emp1.setName("Hi");
emp1.setRollNumber("123456");
List<Employee> empList = new ArrayList<>();
empList.add(emp);
empList.add(emp1);
List<Employee> empListRef = empList;
System.out.println("empList Obj: "+empList.get(0).getName());
System.out.println("empListRef Obj: "+empListRef.get(0).getName());
List<Employee> empListObjDeepCopy = empListRef.stream().map(inv -> new Employee(inv)).collect(Collectors.toList());
empListObjDeepCopy.get(0).setName("Hi");
System.out.println("empList Obj: "+empList.get(0).getName());
System.out.println("empListRef Obj: "+empListRef.get(0).getName());
System.out.println("empListObjDeepCopy Obj: "+empListObjDeepCopy.get(0).getName());
}
}
class Employee {
private String name;
private String rollNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNumber() {
return rollNumber;
}
public void setRollNumber(String rollNumber) {
this.rollNumber = rollNumber;
}
public Employee(Employee employee) {
this.name = employee.name;
this.rollNumber = employee.rollNumber;
}
public Employee() {
super();
}
}
Using .map(Employee::new) is ambiguous because you have two constructors in your Employee class. Try to leave only one.

How can I make my java code compatible with all the tables in database from which I need to extract the data and then writing it back to Excel file

There is a database (northwind) on my machine and I have to write a code in java so as to extract the data from the table (Customers) stored in the database.
If this was only specific to Customers table then I would have done it but I want to make my code generic so that I can extract data from other tables also by simply giving the name of the table in a string variable.
Please have a look to my code.
Main class
package main;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import model.TableModel;
import service.DBConnection;
import service.WriteExcel;
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
double start = System.nanoTime();
String tableName = "Customers";
Class<?> c = Class.forName(tableName);
Connection conn = new DBConnection().getConnection();
System.out.println("Connection Established");
QueryRunner run = new QueryRunner();
ResultSetHandler<List<TableModel>> resultHandler = new BeanListHandler<TableModel>(c.getClass())
List<TableModel> data = run.query(conn, "SELECT * FROM `" + tableName + "`;",
resultHandler);
WriteExcel we = new WriteExcel(tableName+"_sheet", new File(tableName+".xlsx"));
we.writeMultipleRows(data);
we.writeWorkbookToFile();
System.out.println("File Written Succesfully");
conn.close();
System.out.println("Time Taken: " + (System.nanoTime()-start)/1000000+" ms");
}
}
In the above code, at line 27, If the statement would have been as follows
ResultSetHandler<List<TableModel>> resultHandler = new BeanListHandler<TableModel>(Customers.class);
This is running perfectly, as I said I want this statement to be independent of the table name, making my code more general.
TableModel
package model;
import java.util.List;
public interface TableModel {
public List<String> getObjectAsList();
}
Customers
package model;
import java.util.ArrayList;
import java.util.List;
public class Customers implements TableModel {
private String customerId;
private String companyName;
private String contactName;
private String contactTitle;
private String address;
private String city;
private String region;
private String postalCode;
private String country;
private String phone;
private String fax;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactTitle() {
return contactTitle;
}
public void setContactTitle(String contactTitle) {
this.contactTitle = contactTitle;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public List<String> getObjectAsList(){
List<String> fields = new ArrayList<>();
fields.add(customerId);
fields.add(companyName);
fields.add(contactName);
fields.add(contactTitle);
fields.add(address);
fields.add(city);
fields.add(region);
fields.add(postalCode);
fields.add(country);
fields.add(phone);
fields.add(fax);
return fields;
}
#Override
public String toString() {
return "{ CustomerID = "+getCustomerId()+","
+ " CompanyName = "+getCompanyName()+","
+ " ContactName = "+getContactName()+","
+ " ContactTitle = "+getContactTitle()+","
+ " Address = "+getAddress()+","
+ " City = "+getCity()+","
+ " Region = "+getRegion()+","
+ " PostalCode = "+getPostalCode()+","
+ " Country = "+getCountry()+","
+ " Phone = "+getPhone()+","
+ " Fax = "+getFax()+"}";
}
}
I have used DbUtils library for extracting database.
Any further suggestion for enhancing my code is welcomed.
If I understand your question right, you could try something like below.
To query the table, you can use run.query(SQL, ResultHandler).
ResultSetHandler<List<Map<String, Object>>> resultHandler = genericResultHandler();
List<Map<String, Object>> result = null;
// Execute the SQL statement and return the results in a List of
// T objects generated by the BeanListHandler.
try
{
result = run.query(sqlQuery, resultHandler, varargs);
}
catch (SQLException e)
{
e.printStackTrace();
}
result.stream().forEach(System.out::println);
The interesting part here is the private method genericResultHandler. For demonstration purposes, I used a HashMap to store the values and the corresponding cloumn names.
private ResultSetHandler<List<Map<String, Object>>> genericResultHandler()
{
return new ResultSetHandler<List<Map<String, Object>>>()
{
#Override
public List<Map<String, Object>> handle(java.sql.ResultSet rs) throws SQLException
{
List<Map<String, Object>> result = new ArrayList<>();
// Query all rows of the table.
while (rs.next())
{
// Get metadata of the table.
java.sql.ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Map<String, Object> data = new HashMap<>();
// For each column store column name and value of the cell into the hashmap.
for (int i = 1; i < cols; i++)
{
String colName = meta.getColumnName(i);
Object value = rs.getObject(colName);
data.put(colName, value);
}
// Add the row to the result list.
result.add(data);
}
return result;
}
};
}
Afterwards some imports I have used:
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
Output would be something like this (for my test table):
{month=JANUARY, temperature=1.6, globalradiation=0.0, monthid=1}
{month=FEBRUARY, temperature=-0.9, globalradiation=0.0, monthid=2}
{month=MARCH, temperature=0.9, globalradiation=0.0, monthid=3}
{month=APRIL, temperature=7.2, globalradiation=0.0, monthid=4}
{month=MAY, temperature=14.1, globalradiation=0.0, monthid=5}

Java array list in class with tickets

I've to implement Ticket class in java.
This is my code:
public class Ticket {
private String name;
private Float defaultPrice;
private Event event;
private static ArrayList<Ticket> ticketList;
public Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public ArrayList<Ticket> getAllTickets() {
return ticketList;
}
And my main problem is that how to do that creating an instance of Ticket class, ticketList has the newly created Ticket object. Because later I've to use public getAllTickets() method to get all tickets.
Thanks in advance!
Complete example:
package stackoverflow;
import java.math.BigDecimal;
public class Ticket {
private String name;
private BigDecimal defaultPrice;
public Ticket(String name, BigDecimal defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name =
name;
}
public BigDecimal getDefaultPrice() {
return defaultPrice;
}
public void setDefaultPrice(BigDecimal defaultPrice) {
this.defaultPrice = defaultPrice;
}
}
Event class:
package stackoverflow;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Event {
private Date date;
private List<Ticket> ticketList;
public Event(Date date) {
this.date = date;
this.ticketList = new ArrayList<>();
}
public void addTicket(Ticket ticket) {
this.ticketList.add(ticket);
}
public List<Ticket> getTicketList() {
return this.ticketList;
}
}
Main class:
package stackoverflow;
import java.math.BigDecimal;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Event eventX = new Event(new Date());
eventX.addTicket(new Ticket("ticket1", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticket2", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticket3", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticketPremium", new BigDecimal(100)));
for (Ticket ticket: eventX.getTicketList()) {
System.out.println("name:" + ticket.getName() + " price: " + ticket.getDefaultPrice());
}
}
}
I can't comment so I will have to just answer.
Do you mean that you need each ticket to be stored in the list whenever one is created?
If so make the constructor private and provide a factory method.
Like so:
public class Ticket {
private String name;
private Float defaultPrice;
private Event event;
private static ArrayList<Ticket> ticketList;
static {
ticketList = new ArrayList<>();
}
private Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public static ArrayList<Ticket> getAllTickets() {
return ticketList;
}`
public static Ticket getInstance(String name, Float defaultPrice)
{
Ticket temp = new Ticket(name, defaultPrice);
ticketList.add(temp);
return temp;
}
Option 1
If you are trying to make sure every new ticket adds itself to its own list of tickets, this can easily be taken care of in the constructor:
public Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
this.ticketList = new ArrayList<Ticket>();
this.ticketList.add(this);
}
Option 2
You could also have a separate class method to add tickets to the list, and instead use that when you initialize a new ticket. For example your Ticket class would have the following:
public void addTicketToList(Ticket ticket){
this.ticketList.add(ticket);
}
Then, when you create a new ticket you can use this:
Ticket newTicket = new Ticket();
newTicket.addTicketToList(newTicket);

Order ArrayList serializable

I have two class in JAVA:
public class Persons implements Serializable{
String name;
String phone;
...
}
and:
public class Diary implements Comparable{
ArrayList<Persons> persons=new ArrayList();
...
}
I want to order my ArrayList by the name (in alphabetical), but I can't use Collections.sort() because my ArrayList is Persons class and this give me and error. I can't implements Comparable in class Persons because if i do it, i can't read later my ArrayList which is save in a Object .dat
try this
Collections.sort(persons, new Comparator<Persons>() {
#Override
public int compare(Persons o1, Persons o2) {
return o1.name.compareTo(o2.name);
}});
If you want a sorted collection of people I would do this.
class Dairy {
final SortedMap<String, Person> people = new TreeMap<String, Person>();
}
or
class Dairy {
final SortedSet<Person> people = new TreeSet<Person>(new MyNameComparator());
}
or
class Dairy {
final List<Person> people = new ArrayList<Person>();
public void sortPeople() {
Collections.sort(people, new MyNameComparartor());
}
}
Here is complete sample for your problem.. save below code in Test.java file and run it..
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Person implements Serializable{
private static final long serialVersionUID = 1L;
String name ;
String phone ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Person(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
#Override
public String toString() {
return "Person [name=" + name + ", phone=" + phone + "]";
}
}
class Diary {
ArrayList<Person> list = new ArrayList<Person>();
public ArrayList<Person> getList() {
return list;
}
public void setList(ArrayList<Person> list) {
this.list = list;
}
public Diary(ArrayList<Person> list) {
super();
this.list = list;
}
}
public class Test
{
public static void main(String[] args) {
Person p1 = new Person("John","123");
Person p2 = new Person("Aby","456");
Person p3 = new Person("Debra","789");
ArrayList<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
list.add(p3);
Diary d = new Diary(list);
Collections.sort(d.getList(), new Comparator<Person>(){
public int compare(Person item1, Person item2){
int compare = item1.getName().compareTo(item2.getName());
return compare;
}
});
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
It sorts list of person in diary using comparator without touching your person class..

Categories