I was following the Play! Framework tutorial on creating a blog. They use JPA instead of EBeans and they use the find() function that extend from play.db.Jpa.Model . I am using EBeans and have extended with play.db.ebean.Model . However, when I use the find() function, it says that no such method exists. I have done some research and have looked here: http://www.playframework.com/documentation/2.0/api/java/play/db/ebean/Model.html
and here: http://www.playframework.com/documentation/2.0/api/java/play/db/ebean/Model.Finder.html
but there is no mention of a simple find() method (there are others such as findId() but I don't see how they can help). Is there an alternative I could use in the Model class? If not, are there any other classes that I could use easily?
EDIT:
The specific part I need to create is a connect() method in the User class. In the tutorial, this is described as:
In the User.java source, add the connect() method:
public static User connect(String email, String password) {
return find("byEmailAndPassword", email, password).first();
}
What other options do I have for this if I can't use find(). Will ebean.find() work?
I am aware of two methods of using find() method of the play.db.ebean.Model.
The first one goes like this:
User user = Ebean.find(User.class, id);
The second method would be something like this:
//define a Model.finder class in the User model class
//The first parameter would be the datatype of the id used, which is String in my case
public static Model.Finder<String,User> find = new Model.Finder<String,User>(String.class, User.class);
User user = User.find.byId(id);
Since your query fetches data based on two values, your code should look something like this:
User.find.where()
.eq("email", email).eq("password",password)
.findUnique();
Related
I'm developing API using Spring Framework and faced a problem that can be solved by simply adding a necessary logic to every place I have it, but I think that there might be an elegant solution to fix it.
I have the following method in my controller:
#GetMapping("/user/{userId}/permissions")
public List<PermissionDto> list(#PathVariable long userId,
#ModelAttribute #Valid PermissionCriteria criteria) {
return permissionService.list(criteria);
}
The thing is that in dto I have a field called userId. It's made not to have a lot of arguments going to the method of the service. But, I want this user id to be set exactly from path since I use the URL that specifies that we are adding permission exactly to specific user resource. It's doable by making addition line that uses setter in the criteria and sets the value of userId. However, now I should never forget to add this line every time I have a case like that. That's why I decided to move it to InitBinder:
#InitBinder(PERMISSIONS_CRITERIA_NAME)
public void permissionsCriteriaInitBinder(WebDataBinder binder) {
PermissionsCriteria criteria = (PermissionsCriteria) binder.getTarget();
Optional.ofNullable(requestHelper.getUserId())
.map(Long::parseLong)
.ifPresent(criteria::setUserId);
}
It works fine. The user ID is set from the path. However, If I specify request parameter and path variable at the same time, even though userId is set from the path in init binder, it's overridden afterwards before it goes to the controller method. So, this one doesn't solve all the issues.
What I want to find, is someplace where the logic can be put to apply to both init binder(I need it for validation) and controller method. Maybe there is a special type of hook or interceptor or at least something to implement to satisfy this conditions?
I am using Kathatrsis for my REST API. I am also new to the JSONApi spec. I for the life of me cant figure out the url pattern to call the #JsonApiFindAllWithIds method.
For example, say it is annotated as:
#JsonApiFindAllWithIds
public Iterable<ThriftType> findAll(Iterable<String> iterable, QueryParams queryParams) {
And if I call the URL (my resource is called test):
http://localhost:8080/test/1?filter[test][otherId][EQ]=9
I would expect it to hit that method, with an iterable list containing 1 and a query param object containing my filter.
However, it calls my #JsonApiFindOne method described as:
#JsonApiFindOne
public ThriftType findOne(String id) {
Can you tell me the proper url format to hit my #JsonApiFindAllWithIds method?
JsonAliFindAllWithIds is for scenarios where there are more than one id for which value needs to be fetched.
For eg
http://localhost:8080/test/1,2
Would call findallwithids method whereas providing a single
Id would call findone method.
Hope it helps
I've got a simple class which get's validated using the boolean isValid() method, which works and of course the error message is at class/type level.
Here's my simple class:
public class NewPasswordDTO {
#NotNull
public String password;
#NotNull
public String confirmation;
#AssertTrue(message="Passwords must match.")
protected boolean isValid() {
return password.equals(confirmation);
}
}
But what I really want is something like that:
public class NewPasswordDTO {
#NotNull
#Equals("confirmation", message="...")
public String password;
#NotNull
public String confirmation;
}
So the error message would be set at field level and not at class/type level.
Is this possible somehow? Maybe using a custom Validator for that class?
Thanks in advance!
SOLUTION:
Thanks to Gunnar! I've just came up with a nice, universal solution :-). I simply used (means copy & paste) the code from Hibernates #ScriptAssert and ScriptAssertValidator and modified it slightly:
#ScriptAssert:
Add new String field(). (this is where the error message gets appended)
ScriptAssertValidator:
Inside the initialize method, make sure to also save the fieldName and message properties, because we need to access them in the next step
Add this snippet at the bottom of isValid method:
context.buildConstraintViolationWithTemplate(errorMessage)
.addPropertyNode(fieldName).addConstraintViolation();
Also add context.disableDefaultConstraintViolation(); somewhere inside the isValid method to not generate the default error message which else would get appended at class level.
And that's it. Now I can use it like that:
#FieldScriptAssert(lang="javascript", script="_this.password.equals(_this.confirmation)", field="password", message="...")
public class NewPasswordDTO { ... }
You either could use the #ScriptAssert constraint on the class (note that a constraint should always be side-effect free, so it's not a good idea to alter the state of the validated bean; instead you should just check whether the two fieldss match) or you implement a custom class-level constraint.
The latter also allows to point to a custom property path for the constraint violation, which it allows to mark the "confirmation" property as erroneous instead of the complete class.
Simple answer : It is not (unless you implement it) :http://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-summary.html shows all annotation constraints.
Of course you could inject your string as a resource in your class by #producer and so on (which recently is discussed to be removed in jdk8), but you could not use this value for your assert. In reply to the comment:
This was asuming that the nature is a constant string which you would like to use as a string resource.And then of course it is possible to write your own class based on java.lang.string with a #Producer which is then #Inject - able. Though it is certainly not the way I personally would deal with constant strings.
If you’re using the Spring Framework, then as an alternative to the #ScriptAssert using a JSR 223 scripting, you can use the #SpELAssert that uses the Spring Expression Language (SpEL). The advantage is that it doesn’t need any JSR 223 compliant scripting engine which may not be available on some environments. See this answer for more information.
I have been wrestling with this problem for a while. I would like to use the same Stripes ActionBean for show and update actions. However, I have not been able to figure out how to do this in a clean way that allows reliable binding, validation, and verification of object ownership by the current user.
For example, lets say our action bean takes a postingId. The posting belongs to a user, which is logged in. We might have something like this:
#UrlBinding("/posting/{postingId}")
#RolesAllowed({ "USER" })
public class PostingActionBean extends BaseActionBean
Now, for the show action, we could define:
private int postingId; // assume the parameter in #UrlBinding above was renamed
private Posting posting;
And now use #After(stages = LifecycleStage.BindingAndValidation) to fetch the Posting. Our #After function can verify that the currently logged in user owns the posting. We must use #After, not #Before, because the postingId won't have been bound to the parameter before hand.
However, for an update function, you want to bind the Posting object to the Posting variable using #Before, not #After, so that the returned form entries get applied on top of the existing Posting object, instead of onto an empty stub.
A custom TypeConverter<T> would work well here, but because the session isn't available from the TypeConverter interface, its difficult to validate ownership of the object during binding.
The only solution I can see is to use two separate action beans, one for show, and one for update. If you do this however, the <stripes:form> tag and its downstream tags won't correctly populate the values of the form, because the beanclass or action tags must map back to the same ActionBean.
As far as I can see, the Stripes model only holds together when manipulating simple (none POJO) parameters. In any other case, you seem to run into a catch-22 of binding your object from your data store and overwriting it with updates sent from the client.
I've got to be missing something. What is the best practice from experienced Stripes users?
In my opinion, authorisation is orthogonal to object hydration. By this, I mean that you should separate the concerns of object hydration (in this case, using a postingId and turning it into a Posting) away from determining whether a user has authorisation to perform operations on that object (like show, update, delete, etc.,).
For object hydration, I use a TypeConverter<T>, and I hydrate the object without regard to the session user. Then inside my ActionBean I have a guard around the setter, thus...
public void setPosting(Posting posting) {
if (accessible(posting)) this.posting = posting;
}
where accessible(posting) looks something like this...
private boolean accessible(Posting posting) {
return authorisationChecker.isAuthorised(whoAmI(), posting);
}
Then your show() event method would look like this...
public Resolution show() {
if (posting == null) return NOT_FOUND;
return new ForwardResolution("/WEB-INF/jsp/posting.jsp");
}
Separately, when I use Stripes I often have multiple events (like "show", or "update") within the same Stripes ActionBean. For me it makes sense to group operations (verbs) around a related noun.
Using clean URLs, your ActionBean annotations would look like this...
#UrlBinding("/posting/{$event}/{posting}")
#RolesAllowed({ "USER" })
public class PostingActionBean extends BaseActionBean
...where {$event} is the name of your event method (i.e. "show" or "update"). Note that I am using {posting}, and not {postingId}.
For completeness, here is what your update() event method might look like...
public Resolution update() {
if (posting == null) throw new UnauthorisedAccessException();
postingService.saveOrUpdate(posting);
message("posting.save.confirmation");
return new RedirectResolution(PostingsAction.class);
}
I need a way to write a command call that will be executed in compiled code. However, the command will be store in a database as a String because it's configurable by the user. Each command would match a class but there could be multiple commands that need to be executed with input parameters.
How is the best way of handling this?
Example Class that would be called:
public class CreateUser {
protected User user;
public static void create(User user){
CreateUser cu = new CreateUser(user);
cu.newUserFunction();
}
public CreateUser(User user){
this.user = user;
}
public void newUserFunction(){
doSomething();
}
}
Example Method that would call the command:
public void createUser(User user){
dclCommand.createUser(user.getUsername(), user.getPassword());
// Get special commands to run after user is created
List<Command> cmds = this.dbRepository.findCommand(database, Method.CREATE_USER);
for(Command cmd : cmds){
// Here is where the cmd will be executed with input parameters
// In example the command executed would be 'org.example.CreateUser.create(user)'
}
}
The call to 'org.example.CreateUser.create(user)' will be stored in a database and I need to be able to run it from a function that will get it out of the database and call it adding the parameter User.
Have you considered using the Command Pattern?
Basically, you create an interface like
interface DoStuff{
void doIt();
}
Then, for every method that the user could call, you create class that implements that interface. Each implementation^ calls their associate method in the body of their doIt() method. Then, you store each user's chosen implementation class's cannononical name as a string field in the database. When the user logins you fetch than field, instantiate the instance using Class.forName(String), and cast the return to DoStuff. Then, whenever the user's chose method would be called call userStuffDoer.doIt() and their chosen method will be called.
If there is a near infinite number of methods a user could call you will have to use reflection and store class and method names and how to get the method data etc.
^ The implementation classes will need to have empty constructors.
Why don't you implement Command Pattern? You can have the factor to build up the command. This factor would take in the command that you will fetch from database and then based on this command, it would return you a class. You can simply call returnedObj.execute().
For list of commands, you can extend your factory to return command or list of commands based on your inputs.
Your command classes would use "Reflection" to call and execute the method stored in the database.
You could use something like Janino's expression evaluator or embed Groovy. These are especially useful as you do not need to compile any Java code - it is compiled at runtime.
One of the options is to use reflection to create command objects and execute their methods. I would choose it if amount of commands is not so big, and they do not change a lot.
Another soluton would be some JVM scripting language ( I recommend groovy ) which would just evaluate scripts coming from database. This is more flexible and allows for command change on the fly without restarting / redeploying server. ( Used this solution to remote config DSL routers for some 4+ million of customers every night )
Java is not a dynamic scripting language. To accomplish what you are trying to do you'd need to compile the code retrieved from the DB in memory using the JavaCompiler Interface
This should get you pointed in the right direction:
http://www.accordess.com/wpblog/an-overview-of-java-compilation-api-jsr-199/
That being said, be very, very careful about how you approach this. Running user-defined code is always error prone.