javafx tableview not able to fetch data while initializing - mysql

I'm trying to populate tableview at the time of loading. Please forgive if there is any mistake.
public class users {
public String username;
public String FullName;
public String password;
public String phone;
public String email;
public String doj;
public String city;
public String state;
public String address;
public ObservableList <ListEmply> emplylst = FXCollections.observableArrayList();
}
public class UserDetail {
#FXML
private ObservableList <ListEmply> emplylst;
#FXML
private TableView <ListEmply> tbl_employeeview;
#FXML
private TableColumn<Object, Object> employeename;
users User = new users();
Dbconnection dbcon = new Dbconnection();
Connection con;
PreparedStatement pst;
ResultSet rs;
public void showDetails(users User){
con = dbcon.geConnection();
try{
pst = con.prepareStatement("select room_no from room");
rs = pst.executeQuery();
while (rs.next()){
User.emplylst.add(new ListEmply(
rs.getString(1)
));
}
System.out.println(rs);
rs.close();
pst.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void usrdetails(){
tbl_employeeview.setItems(emplylst);
showDetails(User);
employeename.setCellValueFactory(new PropertyValueFactory<>("employeename"));
System.out.println(rs);
}
public void Initializable(URL url, ResourceBundle rb){
usrdetails();
}
}
ListEmply Class
public class ListEmply {
public String employeename;
public ListEmply(String employeename) {
super();
this.employeename = employeename;
}
public String getEmployeename() {
return employeename;
}
}
public void setEmployeename(String employeename) {
this.employeename = employeename;
}
}

As described in the documentation, the controller method that is called to initialize the controller is called initialize(...), not Initializable(...):
public void initialize(URL url, ResourceBundle rb){
usrdetails();
}
As noted by #fabian in the comments, since you are not implementing the (legacy) interface Initializable and not using the parameters, you can omit the parameters from the method definition:
public void initialize(){
usrdetails();
}

Related

java.lang.reflection.InvocationTargetException during creation of object

I have difficult to figure out to create an object in a class for jUnit test.
In my test I have : User user = new User(); , and I receive a
java.lang.reflect.InvocationTargetException cathed into
public abstract class ReflectiveCallable {
public Object run() throws Throwable {
try {
return runReflectiveCall();
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
This is my User class:
#Entity
public class User implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private Double internalKey = (new Random()).nextDouble();
protected User() {
super();
}
public User(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getInternalKey() {
return internalKey;
}
}
What is wrong? thanks

JavaFX tableview column switches values

it's me again. so i have this javafx tableview which i have loaded dynamically with rows and columns from my database. it works out well but there's something i realized. two particular columns in the tableview switch their values. it happened once and when i cancelled the process and ran the program again, it didn't happen, then out of the blues, it happened again. i attached an image so you'd understand better. THANKS GUYS!!
below is the code that populates the tableview with Columns and rows from the database. i don't get any error when i run this.
public void buildData () {
String str = "SELECT * FROM EMPLOYEE_TABLE";
data = FXCollections.observableArrayList();
try {
ResultSet rs = DBaseUtils.dbaseExecuteQuery(str);
for(int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
String columnName = rs.getMetaData().getColumnName(i + 1);
TableColumn<Employee, String> column = new TableColumn<>(columnName);
column.setCellValueFactory(new PropertyValueFactory<>(columnName));
column.setCellFactory(TextFieldTableCell.<Employee>forTableColumn());
column.setOnEditCommit(new EventHandler<>() {
#Override
public void handle(TableColumn.CellEditEvent<Employee, String> event) {
TableColumn<Employee, String> col = event.getTableColumn();
int row = event.getTablePosition().getRow();
ObservableValue<String> observe = col.getCellObservableValue(row);
if (observe instanceof WritableValue) {
((WritableValue<String>) observe).setValue(event.getNewValue());
}
}
});
empTable.getColumns().addAll(column);
}
while(rs.next()) {
Employee emp = new Employee();
emp.setEmployeeId(rs.getString(1));
emp.setFirstname(rs.getString(2));
emp.setLastname(rs.getString(3));
emp.setSex(rs.getString(4));
emp.setEmail(rs.getString(5));
emp.setPhoneNumber(rs.getString(6));
emp.setAddress(rs.getString(7));
emp.setHireDate(rs.getString(8));
emp.setState(rs.getString(9));
emp.setSalary(rs.getString(10));
emp.setDepartment(rs.getString(11));
emp.setSsn(rs.getString(12));
data.add(emp);
}
empTable.setItems(data);
empTable.setEditable(true);
} catch(Exception e) {
e.printStackTrace();
System.out.println("Error building data! ");
}
}
i also attached the model class, well... just in case.
notice the naming conventions for the Property methods, i had to use that because those were the exact names on my database. and since it PropertyValueFactory uses Reflection.
public class Employee {
private SimpleStringProperty employeeId;
private SimpleStringProperty firstname;
private SimpleStringProperty lastname;
private SimpleStringProperty sex;
private SimpleStringProperty email;
private SimpleStringProperty phoneNumber;
private SimpleStringProperty hireDate;
private SimpleStringProperty address;
private SimpleStringProperty state;
private StringProperty salary;
private SimpleStringProperty department;
private SimpleStringProperty ssn;
private long time;
public Employee() {
this.employeeId = new SimpleStringProperty();
this.firstname = new SimpleStringProperty();
this.lastname = new SimpleStringProperty();
this.sex = new SimpleStringProperty();
this.email = new SimpleStringProperty();
this.phoneNumber = new SimpleStringProperty();
this.hireDate = new SimpleStringProperty();
this.address = new SimpleStringProperty();
this.state = new SimpleStringProperty();
this.salary = new SimpleStringProperty();
this.department = new SimpleStringProperty();
this.ssn = new SimpleStringProperty();
}
public String getEmployeeId() {
return employeeId.get();
}
public void setEmployeeId(String id) {
this.employeeId.set(id);
}
public StringProperty EMPLOYEE_IDProperty() {
return employeeId;
}
public String getFirstName() {
return firstname.get();
}
public void setFirstname(String firstname) {
this.firstname.set(firstname);
}
public StringProperty FIRST_NAMEProperty() {
return firstname;
}
public String getLastName() { return lastname.get(); }
public void setLastname(String lastname) {
this.lastname.set(lastname);
}
public StringProperty LAST_NAMEProperty() {
return lastname;
}
public String getSex() {
return sex.get();
}
public void setSex(String sex) {
this.sex.set(sex);
}
public StringProperty SEXProperty() {
return sex;
}
public String getEmail() {
return email.get();
}
public void setEmail(String email) {
this.email.set(email);
}
public StringProperty EMAILProperty() {
return email;
}
public String getPhoneNumber() {
return phoneNumber.get();
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber.set(phoneNumber);
}
public StringProperty PHONE_NUMBERProperty() {
return phoneNumber;
}
public String getHireDate() {
return hireDate.get();
}
public void setHireDate(String date) {
this.hireDate.set(date);
}
public SimpleStringProperty HIRE_DATEProperty() {
return hireDate;
}
public String getAddress() {
return address.get();
}
public void setAddress(String address) {
this.address.set(address);
}
public StringProperty ADDRESSProperty() {
return address;
}
public String getState() {
return state.get();
}
Here's the image. notice the different values in the HIRE_DATE COLUMN AND ADDRESS COLUMN

only one Column was populated in my Tableview

i'm populating my tableview from mysql database but only the column ID is the only one that's populated.
my main:
public void populate() throws Exception{
ObservableList<userdata1> data = FXCollections.observableArrayList();
tableView();
try{
String query = "select * from members";
ps = new Connect().connectDatabase1();
rs = ps.executeQuery(query);
while(rs.next()){
data.add(new userdata1(rs.getInt(1),rs.getString(2),rs.getInt(3)));
tblView.setItems(data);
}
}catch(Exception e){
System.out.print("asdqweasd");
}
}
public void tableView()throws Exception{
tblView.getItems().clear();
tblView.getColumns().clear();
rs = ps.executeQuery("SELECT * FROM members");
ObservableList<userdata1> data = FXCollections.observableArrayList();
TableColumn column1 = new TableColumn("ID");
column1.setMinWidth(85);
column1.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("ID"));
TableColumn column2 = new TableColumn("Name");
column2.setMinWidth(565);
column2.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("comp_name"));
TableColumn column3 = new TableColumn("STATUS");
column3.setMinWidth(123);
column3.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("mem_status"));
tblView.getColumns().addAll(column1,column2,column3);
}
my userdata1:
public class userdata1 {
public SimpleIntegerProperty ID;
public SimpleStringProperty comp_name;
public SimpleIntegerProperty mem_status;
public userdata1(Integer id, String comp_name, Integer mem_status){
this.ID = new SimpleIntegerProperty(id);
this.comp_name = new SimpleStringProperty(comp_name);
this.mem_status = new SimpleIntegerProperty(mem_status);
}
public Integer getID() {
return ID.get();
}
public String getcomp_name(){
return comp_name.get();
}
public Integer getmem_status() {
return mem_status.get();
}
public void setID(Integer id) {
this.ID.set(id);
}
public void setcomp_name(String comp_name ) {
this.comp_name.set(comp_name);
}
public void setmem_status(Integer mem_status) {
this.mem_status.set(mem_status);
}
}
the data mem_status and comp_name is not populating their respective columns
As UserData1 already contains Properties, you can set the according Property to the cellValueFactory:
public class UserData1 {
private StringProperty comp_name;
//additional fields, getters and setters
public StringProperty comp_nameProperty() {
return comp_name;
}
}
setCellValueFactory(cellData -> cellData.getValue().comp_nameProperty());
If you want to stick to the PropertyValueFactory you have to access the fields according to the CamelCase convention:
column2.setCellValueFactory(new PropertyValueFactory<>("comp_name"));
public class UserData1 {
//...
public String getComp_name(){
return comp_name.get();
}
}

Glassfish 4/MySQL Connection Pooling is not working

I have tried to settup derby and mysql databases, but both times it could not find the table. I have created the table, and I connect to it from different devices on my network. I just cant connect to it using the connection pool.
I receive the following messages "java.sql.SQLSyntaxErrorException: Table/View 'USERS' does not exist" or "Table/View 'ADDRESSES' does not exist" for another example.
I can ping the database, and everything is working using the drivermanager, but it is not working using the connection pool. My pool configuration:
user:user
password:password
url:jdbc:mysql://localhost:3306/thechef
port:3306
DatabaseName:thechef
ServerName:localhost
Here is my file:
Users.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
#ManagedBean
#SessionScoped
public class Users {
private String userName;
private String firstName;
private String lastName;
private String city;
private String zipcode;
private String state;
private String country;
private String email;
#Resource (name="jdbc/thechef")
DataSource ds;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String save() throws SQLException
{
if (ds==null)
throw new SQLException ("unable to obtain datasource");
Connection connection = ds.getConnection();
if (connection==null)
throw new SQLException ("unable to obtain datasource");
try{
PreparedStatement addEntry = connection.prepareStatement("INSERT INTO USERS (USERNAME, FIRSTNAME, LASTNAME)VALUES (?,?,?)");
addEntry.setString(1, getUserName());
addEntry.setString(2, getFirstName());
addEntry.setString(3, getLastName());
addEntry.executeUpdate();
return "index";
}
finally{
connection.close();
}
}
}

JSON unmarshalling to POJO and inserting

I would like to unmarshal a json string to a pojo class.
I am reading it from an existing url:
https://builds.apache.org/job/Accumulo-1.5/api/json
I am using apache camel to unmarshal the url
#Component
public class RouteBuilder extends SpringRouteBuilder {
private Logger logger = LoggerFactory.getLogger(RouteBuilder.class);
#Override
public void configure() throws Exception {
logger.info("Configuring route");
//Properties die hij niet vindt in de klasse negeren
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
DataFormat reportFormat = new JacksonDataFormat(objectMapper, HealthReport.class);
from("timer://foo?fixedRate=true&delay=0&period=2000&repeatCount=1")
.routeId("accumoloToJsonRoute")
.setHeader(Exchange.HTTP_METHOD, constant("GET"))
.to("https://builds.apache.org:443/job/Accumulo-1.5/api/json")
.convertBodyTo(String.class)
.unmarshal(reportFormat) //instance van Build
.log(LoggingLevel.DEBUG, "be.kdg.teamf", "Project: ${body}")
.to("hibernate:be.kdg.teamf.model.HealthReport");
}
}
So far so good. I would like to only insert the 'healthReport' node using hibernate annotations.
#XmlRootElement(name = "healthReport")
#JsonRootName(value = "healthReport")
#Entity(name = "healthreport")
public class HealthReport implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
#Column
#JsonProperty("description")
private String description;
#Column
#JsonProperty("iconUrl")
private String iconUrl;
#Column
#JsonProperty("score")
private int score;
public HealthReport() {
}
public HealthReport(int score, String iconUrl, String description) {
this.score = score;
this.iconUrl = iconUrl;
this.description = description;
}
public String getDescription() {
return description;
}
public String getIconUrl() {
return iconUrl;
}
public int getId() {
return Id;
}
public int getScore() {
return score;
}
public void setDescription(String description) {
this.description = description;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public void setId(int id) {
Id = id;
}
public void setScore(int score) {
this.score = score;
}
}
This is where the problem is. It does not recognize the annotations
and only null values are inserted in my database
#XmlRootElement(name = "healthReport")
#JsonRootName(value = "healthReport")
Does anybody know how to fix this?
Thanks
Fixed it using a Processor for my Route
public class HealthReportProcessor implements Processor {
#Autowired
private ConfigurationService configurationService;
#Override
public void process(Exchange exchange) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(exchange.getIn().getBody().toString());
ArrayNode report = (ArrayNode) root.get("healthReport");
int configId = configurationService.findJenkinsConfigurationByName(root.get("displayName").asText()).getId();
for (JsonNode node : report) {
JsonObject obj = new JsonObject();
obj.addProperty("description", node.get("description").asText());
obj.addProperty("iconUrl", node.get("iconUrl").asText());
obj.addProperty("score", node.get("score").asInt());
obj.addProperty("jenkinsConfig", configId);
exchange.getIn().setBody(obj.toString());
}
}
}
It is working but I think there is a better solution.
If you have a better solution please let me know ;)
Can you try this,
from("timer://foo?fixedRate=true&delay=0&period=2000&repeatCount=1")
.routeId("accumoloToJsonRoute")
.setHeader(Exchange.HTTP_METHOD,constant("GET"))
.to("https://builds.apache.org:443/job/Accumulo-1.5/apijson")
.unmarshal().json(JsonLibrary.Jackson, HealthReport.class)
And make sure the response params match the POJO fields.
Let me know if it works.