Accessing variables from another classes with setter and getter JAVA - java

This is a very simple example of my project which is a lot more bigger in scale.
Tasks:
The password will be set at the setpassword method.
The getpassword method will return the password.
The password is called at sendmail class in order to be send via email to the user to log in with the new credentials.
But When I run the whole code everything works except that the sendmail class won't access the password from the getpassword method in users class.
I put a simple version of my code:
users class >>>>>
public class users {
private String password;
public users (){}
// GETTING PASSWORD
public String getpassword(){
return password;
}
// SETTING PASSWORD
public void setapassword(String password){
this.password=password;
}
}
Signup class>>>>>>
public class signup {
public void signsup(){
users user1 =new users();
user1.setapassword("player");
sendmail mail1 =new sendmail();
mail1.Sendsmail();
}
}
sendmail class>>>>
public class sendmail {
public void Sendsmail(){
users user1 =new users(); // object
user1.getpassword(); //getting password
System.out.println(user1.getpassword()); // If print here I get null
}
}
Main signup Class>>>>
public class SignupMain {
public static void main(String[] args) {
signup signup1= new signup();
signup1.signsup();
}
}

The user1 object from your signup class and your sendmail class are different. Surely their variable is named the same way but they refer to different Objects. To access the password from the user you have to pass the user to the sendmail class e.g.:
Signup.java
public class signup
{
public void settingPassowrd()
{
users user1 = new users();
user1.setapassword( "player" );
sendmail mail1 = new sendmail();
mail1.Sendsmail(user1);
}
}
with:
public class sendmail
{
public void Sendsmail(user usr)
{
usr.getpassword(); // getting password
System.out.println( usr.getpassword() ); // will be the proper value from now on.
}
}

Please follow the standard coding conventions. I changed your code with standard coding conventions. just copy paste it , it will work
Users class
public class Users {
private String password;
public users (){}
// GETTING PASSWORD
public String getpassword(){
return password;
}
// SETTING PASSWORD
public void setapassword(String password){
this.password=password;
}
}
Signup class
public class Signup {
public void settingPassowrd(){
Users user1 =new Users();
user1.setapassword("player");
SendMail mail1 =new SendMail(user1);
mail1.Sendsmail();
}
}
SendMail class
public class SendMail {
private Users user1;
SendMail(Users user1){
this.user1 = user1
}
public void sendMail(){
user1.getpassword(); //getting password
System.out.println(user1.getpassword()); // If print here I get null
}
}
Main class to test the code
public class SignupMain {
public static void main(String[] args) {
Signup signup1= new Signup();
signup1.settingPassowrd();
}
}

Problem is that in your sendmail class you create a new user users user1 =new users(); --> so you don't access the user you previously created, but you create a new one which obviously does not have a password.
Instead, pass your user to the sendmail function in the signup class:
public void settingPassowrd(){
users user1 =new users();
user1.setapassword("player");
sendmail mail1 =new sendmail();
mail1.Sendsmail(user1);
}
and in class sendsmail:
public void Sendsmail(users user) {
System.out.println(user.getpassword());
}
By the way, I suggest you read some coding guidelines for Java. for example:
Class names should always start with a capital letter
Class names are usually singular (class users --> class User)
Method names always start with a lowercase letter and use camelCase (getpassword() --> getPassword())

Related

Testing Open-Close principle in Java

To demonstrate Open/Closed principle of SOLID principle, I implemented the following code.
Code:
interface IFaculty{
void admin();
}
class ITFac implements IFaculty{
#Override
public void admin() {
System.out.println("IT Fac Admin");
}
}
class MedFac implements IFaculty{
#Override
public void admin(){
System.out.println("Med Fac Admin");
}
}
class University{
public void adminFaculty(IFaculty iFaculty){
iFaculty.admin();
}
}
To test the above code, I tried to call the adminFaculty() method in the main method of main class as follows.
Code:
public class Main {
public static void main(String[] args) {
University u1 = new University();
u1.adminFaculty(); // cannot call this method without passing parameters
}
}
But I cannot call the method without passing the relevant parameter: an object of IFaculty. But I cannot do so. Does anybody knows how to call the adminFaculty(), from the main method? or any way to call the adminFaculty() and run the code to give relavent output.?
Thank you.
From your question I assume you want to be able to call adminFaculty() and always use the same faculty. For that, don't pass the faculty to the method but keep a reference in University. You can also add a default faculty.
class University {
private IFaculty faculty;
//default configuration of the university: it has a medical faculty
public University() {
this(new MedFac());
}
//allows to create a university with another faculty type
public University( IFaculty faculty) {
this.faculty = faculty;
}
public void adminFaculty(){
faculty.admin();
}
}
Now you can use it like this:
University medicalUni = new University();
medicalUni.adminFaculty();
University anotherMedicalUni = new University(new MedFac());
anotherMedicalUni.adminFaculty();
University itUni = new University(new ITFac());
itUni.adminFaculty();
Note that you always need an implementation of IFaculty like MedFac or ITFac. Of course I now could add a new faculty without having to change University:
class TechFac implements IFaculty{
#Override
public void admin() {
System.out.println("Tech Fac Admin");
}
}
University techUni = new University(new TechFac());

Java:Calling method, initialized in one class, gives Nullpointerexception in other class

I defined a Logininfo class to store the email and password of a user in. I get the email and password from a Login GUI. There are put into the Logininfo class using setMethods. I'm connecting the programming to a mysql server (mysql is not an issue here). I need the the emailadres and password so I can use it for queries in other GUI's later on.
This is the Logininfo class
public class Logininfo {
public static Emailadres emailadres = new Emailadres();
public static Password password = new Password();
public static class Emailadres
{
private String emailadres;
public Emailadres()
{
emailadres = " ";
}
public void setEmailadres(String emailadres)
{
this.emailadres = emailadres;
}
public String getEmailadres()
{
return(emailadres);
}
}
public static class Password
{
private String password ;
public Password()
{
password = " ";
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return(password);
}
}
}
In the login GUI I use the setMethod to store the emailadress and password.
public class Login extends javax.swing.JFrame {
Logininfo logininfo;
Logininfo.Emailadres emailadres = new Logininfo.Emailadres();
Logininfo.Password password = new Logininfo.Password();
private boolean validate_login(String email,String wachtwoord) {
emailadres.setEmailadres(email);
wachtwoord.setPassword(password);
Later on I try to retrieve the emailadress and password in another class.
public class Account extends javax.swing.JFrame {
Logininfo logininfo;
Logininfo.EmailAdres emailadres;
Logininfo.WachtWoord password;
emailadres.getEmailadres(email);
password.getPassword(password);
I get a Nullpointerexception here. I know that you have to make a new instance of Logininfo in the Login GUI screen. However in the Account class you can't make another new instance. Are public class not supposed to be used for this and should I use something else?
Any help would be appreciated
email_adres in your Login class is an instance field of that class, and is completely unrelated to emailadres instance field of Account class. The two pointers point to different places in memory.
If you want the instance of Account to have that data from Login instance, you have to give it to it somehow.

How to get text from JTextField, convert to a string, and use this string in a different java public class

I have a GUI that has 2 JTextFields- EmailLoginField and jPasswordField1. Ill just discuss the EmailLoginField and just duplicate what is recommended on jPasswordField1 too.
So heres some GUI code:
package p;
imports ...
public class EmailLoginGUI extends javax.swing.JFrame {
public EmailLoginGUI() {
initComponents();
}
private void initComponents() {
...
EmailLoginField = new javax.swing.JTextField();
}
...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
EmailMainGUI open = new EmailMainGUI();
open.setVisible(true);
This next code snippet is what I have tried to do to get the text from the JTextField EmailLoginField in EmailLoginGUI.java
public String getEmailLoginField(){
return EmailLoginField.getText();
}
public String getjPasswordField(){
return jPasswordField1.getText();
}
Here is the next part (not assuming the code immediately above is correct). This next code is an entirely different public class, which same package of course. Here is what I have tried it should look at the EmailLoginGUI class and get the JTextField content, eventually storing it as a String.
PLEASE NOTE: the final strings that contain the JTextField content MUST NOT be inside the SendEmail(EmailLoginGUI c1, EmailLoginGUI c2){. They should be just outside of it just inside public class SendEmail { this is so that they can be used by other code later.
package p;
imports ...
public class SendEmail {
JTextField userTF;
JPasswordField passPF;
SendEmail(EmailLoginGUI c1, EmailLoginGUI c2){
userTF.setText(c1.getEmailLoginField());
passPF.setText(c2.getjPasswordField());
}
public String user(){
return userTF.getText();
}
public String pass() {
return passPF.getText();
}
...
SendEmail(...) {
Properties props = new Properties();
...
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return new javax.mail.PasswordAuthentication(user(), pass()); //This is where the final strings need to go.
}
});
Hopefully what I am trying to do is clear:
Get the content from JTextField created in EmailLoginGUI.java. Get this into SendEmail.java. Its final type should be String and is 'just on the inside' of the public class SendEmail. I have had everything from NullPointerException to Cannot find symbol for hours! Think I've been attempting it for so long that I could benefit from some fresh eyes!
Help would be greatly appreciated.
In SendEmail class create Constructor which has an argument of user input
SendEmail(String userInput) {
//Your Code
}
In EmailLoginGUI create
String userInput = EmailLoginField.getText().toString();
SendEmail sendemail = new SendEmail(userInput);
This method works I have used it. Hope it helps.
I realised both the security risk and how a dialogue would be easier, however I don't have time to go back to change it really. I have already coded the listener too so that's not a problem. But yes that's what I want to do! Where am I going wrong?
Then you need to implement some kind of Observer Pattern.
Start by defining the expected operations that the login view might generate, for example, it's reasonable to expect that the user can either accept or cancel the view
public interface EmailLoginListener {
public void emailLoginWasAccepted(EmailLoginGUI gui);
public void emailLoginWasCanceled(EmailLoginGUI gui);
}
Update the view to provide support for the listener
public class EmailLoginGUI extends javax.swing.JFrame {
private List<EmailLoginListener> listeners;
public EmailLoginGUI() {
initComponents();
listeners = new ArrayList<>(25);
}
//...
public void addEmailLoginListener(EmailLoginListener listener) {
listeners.add(listener);
}
public void removeEmailLoginListener(EmailLoginListener listener) {
listeners.add(listener);
}
protected void fireLoginWasAccepted() {
for (EmailLoginListener listener : listeners) {
listener.emailLoginWasAccepted(this);
}
}
protected void fireLoginWasCanceled() {
for (EmailLoginListener listener : listeners) {
listener.emailLoginWasCanceled(this);
}
}
}
In your action handlers for your buttons on the EmailLoginGUI view, trigger the required event...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
fireLoginWasAccepted();
}
Remember, you should also do this for the cancel operation if you have one.
Now, when you create an instance of EmailLoginGUI, make sure you also register a EmailLoginListener with it
EmailLoginGUI loginView = new EmailLoginGUI();
loginView.addEmailLoginListener(new EmailLoginListener() {
#Override
public void emailLoginWasAccepted(EmailLoginGUI gui) {
gui.dispose();
String email = gui.getEmailLoginField();
String password = gui.getjPasswordField();
EmailMainGUI open = new EmailMainGUI();
open.setCredentials(email, password);
//...
open.setVisible(true);
}
#Override
public void emailLoginWasCanceled(EmailLoginGUI gui) {
// Exit the program?
gui.dispose();
}
});
//...
loginView.setVisible(true);
This will require you to either change the constructor of EmailMainGUI to accept the email and password or a method to pass that information to the class (as I've demonstrated above)
Finally change SendEmail to accept String values instead of your gui components
public class SendEmail {
String email;
String password;
SendEmail(String email, String password) {
this.email = email;
this.password = password;
}
public String user() {
return email;
}
public String pass() {
return password;
}
}

Sending Text Field values from a swing class to another class

So, i'm building a login form in java with swing.
and i did this test when login button is clicked
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String username = jTextField1.getText();
String password = jTextField2.getText();
if (username.equals("Admin")&&password.equals("Admin")) {
//Launch admin panel
AdminGui admin = new AdminGui();
admin.setVisible(true);
}
else {
//Some code
}
}
As you see if the username = Admin and the passowrd is also Admin AdminGui will launch, but i want this test to be performed at another class.
How could i send the textfield values from this class to another ?
First option is to send it using the constructor like:
AnotherClass ac = new AnotherClass (yourInput);
or:
AnotherClass ac = new AnotherClass (yourInput);
ac.setYourInput(yourInput);
You could make a Utility-class which you should do, because of the MVC-pattern:
public static class YourUtilityClass{
public static boolean checkLogin(String username, String password){
if(username.equals("Admin") && password.equals("Admin")){
return true;
}else{
return false;
}
}
And in your GUI in your actionPerformer-method you have to do something like that:
boolean loginCorrect = YourUtilityClass.checkLogin(username,password);
if(loginCorrect){
//login was okay and you can load the AdminGui
}else{
//notCorrect
}
Create another class, called maybe UserService, e.g.
public class UserService {
public boolean isValidLogin(String username, String password) {
return username.equals("Admin") && password.equals("Admin");
}
}
Create an instance UserService in your class which has jButton1ActionPerformed method. e.g
Note if you have another class that creates the view you should really pass this on instead with a getter/setter method.
private UserService userService = new UserService();
Then call in your jButton1ActionPerformed() method
if (userService.isValidLogin(username, password)) {

In Play 2 framework (Java), how to add User object to session after authentication

I looked at the "zentasks" sample code to learn some basic user login and security stuff. The Appication controller has an authenticate method, and during that method the User.authenticate method is called. Here are a couple code snippets from those links:
public static Result authenticate() {
Form<Login> loginForm = form(Login.class).bindFromRequest();
if(loginForm.hasErrors()) {
return badRequest(login.render(loginForm));
} else {
session("email", loginForm.get().email);
return redirect(
routes.Projects.index()
);
}
}
...
public static class Login {
public String email;
public String password;
public String validate() {
if(User.authenticate(email, password) == null) {
return "Invalid user or password";
}
return null;
}
}
As you can see, if it authenticates (ie, finds a User object), the authenticate method adds "email" to the session. I'd like to add the full user object instead, but in the controller action, where I have the session, I don't have the User object. I don't want to requery the database, I'd like to use the same User object that was just found in Login.validate. What's a good way to do that?
Is there a reason you can't simply add a field to your login class?
public static class Login {
public String email;
public String password;
public User user;
public String validate() {
user = User.authenticate(email, password);
if(user == null) {
return "Invalid user or password";
}
return null;
}
}
Not that this will necessarily help you, looking at the API it seems you can't add an object to the session, only Strings.
http://www.playframework.org/documentation/api/2.0.4/java/play/mvc/Http.Session.html

Categories