JSF backing bean sets the property to null - jsf-2

I am trying access the form backing bean data from by controller bean. The value from form
gets set in the bean but when i am trying to access it from the controller bean the value comes null.The null value is in createTicket method :---> ticketData.getSummary());
/*from data bean everything sets here*/
import java.io.Serializable;
import java.util.Date;
import java.util.List;
#SuppressWarnings("PMD")
#ManagedBean(name = "createTicketModelData")
#SessionScoped
public class CreateTicketModelData implements CreateTicketData, Serializable {
private static final long serialVersionUID = 1L;
protected String incidentType;
private TicketId ticketId;
protected UserId receiverId;
protected String summary;
private String description;
private String asset;
private Date dateTime;
protected Date reported;
private Date dateChangeNeeded;
private String priority;
protected List<Attachment> attachments;
public void setAttachments(final List<Attachment> attachments) {
this.attachments = attachments;
}
protected String orgUnit;
protected String location;
protected String costCenter;
private Type type = Type.INCIDENT;
private String severity;
#Override
public String getAsset() {
return asset;
}
#Override
public List<Attachment> getAttachments() {
return attachments;
}
public String getCostCenter() {
return costCenter;
}
.....//getter seters
----------------------------------------------------------------------
/*this is the controller bean where i am not able to get the form data values*/
#ManagedBean(name = "createTicketBaseBean")
#SessionScoped
public class CreateTicketBaseBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final transient Logger LOGGER = LoggerFactory.getLogger(CreateTicketBaseBean.class);
#ManagedProperty(value = "#{ticketData}")
private transient CreateTicketModelData ticketData;
#ManagedProperty(value = "#{ticketingService}")
transient TicketingService dispatcher;
#PostConstruct
protected void init() {
this.workplaceBean = JSFUtils.findBean("selectWorkplaceComponentBean");
this.selectUserBean = JSFUtils.findBean("selectUserBean");
}
public void createTicket(final ActionEvent event) {
Response response = null;
System.out.println("ticket summary------------" + ticketData.getSummary());
setTicketData();
LOGGER.info("Incident type in ticketdatabean---->" + incidentType);
try {
response = dispatcher.createTicket(ticketData);
} catch (Exception e) {
LOGGER.error(e);
FacesMessageUtil.addGlobalUnexpectedErrorMessage();
}
LOGGER.info("Response is---->" + response.getTicketId());
ticketId = response.getTicketId();
}

Try changing the value in the annotation #ManagedProperty(value = "#{ticketData}") to use the bean name that you have annotated it with "createTicketModelData".

Related

exception is java.lang.IllegalArgumentException: "DataSource must be provided"

while creating a spring batch job that reads data from one table using a reader class and then writes into another table in the same db.
while running the application getting "datasource must be provided" error
The code looks like this
ApplicationConfiguration.java ( configuration class)
#Configuration
#Log4j2
public class ApplicationConfiguration {
#Bean(name="mysqlDS", destroyMethod = "close")
#Qualifier("mysqlDS")
public DataSource getDataSource(#Autowired DBConfiguration dbProperties) {
log.info("Inside getDataSource method");
HikariConfig jdbcConfig = new HikariConfig();
jdbcConfig.setJdbcUrl(dbProperties.getDbURL());
jdbcConfig.setDriverClassName(dbProperties.getDriverClass());
jdbcConfig.setPoolName(dbProperties.getJdbcPoolName());
jdbcConfig.setMaximumPoolSize(dbProperties.getMaxPoolSize());
jdbcConfig.setIdleTimeout(dbProperties.getIdleTimeout());
jdbcConfig.setMinimumIdle(dbProperties.getMinIdle());
jdbcConfig.setConnectionTimeout(dbProperties.getConnectionTimeout());
jdbcConfig.setUsername(dbProperties.getClientKey());
jdbcConfig.setPassword(dbProperties.getClientSecret());
return new HikariDataSource(jdbcConfig);
}
#Bean(name = "jdbcDS")
public JdbcTemplate getJdbcTemplate(#Autowired DBConfiguration dbProperties) {
return new JdbcTemplate(getDataSource(dbProperties));
}
}
DBConfiguration.java ( getting config properties from service)
#Component
#Getter
#Setter
#Configuration
#ConfigurationProperties("some service")
public class DBConfiguration {
private String dbURL;
private String driverClass;
private String jdbcPoolName;
private int maxPoolSize;
private long idleTimeout;
private int minIdle;
private long connectionTimeout;
private String clientKey;
private String clientSecret;
}
BatchConfig.java ( for creating job)
#Configuration
#EnableBatchProcessing
#Log4j2
public class BatchConfig {
#Autowired
DBConfiguration dbProperties;
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Autowired
SWItemReader itemReader ;
#Autowired
SWItemWriter itemWriter;
#Autowired
SWItemProcessor batchProcessor;
#Bean
public Job Job() {
return jobBuilderFactory.get("batch-job")
.incrementer(new RunIdIncrementer())
.flow(Step())
.end()
.build();
}
#Bean
public Step Step() {
return stepBuilderFactory.get("step")
.<Users,Managers>chunk(1)
.reader(itemReader)
.processor(batchProcessor)
.writer(itemWriter)
.build();
}
SWItemReader.java ( reader to read from db)
#Log4j2
public class SWItemReader extends JdbcCursorItemReader<Users> implements ItemReader<Manager> {
#Autowired
DBConfiguration dbProperties;
public ApplicationConfiguration applicationConfiguration;
private static final String QUERY_SELECT_PARTNERS ="select query"
public SWItemReader getItemReader() {
SWItemReader swItemReader = new SWItemReader();
swItemReader.setDataSource(applicationConfiguration.getDataSource(dbProperties));
swItemReader.setSql(QUERY_SELECT_USERS);
swItemReader.setFetchSize(100);
swItemReader.setRowMapper(new UsersRowMapper());
return swItemReader;
}
}
ERROR
Error creating bean with name 'BatchConfig': Unsatisfied dependency expressed through field 'swItemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SWItemReader' defined in file [D:\\git\SWItemReader.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: DataSource must be provided"}
seems like the datasource is not being set properly .
What am i doing wrong here .

java.lang.NoSuchMethodError using JDBI

public class MyApplication extends Application<MyConfiguration> {
final static Logger LOG = Logger.getLogger(MyApplication.class);
public static void main(final String[] args) throws Exception {
new MyApplication().run(args);
}
#Override
public String getName() {
return "PFed";
}
#Override
public void initialize(final Bootstrap<MyConfiguration> bootstrap) {
// TODO: application initialization
bootstrap.addBundle(new DBIExceptionsBundle());
}
#Override
public void run(final MyConfiguration configuration,
final Environment environment) {
// TODO: implement application
final DBIFactory factory = new DBIFactory();
final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "postgresql");
UserDAO userDAO = jdbi.onDemand(UserDAO.class);
userDAO.findNameById(1);
UserResource userResource = new UserResource(new UserService(userDAO));
environment.jersey().register(userResource);
}
I get the the following error at findNameById.
java.lang.NoSuchMethodError: java.lang.Object.findNameById(I)Ljava/lang/String;
at org.skife.jdbi.v2.sqlobject.CloseInternalDoNotUseThisClass$$EnhancerByCGLIB$$a0e63670.CGLIB$findNameById$5()
}
public interface UserDAO {
#SqlQuery("select userId from user where id = :email")
User isEmailAndUsernameUnique(#Bind("email") String email);
#SqlQuery("select name from something where id = :id")
String findNameById(#Bind("id") int id);
}

ENTITY object in the JSF SelectOneMenu is not working

I want to get the instance of the Entity from SelectOneMenu so i can assign the entity variables to some other method. But it is pointing to null.
xhtml code
<h:selectOneMenu value="#{statusReport.projectDetID}" converter="ObjectStringConv" onchange="#{statusReport.retrieveReport()}" >
<f:selectItems value="#{statusReport.listOfProjectDetail}"
var="projectDetail" itemLabel="#{projectDetail.project} #{projectDetail.startDate} - #{projectDetail.endDate}"
itemValue="#{projectDetail}" noSelectionValue="Select the Saved Project"/>
</h:selectOneMenu>
statusReport bean
public class StatusReport implements Serializable {
private ProjectDetail projectDetID;
private List<ProjectDetail> listOfProjectDetail;
public List<ProjectDetail> getListOfProjectDetail() {
listOfProjectDetail = projectDetailFacade.findAll();
return listOfProjectDetail;
}
public void setListOfProjectDetail(List<ProjectDetail> listOfProjectDetail) {
this.listOfProjectDetail = listOfProjectDetail;
}
public ProjectDetail getProjectDetID() {
return projectDetID;
}
public void setProjectDetID(ProjectDetail projectDetID) {
this.projectDetID = projectDetID;
}
public void retrieveReport(){
System.out.println(" Processing .....");
if ( projectDetID == null )
{
System.out.println("The object from Select null");
}
else
{
System.out.println("The object from Select menu" + projectDetID.toString());
}
System.out.println("Generated Data:Completed");
}}
ProjectDetail Entity Bean
package com.jira.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the PROJECT_DETAIL database table.
*
*/
#Entity
#Table(name="PROJECT_DETAIL",schema="weeklyrep")
public class ProjectDetail implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="projectdetail_seq")
#SequenceGenerator(name="projectdetail_seq",schema="weeklyrep",sequenceName="projectdetail_seq", allocationSize=1)
#Column(name="PDETAIL_ID")
private long pdetailId;
private Boolean completed;
#Temporal( TemporalType.DATE)
#Column(name="END_DATE")
private Date endDate;
private Long project;
#Temporal( TemporalType.DATE)
#Column(name="START_DATE")
private Date startDate;
//bi-directional many-to-one association to MajorEvent
#OneToMany(mappedBy="projectDetail",cascade=CascadeType.ALL)
private List<MajorEvent> majorEvents;
//bi-directional one-to-one association to ExecSummary
#OneToOne(mappedBy="projectDetailExec",cascade=CascadeType.ALL)
private ExecSummary execSummary;
public ProjectDetail() {
}
public long getPdetailId() {
return this.pdetailId;
}
public void setPdetailId(Long pdetailId) {
this.pdetailId = pdetailId;
}
public Boolean getCompleted() {
return this.completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getEndDate() {
return this.endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public long getProject() {
return this.project;
}
public void setProject(long project) {
this.project = project;
}
public Date getStartDate() {
return this.startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public List<MajorEvent> getMajorEvents() {
return this.majorEvents;
}
public void setMajorEvents(List<MajorEvent> majorEvents) {
this.majorEvents = majorEvents;
}
public ExecSummary getExecSummary() {
return execSummary;
}
public void setExecSummary(ExecSummary execSummary) {
this.execSummary = execSummary;
}
}
Converter
I don't know if it needs converter, however i don't know how code it.
package com.weeklyreport.converters;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.jira.entity.ProjectDetail;
#FacesConverter(value="ObjectStringConv")
public class ObjectStringConv implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String svalue) {
System.out.print("String version of object is:" + svalue);
return "test";
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object ovalue) {
return ovalue.toString();
}
}
Please help me figure this out. Is there a way we get instance of the entity object like this?
Your converter needs to be written that way so that it can convert between ProjectDetail and String based on an unique identifier of ProjectDetail. Usually entities have an id. You need to use this as String value. Here's a kickoff example without any trivial checks like null and instanceof:
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Convert ProjectDetail to its unique String representation.
ProjectDetail projectDetail = (ProjectDetail) value;
String idAsString = String.valueOf(projectDetail.getId())
return idAsString;
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Convert unique String representation of ProjectDetail back to ProjectDetail object.
Long id = Long.valueOf(value);
ProjectDetail projectDetail = someProjectDetailService.find(id);
return projectDetail;
}
Note that using EJBs in JSF converters (and validators) needs some hackery. See also How to inject #EJB, #PersistenceContext, #Inject, #Autowired, etc in #FacesConverter?

Lazy loading exception when using JSF Converter (refering to a collection)

This is my first post after many research on this problem.
This example is running under Jboss 7.1 with seam 3.1 (solder + persistence + faces) with seam managed persistence context
I'm facing a problem, the classical failed to lazily initialize a collection, no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed when using a converter on Entity beans. The aim is to stay 100% Object oriented, by reusing the JPA model.
in beans.xml, org.jboss.seam.transaction.TransactionInterceptor is activated
Entity beans :
#Entity
public class Member implements Serializable {
#Id
#GeneratedValue
private Long id;
private String name;
private String email;
#Column(name = "phone_number")
private String phoneNumber;
#ManyToMany
private List<Statut> listeStatut = new ArrayList<Statut>();
// getters, setters, hashcode, equals
}
#Entity
public class Statut implements Serializable {
#Id
#GeneratedValue
private Long id;
private String name;
#ManyToMany(mappedBy="listeStatut")
private List<Member> members = new ArrayList<Member>();
// getters, setters, hashcode, equals
}
The JSF page :
<h:form>
<h:selectManyCheckbox id="stat" value="#{memberModif.member.listeStatut}">
<f:converter converterId="statutConverter"/>
<f:selectItems value="#{memberModif.statutsPossibles}" var="statut" itemValue="#{statut}" itemLabel="#{statut.name}" />
</h:selectManyCheckbox>
<h:commandLink id="register" action="#{memberModif.modifier()}" value="Modifier">
<f:param name="cid" value="#{javax.enterprise.context.conversation.id}"/>
</h:commandLink>
</h:form>
The backing bean (I tried with ConversationScoped after SessionScoped --> same problem)
#ConversationScoped
#Named
public class MemberModif implements Serializable {
private static final long serialVersionUID = -291355942822086126L;
#Inject
private Logger log;
#Inject
private EntityManager em;
#Inject Conversation conversation;
private Member member;
#SuppressWarnings("unused")
#PostConstruct
private void init() {
if (conversation.isTransient()) {
conversation.begin();
}
}
public String modifier() {
em.merge(member);
}
public Member getMember() {
if (member == null) {
member = em.createQuery("from Member m where m.id=:id",Member.class).setParameter("id", new Long(0)).getSingleResult();
}
return member;
}
public List<Statut> getStatutsPossibles() {
return em.createQuery("from Statut", Statut.class).getResultList();
}
}
And the converter (strongly inspired by seam ObjectConverter) :
#FacesConverter("statutConverter")
public class StatutConverter implements Converter, Serializable {
final private Map<String, Statut> converterMap = new HashMap<String, Statut>();
final private Map<Statut, String> reverseConverterMap = new HashMap<Statut, String>();
#Inject
private transient Conversation conversation;
private final transient Logger log = Logger.getLogger(StatutConverter.class);
private int incrementor = 1;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (this.conversation.isTransient()) {
log.warn("Conversion attempted without a long running conversation");
}
return this.converterMap.get(value);
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (this.conversation.isTransient()) {
log.warn("Conversion attempted without a long running conversation");
}
if (this.reverseConverterMap.containsKey(value)) {
return this.reverseConverterMap.get(value);
} else {
final String incrementorStringValue = String.valueOf(this.incrementor++);
this.converterMap.put(incrementorStringValue, (Statut)value);
this.reverseConverterMap.put( (Statut)value, incrementorStringValue);
return incrementorStringValue;
}
}
}
Please note that I put this converter here to avoid you searching over the net for the seam implementation, but it is the same as using <s:objectConverter/> tag instead of <f:converter converterId="statutConverter"/>
Any help would be greetly appreciated.
You should access the objects in the same transaction. If you are sure you are doing that already, you could try getting the entitymanager by looking it up in the context instead of injecting it. Ive had a simular problem which was resolved that way. You can also initialize the collection in the transaction when you first got your reference to it.
Hibernate.initialize(yourCollection);
Take a look at this: selectManyCheckbox LazyInitializationException on process validation
Try:
<f:attribute name="collectionType" value="java.util.ArrayList" />;
on your <h:selectManyCheckbox>

#ManagedProperty annotated type returns null

I have this Service bean:
#Stateless
public class BookService
{
#PersistenceContext(unitName="persistentUnit")
protected EntityManager entityManager;
public BookModel find(Long id) {
return entityManager.find(BookModel.class, id);
}
}
And the backing bean for the Facelet page is:
#ManagedBean(name = "bookBean")
#RequestScoped
public class BookBean implements Serializable
{
#EJB
private BookService bookService;
#ManagedProperty(value="#{param.id}")
private Long id;
private DataModel<BookModel> books;
private BookModel currentBook;
#PostConstruct
public void init() {
if (id == null) {
// UPDATE: Retrieve a list of books.
} else {
// UPDATE: id shouldn't be null here.
// Get detail info about a book using the id
currentBook = bookService.find(id);
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BookModel getCurrentBook() {
return currentBook;
}
public void setCurrentBook(BookModel currentBook) {
this.currentBook = currentBook;
}
}
Why is the value of id always returns null even though the URL returned as bookedit.jsf?id=5418 I don't understand this.
Also, I find the EntityManager#find method quite restrictive in that it only accept a primary key value as the second parameter. What if I want to pass a [hashed] value instead of the primary key. How can I do this with the EntityManager#find method?
P.S. I notice the EntityManager#find requirement is the same for both OpenJPA and EclipseLink implementations. Hmm...
I just tried this in one of my managed beans, and it is working. Here's the relevant code, it's basically the same as yours:
#ManagedBean
#RequestScoped
public class TestBean {
#ManagedProperty(value = "#{param.id}")
private Long prop;
#PostConstruct
public void init() {
System.out.println(prop);
// prints 1234 if I go to the url with http://localhost/page.jsf?1234
}
public Long getProp() {
return prop;
}
public void setProp(Long prop) {
this.prop = prop;
}
}
I'm running this on glassfish 3.1.1. The only thought I had is maybe the injected EJB is somehow messing up the request scope in the ManagedBean?

Resources