Why does my nested POJO return null from a form in Play! 1.x - playframework-1.x

In Play! Framework 1.5.1, why am I getting null back for thingy.Owner ? Shouldn't the automatic binding take care of this?
User class
package models;
#Entity
#Table(name="objtest_user")
public class User extends Model
{
#Required
public String username;
#Password
#Required
public String password;
public String fullname;
public User(String username, String password, String fullname)
{
this.username = username;
this.password = password;
this.fullname = fullname;
}
#Override
public String toString()
{
return this.fullname;
}
}
and this Thingy class that references the User class
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
import play.data.validation.*;
#Entity
public class Thingy extends Model
{
#Required
public String Name;
#ManyToOne
public User Owner;
public Thingy(String name, User owner)
{
this.Name = name;
this.Owner = owner;
}
#Override
public String toString()
{
return Name;
}
}
and this Template form
#{extends 'main.html' /}
#{set title:'Home' /}
<p>Current user = ${currentUser}</p>
#{form #saveThingy(), id:'saveThingy'}
<input type="text" id="thingy.Name" name="thingy.Name"/>
<input type="hidden" id="thingy.Owner" name="thingy.Owner" value="${currentUser}"/>
<input type="submit" id="Save" value="Save"/>
#{/form}
Controller method
public static void saveThingy(Thingy thingy)
{
System.out.println("Name = " + thingy.Name);
System.out.println("Owner = " + thingy.Owner);
thingy.save();
}

Try changing the following line
<input type="hidden" id="thingy.Owner" name="thingy.Owner" value="${currentUser}"/>
To
<input type="hidden" id="thingy.Owner" name="thingy.Owner.id" value="${currentUser.id}"/>
If you check out the docs (https://www.playframework.com/documentation/1.2.x/controllers#params), and look for JPA object binding section, it talks about requiring sub objects to have an id. Play when it finds an ID for an object, it will load the relavent entity via JPA/Hibernate.

Related

Pass multiple list from controller to view

I MVC c# application which has model
public class lstSearchCriteria
{
public List<lstCampaign> cmpList { get; set; }
public List<lstAgent> agentList { get; set; }
}
public class lstCampaign
{
public string campaignName { get; set; }
}
public class lstAgent
{
public string agentShortName { get; set; }
public string agentFullName { get; set; }
}
& controller which returns lstSearchCriteria. I need to display lstCampaign & lstAgent in dropdown list.
In view I am doing
#using QAApplication.Models
#model QAApplication.Models.lstSearchCriteria
<select id="lstCampaigns" multiple="multiple">
#foreach (var item in Model.cmpList)
{
<option >#item.campaignName</option>
}
</select>
<div id="divlstAgents">
<select id="lstAgents" multiple="multiple">
#foreach (var item in Model.agentList)
{
<option >#item.agentShortName</option>
}
</select>
</div>
I am getting below error :The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[QAApplication.Models.lstSearchCriteria]', but this dictionary requires a model item of type 'QAApplication.Models.lstSearchCriteria'.
what could be the best way to pass multiple list to view from controller. Thanks in advance
You are passing List<lstSearchCriteria>, While Views expected model lstSearchCriteria only.

I can't mock property of class

I've just started using spock and I am facing one issue..
public class UserAuthentication {
private UserDAO userDao;
public boolean authenticateUser(String email, String password){
User user = userDao.findUserByEmail(email);
if(password.equals(user.getDecodedPassword())){
return true;
}
return false;
}
}
public interface UserDAO {
User findUserByEmail(String login);
void saveUser(User user);
}
public class User {
private String email;
private String decodedPassword;
public User(String email, String decodedPassword) {
this.email = email;
this.decodedPassword = decodedPassword;
}(...)
Unfortunately my test throw NullPointerException:
import java.text.SimpleDateFormat
import spock.lang.Specification
class UserAuthenticationTest extends Specification {
def "Authenticating correct user" () {
setup:
def email = "email#email.com"
def password = "qwerty1234"
def userDao = Mock(UserDAO)
userDao.findUserByEmail(email) >> new User(email, password)
def userAuthenticator = new UserAuthentication()
userAuthenticator.setUserDao(userDao)
when:
def result = userAuthenticator.authenticateUser(email, password)
then:
1 * userDao.findUserByEmail(email)
result == true
}
}
I got the exception because mock doesn't work when is invoked (userDao.findUserByEmail(email); in UserAuthentication class).
Anyone have some idea why?
When you both mock and verify the returned (from mock) expression should be placed under then block. Here are the docs and below You can find corrected code:
#Grab('org.spockframework:spock-core:0.7-groovy-2.0')
#Grab('cglib:cglib-nodep:3.1')
import spock.lang.*
import java.text.SimpleDateFormat
class UserAuthenticationTest extends Specification {
def "Authenticating correct user" () {
setup:
def email = "email#email.com"
def password = "qwerty1234"
def userDao = Mock(UserDAO)
def userAuthenticator = new UserAuthentication()
userAuthenticator.userDao = userDao
when:
def result = userAuthenticator.authenticateUser(email, password)
then:
1 * userDao.findUserByEmail(email) >> new User(email, password)
result == true
}
}
public class UserAuthentication {
UserDAO userDao;
public boolean authenticateUser(String email, String password){
User user = userDao.findUserByEmail(email);
return password.equals(user.getDecodedPassword());
}
}
public interface UserDAO {
User findUserByEmail(String login);
void saveUser(User user);
}
public class User {
private String email;
private String decodedPassword;
public User(String email, String decodedPassword) {
this.email = email;
this.decodedPassword = decodedPassword;
}
public String getDecodedPassword() {
return decodedPassword;
}
}

how to map sitecore items using glassmapper class in web froms..?

i'm creating demo project there i create Item which contains sub-Item now i want to render these using web controller my code like this
site items created as following image
and my glass mapper code is as:
public static class GlassMapperSc
{
public static void Start()
{
//create the resolver
var resolver = DependencyResolver.CreateStandardResolver();
//install the custom services
GlassMapperScCustom.CastleConfig(resolver.Container);
//create a context
var context = Glass.Mapper.Context.Create(resolver);
context.Load(
GlassMapperScCustom.GlassLoaders()
);
GlassMapperScCustom.PostLoad();
}
public class DesktopHome
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual string LeftRotatorTitle { get; set; }
public virtual string RightRotatorTitle { get; set; }
}
public class GlobalsItem
{
public class HeaderTemplateItem
{
public class NavItem
{
public virtual string Title { get; set; }
public virtual string Link { get; set; }
public virtual IEnumerable<NavItem> Children { get; set; }
}
}
}
}
i'm able to get parent items but not able to get child items please anyone help me to figure out this issue
Define your Modal Class as:
[SitecoreClass]
public class Header
{
[SitecoreInfo(SitecoreInfoType.Url)]
public virtual string About{ get; set; }
[SitecoreField]
public virtual string Home{ get; set; }
[SitecoreField]
public virtual string Services{ get; set; }
[SitecoreField]
public virtual IEnumerable<Header> Links { get; set; }
}
Configuring the application
To configure Glass Mapper is really straight forward. Open or create a Global.ascx file in your project and on the application start add the following code:
protected void Application_Start(object sender, EventArgs e)
{
AttributeConfigurationLoader loader = new AttributeConfigurationLoader(
new string[] { "Glass.Sitecore.Mapper.Demo.Application.Domain, Glass.Sitecore.Mapper .Demo" }
);
Persistence.Context context = new Context(loader, null);
}
your view code will be as:
<div>
<h1>
<asp:Literal runat="server" ID="About" />
</h1>
<div class="body">
<asp:Literal runat="server" ID="Home" />
</div>
<div class="links">
<asp:Repeater runat="server" ID="links">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li><a href='<%# DataBinder.Eval(Container.DataItem,"Url") %>'>
<%# DataBinder.Eval(Container.DataItem,"Services") %></a> </li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
Next lets look at the code behind page, for simplicity everything is going in the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
ISitecoreContext context = new SitecoreContext();
DemoClass item = context.GetCurrentItem<DemoClass>();
title.Text = item.Title;
body.Text = item.Body;
links.DataSource = item.Links;
links.DataBind();
}

Lazy loading in TomEE is not working as expected

Entity's lazy property is always returning null value in TomEE, but working in Glassfish 3 as expected. Is there any listener i am missing to include in web.xml or something else? How to fetch lazy property?
Here is the source code:
AppGroup.java:
package uz.mf.javaee6app;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class AppGroup implements Serializable {
#Id
#GeneratedValue
private Long id;
private String name;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
AppUser.java:
package uz.mf.javaee6app;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
*
* #author ravshan
*/
#Entity
public class AppUser implements Serializable {
#Id
#GeneratedValue
private Long id;
private String name;
private List<AppGroup> roles;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<AppGroup> getRoles() { return roles; }
public void setRoles(List<AppGroup> roles) { this.roles = roles; }
}
I'm skipping AppUserFacade stateless bean and UserManager CDI bean, there's nothing special. and the last users.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Selected user: #{userManager.selectedUser.name}
<h:dataTable value="#{userManager.selectedUser.roles}" var="role">
<h:column>#{role.name}</h:column>
</h:dataTable>
</h:body>
</html>
UserManager.java:
package uz.mf.javaee6app;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class UserManager implements Serializable {
private AppUser selectedUser;
public AppUser getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(AppUser selectedUser) {
this.selectedUser = selectedUser;
}
}
Selected user is being set by another view.
I'd bet the problem is that somehow your Entity is getting detached prior to accessing the lazy loaded field. Be sure to check your transaction attributes to ensure that your context is still active when you are trying to get lazy loading working.

play 2.0 templates html select with if statement in a map

I want to create a <select> without using the helpers (because the select helper is generating a lot of html)
So, I get a list of cities from the Controller like:
public static List<City> getAllSortedByNameAsc() {
List<City> cities = new ArrayList<City>();
cities.addAll(City.find.orderBy("name").findList());
return cities;
}
In my template, I create the options with this code:
#cities.map { city =>
<option value="#city.id">#city.name</option>
}
which works, but I also want to have the chosen city as selected value. I tried several things like this:
#cities.map { city =>
<option value="#city.id" selected="#if(offerForm("city.id").value == city.id){selected}">#city.name</option>
}
But that doesn't work. Can anyone give me a hint?
Configuration File: application.conf
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ebean.default="models.*"
Controller Class => Application.java
package controllers;
import play.*;
import play.mvc.*;
import models.City;
import play.data.Form;
import views.html.*;
public class Application extends Controller {
final static Form<City> cityForm = form(City.class);
public static Result index() {
City pune=new City();
pune.name="pune";
pune.save();
City mumbai=new City();
mumbai.name="mumbai";
mumbai.save();
City city=City.get(2L);
return ok(index.render(cityForm.fill(city),City.all()));
}
}
Model Class => City.java:
package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.ebean.Model;
import java.util.List;
import com.avaje.ebean.validation.NotNull;
#Entity
public class City extends Model{
#Id
public Long id;
#NotNull
public String name;
public static Finder<Long, City> find = new Finder(Long.class, City.class);
public static City get(Long id){
return find.byId(id);
}
public static List<City> all() {
return find.all();
}
}
Template File => index.scala.html
#(cityForm: Form[City],cities: List[City])
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<div>
<select>
#for(city <- cities){
<option value="#city.id" #{if(city.id.toString().equals(cityForm("id").value)) "selected='selected'"}/>#city.name</option>
}
</select>
</div>
</body>
</html>
I'm not positive about how the type mapping is working, but I would try
#cities.map { city =>
<option value="#city.id" selected="#if(offerForm("city.id").value.equals(city.id)){selected}">#city.name</option>
}
rather than using the == operator.
You should also consider whether the helper has a good reason for generating all that HTML. It's generally a pretty smart framework.