EJB session bean does not initialize properly (NameNotFoundException) - java

I am having trouble figuring out why an EJB session bean is not working. The actual error message is an EJBException: NameNotFoundException, but that is not a very illuminating message.
I have traced it down to a exactly what line causes the problem, but have not figure out why. So, I wanted to create a session bean to keep track of the input values from a form.
A slimmed down version of the code is:
public class rrpInputField {
public boolean isRequired;
public int maxLength;
public String inputValue;
public String displayValue;
public String formatMask;
public rrpInputField() {
isRequired = false;
maxLength = 64;
inputValue = "";
displayValue = "";
formatMask = "";
}
}
I then created a interface dohicky...
#Local
public interface Test1 {
public void setAction(String action);
public String getAction();
public void setName(String name);
public String getName();
}
Then I created the test bean itself...
#Stateful
public class Test1Bean implements Test1 {
private String action;
private rrpInputField name;
#PostConstruct
public void initialize() {
action = "initalValue";
//name.currentValue = "TestValue";
#Override
public void setAction(String action){ this.action = action; }
#Override
public void getAction() { return this.action; }
#Override
public void setName(String name) { this.name.currentValue = name; }
#Override
public String getName() { return this.name.currentValue; }
}
In my test servlet I have
#EJB
private Test1 t1;
If I un-comment the one line in the bean initialize method in the bean definition I get the failure. So I know it has something to do with that.
//name.currentValue = "TestValue";
If I leave it commented out, as soon as I code t1.getName("New Value") in the servlet I'll get the same error.
If I leave it commented it out, then the bean works as anticipated - I can initialize, and use setAction and getAction just fine.
I am fairly sure the rrpInput class is correct, because I can code in the servlet:
rrpInputField f1 = new rrpInputField();
f1.currentValue = "TestValue";
I figure it must have something to do with my input field class, but I have had no luck figuring out what.

I really don't understand why, but I got it to work by adding a "new" thingie tin the initialize method of the Table1Bean.
#PostConstruct
public void initialize() {
action = "initialValue";
name = new rrpInputField();
name.currentVAlue = "TestValue;
}
If someone could explain why I had to do this, it would be illuminating.

Related

JMockit - Unexpected invocation

I have a simple implementation using JMockit for unit test. The implementations are as following
Team class
public class Team {
private TeamLeader teamLeader;
public Team(TeamLeader teamleader) {
this.teamLeader = teamleader;
}
public boolean hasDiscussion() {
System.out.println("Discussion is hold by " + teamLeader.getName());
Discussion discussion = new Discussion();
return discussion.start();
}
}
TeamLeader class
public class TeamLeader {
private String name;
public TeamLeader(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Discussion class
public class Discussion {
public boolean start() {
return false;
}
}
Then, I have a unit test to test function hasDiscussion as following
#RunWith(JMockit.class)
public class TeamTest {
private Team team;
#Test
public void hasDiscussion(#Mocked TeamLeader teamLeader, #Mocked Discussion discussion) {
new Expectations() {{
teamLeader.getName(); result = "teamleader";
discussion.start(); result = true;
}};
team = new Team(teamLeader);
boolean actualResult = team.hasDiscussion();
new Verifications() {{
assertThat(actualResult, is(true));
}};
}
}
When executing the test, I got the following error
Unexpected invocation of:
entity.Discussion#Discussion()
on instance: entity.Discussion#7b70deb2
when was expecting an invocation of:
entity.Discussion#start()
on mock instance: entity.Discussion#6f93ad02
mockit.internal.UnexpectedInvocation: Unexpected invocation of:
entity.Discussion#Discussion()
on instance: entity.Discussion#7b70deb2
when was expecting an invocation of:
Any ideas for this sort of problem?
This happened because your hasDiscussion method was creating a new instance of Discussion class, and in this case, you can’t mock it.
To solve this you can receive the Discuss class as a parameter of the method and send the mock, our inject the Discuss class in Team class constructor.

Simple button code using interface

I'll write the code first and ask my question below
Below is my main class
public class Application {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
runApp();
}
});
}
public static void runApp() {
Model model = new Model();
View view = new View(model);
Controller controller = new Controller(view, model);
view.setLoginListener(controller);
}
}
Below is my another class
public class LoginFormEvent {
private String name;
private String password;
public LoginFormEvent(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Below is my controller class
public class Controller implements LoginListener {
private View view;
private Model model;
public Controller(View view, Model model) {
this.view = view;
this.model = model;
}
#Override
public void loginPerformed(LoginFormEvent event) {
System.out.println("Login event received: " + event.getName() + "; " + event.getPassword());
}
}
Below is my LoginListener interface
public interface LoginListener {
public void loginPerformed(LoginFormEvent event);
}
Lastly below is my view class which I have just deleted the JFrame code for simplicity.
public class View extends JFrame implements ActionListener {
private Model model;
private JButton okButton;
private JTextField nameField;
private JPasswordField passField;
private LoginListener loginListener;
#Override
public void actionPerformed(ActionEvent e) {
String password = new String(passField.getPassword());
String name = nameField.getText();
fireLoginEvent(new LoginFormEvent(name, password));
}
public void setLoginListener(LoginListener loginListener) {
this.loginListener = loginListener;
}
public void fireLoginEvent(LoginFormEvent event) {
if(loginListener != null) {
loginListener.loginPerformed(event);
}
}
}
It is a standard button coordinating code so you guys probably won't even need to read my code to answer my question.
So I know how to write this code and this is how I write it when I want a button to do call some action. But when I try to get my logic around it to understand 'why' it works, I get very confused.
so when I call view.setLoginListener(controller) I'm obviously expecting some kind of LoginFormEvent.
Then when I click the button, in the view class, new LoginFormEvent is constructed.
But then how is the constructed LoginFormEvent within the view class be set as the parameter of expected LoginFormEvent in controller class when there's not really any connection between the two classes except that I have defined view.setLoginListener(controller) in the Application class. This just makes setLoginListener of particular instance of view to expect some kind of LoginListener, meaning it doesn't really have to be the one that I set up in the view class upon a click of a button? But obviously it does have to be because that's how the code is run. but why?
You can see the flow as below
Lets start withApplication.java. lets see the method runApp(). It does below things.
Objects of View.java and Controller.java are created.
Controller.java implements LoginListener.java
view.setLoginListener(controller); // this sets the object of
Controller.java in the object of View.java, both these objects are
same as created in step-1.
Now lets move to View.java
It has a field private LoginListener loginListener; and method public void setLoginListener(LoginListener loginListener). This method sets the field loginListener As we see above in step 2 loginListener refers to the same object of Controller.java created in step 1 above.
Now lets move to public void actionPerformed(ActionEvent e) defined in View.java.
It calls fireLoginEvent(new LoginFormEvent(name, password)); See now Object of LoginFormEvent.java is created and it is passed as a parameter to the method fireLoginEvent(LoginFormEvent event).
Now moving to public void fireLoginEvent(LoginFormEvent event)
It has code : loginListener.loginPerformed(event);. From above we know loginListener refers to the one and only object of Controller.java
method public void loginPerformed(LoginFormEvent event) on that very object of Controller.java is called and same object of (again one and only one) LoginEvent.java is passed as parameter.
For such type of scenarios, I would recommend you to note the objects created of each type and connect the flow of calls. Hope above helps you understand the code.

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;
}
}

Java interface access different classes by calling same interface

I want to use java interface in a way that i will make a call defining interface in my other class like 'private SoapURL soapURL;' and than i can access any class's method for example : i want to use login:-
private SoapURL soapURL;
SoapUrl = LoginSoap ();
String nameSpace = soapURL.getMethodName();
String url = soapURL.getUrl();
Is there any way to do something like this. I am sorry i am not very good with Object Oriented principles but if there is a solution for my problem i would like to know it. Thanks in advance.
public interface SoapURL {
public String getNameSpace();
public String getUrl();
public String getSoapAction();
public String getMethodName();
public String getTag();
}
LoginSoap class
public class LoginSoap implements SoapURL {
#Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
#Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
#Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserControl";
}
#Override
public String getMethodName() {
return "UserControl";
}
#Override
public String getTag() {
return "Login Activity";
}
}
SignUpSoap class
public class SignUpSoap implements SoapURL {
#Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
#Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
#Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserRegister";
}
#Override
public String getMethodName() {
return "UserRegister";
}
#Override
public String getTag() {
return "SignUp Activity";
}
}
ResetPasswordSoap class
public class ResetPasswordSoap implements SoapURL {
#Override
public String getNameSpace() {
return "https://host.com/MobileWFC/";
}
#Override
public String getUrl() {
return "https://host.com/MobileWFC/MobileWS.asmx";
}
#Override
public String getSoapAction() {
return "https://host.com/MobileWFC/UserPasswordReset";
}
#Override
public String getMethodName() {
return "UserPasswordReset";
}
#Override
public String getTag() {
return "Forget Password Activity";
}
}
Your implementation looks correct. To make use of it, you can do this in main:
SoapURL reset = new ResetPasswordSoap();
System.out.println(reset.getUrl());
This is a method of minimizing coupling in large systems. And reduces dependency between objects by making use of a common interface for groups of objects that work together. You might be new at Object oriented principles, but you are one step ahead of the game already
To pass it to a function, you do:
public JPanel resetPass(SoapURL reset) {
...
}
// In main:
JPanel resetPassPanel = resetPass(reset);
Just do, for example:
SoapURL example = new LoginSoap();
String a = example.getTag();
a should be equal to "Login Activity"
The main use of Interface is polymorphism, or the ability to perform the same
operation on a number of different objects,
which is exactly what you wanted in your scenario
Your approach is absolutely fine , just a modification needed
private SoapURL soapURL;
//SoapUrl = LoginSoap (); // This line should be replaced with the Below line
soapURL=new LoginSoap();
String nameSpace = soapURL.getMethodName();
String url = soapURL.getUrl();
Since LoginSoap, SignUpSoap,ResetPasswordSoap classes are implemented classes of SoapURL Interface , thus reference variable of SoapURL can store Object of any of these child classes
soapURL=new LoginSoap();//soapURL.someMethod will call method of LoginSoapClass
soapURL=new SignUpSoap();// will call method of SignUpSoap class
soapURL=new ResetPasswordSoap();

Nullpointerexception while setting a bean

I have an action URL after clicking a hyper link like so
/SocialStupendous/GetProfile.action?slno=3&slno=3
In my execute method of ActionClass I have the following code
public String execute() {
int urislno=Integer.parseInt(getServletRequest().getParameter("slno"));
System.out.println(urislno);
bean.setUslno(urislno);
}
I am getting NullPointerException when I am performing bean.setuslno(urislno). Even though urislno is printed properly as 3.
ProfileBean class:
public class ProfileBean {
private int uslno;
public int getUslno() {
return uslno;
}
public void setUslno(int uslno) {
this.uslno = uslno;
}
}
Why is this happening?
The bean is not initialized. You should initialize it somehow in the action
private ProfileBean bean = new ProfileBean();
//and add getter ans setter
the better approach, however is let the container to do it for you. You just need to create a bean configuration in the struts.xml
<bean class="com.yourpackagename.ProfileBean" scope="default"/>
then you would have
private ProfileBean bean;
#Inject
public void setProfileBean(ProfileBean bean) {
this.bean = bean;
}
and you don't need to parse request for parameters, this is already done by the params interceptor which is a part of defaultStack that your action should run. You should create properties in your action to hold parameter values.
private Integer slno;
public Integer getSlno() {
return slno;
}
public void setSlno(Integer uslno) {
this.slno = slno;
}
and the action will look like
public String execute() {
if (slno != null) {
System.out.println(slno)
bean.setUslno(slno);
}
......
return SUCCESS;
}

Categories