I'm creating a restaurant booking system and I have created the customer class but as part of the class you have be able to extend it so a company can add a contact.
I have a customer class, a company class and a TextCustomerDAO. inside the DAO is where i'm getting the error. When I try to say "If 'Y" then add a company contact" if no then just add customer. I can just add customer but when I try to add in the company contact i get an error
TextCustomerDAO: error just after the if statement where it says
contact = companyContact.getContact();
package projects.dao.textdao;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import projects.Customer;
import restaurant.dao.CustomerDAO;
import projects.Company;
public class TextCustomerDAO extends CustomerDAO {
static final char DELIMITER=':';
#Override
public List<Customer> loadCustomers(Path path) {
List<Customer> customers = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(path.toString()))) {
Customer c = null;
Company co = null;
int customerId;
String customerName, customerPhone, customerAddress, customerEmail, contact;
String[] temp;
String line = br.readLine();
while(line!=null){
temp=line.split(Character.toString(DELIMITER));
customerId = Integer.parseInt(temp[0]);
customerName = temp[1];
customerPhone = temp[2];
customerAddress = temp[3];
customerEmail = temp[4];
if (temp.length==6){
String companyContact = temp[5];
contact = companyContact.getContact();
co = new Company(customerId, customerName, customerPhone, customerAddress, customerEmail, contact);
customers.add(co);
}
else {
c = new Customer(customerId,customerName, customerPhone, customerAddress, customerEmail);
customers.add(c);
}
line = br.readLine();
}
br.close();
} catch (IOException ex) {
Logger.getLogger(TextCustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return customers;
}
#Override
public void storeCustomers(Path path, List<Customer> customers) {
try (PrintWriter output = new PrintWriter(path.toFile())) {
for (Customer c:customers) {
output.println(toFileString(c));
}
output.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(TextCustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String toFileString(Customer c) {
return Integer.toString(c.getCustomerId()) + DELIMITER +
c.getCustomerName() + DELIMITER +
c.getCustomerPhone() + DELIMITER +
c.getCustomerAddress() + DELIMITER +
c.getCustomerEmail() + DELIMITER;
}
public String toFileString(Company co) {
return Integer.toString(co.getCustomerId()) + DELIMITER +
co.getCustomerName() + DELIMITER +
co.getCustomerPhone() + DELIMITER +
co.getCustomerAddress() + DELIMITER +
co.getCustomerEmail() + DELIMITER +
co.getContact() + DELIMITER;
}
}
Customer Class:
public class Customer{
private int customerId;
private String customerName;
private String customerPhone;
private String customerAddress;
private String customerEmail;
private static int numberOfCustomers=0;
public Customer()
{
this.customerId = 0;
this.customerName = null;
this.customerPhone = null;
this.customerAddress = null;
this.customerEmail = null;
numberOfCustomers++;
}
public Customer(int customerId, String customerName, String customerPhone,
String customerAddress, String customerEmail)
{
this.customerId = customerId;
this.customerName = customerName;
this.customerPhone = customerPhone;
this.customerAddress = customerAddress;
this.customerEmail = customerEmail;
numberOfCustomers++;
}
public static int getNumberOfCustomers() {
return numberOfCustomers;
}
public int getCustomerId()
{
return customerId;
}
public void setCustomerId(int customerId)
{
this.customerId = customerId;
}
public String getCustomerName()
{
return customerName;
}
public void setCustomerName(String customerName)
{
this.customerName = customerName;
}
public String getCustomerPhone()
{
return customerPhone;
}
public void setCustomerPhone(String customerPhone)
{
this.customerPhone = customerPhone;
}
public String getCustomerAddress()
{
return customerAddress;
}
public void setCustomerAddress(String customerAddress)
{
this.customerAddress = customerAddress;
}
public String getCustomerEmail()
{
return customerEmail;
}
public void setCustomerEmail(String customerEmail)
{
this.customerEmail = customerEmail;
}
#Override
public String toString() {
return "customer id: " + getCustomerId() + ", " +
"customer name: " + getCustomerName() + ", " +
"customer phone: " + getCustomerPhone() + ", " +
"customer address: " + getCustomerAddress() + ", " +
"customer email: " + getCustomerEmail();
}
}
Company Class:
package projects;
public class Company extends Customer {
private String contact;
public Company() {
super();
this.contact = null;
}
public Company(int customerId, String customerName, String customerPhone, String customerAddress, String customerEmail, String contact) {
super(customerId, customerName, customerPhone, customerAddress, customerEmail);
this.contact = contact;
}
public String getContact() {
return this.contact;
}
public void setContact(String contact) {
this.contact = contact;
}
#Override
public String toString() {
return super.toString() + "Company Contact" + getContact();
}
}
Sorry if this is an obvious error but i have been trying for some time to fix the problem. If someone could assist or point me in the right direction it would be greatly appreciated.
Thanks
Related
here is what i have to do, and what I have already did
After a quick meeting with the head of the company, you got the following information:
It is required to store the whole data in one collection
Each flight has a number, a pilot and a specific date. In addition, passengers could be added or removed within a given limit for the maximum number of passengers who could be in the same flight. Furthermore, there are other attributes (add at least 3 attributes from your choice). Of course, flight number is unique within the same date.
Each pilot has a unique ID, a name and other attributes (add at least 2 attributes from your choice).
Each passenger has a unique passport number, a name and other attributes (add at least 2 attributes from your choice but one of them should be common with pilots).
Moreover, you have been informed that the following operations happen frequently:
Offering a new flight
Adding a passenger to a specified flight
Removing a passenger from a specified flight Retrieving the average number of passengers per flight of a specified date
Displaying all available flights in a format similar to the following: date1: flightNo1 flightNo2 flightNo3 … date2: flightNo1 flightNo2 flightNo3 … … where dates and flights are sorted in ascending order
Saving all the data into a text file
this is what did
I am starting the test class and when I started I for some reason couldn't get the date so I tried a shitty way and I don't think I am right
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class Testclass {
public static void main(String[] args) {
Date date1 = new Date("11/12/2020");
Flights a = new Flight(1, date1, 50, 5, "saudi air", "complimentary");
}
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Flight {
final List<Passenger> passengers = new ArrayList<>();
int number;
Pilot pilot;
Date date;
int maxPassengers;
int minPassengers;
String airline;
String food;
public Flight() {
}
public Flight(int number, Date date, int maxPassengers, int minPassengers, String airline, String food) {
this.number = number;
this.date = date;
this.maxPassengers = maxPassengers;
this.minPassengers = minPassengers;
this.airline = airline;
this.food = food;
}
public List<Passenger> getPassengers() {
return passengers;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Pilot getPilot() {
return pilot;
}
public void setPilot(Pilot pilot) {
if (!pilotExistance(pilot)) {
this.pilot = pilot;
System.out.println("Pilot has been added.");
}
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getMaxPassengers() {
return maxPassengers;
}
public void setMaxPassengers(int maxPassengers) {
this.maxPassengers = maxPassengers;
}
public int getMinPassengers() {
return minPassengers;
}
public void setMinPassengers(int minPassengers) {
this.minPassengers = minPassengers;
}
public String getAirline() {
return airline;
}
public void setAirline(String airline) {
this.airline = airline;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public boolean pilotExistance(Pilot newPilot) {
boolean pilotExist = false;
for (Flight flight : Airport.flights) {
if (flight.getPilot() != null && flight.getPilot().getId().equals(newPilot.getId())) {
pilotExist = true;
System.out.println("Pilot id: " + newPilot.getId() + " pilots in plane of flight number: " + flight.getNumber());
break;
}
}
return pilotExist;
}
public boolean passengerExistance(Passenger newPassenger) {
boolean passengerExist = false;
for (Flight flight : Airport.flights) {
final List<Passenger> passengers = flight.getPassengers();
for (Passenger passenger : passengers) {
if (passenger.passportNumber.equals(newPassenger.passportNumber)) {
passengerExist = true;
System.out.println("Passenger with passport number: " + newPassenger.getPassportNumber() + " are on the flight with the flgit number: " + flight.getNumber());
break;
}
}
if (passengerExist) {
break;
}
}
return passengerExist;
}
public void addPassenger(Passenger passenger) {
if (passengers.size() < maxPassengers) {
if (!passengerExistance(passenger)) {
passengers.add(passenger);
System.out.println(" Included.");
}
} else {
System.out.println("The Max number of passengers has already been reached.");
}
}
public void removePassenger(Passenger passenger) {
if (passengers.size() > minPassengers) {
if (passengerExistance(passenger)) {
passengers.remove(passenger);
System.out.println("Passnger has been taken out of flight.");
} else {
System.out.println("Passnger with passport number: " + passenger.getPassportNumber() + " doesn't exist.");
}
} else {
System.out.println("The lowest amount of passengers have been reached.");
}
}
public void passengersInformation() {
if (passengers.isEmpty()) {
System.out.println("There are no passengers.");
} else {
for (Passenger passenger : passengers) {
System.out.println(passenger.toString());
}
}
}
#Override
public String toString() {
return "Number: " + number + ", Pilot: " + pilot != null ? pilot.toString() : "No pilot yet" + ", Date: " + date + ", airline: " + airline + ", food: " + food + ", Number of passengers: " + passengers.size();
}
}
public class Passenger {
String passportNumber;
String name;
String bloodtype;
String agecatagory;
public Passenger() {
}
public Passenger(String id, String name, String bloodtype, String agecatagory) {
this.passportNumber = id;
this.name = name;
this.bloodtype = bloodtype;
this.agecatagory = agecatagory;
}
public String getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBloodtype() {
return bloodtype;
}
public void setBloodtype(String bloodtype) {
this.bloodtype = bloodtype;
}
public String getAgecatagory() {
return agecatagory;
}
public void setAgecatagory(String agecatagory) {
this.agecatagory = agecatagory;
}
#Override
public String toString() {
return "Passport Number: " + passportNumber + ", Name: " + name + ", Bloodtype: " + bloodtype + ", Age catagory: " + agecatagory;
}
}
public class Pilot {
String id;
String name;
String experiancelevel;
String pilotcatagory;
public Pilot() {
}
public Pilot(String id, String name, String experiancelevel, String pilotcatagory) {
this.id = id;
this.name = name;
this.experiancelevel = experiancelevel;
this.pilotcatagory = pilotcatagory;
}
public String getId() {
return id;
}
//This function to get pilot id
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExperiancelevel() {
return experiancelevel;
}
public void setExperiancelevel(String experiancelevel) {
this.experiancelevel = experiancelevel;
}
public String getPilotcatagory() {
return pilotcatagory;
}
public void setPilotcatagory(String pilotcatagory) {
this.pilotcatagory = pilotcatagory;
}
#Override
public String toString() {
return "Id: " + id + ", Name: " + name + ", Experiance level: " + experiancelevel + ", Pilot catagory: " + pilotcatagory;
}
}
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class Airport {
public static final List<Flight> flights = new ArrayList<>();
public Airport() {
}
public List<Flight> getFlights() {
return flights;
}
public boolean flightExistance(Flight newFlight) {
boolean flightExist = false;
if (!flights.isEmpty()) {
for (Flight flight : flights) {
if (flight.date.equals(newFlight.date) && flight.number == newFlight.number) {
flightExist = true;
break;
}
}
}
return flightExist;
}
public void addFlight(Flight flight) {
if (!flightExistance(flight)) {
flights.add(flight);
System.out.println("Flight Included.");
} else {
System.out.println("Number of flight: " + flight.getNumber() + " already in place.");
}
}
public void averageNumberOfPassengersPerFlight(Date date) {
int passengersCount = 0;
int flightsCount = 0;
double average = 0.0;
for (Flight flight : flights) {
if (flight.getDate().equals(date)) {
flightsCount++;
passengersCount += flight.getPassengers().size();
}
}
System.out.println("Total number of passengers in the flight: " + passengersCount);
if (passengersCount > 0 && flightsCount > 0) {
average = passengersCount / flightsCount;
System.out.println("Average number of passengers per flight for the specific date(" + date + "): " + average);
} else {
System.out.println("Average number of passengers per flight for the specific date(" + date + "): " + 0.0);
}
}
public void display() {
final List<Date> dates = new ArrayList<>();
for (Flight flight : flights) {
if (!dates.contains(flight.getDate())) {
dates.add(flight.getDate());
}
}
Collections.sort(dates);
for (Date date : dates) {
System.out.print(date + ": ");
final List<Integer> numbers = new ArrayList<>();
for (Flight flight : flights) {
if (flight.getDate().equals(date)) {
numbers.add(flight.getNumber());
}
}
Collections.sort(numbers);
for (int number : numbers) {
System.out.print("flightNo." + number + " ");
}
System.out.println("---------");
}
}
public void saveInTextFile(String filePath) {
try {
final FileWriter writer = new FileWriter(filePath);
for (Flight flight : flights) {
writer.write(flight.toString());
writer.write("\n");
writer.write("---------");
}
writer.close();
System.out.println("Saved successfully");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
#Override
public String toString() {
return "Number of flights: " + flights.size();
}
}
i'm here to learn but i had a time limit so with the case of using Local time, I don't want to use code that I still don't understand yet so I just continued with what I did, it kinda sucked how I had to make a new object for each time but it's wasn't too bad and I finished the main method.
here it is(of course this isn't the last version as i added many more variables and commands but i just wanted to give you the final draft before i finished it completely.
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class MainClass {
public static void main(String[] args) {
// public Flight(int number, Date date, int maxPassengers, int minPassengers, String airline, String food) {
Date d = new Date("11/12/2020");
Pilot h = new Pilot("qw2563", "zaid", "epxerianced", "main pilot");
Pilot h1 = new Pilot("qw2563", "zaid", "epxerianced", "main pilot");
Pilot h2 = new Pilot("qw2563", "zaid", "epxerianced", "main pilot");
Flight f = new Flight(1, d, 50, 5, "saudi air", "complimentary",h);
Passenger one = new Passenger("23546785", "ahmad", "B+", "adult");
Airport hq = new Airport();
hq.addFlight(f);
f.addPassenger(one);
f.addPassenger(one);
}
}
I have implemented Debezium MySql connector with Apache Flink. I am able to receive CDC event through Kafka. Insert and update event are working fine.But as soon as delete event is received, Flink job and application stops working with Job execution failed exception error. Delete event is received in my code and sink invoke method is getting triggered and my delete query is running successfully but after completion Flink job is stopped with error message Job execution failed. Not aware if it is a bug in Flink or any configuration is not right. I have attached my Flink main configuration class and Sink class.
**//Apache Flink job configuration and implementation class**
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
try{
Properties props = new Properties();
props.put("bootstrap.servers", "172.17.0.3:9092");
props.put("zookeeper.connect", "172.17.0.2:2181");
props.put("group.id", "metric-group");
// props.put("value.serializer", AppConstant.VALUE_SERIALIZER);
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("auto.offset.reset", "latest");
DataStreamSource<String> dataStreamSource = env.addSource(new FlinkKafkaConsumer<>(
"dbserver1.inventory.customers",
new SimpleStringSchema(),
props));
DataStream<MySqlCDCResponse> testEntity = dataStreamSource
.map(string -> new Gson().fromJson(string, MySqlCDCResponse.class));
testEntity.addSink(new MySqlSink());
System.out.println("Data::");
env.execute("MySqlApp");
}
catch (Exception ex){
System.out.println("Error -> " + ex.getMessage());
}
**//MySql Sink class that I am using with Apache Flink **
package entity;
import dto.MySqlCDCResponse;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Objects;
public class MySqlSink extends RichSinkFunction<MySqlCDCResponse> {
private PreparedStatement ps;
private Connection connection;
// private static final Logger log = LoggerFactory.getLogger(MySqlSink.class);
private static String DELETE_OPERATION = "select * from customers where email=?";
#Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
connection = getConnection();
String sql = "insert into customers (first_name, last_name, email) values( ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE first_name = VALUES(first_name) , last_name = VALUES(last_name);";
if (connection != null) {
ps = this.connection.prepareStatement(sql);
}
}
#Override
public void close() throws Exception {
super.close();
if (connection != null) {
connection.close();
}
if (ps != null) {
ps.close();
}
}
#Override
public void invoke(MySqlCDCResponse value, Context context) throws Exception {
System.out.println("Thread name:: " + Thread.currentThread().getName());
System.out.println("value= " + value.getPayload().toString());
if (ps == null) {
return;
}
try {
if(Objects.nonNull(value.getPayload().getBefore()) && Objects.isNull(value.getPayload().getAfter())) {
//connection = getConnection();
System.out.println("Delete Operation " + value.getPayload().toString());
ps = this.connection.prepareStatement(DELETE_OPERATION);
ps.setString(1, value.getPayload().getBefore().getEmail());
ps.executeQuery();
}
else {
ps.setString(1, value.getPayload().getAfter().getFirst_name());
ps.setString(2, value.getPayload().getAfter().getLast_name());
ps.setString(3, value.getPayload().getAfter().getEmail());
ps.executeUpdate();
}
}
catch (Exception ex) {
System.out.println("Error:: " + ex.getMessage());
}
}
private static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8", "root", "root#123");
} catch (Exception ex) {
// log.error("-----------mysql get connection has exception , msg = {}", e.getMessage());
System.out.println("Connection failure::" + ex.getMessage());
}
return con;
}
}
public class MySqlCDCResponse {
private int id;
private String first_name;
private String last_name;
private String email;
public MySqlCDCResponse(String first_name, String last_name, String email){
this.first_name =first_name;
this.last_name =last_name;
this.email =email;
}
private PayloadBean payload;
public PayloadBean getPayload() {
return payload;
}
public void setPayload(PayloadBean payload) {
this.payload = payload;
}
public static class PayloadBean {
private BeforeBean before;
private AfterBean after;
private SourceBean source;
private String op;
private long ts_ms;
private Object transaction;
public BeforeBean getBefore() {
return before;
}
public void setBefore(BeforeBean before) {
this.before = before;
}
public AfterBean getAfter() {
return after;
}
public void setAfter(AfterBean after) {
this.after = after;
}
public SourceBean getSource() {
return source;
}
public void setSource(SourceBean source) {
this.source = source;
}
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public long getTs_ms() {
return ts_ms;
}
public void setTs_ms(long ts_ms) {
this.ts_ms = ts_ms;
}
public Object getTransaction() {
return transaction;
}
public void setTransaction(Object transaction) {
this.transaction = transaction;
}
public static class BeforeBean {
private int id;
private String first_name;
private String last_name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "BeforeBean{" +
"id=" + id +
", first_name='" + first_name + '\'' +
", last_name='" + last_name + '\'' +
", email='" + email + '\'' +
'}';
}
}
public static class AfterBean {
private int id;
private String first_name;
private String last_name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "AfterBean{" +
"id=" + id +
", first_name='" + first_name + '\'' +
", last_name='" + last_name + '\'' +
", email='" + email + '\'' +
'}';
}
}
public static class SourceBean {
private String version;
private String connector;
private String name;
private long ts_ms;
private String snapshot;
private String db;
private Object sequence;
private String table;
private int server_id;
private Object gtid;
private String file;
private int pos;
private int row;
private Object thread;
private Object query;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getConnector() {
return connector;
}
public void setConnector(String connector) {
this.connector = connector;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTs_ms() {
return ts_ms;
}
public void setTs_ms(long ts_ms) {
this.ts_ms = ts_ms;
}
public String getSnapshot() {
return snapshot;
}
public void setSnapshot(String snapshot) {
this.snapshot = snapshot;
}
public String getDb() {
return db;
}
public void setDb(String db) {
this.db = db;
}
public Object getSequence() {
return sequence;
}
public void setSequence(Object sequence) {
this.sequence = sequence;
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public int getServer_id() {
return server_id;
}
public void setServer_id(int server_id) {
this.server_id = server_id;
}
public Object getGtid() {
return gtid;
}
public void setGtid(Object gtid) {
this.gtid = gtid;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public int getPos() {
return pos;
}
public void setPos(int pos) {
this.pos = pos;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public Object getThread() {
return thread;
}
public void setThread(Object thread) {
this.thread = thread;
}
public Object getQuery() {
return query;
}
public void setQuery(Object query) {
this.query = query;
}
#Override
public String toString() {
return "SourceBean{" +
"version='" + version + '\'' +
", connector='" + connector + '\'' +
", name='" + name + '\'' +
", ts_ms=" + ts_ms +
", snapshot='" + snapshot + '\'' +
", db='" + db + '\'' +
", sequence=" + sequence +
", table='" + table + '\'' +
", server_id=" + server_id +
", gtid=" + gtid +
", file='" + file + '\'' +
", pos=" + pos +
", row=" + row +
", thread=" + thread +
", query=" + query +
'}';
}
}
#Override
public String toString() {
return "PayloadBean{" +
"before=" + before +
", after=" + after +
", source=" + source +
", op='" + op + '\'' +
", ts_ms=" + ts_ms +
", transaction=" + transaction +
'}';
}
}
#Override
public String toString() {
return "MySqlCDCResponse{" +
"payload=" + payload +
'}';
}
}
I´m using JPA 2.2(Openjpa) running on OpenLiberty and mysqlVer 15.1 Distrib 10.1.21-MariaDB.
I have an object call Account where I use the entityManager.find to retrieve a given record.
The record is indeed retrieved but only this column "status" returns null.
But when I do the manual select against the DB,the value is there.
My Entity class
Account
package br.com.rsm.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
//#XmlRootElement
#Entity
#Table(name = "tb_account")
#NamedQueries({
#NamedQuery(name="Account.findByEmail", query="SELECT a FROM Account a where a.email = :email"),
#NamedQuery(name="Account.findByCpf", query="SELECT a FROM Account a where a.cpf = :cpf"),
#NamedQuery(name="Account.findByUserId", query="SELECT a FROM Account a where a.userId = :userId")
})
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String fullname;
private String email;
private String birthdate;
private String cpf;
private String rg;
private String address;
private String addressNumber;
private String complement;
private String cep;
private String state;
private int city;
private String phone;
private String mobile;
private String carrier;
#Column(name = "status")
private String status;
private long leftSide;
private long rightSide;
private Timestamp created;
private String parentId;
private String parentSide;
private String networkSide;
private Timestamp activated;
private double points;
private String nickname;
private String nis;
private String whatsapp;
private long bank;
private String accountType;
private String branchNumber;
private String branchDigit;
private String accountNumber;
private String accountDigit;
private String accountOwner;
private String cpfAccountOwner;
private String facebookID;
private double career;
private double pb;
private int certID;
private String automaticRenovation;
private String emailPagamento;
#Transient
private Account rightSideAccount;
#Transient
private Account leftSideAccount;
#Transient
private boolean searchableBySignedInUser;
#Transient
private long totalCandidatosAgente;
#Transient
private long totalAgentes;
#Transient
private long totalAgentesBracoEsq;
#Transient
private long totalAgentesBracoDir;
#Transient
private long totalAnjos;
#Transient
private boolean cfaCompleto;
//#Transient
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "owner" )
List<Ticket> tickets = new ArrayList<Ticket>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("created DESC")
#JoinColumn(name = "accountId" )
private List<Score> scores = new ArrayList<Score>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("activated DESC")
#JoinColumn(name = "idAccount" )
private List<ProductAccount> productsAccount = new ArrayList<ProductAccount>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "origin" )
private List<Trade> trades = new ArrayList<Trade>();
/**
* Construtor
*/
public Account() {}
public List<Trade> getTrades() {
return trades;
}
public void setTrades(List<Trade> trades) {
this.trades = trades;
}
public List<ProductAccount> getProductsAccount() {
return productsAccount;
}
public void setProductsAccount(List<ProductAccount> productsAccount) {
this.productsAccount = productsAccount;
}
public List<Score> getScores() {
return scores;
}
public void setScores(List<Score> scores) {
this.scores = scores;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddressNumber() {
return addressNumber;
}
public void setAddressNumber(String addressNumber) {
this.addressNumber = addressNumber;
}
public String getComplement() {
return complement;
}
public void setComplement(String complement) {
this.complement = complement;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getLeftSide() {
return leftSide;
}
public void setLeftSide(long leftSide) {
this.leftSide = leftSide;
}
public long getRightSide() {
return rightSide;
}
public void setRightSide(long rightSide) {
this.rightSide = rightSide;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentSide() {
return parentSide;
}
public void setParentSide(String parentSide) {
this.parentSide = parentSide;
}
public String getNetworkSide() {
return networkSide;
}
public void setNetworkSide(String networkSide) {
this.networkSide = networkSide;
}
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
public Timestamp getActivated() {
return activated;
}
public void setActivated(Timestamp activated) {
this.activated = activated;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
#Transient
public String getShortName() {
if(fullname==null){
return "";
}
if (nickname == null || nickname.isEmpty() ) {
nickname = fullname;
}
if(nickname != null || !nickname.isEmpty()){
String[] arrTmp = fullname.replace("\n", " ").split(" ");
String shortName = "";
if(arrTmp.length >= 2){
shortName = arrTmp[0] + " " + arrTmp[1] ;
}else if(arrTmp.length >= 1){
shortName = arrTmp[0];
}
//Passo o limitador de tamanho para ambas situações.
if(shortName!=null){
if(shortName.length() > 20){
shortName = fullname.substring(0, 19) + "...";
}
}
return shortName;
}
return "";
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNis() {
return nis;
}
public void setNis(String nis) {
this.nis = nis;
}
public String getWhatsapp() {
return whatsapp;
}
public void setWhatsapp(String whatsapp) {
this.whatsapp = whatsapp;
}
public long getBank() {
return bank;
}
public void setBank(long bank) {
this.bank = bank;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getBranchNumber() {
return branchNumber;
}
public void setBranchNumber(String branchNumber) {
this.branchNumber = branchNumber;
}
public String getBranchDigit() {
return branchDigit;
}
public void setBranchDigit(String branchDigit) {
this.branchDigit = branchDigit;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountDigit() {
return accountDigit;
}
public void setAccountDigit(String accountDigit) {
this.accountDigit = accountDigit;
}
public String getAccountOwner() {
return accountOwner;
}
public void setAccountOwner(String accountOwner) {
this.accountOwner = accountOwner;
}
public String getCpfAccountOwner() {
return cpfAccountOwner;
}
public void setCpfAccountOwner(String cpfAccountOwner) {
this.cpfAccountOwner = cpfAccountOwner;
}
public String getFacebookID() {
return facebookID;
}
public void setFacebookID(String facebookID) {
this.facebookID = facebookID;
}
public double getCareer() {
return career;
}
public void setCareer(double career) {
this.career = career;
}
public double getPb() {
return pb;
}
public void setPb(double pb) {
this.pb = pb;
}
public int getCertID() {
return certID;
}
public void setCertID(int certID) {
this.certID = certID;
}
public String getAutomaticRenovation() {
return automaticRenovation;
}
public void setAutomaticRenovation(String automaticRenovation) {
this.automaticRenovation = automaticRenovation;
}
public String getEmailPagamento() {
return emailPagamento;
}
public void setEmailPagamento(String emailPagamento) {
this.emailPagamento = emailPagamento;
}
public Account getRightSideAccount() {
return rightSideAccount;
}
public void setRightSideAccount(Account rightSideAccount) {
this.rightSideAccount = rightSideAccount;
}
public Account getLeftSideAccount() {
return leftSideAccount;
}
public void setLeftSideAccount(Account leftSideAccount) {
this.leftSideAccount = leftSideAccount;
}
public boolean isSearchableBySignedInUser() {
return searchableBySignedInUser;
}
public void setSearchableBySignedInUser(boolean searchableBySignedInUser) {
this.searchableBySignedInUser = searchableBySignedInUser;
}
public long getTotalCandidatosAgente() {
return totalCandidatosAgente;
}
public void setTotalCandidatosAgente(long totalCandidatosAgente) {
this.totalCandidatosAgente = totalCandidatosAgente;
}
public long getTotalAgentes() {
return totalAgentes;
}
public void setTotalAgentes(long totalAgentes) {
this.totalAgentes = totalAgentes;
}
public long getTotalAgentesBracoEsq() {
return totalAgentesBracoEsq;
}
public void setTotalAgentesBracoEsq(long totalAgentesBracoEsq) {
this.totalAgentesBracoEsq = totalAgentesBracoEsq;
}
public long getTotalAgentesBracoDir() {
return totalAgentesBracoDir;
}
public void setTotalAgentesBracoDir(long totalAgentesBracoDir) {
this.totalAgentesBracoDir = totalAgentesBracoDir;
}
public long getTotalAnjos() {
return totalAnjos;
}
public void setTotalAnjos(long totalAnjos) {
this.totalAnjos = totalAnjos;
}
public boolean isCfaCompleto() {
return cfaCompleto;
}
public void setCfaCompleto(boolean cfaCompleto) {
this.cfaCompleto = cfaCompleto;
}
/**
* Adiciona uma nova classe Score
* #param score Score
*/
public void addScore(Score score) {
getScores().add(score);
}
public void addProductAccount(ProductAccount productAccount) {
getProductsAccount().add(productAccount);
}
public void addTrade(Trade trade) {
getTrades().add(trade);
}
#Override
public String toString() {
return "Account [id=" + id + ", userId=" + userId + ", fullname=" + fullname + ", email=" + email
+ ", birthdate=" + birthdate + ", cpf=" + cpf + ", rg=" + rg + ", address=" + address
+ ", addressNumber=" + addressNumber + ", complement=" + complement + ", cep=" + cep + ", state="
+ state + ", city=" + city + ", phone=" + phone + ", mobile=" + mobile + ", carrier=" + carrier
+ ", status=" + status + ", leftSide=" + leftSide + ", rightSide=" + rightSide + ", created=" + created
+ ", parentId=" + parentId + ", parentSide=" + parentSide + ", networkSide=" + networkSide
+ ", activated=" + activated + ", points=" + points + ", nickname=" + nickname + ", nis=" + nis
+ ", whatsapp=" + whatsapp + ", bank=" + bank + ", accountType=" + accountType + ", branchNumber="
+ branchNumber + ", branchDigit=" + branchDigit + ", accountNumber=" + accountNumber + ", accountDigit="
+ accountDigit + ", accountOwner=" + accountOwner + ", cpfAccountOwner=" + cpfAccountOwner
+ ", facebookID=" + facebookID + ", career=" + career + ", pb=" + pb + ", certID=" + certID
+ ", automaticRenovation=" + automaticRenovation + ", emailPagamento=" + emailPagamento
+ ", rightSideAccount=" + rightSideAccount + ", leftSideAccount=" + leftSideAccount
+ ", searchableBySignedInUser=" + searchableBySignedInUser + ", totalCandidatosAgente="
+ totalCandidatosAgente + ", totalAgentes=" + totalAgentes + ", totalAgentesBracoEsq="
+ totalAgentesBracoEsq + ", totalAgentesBracoDir=" + totalAgentesBracoDir + ", totalAnjos=" + totalAnjos
+ ", cfaCompleto=" + cfaCompleto + ", tickets=" + tickets + ", scores=" + scores + ", productsAccount="
+ productsAccount + ", trades=" + trades + "]";
}
}
And this is my select result( snapshot table is to big )
[
id=2111,
userId=99YWK,
fullname=PatrickRibeiroBraz,
email=null,
birthdate=null,
cpf=null,
rg=null,
address=null,
addressNumber=null,
complement=null,
cep=null,
state=null,
city=0,
phone=null,
mobile=null,
carrier=null,
status=null,
leftSide=0,
rightSide=0,
created=2018-06-1212: 09: 29.0,
parentId=999I2,
parentSide=null,
networkSide=null,
activated=null,
points=0.0,
nickname=null,
nis=null,
whatsapp=null,
bank=0,
accountType=null,
branchNumber=null,
branchDigit=null,
accountNumber=null,
accountDigit=null,
accountOwner=null,
cpfAccountOwner=null,
facebookID=null,
career=0.0,
pb=0.0,
certID=0,
automaticRenovation=null,
emailPagamento=null,
rightSideAccount=null,
leftSideAccount=null,
searchableBySignedInUser=false,
totalCandidatosAgente=0,
totalAgentes=0,
totalAgentesBracoEsq=0,
totalAgentesBracoDir=0,
totalAnjos=0,
cfaCompleto=false,
tickets={
IndirectList: notinstantiated
},
scores={
IndirectList: notinstantiated
},
productsAccount={
IndirectList: notinstantiated
},
trades={
IndirectList: notinstantiated
}
]
ID fullname status
2111 Patrick Ribeiro Braz C
Has anyone went through this before?
I have a method that is supposed to replenish stock parts for a manufacturer. I have tried using super.Method() but its not working. There's also a class called Part if it's needed.
Main Class
package main;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestAssembledPart {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
List<AssembledPart> aparts = new ArrayList<AssembledPart>();
aparts.add(new AssembledPart("a200", "Crank & Pedal", 10, 3.5, "Crank", "Pedal"));
System.out.println("part before stock level change - start");
System.out.println(AssembledPart.toAssembledString(aparts));
for (AssembledPart apart: aparts){
if(apart!=null){
System.out.println("Please enter replenish quantity");
aparts.replenish(sc.nextInt());
}
}
System.out.println("part before stock level change - end");
System.out.println(AssembledPart.toAssembledString(aparts));
}
}
AssembledPart Class
package main;
import java.util.*;
public class AssembledPart extends Part {
private String basica;
private String basicb;
private int assembledstocklevel;
public AssembledPart(String id, String name, int stocklevel, double unitprice,
String basica, String basicb) {
super(id, name, stocklevel, unitprice);
this.basica = basica;
this.basicb = basicb;
}
public void replenish(int qty){
super.replenish(qty);
//super.stocklevel = super.stocklevel + qty;
}
public String toAssembledString() {
return super.toString() + " | " + basica + " | " + basicb;
}
public static String toAssembledString(Collection<AssembledPart> aparts){
String s = "";
for (AssembledPart apart: aparts){
s += apart.toAssembledString() + "\n";
}
return s;
}
}
PartClass
package main;
import java.util.*;
public class Part {
private String id;
private String name;
protected int stocklevel;
private double unitprice;
private int qty = 6000;
public Part(String id, String name, int stocklevel, double unitprice){
this.id = id;
this.name = name;
this.stocklevel = stocklevel;
this.unitprice = unitprice;
}
String partsAvailable()
{
//String newLine = System.getProperty("line.separator");
return (id + "\t" + name + "\t " + stocklevel + "\t\t " + unitprice);
}
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStockLevel(){
return stocklevel - qty;
}
public void setStockLevel(int stocklevel){
this.stocklevel = stocklevel;
}
public double getUnitPrice(){
return unitprice;
}
public void setUnitPrice(double unitprice){
this.unitprice = unitprice;
}
public void replenish(int qty){
this.stocklevel = stocklevel + qty;
}
public double supply(int qty){
return unitprice * qty;
}
public String toString() {
return id + " | " + name + " | " + stocklevel + " | " + unitprice;
}
public static String toString(Collection<Part> parts){
String s = "";
for (Part part: parts){
s += part + "\n";
}
return s;
}
}
Replace this line :
aparts.replenish(sc.nextInt());
With the following
apart.replenish(sc.nextInt());
You were actually calling a method on the collection that contains your objects instead of the objects themself.
i always end up with this error "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" when im running my program. i have Member Class where i code my setter and getter. All the entities i need id there. now i have another method in "Admin Class"
public class Admin {
private ArrayList<Member> members;
private String AccessName;
private String username;
private String password;
public Admin(){
this.AccessName="Ms. April Santos";
this.username = "estella";
this.password = "teller";
this.members = new ArrayList<Member>();
}
public ArrayList<Member> getMembers() {
return members;
}
public void setMembers(ArrayList<Member> members) {
this.members = members;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAccessName() {
return AccessName;
}
public void setAccessName(String AccessName) {
this.AccessName=AccessName;;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Admin other = (Admin) obj;
if ((this.username == null) ? (other.username != null) : !this.username.equals(other.username)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + (this.username != null ? this.username.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "Admin{" + "members=" + members + ", AccessName;=" + AccessName + ", username=" + username + ", password=" + password + '}';
}
public Member searchMember(Member member){
return this.searchMember(member.getMemberId());
}
public Member searchMember(String memberId){
for(Member member : this.members){
if(member.getMemberId().equals(memberId)){
return member;
}
}
return null;
}
public Member addMember(Member member){
if (this.searchMember(member) == null){
this.members.add(member);
return member;
}
return null;
}
public Member addMember(String memberId, String firstName,String middleName, String lastName){
if (this.searchMember(memberId) == null){
Member member = new Member(memberId, firstName,middleName, lastName);
this.members.add(member);
return member;
}
return null;
}
public boolean validateLogin(String username, String password){
boolean valid = false;
valid = this.username.equals(username) && this.password.equals(password);
return valid;
}
}
now im calling public addMember(String memberId, String firstName,String middleName, String lastName) in my AddMemberView(GUI). im trying to get all the text in the textfield/combobox and set it so that it will be temporary saved and ready to be saved in database as i code my DAO. this is my AddMemberView btnSave action look:
import java.sql.SQLException;
import java.text.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import rtu.tomis.bom.Admin;
import rtu.tomis.bom.Member;
import rtu.tomis.dao.MemberDao;
public class AddMemberView extends javax.swing.JPanel {
private MainFrameView mainFrameView;
private Member member;
private Admin admin;
AddMemberView(Member memb, Admin admin){
this.member= memb;
this.admin= admin;
}
public AddMemberView() {
initComponents();
}
public AddMemberView(MainFrameView mf) {
this.mainFrameView = mf;
initComponents();
}
public AddMemberView(Member m) {
this.member = m;
initComponents();
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
String memberid = (this.txtMembersID.getText());
String fname= (this.txtFirstName.getText());
String mname=(this.txtMiddleName.getText());
String lname=(this.txtLastName.getText());
if(this.admin.addMember(memberid, fname,mname, lname) != null)//im having null here
{
try{
member = this.admin.searchMember(memberid);// and if i remove that 1st line of null. the next null pointer is here
String month = (String)cmbMonth.getSelectedItem();
Integer day = (Integer) cmbDay.getSelectedItem();
Integer year = (Integer)cmbYear.getSelectedItem();
String bday = month + " " + day + ", " + year;
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
Date dateBday = df.parse(bday);
String Block = this.txtBlkLotNo.getText();
String Street = (String)this.cmbStreet.getSelectedItem();
String Brgy=(String)this.cmbBarangay.getSelectedItem();
String City= (String)this.cmbCity.getSelectedItem();
String Address = Block + " " + "" + Street + " ," + Brgy + " ," + City;
String Full = fname + " " + mname + " " + lname;
int age= Integer.parseInt(this.txtAge.getText());
int contact = Integer.parseInt(this.txtContact.getText());
String region =(String) this.cmbRegion.getSelectedItem();
this.member.setFirstName(fname);// then if i remove the two my next null line is here and those who have this.**member**.setblabla.
this.member.setMiddleName(mname);
this.member.setLastName(lname);
this.member.setFullname(Full);
this.member.setLotNo(Block);
this.member.setBarangay(Brgy);
this.member.setCity(City);
this.member.setFulladdress(Address);
this.member.setBirthday(dateBday);
this.member.setAge(age);
this.member.setEmailAddress(this.txtEadd.getText());
this.member.setVotersId(this.txtVotersID.getText());
this.member.setContactNo(contact);
this.member.setRegion(region);
this.member.setMemberId(memberid);
if(this.rbtnFemale != null){
this.member.setGender(this.rbtnFemale.getLabel());
}
else{
this.member.setGender(this.rbtnFemale.getLabel());
}
}catch (ParseException ex) {
System.out.println("Exception: "+ ex.getMessage());
}
JOptionPane.showMessageDialog(this, "Info saved!");
JOptionPane.showMessageDialog(this,"Name" + this.member.getFirstName());
}
}
thanks for your help.
I think your "admin" variable is null. Do you call your constructor? If yes, are the parameters correct?
Just write "private Admin admin" dont make the admin variable an Admin Object. Try initialize it or call the constructor properly.