Java throwing exception on Play bindFromRequest - java

I'm trying to bind some data from a POST, but for some reason, it keeps throwing an exception. The weird thing though is that I have an almost identical object that is bound just fine. Some of my code is as follows:
public static Result login() {
return ok(
login.render(Form.form(Login.class))
);
}
public static Result authenticate() {
Form<Login> loginForm = Form.form(Login.class).bindFromRequest();
// Do stuff
}
public static Result createUser() {
return ok(createUser.render(Form.form(NewUser.class)));
}
public static Result createUserPost() {
Form<NewUser> newUserForm = Form.form(NewUser.class).bindFromRequest();
// Do stuff
}
public static class Login {
public String userName;
public String password;
public String validate(){
Logger.info("userName: %s, Password: %s", userName, password);
if (User.validate(userName, password) == null){
return "Invalid username or password";
}
return null;
}
}
public static class NewUser {
public String userName;
public String password;
public String validate() {
// TODO: Better error messages
if (Validation.username(userName) == null && Validation.password(password) == null) {
return null;
}
else {
return "The username or password is not valid.";
}
}
}
For some reason, the authenticate method binds the Login class fine, but the createUserPost method doesn't bind the NewUser class (both views are exactly the same with the exception that the Form type is either Login or NewUser). The weirder thing is that if I change the createUser, createUserPost, and the view to use the Login class, it binds just fine.
Does anyone have any idea why this is happening?

So it turns out that for some reason Play (or Java) doesn't like having multiple static classes in the same Java file. Once we refactored the two classes out to their own files, it worked fine.

Related

Java method that adds a given User to a website's list of users, provided that there are no other users with the same userName

I'm trying to create a method called registerUser(User x) method that adds a given User to a website's list of users, provided that there are no other users with the same userName. If there are other users with the same userName, then this method does nothing. I'm also trying to make use of the userWithName(String s) method I already created, which basically finds and returns the user object with the given name if it is in the list of users, and returns null if it isn't there.
I started the registerUser method, but I'm struggling to continue it. I also don't quite understand where I'm supposed to make use of userWithName() in the registerUser() function because it's only purpose is to adds a user provided that there are no other users with the same userName.
public String userWithName(String s) {
for (User u: listofusers) {
if (u.getUserName().contains(s)) {
return u.getUserName();
}
}
return null;
}
public registerUser(User x) {
for (User u: listofusers) {
if (!listofusers.contains(u.getUserName) {
listofusers.add(x);
}
}
}
If I understand what you're asking, I think you have some bugs in the pasted code. You need to search for strings in a list of strings, and users in a list of users. You can't mix the two up.
public String userWithName(String s) {
//gets a list of String usernames from list of users
List<String> usernames = listofusers.stream().map(User::getUserName).collect(Collectors.toList());
if (usernames.contains(s)) {
return s;
} else {
return null;
}
}
public registerUser(User x){
if(!listofusers.contains(x)) {
listofusers.add(x);
}
}
If the Java 8 Stream nonsense to get a list of usernames is intimidating, this is a perfectly viable alternative.
public String userWithName(String s) {
String username = null;
for(User u: listofusers) {
if(u.getUsername().equals(s)) {
username = s;
}
}
return username;
}
If this does not answer the question, please provide more information.
You mean something like this?
public registerUser(User x){
if(userWithName(x.getUserName() == null) {
listofusers.add(x);
}
}
public String userWithName(User X){
for(User u: listofusers){
if(u.getUserName().contains(X.getUserName()){
return u.getUserName();
}
}
/* that means there is not a user of this name, so we add it*/
registerUser(X);
}
public registerUser(User x){
listofusers.add(x);
}

How to get a result from a void method from another class

In Class1 we have a method:
public void check(String username, String password) {
if (username and password are correct) {
message = "checked";
} else
{
message = "not checked";
}
}
In Class2 we have a method doPost and then we do this :
Class1 cl = new Class1();
cl.open();
cl.check(username,password);
cl.close()
In class Error I would like to show the message, which is in Class1. Maybe with one Dispatcher? Which is the most efficiency way to make it?
Surely there are much better ways for that, but if you don't want to change your solution as you are setting a message in Class1, you should be able to access to that message in Class2, so create getter and setter for the message variable and access the message via getter(and setters):
in Class1:
public String setMessage(String message){
this.message=message;
}
public String getMessage(){
return message;
}
public void check(String username, String password) {
if (username and password are correct) {
message = "checked";
} else
{
message = "not checked";
}
}
in Class2:
Class1 cl = new Class1();
cl.open();
cl.check(username,password);
cl.close();
out.println(cl.getMessage());//or anything else(you have access to generated message)
You can throw an exception in check() if the check fails.

Adding methods to AuthenticatedWebSession in Wicket 7 by extension

I'm using Wicket 7 and extending AuthenticatedWebSession as a class called BasicAuthenticatedSession. While I'm doing this, I'd like to add a method that returns some additional information about the authenticated user.
In BasicAuthenticatedSession#authenticate, I get a Sysuser object which is a wrapper for a user in the database. I use some of the information in this object for the authentication, but want to have access to all of the info (firstname, lastname, etc.) throughout the session.
I was expecting to be able to create a new method call getUser which would return this database object to the caller.
However, this method, even though declared public, isn't visible when attempting to call it. I'm not sure if this is something to do with Wicket, or just a general misunderstanding on my part how inheritance works. ;)
BasicAuthenticatedWebSession.java
public class BasicAuthenticatedWebSession extends AuthenticatedWebSession {
public BasicAuthenticatedWebSession(Request request) {
super(request);
}
#Override
protected boolean authenticate(String username, String password) {
Sysuser[] sysusers;
try {
SysuserCriteria userCriteria = new SysuserCriteria();
userCriteria.username.eq(username);
sysusers = Sysuser.listSysuserByCriteria(userCriteria);
} catch (PersistentException e) {
e.printStackTrace();
return false;
}
if (sysusers.length == 0) {
return false;
}
this.username = username;
this.userid = sysusers[0].getId();
return password.compareTo(sysusers[0].getPasswd()) == 0;
}
public Roles getRoles() {
Roles roles = new Roles();
Sysuser[] sysusers;
if (isSignedIn()) {
roles.add("SIGNED_IN");
}
try {
SysuserCriteria sysuserCriteria = new SysuserCriteria();
sysuserCriteria.username.eq(username);
sysusers = Sysuser.listSysuserByCriteria(sysuserCriteria);
for (Object sysuser : sysusers) {
SysroleSetCollection sysroles = ((Sysuser) sysuser).sysrole;
for (Sysrole sysrole : sysroles.toArray()) {
roles.add(sysrole.getRolename().toUpperCase());
}
}
} catch (PersistentException e) {
e.printStackTrace();
}
return roles;
}
public Sysuser getSysuser() {
return sysuser;
}
}
Test.java This class fails to compile as the getSysuser method in BasicAuthenticatedSession is not found.
public class Test {
public Test() {
}
public void foo {
if(BasicAuthenticatedSession.get().isSignedIn()) {
Sysuser sysUser = BasicAuthenticatedSession.get().getSysuser();
System.out.println(sysuser.getFirstname);
}
}
}
Wicket project require specific "override" of static methods, I guess that You return original wicket API session. Edited copy from my project (session is Your classname)
public class BasicAuthenticatedWebSession extends AuthenticatedWebSession {
public static BasicAuthenticatedWebSession get() {
return (BasicAuthenticatedWebSession ) Session.get();
}
...
}
and in XxxxxApplication class
public class MyProject extends AuthenticatedWebApplication
{
...
#Override
public Session newSession(Request request, Response response) {
return new BasicAuthenticatedWebSession (request);
}
}

Sending and receiving an Object from an RMI Server and Client using seralization

I was implementing a banking system and I want to send a ResultSet to the client. But Java shows me an error.
public interface SekelatonInterface extends Remote {
public String test() throws RemoteException; // this is ok it works fine
public ConnectionClass getConnection() throws RemoteException; //shows error on client call
public ResultSet getAllDeposits(Integer CustomerId) throws RemoteException;
}
public class SekelatonImpl extends UnicastRemoteObject implements SekelationInterface {
SekelatonImpl() throws RemoteException{
}
//sekelaton implemeation
public ConnectionClass getConnection() {
try {
dbobject = new ConnectionClass();
dbobject.connectDb();
dbObject.setQuery("select * from cutomer");
return dbobject; //this method is on connection class ,dont be confuse
}
catch(Exception ex)
{
System.out.println("Error :"+ex.getMessage());
}
}
}
public class Server {
public void PackServerandRun(String SecurityFilePath,Integer port,String rmiUrl) {
//do rmi registery stuff and run server
SekelatonImpl databaseObject = new SekelationImpl(); // rebind this object
}
}
cleintstub.test(); //this recive the server message or works fine
cleintStub.getConnection(); //why couldn't i get a ConnectionClass Object ?
When I run client the error I'm seeing is:
Registry Look Up has error Error unmarshaling return header; nested exception is: java.io.EOFException
I want to send a ResultSet
Bad luck, you can't. ResultSet isn't Serializable.
or connection object to the client ,actually the later is no good idea.
It is not only not a 'good idea', it is a completely meaningless idea. You can't send a telephone over a telephone wire. Similarly you can't send a connection over another connection. Let alone the fact that Connection isn't Serializable either.
But, Java shows me an error.
Next time you post a problem report, anywhere, make sure to include the actual problem, including the error message, verbatim, cut-and-pasted, not manually transcribed, along with the relevant section of source code, a line number indication if necessary, and the expected and actual outputs.
catch(){
}
Never ignore an exception. Otherwise you turn debugging into a mere guessing game.
OK i will attempt to answer my own question after i have gone through some research i have solved the problems.
the error was sending un-serialized object.
Since,ResultSet Doesn't support Serialization i have also created a Model class and Return
List of the model class object to the client.By adding Serialization to every class you want to transfer as parameter ,and also including your skeleton implementation serialization ,Note that all the class need to be defined on client side.
public class ConnectionClass implements java.io.Serializable {
}
public interface SekelatonInterface extends Remote ,java.io.Serializable{
public Login getTestClass()throws RemoteException;
public String test() throws RemoteException;
public List<Login> getConnection() throws RemoteException;
public void sayHitoServer(String messages) throws RemoteException;
}
public class SkeletonInterfaceImpl extends UnicastRemoteObject implements SekelatonInterface,Serializable {
//implement all your skeleton methods
}
//this to change result set into model class to transefer it to client
public class Login {
private int Id;
private String Username;
private String Password;
public Login() {
}
public int getId() {
return Id;
}
public void setId(int Id) {
this.Id = Id;
}
public String getUsername() {
return Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public Login(ResultSet resultset){
try{
// resultset.next();
Id = resultset.getInt("LoginId");
Username =resultset.getString("Uname");
Password = resultset.getString("Password");
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Error Setting Up Login"+ex.getMessage());
}
}
}
ALl the above method will work just fine.But,the problem here is i want to bind the list of model class to a jtable model.how can i pass columns suitable for TableModel ?

Is the adapter pattern usable in cases where the different interface methods have varying parameters

I am creating a client side swing app that will have data provided by/from one of many data providers(brokers). The data providers however, have varying ways of perfoming same things e.g.
broker1's login method
public boolean doLogin(String username, String password);
broker2's login method
public int login(String username, String password,String sessionId);
For all providers the set of required actions is the same
e.g
login, getstatus, sendRequest, getData, logOff
(but they have different params and return types)
I took a look at the adapter pattern but am unfortunately not able to use it well as the required methods have different parameters.
Is the adapter pattern usable in this case? if so how?
If not what would be the best way of doing this?
Thanks.
Patterns are general guidelines (starting point) of best practices. Many developers "adapts" the patterns to their needs; the important thing is, then, if you must use a pattern, use it consistently throughout your whole application.
Now, to answer your question; yes the adapter pattern can very well be used in your situation. A possible solution (in the like) could be:
abstract class BrokerAbstract<T> {
private int errCode;
private String errMessage;
abstract public boolean login(String user, String pass, Map<String,Object> options);
abstract public int getStatus(Map<String,Object> options);
abstract public boolean sendRequest(Map<String,Object> options);
abstract public T getData(Map<String,Object> options);
abstract public boolean logOff(Map<String,Object> options);
protected void setError(int code, String message) {
this.errCode = code;
this.errMessage = message;
}
public int getErrorCode() { return this.errCode; }
public String getErrorMessage() { return this.errMessage; }
}
Then
class Broker1 extends BrokerAbstract<Object> {
private OriginalBroker1 original;
public boolean login(String user, String pass, Map<String,Object> options) {
return original.doLogin(user, pass); // ignore options
}
public boolean login(String user, String pass) {
return login(user, pass, null); // third parameters will be ignored
}
public int getStatus(Map<String,Object> options) { /*...*/ return 0; }
public boolean sendRequest(Map<String,Object> options) { /*...*/ return false; }
public Object getData(Map<String,Object> options) {
return original.getData(); // OriginalBroker1.getData():Object
}
public boolean logOff(Map<String,Object> options) {
return original.doLogout((boolean) options.get("clearSession"));
}
public boolean logoff() {
HashMap<String,Object> options = new HashMap<String,Object>();
options.put("clearSession", true);
return logoff(options); // proxy to original method
}
}
Or
class Broker2 extends BrokerAbstract<Integer> {
private OriginalBroker2 original;
public boolean login(String user, String pass, Map<String,Object> options) {
int code = original.doLogin(user, pass, (String) options.get("sessionId"));
if (0 != code) {
setError(code, "Custom error message"); // could use enum here for messages...
return false;
} else {
return true;
}
}
public boolean login(String user, String pass, String sessionId) {
HashMap<String,Object> options = new HashMap<String,Object>();
options.put("sessionId", sessionId);
return login(user, pass, options);
}
public int getStatus(Map<String,Object> options) { /*...*/ return 0; }
public boolean sendRequest(Map<String,Object> options) { /*...*/ return true; }
public Integer getData(Map<String,Object> options) {
return original.getData(options.get("key")); // OriginalBroker2.getData(key:String):int
}
public boolean logOff(Map<String,Object> options) {
return original.doLogout();
}
public boolean logoff() {
return logoff(null); // ignore third parameter
}
}
Of course this is a very general approach. If you know that one method will be receiving strings for all parameters, you could also have a abstract signature like :
abstract public boolean login(String...args);
Then your concrete implementation would be :
abstract class A {
abstract public boolean login(String...args);
}
class B extends A {
public boolean login(String...args) { return this.login(args[0], args[1]); }
public boolean login(String user, String pass) { return original.login(user,pass); }
}
class C {
public void login() {
B b = new B();
b.login("foo", "secret");
// or
b.login(new String[] {"foo", "secret"});
// or !
b.login("foo", "secret", "sessionId"); // will ignore third, but otherwise would still work...
}
}
etc.
My first thought was looking into the facade pattern, which, in my 'Head First Design Patterns' book, is explained in the same chapter as Adapter and compared with a remoted control for home theatre components.
This facade would sit between the client app and the various brokers. So the client wouldn't have to care, which and how many brokers are part of the 'theatre', it just have to 'press the login button' and 'all broker connections are switched on'.

Categories

Resources