Constructing object - java

I have a query in constructing an object and storing it in database in json format.
Its in air domain industry. Need to construct an ojbect and store it in database in json format so the other applications can use the same object for various test automation scripts.
What i have done is i have created a class called PassengerDetails and inserted to station, from station etc., as below.
class PassengerDetails{
private String toStation;// Origin
private String fromStation;// destination
private String noOfAdults;
and getters and setters.
}
The passenger type also changes, like infants, companions etc., and i am not understanding how to handle it in class PassengerDetails. I have a guess like i have to add another class for PassengerType. Please correct me if i am wrong and suggest me how to add that passengertype details.
And I have created one ticket class (one ticket for each passenger, if 3 adults are there then 3 tickets and and three tickets are associated with one unique PNR). Here we have to store how the ticket is purchased, i mean by cash or credit card
class PaymentDetails{
private String creditCardType;
private String creditCardNo;
private String creditCardHolderName;
private String cash;
getters and setters.
}
We are having different payment types like Creditcard, cash, vouchers, refund amount etc., I am in confusion again how to handle this in the above PaymentDetails Class and how to link this class with TicketInformation and PassengerDetails
class TicketInformation{
private List<PassengerDetails> passengerDetails;
Getters and setters...
}
For multiple tickets, we have one PNR.
class PNRDetails{
List<TicketInformation> ticketInformationList = new ArrayList();
getters and setters.
}
Now i have a query like, if there is modification in flights or dates etc., new ticket will be issued. Now the question is how to store this new tickets and old tickets so that the user who retrieves the list of tickets can understand that there is a modification and hence there are new tickets and old tickets.
The other scenario is that if there is an addition of additonal passenger then not only the ticket changes but also the PNR changes, Now the question is i want to store both new and old PNRs and associated tickets.
For multiple PNR's how to write the class, do i have to write a class where it has List as instance variable. I messed up the code and i am in confusion. Could any one suggest better approach in modifications of code.

Here's an example on how to create an object and storing in json format:
var myObj = { "name":"John", "age":31, "city":"New York" };
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
This is a very simple example of course.
Go through this website for more information and tutorials:
https://www.w3schools.com/js/js_json_intro.asp

Related

How to manage access to a database object properly?

I am wondering weather there is a better solution to my problem.
Better in the sense that not every object of the class Segment has to create a new database object.
I am trying to keep only one database in my program because the database is very big and I am sure there is a more efficient solution to this.
The Database holds objects of the class SegmentInformetion in a List. Each Object contains many informations each Segment object needs for its instantiation.
The Layer Class contains a List of Segments. The Layers Constructor contains an array with IDs. Every Segment will get its Information from the Database depending on the ID with which it is calling the Database.
Database {
List<SegmentInformation> segInfoList;
public SegmentInformation getSegInfos( int id ){
return segInfoList.get(id);
}
}
Layer{
List<Segments> segmentList;
public Layer( int[] segmentIDs ){
for (int i : segmentIDs){
segmentList.add( new Segment( segmentIDs[i] ) );
}
}
}
Segment{
double value1;
//....
double valuenN;
public Segment(int sID){
Database db = new Database();
SegmentInformation info = db.getSegInfos( sID );
value1 = info.getValue1();
//....
valueN = info.getValueN();
}
}
I am trying to avoid a global static variable which contains the Database.
Any suggestions for a more suitable way to instantiate all the Segment objects?
Use a Singleton to contain all the Segment objects:
In software engineering, the singleton pattern is a software design
pattern that restricts the instantiation of a class to one "single"
instance. This is useful when exactly one object is needed to
coordinate actions across the system. The term comes from the
mathematical concept of a singleton.
https://en.wikipedia.org/wiki/Singleton_pattern

How to iterate and add each "many" in a one-to-many class

I have two classes. The OrderSlip class has a one-to-many relationship with orderedItemDescription.
class OrderSlip {
String employeeID
int serving
int tableNumber
static hasMany = [orderedItemDescription: OrderedItemDescription]
}
class OrderedItemDescription {
MenuItem menuItem
MenuItemProgressStatus progress//progress
String descriptionOfOrder
int quantity = 1
static belongsTo = OrderSlip
}
Now my problem is how do i iterate orderedItemDescription so that when i update my orderSlip i can add many orderedItemDescriptions along with its properties.
def updateOrderSlip(Long id) {
User currentUser = springSecurityService.currentUser
def orderSlipInstance = Table.get(id)
//other codes for orderedItemDescription here
orderSlipInstance.employeeID = currentUser.username
orderSlipInstance.serving= Integer.parseInt(params.serving)
orderSlipInstance.tableNumber= params.tableNumber
render(action:'server')
}
Im doing something like this in my gsp. im only adding data to the DOM with the add buttons. Then for the send order im hoping i can update it like the problem since im also adding many g:hiddenField for each orderedItemDescription in my summary
You should be persisting each new instance OrderedItemDescription somehow.
You can store it immediately in the DB upon click on add-button with the status flag set to incomplete. When you save the whole order, you must change the incomplete to complete.
Another option would be to keep the items in the http session. Upon send order you iterate through the in-session items and persist them all along with the order instance.
Both ways have advantages and drawbacks, but they both are useful.

Storing and comparing against objects from a database

I am working on an android app that loads in a list of students to display in a list based activity. There are two components to the app. There is a server which responds via xml with the list of current active students and a database on the app end which stores theses students with some details (name,age etc). I would like a way to sync these two data sources. When the app starts, I would like to check against the xml to see if students on the server were added/deleted and update the db accordingly.
I would be parsing the xml list into a student object at login. Is there any way to store/retrieve an entire object into an android supported db so I can do a direct comparison to see what to update/delete? It would end up being something like
if (serverStudent[0].name == dbStudent[0].name)
//overwrite dbStudent object with serverStudent fields
What is the most efficient/lightweight way to achieve object persistance and then comparison in Android?
Here's a method I have used in the past:
Anytime an object in the database is changed, use a timestamp column to store that time. When the app connects on startup, simply check each timestamp in the app db against the timestamp in the server db for each object. If the timestamps match, do nothing. If the timestamps don't match, retrieve the updated record from the server. Make sure you're using a detail enough timestamp (usually down to milli- or micro- seconds).
The nice thing about timestamps is that if you don't want the server data to override the app data, you could look at which is newer and keep that object if they've both been edited. Just adding some additional thoughts!
You can do something like this -
public class StudentRecord {
Vector<StudentData> studentDatas;
public StudentRecord()
{
studentDatas = new Vector<StudentData>();
}
public Vector<StudentData> getRecords() {
return studentDatas;
}
public void setRecords(Vector<StudentData> records) {
this.studentDatas = records;
}
public class StudentData
{
String name,Rollno;
public String getRollno() {
return Rollno;
}
public void setRollno(String rollno) {
Rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
When you get the vector object studentDatas you can do something like this -
for(Object object : record.getRecords())
{
data = (StudentData)object;
data.getRollno();
data.getName();
}
Check out these libraries:
http://www.datadroidlib.com/
https://github.com/octo-online/robospice
I believe both offer solutions for your situation.
Or you can roll your own solution... Basically you will want to create a service or asynctask to do the syncing, in your student object you can create a constructor that you can pass an id to and have it pull the appropriate record from your local db then make a comparison method that will update if newer information is available.
I'm not sure i understood your question correctly.But as far as i understand i would do something like this.
In server side send send Json array which holds json student objects.
In android side create similer Student class and override equals
method as you want.
Then for each student check with equals method whether they are
equals or not and take action accordingly.
If you want to make faster search in students object array then apply
hash map instead of arrays.

How do I add an ArrayList to another ArrayList?

This makes my brain hurt...
I'd like to add multiple variables such as date and time to an arraylist, and add that arraylist to another arraylist holding different variables such as name and age.
Example: An ArrayList holds multiple accounts. Each account has an id, name, balance and transaction history. Each transaction has an id, date, time and transaction amount.
So the accounts ArrayList would contain: (int | String | double | ArrayList),
and the transactions ArrayList would contain: (int | Date | Time | double).
I'd appreciate it if you could help me understand how to do this, or offer a better solution.
EDIT:
I can't really show all my code because I'm using a model view controller which accesses a model and 4 views. I can try to describe what it does though.
Click "Create Account" button:
make a new account (using Account class)
set accountID = length of accounts ArrayList
set accountName = textbox input
set accountBalance = 0
create transactions ArrayList (using Transactions class)
add all to the accounts ArrayList.
Click "Deposit" button:
add TextBox input to accountBalance
set transactionID = length of transactions ArrayList
set transactionDate = current date
set transactionTime = current time
add all to selected account's transactions ArrayList
Do not use only lists for this, use concrete classes, i.e:
class Account {
String id;
String name;
float balance;
List<Transaction> history;
}
class Transaction {
String id;
Date date;
double amount;
}
And finally have a Map with your relevant data:
Map<Account, List<Transaction>> data = new HashMap<Account, List<Transaction>>();
Create an Account Class and a Transaction class. The Account class will hava as an attribute a list of transaction and when creating a List just declare it as following:
List<Account> myAccounts = new ArrayList<Account>();
and when you want to add an account just write :
myAccounts.add(new Account());

Problems merging multiple objects into a complex object for Morphia

I'm trying to merge these three objects into a single complex object:
public class Person {
private String name;
private List<Event> events;
// getters and setters
}
public class Event {
private String name;
private List<Gift> gifts;
// getters and setters
}
public class Gift {
private String name;
private String recipient;// the name of the person
private String eventName;
// getters and setters
}
My goal is to save the Person object in MongoDB using Morphia and this how I want my document laid out. I've created a document builder, of sorts, that combines lists of each object. Each Person gets a list of all Events, but can only receive specific Gifts. While my document builder does create a document that Morphia can persist, only the Gifts of that last recipient (sort order) are inserted into the Events for all Persons. Though for the correct Events.
public void merge() {
for (Person person : listOfPersons) {
for (Event event : listOfEvents) {
// somePersonsGifts: a sublist of gifts based on Event and Person.
List<Gift> somePersonsGifts = new ArrayList<Gift>();
for (Gift gift : listOfGifts) {
if (person.getName().equals(gift.getRecipient()) && gift.getEventName().equals(event.getName())) {
somePersonsGifts.add(gift);
}
}
event.setGifts(somePersonsGifts);
}
person.setEvents(listOfEvents)
}
}
If I modify the code slightly to process one person at a time by removing the outer loop and having the method take an argument for specific index of the Persons list:
public void merge(int p) {
Person person = listOfPersons.get(p);
//...and so on
I get one complete Person object with the correct gifts. If try to feed the this modified version into a loop, the problem comes back. I've tried using regular for-loops and synchronized collections. I've tried using Google Guava's ImmutableArrayList and still no luck. I know the problem is that I'm changing the lists while accessing them but I can't find anyway around it. I wrote a DAO that uses the MongoDB driver directly and it works properly, but it's a lot more code and quite ugly. I really want this approach to work, the answer is in front of me but I just can't see it. Any help would be greatly appreciated.
Here is your problem:
List<Gift> somePersonsGifts = new ArrayList<Gift>();
....
event.setGifts(somePersonsGifts);
You add the gifts only for one person; if you want to aggregate all the gifts into the event, re-use the existing list.
I don't know anything about MongoDB or Morphia but I suspect the problem is your use of the setters event.setGifts(somePersonsGifts) and person.setEvents(events). Your code does not seem to merge the existing gift and event lists with the ones you are calculating further in the loop, which is how you would want it to behave (if I understand the question correctly).
You should retrieve the allready existing gift list (and event list too) instead of overwriting them with empty new ones.
I don't know if the method merge() is inside the list but I assume that since you are using the list events here
person.setEvents(events);
Maybe you meant
person.setEvents(listOfEvents)
Notice that you are adding all the events to each person. If all the persons went to all the events, it is unnecessary to have the events inside the person.

Categories