How can I get hashmap's key inside of the hashmap [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed last year.
I'm trying to make a system without MySQL database which will have accounts and accounts' data. But it didn't work
My accounts java file:
/*
* Instead of using 2 different ArrayList (for Username and Password) we used Hashmap
* HashMap stores keys and the keys' values
* In our HashMap keys refer to usernames values refer to passwords
*/
import java.util.HashMap;
import javax.swing.JOptionPane;
public class Accounts {
//I used static to reach list from another class suggest me another way please
static HashMap AccountList = new HashMap<String, HashMap<String, String>>();
public static void CreateAccount(String userID, String password, String email, String fullName, String department){
//We have to check that there shouldn't be an account with the same username
if (AccountList.containsKey(userID)){
JOptionPane.showMessageDialog(null, "There is an account with that username");
}
else{
HashMap Data = new HashMap<String, String>();
Data.put("userID", userID);
Data.put("password", password);
Data.put("email", email);
Data.put("fullName", fullName);
Data.put("department", department);
AccountList.put(userID, Data);
JOptionPane.showMessageDialog(null, "Member created successfully");
}
}
}
In my login.java I get an error on that line
boolean IsLoginSuccessful = false;
//We are getting username and password text/string from the form
String userID = username_field.getText();
String password = password_field.getText();
//Now check if username is in list then check if username's password equals to password
if (Accounts.AccountList.containsKey(userID)){
String userPassword = Accounts.AccountList.get(userID).get("password");
IsLoginSuccessful = true;
}
That second ".get" gives error like "cannot find symbol". Why does it take the hashmap as an object element? Also if you have another way to store these datas without hashtable and check the password etc. Show me please thank you.

To get the keys you would do
Set<String> keys = AccountList.keySet();
And you should declare your map as
Map<String, Map<String,String>> accountList = new HashMap<>();
Map<String,String> data = new HashMap<>();
But it would be best if you would declare a user class and put that in the map.
class User {
private String username;
private String password;
...
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
Map<String, User> accountList = new HashMap<>();
You could then use defined getters (e.g. user.getPassword(),
user.getUsername()) to retrieve the information.
Then it might be used as follows:
String username = get_from_console.
User user = accountList.get(username);
String password = user.getPassword();

Related

Issues with object oriented java code and firebase

Cut to the chase:
I've got a class User, which holds an instance of Security:
public class User {
private long id;
private String name;
Security security;
public User(String nname, String password, String userName, String email) {
this.id = 0;
this.name = nname;
this.security = new Security(password, userName, email);
}
/**
* getters and setters
*/
}
Yes, the id is currently temporary for testing, and Security has a very similar format.
Next I run this code for setting up my firebase entry:
FirebaseApp app = FirebaseApp.initializeApp(options);
this.db = com.google.firebase.cloud.FirestoreClient.getFirestore(app);
ApiFuture<WriteResult> collectionsApiFuture =
db.collection("users").document(user.getName()).set(user);
System.out.println(collectionsApiFuture.get().getUpdateTime().toString());
And I use this as my test data:
FirebaseInitialise testFirebase = new FirebaseInitialise();
User tempUser = new User("Ollie", "123", "OlliesRealm", "email#mail.com");
testFirebase.initialize(tempUser);
However, when I run the code, the relation appears in the firestore application as:
id: 0
name: "Ollie"
security:
unlocked: true
userName: "OlliesRealm"
I would like it to either properly hold the full information for security, which it seems to be unable to do, or to just hold an ID of it without actually having the security info stored in user.
If anyone could suggest anything or help me out that would be greatly appreciated!!
To be able to get Security as a full object you just need to save it specifically when uploading on the Firestore database.
#Override
public String createUser(user user) {
String id = UUID.randomUUID().toString();
DocumentReference document = userCollection.document(id);
Map<String, Object> data = Maps.newHashMap();
data.put("name", user.getName());
data.put("security", user.getSecurity());
try {
document.set(data).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
If you want to have them separately you just need to create a different collection for the Security and save it there with something like that:
#Override
public String createUser(user user) {
String id = UUID.randomUUID().toString();
DocumentReference userDocument = userCollection.document(id);
DocumentReference securityDocument = SecurityCollection.document(id);
Security temp = user.getSecurity();
Map<String, Object> userData = Maps.newHashMap();
Map<String, Object> securityData = Maps.newHashMap();
userData.put("name", user.getName());
userData.put("security", user.getSecurity());
securityData.put("username", security.getUserName());
securityData.put("password", security.getPassword());
securityData.put("email", security.getEmail());
try {
userDocument.set(userData).get();
securityDocument.set(securityData).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}

Display contents of an array in a listview

Im making a project where the list items are contents with multiple attributes (username and passoword). I want to make the listview only display the usernames and once the username is clicked it would show the users password in a toast message. Im new to programming so i would need a few hints.
I managed to make the class and add 2 users to the array list.
Any ideas on how i could make the listview only display the usernames and then the password once the username is clicked?
Thanks in advance :)
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
static class user {
public String username;
public String password;
public user(String name, String pass) {
username = name;
password = pass;
List<user> userList = new ArrayList<>();
userList.add(new user("Tom", "Hello123"));
userList.add(new user("Jack", "Hell1"));
}
}
}
So, it might look like just adding a if statement and depending on what you are useing as a check box, then you could edit accordingly.
if(username == "Tom" ){
Toast.makeText(this, "Your password is: Hello123", LENGTH_LONG);
} else if (username == "Jack"){
Toast.makeText(this, "Your password is: Hell1", LENGTH_LONG);
} else {
Toast.makeText(this, "Invalid or error found", LENGTH_LONG);
}

how to retrieve the attribute "unicodePwd" in Active Directory through java programming

First of all, I apology for my bad english. I'm brazilian, so if there is any mistakes at the text, please, just disconsidered.
I read a lot of articles here about retrieving the attribute "unicodePwd" in Active Directory, but none of then actually helped me out.
Well, why do I need that information? I'll explain:
I have here some java routines that unify user information from differents systems one to another.
This routines get the information needed in a main Oracle Database and set the information in another Databases (Oracle and MySQL, basically).
For example: We have a private cloud system, that runs in a CentOS Linux OS, that has it own MySQL Database. To unify the users informations, including the users passwords, we get the information from the main Oracle Database and set do this system's MySQL Database, to unify user details and login information.
All the routines that i have here are working and there's no problems, but now we have a new challenge.
We need to do the same unification with ours Active Directory users, getting the information needed in this main Oracle Database and then setting all the information into Active Directory users, including the users passwords.
I already updated the password succesfully in Active Directory users, but I don't want that the password get updated everytime that this java routine runs, but only when the password changes in the main Oracle Database.
Example: When one of the users change the password in the main Oracle Database, the java routine gets this user information to set then in the same user in Active Directory. To do that properly, the routine gets the same information in Active Diretory, then it compares both passwords (Oracle's password and Active Diretory's password) and finally, if the password is different, the routine will update it, but if the password is not different, the routine will do nothing.
That is why i need to retrieve the attribute "unicodePwd" in Active Directory.
Here is some of my code:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import org.apache.commons.mail.EmailException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class ldapQuery {
String distinguishedName = "";
String department = "";
String physicalDeliveryOfficeName = "";
String telephoneNumber = "";
String mobile = "";
String title = "";
String sAMAccountName = "";
String unicodePwd = "";
public ldapQuery(String mail) {
try {
final Hashtable<String, String> env = new Hashtable<String, String>();
final String adminName = "CN=MY DOMAIN ADMIN,CN=MY DOMAIN ADMIN FOLDER LOCALIZATION,DC=MY DOMAIN,DC=MY DOMAIN,DC=MY DOMAIN";
final String adminPasswd = "MY DOMAIN ADMIN PASSWORD";
final String ldapUrl = "ldaps://MY ACTIVE DIRECTORY SERVER:636";
final String factory = "com.sun.jndi.ldap.LdapCtxFactory";
final String authType = "simple";
final String protocol = "ssl";
env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
env.put(Context.SECURITY_AUTHENTICATION, authType);
env.put(Context.SECURITY_PRINCIPAL, adminName);
env.put(Context.SECURITY_CREDENTIALS, adminPasswd);
env.put(Context.SECURITY_PROTOCOL, protocol);
env.put(Context.PROVIDER_URL, ldapUrl);
DirContext ctx = new InitialLdapContext (env,null);
SearchControls searchCtls = new SearchControls();
String returnedAtts[] = {"sAMAccountName", "distinguishedName","department", "physicalDeliveryOfficeName", "telephoneNumber", "mobile", "title", "unicodePwd"};
searchCtls.setReturningAttributes(returnedAtts);
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=user)(mail=" + mail +"))";
String searchBase = "DC=MY DOMAIN,DC=MY DOMAIN,DC=MY DOMAIN";
int totalResults = 0;
NamingEnumeration<SearchResult> answer =ctx.search(searchBase, searchFilter, searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult)answer.next();
totalResults++;
Attributes attrs = sr.getAttributes();
if (attrs != null) {
distinguishedName = (String) attrs.get("distinguishedName").get();
department = (String) attrs.get("department").get();
physicalDeliveryOfficeName = (String) attrs.get("physicalDeliveryOfficeName").get();
telephoneNumber = (String) attrs.get("telephoneNumber").get();
mobile = (String) attrs.get("mobile").get();
title = (String) attrs.get("title").get();
sAMAccountName = (String) attrs.get("sAMAccountName").get();
Attribute passwd = attrs.get("unicodePwd");
unicodePwd = unicodePwd + passwd;
if (department == null) {
department = "";
}
if (physicalDeliveryOfficeName == null) {
physicalDeliveryOfficeName = "";
}
if (telephoneNumber == null) {
telephoneNumber = "";
}
if (mobile == null) {
mobile = "";
}
if (title == null) {
title = "";
}
}
}
}
catch (NamingException e){
System.err.println("FAIL MESSAGE: " + e);
}
}
public String ldapSearchResultDistinguishedName() {
return distinguishedName;
}
public String ldapSearchResultDepartment() {
return department;
}
public String ldapSearchResultPhysicalDeliveryOfficeName() {
return physicalDeliveryOfficeName;
}
public String ldapSearchResultTelephoneNumber() {
return telephoneNumber;
}
public String ldapSearchResultMobile() {
return mobile;
}
public String ldapSearchResultTitle() {
return title;
}
public String ldapSearchResultUnicodePwd() {
return unicodePwd;
}
public String ldapSearchResultSAMAccountName() {
return sAMAccountName;
}
}
After running the code, all the variables return the correct information but the variable "unicodePwd", that returns "null", even though the user has a password.
I know about the byte UTF-16LE thing and that the "unicodePwd" field in Active Directory is encrypted, but, as I explained earlier, i need that information decrypted in a String variable.
Any ideias?
Thank you!
I know this is an old question but I stumbled across it as I was also looking for an answer to the same question. I found the answer and thought it might help anybody else who lands here.
According to Microsoft Documentation it would appear that the unicodePwd attribute is NEVER returned by an LDAP search.
In my case, I need to validate that the credentials received are correct. So my plan is to use the username/password received and create a custom LdapContextFactory on the fly with those credentials. If I can contact the server successfully by doing an LdapContextFactory.get and get back an LdapContext then I can be certain that the password supplied was correct. If you don't get it back then you know it's wrong and can take it from there.

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

Testing Forms in Play 2 with Java and JUnit

So, testing in Play is causing me a headache and I'm hoping someone out there will have an answer to my problem.
I need to test my registration system (among many other things), which of course involves the submission of a form on behalf of the user.
My Stripped Down Version of Controller Action - add()
public static Result add() {
String email = form().bindFromRequest().get("email");
String name = form().bindFromRequest().get("name");
String password = form().bindFromRequest().get("password");
String password_confirm = form().bindFromRequest().get("password-confirm");
[stripped out code]
if(!check){
flash("error", "Not a valid email, please use the email address provided by your employer");
return redirect(
routes.UserController.registration()
);
}
else {
String passwordHash = BCrypt.hashpw(form().bindFromRequest().get("password"), BCrypt.gensalt());
// Create unverified User
User newUser = User.create(
form().bindFromRequest().get("email"),
form().bindFromRequest().get("name"),
passwordHash
);
// Generate verification key
String key = newUser.verification_key;
// Send verification email
sendVerificationLink(key);
flash("success", "Thanks for registering! We have sent you an email with a verification link.");
return redirect(
routes.Application.login()
);
}
Here's the JUnit Test I've written.
#Test
public void registerTest() {
running(fakeApplication(), new Runnable() {
public void run() {
String registeredUserName = "bob";
String registeredUserEmail = "bob#gmail.ac.uk";
String registeredUserPass = "secret";
String registeredUserPassConfirm = "secret";
Map<String, String> userData = new HashMap<String, String>();
userData.put("name", registeredUserName);
userData.put("email", registeredUserEmail);
userData.put("password", registeredUserPass);
userData.put("passwordconfirm", registeredUserPassConfirm);
Result r = callAction(routes.ref.UserController.add(), fakeRequest()
.withFormUrlEncodedBody(Form.form(User.class).bind(userData).data()));
assertEquals(r, 200);
}
});
}
Given suitably correct details within the HashMap, r, in my mind, should return OK or 200?
However, I am getting the following... "expected: play.test.Helpers$1#29cd761a but was:<200>"
What is this "play.test.Helpers$1#29cd761a"? It looks like it referencing an object or memory address but I don't know why??
If this is vague in anyway, please just say so and I'll try to elaborate.
Thanks in advance
Yo!
Sussed it!
For anyone else having a momentary brain fart... use the status() method to read the returned result!
Result r = callAction(routes.ref.UserController.add(), fakeRequest()
.withFormUrlEncodedBody(Form.form(User.class).bind(userData).data()));
assertEquals(200, status(r));

Categories