Input 3 Attributes Into HashMap Key - java

I am new to Java. I am now using HashMap for the purpose to store data from MySQL database and I will use the JSon POST request to get the input from user and search for the related data in the HashMap and retrieve from the HashMap. I need three inputs from the user but in the HashMap only able to input 1 key. So, I tried the way to input the key as an object but it is not working. Below is my code for storing data from MySQL database.
public class AppDataService {
HashMap<AppDataRequest, AppData> appdatas = new HashMap<AppDataRequest, AppData>();
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://****:3306/****_demo";
static final String USER = "****";
static final String PASS = "****";
public AppDataService(){
Connection conn = null;
Statement stat = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stat = conn.createStatement();
String sql = "SELECT * FROM testdata";
ResultSet resu = stat.executeQuery(sql);
while(resu.next()){
int id = resu.getInt("app_id");
String email = resu.getString("email");
String password = resu.getString("password");
String status = resu.getString("status");
String message = resu.getString("message");
String token = resu.getString("token");
appdatas.put(new AppDataRequest(id, email, password), new AppData(status, message, token));
}
resu.close();
stat.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(stat!=null){
stat.close();
}
}
catch (SQLException se2){
}
try{
if(conn!=null){
conn.close();
}
}
catch(SQLException se3){
se3.printStackTrace();
}
}
}
public List<AppData> getAllAppData(){
return new ArrayList<AppData>(appdatas.values());
}
public AppData getAppData(int id){
return appdatas.get(id);
}
public AppData getSAppData(int id, String email, String password){
return appdatas.get(new AppDataRequest (id, email, password));
}
}
My JSon POST code
#Path("/appdata")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
AppDataService ads = new AppDataService();
#POST
#Path("/appdatas")
public AppData getSAppData(AppDataRequest adr){
return ads.getSAppData(adr.getId(), adr.getEmail(),adr.getPassword());
}
AppData Class
public class AppData {
public String status;
public String message;
public String token;
public AppData(){
}
public AppData(String status, String message, String token) {
this.status = status;
this.message = message;
this.token = token;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
AppDataRequest Class
public class AppDataRequest {
public int id;
public String email;
public String password;
public AppDataRequest(){
}
public AppDataRequest(int id, String email, String password) {
this.id = id;
this.email = email;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}

You can overide hashCode and equals in your class :
#Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + this.id;
hash = 83 * hash + Objects.hashCode(this.email);
hash = 83 * hash + Objects.hashCode(this.password);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AppDataRequest other = (AppDataRequest) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.email, other.email)) {
return false;
}
if (!Objects.equals(this.password, other.password)) {
return false;
}
return true;
}
Why you don't make the id like a key if it is unique in your table, and your other information as value of map :
Map<Integer, AppData> appdatas;
appdatas.put(id, new AppData(status, message, token, email, password));

HashMap internally makes use of HashCode and Equals method to insert and retrieve the Object from the collection.
You need to override the equals() and Hashcode() method in Java to use a Custom Object as Key within a HashMap. Also it is preferred to have an Immutable Class as a Key which again you have to consider.
Have a look at below
What issues should be considered when overriding equals and hashCode in Java?
If not you can always use the Standard String/Wrapper Classes as Key as they by default provide the methods and design necessary to use.
As Further Reading look for how HashMap Works and you will understand why.
Hope this helps.

Related

Android Java rest call passes correct params in debug mode but not in signed apk

I have no idea what is the connection between those two variants in terms of sending POST request.
My User class:
public class User {
String name, pass, email;
int level, exp, gold;
Timestamp regDate, lastVisited;
boolean loginStatus;
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getLoginStatus() {
return loginStatus;
}
public void setLoginStatus(boolean loginStatus) {
this.loginStatus = loginStatus;
}
public Timestamp getLastVisited() {
return lastVisited;
}
public void setLastVisited(Timestamp lastVisited) {
this.lastVisited = lastVisited;
}
public Timestamp getRegDate() {
return regDate;
}
public void setRegDate(Timestamp regDate) {
this.regDate = regDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getGold() {
return gold;
}
public void setGold(int gold) {
this.gold = gold;
}
public User(String name, String pass) {
this.name = name;
this.pass = pass;
}
public User(String name, String pass, String email) {
this.name = name;
this.pass = pass;
this.email = email;
}
public User(String name, boolean loginStatus, int level, int exp, int gold, Timestamp regDate, Timestamp lastVisited) {
this.name = name;
this.loginStatus = loginStatus;
this.level = level;
this.exp = exp;
this.gold = gold;
this.regDate = regDate;
this.lastVisited = lastVisited;
}
}
I have such retrofit request:
#POST("/login")
Call<String> checkLogin(#Body User user);
And such retrofit call:
#Override
public void checkLogin(final OnFinishedLoginListener onFinishedListener, String login, String passWhenLogin, List<String> usersLoggedOnCredential) {
Call<String> result = Api.getClient().checkLogin(new User(login, passWhenLogin));
result.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
onFinishedListener.onFinishedLogin(response.body());
usersLoggedOnCredential.add(login);
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("checkLogin", t.toString());
onFinishedListener.onFailureLogin(t);
}
});
}
And server code:
#PostMapping("/login")
public String login(#RequestBody UserForCreateDto userForCreateDto) throws SQLException {
return usersDao.userExists(userForCreateDto.getName(), userForCreateDto.getPass(), conn);
}
and
public String userExists(String name, String pass, Connection connection) {
String passEncoded = "";
String result;
System.out.println("qqqqqqq " + name + " " + pass);
PasswordEncoder encoder = new BCryptPasswordEncoder();
PreparedStatement ps;
try {
ps = connection.prepareStatement("select * from users where username='" + name + "'");
ResultSet rs = ps.executeQuery();
if (rs.next())
passEncoded = rs.getString(3);
if (encoder.matches(pass, passEncoded))
result = "true";
else
result = "false";
} catch (Exception e) {
System.out.println("aaaaaaaaaab");
e.printStackTrace();
return e.getMessage();
}
return result;
}
and
#Data
public class UserForCreateDto {
private String name;
private String pass;
private String email;
private int level;
private int exp;
private int gold;
}
In debug mode I get respectively true or false depending on what I input as a response, but when I sign my app to be published to Google Play Store the pass from Android client seems not to reach the server and I get error then:
pass == null (name is correct).
Why is that so?
Probably your request and response models are obfuscated from Proguard. To prevent this, add your request-response classes in Proguard with the "Keep" rule.
https://developer.android.com/studio/build/shrink-code

JsonMappingException: Cannot find a deserialzer for non-concrete Map type

I am new to java!
I am trying to read objects of type Admin, containing 3 strings, from a JSON file and store them in a List. I am getting "com.fasterxml.jackson.databind.JsonMappingException: Cannot find a deserializer for non-concrete Map type" but it seems I cannot find a solution.
What is a solution for my code so that I can load the list from the file?
Code snippet :
private static List<Admin> admins=new ArrayList<Admin>();
public static void loadAdminsFromFile() { /*LOAD THE LIST WITH JSON(ADMIN) OBJECTS*/
try {
ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = new FileInputStream(new File("*path to file*"));
TypeReference<List<Admin>> typeReference = new TypeReference<List<Admin>>() {};
admins = mapper.readValue(inputStream, typeReference);
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Admin class :
package model;
import javafx.scene.control.TextField;
public class Admin {
private String username;
private String ID;
private String password;
public Admin() {}
public Admin(String username, String ID, String password) {
this.username=username;
this.ID=ID;
this.password=password;
}
public String getUsername() {
return this.username;
}
public void setUsername(TextField username) {
this.username = username.getText();
}
public String getID() {
return this.ID;
}
public void setID(TextField ID) {
this.ID = ID.getText();
}
public String getPassword() {
return this.password;
}
public void setPassword(TextField password) {
this.password = password.getText();
}
#Override
public boolean equals(Object o) {
if(this==o) return true;
if(o==null || getClass()!=o.getClass()) return false;
Admin admin=(Admin) o;
if(!username.equals(admin.username)) return false;
if(!ID.equals(admin.ID)) return false;
if(!password.equals(admin.password)) return false;
return true;
}
#Override
public int hashCode (){
int result=username.hashCode();
result=31*result+ID.hashCode();
result=31*result+password.hashCode();
return result;
}
#Override
public String toString() {
return "Admin -> " + username + ID + password;
}
}
Try to override the setters method to accept String values:
....
public void setUsername(String username) {
this.username = username;
}
....

How should i specify the managed bean method to save the data on the directed FOREIGN KEY?

I am currently new to do website project with JSF specification. as you all know, JSF should include xhtml for the server page and managed bean to determine the class method, and I have made connection between my project and MySQL localhost.
The problem is, i created 1 main table for User categories which include common attributes such as name, gender etc. and i made other two table that specify the user for its role. The thing is that the main User table that contain user_ID as PRIMARY KEY to become the reference for the other 2 tables FOREIGN KEY ex: student, staff.
If i created a registration form on the server page, how should i determine the method to separate the data into the database from coming to the wrong table?
LoginBean.Java
private String fullName_;
private String gender_;
private String phoneNumber_;
private String IC_;
private String email_;
private String Address_;
private String password_;
public String getFullName_() {
return fullName_;
}
public void setFullName_(String fullName_) {
this.fullName_ = fullName_;
}
public String getGender_() {
return gender_;
}
public void setGender_(String gender_) {
this.gender_ = gender_;
}
public String getPhoneNumber_() {
return phoneNumber_;
}
public void setPhoneNumber_(String phoneNumber_) {
this.phoneNumber_ = phoneNumber_;
}
public String getIC_() {
return IC_;
}
public void setIC_(String IC_) {
this.IC_ = IC_;
}
public String getEmail_() {
return email_;
}
public void setEmail_(String email_) {
this.email_ = email_;
}
public String getAddress_() {
return Address_;
}
public void setAddress_(String Address_) {
this.Address_ = Address_;
}
public String getPassword_() {
return password_;
}
public void setPassword_(String password_) {
this.password_ = password_;
}
public String saveUser(LoginBean loginBean){
UserDao dao = new UserDao(); //METODE SIMPAN KE DATABASE!!!
User user = new User();
user.setFullName(loginBean.getFullName_());
user.setGender(loginBean.getGender_());
user.setPhoneNumber(Integer.parseInt(loginBean.getPhoneNumber_()));
user.setIc(loginBean.getIC_());
user.setEmail(loginBean.getEmail_());
user.setPassword(loginBean.getPassword_());
dao.saveStudent(user);//untuk menyimpan di database
Map<String,Object> sessionMapObj = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
sessionMapObj.put("msg", "Data "+user.getIc() +"successfull!");
return"/sukses.xhtml?faces-redirect=true";
}
User.java
private Integer userId;
private String fullName;
private String gender;
private Integer phoneNumber;
private String ic;
private String email;
private String address;
private String password;
private Set students = new HashSet(0);
private Set staffs = new HashSet(0);
public User() {
}
public User(String fullName, String gender, Integer phoneNumber, String ic, String email, String address, String password, Set students, Set staffs) {
this.fullName = fullName;
this.gender = gender;
this.phoneNumber = phoneNumber;
this.ic = ic;
this.email = email;
this.address = address;
this.password = password;
this.students = students;
this.staffs = staffs;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(Integer phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getIc() {
return this.ic;
}
public void setIc(String ic) {
this.ic = ic;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Set getStudents() {
return this.students;
}
public void setStudents(Set students) {
this.students = students;
}
public Set getStaffs() {
return this.staffs;
}
public void setStaffs(Set staffs) {
this.staffs = staffs;
}
I suppose you want to have a look at jdbc. Java Database Connectivity allows you to create sql queries in java. However, alot of times a Java Persistence API is used (JPA) in Java EE applications. This is a specification on how you can store and retrieve Java-Objects from a database. A very common implementation of that is the hibernate framework.
If you want to enable Hibernate capabilies for your jsf project, follow this guide:
https://howtodoinjava.com/hibernate/hibernate-3-introduction-and-writing-hello-world-application/. If your project isn't build with Maven, just ignore that part of the tutorial.
With hibernate for eg. you can create a User Entity. You can follow this easy tutorial on how to create entities: https://www.baeldung.com/jpa-entities
Now let's suppose you don't want to use any of that and just want a default solution with jdbc:
import java.sql.*;
public class Userdao
{
public static void saveUser(User user)
{
try
{
value1 = user.getId();
value2 = user.getFirstName();
value3 = user.getLastName();
String myUrl = "jdbc:somesql:localhost/test";
//now we load the driver
Class.forName("oracle.jdbc.driver.OracleDriver"); //download the correct driver of your database and add as library to your project
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String addUserQuery = "INSERT INTO table_name (column1, column2, column3, ...) VALUES (" + value1 + ", " + value2 + ", " + value3, + "...);" //column1 could be Userid-Primarykey, 2 Name ...
Statement addSt = conn.createStatement();
addSt.executeQuery(addUserQuery)
// create the java statement for retrieving
String query = "SELECT + from table_name";
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
int id = rs.getInt("id");
String firstName = rs.getString("first_name"); //first_name being the column name
String lastName = rs.getString("last_name");
// print the Name
System.out.format("%s, %s\n", id, firstName, lastName);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Foreign Key references are handled in the database, so for. eg. if you want to get the child objects you simply need a query that joins the tables, and then extract the corresponding values from the result set.

How do I return an object when I only have access to one field of it?

Sorry if this doesn't make sense, I can't think of a better way to phrase it. Hopefully my code illustrates my problem better.
So in this method I want to return a Myuser object. A Myuser object has about 8 string fields, one of which is userId.
As you can see, when this method is called, a string is passed in. If this string has the same value as the userId field in the Myuser object, then I want it to return the full Myuser object. Otherwise it returns null.
public Myuser getRecord(String userId) {
Connection cnnct = null;
PreparedStatement pStmnt = null;
Myuser myusr = null;
boolean result = false;
try {
cnnct = getConnection();
String preQueryStatement = "SELECT * FROM MYUSER WHERE USERID = ?";
pStmnt = cnnct.prepareStatement(preQueryStatement);
pStmnt.setString(1, userId);
ResultSet rslt = pStmnt.executeQuery();
result = rslt.next();
if (result) {
//return myusr in its entirety
}
} catch (SQLException ex) {
while (ex != null) {
ex.printStackTrace();
ex = ex.getNextException();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (pStmnt != null) {
try {
pStmnt.close();
} catch (SQLException e) {
}
}
if (cnnct != null) {
try {
cnnct.close();
} catch (SQLException sqlEx) {
}
}
}
return myusr;
}
Edit: I thought for the heck of it I would post the Myuser class as well.
public class Myuser {
private String userid;
private String name;
private String password;
private String email;
private String phone;
private String address;
private String secQn;
private String secAns;
public Myuser(String userid, String name, String password, String email, String phone, String address, String secQn, String secAns) {
this.userid = userid;
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
this.address = address;
this.secQn = secQn;
this.secAns = secAns;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecQn() {
return secQn;
}
public void setSecQn(String secQn) {
this.secQn = secQn;
}
public String getSecAns() {
return secAns;
}
public void setSecAns(String secAns) {
this.secAns = secAns;
}
}
You can easily use result.getXXX(field_name):
if (rslt.next()) {
myusr = new Myuser(result.getString("userid"), result.getString("name"),
result.getString("password"), result.getString("phone"),
...);
}
Note don't need to use result = rslt.next(); before if(result), you have to use directly
if (rslt.next()) {
...
}

two methods of a class constructor

I have a main class called User implemented as follows
package edu.uoc.dpoo;
import java.util.ArrayList;
import java.util.List;
public class User {
private String username;
private String password;
private String fullName;
private Platform platform;
private List<Message> inBox;
private List<Message> outBox;
public User(String username, String password, String fullName) {
this.username = username;
this.password = password;
this.fullName = fullName;
inBox = new ArrayList<Message>();
outBox = new ArrayList<Message>();
}
public User() {
username="";
password="";
fullName="";
}
public String getUserName() {
return username;
}
public String getPassword() {
return password;
}
public String getFullName() {
return fullName;
}
public void setUserName(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setFullName(String fullname) {
this.fullName = fullname;
}
public boolean checkPassword(String password){
if (password.equals(this.password)){
return true;
}else
{
return false;
}
}
public List<Message> getMessages() {
return null;
}
public Organizer asOrganizer(){
Organizer ObjetoO = new Organizer(username,password,fullName);
return ObjetoO;
}
public Participant asParticipant(){
Participant ObjetoP = new Participant(username,password,fullName);
return ObjetoP;
}
public Message sendMessage(String to,String Subject,String message){
return null;
}
public String toString () {
return null;
}
#Override
public boolean equals (Object o) {
boolean prueba = false;
if ((o != null) && (o instanceof User)) {
User p = (User) o;
if (this.username == null && this.password == null && this.fullName == null) {
prueba = (p.username == null);
prueba = (p.password == null);
prueba = (p.fullName == null);
}
else {
prueba = this.username.equals(p.username);
prueba = this.password.equals(p.password);
prueba = this.fullName.equals(p.fullName);
}
}
return prueba;
}
public List<Competition> myCompetitions(){
return null;
}
User(User u1) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
And two classes that inherit from User that are Organizer and Participant implemented as follows
Organizer
package edu.uoc.dpoo;
import java.util.ArrayList;
import java.util.List;
public class Organizer extends User {
private List<Competition> competitions;
public Organizer(String username, String password, String fullName) {
super(username, password, fullName);
competitions = new ArrayList<Competition>();
}
public boolean removeSubmission(Submission submission){
return true;
}
public boolean sendMessage(Competition competition, String subject, String message){
return true;
}
public Competition newCompetition(String tittle,float target){
return null;
}
public void closeCompetition(Competition competition){
}
}
Participant
package edu.uoc.dpoo;
import java.util.ArrayList;
import java.util.List;
public class Participant extends User {
private List<Competition> competitions;
private List<Submission> submission;
public Participant(String username, String password, String fullName) {
super(username, password, fullName);
competitions = new ArrayList<Competition>();
submission = new ArrayList<Submission>();
}
public Submission submitPrediction(Competition competition, float prediction){
return null;
}
public List<Submission> getSubmissions(){
return null;
}
void asParticipant(Submission aThis) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
I'm asked to implement the asOrganizer and asParticipant methods of the User class.
These methods must create an object of the specific class, and initialize the parent class with the data of the User object. To perform this task, you are prompted to implement the copy constructor of the User class.
I create the objects in the two methods that ask me but I should not do something well in the constructor because junit fails me
I add the junit that fails me
#Test
public void userCopyConstructor() {
Platform platform = new Platform();
User u1=platform.registerUser(username1, password1, fullName1);
// User is not NULL
assertNotNull(u1);
// Get a participant object from user object
User u2 = new User(u1);
assertNotNull(u2);
assertEquals(u1, u2);
}
My problem comes at this point
// Get a participant object from user object
User u2 = new User(u1);
assertNotNull(u2);
assertEquals(u1, u2);
public User(User Prueba){
this(Prueba.getUserName(),Prueba.getPassword(),Prueba.getFullName());
}
Thanks to the answers they gave me.
Without you it would be more difficult

Categories

Resources