JDBC Web application in netbeans with wildfly server - web

I am trying to run my Web application in netbeans with wildfly server. I got error
"jboss.naming.context.java.module.LocalShop.LocalShop.env.ReadBean.dp is missing [jboss.naming.context.java.jboss.datasources.shopstyles]" and I think line
#Resource (lookup= "java:jboss/datasources/shopstyles") is causing the error. Can someone help me?
Package structure
MANIFEST.MF
My code for web application in netbeans:
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.sql.DataSource;
#Named (value="readBean")
#RequestScoped
public class ReadBean implements Serializable {
#Resource (lookup= "java:jboss/datasources/shopstyles")
private DataSource dp;
public List<Veggie>performRead() throws SQLException{
if(dp == null){
throw new SQLException("Cannot access data pool");
}
List<Veggie>list;
try (Connection con =dp.getConnection()){
if(con == null){
throw new SQLException("Cannot establish connection to database");
}
PreparedStatement ps =con.prepareStatement("select veggie_id,name,price,created_date from veggie");
ResultSet result =ps.executeQuery();
list=new ArrayList<>();
while(result.next()){
Veggie veggie=new Veggie();
veggie.setVeggieID(result.getInt("veggie_id"));
veggie.setName(result.getString("name"));
veggie.setPrice(result.getString("price"));
veggie.setCreated_date(result.getDate("created_date"));
list.add(veggie);
}
}
return list;
}
}
Manifest.mf code:
Manifest-Version: 1.0
Netbeans config
Part of Standalone

Related

Sessionscoped bean is not sessionscoped

I am currently building an application of which the (customer) requirements are Java EE and JSF (Primefaces) as front-end.
In this application I need to create a kind of wizard with several steps. I thus created a backing bean which holds the information of the several steps and a controller which handles the clicks and actions in the form, hence depending strongly on the Bean.
Problem is that the Bean although annotated as Sessionscoped is recreated every single time the controller is invoked. Hence, I get nullpointers and such since fields which I expect to be initiated remain null.
This is a part of the code of the bean:
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;
#SessionScoped
#Named
/**
* A placeholder for all the information needed in the wizard.
*/
public class WizardBean implements Serializable {
And this is part of the code for the controller:
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
#ManagedBean(name = "registerInvestigationController")
#SessionScoped
public class WizardController implements Serializable {
private static final long serialVersionUID = 3327044905245768948L;
private static final Logger LOGGER = LoggerFactory.getLogger(WizardController.class);
#Inject
private WizardBean wizardBean;
Any idea what I am doing wrong?

invoke a method in Liferay

I use Liferay Tomcat bundle 6.2, and I work with Liferay IDE(eclipse)
How I can invoke a method in Liferay?
I create one Liferay Plugin Project and write in java class this following code. But I don't know, How I can invoke this method?
I can't create a main class in Liferay. But, I think, I can invoke this method in view.jsp with creating an action URL, it this right?
Can you give me a sample example?
Thank you
public class TestLoggerPortlet extends MVCPortlet {
private static final Log logger = LogFactoryUtil.getLog(TestLoggerPortlet.class);
public void addEntry() {
logger.info("This is my message.");
if (logger.isDebugEnabled()) logger.debug("Not always printed.");
}
}
I think you are confusing desktop/mobile application with web application.
In my mind you have to study Java EE basics (how a browser performs a request to an application server and, how to server proceed to understand the request and dispatch it to the right method of the righte class, etc... it is called "servlet lifecycle").
Then should be easy to understand the differences with a portlet lifeycle (and how Liferay MVC portlets work for managing what you need).
I can suggest some interesting reading (in order of learning path):
http://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html (see lifecycle part); basics to have a global idea about what happens behind the stages;
http://www.opensource-techblog.com/2014/12/introduction-to-portlet-phases-and.html an easy comparation to portlet lifecycle;
https://www.liferay.com/it/documentation/liferay-portal/6.0/development/-/ai/portlet-development - Liferay official general introduction to development
https://dev.liferay.com/develop/tutorials/-/knowledge_base/6-2/creating-a-liferay-mvc-portlet-project - THE TUTORIAL YOU NEED to understand how to create a simple LR mvc portlet;
https://www.liferay.com/it/web/meera.success/blog/-/blogs/liferay-mvc-portlet-development-introduction another interesting tutorial.
Hope it helps
See the below code.
view.jsp
<portlet:defineObjects />
<portlet:actionURL var="myAction" name="myAction">
<portlet:param name="someTxt" value="Text Message" />
</portlet:actionURL>
<form action="<%= myAction %> method="post" name="fm">
<input name="<portlet:namespace/>txtName" type="text" />
<input type="submit" name="<portlet:namespace/>submit" value="submit"/> 
</form>
Controller Class. TestLoggerPortlet.java
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class TestLoggerPortlet
*/
public class TestLoggerPortlet extends MVCPortlet {
private static Log _log = LogFactoryUtil.getLog(TestLoggerPortlet.class);
#ProcessAction
public void myAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
String var1 = actionRequest.getAttribute("someText");//output -> "Text Message"
String var2 = actionRequest.getAttribute("txtName");//output -> Value of Text field.
sendRedirect(actionRequest, actionResponse);
}
}

How to get selectonemenu value after ajax process [duplicate]

This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 6 years ago.
I know this seems to be a common one, but I'm lost with it. Occurs on clicking the Add button in assessment.jsf. Anyway, I've attached what I think are the relevant sections.
FWIW, AssessmentType.equals() isn't triggered when I debug.
Thanks in advance.
j_idt38:j_idt47:j_idt48: Validation Error: Value is not valid
assessment.xhtml:
<h:form>
<h:selectOneMenu value="#{assessmentBean.assessmentField}">
<f:selectItems value="#{assessmentBean.assessment.type.fields}" />
</h:selectOneMenu>
<h:commandButton value="Add" action="#{assessmentBean.doAddField}">
<f:param name="assessmentId"
value="#{assessmentBean.assessment.id}" />
</h:commandButton>
</h:form>
assessment.jsf:
<form id="j_idt38:j_idt47" name="j_idt38:j_idt47" method="post" action="/jsf-web/edit/assessment.jsf" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt38:j_idt47" value="j_idt38:j_idt47" />
<select name="j_idt38:j_idt47:j_idt48" size="1"> <option value="1">Presenting Condition</option>
<option value="2">Problem Duration</option>
</select>
<script type="text/javascript" src="/jsf-web/javax.faces.resource/jsf.js.jsf?ln=javax.faces"></script>
<input type="submit" name="j_idt38:j_idt47:j_idt50" value="Add" onclick="mojarra.jsfcljs(document.getElementById('j_idt38:j_idt47'),{'j_idt38:j_idt47:j_idt50':'j_idt38:j_idt47:j_idt50','assessmentId':'1'},'');return false" /><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="3431661972220941645:6952134510589038883" autocomplete="off" />
</form>
AssessmentType.java:
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import lombok.Data;
import org.hibernate.envers.Audited;
#Audited
#Data
#Entity
public class AssessmentType implements Comparable<AssessmentType> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String name;
#OneToMany( fetch=FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, targetEntity=AssessmentField.class )
private List<AssessmentField> fields;
#Override
public int compareTo(final AssessmentType o) {
return getId().compareTo(o.getId());
}
#Override
public String toString() {
return getName();
}
}
AssessmentFieldConverter.java
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.htu.fizio.api.AssessmentFieldManager;
import com.htu.fizio.domain.AssessmentField;
#FacesConverter(forClass = AssessmentField.class)
public class AssessmentFieldConverter implements Converter {
AssessmentFieldManager<AssessmentField> assessmentFieldManager;
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
try {
final InitialContext ic = new InitialContext();
assessmentFieldManager = (AssessmentFieldManager) ic.lookup("fizio/AssessmentFieldManagerImpl/local");
return assessmentFieldManager.find(Long.valueOf(value));
} catch (NamingException e) {
e.printStackTrace();
}
return null;
}
#Override
public String getAsString(FacesContext ctx, UIComponent component, Object value) {
return String.valueOf(((AssessmentField) value).getId());
}
}
AssessmentBean.java
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import lombok.Getter;
import lombok.Setter;
import com.htu.fizio.api.AssessmentManager;
import com.htu.fizio.domain.Assessment;
import com.htu.fizio.domain.AssessmentField;
import com.htu.fizio.domain.AssessmentFieldValue;
import com.htu.fizio.jsf.faces.FacesUtil;
...
#PostConstruct
public void init() {
if (FacesUtil.containsKey("assessmentId")) {
final Long id = Long.parseLong(FacesUtil.get("assessmentId"));
assessment = assessmentManager.find(id);
} else {
assessment = new Assessment();
}
}
public String doAddField() {
final AssessmentFieldValue value = new AssessmentFieldValue();
value.setField(assessmentField);
value.setValue("");
assessment.getFieldValues().add(value);
assessmentManager.save(assessment);
return "/edit/assessment";
}
Edit:
Just noticed this when debugging, is it a likely suspect?:
Daemon Thread [HandshakeCompletedNotify-Thread] (Suspended (exception ConcurrentModificationException))
HashMap$EntryIterator(HashMap$HashIterator<E>).nextEntry() line: 793
HashMap$EntryIterator.next() line: 834
HashMap$EntryIterator.next() line: 832
SSLSocketImpl$NotifyHandshakeThread.run() line: 2214
Validation Error: Value is not valid
To the point, this error means that the selected item does not match any of the items available in the list. I.e. the object represented by the selected item value has never returned true on its equals() call with any of the available select items.
There are only two causes for this problem:
The equals() method of the object type in question is broken.
The contents of the list of items is different during the validations phase of the form submit request than as it was during the render response phase of the initial request to display the form.
Since the first seems to be properly implemented -as per the comments-, the only cause left is the second. Assuming that you're nowhere doing business logic in a getter method, an easy test is to put the #{assessmentBean} in the session scope. If it works, then the data (pre)loading logic of the list of select items is definitely wrong.
The validation is failing because after your converter converts the String representation of AssessmentType back to an object, JSF iterates over the existing values (assessmentBean.assessment.type.fields) and compares this recently converted object with all those existing ones.
Since you did not implement Object#equals for AssessmentType, it will default to an object identity comparison (roughly spoken, the memory address of your object) , which will of course fail.
The solution is thus to either implement Object#equals, or let the converter get the object from assessmentBean.assessment.type.fields instead of from AssessmentTypeManager.
I think I've resolved this, at least, I've moved on to the next error!
Despite posting reams of code I'd not posted the full xhtml in which there were multiple and nested form tags. Just the one form seems to allow passing the assessmentId parameter which in turn allows the AssessmentBean to then populate the List of AssessmentFields for the assessment type correctly.
Thanks for all the help.

JSF - Updating a JSF datatable on page refresh

I have a datatable on my JSF page, which gets filled dynamically on page load thanks to BalusC and Odelya.
But now when I try to refresh the JSF page to retrieve the updated data from database, I don't get the updated data in the Datatable.
I have already gone through the following link but couldn't understand the nuances..!
JSF datatable refresh on page load
Is your bean scope configured as a Session?
Have you tried to change its scope to Request?
Don't forget to close your connection after filling your resultset, which has to be a CachedRowSet
Here is an example from Core JavaServer Faces book:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.enterprise.context.RequestScoped;
import javax.sql.DataSource;
import javax.sql.rowset.CachedRowSet;
#ManagedBean
#RequestScoped
public class CustomerBean {
#Resource(name = "jdbc/mydb")
private DataSource ds;
public ResultSet getAll() throws SQLException {
Connection conn = ds.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM Customers");
CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl();
crs.populate(result);
return crs;
} finally {
conn.close();
}
}
}
'#RequestScoped' should be added to refresh your bean File to get the new data.

using #Produces and #Inject across AS7 module dependencies

is it possible to use a CDI producer method defined in module A in order to CDI inject into a bean in a second module B?
Is there any description on the relation between CDI and the JBoss Modules System?
In producer.jar:
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import java.util.logging.Logger;
public class Producer {
#Produces
public static Logger produceLog(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
}
In consumer.war:
import javax.inject.Inject;
import java.util.logging.Logger;
public class Consumer {
#Inject
Logger logger;
public void doLog() {
logger.info("Hello CDI with JBoss Modules");
}
}
module B has a Manifest Dependency on module A:
Manifest-Version: 1.0
Dependencies: deployment.producer.jar
this approach leads to an weld unsatisfied dependency problem:
"JBAS014671: Failed services" => {"jboss.deployment.unit.\"consumer.war\".WeldService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"consumer.war\".WeldService: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Logger] with qualifiers [#Default] at injection point [[field] #Inject question.Consumer.logger]"
I posted a sample project on Github: https://github.com/sistar/jboss-cdi-demo
TIA
Ralf

Resources