Unabel to submit form data using jersy to mysql database - mysql

This is the Database connection java file which will connect to mysql local databse
package com.example.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
public Connection getConnection() throws Exception
{
Connection connection = null;
try
{
String connectionURL = "jdbc:mysql://localhost:3306/test1";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL,
"root", "root");
}
catch (Exception e)
{
e.printStackTrace();
}
return connection;
}
}
This is the web service file for getting and adding up the candidates using com.perpule/hello/plain to get simple hello message & /getCandidate to get all list of candidates
package com.example.webservice;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import org.apache.http.HttpServerConnection;
import com.example.dao.Candidate;
import com.example.model.CandidateManager;
import com.google.gson.Gson;
#Path("/hello")
public class SayHello {
ArrayList<Candidate> candidateArr= new ArrayList<Candidate>();
#Context
UriInfo uriInfo;
#Context
Request request;
#GET
#Path("/plain")
#Produces(MediaType.TEXT_PLAIN)
public String sayHelloPlain()
{
return "hello ";
}
#GET
#Path("/candidates")
#Produces(MediaType.TEXT_PLAIN)
public String CandidateList()
{
String candidates=null ;
try {
candidateArr= new CandidateManager().getCandidates();
Gson gson=new Gson();
candidates=gson.toJson(candidateArr);
}catch (Exception e) {
e.printStackTrace();
}
return candidates;
}
#POST
#Path("/addCandidates")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_PLAIN)
public void submitCandidates(#FormParam("name") String name,
#FormParam("pass") String pass,
#FormParam("phone") String phone, #FormParam("email") String
email,#FormParam("city") String city)
{
Candidate candidate =new Candidate();
candidate.setName(name);
candidate.setPass(pass);
candidate.setPhone(phone);
candidate.setCity(city);
candidate.setEmail(email);
CandidateManager candidateManager=new CandidateManager();
try {
candidateManager.addCandidates(candidate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Model class
package com.example.model;
import java.sql.Connection;
import java.util.ArrayList;
import com.example.dao.Access;
import com.example.dao.Candidate;
import com.example.dao.Database;
public class CandidateManager {
public ArrayList<Candidate> getCandidates() throws Exception
{
ArrayList<Candidate> candidateList = new ArrayList<Candidate>();
Database db= new Database();
Connection con=db.getConnection();
Access access=new Access();
candidateList=access.getCandidates(con);
return candidateList;
}
public void addCandidates(Candidate candidate) throws Exception
{
// ArrayList<Candidate> candidateData = new ArrayList<Candidate>();
Database db= new Database();
Connection con=db.getConnection();
new Access().addCandidates(con,candidate);
}
}
This is the DAO class for execueteQuery purpose : code for addCandidate is here
package com.example.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class Access {
ResultSet rs=null;
public ArrayList<Candidate> getCandidates(Connection connection) throws
SQLException{
ArrayList<Candidate> candidateList =new ArrayList<Candidate>();
String sql="select * from candidate";
PreparedStatement psmt =connection.prepareStatement(sql);
rs=psmt.executeQuery();
try {
while(rs.next())
{
Candidate candidateObj = new Candidate();
candidateObj.setName(rs.getString("name"));
candidateObj.setPass(rs.getString("pass"));
candidateObj.setEmail(rs.getString("email"));
candidateObj.setPhone(rs.getString("phone"));
candidateObj.setCity(rs.getString("city"));
candidateList.add(candidateObj);
}
}catch (SQLException e) {
e.printStackTrace();
}
return candidateList;
}
public void addCandidates(Connection connection, Candidate candidate)
throws SQLException
{
String sql="insert into candidate values(?,?,?,?,?)";
try {
PreparedStatement preparedStatement
=connection.prepareStatement(sql);
// preparedStatement.executeQuery();
preparedStatement.setString(1, candidate.name);
preparedStatement.setString(2, candidate.pass);
preparedStatement.setString(3, candidate.phone);
preparedStatement.setString(4, candidate.city);
preparedStatement.setString(5, candidate.phone);
preparedStatement.execute();
connection.close();
}catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}

Related

How I can display data from 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);
}

EJB 3 Test Locally, Getting Error

I have created a web project and created an EJB(interface: LibrarySessionBeanRemote.java and class: LibrarySessionBean). I have deployed the war file on JBoss 7.1 server. Below is the code of both files:
LibrarySessionBeanRemote.java
package com.practice.stateless;
import java.util.List;
import javax.ejb.Remote;
#Remote
public interface LibrarySessionBeanRemote {
void addBook(String bookName);
List<String> getBooks();
}
LibrarySessionBean.java
package com.practice.stateless;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
#Stateless
public class LibrarySessionBean implements LibrarySessionBeanRemote {
List<String> bookShelf;
public LibrarySessionBean() {
bookShelf = new ArrayList<String>();
}
#Override
public void addBook(final String bookName) {
bookShelf.add(bookName);
}
#Override
public List<String> getBooks() {
return bookShelf;
}
}
I am trying to call the EJB locally inside main method, below is the code:
LibrarySessionBeanTest2
package com.practice.stateless.test;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.practice.stateless.LibrarySessionBean;
import com.practice.stateless.LibrarySessionBeanRemote;
public class LibrarySessionBeanTest2 {
public static LibrarySessionBeanRemote doLookup() throws NamingException {
final Properties jndiProp = new Properties();
jndiProp.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jboss.naming.remote.client.InitialContextFactory");
jndiProp.put(Context.PROVIDER_URL, "remote://localhost:4447");
jndiProp.put(Context.SECURITY_PRINCIPAL, "username");
jndiProp.put(Context.SECURITY_CREDENTIALS, "password");
final String appName = "";
final String moduleName = "StatelessExample";
final String distinctName = "";
final String beanName = LibrarySessionBean.class.getSimpleName();
final String viewClassName = LibrarySessionBeanRemote.class.getName();
final Context ctx = new InitialContext(jndiProp);
final String jndiName = "ejb:" + appName + "/" + moduleName + "/"
+ distinctName + "/" + beanName + "!" + viewClassName;
// jndiName = "java:global/StatelessExample/LibrarySessionBean";
return (LibrarySessionBeanRemote) ctx.lookup(jndiName);
}
public static void invokeStatelessBean() throws NamingException {
final LibrarySessionBeanRemote librarySessionBeanRemote = doLookup();
librarySessionBeanRemote.addBook("book 1");
for (final String book : librarySessionBeanRemote.getBooks()) {
System.out.println(book);
}
}
public static void main(final String[] args) {
try {
invokeStatelessBean();
} catch (final NamingException e) {
e.printStackTrace();
}
}
}
After running the LibrarySessionBeanTest2 class I am getting below error:
javax.naming.NameNotFoundException: ejb:/StatelessExample//LibrarySessionBean!com.practice.stateless.LibrarySessionBeanRemote -- service jboss.naming.context.java.jboss.exported.ejb:.StatelessExample."LibrarySessionBean!com.practice.stateless.LibrarySessionBeanRemote"
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:97)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:178)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleServerMessage(Protocol.java:127)
at org.jboss.naming.remote.protocol.v1.RemoteNamingServerV1$MessageReciever$1.run(RemoteNamingServerV1.java:73)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I am new to EJB 3 so I don't know whether I am using JNDI name correctly or not. It would be great if somebody can help me to fix this problem.
Now issue has been fixed by adding two more properties, please find them below:
jndiProp.put("jboss.naming.client.ejb.context", true);
jndiProp.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");

JSON parse to populate listview Android Studio

I am pulling my hair out over this. After numerous tutorials, I thought I found the perfect one (7th to be exact. But after following the tutorial, I found out that JSONparse is deprecated. Can someone please give me a solution for this. I just want to read an array from the url and populate a listview.
The array is:
{ "lotInfo":[{"lot":"A","spaces":"198","rates":"3.25"},
{"lot":"B","spaces":"165","rates":"7.50"}]}
MainActivity.Java:
package com.example.sahan.wtf;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
private Context context;
private static String url = "http://192.168.0.199/get_info.php";
private static final String lot = "lot";
private static final String spaces = "spaces";
private static final String rates = "rates";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(ListActivity activity) {
Log.i("1", "Called");
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { lot, spaces, rates }, new int[] { R.id.lot, R.id.spaces, R.id.rates });
setListAdapter(adapter);
lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vlot = c.getString(lot);
String vspaces = c.getString(spaces);
String vrates = c.getString(rates);
HashMap<String, String> map = new HashMap<String, String>();
map.put(lot, vlot);
map.put(spaces, vspaces);
map.put(rates, vrates);
jsonlist.add(map);
} catch (JSONException e)
{
e.printStackTrace();
}
}
return null;
}
}
}
JSONParser.Java:
package com.example.sahan.wtf;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("Error....", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return array;
}
}
The error I get is:
Error:(74, 13) error: cannot find symbol class JSONParse
It seems that you have a typo, instead of:
JSONParse jParser = new JSONParser();
Should be:
JSONParser jParser = new JSONParser();

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");
}
}
}
}

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;