How do I get variables of an object from a vector? - java

My code
package crypto;
import java.util.Vector;
public class Wallet {
public void main() {}
public String username;
public String password;
public int coins;
Vector<Object> wallets = new Vector<Object>();
public Wallet(String username, String password) {
this.username = username;
this.password = password;
this.coins = 0;
}
public void createWallet(String username, String password) {
wallets.add(new Wallet(username, password));
}
public Object findWallet(String username, String password) {
Object wallet;
for (int i = 0; i < wallets.size(); i++) {
wallet = wallets.get(i);
if (wallet.username == username && wallet.password == password) {
return wallet;
}
}
return 0;
}
public void addCoins(String username, String password, int coins) {
Object wallet = findWallet(username, password);
wallet.coins += coins;
}
}
Any help would be appreciated.
This is a test program for a cryptocurrency (just a personal project)
FYI this is just filler text because apparently you have to do that.

Your question is not very clear but let me guess what you need.
You can use generics:
Vector<Wallet> wallets = new Vector<Wallet>();
Anyway why didn't you consider using a simple ArrayList?
List<Wallet> wallets = new ArrayList<>();
Now you have an access to your Wallet methods when looking it up within a vector.
And change Object type to Wallet everywhere.
I would recommend you to rewrite search logic to something like that:
public Wallet findWallet(String userName, String password) {
return wallets.stream()
.filter(e -> e.getUserName().equals(userName))
.filter(e -> e.getPassword().equals(password))
.findAny()
.orElse(null);
}
You can google what getters and setters are.
I would also like to mention that you might want to use separate classes for your Wallet itself and a service that tends to perform operations over it.
I assume you can find more useful info here

I think you need method get(int index). It returns the element at the specified position in your Vector.

Related

How to read data from nested array in Firestore

I have the below structure in my Firestore and I want to read data and store it in ArrayList like I have "amountArrayList" which will read data from the "transactions" field in Firestore, I want to read all the "amount" fields from "transactions" field and make array list of it so that I can show it in list manner.
My code
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("transactions")) {
System.out.println(entry.getValue().toString());
}
}
Output
[{transactionType=Credit, amount=3000, dateToStr=17/12/2021, timeToStr=08:06:10, description=}, {transactionType=Credit, amount=2000, dateToStr=17/12/2021, timeToStr=08:06:50, description=}]
Since transactions is an array field, the value you get from entry.getValue() is a List of objects. Since each of these objects in the JSON has properties, they each will be a Map<String, Object> again in the Java code.
A simple way to print the amounts would be something like:
List transactions = document.get("transactions");
for (Object transaction: transactions) {
Map values = (Map)transaction;
System.out.println(values.get("amount")
}
While Frank van Puffelen's answer will work perfectly fine, there is a solution in which you can directly map the "transactions" array into a list of custom objects. Assuming that you have a class declaration that looks like this:
class User {
public String balance, email, firstname, lastname, password, username;
public List<Transaction> transactions;
public User(String balance, String email, String firstname, String lastname, String password, String username, List<Transaction> transactions) {
this.balance = balance;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.username = username;
this.transactions = transactions;
}
}
And one that looks like this:
class Transaction {
public String amount, dateToStr, description, timeToStr, transactionType;
public Transaction(String amount, String dateToStr, String description, String timeToStr, String transactionType) {
this.amount = amount;
this.dateToStr = dateToStr;
this.description = description;
this.timeToStr = timeToStr;
this.transactionType = transactionType;
}
}
To get the list, it will be as simple as:
docRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
List<Transaction> transactions = document.toObject(User.class).transactions;
List<String> amountArrayList = new ArrayList<>();
for(Transaction transaction : transactions) {
String amount = transaction.amount;
amountArrayList.add(amount);
}
// Do what you need to do with your amountArrayList
}
}
});
You can read more info in the following article:
How to map an array of objects from Cloud Firestore to a List of objects?.
I found the best way to map the data from/to hashmap to send/retrieve it from FirebaseFirestore
First, you need to create an extension class to handle the mapping
fun <T> T.serializeToMap(): Map<String, Any> {
return convert()
}
inline fun <reified T> Map<String, Any>.toDataClass(): T = convert()
inline fun <A, reified B> A.convert(): B =
Gson().fromJson(Gson().toJson(this), object : TypeToken<B>() {}.type)
Don't forget to add Gson
implementation 'com.google.code.gson:gson:2.9.0'
Then, you can use these functions for mapping the result from firebase
if (task.isSuccessful) {
val list: MutableList<YourObject> = ArrayList()
for (document in task.result) {
list.add(document.data.toDataClass())
}
// do whatever you want with the list :)
} else {
// handle the error
}

Cannot add element to Map - Unsupported Operation Exception

I am having trouble inserting element to this mutable Map and i cannot figure out why?
I can see it returns Map so it should not an issue to put element in.
Can you help me with that?
myClient.authentications.put("basicAuthentication", httpBasicAuth)
Authentications look like this:
public Map<String, Authentication> getAuthentications() {
return authentications;
}
private Map<String, Authentication> authentications;
Is there something that i am missing here?
Edit 1:
Adding some more code for clearance
HttpBasicAuth is just a basic class that implements Authentication
public class HttpBasicAuth implements Authentication {
private String username;
private String 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;
}
#Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
if (username == null && password == null) {
return;
}
headerParams.put("Authorization", Credentials.basic(
username == null ? "" : username,
password == null ? "" : password));
}
val httpBasicAuth = HttpBasicAuth()
httpBasicAuth.username = "user"
httpBasicAuth.password = "pass"
myClient.authentications.put("basicAuthentication", httpBasicAuth)
Currently, by default this field has null value so you CAN NOT call any method on it. So when you call:
myClient.authentications.put("basicAuthentication", httpBasicAuth)
you are trying call method put() on null.
To solve it, you can change your initialization from:
private Map<String, Authentication> authentications;
To (in Java):
private Map<String, String> authentications = new HashMap<>();
or in to (in Kotlin):
private val authentications: Map<String, Authentication> = mapOf();
After those changes this field will be initialized with empty array instead of null. Remember that this change it's very important when you have some logic based on it (e.g. you are checking authentications == null).

Convert String to Enum to enable a file to be read

Im writing code that needs to take a file input and then reconstruct the values into an ArrayList.
This is the code ive done so far to convert a file to an object.
public static ArrayList<User> fileToObject() {
ArrayList<User> FileToObject = new ArrayList<>();
Scanner in = null;
boolean err0 = false;
try {
in = new Scanner(Paths.get("User_info.txt"));
} catch (IOException ex) {
err0 = true;
}
if (!err0) // if couldn't open file then skip
{
while (in.hasNext()) {
String theUser = in.nextLine();
String[] Line = theUser.split(",");
User user = null;
try {
if ( Line.length == 10) {
// reconstruct Address
Address a1 = new Address( Line[2], Line[3], Line[4], Line[5], Line[6],
Integer.parseInt( Line[7]));
// reconstruct Customer
user = new Customer( Line[0], Line[1], Line[2], Line[3], Line[4], Line[5], Line[6], Line[7],a1, Line[14]);
FileToObject.add(user);
} else {
return null;
}
} catch (NoSuchElementException ex) {
System.out.println("File improperly formed. Terminating.");
}
}
in.close();
}
// write object back to file.
File f1 = new File(Paths.get("User_info.txt").toUri());
Formatter out = null;
boolean err = false;
try {
out = new Formatter(f1);
} catch (FileNotFoundException ex) {
err = true;
}
if (!err) {
//System.out.println(e3.size());
for (User i : FileToObject) {
out.format("%s%n", i.toString()); // output the card object to cvs format
}
out.close();
}
}
}
My issue here is that element Line[5] of the array User( user = new Customer(Line[0], Line[1], Line[2], Line[3], Line[4], Line[5)) is of Type enum(as seen in the first constructor of the below customer class) so i get an error "Incompatible Type, String cannot be converted to UserType(UserType being the Enum).
import java.util.ArrayList;
public class Customer extends Billing {
Address customerAddress;
public Customer(String id, String firstName, String lastName, String userName, String password, UserType userType, PermissionType permission, Boolean Status, Address billingAddress, String email, Address customerAddress) {
super(id, firstName, lastName, userName, password, userType, permission, Status, billingAddress, email);
this.customerAddress = customerAddress;
permission = PermissionType.Booking;
userType = UserType.VIP;
setId(id);
setPermission(permission);
setCustomerAddress(billingAddress);
}
public Customer(String id, String firstName, String lastName, String userName, String password, UserType userType, PermissionType permission, Boolean Status, Address billingAddress, String email) {
super(id, firstName, lastName, userName, password, userType, permission, Status, billingAddress, email);
}
public Address getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(Address customerAddress) {
this.customerAddress = customerAddress;
}
I spoke to my Tutor and he told me i need to convert the String to an Enum. Im unsure of what he meant by this as he wouldnt explain any Further. Is he talking about the String Array or do i need to convert the String within the file im reading to an enum? Im a bit lost so any help is greatly appreciated
If UserType is an enum, you can convert it with the static UserType.valueOf() method, i.e.:
UserType userType = UserType.valueOf(Line[5]);
Now you can use userType in place of Line[5] in the following code.
Note that Line[5] must exactly match the spelling of any of the enum types, or an IllegalArgumentException will be thrown.
If UserType.valueOf could not provide what you need, add a static method that returns specific UserType instance. For example:-
public enum UserType{
CUSTOMER("customer");
private String name;
UserType(String name){
this.name = name;
}
//A Map that holds user type name as key.
private static Map<String,UserType> userTypeMap = new HashMap<>();
//Populate userTypeMap with UserType instance
static{
for(UserType type : values()){
userTypeMap.put(type.name, type);
}
}
public static UserType of(String name){
return userTypeMap.get(name);
}
}
Callers could get UserType instance as below:-
UserType type = UserType.of("customer");
your solution is so long. there is an elegant way of doing this
Properties properties = new Properties();
properties.load(new FileInputStream(new File("FileLocation")));
properties.values();
File can contain, list of values, key value pairs. At line no 2 file is loaded in Properties object. Now u can process it according to your need.

Jdbc returns empty list but SQL query succesfully gets data [Spring]

I am trying to execute this query:
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql,new UserInfoMapper(),id);
return list.get(0);
}
but jdbc return empty list and I get exception at return line.
But if try to execute directly though the console it returns:
Query, Answer
Query was executed with id 1 and retured correct anwser;
But in method its returned this
I couldn't find any same questions so that may be point at my inattention to something. But I can't see any problem that may cause this. Thanks in advance;
Updated 1
Changing code to
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql, new Object[] {id},new UserInfoMapper());
return list.get(0);
}
resulted in same: result
Updated 2
#Override
public UserInfo mapRow(ResultSet resultSet, int i) throws SQLException {
UserInfo info = new UserInfo();
info.setId(resultSet.getLong("id"));
info.setFirstname(resultSet.getString("firstname"));
info.setMiddlename(resultSet.getString("middlename"));
info.setLastname(resultSet.getString("lastname"));
info.setUsername(resultSet.getString("username"));
info.setPassword(resultSet.getString("password"));
info.setEmail(resultSet.getString("email"));
info.setMobilephone(resultSet.getString("mobilephone"));
info.setPosition(resultSet.getString("position"));
return info;
}
public class UserInfo {
private Long id;
private String firstname;
private String middlename;
private String lastname;
private String username;
private String password;
private String email;
private String mobilephone;
private String position;
public UserInfo() {
}
}
Getter and setters for each field is there but I think there is no need to show them up.
Check user credentials that you are using to connect database from your application and the user credentials in console. And also check owner schema , table owner schema in your application.

how to convert url to java object [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
url:
http://www.xxx.com/getUser?userid=1&username=john&usersex=1
Java Class:
Class User{
private long userId;
private String userName;
private int userSex;
// get and set methods
...
//constructos
User(long userId, String userName, int userSex){
this.userId = userId;
this.userName = userName;
this.userSex = userSex;
}
}
how to convert this url to User object?for this url,i want to get User user = new User(1,"john",1).and does have any java framework?
NO. just use substring for that,and set in your object
I think there is no java framework for this. Since solution is quite simple, you can implement it yourself.
get attributes passed into URL via Servlet's request parameters.
set attributes to User either dynamically using Java Reflection API, or manually by implementing lots of ifelse statements
Have a look at Apache Commons BeanUtils.
Java library to map request parameters onto an object
http://commons.apache.org/beanutils/
You can use any MVC framework like Struts where each HTML form will
have a java backing bean.
If you feel MVC is heavy, You can write your own logic by using
Java Reflections API.
Try using Apache HttpComponents. I can help you read and parse a URL into individual components like
Called Page
List of Arguments with values as a Named value Pair
Link :
Apache HttpComponents
You can use the different examples given and tweak for your purpose.
How about using RestEasy?
I've not used it before, but based on some examples seems to be really simple. See the possible implementation:
#GET
#Path("getUser") //example: "/getUser?userid=1&username=john&usersex=1"
#Produces("application/json")
public User getUser(#QueryParam("userid") final long userId, #QueryParam("username") final String userName, #QueryParam("usersex") final int userSex) {
User user = new User(userId, userName, userSex);
// do what's required
return user;
}
the question is also what output format you expect to be returned here. I provided sample for JSON reply.
It's quite simple, no framework should be required. See below:
public class TestClass {
public static void main (String[] args) throws Exception {
URL url = new URL("http://www.xxx.com/getUser?userid=1&username=john%20doe&usersex=1");
String q = url.getQuery();
User user = new User();
for (String token : q.split("&")) {
if (token.startsWith("userid")) {
int index = token.indexOf('=');
if (index >= 0 && index <token.length()-1) {
user.setUserId(Long.parseLong(token.substring(index+1)));
}
}
if (token.startsWith("username")) {
int index = token.indexOf('=');
if (index >= 0 && index <token.length()-1) {
user.setUserName(java.net.URLDecoder.decode(token.substring(index+1)));
}
}
if (token.startsWith("usersex")) {
int index = token.indexOf('=');
if (index >= 0 && index <token.length()-1) {
user.setUserSex(Integer.parseInt(token.substring(index+1)));
}
}
}
System.out.println(user.toString());
}
}
class User {
private long userId;
private String userName;
private int userSex;
//constructos
User(long userId, String userName, int userSex){
this.userId = userId;
this.userName = userName;
this.userSex = userSex;
}
User() {
this.userId = -1;
this.userName = "undefined";
this.userSex = -1;
}
#Override
public String toString() {
return String.format("id: %d; name: %s, sex: %d", userId, userName, userSex);
}
/**
* #return the userId
*/
public long getUserId() {
return userId;
}
/**
* #param userId the userId to set
*/
public void setUserId(long userId) {
this.userId = userId;
}
/**
* #return the userName
*/
public String getUserName() {
return userName;
}
/**
* #param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* #return the userSex
*/
public int getUserSex() {
return userSex;
}
/**
* #param userSex the userSex to set
*/
public void setUserSex(int userSex) {
this.userSex = userSex;
}
}

Categories