Java calling function with class in argument - java

We have simple homework. I need to create a user with address in java. But I can't figure out where to write address or how to connect the address to user.
My User
package xxx;
import java.util.List;
import java.util.UUID;
public class User {
private String ID;
private String firstName;
private String lastName;
private int idNumber;
private String email;
private Address officialAddress;
private Address postAddress;
private List contracts;
public User(String firstName, String lastName, int idNumber, String email,Address officialAddress, Address postAddress) {
ID = UUID.randomUUID().toString();
setFirstName(firstName);
setLastName(lastName);
setIdNumber(idNumber);
setEmail(email);
}
public void setFirstName(String firstName) {
if(firstName == null){
throw new IllegalArgumentException("Please fill firstName");
} this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String lastName) {
if(lastName == null){
throw new IllegalArgumentException("Please fill lastName");
} this.lastName = lastName;
}
public String getLastName(){
return lastName;
}
public void setIdNumber(int idNumber) {
if(idNumber > 0){
throw new IllegalArgumentException("Please fill idNumber");
} this.idNumber = idNumber;
}
public int getIdNumber(){
return idNumber;
}
public void setEmail(String email) {
if(email == null){
throw new IllegalArgumentException("Please fill email");
} this.email = email;
}
public String getEmail(){
return email;
}
}
My address
package xxx;
public class Address {
private int zipcode;
private String region;
private String streetName;
private int streetNumber;
public Address(int zipcode, String region, String streetName, int streetNumber) {
setZipcode(zipcode);
setRegion(region);
setStreetName(streetName);
setStreetNumber(streetNumber);
}
private void setZipcode(int zipcode) {
if(zipcode > 0){
throw new IllegalArgumentException("Please fill zipcode");
} this.zipcode = zipcode;
}
private int getZipcode(){
return zipcode;
}
private void setRegion(String region) {
if(region == null){
throw new IllegalArgumentException("Please fill region");
} this.region = region;
}
private String getRegion(){
return region;
}
private void setStreetName(String streetName) {
if(streetName == null){
throw new IllegalArgumentException("Please fill region");
} this.streetName = streetName;
}
private String getStreetName(){
return streetName;
}
private void setStreetNumber(int streetNumber) {
if(streetNumber > 0){
throw new IllegalArgumentException("Please fill zipcode");
} this.streetNumber = streetNumber;
}
private int getStreetNumber(){
return streetNumber;
}
}
But how i can create user if there is no address in arguments. But i dont know how to create it with that address argument.(Maybe i need it to put out of arguments and connect somehow different).
And this is my try but i get error that i need to fill zipcode.
private Scanner scannerBuff = new Scanner(System.in);
private String firstName;
private User customer;
private Address officialAddress;
private Address postAddress;
public Engine() {
officialAddress = new Address(484984,"gdfgfd","gdfgdfgdf",4);
postAddress = new Address(484984,"gdfgdf","gdfgdfg",4);
customer = new User("gdfgdf","gdfgdf",123456,"fdsfd",officialAddress,postAddress );
Thanks for any help.

To handle addresses, or no addresses, make multiple constructors
public User(String firstName, String lastName, int idNumber, String email) {
ID = UUID.randomUUID().toString();
setFirstName(firstName);
setLastName(lastName);
setIdNumber(idNumber);
setEmail(email);
}
public User(String firstName, String lastName, int idNumber, String email, Address officialAddress, Address postAddress) {
this(firstName, lastName, idNumber, email); // call the first constructor to avoid duplicate code
setOfficialAdress(officialAddress);
setPostAdress(postAddress);
}
And the setters like the others
public void setOfficialAdress(Address officialAddress) {
if(officialAddress == null){
throw new IllegalArgumentException("Please fill officialAddress");
}
this.officialAddress = officialAddress;
}

Related

override equals of a custom object (called by contains method of a list)

I have two types of user, LibraUsers and GenesysUser. Each have their own properties, but some are similar.
I need to find the differences between two lists of these types of users. Made a small program to illustrate my problem - My issue is that I have duplicate entries in my difference list, the compare method on the list does not seem to do its job. I've read that I should override the equals method, and also the hashcode (in this case of the LibraUser). I tried that using an apache function, but it did not work.
The question therefore is, what are the alternatives for solving this problem?
import java.util.ArrayList;
import java.util.List;
// one class needs to have a main() method
public class HelloWorld {
public static List<LibraUser> libraUsers = new ArrayList<LibraUser>();
public static List<GenesysUser> genesysUsers = new ArrayList<GenesysUser>();
public static List<LibraUser> difference = new ArrayList<LibraUser>();
public static void initialiseGenesysUsers() {
// GenesysUser(String alias, String firstname, String lastname, String email)
genesysUsers.add(new GenesysUser("Donna", "Donna", "Paulsen", "donna#gmail.com", true));
genesysUsers.add(new GenesysUser("TheHarv", "Harvey", "Specter", "harvey#gmail.com", true));
genesysUsers.add(new GenesysUser("Rache", "Rachel", "Zane", "rachel#gmail.com", true));
genesysUsers.add(new GenesysUser("Mike", "Mike", "Ross", "mike#gmail.com", true));
}
public static void initialiseLibraUsers() {
// LibraUser(String name, String email, String telephone) {
libraUsers.add(new LibraUser("Louis", "louis#gmail.com", "0447521082"));
libraUsers.add(new LibraUser("Jessica", "jessica#gmail.com", "0447521044"));
libraUsers.add(new LibraUser("Mike", "mike#gmail.com", ""));
}
public static void getDifference() {
for (LibraUser librauser : libraUsers) {
for (GenesysUser genesysuser : genesysUsers) {
String genusername = genesysuser.getFirstname();
LibraUser dummy = new LibraUser(genusername, genesysuser.getEmail(), "");
if (!difference.contains(dummy)) {
// do the actual comparison using the relevant keys and insert into a new list
if (!librauser.getUsername().equals(genusername)) {
difference.add(dummy);
}
}
} // inner for loop
}// outer for loop
}
public static void printDifference() {
for (LibraUser usr : difference) {
System.out.println(usr.getUsername());
}
}
// arguments are passed using the text field below this editor
public static void main(String[] args) {
initialiseGenesysUsers();
initialiseLibraUsers();
getDifference();
printDifference();
}
}
public class GenesysUser {
private String Alias;
private String Firstname;
private String Lastname;
private String Email;
private boolean Active;
public GenesysUser(String alias, String firstname, String lastname, String email, boolean active) {
Alias = alias;
Firstname = firstname;
Lastname = lastname;
Email = email;
Active = active;
}
public String getAlias() {
return Alias;
}
public String getFirstname() {
return Firstname;
}
public String getLastname() {
return Lastname;
}
public String getEmail() {
return Email;
}
public void setAlias(String alias) {
Alias = alias;
}
public void setFirstname(String firstname) {
Firstname = firstname;
}
public void setLastname(String lastname) {
Lastname = lastname;
}
public void setEmail(String email) {
Email = email;
}
public void setActive(boolean active) {
Active = active;
}
public boolean getActive() {
return Active;
}
}
public class LibraUser {
private String username;
private String email;
private String telephone;
public LibraUser(String username, String email, String telephone) {
this.username = username;
this.email = email;
this.telephone = telephone;
}
public String getUsername() {
return this.username;
}
public String getEmail() {
return this.email;
}
public String getTelephone() {
return this.telephone;
}
public void setName(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof LibraUser)) {
return false;
}
LibraUser user = (LibraUser) o;
return new EqualsBuilder()
.append(username, user.getUsername())
.append(email, user.getEmail())
.isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(username)
.append(email)
.toHashCode();
}
}
You need to use .equals instead of == to test the equality
if(librauser.getUsername() != genusername)
should be replaced with
if(!librauser.getUsername().equqls(genusername))

How to map JSONObject in Java object

I have to map this JSONObject into a Java object.
This is my Json:
{"WALLET":{
"ID":"1234",
"BAL":"20.000",
"NAME":"Filomena",
"EMAIL":"filo#gmail.com",
"DOCS":[
{
"ID":"001",
"S":"0",
"TYPE":"CardId",
"VD":"2019"
}
],
"IBANS":[
{
"ID":"001",
"S":"1",
"DATA":"iban",
"SWIFT":"swiftCode",
"HOLDER":"holder"
}
],
"STATUS":"string",
"BLOCKED":"1",
"SDDMANDATES":[
{
"ID":"sddMandateId",
"S":"status",
"DATA":"iban",
"SWIFT":"swiftCode"
}
],
"LWID":"string",
"CARDS":[
{
"ID":"string",
"EXTRA":{
"IS3DS":"string",
"CTRY":"string",
"AUTH":"string",
"NUM":"string",
"EXP":"string",
"TYP":"string"
}
}
],
"FirstName":"string",
"LastName":"string",
"CompanyName":"string",
"CompanyDescription":"string",
"CompanyWebsite":"string"
}
}
This is my Java class:
public class Wallet {
private String id;
private String bal;
private String name;
private String email;
private List<Doc> docs;
private List<Iban> ibans;
private String status;
private String blocked;
private List<SddMandate> sddMandates ;
private String lwid;
private List<Card> cards;
private String firstName;
private String lastname;
private String companyName;
private String companyDescription;
private String companyWebSite;
public Wallet(){
}
public Wallet(String id, String bal, String name, String email, List<Doc> docs, List<Iban> ibans, String status,
String blocked, List<SddMandate> sddMandates, String lwid, List<Card> cards, String firstName,
String lastname, String companyName, String companyDescription, String companyWebSite) {
super();
this.id = id;
this.bal = bal;
this.name = name;
this.email = email;
this.docs = docs;
this.ibans = ibans;
this.status = status;
this.blocked = blocked;
this.sddMandates = sddMandates;
this.lwid = lwid;
this.cards = cards;
this.firstName = firstName;
this.lastname = lastname;
this.companyName = companyName;
this.companyDescription = companyDescription;
this.companyWebSite = companyWebSite;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBal() {
return bal;
}
public void setBal(String bal) {
this.bal = bal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
public List<Iban> getIbans() {
return ibans;
}
public void setIbans(List<Iban> ibans) {
this.ibans = ibans;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getBlocked() {
return blocked;
}
public void setBlocked(String blocked) {
this.blocked = blocked;
}
public List<SddMandate> getSddMandates() {
return sddMandates;
}
public void setSddMandates(List<SddMandate> sddMandates) {
this.sddMandates = sddMandates;
}
public String getLwid() {
return lwid;
}
public void setLwid(String lwid) {
this.lwid = lwid;
}
public List<Card> getCards() {
return cards;
}
public void setCards(List<Card> cards) {
this.cards = cards;
}
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 getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyDescription() {
return companyDescription;
}
public void setCompanyDescription(String companyDescription) {
this.companyDescription = companyDescription;
}
public String getCompanyWebSite() {
return companyWebSite;
}
public void setCompanyWebSite(String companyWebSite) {
this.companyWebSite = companyWebSite;
}
Now i'm trying to map the object with gson library.
Wallet walletDetails=gson.fromJson(rispostaGetWalletDetails.toString(), Wallet.class);
System.out.println("Balance: "+walletDetails.getBal());
Now when i try to call method on the object i have always null and not the real value.
How i can do?
You have a wrong root level.
Probably, you need to need to get one level down
JSONObject yourObject = json.get("WALLET");
Wallet walletDetails = gson.fromJson(yourObject.toString(), Wallet.class);
To have Gson handle the correct field name mapping while deserializing, you have to register a FieldNamingStrategy like this (using Java 8):
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(field -> field.getName().toUpperCase())
.create();
The strategy will convert each Java field name to match those in your JSON.
This will cover almost all your fields except for those upper-camel-cased in the JSON response, such as "LastName", "CompanyName", etc. In order to map those too, your FieldNamingStrategy will have to become a little bit smarter, like:
field -> {
String fname = field.getName();
return "firstName".equals(fname) || "companyName".equals(fname) /*etc...*/ ? capitalize(fname) : fname.toUpperCase();
}
and so on, I think you got the idea.
The capitalize() method you can find in libraries like Apache Commons Lang or write your own, it's just for examplification here.
Your object variable name doesn't match the json attribute name. "EMAIL" in json should have same EMAIL in object. To overcome this, you could mention #JsonProperty before your attribute declaraction.
for eg:
#JsonProperty("EMAIL")
private String email;

Java: I'm having an issue connecting to a database from another class

I'm making a simple address book app. I have a DatabaseUtility class, which has one method, connectToDatabase() is responsible for pulling info from an embedded database (Java DB) and constructing Contact objects from it.
These Contact objects are then placed into an ArrayList and then the entire ArrayList is returned. Yes, I know this is poor programming. It makes more logical sense to have separate methods for connecting and constructing objects, but this is kind of a quick little project I'm doing for practice, and I think I can get by, right?
Anyways, I also have a ContactControl class which contains an instance of the DatabaseUtility class as one of it's fields, as well as a private ArrayList of Contacts as one of it's fields.
What I want is for the ArrayList in the ContactControl class to be instantiated by the return value of the connectToDatabase() method (which, as I've already mentioned, returns an ArrayList).
However, I keep getting an exception. It's not connecting to the database. It connects when I run the main method that I placed in the DatabaseUtility class, but when I run the main method from the ContactControl class, I get an exception.
My code is below:
Contact class:
package contactbook;
import java.io.IOException;
import java.io.ObjectStreamException;
import java.util.Date;
public class Contact {
private int contactId;
private String lastName;
private String firstName;
private String address;
private String city;
private String state;
private String zip;
private String picture;
private String dob;
public Contact()
{
contactId = 0;
lastName = "Doe";
firstName = "John";
dob = "01/01/1997";
address = "123 ABC Dr.";
city = "Pensacola";
state = "FL";
zip = "12345";
picture = "default1.gif";
}
public Contact(int contactId, String lastName, String firstName, String address, String city, String state, String zip, String picture, String dob)
{
this.contactId = contactId;
this.lastName = lastName;
this.firstName = firstName;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.picture = picture;
this.dob = dob;
}
//setters
public void setContactId(int contactId)
{
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public void setAddress(String address)
{
this.address = address;
}
public void setCity(String city)
{
this.city = city;
}
public void setState(String state)
{
this.state = state;
}
public void setZip(String zip)
{
this.zip = zip;
}
public void setPicture(String picture)
{
this.picture = picture;
}
public void setDob(String dob)
{
this.dob = dob;
}
//getters
public int getContactId()
{
return contactId;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getAddress()
{
return address;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public String getZip()
{
return zip;
}
public String getPicture()
{
return picture;
}
public String getDob()
{
return dob;
}
}
DatabaseUtility class:
package contactbook;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Properties;
public class DataBaseUtility {
public ArrayList<Contact> connectToDatabase() throws Exception {
ArrayList<Contact> contacts = new ArrayList<Contact>();
try
{
// Step 1: "Load" the JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
// Step 2: Establish the connection to the database
String url = "jdbc:derby://localhost:1527/ContactBook";
Connection conn = DriverManager.getConnection(url,"app","app");
System.out.println("Connected!");
Statement stat = null;
stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM PERSON");
int id = 1;
while(rs.next())
{
Contact contact = new Contact();
contact.setContactId(id);
System.out.println(id);
String lastName = rs.getString("lastName");
System.out.println(lastName);
contact.setLastName(lastName);
String firstName = rs.getString("firstName");
System.out.println(firstName);
contact.setFirstName(firstName);
String address = rs.getString("address");
System.out.println(address);
contact.setAddress(address);
String city = rs.getString("city");
System.out.println(city);
contact.setCity(city);
String state = rs.getString("state");
System.out.println(state);
contact.setState(state);
String zip = rs.getString("zip");
System.out.println(zip);
contact.setZip(zip);
String picture = rs.getString("picture");
System.out.println(picture);
contact.setPicture(picture);
Date dob = rs.getDate("dob");
System.out.println(dob);
contact.setDob("" + dob);
contacts.add(contact);
System.out.println("");
contacts.add(contact);
id++;
}
}
catch (Exception e)
{
System.err.println("D'oh! Got an exception!");
System.err.println(e.getMessage());
}
return contacts;
}
public static void main(String[] args)
{
DataBaseUtility dbu = new DataBaseUtility();
try
{
dbu.connectToDatabase();
}
catch(Exception e)
{
e.getMessage();
}
}
}
ContactControl class:
package contactbook;
import java.util.ArrayList;
public class ContactControl {
private DataBaseUtility dbu;
private ArrayList<Contact> contacts;
public ArrayList<Contact> createContacts() throws Exception
{
try
{
contacts = dbu.connectToDatabase();
}
catch(Exception e)
{
System.out.println("Error!");
}
return contacts;
}
public Contact getContact(int id)
{
Contact tact = new Contact();
for(Contact c : contacts)
{
if(id == c.getContactId())
{
tact = c;
}
}
return tact;
}
public static void main(String[] args)
{
ContactControl cc = new ContactControl();
ArrayList<Contact> tacts = new ArrayList<>();
try
{
tacts = cc.createContacts();
}
catch(Exception e)
{
System.out.println("Uh oh! Problem!");
}
}
}
Whenver I run the main method of the ContactControl class, I get the "Error!" message that you see in the try-catch block.
I think the issue is that you're calling a null object in your ContactControl class.
contacts = dbu.connectToDatabase();
dbu is not initialized and basically it's null thus the NullPointerException. Since you're hiding actual exception messages from yourself with some custom messages you wouldn't see it.

while getting values in the form it returns null value

while getting values in the form the bindFromRequest().get() it returns only null value.I got all the String type is null and integr as zer0. Here is my code for controller and model packages and how I can resolve this error:
enter code here
In controller:
public static Result getShow(){
Register register=Form.form(Register.class).bindFromRequest().get();
register.save();
System.out.println(register);
return ok("#Required annotation kicked in.."+register);
}
In Models:
package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="register")
public class Register {
//private static final long serialVersionUID = 1L;
private String firstname;
private String lastname;
#Id
private String displayname;
private String date;
private String email;
private String password;
private String confirm_password;
private String gender;
private int phone_no;
private String address;
private int zipcode;
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 getDisplayname() {
return displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirm_password() {
return confirm_password;
}
public void setConfirm_password(String confirm_password) {
this.confirm_password = confirm_password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getPhone_no() {
return phone_no;
}
public void setPhone__no(int phone_no) {
this.phone_no = phone_no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
}
If bindFromRequest().get() returns null, then the Form didn't validate. To debug this, log Form.form(Register.class).bindFromRequest().errors(), to see the validation errors in the Form. Beyond that no one can tell you what's wrong without seeing the Register class, and the data you're trying to bind to it.
You shouldn't be blindly calling get() on the Form and trying to save it, as this obviously can fail. At least check that it hasErrors() before trying to save it. And if it does have validation errors, you should be passing that Form back to the view to show those errors to the user.
See Handling Binding Failure in the docs.

Getting null with getters and setters

When I place the getters and setters in a method, then call that method in the main method, I get a value of null despite having set the value to something else! Additionally, I'm not receiving any errors from the compiler, so I'm sure it's a logical error somewhere but I cannot figure it out.
This is from the class containing the methods in question:
public class URTest {
UserRegistration _user = new UserRegistration();
public static void main(String[] args) {
String fieldName;
UserRegistration _user = new UserRegistration();
URTest _run = new URTest();
Scanner input = new Scanner(System.in);
fieldName = input.nextLine();
_run.test(fieldName);
System.out.println(_user.getUsername());
}
public void test(String fieldName) {
UserRegistration _user = new UserRegistration();
Scanner input = new Scanner(System.in);
String result;
System.out.print("Enter " + fieldName + ": ");
result = input.nextLine();
while(true) {
if(result.equals("")) {
System.out.print("Please enter a value for the " + fieldName + ": ");
result = input.nextLine();
} else {
break;
}
if(fieldName.equals("username")) {
_user.setUsername(result);
}
}
}
}
Here is the class containing my getters and setters:
import java.io.Serializable;
public class UserRegistration implements Serializable {
private String username;
private int userId;
private String firstName;
private String lastName;
private String password;
private String email;
public UserRegistration() {
this.username = username;
this.userId = userId;
}
public UserRegistration(String uName, int id, String uPassword) {
this.username = uName;
this.userId = id;
this.password = uPassword;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
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 void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
String name = getFirstName() + getLastName();
String output = name + "has the user id " + getUserId() +
"username " + getUsername() + " and email " + getEmail();
return output;
}
}
You are calling
UserRegistration _user = new UserRegistration();
And in your class
public UserRegistration() {
this.username = username;
this.userId = userId;
}
When the above constructor gets called, there is no value to be set to the member variable and therefore you are getting null
In your calling method,
UserRegistration _user = new UserRegistration("name","id1");
OR
set default values in your constructor:
public UserRegistration() {
this.username = "name";
this.userId = "id1";
}

Categories