Primefaces 5.2, when menuitem should be evaluated/executed? - primefaces

I am using JSF 2.2 with Primefaces 5.2 to implement my JSF project. I'm trying put a linkage with menuitem by using outcome to access my backing bean controller in my main.xhtml such as:
<h:form prependId="false" id="headerForm">
......
<p:menubar >
<p:submenu label="#{apps['application.staff.myinfo']}" icon="ui-icon-document">
<p:menuitem value="#{apps['application.staff.myinfo']}" immediate="true" outcome="#{staffControlBean.viewStaff()}" process="#form" update="#all" icon="fa fa-fw fa-leaf"
disabled="#{empty loginControlBean.staffSession.username}"/>
<p:separator />
<p:menuitem value="Quit" url="#" />
</p:submenu>
</p:menubar>
......
</h:form>
My backing bean as:
#Named(value = "staffControlBean")
#SessionScoped
public class StaffControlBean implements Serializable{
private static final String STAFF_VIEW="/staff/staffView.xhtml";
......
public String viewStaff(){
logger.info("View staff from menuitem clicked.");
if(loginControlBean.getStaffSession().isChangePassword()){
logger.info("password has to be changed before use this services.");
loginControlBean.fireChangePasswordDialog();
return "";
}else {
return STAFF_VIEW;
}
}
......
}
From above snippet you will see, I expect when I click the menuitem from the menubar, backing end controller method viewStaff will be invoked to return a change password dialog or return to my staff view.
But unfortunately, every time when I access (or refresh) main.xhtml without click any menuitem from menubar, the backing bean method was evaluated/executed twice. This is what I found from my server log:
......
####<Nov 10, 2016 2:02:29 PM AEDT> <Info> <com.longz.ozssc.web.staff.StaffControlBean> <macmini16g.tweedheadstorage.com.au> <OzsscWEBServer> <[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <bc92beef-9f93-4923-a503-9a9cee37010d-00000071> <1478746949108> <[severity-value: 64] [rid: 0] [partition-id: 0] [partition-name: DOMAIN] > <BEA-000000> <View staff from menuitem clicked.>
####<Nov 10, 2016 2:02:29 PM AEDT> <Info> <com.longz.ozssc.web.staff.StaffControlBean> <macmini16g.tweedheadstorage.com.au> <OzsscWEBServer> <[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <bc92beef-9f93-4923-a503-9a9cee37010d-00000071> <1478746949109> <[severity-value: 64] [rid: 0] [partition-id: 0] [partition-name: DOMAIN] > <BEA-000000> <View staff from menuitem clicked.>
......
My question is: When the linkage or buttons in the JSF will be evaluated or executed? Why it always been evaluated or executed when the page was loaded or refreshed. How I can avoid it happen?
Any advice are welcome and appreciated.

Related

Liberty Server :It is not valid to call the 'commit' method on a nontransacted session

I'm moving from WAS8 to Liberty. Following is my code:
connection = factory.createConnection();
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
When I run my application it gives error saying:
DetailedIllegalStateException: JMSCC0014: It is not valid to call the 'commit' method on a nontransacted session.
Server.xml
<variable name="wmqJmsClient.rar.location"
value="${server.config.dir}/wmq/wmq.jmsra.rar"/>
<jmsConnectionFactory jndiName="jms/xyz/QCF" >
<properties.wmqJms
transportType="CLIENT"
hostName="host3153.GOT.NET"
port="1414"
channel="CLIENTS.xyz"
queueManager="host141Q"/>
<connectionManager maxPoolSize="10"/>
</jmsConnectionFactory>
<jmsQueue id="jms/queue1" jndiName="jms/xyz/queue/response">
<properties.wmqJms
baseQueueName="host1533A.RESP"
baseQueueManagerName="host141Q" CCSID="1208" expiry="APP" failIfQuiesce="true" persistence="APP" priority="APP" putAsyncAllowed="ENABLED" readAheadAllowed="ENABLED" readAheadClosePolicy="ALL" receiveConversion="QMGR" targetClient="JMS" receiveCCSID="1208" />
</jmsQueue>
<jmsQueue id="jms/queue2" jndiName="jms/xyz/queue/transportAssignment/request">
<properties.wmqJms
baseQueueName="host1533A.RQST"
baseQueueManagerName="host141Q" CCSID="1208" expiry="APP" failIfQuiesce="true" persistence="APP" priority="APP" putAsyncAllowed="ENABLED" readAheadAllowed="ENABLED" readAheadClosePolicy="ALL" receiveConversion="QMGR" targetClient="JMS" receiveCCSID="1208" />
</jmsQueue>

How to pass data from one Managed Bean to another? [duplicate]

This question already has answers here:
Creating master-detail pages for entities, how to link them and which bean scope to choose
(2 answers)
Closed 4 years ago.
I am developing a website using JSF 2.2 and Primefaces 6.1 where I have, initially, 2 pages: A "list" page, where I can show the data to the user, and a "create" page, where I can create new data or edit existing ones.
NOTE: "Cargo" means occupation.
list.xhtml:
...
<h:form>
<p:commandButton value="Cadastrar" styleClass="ui-button-sucesso" action="create.xhtml?faces-redirect=true"/>
</h:form>
...
<h:form>
<p:dataTable value="#{cargoListMB.listaCargo}" var="cargo" rowKey="#{cargo.codigo}" emptyMessage="Nenhum cargo encontrado" filteredValue="#{cargoListMB.listaCargoFiltro}">
<f:facet name="header">Tabela de Cargos</f:facet>
<p:column headerText="Código" sortBy="#{cargo.codigo}" filterBy="#{cargo.codigo}" filterPosition="top">
<h:outputText value="#{cargo.codigo}"/>
</p:column>
<p:column headerText="Nome" sortBy="#{cargo.nome}" filterBy="#{cargo.nome}" filterPosition="top" filterMatchMode="contains">
<h:outputText value="#{cargo.nome}"/>
</p:column>
<p:column headerText="Funcionários" sortBy="#{cargo.funcionariosNesteCargo}"filterBy="#{cargo.funcionariosNesteCargo}" filterPosition="top">
<h:outputText value="#{cargo.funcionariosNesteCargo}"/>
</p:column>
<p:column headerText="Editar">
<p:commandButton icon="fa fa-pencil" title="Editar" styleClass="ui-button-icone-apenas" action="create.xhtml?faces-redirect=true">
<f:param name="objcargo" value="#{cargo.codigo}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
CargoListMB.java:
#ManagedBean(name = "cargoListMB")
#ViewScoped
public class CargoListMB implements Serializable {
private List<Cargo> listaCargo;
private List<Cargo> listaCargoFiltro;
public List<Cargo> getListaCargo() {
if (listaCargo == null) {
listaCargo = CargoDAO.listarTodos(); //load data from database
}
return listaCargo;
}
public void setListaCargo(List<Cargo> listaCargo) {
this.listaCargo = listaCargo;
}
...
}
create.xhtml:
<h:form>
<f:metadata>
<f:viewParam name="objcargo" value="#{cargoCreateMB.cargo}" converter="cargoConverter"/>
<f:viewAction action="#{cargoCreateMB.inicializar()}"/>
</f:metadata>
<div class="ui-grid ui-grid-responsive">
<div class="ui-grid-row">
<div class="ui-grid-col-6">
<h1 class="if-page-title"><h:outputText value="#{cargoCreateMB.cargo.codigo == 0? 'Cadastro de Cargos' : 'Edição de cargo'}"/></h1>
</div>
<div class="ui-grid-col-6"></div>
</div>
<br/>
<div class="ui-grid-row">
<div class="ui-grid-col-12">
<div class="ui-grid-row">
<div class="ui-grid-col-1">
<p:outputLabel for="nome" value="Nome:"/>
</div>
<div class="ui-grid-col-3">
<p:inputText id="nome" placeholder="nome" value="#{cargoCreateMB.cargo.nome}" required="true""/>
</div>
<div class="ui-grid-col-8">
<p:message for="nome"/>
</div>
</div>
<br/>
<div class="ui-grid-row">
<div class="ui-grid-col-3">
<p:commandButton value="Salvar" actionListener="#{cargoCreateMB.salvar}" update="form" styleClass="ui-button-salvar"/>
</div>
<div class="ui-grid-col-9"></div>
</div>
</div>
</div>
</div>
</h:form>
CargoCreateMB.java
#ManagedBean(name = "cargoCreateMB")
#ViewScoped
public class CargoCreateMB implements Serializable {
private Cargo cargo;
public void salvar() {
try {
ControleCargo.insereCargo(cargo); //saves the 'occupation' on the database
MensagensUtil.mensagemInfo("Atenção", "Cargo inserido com sucesso");
} catch (RuntimeException e) {
MensagensUtil.mensagemInfo("Erro", "Erro ao inserir cargo");
System.out.println("Erro: " + e);
}
}
public void inicializar() {
//QUESTION!! : Due to a JSF page's life cycle, could I put this code on the constructor??
if (this.cargo == null) {
this.limpar();
}
}
private void limpar() {
cargo = new Cargo();
}
public Cargo getCargo() {
return cargo;
}
public void setCargo(Cargo cargo) {
this.cargo = cargo;
}
}
As you can see, I am trying to pass the selected 'occupation' from page list.xhtml to crate.xhtml using <f:param> and <f:viewParam> tags. When I click on button 'Cadastrar' (means 'register'), everything works fine (the "cargo" object is initially null, as expected), but when I click on the edit button, the "cargo.codigo" (occupation's ID) value, sent by the <f:param> tag, does not "arrive" to the "cargo" object. The converter ('cargoConverter') should be working fine, BUT, when I checked the String value that the method getAsObject was receiving, it was ALWAYS "0", no matter which occupation I choose on my list.
I also tried to send the "raw" data: Instead of using a converter, I sent the "cargo.codigo" value directly to a String field, but it was ALWAYS null.
Could someone help me discover what was my mistake? Also, if it is possible, is there another way to send data to other Managed Beans? Thanks in advance.
Edit: Based on Kukeltje's comments, I formatted my code (which can be seen above) and removed all the nested <h:form> elements BUT the problem still persists. Therefore, the answers on question How to use <h:form> in JSF page? didn't help at all and this question is not a duplicate.
Based on Kukeltje's comments and tips and the answers on this question, I managed to find my mistake: my <f:metadata> was indeed inside a <h:form>
tag. I removed it from there and it worked perfectly.

Hit query on pagination in display tag

I use DisplayTag in my struts2 application and i want to hit query on clicking pagination.
Ex : When user click on the next page or any page then query is fire on action class.
FILE : displayTag.jsp
<display:table name="list1" sort="list" size="20" pagesize="5" id="table1" export="true" requestURI="" partialList="true">
<display:column property="no" group="1" sortable="true" headerClass="sortable"></display:column>
<display:column property="nam" group="2" sortable="true" headerClass="sortable"></display:column>
<display:column property="ct" group="3" sortable="true" headerClass="sortable" autolink="true"></display:column>
<display:setProperty name="export.excel.filename" value="diplayTag.xls"></display:setProperty>
<display:setProperty name="export.pdf.filename" value="diplayTag.pdf"></display:setProperty>
<display:setProperty name="export.csv.filename" value="diplayTag.csv"></display:setProperty>
<display:setProperty name="export.pdf" value="true"></display:setProperty>
</display:table>
I use request.setAttribute("list1", li); where i set all data in list1(ArrayList) and pass to the displayTag.jsp.
DisplayTag get all data and display in the table format. But my need is to pass only 5 data at a time and on clicking next page action class send other 5 data and so on.
I refer link : Display tag pagination problem
But i can not understand because i'm use MySql and also new on DisaplyTag.
DB : MySql
Framework : struts2
After researching and hard working i found answer.
FILE : displayTag.jsp
<display:table name="list1" sort="external" size="20" pagesize="5" id="table1" export="true" requestURI="disTag" partialList="true">
// code as above
</dispaly:table>
here requestURI="disTag" is a action name.
FILE : struts.xml
<action name="disTag" class="className">
<result name="success">/displayTag.jsp</result>
<result name="error">/error.jsp</result>
</action>
FILE : class file
page = Integer.parseInt(request.getParameter((new ParamEncoder("table1").encodeParameterName(TableTagParameters.PARAMETER_PAGE))));
if(page != 0)
{
start = (page - 1) * 5; //5 is row or data per page.
}
getData(start, 5); //getData is a method which store all data in ArrayList. Based on start index.

Spring integration tcp outbound and http inbound don t work properly

Hey I am sitting in front of Spring Integration for several days without speedy progress. Hope you can help me:
My trace:
Client.Input (POJO)
-> Client.[tcp-outbound].defaultserializer
-> Server.[tcp-inbound].defaultserializer
-> Server.[http-outbound] -> transform(POJO-to-Json)
-> Spring MVC Controller : return same POJO (automatic transform to json)
-> Server -> transform(Json-to-POJO)
-> Server -> defaultserializer
-> Client -> defaultserializer
Here the configuration:
Client-Side:
<int:channel id="input" />
<int-ip:tcp-connection-factory id="client"
type="client"
host="192.168.178.28"
port="5678"
serializer="javaSerializer"
deserializer="javaDeserializer"/>
<int-ip:tcp-outbound-gateway id="outboundGateway"
request-channel="input"
connection-factory="client"
request-timeout="10000"
reply-timeout="10000"/>
Server-Side:
<int-ip:tcp-connection-factory id="connectionFactory"
type="server"
port="6000"
serializer="javaSerializer"
deserializer="javaDeserializer"/>
<int-ip:tcp-inbound-gateway id="inboundGateway"
connection-factory="connectionFactory"
request-channel="requestChannel"
reply-channel="outboundChannel"/>
<int:channel id="requestChannel" />
<int:channel id="toMvcChannel" />
<int:channel id="toTcpChannel" />
<int:channel id="outboundChannel" />
<int:object-to-json-transformer input-channel="requestChannel"
output-channel="toMvcChannel"/>
<int:header-enricher input-channel="toMvcChannel">
<int:header name="Content-Type" value="application/json" />
</int:header-enricher>
<int-http:outbound-gateway
url="http://localhost:10100/arx/dataset/receiveGateway"
request-channel="toMvcChannel"
reply-channel="toTcpChannel"/>
<int:json-to-object-transformer input-channel="toTcpChannel"
output-channel="outboundChannel"/>
SimpleGateway:
public interface SimpleGateway {
public DefinitionServer send(DefinitionServer definition);}
I cannot understand why I get the error message below on Client side ON RECEIVE (last step in the routing):
No converter found capable of converting from type [java.lang.String] to type [...DefinitionServer]
Thanks in advance!

Wildfly with jaas always results in login-error

For some reason i can't loggin in my application using Wildfly, primefaces and JAAS. I didn't try it in others versions like JBoss 7 AS because i want to see this working on Wildfly.
After try loggin using admin for j_username and 1234 for j_password, it redirecting to login-error page. I can't understand why.
MD5 hash econding it's right with generated password from postgres
I can acess this JDNI and execute some querys from java code, concluding it's working.
String DATASOURCE_CONTEXT = "java:jboss/datasources/zephyrplace-ds";
Connection result = null;
try {
Context initialContext = new InitialContext();
if ( initialContext == null){
System.out.println("JNDI problem. Cannot get InitialContext.");
}
DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);
if (datasource != null) {
result = datasource.getConnection();
}
else {
System.out.println("Failed to lookup datasource.");
}
}
catch ( NamingException ex ) {
System.out.println("Cannot get connection: " + ex);
}
catch(SQLException ex){
System.out.println("Cannot get connection: " + ex);
}
return result;
login.xhtml (primefaces):
<h:form id="login" onsubmit="document.getElementById('login').action='j_security_check';" prependId="false">
<ul class="nav navbar-nav navbar-right">
<li>
<center>
<p:inputText name="j_username" placeholder="Usuario" style="margin-top:10px;margin-left:10px;" size="15" id="user" value="#{usuarioBean.usuario.usuario}" rendered="#{empty usuarioBean.usuarioLogado}"></p:inputText>
</center>
</li>
<li>
<center>
<p:inputText id="j_password" name="j_password" placeholder="Senha" style="margin-top:10px;margin-left:10px;" size="15" type="password" value="#{usuarioBean.usuario.senha}" rendered="#{empty usuarioBean.usuarioLogado}"></p:inputText>
</center>
</li>
<li>
<center>
<p:commandButton style="margin-top:10px;margin-left:10px;" value="Entrar" rendered="#{empty usuarioBean.usuarioLogado}" ajax="false"></p:commandButton>
</center>
</li>
</ul>
</h:form>
jboss-web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<security-domain>zephyrplace-security-domain</security-domain>
</jboss-web>
standalone.xml:
<security-domains>
<security-domain name="zephyrplace-security-domain" cache-type="default">
<authentication>
<login-module code="Database" flag="required">
<module-option name="dsJndiName" value="java:jboss/datasources/zephyrplace-ds"/>
<module-option name="principalsQuery" value="select pass from users where name=?"/>
<module-option name="rolesQuery" value="select role_name from user_roles where user_name = ?"/>
<module-option name="hashAlgorithm" value="MD5"/>
<module-option name="hashEncoding" value="base16"/>
</login-module>
</authentication>
</security-domain>
</security-domains>
postgres:
CREATE TABLE "users"
(
"name" character varying(50),
pass character varying(50)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "users" OWNER TO postgres;
CREATE TABLE user_roles
(
user_name character varying(50),
role_name character varying
)
WITH (
OIDS=FALSE
);
ALTER TABLE user_roles OWNER TO postgres;
INSERT INTO users("name", pass) VALUES ('admin', MD5('1234'));
INSERT INTO user_roles(user_name, role_name) VALUES ('admin', 'ADMIN');
web.xml:
<!-- Protected Areas -->
<security-constraint>
<web-resource-collection>
<web-resource-name>Only admins</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Users and admins</web-resource-name>
<url-pattern>/index/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
<!-- Allowed Roles -->
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<security-role>
<role-name>USER</role-name>
</security-role>
<!-- Login Prompt -->
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login/login.xhtml</form-login-page>
<form-error-page>/login/login-error.xhtml</form-error-page>
</form-login-config>
</login-config>
In my application i use also wildfly and i configurated the security on the standalone-full.xml. Also on rolesQuery i gave 'Roles' for the name of the result of the query. Sorry for my english. This way is better to explain:
<module-option name="rolesQuery" value="select role_name, 'Roles' from user_roles where user_name = ?"/>
it think it needs that name. those are the differences i see.