I'm trying to make a Sign Up window on JFrame Form in NetBeans. I have created a class named users (in the same package) that has a username as String and password as char[].
When the username and password are filled, and Sign Up button is pressed, I want to make a new object in the class 'users' so that it's name is taken from username textfield itself.
I want to dynamically create object whose names have been taken from a string.
eg: If I put value of Username as "guy", then create users.guy which has a String = "guy" and a char[] as password.
package login;
public class users {
private char[] password;
String username;
users() {
username = "anonymous";
password = null;
}
users(String u, char[] p) {
username = u;
password = p;
}
void putdata() {
System.out.println(username);
System.out.println(password);
}
}
Thanks in advance.
If I understand good your question what you want to do is a mapping. In Java there's a lot of ways for do that.
I would recommend you the use of HashMap, it's simple and efficient.
There's a simple example.
String userYayotrón = "Yayotrón";
char[] passwordYayotrón = "contraseña".toArray();
Map<String, char[]> usersMap = new HashMap<String, char[]>();
//This hashmap will take two values, the KEY which identifies the VALUE. The key is the first one, which I define as String. I will use it for save the User's name. And the value will be the password.
usersMap.put(userYayotrón,passwordYayotrón);
Now, you can use this map for a lot of things. For example:
usersMap .get(userYayotrón); // This will return an char[] with the password of Yayotrón.
usersMap .size(); // How many users do you have in this map.
Also I highly recommend read the following question related:
What java collection should I use?
How to use Java Set?
How does HashMap works in Java?
Create a new instance of the users class passing the username and password like so:
new users(userTextField.getText(), userPasswordField.getText().toCharArray())
If you include the code for the GUI itself I'd be able to give you a more direct answer/solution.
Related
I once saw a talk by Douglas Crockford where, in the context of javascript, he mentioned that it could be useful to store secrets in closures.
I imagine this could be naively implemented like this in Java:
public static Supplier<String> passwordStore(String encryptedPassword){
String plainTextPassword = encryptedPassword; //do some decryption
return () -> plainTextPassword;
}
I wonder: Is there any benefit to doing this? Is it maybe in some way less secure?
No reason to do that. Store the password in the array of characters, since they must be explicitly converted to String if you want to print them out.
Consider the following example:
String stringPassword = "password";
char[] charactersPassword = new char[]{'p','a','s','s','w','o', 'r', 'd'};
System.out.println("Password: " + stringPassword); // Password: password
System.out.println("Password: " + charactersPassword); // Password: [C#6ce253f1
The main idea is you can clear the array's items, since it is not immutable (#Klitos Kyriacou).
Arrays.fill(charactersPassword, '0');
Moreover, if you store the password as a plain text - String, which is immutable, it will be available in the memory for a long time (which is still somehow accesible) until the Garbage collector takes care of it.
Anyway, it's highly recommended to look after some security library which can handle much more than inventing a new (usually still risky) way.
Here's a very "engineered" example so DO NOT USE IT IN YOUR CODE.
I think the effect can be better demonstrated with a predicate rather than a supplier.
Assume you implement a password checker as follows:
public class PasswordChecker {
private final String secretPassword;
public PasswordChecker(String secretPassword) {
this.secretPassword = secretPassword;
}
public boolean test(String password) {
return Objects.equals(this.secretPassword, password);
}
}
Then you can create an instance an pass it around:
final PasswordChecker passwordChecker = new PasswordChecker("changeit");
And somewhere else you could use it to check the password:
assertThat(passwordChecker.test("foobar")).isFalse();
However for the client which has an instance of PasswordChecker at hand, it is not so difficult to extract the password with some reflection:
Field secretPasswordField = passwordChecker.getClass().getDeclaredField("secretPassword");
secretPasswordField.setAccessible(true);
String secretPassword = (String) secretPasswordField.get(passwordChecker);
System.out.print(secretPassword);
Now here's the same thing with a closure:
final String secretPassword = "changeit";
final Predicate<String> passwordChecker = password -> Objects.equals(secretPassword, password);
Now you can't extract secretPassword from the passwordChecker.
I am relatively new to Java and would like to know how to store variables separately from a single line of user input.
At the minute the user is prompted to enter football results in the following format
home_name : away_name : home_score : away_score
and I am using a while loop to continue to ask user for input until they enter "stop"
(while (input != "stop))
Once the loop is broken I would like my program to output a variety of data such as total games played, but I'm struggling to store the home_name, away_name etc.. especially if the user wishes to enter multiple lines of results.
Two mainstream ways to store a "record" are:
Maps
Data objects
A map is more generic:
Map<String,String> match = new HashMap<>();
match.put("home_name", "Alvechurch Villa");
match.put("away_name", "Leamington");
match.put("home_score", "0");
match.put("away_score", "6");
You can add a map to a list:
List<Map<String,String>> matches = new ArrayList<>();
matches.add(list);
... and retrieve them:
Map<String,String> match = matches.get(0);
System.out.println(match.get("away_score"));
A data object is more tuned to your data format, but you have to write the class yourself.
public class Match {
public String homeName;
public String awayName;
public int homeScore;
public int awayScore;
}
Now you can use this class:
Match match = new Match();
match.homeName = "Studley";
// etc.
You can add and retrieve these from lists too:
List<Match> matches = new ArrayList<>();
matches.add(match);
Match aMatch = matches.get(0);
This is simple, but it's considered bad practice to have public fields like this - it's better to get at them via methods. For brevity, here's a data class with only one field:
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String name() {
return name;
}
}
Player neilStacey = new Player("Neil Stacey");
You can use the same technique with all the fields in Match.
(A common style is to name a method like this getName(), and also to have a setName(). I have used a different style and made the object immutable, in an effort to set a good example!)
One advantage of the data object is that it has different types for different fields: homeName is a String, homeScore is an integer. All the fields in the Map are Strings. You can get around this by using Map<String,Object> but then as a consumer you have to cast to the right type when you read.
String homeName = (String) match.get("home_name");
Data objects allow the compiler to do a lot of compile-time checking that helps you know your code is correct. If you use a map, you won't find out until runtime.
Prompt the user separately for each input.
System.out.println("home_name: ");
String hN = scan.next();
System.out.println("away_name: ");
String aN = scan.next();
System.out.println("home_score: ");
String hS = scan.next();
System.out.println("away_score: ");
String aS = scan.next();
What data structure array would you use to store an authentication table and have the user use a Scanner input to get certain data from the table. Such as, if the user types in "delta three" the program should respond with "romeo four" and authenticate it.
Questions:
What data structure should I use? ArrayList maybe?
How to give the data structure the dimensions of the authentication table? I assume I can use an index and put a number to represent the rows and columns.
How to make the objects that fill the table have no duplicates otherwise it will need to be regenerated?
How would I generate a new table?
So what sort of Java imports do I need and are there already built-in functions in Java/Netbeans that can help me out?
Yes, this seems like a lot but I struggle with this sort of things and need expert help.
If you need an example of the authentication table. Here is an example:
public class AuthenticationTable
{ //Start of class method.
public static void main(String[] args)
{ //Start of main method
String [] [] Table = {{"E3","H5","R9","W8","S1"},
{"Z9","P5","K8","X5","I9"},
{"B2","F7","L2","M4","H3"},
{"J7","A7","N2","R6","V4"},
{"O9","W3","E8","U4","E8"}};
System.out.println(Table[2][1]);
System.out.println(Table[4][0]);
} //End of main method
}//End of class method
This question sounds a lot like homework, so I'll try to simply point you in the right direction:
Take a look at the HashMap. You could store what the user will provide as key and the respective authentication as value.
The HashMap is a key value structure, thus you could store the request-expected response as so.
The keys of HashMap structures must be unique. So you will not have any duplicates. You could also use the containsKey method to see if a key already exists.
Given your example,
Such as, if the user types in "delta three" the program should respond
with "romeo four" and authenticate it.
You could do something like so:
Map<String, String> authTable = new HashMap<String, String>();
authTable.put("D3", "R4");
...
String userInput = "D3";
System.out.println(authTable.get(userInput)); //This should yield R4, assuming that it exists.
As a side note, one usually keeps sensitive information stored somewhere else and does not ship the authentication table with the product since that would be a security risk. You could layer your code in such a way that one part pretends to send a request for authentication.
EDIT:
public class AuthenticationProvider {
private Map<String, String> authTable;
public AuthenticationProvider()
{
this.authTable = new HashMap<>();
}
public String authenticate(String input)
{
return this.authTable.get(input);
}
public void addAuthentication(String source, String expected)
{
if(!this.authTable.containsKey(source))
this.authTable.put(source, expected);
}
}
.....
Scanner scan = new Scanner(System.in);
AuthenticationProvider authProvider = new AuthenticationProvider();
authProvider.addAuthentication("D3", "R4");
System.out.print("The co-ordinates that your after: ");
String userInput = scan.nextLine();
System.out.print(authProvider.authenticate(userInput));
public void TheBank() {
Scanner Sc = new Scanner(System.in);
System.out.println("Please Enter your Username and Password");
MemoryStorage();// Stores the Username and Password in the system.
VariableCompare();// Compares the Username and Password to see if they match or do not
}
private void MemoryStorage(){// this should just be here to store the variables username and password
Scanner Sc = new Scanner(System.in);
String username = Sc.nextLine();
String password = Sc.nextLine();
}
private void VariableCompare() {// this should compare to see if they match or dont and print the results
if (username.equals (password){
System.out.println("Please try again your Username and Password cannot be the same");
} else {
System.out.println (" Your username is:" + username);
System.out.println(" Your password is:" + password);
}
}
}
My question is the body (MemoryStorage), i want it to save the username and password, so that the other bodies can use it aswell to proceed with their calculations. At the moment the variables username and password are not accepted into the other bodies and i want to know how i can make those two variables available to all bodies to use.
Currently you're declaring local variables. Those only exist while you're executing the method. It sounds like they should actually be instance variables (fields) within your class:
public class Whatever {
private String username;
private String password;
// Methods which assign to username/password and read from them
}
You should also read up on naming conventions in Java, and think about how to name your methods more along the lines of what they're actually doing. Oh, and consider passing the Scanner into your current MemoryStorage method rather than creating a new one - I've seen various problems when people create multiple instances of Scanner with the same underlying stream.
As an alternative to instance fields, you could consider using return values from the methods. For example:
AuthenticationInfo auth = requestUserAuthentication(scanner);
validateAuthentication(auth);
... again though, it's not clear that these should really be separate methods. Why is the method which asks for the auth info not validating it? Note that the validation you're using is a simple one which isn't actually checking that the username/password combination is correct - it's just checking that it's possibly correct (the same sort of validation as would check for a minimal password length etc).
in my method I have let's say UserDetails object which has some defined value like id, phone etc.
User changing only one value through form, it's email. Is the way how I could use method
userDetailsForm.bindFromRequest(new String[]{"email"}).get()
to not 'loose' previous values? The above example give me new userDetail object with only defined email field. Of course I know that I can use DynamicForm class, or just
userDetailsForm.bindFromRequest().get().getEmail()
but it would be helpfull to have method which does all this binding in one line.
=========EDIT
DynamicForm dynamicForm = Form.form().bindFromRequest();
String email = dynamicForm.get("email");
isn't that what I'm looking for.
=========EDIT======================================
In other words, I want to divide my form to 3 steps, but after every step I am doing update on DB. So for example when I am POSTing step2 I have object with values from previous step:
User [userId=8, createdById=12, name=null, active=false, country=EN]
so now when I am doing:
static Form<User> userForm = Form.form(User.class);
User user = User.find(8);
User user2 = (User) userForm.fill(user).bindFromRequest("name").get();
I am geting new object with empty fields:
User [userId=0, createdById=0, name="value from step 2", active=false, country=null]
I will be very greatfull for any advise.
Try this
Form<UserDetail> submittedForm = form(UserDetail.class).bindFromRequest();
String emailID = submittedForm.data().get("email");
data() will hold name and value pair like following Map<String, String>, further retrieve value by providing its key name inside get() will return you the desired value.
Ok guys, I've figured out how to solve problem.
Here is discussion about this:
https://groups.google.com/forum/#!searchin/play-framework/Form$20bind/play-framework/MtjBV5YNQ3E/QumAmLbMl5sJ
one of possible solution is here:
https://gist.github.com/nraychaudhuri/10590943
import com.fasterxml.jackson.databind.ObjectMapper;
private static Form<Computer> editableForm(final Computer obj) {
ObjectMapper mapper = new ObjectMapper();
Form<Computer> form = Form.form(Computer.class);
Map<String,String> data = mapper.convertValue(obj, Map.class);
Map<String, String> submittedData = form.bindFromRequest().data();
data.putAll(submittedData);
return form.bind(data);
}
and my solution is below:
public T bind(T target, Map<String, String> newValues) {
DataBinder binder = new DataBinder(target);
binder.setAllowedFields(getAllowedFields());
binder.bind(new MutablePropertyValues(newValues));
return target;
}
=================EDIT
Here is important disscussion about security issue: https://groups.google.com/forum/#!searchin/play-framework/Form$20bind/play-framework/uGrSlJMo48c/QnVjzP4ovqcJ
Form.bindFromRequest
without arguments. However, as probably most of you know, invoking
that method without parameters will bind all fields of the
corresponding model object to like-named request parameters, including
fields holding internal state that must never be set from the outside
(e.g. boolean isAuthenticated). That is, an attacker may set any field
and circumvent security if they only know the name of the
corresponding model object field. This is of course a catastrophic
security vulnerability (similar to PHP's notorious and deprecated
register_globals option:
http://www.php.net/manual/en/security.globals.php).