why the getter method goes null when i call in another class? - java

but in the set method on another class when i got the value is exist,,
so i have 3 classes the first class is getter setter class , second is the class to fill the set and the last is class to get the method getter,, but it goes null value...
public class loginAdminn {
String Username, Password;
public String getUsername() {
return Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
}
// method to fill the set on another class
public void in(){
loginAdminn p = new loginAdminn();
String user = Username.getText();
String pass = Password.getPassword().toString();
p.setUsername(user);
p.setPassword(pass);
// new NewMain().run();
tes.jalankan();
}
// class method getter (null)
public void jalankan() {
loginAdminn br = new loginAdminn();
String kueri = "Select Username, password from Admin";
int x = 0;
try {
ps = conn.prepareStatement(kueri);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if (br.getUsername().equalsIgnoreCase(rs.getString("Username"))) {
if (br.getPassword().equalsIgnoreCase(rs.getString("Password"))) {
JOptionPane.showMessageDialog(null, "Masuk Berhasil");
x = 1;
break;
}
}
}
if (x == 1) {
HomeAdmin b = new HomeAdmin();
b.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Masuk Gagal");
DaftarAplikasi da = new DaftarAplikasi();
da.setVisible(true);
}
ps.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
//the getUsername and getPassword goes null

Class A
String x;
setter getter x
A c = new A();
c.get... // object Class A type X
Class B
A c = new A();
c.get... // object Class B type X
c.get from Class A != c.get from Class B
Basically by using new you're creating two independent from each other objects!

Your getUserName() is coming null because the object you are using to compare has not userName value assigned to it.
public void jalankan() {
//creating an object here , br has no username assigned
loginAdminn br = new loginAdminn();
String kueri = "Select Username, password from Admin";
int x = 0;
try {
ps = conn.prepareStatement(kueri);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if (br.getUsername().equalsIgnoreCase(rs.getString("Username"))) {
if (br.getPassword().equalsIgnoreCase(rs.getString("Password"))) {
JOptionPane.showMessageDialog(null, "Masuk Berhasil");
x = 1;
break;
}
}
}
when you are reading br.getUserName() it is suppose to give you null.

Related

Java Unit Testing Help for loop

public void login(String username, String password) {
for(int i = 0; i < Users.size(); i++) {
user users = (user) Users.get(i);
if(users.getUsername().contains(username)
&& users.getPassword().contains(password)) {
userName = users.getUsername();
userLevel = users.getUserLevel();
isSuccess = true;
}
}
}
Hello everyone. I'm trying to do a java unit testing for this method using Java Junit. But i don't know how to do that? Because there's a for loop.
Let me explain the method.
for(int i=0;i<Users.size();i++){
This "Users" is a vector. This loop runs unit this vector ends.
user users = (user) Users.get(i);
Then im calling user class for user instance.
if((users.getUsername().contains(username)) &&
(users.getPassword().contains(password))) {
Then if any of the users that matches with the values in the vectors, this gives the output.
Can anyone tell me how to write a unit test for this?
Your code is hard to read. Learn Java coding standards.
Your method should not be printing anything. Determine if the user is valid. Print messages elsewhere.
I'll assume you've got a class User that encapsulates credentials:
package misc.user;
import org.apache.commons.lang3.StringUtils;
/**
* Created by Michael
* Creation date 8/5/2017.
* #link https://stackoverflow.com/questions/45524768/java-unit-testing-help-for-loop
*/
public class User {
private final String username;
private final String password;
public User(String username, String password) {
if (StringUtils.isBlank(username)) throw new IllegalArgumentException("username cannot be blank or null");
if (StringUtils.isBlank(password)) throw new IllegalArgumentException("password cannot be blank or null");
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
User user = (User) o;
if (!getUsername().equals(user.getUsername())) { return false; }
return getPassword().equals(user.getPassword());
}
#Override
public int hashCode() {
int result = getUsername().hashCode();
result = 31 * result + getPassword().hashCode();
return result;
}
#Override
public String toString() {
return "{\"User\":{"
+ "\"username\":\"" + username + "\""
+ ",\"password\":\"" + password + "\""
+ "}}";
}
}
I'd test it using JUnit:
package misc.user;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Michael
* Creation date 8/5/2017.
* #link https://stackoverflow.com/questions/45524768/java-unit-testing-help-for-loop
*/
public class UserTest {
private static List<User> users;
#BeforeClass
public static void setUp() {
users = new ArrayList<>();
users.add(new User("FooBar", "myPassword"));
users.add(new User("GeorgeBush", "exPrez"));
users.add(new User("weatherBoy", "cloudy"));
}
#Test
public void testLogin_Success() {
// setup
String username = "weatherBoy";
String password = "cloudy";
// exercise
boolean isValidUser = users.contains(new User(username, password));
// assert
Assert.assertTrue(isValidUser);
}
#Test
public void testLogin_Failure() {
// setup
String username = "noSuchUser";
String password = "does not matter";
// exercise
boolean isValidUser = users.contains(new User(username, password));
// assert
Assert.assertFalse(isValidUser);
}
}

Listeners and instance variable scope [javafx]

I cannot understand why I can't get proper values of my object inside a listener. I created an instance variable "plant" which is type of "Plant". Then in one of my methods I created a Plant object and assigned it to "plant variable". Then I set some fields of plant object like "name" and "id". Everything works fine but... I created a listener to open a new window after button click. And what is strange for me, inside this listener the program cannot see the plant object fields which I set earlier.
Here is my code:
class Plant {
private plantName;
private gridId;
public String getName() {
return plantName;
}
public void setName(String plantName) {
this.plantName = plantName;
}
public int gridId() {
return gridId;
}
public void setGridId(int gridId) {
this.gridId = gridId;
}
}
The following code presents fragment of GrowboxModel class where the fields for Plant object are setted:
public Plant selectAll(int gridId) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM plant WHERE gridId = ?";
Plant plant = new Plant();
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, gridId);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
plant.setName(resultSet.getString("name"));
plant.setGridId(resultSet.getInt("gridId"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
preparedStatement.close();
resultSet.close();
}
return plant;
}
Below is fragment of my growboxController class:
public Plant plant;
public GrowboxModel model = new GrowboxModel();
private void growboxCellContent(VBox plantAreaVbox) {
plant = model.selectAll(Integer.parseInt(plantAreaVbox.getId()));
if (plant.getName() == null) {
plantName.setText("EMPTY " + plantAreaVbox.getId());
} else {
System.out.println("FULL" + plant.getGridId());
}
}
For now everything was great. The program the fields of plant object. But the problem is below:
public void growboxCellBehaviour(VBox plantAreaVbox) {
plantAreaVbox.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("NAME: " + plant.getName() + ", gridId: " + plant.getGridId());
}
});
}
It was a moment when "plant.getName()" etc. are null, although should have same name.
I know how to create a workaround but just wonder if anyone know why listener can't see these fields.
In the plant class, nothing is actually being assigned you need to actually set the variables.
class Plant {
String plantName;
int id;
public String getName() {
return plantName;
}
public void setName(String plantName1) {
plantName = plantName1;
}
public int gridId() {
return gridId;
}
public void setId(int id1) {
id = id1;
}
}

How to read elements of arraylist of a class defined in another class in java?

I am working on a project for my college.
i have two classes as "Email_info" and "contacts". In class "contacts", i made an Arraylist of type "Email_info". This class contacts is used to add data to a XML file("contacts.xml" ), and uses variables of email_info class. The problem is whenever i try to access elements of this "contacts.xml" file after unmarshalling the file, i get address as "mailwidgetaa.Email_info#12d3a4e9" instead of the actual data( which should be like, e_id- abc#gmail.com, pass- password). So how do I do get the actual data ?
below is the full code::
package mailwidgetaa;
#XmlRootElement
public class Contacts {
List<Email_info> contacList = new ArrayList<Email_info>();
#XmlElement
public List<Email_info> getContacList() {
return contacList;
}
public void setContacList(List<Email_info> contacList) {
this.contacList = contacList;
}
}
#XmlRootElement
class Email_info {
String e_id;
String u_name;
String pass;
#XmlElement
public String getE_id() {
return e_id;
}
public void setE_id(String e_id) {
this.e_id = e_id;
}
#XmlElement
public String getU_name() {
return u_name;
}
public void setU_name(String u_name) {
this.u_name = u_name;
}
#XmlElement
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
public class Mailwidgetaa {
public static void main(String[] args) {
contatcs con = new contacts();
con = null;
try {
JAXBContext jaxbc1 = JAXBContext.newInstance(Contacts.class);
Unmarshaller unmarsh = jaxbc1.createUnmarshaller();
con = (Contacts) unmarsh.unmarshal(new File("contacts.xml"));
} catch (Exception e) {
System.out.println("Exception " + e.getMessage());
}
Email_info ein = new Email_info();
ein.setE_id(ui);
ein.setU_name(un);
con.getContacList().add(ein);
try {
JAXBContext jaxbc = JAXBContext.newInstance(Contacts.class);
Marshaller marsh = jaxbc.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marsh.marshal(con, new File("contacts.xml"));
} catch (JAXBException e) {
System.out.println("EXCEPTION" + e.getMessage());
}
}
Iterator e= con.contacList.iterator();
while(e.hasNext()){
System.out.println(e.next());
}
}
That's because you haven't implemented toString method in your Email_Info class. Implement it like:
#Override
public String toString() {
return "e_id: " + e_id + " u_name: " + u_name + " pass: " + pass;
}

Why do I have "private access" error even if I didn't return any field?

I am learning OOP in Java. When finishing coding and compiling it, the compiler shows that this Manager class has private access to the Photographer class. I've been working on for a whole night, but I still cannot find the problem. Anyone could tell me how to fix it?
public class Manager
{
private ArrayList<Assignment> toDoList;
private ArrayList<Photographer> employees;
public Manager()
{
this.toDoList = new ArrayList<Assignment>();
this.employees = new ArrayList<Photographer>();
}
public void hire(String photographer)
{
employees.add(new Photographer(photographer));
}
public void giveOutAssignments()
{
int maxId;
if(toDoList.size()!=0 && employees.size()!=0){
for(Photographer p: employees){
maxId = 0;
//get highest priority
for(int i = 1; i<toDoList.size();i++){
//just check the unfinished assigns
if(!toDoList.get(i).getStatus()){
if(toDoList.get(i).getPriority()>toDoList.get(maxId).getPriority())
maxId = i;
}
}
//take the highest priority
Assignment currentAssign = toDoList.get(maxId);
//HERE IS THE PROBLEM
p.takePicture(currentAssign.getDescription());
//set it as finished
toDoList.get(maxId).setStatus();
}
}
}
}
Here is the Photographer class:
public class Photographer
{
private Map photos;
private String name;
public Photographer(String name)
{
photos = new HashMap(); // An important line. Must go in the constructor.
readPhotos(); // A very important line. this must go in the Photographer
// constructor so that the photographer will be able to take Pictures.
this.name = name;
}
private String takePicture(String description)
{
return photos.get(description);
}
private void readPhotos()
{
Pattern commentPattern = Pattern.compile("^//.*");
Pattern photoPattern = Pattern.compile("([a-zA-Z0-9\\.]+) (.*)");
try
{
Scanner in = new Scanner(new File("photos.txt"));
while (in.hasNextLine())
{
String line = in.nextLine();
Matcher commentMatcher = commentPattern.matcher(line);
Matcher photoMatcher = photoPattern.matcher(line);
if (commentMatcher.find())
{
// This line of the file is a comment. Ignore it.
}
else if (photoMatcher.find())
{
String fileName = photoMatcher.group(1);
String description = photoMatcher.group(2);
photos.put(description, fileName);
}
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
}
takePicture is declared private, it is inaccessible from any other context other than Photographer...
private String getDescription() {
change it to public...
public String getDescription() {
Take a look at Controlling Access to Members of a Class for more details
ps-
I also had an issue with the return type of takePicture in Photographer...
private String takePicture(String description)
{
return photos.get(description);
}
And had to change to something more like...
public String takePicture(String description) {
return (String)photos.get(description);
}

Creating an organized Java library

I want to create a library(Jar file) in Java which would contain all my methods for the database we use. There are about 60 methods in there so I would like to make it more organized. I would like to call the methods like the example provided below.
db.accounts.add(username, password); or db.accounts().add(username, password);
db.names.delete(name); or db.names().delete(name);
What is the best way of doing this in Java?
You could save yourself a lot of trouble and write a generic DAO:
package persistence;
public interface GenericDao<K, V> {
V find(K id);
List<V> find();
K save(V value);
void update(V value);
void delete(V value);
}
I'd forget about writing your own persistence classes and use a proven solution, like Spring JDBC template.
This problem has been solved many times, many ways. What do you hope to do to improve upon what exists? How will you justify the added expense of developing, testing, and maintaining this functionality?
Here some snapshot of my custom library for connect to database:
PostgreConnection.java
public class PostgreConnection {
private static Connection conn;
public Connection makeConnection(String url, String db, String username, String password) {
if (conn == null) {
try {
Class.forName(Constants.POSTGRES_DRIVER);
conn = DriverManager.getConnection(Constants.POSTGRES_URL + url + "/" + db, username, password);
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(PostgreConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
return conn;
}
}
Constants.java
public class Constants {
public static String POSTGRES_URL = "jdbc:postgresql://";
public static String POSTGRES_DRIVER = "org.postgresql.Driver";
}
In org.ert.model you can store all the Model that you need based on the tables of your database.
NotifyCharts.java
public class NotifyCharts {
private Integer Id;
private String revName;
private Date importDate;
private Integer pages;
private Boolean status;
public Integer getId() {
return Id;
}
public void setId(Integer Id) {
this.Id = Id;
}
public Date getImportDate() {
return importDate;
}
public void setImportDate(Date importDate) {
this.importDate = importDate;
}
public Integer getPages() {
return pages;
}
public void setPages(Integer pages) {
this.pages = pages;
}
public String getRevName() {
return revName;
}
public void setRevName(String revName) {
this.revName = revName;
}
public Boolean isStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
}
SQLQuery is an abstract class for some basic method such as insert, update, delete, etc.
SQLQuery.java
public abstract class SQLQuery<T> {
protected void makeStatement(String url, String db, String username, String password) {
PostgreConnection connect = new PostgreConnection();
Connection con = connect.makeConnection(url, db, username, password);
try {
state = (Statement) con.createStatement();
} catch (SQLException ex) {
Logger.getLogger(SQLQuery.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String arrayBuilder(Object[] obj, boolean val) {
StringBuilder arr = new StringBuilder();
arr.append("(");
for (int i = 0; i < obj.length; i++) {
if (i < obj.length - 1) {
if (val) {
arr.append("'");
}
arr.append(obj[i]);
if (val) {
arr.append("'");
}
arr.append(", ");
} else {
if (val) {
arr.append("'");
}
arr.append(obj[i]);
if (val) {
arr.append("'");
}
}
}
arr.append(")");
return arr.toString();
}
public int insertRecord() throws SQLException {
StringBuilder query = new StringBuilder();
query.append("INSERT INTO ").append(tableName).append(arrayBuilder(columns, false)).append(" VALUES ").append(arrayBuilder(values, true));
return state.executeUpdate(query.toString());
}
public ResultSet getAll() throws SQLException {
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM ").append(tableName);
rSet = state.executeQuery(query.toString());
return rSet;
}
public abstract void setColsAndVals(T t);
}
NotifyChartsSQL.java is implementation of the abstract class, org.ert.sql.impl is package to store all your implementation that you need.
NotifyChartsSQL.java
public class NotifyChartsSQL extends SQLQuery<NotifyCharts> {
public NotifyChartsSQL(String url, String db, String username, String password, NotifyCharts notify) {
makeStatement(url, db, username, password);
setColsAndVals(notify);
}
#Override
public final void setColsAndVals(NotifyCharts notify) {
Map<String, Object> objects = new HashMap<>();
String[] columns;
Object[] values;
if(notify.getId() != null)
objects.put("id", notify.getId());
if(notify.getRevName() != null)
objects.put("rev_name", notify.getRevName());
if(notify.getImportDate() != null)
objects.put("import_date", notify.getImportDate());
if(notify.getPages() != null)
objects.put("pages", notify.getPages());
objects.put("status", notify.isStatus());
columns = Arrays.copyOf(objects.keySet().toArray(), objects.size(), String[].class);
values = objects.values().toArray();
setColumns(columns);
setValues(values);
setTableName("notify_charts");
}
}
And last is the test package that test your custom library to make sure that everything is ok.
TestMain.java
public class TestMain {
public static void main(String[] args) {
NotifyCharts notify = new NotifyCharts();
try {
notify.setRevName("Test456");
notify.setImportDate(new Date());
notify.setPages(10);
notify.setStatus(false);
NotifyChartsSQL notCharts = new NotifyChartsSQL("localhost:5432", "charts", "username", "password", notify);
int status = notCharts.insertRecord();
if (status == 1) {
System.out.println("Success Insert");
} else {
System.out.println("Failed Insert");
}
} catch (SQLException ex) {
Logger.getLogger(TestMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I suggest if you want to make this custom library if you using manual JDBC and not using ORM such as Hibernate. Because in Hibernate is already provide all the methods that you need except do you want to add some special method you can do like duffymo said before. This idea of custom library is come from the DAO and the Hibernate structure.
Thanks for read it, and please learn some Design Pattern in Java if you want to make some custom library that more organized.

Categories

Resources