Access Variables From Other Class With Getter Setter JAVA - java

I'm getting problem with accessing variables with getter & setter on multiple classes. I looked up this one but I'm too confused.
I have 3 type users: Admin (Position No: 0 in mysql table), Manager (Position No: 1), Clerk (Position No:2).
I have SeeReportsAndFeedbacks class. I want to show all reports by selecting rows with position_no = 0 and 1 to admin and manager, 2 to clerk. It's already done with if statement.
So clerk can see only see reports that with position_no=2
manager can see only see reports that with position_no=0 and 1
admin can see only see reports that with position_no=0 and 1
Please help me. I'm stucked here for a long time. What are wrong with my getter setters?
If i set on Login_Form, and call get it shows correct in girisyap() function but if i call get in other class named SeeReportsAndFeedbacks it shows first initial value from Users () constructor instead of set value on girisyap() function on Login_Form.
tip value takes position_no from mysql db as string, new1 value is parsing (converting) string to int for if statement
screenshot
GIST
Users Class
public class Users {
private int id;
private String username;
private String fullname;
private String password;
private String phone;
private String gender;
private byte[] image;
private int position_no;
public Users () {
setPno(1); //firsst initialize
//getFullname();
}
public Users (int uid ,String uname, String fname, String upassword, String uphone, String ugender, byte[] uimage, int pno){
this.id = uid;
this.username = uname;
this.fullname = fname;
this.password = upassword;
this.phone = uphone;
this.gender =ugender;
this.image =uimage;
this.position_no = pno;
}
public Users (int pno){
setPno(pno);
}
public int getPno(){
return position_no;
}
public void setPno(int pno){
this.position_no = pno;
}}
SeeReportsAndFeedbacks class (i removed not-related funcs or some other gui things for the question.
public class SeeReportsAndFeedbacks { // extends javax.swing.JFrame
//CLIENT client = new CLIENT();
int new1 = 9999; //testing something
int PositionNoGetiren;
//sers loginf = new Users(0, null,null,null,null,null,null,new1);
public SeeReportsAndFeedbacks() {
//initComponents();
Users loginf = new Users();
PositionNoGetiren = loginf.getPno(); //gets initial value instead of set value on login_form
System.out.println("Babakingg " + PositionNoGetiren);
//int ananas = loginf.getPno();
//fillFeedbackJTable(jTable2);
}
public void fillReportJTable(){//JTable table
//loginf.setPno(2); it works if i manually set but it's useless
//System.out.println("Loginfvalue in see reports: " + loginf.getPno() + loginf.getUsername());
//new1 = loginf.getPno(); //not works shows 0
//see.getNo();
new1=PositionNoGetiren;
String selectQuery = "SELECT * FROM `users` WHERE `position_no` = ?";
if(new1==0){//admin
selectQuery = "SELECT * FROM `reports`";
}
if(new1==1){//manager
selectQuery = "SELECT * FROM `reports` WHERE `position_no` = 1";
}
if(new1==2){//clerk
selectQuery = "SELECT * FROM `reports` WHERE `position_no` = 2";
}
//}
}}
Login_Form
public class Login_Form {
int positionNoGetiren;
/**
* Creates new form Login_Form
*/
public Login_Form() {
//initComponents();
//positionNoGetiren = 9999;
}
private void girisyap() {
//I DELETED ALL DATABASE RELATED THINGS FOR QUESTION.
//String tip = rs.getString("position_no"); //DETECTS CORRECTLY POSITION NO FROM DATABASE
String tip = "IT'S rs.getString(\"position_no\")"; //for posting question
System.out.println(tip);
int new1 = Integer.parseInt(tip);
//Users loginf = new Users(new1); //welcome yazisi icin
Users loginf = new Users(); //ONLY WORKS IN THIS CLASS.
loginf.setPno(new1); //set user type for reports class BUT IT'S NOT WORKING
System.out.println("Loginf degeri login_formdaki: " + loginf.getPno());
//THIS IF IS WORKING CORRECTLY.
if(new1==0){
//Admin form = new Admin();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
// form.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
if(new1==1){
//Manager form = new Manager();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
}
if(new1==2){
//Clerk form = new Clerk();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
// form.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
//this.dispose();
}
private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {
girisyap();}
}

There is nothing wrong with your getters and setters.
This is most likely an issue with parsing the value of TIP, that could not be parsed as an INT, maybe its a float with a weird value of like 2.00000004, or simply null. Try writing a test or log the value which your query return and check if this is the value you are looking for.

Related

Corda LinearState: trying to transfer consumed state from one owner to the other

I am trying to transfer a state from one owner to the other back and forth. So always end up having new state created with same values. But intend to pass the state even if it is consumed to another owner. Trying to achieve this with linear state. I have pasted the transfer flow that basically should use the same car state that was issued to transfer across owners. The same consumed car state should be possible to transfer back and forth with the same state being consumed agian and again. Is this possible in Corda. From atheory perspective I am trying to transfer the car back and forth between two or more partys.
State
#ConstructorForDeserialization
public CarState(String carMake, String carModel, int carYear, double carMileAge, String carVIN, Party issuer, Party owner,UniqueIdentifier linearId) {
this.carMake = carMake;
this.carModel = carModel;
this.carYear = carYear;
this.carMileAge = carMileAge;
this.carVIN = carVIN;
this.issuer = issuer;
this.owner = owner;
this.linearId = linearId;
}
Contract
if(!(inputState.getLinearId().getExternalId().equals(outputState.getLinearId().getExternalId()))){
throw new IllegalArgumentException("UUID of input state and output state must be same");
}
Flow
#InitiatingFlow
#StartableByRPC
public class CarTransferFlowInitiator extends FlowLogic<String> {
// private final String carMake;
// private final String carModel;
// private final int carYear;
private final String carVin;
// private final double carMileage;
private final Party carOwner;
private final UniqueIdentifier linearId;
private int input;
public CarTransferFlowInitiator(String carVin,Party carOwner,UniqueIdentifier linearId){
this.carVin = carVin;
this.carOwner = carOwner;
this.linearId = linearId;
}
private final ProgressTracker.Step RETRIEVING_NOTARY = new ProgressTracker.Step("Retrieving Notary");
private final ProgressTracker.Step CREATE_TRANSACTION_INPUT= new ProgressTracker.Step("Creating Transaction Input");
private final ProgressTracker.Step CREATE_TRANSACTION_OUTPUT= new ProgressTracker.Step("Creating Transaction Output");
private final ProgressTracker.Step CREATE_TRANSACTION_BUILDER= new ProgressTracker.Step("Creating transaction Builder");
private final ProgressTracker.Step SIGN_TRANSACTION = new ProgressTracker.Step("Signing Transaction");
private final ProgressTracker.Step INITIATE_SESSION = new ProgressTracker.Step("Initiating session with counterparty");
private final ProgressTracker.Step FINALIZE_FLOW = new ProgressTracker.Step("Finalizing the flow");
private final ProgressTracker progressTracker = new ProgressTracker(
RETRIEVING_NOTARY,
CREATE_TRANSACTION_OUTPUT,
CREATE_TRANSACTION_BUILDER,
SIGN_TRANSACTION,
INITIATE_SESSION,
FINALIZE_FLOW
);
#Override
public ProgressTracker getProgressTracker() {
return progressTracker;
}
public StateAndRef<CarState> checkForCarStates() throws FlowException {
//QueryCriteria generalCriteria = new QueryCriteria.VaultQueryCriteria(Vault.StateStatus.UNCONSUMED);
QueryCriteria generalCriteria = new QueryCriteria.VaultQueryCriteria(Vault.StateStatus.ALL);
List<StateAndRef<CarState>> CarStates = getServiceHub().getVaultService().queryBy(CarState.class, generalCriteria).getStates();
boolean inputFound = false;
int t = CarStates.size();
input = 0;
for (int x = 0; x < t; x++) {
if (CarStates.get(x).getState().getData().getCarVIN().equals(carVin)) {
// if (CarStates.get(x).getState().getData().getLinearId().getExternalId().equals(linearId.getExternalId())) {
input = x;
inputFound = true;
}
}
if (inputFound) {
System.out.println("\n Input Found");
// System.out.println(CarStates.get(input).getState().getData().getCarMake());
// System.out.println(CarStates.get(input).getState().getData().getCarModel());
// System.out.println(CarStates.get(input).getState().getData().getCarYear());
// System.out.println(CarStates.get(input).getState().getData().getCarMileAge());
// System.out.println(CarStates.get(input).getState().getData().getCarVIN());
} else {
System.out.println("\n Input not found");
throw new FlowException();
}
return CarStates.get(input);
}
#Suspendable
public String call() throws FlowException {
//Retrieve the notary identity from the network map
progressTracker.setCurrentStep(RETRIEVING_NOTARY);
Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);
//Create transaction components both input and output for this application
progressTracker.setCurrentStep(CREATE_TRANSACTION_OUTPUT);
StateAndRef<CarState> inputState = null;
inputState = checkForCarStates();
//Issuer is Toyota
//Owner is AutoSmart
Party issuer = inputState.getState().getData().getIssuer();
PublicKey issuerKey = issuer.getOwningKey();
//Create transaction components both input and output for this application
progressTracker.setCurrentStep(CREATE_TRANSACTION_OUTPUT);
//CarState outputState = new CarState(carMake,carModel,carYear,carMileage,carVin,issuer,carOwner);
String carMake = inputState.getState().getData().getCarMake();
String carModel = inputState.getState().getData().getCarModel();
int carYear = inputState.getState().getData().getCarYear();
double carMile = inputState.getState().getData().getCarMileAge();
String carVIN = inputState.getState().getData().getCarVIN();
Party carIssuer = inputState.getState().getData().getIssuer();
UniqueIdentifier carLinearId = inputState.getState().getData().getLinearId();
System.out.println(carLinearId);
CarState outputState = new CarState(carMake,carModel,carYear,carMile, carVin,carIssuer,carOwner,carLinearId);
List<PublicKey> requiresSigners = Arrays.asList(issuerKey,getOurIdentity().getOwningKey(),outputState.getOwner().getOwningKey());
// requiresSigners.add(outputState.getIssuer().getOwningKey());
// requiresSigners.add(outputState.getOwner().getOwningKey());
final Command<CarContract.Transfer> txCommand = new Command<>(
new CarContract.Transfer(),
requiresSigners
);
final TransactionBuilder txBuilder = new TransactionBuilder(notary)
.addInputState(inputState)
.addOutputState(outputState, CID)
.addCommand(txCommand);
// Create the transaction builder here and add compenents to it
progressTracker.setCurrentStep(CREATE_TRANSACTION_BUILDER);
//TransactionBuilder txB = new TransactionBuilder(notary);
// PublicKey issuerKey = getServiceHub().getMyInfo().getLegalIdentitiesAndCerts().get(0).getOwningKey();
// PublicKey ownerKey = carOwner.getOwningKey();
//List<PublicKey> requiredSigners = ImmutableList.of(issuerKey,ownerKey);
//ArrayList<PublicKey> requiredSigners = new ArrayList<PublicKey>();
//requiredSigners.add(issuerKey);
//requiredSigners.add(ownerKey);
// Command cmd = new Command(new CarContract.Register(), getOurIdentity().getOwningKey());
//txB.addOutputState(outputState, CID)
// .addCommand(cmd);
// Sign the transaction
progressTracker.setCurrentStep(SIGN_TRANSACTION);
final SignedTransaction signedTx = getServiceHub().signInitialTransaction(txBuilder);
// Create session with counterparty
progressTracker.setCurrentStep(INITIATE_SESSION);
FlowSession issuePartySession = initiateFlow((issuer));
FlowSession otherPartySession = initiateFlow(carOwner);
ArrayList<FlowSession> sessions = new ArrayList<>();
sessions.add(otherPartySession);
sessions.add(issuePartySession);
final SignedTransaction fullySignedTx = subFlow(
new CollectSignaturesFlow(signedTx, sessions, CollectSignaturesFlow.Companion.tracker()));
// SignedTransaction fullySignedTx = subFlow(new CollectSignaturesFlow(
// signedTx, Arrays.asList(otherPartySession), CollectSignaturesFlow.tracker()));
//Finalizing the transaction
progressTracker.setCurrentStep(FINALIZE_FLOW);
subFlow(new FinalityFlow(fullySignedTx,sessions));
return "Transfer Completed";
}
}
You need to create a second constructor for your linear state which accepts as input parameter a linearId; you should mark the constructor with the annotation #ConstructorForDeserialization.
Otherwise, when your flow suspends (for any reason) and it serializes your linear state, when the flow will attempt to resume and deserialize the state; it will use your current constructor which generates a random linearId, so the flow will end up with a new/different state than yours (because it has a different linearId).
But when you create that second constructor and mark it with the annotation, the flow will use it to deserialize and create an identical state.
You can use that constructor as well when you create the output state instead of using the setter like you do now.
Edit (after you added the flow code):
You cannot use a consumed state as an input; that's what's known as the double-spend problem. Imagine you had a US Dollar state and you tried to use the same dollar twice to buy things; that cannot happen. The notary will throw and exception if you try to use a consumed state as an input.
That's why when you query, you should query for UNCONSUMED instead of ALL.
Your query solution is not correct and not efficient, imagine if you had 100,000 cars; you're going to fetch all 100,000 then loop through them until you find the car with the VIN that you want? First of all you need pagination (Corda will throw an error if your result set returns more than 200 records and you're not using pagination), second of all this will probably drain your Java heap from creating those 100,000 objects and crash your CorDapp.
Instead, you should create a custom schema for your car state; then use a custom query criteria to query by the VIN number. Have a look at the IOU example how they created a custom schema for IOU state (see here and here). Then you can use the custom schema in a VaultCustomQueryCriteria (read here).

When spring boot service starts, insert data into mongodb

I'm currently new to the Spring Boot Java framework and I'm building a simple application. When my service starts, I want to be able to read a raw file from a URL, parse that data, and upload it into my mongodb database of atlas. So far this is what I have:
#Service
public class CoronaVirusDataService {
private List<LocationStats> allConfirmedStats = new ArrayList<>();
MongoOperations mongoOperations;
#PostConstruct // run this method as soon as the application runs
#Scheduled(cron = "* * 1 * * *") // execute this method every day
public void fetchVirusData() {
List<LocationStats> newStats = new ArrayList<>(); // to hold the stats of each state
HttpClient client = HttpClient.newHttpClient();
// creating a new http request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(ConstantsUtil.VIRUS_CONFIRMED_DATA_URL))
.build();
// get a response by having the client send the request
try {
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
// parse the body of the request from csv format to readable format
StringReader csvBodyReader = new StringReader(httpResponse.body());
Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(csvBodyReader);
for (CSVRecord record: records) {
// create a model with the parsed data
LocationStats stats = new LocationStats();
stats.setState(record.get("Province/State"));
stats.setCountry(record.get("Country/Region"));
// the latest day
int latestCases = Integer.parseInt(record.get(record.size() - 1));
int prevDayCases = Integer.parseInt(record.get(record.size() - 2));
stats.setLatestTotalCases(latestCases);
stats.setDiffFromPreviousDay(prevDayCases);
mongoOperations.save(LocationStats);
// add to new stats
newStats.add(stats);
}
// assign to class array -> we use this array to display the data
this.allConfirmedStats = newStats;
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
So the main issue with this is the data is not saving to the mongoDB once I call mongoOperations.save(). Also, I've learned that it is bad practice to maintain some type of state in a Service. What is the best practice for this? Will inserting the data into MongoDB take care of that since we are not managing state.
Here is my model class that I want to save to mongodb
#Document(collection = "LocationStats")
public class LocationStats {
/** Location model to show corona virus statistics in each state*/
#Id
private String state;
private String country;
private int latestTotalCases;
private int diffFromPreviousDay;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getLatestTotalCases() {
return latestTotalCases;
}
public void setLatestTotalCases(int latestTotalCases) {
this.latestTotalCases = latestTotalCases;
}
public int getDiffFromPreviousDay() {
return diffFromPreviousDay;
}
public void setDiffFromPreviousDay(int diffFromPreviousDay) {
this.diffFromPreviousDay = diffFromPreviousDay;
}
#Override
public String toString() {
return "LocationStats{" +
"state='" + state + '\'' +
", country='" + country + '\'' +
", latestTotalCases=" + latestTotalCases +
'}';
}
}
once I have my models saved into mongoDB, I want to read from the database and get all the data from each collection and display it on the webpage. I'm thinking I'd fetch that data within the controller class and pass it to the frontend, is this good practice? here is my controller class.
#Controller
public class HomeController {
/** Controller class to generate/render the html UI */
#Autowired
CoronaVirusDataService coronaVirusDataService;
#Autowired
MongoOperations mongoOperations;
#GetMapping("/") // map this to the root template
public String home(Model model) {
List<LocationStats> allStats = coronaVirusDataService.getAllConfirmedStats();
// instead of above getter method, have a method call that fetches all data from mongoDB and return it as a List<LocationStats>
// get the total confirmed cases
int totalConfirmedCases = allStats.stream().mapToInt(LocationStats::getLatestTotalCases).sum();
int totalNewCases = allStats.stream().mapToInt(LocationStats::getDiffFromPreviousDay).sum();
// send the models to the view
model.addAttribute("locationStats", allStats);
model.addAttribute("totalReportedCases", totalConfirmedCases);
model.addAttribute("totalNewCases", totalNewCases);
return "home";
}
}

How to print out a list item based on its status?

I'm creating an eAuction system and I have a method for browsing auctions. Each auction has a status (OPEN or CLOSED) and I want the browseAuctions method to only print out auctions that are opened.
I've tried a number of if statements and it always keeps printing out every single auction.
The following code is a few things I've hardcoded to test the system
public List<Auction> auctionSystem() throws Exception {
List<Auction> auctions = new LinkedList<Auction>();
auctions.add(new Auction (35.50, 75.50, 40.00, users.get(3), LocalDateTime.now().minusSeconds(60), "Xbox", users.get(1), Status.OPEN));
auctions.add(new Auction (27.00, 42.00, 32.00, users.get(2), LocalDateTime.now().plusSeconds(10), "PS3", users.get(1), Status.OPEN));
auctions.add(new Auction (19.00, 21.00, 50.00, users.get(2), LocalDateTime.now().minusSeconds(1), "iPhone", users.get(1), Status.CLOSED));
return auctions;
}
This is the Auction class constructor:
public Auction (double startPrice, double reservePrice, double currentBid, User highestBidder, LocalDateTime closeDate, String item, User seller, Status status) throws Exception {
if (closeDate.isBefore(LocalDateTime.now().plusDays(7))) {
this.startPrice = startPrice;
this.reservePrice = reservePrice;
this.closeDate = closeDate;
this.item = item;
this.highestBidder = highestBidder;
this.currentBid = currentBid;
this.seller = seller;
UP = currentBid * 0.20;
LOW = currentBid * 0.10;
} else {
throw new Exception ("CloseDate error: " + closeDate.format(formatter));
}
}
This is the Status class:
public enum Status {
OPEN, CLOSED
}
This is the method inside the Auction class to browse auctions:
public void browseAuctions () {
System.out.println("-----All Auctions-----");
for (Auction a : auctions) {
if (a.status.equals(Status.OPEN)){
System.out.println("Item: " + a.getItem());
System.out.println("Current Bid: " + "£" + a.getCurrentBid());
System.out.println("Close Date: " + a.getCloseDate());
}
}
}
}
The status is ignored in the constructor, therefore all the Auction instances shall be not be qualified according to the condition in the loop. I wonder all pass and the only explanation is that the Status.OPEN is set by default, it means you have the following declaration in the code:
private Status status = Status.OPEN;
Since it is missing in the constructor, it is not set to a new passed value. These are problems with mutable fields, so I suggest you declare them final and resolve a default value with a secondary constructor:
private final Status status;
// the rest
public Auction (double sPrice, double rPrice, double currentBid,
User highestBidder, LocalDateTime closeDate, String item, User seller)
{
this(sPrice, rPrice, currentBid, highestBidder, closeDate, item, seller, Status.OPEN)
}
Anyway, to fix your issue, complete the constructor with:
this.status = status;

Unit Tests Junit NullPointerException and NoSuchElement help! Rest endpoints

When I am accessing my class to test the methods, I am getting exceptions every time I try to define a new object and use the newly defined object.
Tests in error:
UserInformationControllerTest.deleteUser:83 » NullPointer
UserInformationControllerTest.getUserInfo:27 » NullPointer
UserInformationControllerTest.updateUserInfo:68 » NullPointer
UserOrderControllerTest.createUserOrder:60 » NoSuchElement
UserOrderControllerTest.getUserOrder:47 » NullPointer
UserOrderControllerTest.updateUserOrder:85 » NullPointer
My assignment is to make 4 happy cases and 4 unhappy cases for each class
I am thoroughly confused.
My test class for UserInformation
private HashMap<Integer,UserInformation> userInformationHashMap;
#Test
public void getUserInfo(){
UserInformationController userInformationController = new UserInformationController();
this.userInformationHashMap = new HashMap<>();
int user0 = 0;
int user1 = 1;
UserInformation userInformation0 = new UserInformation("Doug","Jones", "djones#gmail.com","17073");
UserInformation userInformation1 = new UserInformation("Natalie","Peirce", "nataliepeirce12#yahoo.com","dynamicrabbit");
this.userInformationHashMap.put(user0,userInformation0);
this.userInformationHashMap.put(user1,userInformation1);
userInformationController.getUserInfo(user0);
userInformationController.getUserInfo(user1);
Assert.assertEquals(userInformationController.getUserInfo(user0),userInformationController.getUserInfo(user1)); //False
Assert.assertNotEquals(user0,user1); //True
}
#Test
public void createUser(){
UserInformationController userInformationController = new UserInformationController();
this.userInformationHashMap = new HashMap<>();
UserInformation userInformation0 = new UserInformation("Troy","Green","tjg217#verizon.com","2012hummingbirds");
UserInformation userInformation1 = new UserInformation("Sierra", "West","themostimportantwest#msn.com","shadeyglasses77");
int user0 = userInformationController.createUser(userInformation0);//Can you tell me why this does not work
int user1 = userInformationController.createUser(userInformation1);//Can you tell me why this does not work
this.userInformationHashMap.put(user0, userInformation0);
this.userInformationHashMap.put(user1, userInformation1);
Assert.assertNotEquals(this.userInformationHashMap.get(user0),this.userInformationHashMap.get(user1)); //True
Assert.assertNotNull(this.userInformationHashMap.get(user0)); //False
}
#Test
public void updateUserInfo(){
UserInformationController userInformationController = new UserInformationController();
this.userInformationHashMap = new HashMap<>();
int userId = 0;
UserInformation userInformation = new UserInformation("Nicole", "Rigby", "sexygirl69#babellon.com","throwmethemoney");
UserInformation newUserInformation = new UserInformation("Kitty", "Morgan", "ilovecats#cats.com","cats");
this.userInformationHashMap.put(userId,userInformation);
Assert.assertEquals(this.userInformationHashMap.get(userId),userInformation); //True
userInformationController.updateUserInfo(userId,newUserInformation); //Can you tell me why this does not work
Assert.assertNotEquals(this.userInformationHashMap.get(userId),newUserInformation); //False
}
#Test
public void deleteUser(){
UserInformationController userInformationController = new UserInformationController();
this.userInformationHashMap = new HashMap<>();
int user = 0;
UserInformation userInformation = new UserInformation("Camryn","Resele","smartcookie#email.com","28564088");
this.userInformationHashMap.put(user,userInformation);
userInformationController.deleteUser(user);
Assert.assertNull(this.userInformationHashMap.get(user)); //True
Assert.assertTrue(this.userInformationHashMap.containsKey(user)); //False
}
}
UserInformationController
private HashMap<Integer,UserInformation> userInformationHashMap;
/**
* Default json constructor`enter code here`
* #return new user object
*/
#GetMapping(path = "/defaultUserInformation")
public UserInformation test()
{
return new UserInformation("fname", "lname", "email", "pass");
}
/**
* Gets the users information
* #return users information
*/
#GetMapping (path = "/userInfo")
public UserInformation getUserInfo(#RequestParam ("id") int id){
return userInformationHashMap.get(id);
}
/**
* Sets the users information
* #param userInformation userInformation model
* #return users key
*/
#PostMapping (path = "/createUser")
public int createUser(#RequestBody UserInformation userInformation){
if(this.userInformationHashMap == null){
this.userInformationHashMap = new HashMap<>();
}
int maxKey = 0;
if(this.userInformationHashMap.size() != 0){
maxKey = Collections.max(this.userInformationHashMap.keySet()) + 1;
}
this.userInformationHashMap.put(maxKey,userInformation);
return maxKey;
}
#PutMapping (path = "/updateUserInfo")
public void updateUserInfo(#RequestParam ("id") int id, #RequestBody UserInformation userInformation) {
if (this.userInformationHashMap.containsKey(id)) {
this.userInformationHashMap.put(id, userInformation);
}
}
#DeleteMapping (path = "/deleteUser")
public void deleteUser(#RequestParam ("id") int id){
this.userInformationHashMap.remove(id);
}
}
userInformationHashMap within UserInformationController is never initialized, this is why you're getting the NullPointerExceptions.
You're initializing the HashMap in the createUser endpoint and it's never being called within the test.
The createUser endpoint I can't see where it's failing, but anyway this code should really be reorganized because it has many points of failure. The HashMapshould really be initialized when the Bean is created, and you should revisit the way you are calculating the Key.
Also for Controller testing purposes, you should be using MockMvc instead of calling controller methods directly.

Java, Generating a dynamic object name [duplicate]

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 8 years ago.
I was trying to generate a dynamic object names that will change everytime an object is created. Something like:
first object name would be like "userName" and the following would be like "userName1".
I'm new to java, and I tried to initialize int count=0 and count++ to do it, but the User class doesn't seem to allow me to do that like userName+count. Therefore, is there anyway i could possible go about doing it?
I have search through all the similar thread about dynamic object name, but it doesn't seems to work out for my case.
EDIT
So i have this app built up, that allow user to create account.
And, now i encounter this problem where whenever i tried to create new account,
Firebase clear away all my previous data that i have inserted, and replace it with the current inserted data.
Here's my code:
Main.java
name = (EditText) findViewById(R.id.edit_rName);
email = (EditText) findViewById(R.id.edit_rEmail);
password = (EditText) findViewById(R.id.edit_rPassword);
Button btnSubmit = (Button) findViewById(R.id.btn_rSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Firebase f = new Firebase("https://xxx.firebaseio.com/");
Firebase usersRef = f.child("users");
Map<String, User> users = new HashMap<String, User>();
users.put(name.getText().toString(), new User(name.getText().toString(), password
.getText().toString(), email.getText().toString()));
usersRef.setValue(users);
}
});
User.java
public class User {
private String fullName;
private String password;
private String email;
public User(String fullName, String password,String email) {
this.fullName = fullName;
this.password = password;
this.email = email;
}
public String getPassword() {
return password;
}
public String getFullName() {
return fullName;
}
}
You should use an array if you know in advance how many objects you will create, and a list if you don't know in advance.
Array:
String[] usernames = new String[4];
usernames[0] = "Alex";
usernames[1] = "Bob";
usernames[2] = "Carol";
usernames[3] = "David";
//usernames[4] = "Eliza"; // won't work, out of bounds!
System.out.println(usernames[2]); //prints Carol
List(recommended) (first import java.util.ArrayList):
List<String> usernames = new ArrayList<String>();
usernames.add("Alex");
usernames.add("Bob");
usernames.add("Carol");
usernames.add("David");
usernames.add("Eliza");
System.out.println(usernames.get(2)); // prints Carol
usernames.set(2, "Carlos");
System.out.println(usernames.get(2)); // prints Carlos

Categories