Just as a precurser to the question, I am moderately new to Java, so please bear with me.
I am right now attempting to create an account system, and it seems that automating the account ID process is more difficult than previously thought. I want to be able to have customized user IDs for each individual object reference, so it's easy to access, count how many users there are, edit values in the object, etc.
I basically want:
int accountsMade=1;
userAccount (A1) = new userAccount(other Input);
And then the next time a user registers an account, the object reference will be:
userAccount (A2) = new userAccount(Different input);
Is there any way to automate this system? It seems as if there is, but I can't figure it out.
What you'd want to do is create and keep reference to a HashMap object. These are key-value pairs, in which providing a key (in this case, the user ID provided by the user) allows you to get the value (in this case, the user account object) in a very quick and efficient fashion.
The actual signature of the HashMap you'd want to use would be Map.
Here's the current documentation on HashMap: http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html.
However, I think there's a pretty significant issue with the design you're building right now, and that's that you're constructing a new userAccount object each time you get input. The concept of an account suggests some sort of continuity - saved data, passwords, etc. Right? GMail doesn't make a new account for you every time you sign in.
So, you're going to need somewhere to keep that data, somehow. You could either use an external database, like SQL, or, if you're 100% sure that your use cases and userbase will never, ever, change, you could just hardcode account objects into your prototype and check user login attempts against the keys in the HashMap. Either way, I'm not sure it'll work for your purposes to be constructing a userAccount object upon user login.
Related
I have a Java application that receives orders from a remote server then logs into an account and executes the order (I.e, purchases product and ships to correct address).
I am storing the account details (such as username, password, funds remaining in account) in an object called "AccountDetails". I am also storing the purchase details (such as shipping address, first and last name, product ID and so on) in an object called "OrderDetails).
Throughout the execution of program both account and orders will be added to program on constant basis.
My question is - if I exit application and then launch the application I understand the program needs someway to instantiate all previous objects (such as all pending orders and account details).
What is the best way to do this?
I understand I would store "the state" of each object in a MYSQL database and then when I launch program connect to DB and instantiate object. However, I'm not sure exactly the best way to instantiate the object.. And do I have the general right approach here?
Thanks
You could serialise the object every time it is changed or if your application has a GUI serialise the object and save it in some file(MYSQL database in your case) when the user clicks save button.
Your constructor should look something like this
public foo(){
if (file has your object)
//code for deserializing
else
//create new object
}
I'm still new to MVC programming in Java. My question is, in what part of the program is it best practice so store user information? I have a login form and I handle the login in one of my models. What's the best way to make the user data available to the entire application? I was thinking about adding field variables to my model and simply storing the data there, but since I have several models I wouldn't be able to retrieve the data from other models. Is it a good idea to create an object that stores the user data and calling that object from all models? Or is there a better approach? Thanks!
First of your question is too generic an is risking its closure.
Your gut feeling to not mix data is right. Keep whatever user data together. Maybe for now it's just a username but this kind of data tend to grow over time and you want this flexibility later.
Think about where you need that data most. User data is needed for authentication, authorization and tracking.
If you think of the relation of user data and user generated data, or the interaction between content and user data, how would you structure such relations?
If you think about performance, which subset of the user data is at least necessary to fullfil your requirements?
I know I am wage but your question is wage itself.
Try to step back from your code and think more about the architecture of your software.
I am in the design stage of my next task and I am not sure whether my idea for it is right or not, as I am not quite sure on how to realize it in an UML diagram. I would appreciate much your comments about it.
Basically the point is that I am going to have a reader and a writer class. They will be used to read and write values from/to an certain data source, i.e a database or a modbus PLC. Each of these values is identified by a unique id in my data model and in the data source. The read operation will be performed periodically for all the values by sending all their ids and quering its values. The write operation is made each time one of these values change in my datamodel and needs to be sent to this data source.
My idea is to have a shared List for the reader and the writer containing all the objects in my datamodel. For example:
class ExternalObject {
private String id;
private String transactionId;
private String value;
private String lastValue;
}
There will be a controller class that when a value changes in my data model will write it in the value attribute of the right object, then the Writer class, that is iterating through all the elements of the list all the time will see that the value is not null and send it. After this, it will reset it to null and set it to the lastValue.
Besides, the Reader class, that is reading the values from this data source all the time, when sees that a value read is different from the lastValue, it will save it in my datamodel.
By now I suppose you got the idea. There will be of course some more logics to reset values when there's no connection with the data source or to send the initial values or read them, but that's another thing.
My concern is this shared list. I am not sure if it is fine, in object oriented design, to share lists or objects like this. If this is fine, the next thing is that I don't know how to model it in an UML diagram to indicate that one object is shared between two classes.
Any ideas about it are much welcomed.
Unfortunately this is not a complete answer because I've never implemented anything like that in industry grade, but a few notes come to mind:
1) New IDs: the Reader polls for IDs it knows - but what about new IDs, inserted by external processes?
2) Performance: do you control the schema, and are your machine clocks synchronized within some reasonable margin? If so, perhaps you could have a timestamp on each object, and the reader could 'refresh' only objects that were edited/inserted since its last refresh (plus some safely margin)?
3) List: I wouldn't say "object oriented forbids list sharing", but for your own convenience you might like to consider a wrapper data structure, with methods for searching/updating/inserting/deleting. Thus you can easily replace the datastructure at will, e.g. to a map.
4) Transactions: how were you going to handle transactions of those data sources?
anyway, good luck
There is an application that I'm basically writing with Swing, JDBC and MySQL.
In DB there are tables like Article, Company, Order, Transaction, Client etc.
So also there are java classes which describes them.
User can create, update, delete information about them.
I give an example of my problem. The article characterizes with id, name, price, company, unit. And when user wants to save new article he chooses the company for this article from the list of all companies. This list in perspective could be really big.
Now I could think of two ways to solve this.
When application starts, it connects to the DB and load all the data with which then I will work.
public final class AllInformationController {
public static final Collection<Company> COMPANIES= new HashSet<>(1_000_000);
public static final Collection<Article> ARTICLES= new HashSet<>(1_000_000);
public static final Collection<Order> ORDERS= new HashSet<>(1_000_000);
public static final Collection<Transaction> transactionsHistory= new HashSet<>(10_000_000);
//etc...
private AllInformationController() {}
}
Then if user wants for example to change some Company data (like address or telephone etc.), after doing it the program should update the DB info for that company.
The second approach is basically to connect to the database every time user queries or changes some information. So then I will mostly work with ResultSet's.
I prefer the second way, but just not sure if it's the best one. Think there should be more productive ways to work with data that could be less expensive.
The 2nd approach is better, although there's probably a best case that lies somewhere between them. The 2nd approach here allows multiple applications (or users of the same application) to modify the data at the same time, as the 1st approach may end up using old data if you load all the data at once (especially if a user leaves the application on a while). I would go with the 2nd approach and then figure out what optimizations to make.
Since you think the 1st approach may be usable, I'd assume then you don't have too many users who would use the tool at the same time. If that is the case then, perhaps then you don't need to use any optimizations that the 1st method itself would give you as there's not going to be too much database usage.
When you say you working with ResultSets more often in the 2nd approach than the 1st, well it doesn't need to be that way. You can use the same methods from the 1st approach which translates your data into Java data structures to be used in the 2nd approach.
You already made a very bad decision here:
And when user wants to save new article he chooses the company for this article
from the _list_ of all companies
A list works only reasonably if the number of choices is fairly limited; below 10-20 you may get away with a combo box. For thousands of choices a list is very cumbersome, and the further it grows the slower and more unwieldly chosing from a list becomes.
This is typically solved by some kind of search field (e.g. user types customer number, presses tab and information is fetched), possibly combined with a search dialog (with more search options and a way to select a result found as "it").
Since you will typically be selecting only a few items with a search request, directly quering the DB is usually practical. For a search dialog you may need to artificially limit the number of results (using specific SQL clauses for paging).
I am storing some data in a hash map. Now I want to modify the values associated with a key based on a user input and store them these way permanently.
To make myself more clear, I have a hashmap like this:
public static HashMap<String,Integer> mymap= new HashMap<String,Integer>();
mymap.put("Hi",2);
mymap.put("Hello",3);
I will take feedback from user in some user and if he wants then I will, say, store 4 against Hello. I want these changes to be saved for future references.
I have heard about Reflection API in Java, but am not sure whether that will serve the purpose.
Reflection API allows one to manipulate/access data that is not accessable otherwise - or some data on the class that is unknown at compile time.
In here, it is really not needed. All you need is to put() the element into the map, it will "remove" the old value from the key you just inserted (if it is already there) and associate it (the key) with the newly added value.
So, basically - all you need to do is myMap.put(key,newValue), and the implementation of the Map (assuming it is a correct one, of course) will take care of the rest.
If you want to store the data between runs of the program - you will have to save it (the map) on disk. In order to do so, you can use serialization, or if you can use Properties in some cases.
Make sure that you load the map from disk once the program starts, or you will not see the values you stored.
Just say, mymap.put(key,value);. It will update the value for matching key. If not there, it will insert a new entry e.g.
mymap.put("Hello",4);
If you don't want to insert new value for a new key e.g. World, you can put a check like this:
if(mymap.containsKey(key)){
mymap.put(key,value);
}else{
//no existing key found
}
The Preferences API makes it easy to store a small amount of data on disk. It's usually used to store configuration data. It's similar to the Windows registry.
Here's an introduction: http://docs.oracle.com/javase/1.4.2/docs/guide/lang/preferences.html