outer method execute before override inside method in java - java

Currently trying to set User u object by using JSON data from response.body() (retrofit). However, I am not able to do that. loginOperation(email,psswd) returns a boolean value which states whether a successful logged-in or not. When I try to execute this outer method, it returns check before the overridden method onResponse().
Is there any advice? Thanks in advance!
AuthenticationCheck class ----------
public class AuthenticationCheck {
RetrofitConnection rc = new RetrofitConnection();
Retrofit retrofit = rc.getRetrofit();
private static boolean check = false;
private static User u = new User();
synchronized public boolean loginOperation(String email, String password){
LoginService loginService = retrofit.create(LoginService.class);
Call<ResponseBody> call = loginService.loginWithCredentials(new
LoginCredentials(email, password));
call.enqueue(new Callback<ResponseBody>() {
#Override
synchronized public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
check=true;
final JSONObject obj;
try {
obj = new JSONObject(response.body().string());
final JSONObject userObj = obj.getJSONObject("user");
u.setSurname(userObj.getString("surname"));
u.setPhone(userObj.getString("phonenumber"));
u.setUser_id(userObj.getInt("user_id"));
u.setName(userObj.getString("name"));
u.setEmail(userObj.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
synchronized public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("FAIL","onFailure ");
}
});
return check;
}
public User getAuthenticatedUser(){
return u;
}
LoginCredentials
public class LoginCredentials {
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
public LoginCredentials(String email, String password) {
this.email = email;
this.password = password;
}
}
LoginInterface
public interface LoginService {
#POST("mlogin")
Call<ResponseBody> loginWithCredentials(#Body LoginCredentials data);
}
User Class
public class User {
#SerializedName("user_id")
#Expose
private int user_id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("phonenumber")
#Expose
private String phone;
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
public User(int user_id, String name, String surname, String phone,String email,String pass){
this.user_id = user_id;
this.name = name;
this.surname = surname;
this.phone = phone;
this.email = email;
this.password = pass;
}
public User(){
this.user_id = 0;
this.name = null;
this.surname = null;
this.phone = null;
this.email = null;
this.password = null;
}
public String getEmail() { return email; }
public String getName() { return name; }
public String getPasswd() { return password; }
public String getPhone() { return phone; }
public String getSurname() { return surname; }
public int getUser_id() { return user_id; }
public void setEmail(String email) {
this.email = email;
}
public void setName(String name) {
this.name = name;
}
public void setPasswd(String password) {
this.password = password;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setUser_id(int user_id) { this.user_id = user_id; }
#Override
public String toString() {
return "Post{" +
"user_id='" + user_id + '\'' +
", name='" + name + '\'' +
", surname=" + surname +
", phone=" + phone +
", email='" + email + '\'' +
", pass=" + password +
'}';
}
}

call.enqueue is an asynchronous operation, so rest of the code in loginOperation() after this call will continue to execute. If you want to block till response is received you need use synchronous call.execute

Use Rest Template instead of your call, it will be a blocked http call, see examples here

Related

Error while deleting data from dynamoDB table

I am trying to delete the data from my DynamoDB table based on the Id(HashKey).
Association.java
#DynamoDBTable(tableName = "Association")
public class Association {
private String id;
private String name;
private String adminName;
private String email;
private String url;
private String contactNumber;
private String password;
public Association() { }
public Association(String name, String adminName, String email, String url,
String contactNumber, String password) {
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
public Association(String id, String name, String adminName, String email, String url,
String contactNumber, String password) {
this.id = id;
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
#DynamoDBHashKey(attributeName = "Id")
#DynamoDBAutoGeneratedKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBAttribute(attributeName="Name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#DynamoDBAttribute(attributeName="AdminName")
public String getAdminName() { return adminName; }
public void setAdminName(String adminName) { this.adminName = adminName; }
#DynamoDBAttribute(attributeName="Email")
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
#DynamoDBAttribute(attributeName="Url")
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
#DynamoDBAttribute(attributeName="ContactNumber")
public String getContactNumber() { return contactNumber; }
public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; }
#DynamoDBAttribute(attributeName="Password")
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
AssociationRepository.java:-
private AmazonDynamoDBClient getDynamoDBClient(){
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
client.setRegion(Region.getRegion(REGION));
client.setEndpoint(EndPoint);
return client;
}
private void deleteAssociation(String id) {
try {
DynamoDBConfig dynamoDBConfig = new DynamoDBConfig();
DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBConfig.getDBClient());
Association associationToDelete = new Association();
associationToDelete.setId(id);
// Delete the item.
mapper.delete(associationToDelete);
} catch (Exception exception) {
System.out.println(exception);
throw exception;
}
}
I am getting the below error:-
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: No method annotated with interface com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey for class class Association
I have searched the AWS docs for this but could not find any solution that fixes this.Does anyone of you ever faced this issue?
The issue is the same I mentioned on your other post, in DynamoDB you can’t work an item using attributes which are not the primary key (Partition Key only in your scenario).
Moreover, to delete an item it is mandatory to do it by its primary key, so in your case the attribute Name.
Try to do same operation by setting the name, the error is not very descriptive so maybe there is another underlying issue. However, if you don’t meet above requirement it will never work.

Error while retrieving data by Id(hashKey) of a dynamoDb table

I am trying to fetch the data from my DynamoDB table based on the Id(HashKey).
Association.java
#DynamoDBTable(tableName = "Association")
public class Association {
private String id;
private String name;
private String adminName;
private String email;
private String url;
private String contactNumber;
private String password;
public Association() { }
public Association(String name, String adminName, String email, String url,
String contactNumber, String password) {
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
public Association(String id, String name, String adminName, String email, String url,
String contactNumber, String password) {
this.id = id;
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
#DynamoDBHashKey(attributeName = "Id")
#DynamoDBAutoGeneratedKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBAttribute(attributeName="Name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#DynamoDBAttribute(attributeName="AdminName")
public String getAdminName() { return adminName; }
public void setAdminName(String adminName) { this.adminName = adminName; }
#DynamoDBAttribute(attributeName="Email")
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
#DynamoDBAttribute(attributeName="Url")
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
#DynamoDBAttribute(attributeName="ContactNumber")
public String getContactNumber() { return contactNumber; }
public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; }
#DynamoDBAttribute(attributeName="Password")
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
AssociationRepository.java:-
private AmazonDynamoDBClient getDynamoDBClient(){
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
client.setRegion(Region.getRegion(REGION));
client.setEndpoint(EndPoint);
return client;
}
public Association fetchById(String id) {
DynamoDBConfig dynamoDBConfig = new DynamoDBConfig();
DynamoDBMapper mapper = new DynamoDBMapper(getDBClient());
Association association = new Association();
association.setId(id);
Association scanResult = null;
try {
scanResult = mapper.load(association);
}
catch (Exception exception){
throw exception;
}
return scanResult;
}
Invoking fetchById("123"). Where "123" is an existing Id of the table It throws the below error to me:-
{
"errorMessage": "The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: IT6U9BJ0RAJUDPMLGGR67C542VVV4KQNSO5AEMVJF66Q9ASUAAJG)",
"errorType": "com.amazonaws.AmazonServiceException",
"stackTrace": [
"com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1305)",
"com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:852)",
DYNAMODB TABLE DETAILS:-
I have searched the AWS docs for this but could not find any solution that fixes this.Does anyone of you ever faced this issue?
If you realize, you defined Name as your partition key. However on code, you are trying to load an item by the attribute Id.
That's not possible as DynamoDB only allows you to load an item by its primary key, which in your case is only the partition key (the attribute Name).
So you have to modify either the table to set Id as partition key, or create a secondary global index to accomplish that:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html

How to get a specific data from a document in firestore and pass it to a local variable in android

This is the screenshot of my firestore structure
I want to get the data from my model stored in my firestore documents to my local variable
final EmployeeModel model = new EmployeeModel();
firebaseFirestore.collection("USERS").document(firebaseUser.getUid()).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
String username = documentSnapshot.getString(model.getUsername());
String email = documentSnapshot.getString(model.getEmail());
String location = documentSnapshot.getString(model.getLocation());
String phonenumber = documentSnapshot.getString(model.getPhonenumber());
String genderS = documentSnapshot.getString(model.getGender());
// Map<String, Object> userInfo = documentSnapshot.getData();
fragmentname.setText(username);
welcomeUser.setText(email);
employeeID.setText("1610225");
city.setText(location);
number.setText(phonenumber);
gender.setText(genderS);
} else {
Toast.makeText(getActivity(), "Document does not exist", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Error ", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
please correct my syntax I'm really new at this
This is EmployeeModel.class
And please show how to pass the .getUsername to a variable String username
public class EmployeeModel {
public static final String MFIELD_USERNAME = "username";
public static final String MFIELD_EMAIL = "email";
public static final String MFIELD_PASSWORD = "password";
public static final String MFIELD_LOCATION = "location";
public static final String MFIELD_PHONENUMBER = "phonenumber";
public static final String MFIELD_GENDER = "gender";
public static final String MFIELD_TYPE = "type";
private String username;
private String email;
private String password;
private String location;
private String phonenumber;
private String gender;
private String type;
private #ServerTimestamp Date timestamp;
public EmployeeModel() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public EmployeeModel(String username, String email, String password, String location, String phonenumber, String gender, String type, Date timestamp) {
this.username = username;
this.email = email;
this.password = password;
this.location = location;
this.phonenumber = phonenumber;
this.gender = gender;
this.type = type;
this.timestamp = timestamp;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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 getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}}
This is my EmployeeModel.class
and my Firestore screenshot, please help! Thank you
what you are missing is to get the model from the document
if(documentSnapshot.exists()){
EmployeeModel model = documentSnapshot.toObject(EmployeeModel.class);
//
just add the line after if statement to your existing code the rest seems fine.

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.ipl.model.User

I have one REST Call as
List<User> userList = (List<User>) iplUtil.getResult(user, mongoGetURL);
System.out.println("userList === "+userList);
output as
userList = [{_id={$oid=571903dae4b085317593a0d3}, nickName=aa, email=aa, password=aa, userId=1}]
No complile time error..
but this line failing in runtime
User u =userList.get(0);
getting exception at this line as
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.ipl.model.User
and model as
package com.ipl.model;
import java.io.Serializable;
import java.util.Map;
#SuppressWarnings("serial")
public class User implements Serializable {
private Map<String, String> _id;
private String nickName;
private String email;
private String password;
private int userId;
public User(String nickName,String password) {
this.nickName=nickName;
this.password=password;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User() {
// TODO Auto-generated constructor stub
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Map<String, String> get_id() {
return _id;
}
public void set_id(Map<String, String> _id) {
this._id = _id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User [_id=" + _id + ", nickName=" + nickName + ", email=" + email + ", password=" + password
+ ", userId=" + userId + "]";
}
}
Im not getting any complie time error..why its failing in runtime

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