Java/Spring: Populate initial user data - java

I am wondering what is the pattern for this. I am building an application where users can create their accounts. And once a user creates her account she gets some basic data set up such as amount of money, name of her cat, and other complex objects.
What is the best way to handle these default values?
One way is to hard code them in the Account bean. However, what happens if these default values ever have to change in production?
One naive way is to have the default values in the settings and then copy them into the Account bean when creating each user.
Though things get messy when these default values differ by user groups. For instance if the user is from Europe, I want to set her initial amount of money to 54 Euros. If she is from the US, I want to set it to -20 US Dollars. And if the user is from China, I want to assign 20 initial cars to her while assigning 10 buildings if the user is from Mexico.
As you can see these initial setup for each user can comprise some complex objects.
What is the best way/pattern to handle this in Java and Spring?

Properties file is a good solution. A database would be more initial cost but perhaps provide better long value. You can account for the difference in values per user group by having grouped properties, such as
us.initial_value=-20
us.unit=USD
eu.initial_value=54
eu.unit=Euros
china.initial_valu=20
china.unit=cars
You could have the code provide a default value for the default, in case the value isn't read in from the file correctly.

Related

Generate a 9 digit Integer in java without repeating the same number

I am new to java programming and I am using databases to create a simple Bank Management system. I need to create user accounts with an account number with 9 digits, that does not start with 0. also, all the account numbers must be different(one account number can have repeating digits). Every time I run the program, it should give me a 9-digit number that is not stored in the 'accounts' table under 'account_number' in the 'login_info' database.
The program runs like this,
User goes to the login page
If he does not have an account he can go to the create account page
create account page has 3 tabs, Personnel info, bank account info, and online account info
user must fill out personnel info got be able to go to the bank account info
when the user goes to bank account info, it shows the previously filled items (Personel info) and a couple of additional items - Bank account type and account number
The account number must be generated when the user goes to the bank account info tab. The user cannot change the account number. (The account number must be one that has not been saved in the database before)This is the step I am stuck
After selecting the account type, the user can go to the online account info page and select a unique username and password
After that, the user can hit create account button to create his bank account along with the online account or he can exit the program if he is having second thoughts
When the user hit create account button, a query will run and insert data into MySQL tables. This is the point where the account is created.
The program runs beautifully, but I can't seem to generate a unique bank account number. Other steps are already completed.
(This is not for any commercial products, just a project I work on to get myself acquainted with database handling with java.)
Any Idea how to do this?
Thank you.
Here is an approach you could take, elaborating on my comments posted above:
pre-calculate all valid account numbers – there are a total of 3,265,920 valid combinations
9 choices for first digit: 1-9,
9 choices for 2nd digit: 0 is available, so 10 possible digits (0-9) except that something was used for the 1st digit
8 choices for 3rd, etc.
so: 9*9*8*7*6*5*4*3*2 combinations
populate each of those ~3 million numbers into the database table
include a "status" field to represent things like: "unclaimed", "pending", "claimed"
all account numbers start out as "unclaimed"
In your Java app, when you want to present the user with a candidate account number, you can use the database to update a single row from "unclaimed" to "pending" and return that account number – so the database would enforce correctness even if multiple callers simultaneously try to set up a new account. Something like: "update accounts where status=unclaimed set status=pending limit 1" and return the updated row.
From there:
If the user accepts the account number, simply change the status from "pending" to "claimed"
If they decline, change it back to "unclaimed"
This approach would allow you to do numeric specifics only once, up front, when creating all initial unclaimed accounts. It does have a potential drawback that you have 3 million rows sitting there unused, but there is a nice simplicity overall – no further combinations to worry about, or generating a number and then involving the database to see if that number is claimed or not (and re-generating if number in use), or any kind of scanning through the database to use as input for the number selecting process, or whatever other ideas people might come up with. Just do the work up front.
If you want the number to be random, create a number from 0 to 899 999 999 and then add 100 000 000 (so the first will never be 0). If the numbers are stored in an Arraylist (in this case called nums), the following code should help:
int num;
Do{
num = (int)(Math.random()*800000000)+100000000;
}while (nums.contains(num));
nums.add(num);
I am using databases to create a simple Bank Management system. I need
to create user accounts with an account number with 9 digits, that
does not start with 0. also, all the account numbers must be
different. Every time I run the program, it should give me a 9-digit
number that is not stored in the 'accounts' table under
'account_number' in the 'login_info' database.
This actually turns out to be an unexpectedly complicated question to answer. The best answer depends upon other factors which you have not mentioned:
Does the account number have to be unique "each time the program is run" or "each time an account number is requested during the same run (but not necessarily from run to run)"?
Is this a single-threaded environment (i.e., how many simultaneously executing threads might be trying to create account numbers at the same time)?
Does the account number have the sense of identity; does it need to be able to uniquely identify a specific account at all times (or are there times, perhaps when the account is being created from a form, when an account doesn't need to have identity?
What manages the identity? Your program system? The database that you are using to store the information?
If the first bullet item answer is "each time the program is run", then you need to think about how the account number seed (the quantity or quantities that are used to generate your next available account number) is persisted from run to run (the seed otherwise is destroyed when the JVM exits).
If the second bullet item is "multiple threads", then you need to think about how to prevent the same account number from being inadvertently provided to threads requesting one at the same time.
The remaining bullet items deal with identity. Account numbers are generally used to identify specific accounts to the system (but not necessarily). So, you have to consider when the identity needs to become available to the system. You also have to think about what system is responsible for managing the identity. If the identity is needed as soon as an account entity is created, then it needs to be obtained during the instantiation of the account by Java. If it is not needed until the account entity is persisted to the database, then it may be possible for the database system to create the identity.
A hybrid solution would be to persist the account as soon as it was instantiated, and then read it right back again to obtain the account number (at the cost of increasing database traffic). Logic might be needed to delete the database record if the account did not need to be persisted after all (because, say, it had been canceled).
Depending on the answers to these questions, and upon other important factors such as availability, scalability, redundancy, security etc., the complete solution to the original problem could become arbitrarily complex.
But if we assume that account numbers need to be unique only during the same run of the Java system and that account accesses are only single threaded, then a solution could become very simple:
public static class AccountNumberManager {
private static long accountNumberSeed = getStartupSeedValue();
private AccountNumberManager() { }
public long getNextAccountNumber() {
return ++accountNumberSeed;
}
private static long getStartupSeedValue() {
return 100000000L;
}
}
Some brief notes:
A static class for account number management makes the initialization of the account number seed value thread safe. The initial value initialization occurs while the class is locked by the class loader during the loading process and is therefore thread safe (the class and its static fields can only be initialized once and once only). This is the static holder class initialization method. This would be handy if the system ever evolved into a concurrent environment.
This solution, of course, assumes that the account number is needed when the account entity is initialized. I think this is a good practice anyway. My bias is that database systems should not be used to create system-wide identitifiers when possible (only to persist them).
It is not a best practice to use account numbers as database primary keys. This is an opinion that is fairly widely, not but universally, held.

What is the DDD way to make sure that there is only one obj created with 2 attribute combinations

im pretty new to the whole DDD concept and i have the following question:
Lets say i have a UI where Users can save cars by putting in a id and a name. What is the DDD way to make sure that every unique id and name combination is only created once. The cars are all Entities and will be stored in a database. Usually i would just have put a primary and a foriegn key in a DB and just check if the combination is already there and if not create/store the obj and if there is the same combination then don´t.
Now i´m thinking if this is domain logic or just a simple CRUD. If it is domain logic and if i udnerstood correctly i should make my car object decide if it is valid or not. If thats the case how would i do that?
thanks in advance!
edit:
another thing: What if every created object should be deleted after 10 days. That would be a concept in the domain and would hence be also part of the domain logic. But how should the Object know when to delete itself and how should it do it? Would that be a domain service that checks the creation date of the objects and if it is older than 10 days it should perform a delete operation inside the DB?
I would go with a UNIQUE constraints on the 2 fields if you don't care about the validity of the values entered. That way even if someone, for some reasons, inserts/updates the records directly in the DB, the DB will prevent it.
If you care about the validity of the combined values entered, then you will have to add on top of that some logic in your code before saving it in the DB.
About your deletion mechanism, you can have a scheduler that check every day what are the data older than 10 days by checking a previously filled DB column (eg CREATED_ON) and delete them.
"It depends".
If id and name are immutable properties that are assigned at the beginning of the objects lifetime, then the straight forward thing to do is incorporate them into the key that you use to look up the aggregate.
car = Garage.get(id, name)
If instead what you have is a relation that changes over time (for instance, if you have to worry about name being corrupted by a data entry error) then things become more complicated.
The general term for the problem you are describing is set-validation. And the riddle is this: in order to reliably verify that a set has some property, you need to know that the property doesn't change between when you check it and when you commit your own change. In other words, you need to be able to lock the entire set.
Expressed more generally, the set is a collection of associated objects that we treat as a unit for the purpose of data changes. And we have a name for that pattern: aggregate.
So "the registry of names" becomes an aggregate in its own right - something that you can load, modify, store, and so on.
In some cases, it can make sense to partition that into smaller aggregates ("the set of things named Bob") - that reduces the amount of data you need to load/store when managing the aggregate itself, but adds some complexity to the use case when you change a name.
Is this "better" than the answer of just using database constraints? It depends on which side of the trade off you value more -- enforcing part of the domain invariant in the domain model and part of it in the data store adds complexity. Also, when you start leaning on the data store to enforce part of the invariant, you begin to limit your choices of what data store to use.

How to dynamically set different Condition in Config.prop on server side in JAVA ?

Basically i want to read differnet key values pair(url's) for different user dynamically.Means if user is 1 then the specfic urls should be shown .let's say first 10 values.and same goes for the other user's.This is my config.prop file.I want to set the values dynamically ?
User 1 (This is from the database) same applies to user 2 and user 3
KPI_TT_Executive=https://tntanalytics3.sl1430087.com
ONTIME_TT_Executive=https://tntanalytics3.sl1430087.com
ALERTING_TT_Executive=https://tntanalytics3.sl1430087.com
User 2
different sets or url's
...
same goes for user 3 and user 4.
How can i do this in config.prop file.I know how to read the values.Just i want to call the values (or key value pair) dynamically from the config.prop file.and one thing if user is 2 then only those specfic values should come.
can anybody help me in how to achieve this?? in java
It would be quite an unusual design to have individual user-specific configuration in a properties file like this.
It might be better to have a new database attribute for users that indicates the type of config they should be given e.g. config_type. Let's say for example that this type would be an enum with the following made up values: REGULAR, ADVANCED, TYPE_A, TYPE_B
Then you could easily prefix the configuration with these types when fetching properties and have different values in the config file:
REGULAR_KPI_TT_Executive=https://tntanalytics3.sl1430087.com
REGULAR_ONTIME_TT_Executive=https://tntanalytics3.sl1430087.com
REGULAR_ALERTING_TT_Executive=https://tntanalytics3.sl1430087.com
TYPE_A_KPI_TT_Executive=https://tntanalytics3.sl1430087.com
TYPE_A_ONTIME_TT_Executive=https://tntanalytics3.sl1430087.com
TYPE_A_ALERTING_TT_Executive=https://tntanalytics3.sl1430087.com
etc. for other types.
This is tidier and also means you don't have to duplicate configuration in future when more than one user exists that requires the same configuration.
Personally, I would probably put user config this specific into the DB but if you have to change it regularly then I can sympathise with config files.

Performance of database call from JAVA to Database

Our team is building a small application wherein a UI has about 10 drop-down list boxes. ( DDLB ).
These list boxes will be populated by selecting data from different tables.
Our JAVA person feels that making separate database call for each list will be very expensive and wants to make a single database call for all lists.
I feel it is impractical to populate all lists in one database call due to following reason
a. Imagine an end user chooses state = 'NY' from one DDLB.
b. The next drop down should be populated with values from ZIP_CODES table for STATE='NY'
Unless we know ahead of time what state a user will be choosing - our only choice is to populate a java structure with all values from ZIP_CODES table. And after the user has selected the state - parse this structure for NY zipcodes.
And imagine doing this for all the DDLB in the form. This will not only be practical but also resource intensive.
Any thoughts ?
If there are not many items in those lists and memory amount allows you could load all values for all drop boxes into memory at application startup and then filter data in memory. It will be better then execute SQL query for every action user makes with those drop boxes.
You could also use some cache engines (like EhCache) that could offload data to disk and store only some fraction in memory.
You can run some timings to see, but I suspect you're sweating something that might take 100th of a second to execute. UI design wise I never put zip codes in selection menus because the list is too long and people already know it well enough to just punch in. When they leave the zip code field I will query the city and state and pre-fill those fields if they're not already set.

Design for Users-Challenges Relationship in Java/Android

I am just starting off with app development and am currently writing an Android application which has registered users and a list of 'challenges' which they are able to select and later mark as completed/failed.
The plan is to eventually store all users/challenge/etc data on a database though I haven't implemented this yet.
The issue I have run in to is this - in my current design each User has list variables containing their current challenges and completed challenges eg. two ArrayList fields.
Users currently select challenges from a listview of different Challenge objects, which are then added to the user's CurrentChallenges list.
What I had not accounted for is how to structure this so that when a user takes on a challenge, they have their own unique copy of that challenge that can be independently marked as completed etc, whereas at the minute every user that selects say, Challenge 1, is simply adding the same challenge with the same ID etc. as each other user that selects Challenge 1.
I supposed I could have each different challenge be its own sub-class of Challenge and assign every user which selects that challenge type a different instance of that class, however this seems like it would be a very messy/inefficient method as all the different classes would be largely the same.
Does anyone have any good ideas or design patterns for this case? Preferably a solution that will be compatible with later storing these challenges in a database and presumably using ORM.
Thanks a lot for any suggestions,
E
I'd move every aspect of a challenge that is different for each user into a new Attempt class. So Challenge might have variables for name, description etc. and Attempt would have inProgress, completed etc. Obviously these are just examples, replace them with whatever data you're actually storing.
Now in your User class, you can record challenges using a Map. Make it a Map<Challenge, Attempt> and each User will be able to store an Attempt for each Challenge to record their progress. The Challenge instances are shared between users but there is an Attempt instance for each combination of User and Challenge.
When you implement the database later, Challenge, User and Attempt would each translate to a table. Attempt would have foreign keys for both of the other tables. Unfortunately I haven't used ORMs much so I'm not sure whether they'd work with a Map correctly.

Categories