How I can display data from MySQL? - mysql

I have a database "workschedule" and a table "employee". But when I try to display data from this table, I can see only the last record from the table
ObservableList<Variable> employeeObList = FXCollections.observableArrayList();
columnId.setCellValueFactory(new PropertyValueFactory<Variable, Integer>("id"));
columnName.setCellValueFactory(new PropertyValueFactory<Variable, String>("name"));
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM workchedule.employees;");
try {
while (rs.next()) {
employeeObList.add(new Variable(rs.getInt("id"), rs.getString("name")));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
finally {
rs.close();
conn.close();
}
employeeTableView.setItems(employeeObList);
#FXML private TableView<Variable> employeeTableView;
#FXML private TableColumn<Variable, Integer> columnId;
#FXML private TableColumn<Variable, String> columnName;
Variable - a class where I save variables with getters and setters
Image from MySQL
Image from a scene

So using jdbc I always do it like this:
Connector responsible for connecting to the DB:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connector {
public Connection con = null;
final String URL = "jdbc:mysql://localhost:3306/dbname";
final String USERNAME = "username";
// Not so safe but easy
final String PASSWORD = "1234";
/*
* Adds DB Connection
*/
public void add() {
try {
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException se) {
se.printStackTrace();
}
}
}
Then I use a DAO to get the data from the database:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import application.controller.Connector;
public class Dao{
Connector c = new Connector();
public ArrayList<Model> selectAllData() {
ArrayList<Model> list = new ArrayList<>();
try {
c.add();
PreparedStatementstmt = c.con.prepareStatement("SELECT id FROM db.table");
ResultSet result = stmt.executeQuery(
);
while (result.next()) {
Model model= new Model();
//here set all the attributes
model.setId(result.getInt("id"));
list.add(model);
}
} catch (SQLException se) {
se.printStackTrace();
} finally {
if (c.con != null) {
try {
c.con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
return list;
}
Then in the JavaFX Controller I can just call the DAO function.
#FXML
public void initialize() {
initTable();
}
/*
* Sets up the table and maps the values
*/
#SuppressWarnings("unchecked")
private void initTable() {
idCol.setCellValueFactory(new PropertyValueFactory<Model, Integer>("id"));
loadTableData();
}
/*
* Loads all the data into table
*/
private void loadTableData() {
models = dao.selectAllData();
data = FXCollections.observableArrayList(models);
table.setItems(data);
}

Related

Adding new User to a table from MYSQL database using JavaFX is not working

I searched but couldn't find a solution because the examples on google search does not with my programming stil.
edit: I solved the problem in the addUser method.
The date format in MySQL is YYY-MM-DD. In my DatePicker it's DD.MM.YYY. How can get this fixed?
Do I have to change something in my database or in my java file?
package application;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
public class Main extends Application {
private BorderPane root;
private Scene scene;
private GridPane grid;
private Label lblFirstName;
private Label lblLastName;
private Label lblDOB;
private TextField txtFirstName;
private TextField txtLastName;
private DatePicker txtDOB;
private Button btnAdd;
private Button btnCancel;
private Button btnUpdate;
private HBox hbox;
private ButtonBar buttonBar;
private TableView<User> table;
final ObservableList<User> data = FXCollections.observableArrayList();
Connection conn;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/...";
String user = "root";
String password = "...";
#Override
public void start(Stage primaryStage) {
try {
CheckConnection();
root = new BorderPane();
grid = new GridPane();
// Create labels and textfields
lblFirstName = new Label("First Name");
lblFirstName.setFont(new Font("Times New Roman", 18));
lblFirstName.setPrefSize(100, 50);
lblLastName = new Label("Last Name");
lblLastName.setFont(new Font("Times New Roman", 18));
lblLastName.setPrefSize(100, 50);
lblDOB = new Label("DOB");
lblDOB.setFont(new Font("Times New Roman", 18));
lblDOB.setPrefSize(150, 50);
txtFirstName = new TextField();
txtLastName = new TextField();
txtDOB = new DatePicker();
// add to grid
grid.add(lblFirstName, 0, 0, 1, 1);
grid.add(txtFirstName, 1, 0, 1, 1);
grid.add(lblLastName, 0, 1, 1, 1);
grid.add(txtLastName, 1, 1, 1, 1);
grid.add(lblDOB, 0, 2, 1, 1);
grid.add(txtDOB, 1, 2, 1, 1);
grid.setHgap(10);
grid.setVgap(5);
grid.setPadding(new Insets(50, 10, 10, 30));
// Column constraints
ColumnConstraints column1 = new ColumnConstraints();
ColumnConstraints column2 = new ColumnConstraints();
grid.getColumnConstraints().add(column1);
grid.getColumnConstraints().add(column2);
column1.setPrefWidth(110);
column2.setPrefWidth(200);
// Buttons, Button Actions, ButtonBar
btnAdd = new Button("Add");
btnAdd.setPrefSize(40, 40);
btnAdd.setOnAction(e -> {
addUser();
});
btnCancel = new Button("Cancel");
btnCancel.setPrefSize(40, 40);
btnCancel.setOnAction(e -> {
clearFields();
});
btnUpdate = new Button("Update");
btnUpdate.setPrefSize(40, 40);
btnUpdate.setOnAction(e -> {
updateTable();
});
buttonBar = new ButtonBar();
buttonBar.getButtons().addAll(btnAdd, btnCancel, btnUpdate);
// add ButtonBar to HBox
hbox = new HBox();
hbox.getChildren().add(buttonBar);
hbox.setPadding(new Insets(10));
// create table
table = new TableView<>();
TableColumn<User, String> IDColumn = new TableColumn<User, String>("PersonID");
IDColumn.setPrefWidth(100);
IDColumn.setCellValueFactory(new PropertyValueFactory<>("personID"));
TableColumn<User, String> vornameColumn = new TableColumn<User, String>("First Name");
vornameColumn.setPrefWidth(100);
vornameColumn.setCellValueFactory(new PropertyValueFactory<>("firstName"));
TableColumn<User, String> nachnameColumn = new TableColumn<User, String>("Last Name");
nachnameColumn.setPrefWidth(100);
nachnameColumn.setCellValueFactory(new PropertyValueFactory<>("lastName"));
TableColumn<User, String> dobColumn = new TableColumn<User, String>("DOB");
dobColumn.setPrefWidth(100);
dobColumn.setCellValueFactory(new PropertyValueFactory<>("dob"));
table.getColumns().addAll(IDColumn, vornameColumn, nachnameColumn, dobColumn);
root.setCenter(table);
BorderPane.setMargin(table, new Insets(10, 10, 10, 10));
root.setLeft(grid);
root.setBottom(hbox);
scene = new Scene(root, 1000, 500);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void CheckConnection() {
conn = DBConnection.DbConnector();
if (conn == null) {
System.out.println("Connection Not Successful");
System.exit(1);
} else {
System.out.println("Connection Successful");
}
}
public void updateTable() {
data.clear();
try {
String query = "SELECT * FROM persons ";
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
while (rs.next()) {
data.add(new User(rs.getString("PersonID"), rs.getString("Firstname"), rs.getString("Lastname"),
rs.getString("DOB")
));
table.setItems(data);
}
pst.close();
rs.close();
} catch (Exception e1) {
System.err.println(e1);
}
}
public void addUser() {
try {
conn = DBConnection.DbConnector();
String query = "INSERT into persons (Firstname, Lastname, DOB) VALUES (?, ?, ?)";
pst = conn.prepareStatement(query);
pst.setString(1, txtFirstName.getText());
pst.setString(2, txtLastName.getText());
pst.setString(3, ((TextField)txtDOB.getEditor()).getText());
pst.executeUpdate();
pst.close();
} catch (Exception e2) {
System.err.println(e2);
}
}
public void clearFields() {
txtFirstName.clear();
txtLastName.clear();
txtDOB.setValue(null);
}
public static void main(String[] args) {
launch(args);
}
}
package application;
import javafx.beans.property.SimpleStringProperty;
public class User {
private SimpleStringProperty personID;
private SimpleStringProperty firstName;
private SimpleStringProperty lastName;
private SimpleStringProperty dob;
public User(String pID, String fName, String lName, String DOB) {
this.personID = new SimpleStringProperty(pID);
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.dob = new SimpleStringProperty(DOB);
}
// getter , setter
public String getPersonID() {
return personID.get();
}
public void setPersonenID(String pID) {
personID.set(pID);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lName) {
lastName.set(lName);
}
public String getDob() {
return dob.get();
}
public void setDob(String DOB) {
dob.set(DOB);
}
}
package application;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
static String url ="jdbc:mysql://localhost:3306/...";
static String user ="root";
static String password="...";
public static Connection DbConnector(){
try{
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return null;
}
}
I understand from your comment that the data type of column DOB, in database table persons is DATE. Hence the format is irrelevant because even though the documentation for DATE type includes the following:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
I think this is misleading because according to the storage requirements documentation, a DATE value is stored in three bytes. So the format is only for human-readable display.
So since the format is irrelevant, your problem is basically how to get the DatePicker value and insert it into DOB column of persons database table.
Method getValue(), in class DatePicker, returns a LocalDate.
If you are using MySQL Connector, then according to the documentation, the DATE data type maps to java class java.sql.Date.
Therefore you need to convert java.time.LocalDate to java.sql.Date. You can do this by calling static method valueOf() in class java.sql.Date. Refer to this SO question.
Here is my rewritten version of your addUser() method. It uses try-with-resources.
public void addUser() {
String query = "INSERT into persons (Firstname, Lastname, DOB) VALUES (?, ?, ?)";
try (conn = DBConnection.DbConnector();
pst = conn.prepareStatement(query)) {
pst.setString(1, txtFirstName.getText());
pst.setString(2, txtLastName.getText());
pst.setDate(3, java.sql.Date.valueOf(txtDOB.getValue()));
pst.executeUpdate();
}
catch (SQLException xSql) {
xSql.printStackTrace();
}
}
If you still also want to change the format of the date displayed by DatePicker, you can set its converter property. The below code demonstrates how to do this using an anonymous class.
DatePicker txtDOB = new DatePicker();
txtDOB.setConverter(new StringConverter<LocalDate>() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.ENGLISH);
#Override
public String toString(LocalDate object) {
if (object != null) {
return object.format(formatter);
}
return null;
}
#Override
public LocalDate fromString(String string) {
if (string != null) {
return LocalDate.parse(string, formatter);
}
return null;
}
});

MySQL javafx search like

I'm losing my mind over this. Maybe its something very simple that I miss. But I can't seem to get it work. I received help from other users and edited my code. But really can't get it to work.
This is my table in my database
+----------------+-----------------------+---------------------+
| colID | colTitle | colKeywords |
+----------------+-----------------------+---------------------+
| 1 | Jumanji | comedy adventure |
| 2 | Moana | adventure animation |
| 3 | Shawshank Redemption | drama tearjerker |
| 4 | Avengers | action |
+----------------+-----------------------+---------------------+
+-----------------------------+ +---------+
Search: | adventure and action movies | |button GO|
+-----------------------------+ +---------+
What I want to do is if I type "adventure and action movies" in the textfield, and after I hit the button go, the result in the tableview should be:
Jumanji
Moana
Avengers
My updated code:
public class UserMainPageController implements Initializable {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
#FXML
private TableView table_title;
#FXML
private TableColumn titleCol;
#FXML
private TextField txt_search;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
private void logOut(ActionEvent event) throws IOException{
Main.showUserLogin();
}
#FXML
private void goSearch(ActionEvent event) throws IOException, SQLException{
try{
conn = SqlConnection.ConnectDB();
String criteria = txt_search.getText();
if (criteria.trim().length() == 0) { return; }
String[] arryCriterion = criteria.split(" ");
List<String> results = new ArrayList<>();
for (int i = 0; i < arryCriterion.length; i++) {
List<String> text = populateField(arryCriterion[i], conn);
results.addAll(text);
}
ObservableList<String> observableList = FXCollections.observableList(results);
table_title.setItems(observableList);
}finally{
conn.close();
}
}
private List<String> populateField(String s, Connection conn) throws SQLException{
List<String> myList = new ArrayList<>();
String sql = "SELECT * FROM table_entry WHERE colTitle LIKE ? ";
pst=conn.prepareStatement(sql);
pst.setString(1, "%" + s + "%");
rs = pst.executeQuery();
while (rs.next()) {
myList.add(rs.getString("colTitle"));
}
return myList;
}
}
If I press the search button, nothing seems to appear in the tableview
Basically, my approach is similar to what #James_D is suggesting. First get all the data from the Database. Then filter the data using Java.
In my Database, I use Unicode Character INFORMATION SEPARATOR THREE (U+001D) between each keyword. Example: comedy↔adventure. I do this so that I can get each keyword using String.split().
In the app, I use a FilteredList to filter the TableView. If a DB(Database) entry contains at least one of the keywords, That entry will be shown. !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor); handles this.
Also, I have created a Tag class. This helps me keep up with things. These Tags look terrible, but you can beautify them using ideas from here.
Code:
Main:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Application;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private final TableView<Movie> table = new TableView<>();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setWidth(450);
stage.setHeight(550);
TableColumn colID = new TableColumn("ID");
colID.setMinWidth(100);
colID.setCellValueFactory(new PropertyValueFactory<>("colID"));
TableColumn colTitle = new TableColumn("Title");
colTitle.setMinWidth(100);
colTitle.setCellValueFactory(new PropertyValueFactory<>("colTitle"));
TableColumn colKeywords = new TableColumn("Keywords");
colKeywords.setMinWidth(200);
colKeywords.setCellValueFactory(new PropertyValueFactory<>("colKeywords"));
DBHandler dbhandler = new DBHandler();
FilteredList<Movie> filteredList = new FilteredList(dbhandler.getDBMovies());
table.setItems(filteredList);
table.getColumns().addAll(colID, colTitle, colKeywords);
FlowPane flowPane = new FlowPane();
TextField searchField = new TextField();
searchField.setOnAction(event -> {
List<String> searchingFor = new ArrayList();
Tag tempTag = new Tag(searchField.getText());
tempTag.getCloseButton().setOnAction((actionEvent) -> {
flowPane.getChildren().remove(tempTag);
if(flowPane.getChildren().isEmpty())
{
filteredList.setPredicate(null);
}
else{
filteredList.setPredicate((t) -> {
return !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor);
});
}
});
flowPane.getChildren().add(tempTag);
for(Node node : flowPane.getChildren())
{
searchingFor.add(((Tag)node).getText());
}
filteredList.setPredicate((t) -> {
return !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor);
});
searchField.clear();
});
HBox hbox = new HBox(searchField, flowPane);
final VBox vbox = new VBox(table, hbox);
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
}
Movie Class:
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* #author Sedrick
*/
public class Movie {
private static final String INFORMATION_SEPARATOR_THREE = "\u001D";
private final IntegerProperty colID = new SimpleIntegerProperty();
private final StringProperty colTitle = new SimpleStringProperty();
private final StringProperty colKeywords = new SimpleStringProperty();
public Movie(int colID, String colTitle, String colKeywords)
{
this.colID.set(colID);
this.colTitle.set(colTitle);
this.colKeywords.set(colKeywords);
}
public void setColID(int colID)
{
this.colID.set(colID);
}
public int getColID()
{
return this.colID.get();
}
public void setColTitle(String colTitle)
{
this.colTitle.set(colTitle);
}
public String getColTitle()
{
return this.colTitle.get();
}
public void setColID(String colKeywords)
{
this.colKeywords.set(colKeywords);
}
public String getColKeywords()
{
return this.colKeywords.get();
}
//Utility Methods
//Converts a String of keywords to a list<String> of keywords
public static List<String> KeywordsStringToList(String keywords)
{
String[] keywordsArray = keywords.split(INFORMATION_SEPARATOR_THREE);
List<String> keywordsList = new ArrayList();
for(String entry : keywordsArray)
{
keywordsList.add(entry);
}
return keywordsList;
}
//Convert a List<String> of keywords to a String of keywords
public static String keywordsListToString(List<String> keywords)
{
return String.join(INFORMATION_SEPARATOR_THREE, keywords);
}
}
Database Handler Class: This example uses an SQLite DB
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* #author Sedrick
*/
public class DBHandler {
Connection connection;
public DBHandler()
{
try
{
connection = DriverManager.getConnection("jdbc:sqlite:movie.db");
System.out.println("connected to db!");
} catch (SQLException ex)
{
Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ObservableList<Movie> getDBMovies()
{
String query = "SELECT * FROM MovieInfo";
ObservableList<Movie> movies = FXCollections.observableArrayList();
try(Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(query))
{
while(result.next())
{
Movie movie = new Movie(result.getInt("id"), result.getString("title"), result.getString("keywords"));
movies.add(movie);
}
}
catch (SQLException ex) {
Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return movies;
}
}
Tag Class:
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
/**
*
* #author Sedrick
*/
final public class Tag extends HBox{
final private Label keyword;
final private Button closeButton;
public Tag(String keyword) {
this.keyword = new Label(keyword);
closeButton = new Button("x");
this.getChildren().addAll(this.keyword, closeButton);
}
public String getText()
{
return keyword.getText();
}
Button getCloseButton()
{
return closeButton;
}
}
Full Code including DB on GitHub

dump csv file into db causing error connection closed

package com.test.mysql;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.test.mysql.FileReaderer;
public class automateImport {
/**
* #param args
* #throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException {
/* Class.forName("com.mysql.jdbc.Driver");
try {
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
FileReaderer fr = null;
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
System.out.println("f1"+fl.getPath());
if (fl.canRead()){
System.out.println("f2"+fl.getPath());
fr = new FileReaderer(fl);
break;
}
else{
System.out.println("Error:Directory does not exists");
}
}
}
}
package com.test.mysql;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileReaderer {
private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
private final File txtFolder;
Connection con = null;
Statement stmt = null;
public FileReaderer(File txtFolder) {
this.txtFolder = txtFolder;
readFiles();
}
public List<Person> readFiles() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final List<Person> people = new LinkedList<>();
System.out.println("txt folder"+txtFolder.getPath());
for (final File txtFile : txtFolder.listFiles()) {
if (txtFilter.accept(txtFile)) {
System.out.println("txt Files " +txtFile.getName());
people.addAll(readFile(txtFile));
}
}
System.out.println("File Final List==>"+people);
insertData(con,stmt,people);
return people;
}
private List<Person> readFile(File txtFile) {
try (final Scanner scanner = new Scanner(txtFile)) {
/* scanner.useDelimiter(lineBreakPattern);
final Person person = new Person();
while (scanner.hasNext()) {
final String line = scanner.next();
final Matcher matcher = linePattern.matcher(line);
if (matcher.matches()) {
switch (matcher.group(1).toUpperCase()) {
case "ID":
person.setId(Integer.parseInt(matcher.group(2)));
break;
case "NAME":
person.setName(matcher.group(2));
break;
default:
throw new IOException("Illegal line '" + matcher.group() + "'.");
}
}
}*/
BufferedReader br = new BufferedReader(new FileReader(txtFile));
String currentLine = br.readLine();
List<Person> processPersonList = new ArrayList<Person>();
while (currentLine != null) {
String[] tokens = currentLine.split(",");
Person finalPerson = new Person();
finalPerson.setFirstName(tokens[0]);
finalPerson.setLastName(tokens[1]);
finalPerson.setSIN(tokens[2]);
currentLine = br.readLine();
processPersonList.add(finalPerson);
}
System.out.println("final list==>"+processPersonList);
br.close();
return processPersonList;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void insertData(Connection con,Statement stmt,List<Person> pp){
System.out.print("\nInserting records into table...");
try{
for(Person pr:pp){
System.out.println("First Name " +pr.getFirstName()+" Second Name " +pr.getLastName()+"SIN Name " +pr.getSIN());
String sql = "INSERT INTO employee(first_name, last_name,sin) values (?,?,?)" ;
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString (1, pr.getFirstName());
preparedStmt.setString (2, pr.getLastName());
preparedStmt.setString (3, pr.getSIN());
preparedStmt.execute();
}
System.out.println(" SUCCESS!\n");
con.close();
} catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
package com.test.mysql;
public class Person {
private String firstName;
private String lastName;
private String SIN;
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 getSIN() {
return SIN;
}
public void setSIN(String sIN) {
SIN = sIN;
}
//
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
}
package com.test.readfile;
import java.util.Date;
public class Employee {
private long id;
private String firstName;
private String lastName;
private Double salary;
private String sin;
private Date dob;
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 Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public String getSin() {
return sin;
}
public void setSin(String sin) {
this.sin = sin;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
package com.test.readfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileReaderer {
private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
private final File txtFolder;
Connection con = null;
Statement stmt = null;
public FileReaderer(File txtFolder) {
this.txtFolder = txtFolder;
readFiles();
}
public List<Employee> readFiles() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "ptlusrapp$246");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final List<Employee> people = new LinkedList<>();
System.out.println("txt folder"+txtFolder.getPath());
for (final File txtFile : txtFolder.listFiles()) {
if (txtFilter.accept(txtFile)) {
System.out.println("txt Files " +txtFile.getName());
people.addAll(readFile(txtFile));
}
}
System.out.println("File Final List==>"+people);
insertData(con,stmt,people);
return people;
}
private List<Employee> readFile(File txtFile) {
try (final Scanner scanner = new Scanner(txtFile)) {
/* scanner.useDelimiter(lineBreakPattern);
final Employee Employee = new Employee();
while (scanner.hasNext()) {
final String line = scanner.next();
final Matcher matcher = linePattern.matcher(line);
if (matcher.matches()) {
switch (matcher.group(1).toUpperCase()) {
case "ID":
Employee.setId(Integer.parseInt(matcher.group(2)));
break;
case "NAME":
Employee.setName(matcher.group(2));
break;
default:
throw new IOException("Illegal line '" + matcher.group() + "'.");
}
}
}*/
BufferedReader br = new BufferedReader(new FileReader(txtFile));
String currentLine = br.readLine();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date convertedDate = null;
String splitterString="\\s";
List<Employee> processEmployeeList = new ArrayList<Employee>();
while (currentLine != null) {
if(currentLine.indexOf(",")>-1)
splitterString = ",";
else
splitterString = "\\|";
String[] tokens = currentLine.split(splitterString);
Employee finalEmployee = new Employee();
finalEmployee.setId(Long.parseLong(tokens[0]));
finalEmployee.setFirstName(tokens[1]);
finalEmployee.setLastName(tokens[2]);
finalEmployee.setSalary(Double.parseDouble(tokens[3]));
finalEmployee.setSin(tokens[4]);
try {
convertedDate = formatter.parse(tokens[5]);
finalEmployee.setDob(convertedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// finalEmployee.setDob(convertedDate);
currentLine = br.readLine();
processEmployeeList.add(finalEmployee);
}
System.out.println("final list==>"+processEmployeeList);
br.close();
return processEmployeeList;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void insertData(Connection con,Statement stmt,List<Employee> pp){
System.out.print("\nInserting records into table...");
try{
for(Employee pr:pp){
System.out.println("First Name " +pr.getFirstName()+" Second Name " +pr.getLastName()+"SIN Name " +pr.getSin() +"DOB: "+pr.getDob());
//String sql = "INSERT INTO employee(first_name, last_name,sin) values (?,?,?)" ;
String sql = "INSERT INTO employee(id,first_name,last_name,salary,sin,dob) values (?,?,?,?,?,?)" ;
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setLong(1,pr.getId());
preparedStmt.setString (2, pr.getFirstName());
preparedStmt.setString (3, pr.getLastName());
preparedStmt.setDouble(4, pr.getSalary());
preparedStmt.setString (5, pr.getSin());
java.sql.Date sqlDate = new java.sql.Date(pr.getDob().getTime());
preparedStmt.setDate(6, sqlDate);
preparedStmt.execute();
}
System.out.println(" SUCCESS!\n");
con.close();
} catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
package com.test.readfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AutomateImport {
/**
* #param args
* #throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException {
/* Class.forName("com.mysql.jdbc.Driver");
try {
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
FileReaderer fr = null;
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
System.out.println("f1"+fl.getPath());
if (fl.canRead()){
System.out.println("f2"+fl.getPath());
fr = new FileReaderer(fl);
break;
}
else{
System.out.println("Error:Directory does not exists");
}
}
}
}

Getting Connection Reset when lost connection with Smack API

i implement a small client which runs as bot on my Server.
I test the reconnect method and cut the internet connection.
I always get this error when i establish the connection again:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
at sun.security.ssl.InputRecord.read(InputRecord.java:480)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:884)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:102)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.read1(BufferedReader.java:205)
at java.io.BufferedReader.read(BufferedReader.java:279)
at org.xmlpull.mxp1.MXParser.fillBuf(MXParser.java:2992)
at org.xmlpull.mxp1.MXParser.more(MXParser.java:3046)
at org.xmlpull.mxp1.MXParser.nextImpl(MXParser.java:1144)
at org.xmlpull.mxp1.MXParser.next(MXParser.java:1093)
at org.jivesoftware.smack.PacketReader.parsePackets(PacketReader.java:325)
at org.jivesoftware.smack.PacketReader.access$000(PacketReader.java:43)
at org.jivesoftware.smack.PacketReader$1.run(PacketReader.java:70)
This is my Jabber-Manager Class:
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import java.io.IOException;
import java.util.Scanner;
public class JabberSmackApi extends Thread {
private static final int packetReplyTimeout = 500; // millis
private String server;
private ConnectionConfiguration config;
private XMPPConnection connection;
private ChatManager chatManager;
private MessageListener messageListener;
private String user;
public JabberSmackApi(String server) {
this.server = server;
}
public static boolean stopValue = true;
#Override
public void run() {
try {
init();
performLogin("Test#jabber.de", "password");
setStatus(true, "Hiiiii!!!!");
user = "otherUser#jabber.de";
String name = "otherUser";
createEntry(user, name);
sendMessage("Hello mate", user);
while(stopValue) {
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopMe() {
this.stopValue = false;
}
public void init() throws XMPPException {
System.out.println(String.format("Initializing connection to server %1$s", server));
SmackConfiguration.setPacketReplyTimeout(packetReplyTimeout);
config = new ConnectionConfiguration(server);
config.setReconnectionAllowed(true);
connection = new XMPPConnection(config);
connection.connect();
System.out.println("Connected: " + connection.isConnected());
chatManager = connection.getChatManager();
messageListener = new MyMessageListener();
}
public void performLogin(String username, String password) throws XMPPException {
if (connection!=null && connection.isConnected()) {
connection.login(username, password);
}
}
public void setStatus(boolean available, String status) {
Presence.Type type = available? Type.available: Type.unavailable;
Presence presence = new Presence(type);
presence.setStatus(status);
connection.sendPacket(presence);
}
public void destroy() {
if (connection!=null && connection.isConnected()) {
connection.disconnect();
}
}
public void sendMessage(String message, String buddyJID) throws XMPPException {
System.out.println(String.format("Sending mesage '%1$s' to user %2$s", message, buddyJID));
Chat chat = chatManager.createChat(buddyJID, messageListener);
chat.sendMessage(message);
}
public void createEntry(String user, String name) throws Exception {
System.out.println(String.format("Creating entry for buddy '%1$s' with name %2$s", user, name));
Roster roster = connection.getRoster();
roster.createEntry(user, name, null);
}
class MyMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message message) {
String from = message.getFrom();
String body = message.getBody();
System.out.println(String.format("Received message '%1$s' from %2$s", body, from));
}
}
}

EJB - JPA - Hibernate - JBoss 6-MySql

I am deleveloping web project EJB,JPA - Hibernate as provider, JBoss 6,MySql.
I new in EJB, JPA.I have problems with load ejb bean in servlet.
persistence.xml
<persistence-unit name="LibraryPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/MySqlDS</jta-data-source>
<class>library.entity.User</class>
<class>library.entity.Book</class>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
UserFacade.java
#Local
public interface UserFacade {
User findUserByLoginAndPassword(String login, String password);
/* List<User> getClients();
void returnBooks(long userId, long[] ids);
void takeBooks(long userId, long[] ids);*/
}
UserFacadeImpl.java
package library.facades.impl;
import library.dao.impl.UserDAO;
import library.entity.User;
import library.facades.interfaces.UserFacade;
import javax.ejb.EJB;
import javax.ejb.Stateless;
#Stateless
public class UserFacadeImpl implements UserFacade {
#EJB
private UserDAO userDAO;
public UserFacadeImpl() {
}
public User findUserByLoginAndPassword(String login, String password) {
User user = userDAO.selectUserByLoginAndPassword(login, password);
return user;
}
/* public List<User> getListClients() {
List<User> userList = userDAO.getClients();
return userList;
}
public void returnBooks(long userId, long[] ids) {
userDAO.returnBooks(userId, ids);
}
public void takeBooks(long userId, long[] ids) {
userDAO.takeBooks(userId, ids);
}*/
}
UserDAO.java
package library.dao.impl;
import library.dao.interfaces.GenericDAO;
import library.entity.User;
import javax.ejb.Local;
import javax.ejb.Stateless;
import java.util.HashMap;
import java.util.Map;
#Stateless
public class UserDAO extends GenericDAO {
public UserDAO() {
super(User.class);
}
public User selectUserByLoginAndPassword(String login, String password) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("login", login);
parameters.put("password", password);
return (User) super.findOneResult(User.SELECT_USER_BY_LOGIN_AND_PASSWORD, parameters);
}
/*public List<User> getClients() {
Query namedQuery = entityManager.createNamedQuery(User.ALL_CLIENTS, User.class);
List<User> clientsList = namedQuery.getResultList();
return clientsList;
}
#Override
public void returnBooks(long userId, long[] ids) {
User user = entityManager.find(User.class, userId);
for (long id : ids) {
Book book = entityManager.find(Book.class, id);
user.getTakenBooks().remove(book);
}
entityManager.merge(user);
}
#Override
public void takeBooks(long userId, long[] ids) {
User user = entityManager.find(User.class, userId);
for (long id : ids) {
Book book = entityManager.find(Book.class, id);
user.getTakenBooks().add(book);
}
entityManager.merge(user);
}*/
}
GenericDAO.java
package library.dao.interfaces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;
public abstract class GenericDAO<T> {
private static final String LIBRARY_PERSISTENCE_UNIT = "LibraryPersistenceUnit";
#PersistenceContext(unitName = LIBRARY_PERSISTENCE_UNIT)
private EntityManager entityManager;
private Class<T> entityClass;
public GenericDAO() {
}
public GenericDAO(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void save(T entity) {
entityManager.persist(entity);
}
protected void delete(Object id, Class<T> classe) {
T entityToBeRemoved = entityManager.getReference(classe, id);
entityManager.remove(entityToBeRemoved);
}
public T update(T entity) {
return entityManager.merge(entity);
}
public T find(int entityID) {
return entityManager.find(entityClass, entityID);
}
// Using the unchecked because JPA does not have a
// entityManager.getCriteriaBuilder().createQuery()<T> method
#SuppressWarnings({"unchecked", "rawtypes"})
public List<T> findAll() {
/* CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));*/
return null;//entityManager.createQuery(cq).getResultList();
}
// Using the unchecked because JPA does not have a
// ery.getSingleResult()<T> method
#SuppressWarnings("unchecked")
protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
T result = null;
try {
Query query = entityManager.createNamedQuery(namedQuery);
// Method that will populate parameters if they are passed not null and empty
if (parameters != null && !parameters.isEmpty()) {
populateQueryParameters(query, parameters);
}
result = (T) query.getSingleResult();
} catch (Exception e) {
System.out.println("Error while running query: " + e.getMessage());
e.printStackTrace();
}
return result;
}
private void populateQueryParameters(Query query, Map<String, Object> parameters) {
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
}
LibraryController
package library.controller;
import library.entity.User;
import library.facades.interfaces.UserFacade;
import library.resourses.constants.Constants;
import library.resourses.enums.Role;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LibraryController extends HttpServlet {
#EJB
private UserFacade userFacade;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
performAction(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
performAction(request, response);
}
private void performAction(HttpServletRequest request, HttpServletResponse response) {
String pageType = request.getParameter(Constants.PAGE_TYPE);
if (pageType != null) {
try {
String page = null;
String login = request.getParameter(Constants.USER_LOGIN);
String password = request.getParameter(Constants.USER_PASSWORD);
User user = userFacade.findUserByLoginAndPassword(login, password);
if (user == null) {
request.getSession().setAttribute(Constants.ERROR,
Constants.ERROR_MESSAGE_7);
page = Constants.MAIN_PAGE;
} else {
String namePage = user.getRole().toString().toLowerCase();
if (isClient(user)) {
request.getSession().setAttribute(Constants.CLIENT,
user);
request.getSession().setAttribute(Constants.ERROR, null);
} else if (isAdministrator(user)) {
request.getSession().setAttribute(Constants.ADMINISTRATOR,
user);
request.getSession().setAttribute(Constants.ERROR, null);
}
page = Constants.START_PAGES + namePage + Constants.END_PAGES;
}
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(page);
requestDispatcher.forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean isAdministrator(User user) {
return user.getRole().equals(Role.ADMINISTRATOR);
}
private boolean isClient(User user) {
return user.getRole().equals(Role.CLIENT);
}
}
I get null for userFacade.Can you explain me what I do wrong.
Thanks.
The problem is that instead of letting the container instantiate and inject the DAO for you, you explicitely create the DAO instance by yourself:
private IUserDAO dao;
public UserService() {
dao = UserDAOImpl.getInstance();
}
For the EntityManager to be injected into the DAO, the container must instantiate it, not you. Replace the above code with the following, which uses dependency injection, and will thus also have the advantage of making your code testable:
#Inject
private IUserDAO dao;