|
|
|
Search on blog
Petition by Java EE Guardians
Se afișează postările cu eticheta JSF. Afișați toate postările
Se afișează postările cu eticheta JSF. Afișați toate postările
duminică, 21 august 2016
joi, 4 august 2016
duminică, 31 iulie 2016
[OmniFaces utilities (2.4)] Format the given number to nearest 10^n (rounded to thousands)
[OmniFaces utilities] The
formatThousands() formats the given number to nearest 10n (rounded to thousands), immediately suffixed (without space) with metric unit (k, M, G, T, P or E), rounding half up with a precision of 3 digits, whereafter trailing zeroes in fraction part are stripped. Numbers lower than thousand are not affected. The format locale will be set to the one as obtained by Faces#getLocale(). If the value is null, NaN or infinity, then this will return null.This function is available from OmniFaces 2.3, but in OmniFaces 2.4, the incorrectly trimmed trailing zeroes from non-fractional integer numbers was fixed and now also supports cutting down fractions of values lower than thousand.
Function:
Usage:
// 9.99 k
#{of:formatThousandsUnit(9994)}
// 10 M
#{of:formatThousandsUnit(9995000)}
// 532 k
#{of:formatThousandsUnit(532230.6483)}
sâmbătă, 23 iulie 2016
[OmniFaces utilities (2.4)] Format the given number to nearest 10^n, suffixed with a space, the metric unit prefix and the given unit
[OmniFaces utilities] The
formatThousandsUnit() formats the given number to nearest 10n (rounded to thousands), suffixed with a space, the metric unit prefix (k, M, G, T, P or E) and the given unit, rounding half up with a precision of 3 digits, whereafter trailing zeroes in fraction part are stripped. The format locale will be set to the one as obtained by Faces#getLocale(). If the value is null, NaN or infinity, then this will return null.The given unit used in the format is of type B for Bytes, W for Watt, etc. If the unit is null, then this method will behave exactly as described in #formatThousands(Number).This function is available from OmniFaces 2.3, but in OmniFaces 2.4, the incorrectly trimmed trailing zeroes from non-fractional integer numbers was fixed and now also supports cutting down fractions of values lower than thousand.
Function:
Usage:
// 9.99 kB
#{of:formatThousandsUnit(9994 , "B")}
// 10 MW
#{of:formatThousandsUnit(9995000
, "W")}
// 532 kFOO
#{of:formatThousandsUnit(532230.6483
, "FOO")}
luni, 18 iulie 2016
duminică, 17 iulie 2016
[OmniFaces utilities (2.4)] Get all request query string or view parameters appended with all child UIParameter components of the given parent component
[OmniFaces utilities] The
getParams() returns an unmodifiable map with all request query string or view parameters, appended with all child UIParameter components (<f|o:param>) of the given parent component. Those with disabled=true or an empty name or an empty value are skipped. The <f|o:param> will override any included view or request parameters on the same name.Method:
See also: Servlets.getRequestQueryStringMap() | Faces.getViewParameterMap() | Components.getParams()
Usage:Let's suppose that we have the following page:
<f:metadata>
<f:viewParam
name="playernameparam"
value="#{playersBean.playerName}"/>
<f:viewParam
name="playersurnameparam"
value="#{playersBean.playerSurname}"/>
</f:metadata>
<h:head>
<title></title>
</h:head>
<h:body>
<h:panelGrid columns="2">
<h:form id="form">
<h:commandButton id="submit"
value="Get all params"
action="#{playersBean.allParams()}">
<f:param name="ageParam" value="29"/>
<o:param name="playParam" value="left"/>
</h:commandButton>
</h:form>
</h:panelGrid>
</h:body>
Further, we can use the Components#getParams()
utility to programmatically collect the UIParameters
(<f|o:param/>)
nested in the above <h:commandButton/>
and the view parameters. This can be accomplish in different JSF
artifacts; for example, in a bean (obviously, there are several ways to
identify the parent UIComponent
of the UIParameters
that we want to collect - the UIComponent
that should be passed to the #getParams()
should be obtained in a convenient manner depending on your circumstances;
below, we simply used the Components#findComponent()
utility):
import
org.omnifaces.util.Components;
...
public void
allParams() {
UIComponent uc = Components.findComponent("form:submit");
Map<String, List<String>>
paramsMap = Components.getParams(uc, false, true);
for (Map.Entry<String,
List<String>> entry : paramsMap.entrySet()) {
System.out.println("Param: "+
entry.getKey() + "/" + entry.getValue());
}
}
Let's suppose that we start the application with an URL like this:
http://myapp/?playernameparam=rafael&playersurnameparam=nadal
After we press the Get
all params button the server log will reveal the following output:
Param:
playernameparam/[rafael]
Param:
playersurnameparam/[nadal]
Param:
ageParam/[29]
Param:
playParam/[left]
sâmbătă, 9 iulie 2016
[OmniFaces utilities (2.4)] Get the HTTP request URL with query string, regardless of any forward
[OmniFaces utilities] The
getRequestURL() method returns the HTTP request URL with query string, regardless of any forward. This is the full request URL without query string as the enduser sees in browser address bar.
Method:
See also: Faces.getRequestDomainURL() | Faces.getRequestURI()
Usage:
import org.omnifaces.util.Servlets;
...
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// e.g. http://localhost:8080/MyApp/MyServlet
String req = Servlets.getRequestURL(request);
}
...
}
miercuri, 6 iulie 2016
[OmniFaces utilities (2.4)] Get the HTTP request query string, regardless of any forward
[OmniFaces utilities] The
getRequestQueryString() method returns the HTTP request query string, regardless of any forward.Method:
| Use this one outside JSF context (Servlets#getRequestQueryString()) See also: Utils.coalesce() | Use this one in JSF context (Faces#getRequestQueryString()) See also: Faces.getRequest() | Faces.getContext() |
Some use cases are available right in OmniFaces source code. For example, OmniFaces uses getRequestQueryString() to get the HTTP request URI with query string, regardless of any forward:
public static String getRequestURIWithQueryString(HttpServletRequest request) {
String requestURI = getRequestURI(request);
String queryString = getRequestQueryString(request);
return (queryString == null) ? requestURI : (requestURI + "?" + queryString);
}
luni, 4 iulie 2016
[OmniFaces utilities (2.4)] Get the HTTP request URI, regardless of any forward or error dispatch
[OmniFaces utilities] The
getRequestURI() method returns the HTTP request URI, regardless of any forward or error dispatch. This is the part after the domain in the request URL, including the leading slash.Method:
| Use this one in JSF context (Faces#getRequestURI()) See also: Faces.getRequest() | Faces.getContext() | Use this one outside JSF context (Servlets#getRequestURI()) See also: Utils.coalesce() |
|
|
Some use cases are available right in OmniFaces source code. For example, OmniFaces uses getRequestURI() to check if the given HTTP servlet request is a JSF resource request:
public static
boolean isFacesResourceRequest(HttpServletRequest request) {
return getRequestURI(request).startsWith(request.getContextPath()
+ ResourceHandler.RESOURCE_IDENTIFIER + "/");
}
public static
String getRequestURIWithQueryString(HttpServletRequest request) {
String requestURI = getRequestURI(request);
String queryString =
getRequestQueryString(request);
return (queryString == null) ? requestURI :
(requestURI + "?" + queryString);
}
duminică, 3 iulie 2016
[OmniFaces utilities (2.4)] Get a list of all action expressions and listeners associated with given component
[OmniFaces utilities] The
getActionExpressionsAndListeners() method returns a list of all action expressions and listeners associated with given component. This covers expressions in action attribute of command components and listener attribute of ajax components. Any method expressions are in format #{bean.method} and any action listeners are added as fully qualified class names. This list is primarily useful for logging postback actions in a phase listener. You can use #getCurrentActionSource() to obtain the current action source.Method:
Usage:
Let's suppose the following code:
<h:form>
<h:commandButton value="Foo" actionListener="#{fooBean.fooActionListener()}"
action="#{fooBean.fooAction()}">
<f:setPropertyActionListener id="foo"
target="#{fooBean.foo}" value="Foo"/>
<f:ajax execute="@form"
render="@form" listener="#{fooBean.ajaxFooListener()}"/>
</h:commandButton>
</h:form>
Now,
programmatically (for example in a phase listener) we can do this:
import
org.omnifaces.util.Components;
...
// use getCurrentActionSource()
to get the source of the currently invoked action
UIComponent
command = Components.getCurrentActionSource();
List<String>
ael = Components.getActionExpressionsAndListeners(command);
// or, use getCurrentCommand()
to get the currently invoked UI command component
UIComponent
command = Components.getCurrentCommand();
List<String>
ael = Components.getActionExpressionsAndListeners(command);
Both
examples will return a List<String> that contains the following items:
[
#{fooBean.fooAction()},
javax.faces.event.MethodExpressionActionListener,
com.sun.faces.facelets.tag.jsf.core.SetPropertyActionListenerHandler$SetPropertyListener,
#{fooBean.ajaxFooListener()}
]
[OmniFaces utilities (2.4)] Get the source of the currently invoked action
[OmniFaces utilities] The
getCurrentActionSource() method returns the source of the currently invoked action, or null if there is none, which may happen when the current request is not a postback request at all, or when the view has been changed by for example a successful navigation. If the latter is the case, you'd better invoke this method before navigation.Method:
Usage:
import org.omnifaces.util.Components;
...
UIComponent action = Components.getCurrentActionSource();
You can see several examples of using this method as:
- check whether the given component has invoked the form submit (hasInvokedSubmit()):
public static
boolean hasInvokedSubmit(UIComponent component) {
UIComponent source = getCurrentActionSource();
return source != null &&
source.equals(component);
}
- get the currently invoked UI command component (getCurrentCommand()):
public
static UICommand getCurrentCommand() {
UIComponent source = getCurrentActionSource();
return source instanceof UICommand ?
(UICommand) source : null;
}
sâmbătă, 2 iulie 2016
marți, 28 iunie 2016
CDI-JSF: Beans discovery modes
When we write applications that involves CDI we need to activate CDI by
adding in our project a file named beans.xml. Usually, this file will look like below:
<?xml
version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
In this post, we are interested in the part highlighted in red. If you
never notice that part before, then this quick post is for you. Let's see what
is happening when we have bean-discovery-mode="all",
and for this let's consider a simple interface with two implementations, as
follows:
public
interface IFoo {
public void fooSlaveAction();
}
@RequestScoped
public class
FooImplAnnotated implements IFoo {
private static final Logger LOG =
Logger.getLogger(FooImplAnnotated.class.getName());
@Override
public void fooSlaveAction() {
LOG.info("FooImplAnnotated#fooSlaveAction() invoked ...");
}
}
public class
FooImplNoAnnotation implements IFoo {
private static final Logger LOG =
Logger.getLogger(FooImplNoAnnotation.class.getName());
@Override
public void fooSlaveAction() {
LOG.info("FooImplNoAnnotation#fooSlaveAction() was invoked
...");
}
}
As you can see, the main difference between these two implementations
consist in the fact that FooImplAnnotated
is annotated with a CDI annotation, @RequestScoped. Well, now let's inject these
two implementation in a third CDI bean:
@Named
@RequestScoped
public class
FooBean {
// inject the annotated bean
@Inject
private FooImplAnnotated fooAnnotated;
// inject the no-annotation bean
@Inject
private FooImplNoAnnotation fooNoAnnotation;
public void fooMasterAction(){
// call fooSlaveAction() of the annotated
bean
fooAnnotated.fooSlaveAction();
// call fooSlaveAction() of the no annotation
bean
fooNoAnnotation.fooSlaveAction();
}
}
If we test this application (for example by calling the fooMasterAction() method via a simple EL as #{fooBean.fooMasterAction()}), we will get the following messages in the server log:
FooImplAnnotated#fooSlaveAction()
invoked ...
FooImplNoAnnotation#fooSlaveAction()
was invoked ...
Ok, this is the effect of using bean-discovery-mode="all"
who tells CDI to discover all beans. No, let's alter the beans.xml as switch
the value of bean-discovery-mode
from all to
annotated:
<?xml
version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="annotated">
</beans>
This time the test will fail with an error of type org.jboss.weld.exceptions.DeploymentException:
WELD-001408: Unsatisfied dependencies for type FooImplNoAnnotation with
qualifiers @Default. Well, the problem is that the FooImplNoAnnotation is
not discoverable and it cannot be injected in FooBean. Since we are looking only for
annotated implementation, we can re-write our FooBean like below:
@Named
@RequestScoped
public class
FooBean {
// inject the annotated bean
@Inject
private IFoo fooAnnotated;
public void fooMasterAction() {
// call
fooSlaveAction() of the annotated bean
fooAnnotated.fooSlaveAction();
}
}
Now, the test will pass again, and the server log will reveal this
message: FooImplAnnotated#fooSlaveAction()
invoked ...Since the FooImplNoAnnotation
is not discoverable, CDI has choose
the single available implementation, FooImplAnnotated. Of course, if we make the FooImplNoAnnotation discoverable
by adding a CDI annotation to it, then CDI will cause ambiguous
dependencies errors.
Ok, finally, let's switch the value of bean-discovery-mode from annotated to none:
<?xml
version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="none">
</beans>
This time the test will not cause any error and no messages will be
available in the server log. We just told CDI to not try to discover any bean.
The complete example is available here.
[OmniFaces utilities (2.4)] Create a copy of the array with items in reversed order
[OmniFaces utilities] The
reverseArray() function returns a copy of the array with items in reversed order.Function:
Usage:
Let's suppose that we have the following simple array defined in a bean:
@Named
@RequestScoped
public class
MonthsBean {
private String[] months = new String[]
{"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October", "November", "December"};
"August", "September", "October", "November", "December"};
public String[] getMonths() {
return
months;
}
}
Now, we can display the array as it was defined and in reverse order as below:
// as it was
defined
<ui:repeat
value="#{monthsBean.months}" var="item"
varStatus="loop">
#{loop.index + 1} : #{item} #{!loop.last ? ',
' : ''}
</ui:repeat>
Output:
Output:
1 : January , 2 : February , 3 : March , 4 : April , 5 : May , 6
: June ,
7 : July , 8 : August , 9 : September , 10 : October , 11 : November , 12 : December
7 : July , 8 : August , 9 : September , 10 : October , 11 : November , 12 : December
// reversed
(xmlns:of="http://omnifaces.org/functions")
<ui:repeat
value="#{of:reverseArray(monthsBean.months)}"
var="item" varStatus="loop">
#{loop.index + 1} : #{item} #{!loop.last ? ',
' : ''}
</ui:repeat>
Output:
Output:
1 : December , 2 : November , 3 : October , 4 : September , 5 :
August , 6 : July ,
7 : June , 8 : May , 9 : April , 10 : March , 11 : February , 12 : January
7 : June , 8 : May , 9 : April , 10 : March , 11 : February , 12 : January
joi, 23 iunie 2016
[OmniFaces utilities 2.4] Check if the given object is serializable
[OmniFaces utilities] The
isSerializable() method returns true if the given object is serializable.Method:
Usage:
Example 1 - test Object:
import org.omnifaces.util.Utils;
...
Utils.isSerializable(new
Object()); // return false
Example 2 - test two classes
// Serializable class
public class ShopingCart implements Serializable {
...
}
// NOT Serializable class
public class Item {
...
}
Utils.isSerializable(new ShopingCart()); // return true
Utils.isSerializable(new
Item()); // return false
marți, 21 iunie 2016
CDI-JSF: Using CDI alternatives priority (@Priority)
Before you read this post please read: Use
a CDI alternative as a mock implementation for a stateless session bean
So, since you are familiar with the above post, now let's suppose that
we have multiple mock implementations. In such cases, the problem is how to
instruct the container to choose between the implementations? The answer relies
on alternatives priority!
Basically, we annotate each mock implementation with @Priority and
provide a number as the level of priority. The higher number has the higher
priority. Here it is three mock implementations with priorities 1,2 and 3:
@Priority(1)
@Alternative
@Stateless
public class
FooServiceMock implements IFooService {
@Override
public List getAllFoo() {
return Arrays.asList("foo 1",
"foo 2", "foo 3");
}
}
@Priority(2)
@Alternative
@Stateless
public class
BestFooServiceMock implements IFooService {
@Override
public List getAllFoo() {
return Arrays.asList("best foo 1",
"best foo 2", "best foo 3");
}
}
@Priority(3)
@Alternative
@Stateless
public class
GreatFooServiceMock implements IFooService {
@Override
public List getAllFoo() {
return Arrays.asList("great foo 1",
"great foo 2", "great foo 3");
}
}
The mock implementation annotated with @Priority(3)
has the higher priority. When we run the below code CDI will automatically
choose the GreatFooServiceMock:
@Named
@RequestScoped
public class
FooBean {
private static final Logger LOG =
Logger.getLogger(FooBean.class.getName());
@Inject
private IFooService fooService; // choose GreatFooServiceMock
public void loadAllFoo() {
List allfoo = fooService.getAllFoo();
LOG.log(Level.INFO, "allfoo:{0}",
allfoo);
}
}
Now, we can also write a test using CDI-Unit as below (this will also
choose the GreatFooServiceMock):
@RunWith(CdiRunner.class)
@ActivatedAlternatives({FooServiceMock.class,
BestFooServiceMock.class, GreatFooServiceMock.class})
public class
FooBeanTest {
@Inject
FooBean fooBean;
@Test
@InRequestScope
public void testStart() {
fooBean.loadAllFoo();
}
}
We can use the @Priority annotation to specify alternatives globally for an application that consists of multiple modules like this:
@Alternative
@Priority(Interceptor.Priority.APPLICATION+10)
public class ...
The complete example is available here.
Abonați-vă la:
Postări
(
Atom
)
|
| [JSF Page Author Beginner's Guide] |
Postări populare
-
If you like this article, I think you are going to like JSF 2.3 Tutorial as well.
-
Starting with JSF 2.3 the JSF "native" managed bean annotations are officially deprecated. So, there is no doubt now that CDI is ...
-
[OmniFaces utilities] The getRequestURL() method returns the HTTP request URL with query string, regardless of any forward. This is the f...
-
[OmniFaces utilities] The getCurrentActionSource() method returns the source of the currently invoked action, or null if there is none, ...
-
Before you read this post please read: Use a CDI alternative as a mock implementation for a stateless session bean So, since you are fa...
-
[OmniFaces utilities] The getActionExpressionsAndListeners() method returns a list of all action expressions and listeners associated wit...
-
Starting with JSF 2.3, more exactly with m07 , we can take advantage of using the auto detection of convertors based on 1st UISelectMany it...
-
[OmniFaces utilities] The isSerializable() method returns true if the given object is serializable. Method: Usage: Example 1 - te...
-
[OmniFaces utilities] The reverseArray() function returns a copy of the array with items in reversed order. Function: Usage: Let...
-
Let's checkout a common practice for declaring constants in Java using the public static final declaration: public class Circle { ...
JSF/OmniFaces Resources |





















JSF 2 Tutorials at www.mkyong.com
JavaServer Faces (JSF) Tutorial 
















