JSF Input text placeholder

Reading Time: < 1 minute

In the Tag description add the pt entry and its corresponding web address

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:pt="http://xmlns.jcp.org/jsf/passthrough">

in the input text declaration

<h:inputText styleClass="form-control" 
pt:placeholder="Enter Search Value" required="true"
requiredMessage="Please enter search value"
value="#{orderController.keyword}" id="keywordSearch"/>

JSF File Download

Reading Time: < 1 minute
<h:commandLink action="#{logController.downloadMessage}">
                                    <h:outputText
                                            styleClass="fa fa-fw fa-download"/>
                                    <f:setPropertyActionListener value="#{log}"
                                                                 target="#{logController.selectedLog}"/>
                                </h:commandLink>
public void downloadMessage() throws IOException {
        logger.info("downloading the log file");
        File file = new File(searchKeyword + "_log.txt");
        FileUtils.writeStringToFile(file, selectedLog.getMessageContent(), Charset.defaultCharset());
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        response.setContentLength((int) file.length());
        FileInputStream input = null;
        try {
            int i = 0;
            input = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            while ((i = input.read(buffer)) != -1) {
                response.getOutputStream().write(buffer);
                response.getOutputStream().flush();
            }
            facesContext.responseComplete();
            facesContext.renderResponse();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

 

d

JSF Primefaces Indicator

Reading Time: < 1 minute

This example will show how to show a loader indicator while data is being fetch from the server.

<h:panelGrid columns="1" id="searchPanelGrid">
                        <h:panelGroup>
                            <p:inputText id="employeeId" placeholder="Employee Id" required="true"
                                         requiredMessage="Employee Id is required"
                                         value="#{createAdminController.employeeId}"/>
                            <p:commandButton value="Search in VCN" update="ldapPanel @form"
                                             actionListener="#{createAdminController.searchInVCN}" id="searchButton"/>
                        </h:panelGroup>
                    </h:panelGrid>
                    <p:blockUI block="searchPanelGrid" trigger="searchButton">
                        <h:graphicImage library="images" name="loader.gif"/>
                    </p:blockUI>

 

https://www.primefaces.org/showcase/ui/misc/blockUI.xhtml

http://ajaxload.info/

https://answers.axonivy.com/questions/14/how-to-create-a-loading-indicator-in-a-html-user-dialog/15

JSF Return Hostname and App name

Reading Time: < 1 minute
private static HttpServletRequest request = (HttpServletRequest) FacesContext
            .getCurrentInstance().getExternalContext().getRequest();
    static Logger logger = LoggerFactory.getLogger(JSFUtils.class);

    public static String getServerHost() {
        return "http://" + request.getServerName() + ":" + request.getServerPort();
    }

    public static String getServerHostWithAppName(){
        String url = null;
        try {
            url =  new URL(request.getScheme(),
                    request.getServerName(),
                    request.getServerPort(),
                    request.getContextPath()).toString();
        } catch (MalformedURLException e) {
           logger.error(e.toString());
        }
        return url;
    }

 

IBM Websphere Classloading set to PARENT_LAST

Reading Time: 3 minutes

The main responsibility of class loaders is to find and load the classes[1]. What do we get to do with this. First I’d like to explain the first terms. In class loading we have;

  • PARENT_LAST: Allows us to use the jars that we provide,
  • PARENT_FIRST: Uses existing jars provided by the WAS.

How does this help us? Well if you are using different jar stack than IBM provides, like JSF library in my case, then you will have some troubles with it. In our project our stack was JSF 2.2 Mojarra and Primefaces 6.0 with JDK 1.8. This option can be found All Applications > APPLICATION > Class loader.

However, this option is global setting. If your project EAR, contains multiple WAR files and context and some of them shall be excluded from this operation. Well you can also set class loading separately on the WAS console

All Applications > APPLICATION > Manage Modules > MODULE.war

I assume that the disadvantage of setting the class loading on the console is not permanent, every time you need to make this setting. However, there is an alternative way to set the class loading in a class way during the deployment. In my example I’ll show an EAR having 2 modules, one of them the JSF project will have the class loading set as PARENT_LAST and the other project as a default setting will have the PARENT_FIRST option. The target project is a maven multiple module project [2] [3]. We will succeed this operation by using a deployment.xml file in the EAR project.

Parent pom.xml

The version of the jsf project is kept here, I’ll explain the main reason further.

<properties>
    <supporttool.version>1.0.0</supporttool.version>
</properties>

Ear project pom.xml

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>WINS</artifactId>
    <groupId>PACKAGENAME</groupId>
    <version>18.0-SNAPSHOT</version>
  </parent>
  <artifactId>WinsEar</artifactId>
  <packaging>ear</packaging>
  <name>WinsEar</name>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-ear-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <generateApplicationXml>true</generateApplicationXml>
          <version>5</version>
          <modules>
            <webModule>
              <groupId>PACKAGENAME</groupId>
              <artifactId>WebClient</artifactId>
              <contextRoot>/wins</contextRoot>
            </webModule>
            <webModule>
              <groupId>PACKAGENAME</groupId>
              <artifactId>WINSSupportToolWeb</artifactId>
              <contextRoot>/supporttool</contextRoot>
            </webModule>
          </modules>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>PACKAGENAME</groupId>
      <artifactId>WebClient</artifactId>
      <version>18.0-SNAPSHOT</version>
      <type>war</type>
    </dependency>
    <dependency>
      <groupId>PACKAGENAME</groupId>
      <artifactId>WINSSupportToolWeb</artifactId>
      <version>${supporttool.version}</version>
      <type>war</type>
    </dependency>
  </dependencies>
</project>

Here you don’t have to create an explicit application xml file that has the settings for each project.  In the ear pom, the <generateApplicationXml> tag will create one for you.

Creating path for deployment.xml file

Now this is the very tricky part. You have to create the following path in your EAR project accordingly;

EARPROJECT\src\main\application\META-INF\ibmconfig\cells\defaultCell\applications\defaultApp\deployments\defaultApp

deployment.xml

Now after we are sure that the above folders are created successfully, then we can create our file

<?xml version="1.0" encoding="UTF-8"?>
<appdeployment:Deployment xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:appdeployment="http://www.ibm.com/websphere/appserver/schemas/5.0/appdeployment.xmi" xmi:id="Deployment_1495796489455">
  <deployedObject xmi:type="appdeployment:ApplicationDeployment" xmi:id="ApplicationDeployment_1495796489455" startingWeight="100">
    <modules xmi:type="appdeployment:WebModuleDeployment" startingWeight="10000" uri="WINSSupportToolWeb-1.0.0.war" classloaderMode="PARENT_LAST"/>
<!-- To set the classloading level as "PARENT_LAST" for the whole modules, remove the above line and commment out the below line -->
<!--<classloader xmi:id="Classloader_1297859327856" mode="PARENT_LAST"/>-->
  </deployedObject>
</appdeployment:Deployment>

you need to ensure that maven will create the project as it is defined in the detployment.xml file, otherwise it will not work out.

References

  1. https://www.ibm.com/support/knowledgecenter/en/SSAW57_8.5.5/com.ibm.websphere.nd.iseries.doc/ae/crun_classload.html
  2. https://maven.apache.org/guides/mini/guide-multiple-modules.html
  3. http://maven.apache.org/plugins/maven-eclipse-plugin/reactor.html

Enabling Fontawesome icons in Primefaces

Reading Time: < 1 minute

I’ve tested this in the Primefaces 6.0 and JSF 2.2 configuration

https://www.primefaces.org/showcase/ui/misc/fa.xhtml

http://fontawesome.io/cheatsheet/

Before

After

web.xml  

<context-param>
        <param-name>primefaces.FONT_AWESOME</param-name>
        <param-value>true</param-value>
</context-param>
<mime-mapping>
 <extension>woff2</extension>
 <mime-type>application/x-font-woff2</mime-type>
</mime-mapping>

jsf page  

<p:column headerText="Actions">
                        <p:commandButton type="button" value="Edit" icon="fa fa-fw fa-edit"/>
                        <p:commandButton type="button" value="Delete" icon="fa fa-fw fa-remove"/>
</p:column>

 

Spring Security JSF showing content depending on user role

Reading Time: 2 minutes

Spring is a very powerful framework, its security framework offers a splendid mechanism and security. It also integrates with other frameworks well too. In this post I’ll share an example of how you can show the content of a page depending on user’s role. I am assuming that you already have a spring security setup with spring security expressions are enabled in the config file. Now let’s start out;

1. create a file called “springsecurity.taglib.xml” underneath WEB-INF folder,

<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC
  "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
  "http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
<facelet-taglib>
  <namespace>http://www.springframework.org/security/tags</namespace>
  <tag>
    <tag-name>authorize</tag-name>
    <handler-class>org.springframework.faces.security.FaceletsAuthorizeTagHandler</handler-class>
  </tag>
  <function>
    <function-name>areAllGranted</function-name>
    <function-class>org.springframework.faces.security.FaceletsAuthorizeTagUtils</function-class>
    <function-signature>boolean areAllGranted(java.lang.String)</function-signature>
  </function>
  <function>
    <function-name>areAnyGranted</function-name>
    <function-class>org.springframework.faces.security.FaceletsAuthorizeTagUtils</function-class>
    <function-signature>boolean areAnyGranted(java.lang.String)</function-signature>
  </function>
  <function>
    <function-name>areNotGranted</function-name>
    <function-class>org.springframework.faces.security.FaceletsAuthorizeTagUtils</function-class>
    <function-signature>boolean areNotGranted(java.lang.String)</function-signature>
  </function>
  <function>
    <function-name>isAllowed</function-name>
    <function-class>org.springframework.faces.security.FaceletsAuthorizeTagUtils</function-class>
    <function-signature>boolean isAllowed(java.lang.String, java.lang.String)</function-signature>
  </function>
</facelet-taglib>

2. Register the taglib file in the web.xml file,

<context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/springsecurity.taglib.xml</param-value>
</context-param>

3. Include required dependencies,

<properties>
 <spring-security.version>3.1.2.RELEASE</spring-security.version>
 <spring-faces.version>2.4.1.RELEASE</spring-faces.version>
</properties>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>${spring-security.version}</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.springframework.webflow</groupId>
    <artifactId>spring-faces</artifactId>
    <version>${spring-faces.version}</version>
    <scope>compile</scope>
</dependency>

Now up to this point we are all set to use the implementation. From now on we can use this solution for;

a)Showing a nested content conditionally depending on roles and some other metrics;

<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:sec="http://www.springframework.org/security/tags">

  <sec:authorize ifAllGranted="ROLE_FOO, ROLE_BAR">
    Lorem ipsum dolor sit amet
  </sec:authorize>

  <sec:authorize ifNotGranted="ROLE_FOO, ROLE_BAR">
    Lorem ipsum dolor sit amet
  </sec:authorize>

  <sec:authorize ifAnyGranted="ROLE_FOO, ROLE_BAR">
    Lorem ipsum dolor sit amet
  </sec:authorize>

</ui:composition>

b)Using the role as a metric to hide/show some components depending on the role;

<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:sec="http://www.springframework.org/security/tags">

  <!-- Rendered only if user has all of the listed roles -->
  <h:outputText value="Lorem ipsum dolor sit amet" rendered="#{sec:areAllGranted('ROLE_FOO, ROLE_BAR')}"/>	
  
  <!-- Rendered only if user does not have any of the listed roles -->
  <h:outputText value="Lorem ipsum dolor sit amet" rendered="#{sec:areNotGranted('ROLE_FOO, ROLE_BAR')}"/>	
  
  <!-- Rendered only if user has any of the listed roles -->
  <h:outputText value="Lorem ipsum dolor sit amet" rendered="#{sec:areAnyGranted('ROLE_FOO, ROLE_BAR')}"/>	
  
  <!-- Rendered only if user has access to given HTTP method/URL as defined in Spring Security configuration -->
  <h:outputText value="Lorem ipsum dolor sit amet" rendered="#{sec:isAllowed('/secured/foo', 'POST')}"/>	

</ui:composition>

References

https://docs.spring.io/spring-webflow/docs/current/reference/html/spring-faces.html

http://docs.spring.io/autorepo/docs/webflow/2.3.x/reference/html/spring-faces.html#spring-faces-security-taglib

https://stackoverflow.com/a/15378140/1958683

http://keylesson.com/index.php/2015/06/18/spring-security-authorize-tag-example-1993/

 

JSF a closable div

Reading Time: < 1 minute

In this sample I’ve achieved one of demanded tasks at work regarding a closable mobile app pane, when the site is visited on mobile devices This is a good example also to study how to pass and set values in the backbean. Because we know what JSF is more of action based although there are events as well

SessionInformation

@Component("sessionInfo")
@Scope("session")
public class SessionInformation {

	@Setter
	@Getter
	public String mobileFramePane;
}

BackBean

@Component("templateController")
@Data
@Scope("session")
@Lazy
@NoArgsConstructor
public class TemplateControllerImpl implements TemplateController {

	@Autowired
	private SessionInformation sessionInformation;

	public String getCurrentYear() {
		return String.valueOf(CalendarUtil.getCurrentYear());
	}


	public void closeMobilePane(){
		sessionInformation.setMobileFramePane("closed");
	}


}

Xhtml

<h:form id="mobilePaneForm">
        <h:inputHidden id="mobilePaneVisibility" value="#{templateController.sessionInformation.mobileFramePane}" />
        <div id="androidDeviceContent" style="display: none;"
             class="androidDevice close-action">
            <img class="android-logo" src="/images/logo.png"
                 style="float: left;"/>

            <div class="mobileAppContent">
                #{msg.template_macfit_title} <br/> #{msg.mobile_app_android_1}
            </div>

            <div class="mobileAppLink">
                <a
                        href="intent://macfit.adesso.com/#Intent;package=com.adesso.macfit;scheme=http;end;">#{msg.mobile_app_run_on_app}</a>
            </div>
            <h:commandButton styleClass="close-icon" onclick="closeMobilePane()" action="#{templateController.closeMobilePane}" />
        </div>
        <div id="iosDeviceContent" style="display: none;" class="iosDevice close-action">
            <img class="android-logo" src="/images/logo.png"
                 style="float: left;"/>

            <div class="mobileAppContent">
                #{msg.template_macfit_title} <br/> #{msg.mobile_app_ios_1}
            </div>

            <div class="mobileAppLink">
                <a href="#" onclick="iosDeviceLauncher()">#{msg.mobile_app_run_on_app}</a>
            </div>
            <h:commandButton styleClass="close-icon"  onclick="closeMobilePane()" action="#{templateController.closeMobilePane}"/>
        </div>
    </h:form>

Before

mobile_pane_before

After

mobile_pane_after

JSF/Primefaces Multilingual calendar

Reading Time: 2 minutes

At work in my current project the customer has delivered their immediate need in the Turkish translation. Our project is multilingual that support English and Turkish. I’ve conducted a research on how to implement a multiple language support on our project, first of all I’ve managed to find Primeface’s prior manual site being hosted on google, there it show the language entries, but no clear sign on implementation.

Then it made me check a few of resources online, and finally I’ve come up with the solution. To explain the dynamics of Primefaces multilingual components is that, English is the default language, for other languages, you need to call a javascript file(s) in your external .js file or in the designated file. In my example I’ve called implemented the js file in the designated file, and return a “tr”/”en” key from the backbean because of the language selection of the users

JSF File

	<ui:define name="body">

		<link
			href="#{facesContext.externalContext.requestContextPath}/css/customMember.css"
			rel="stylesheet" type="text/css" />
		<script type="text/javascript">
			PrimeFaces.locales['tr'] = {
				closeText : 'kapat',
				prevText : 'geri',
				nextText : 'ileri',
				currentText : 'bugün',
				monthNames : [ 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs',
						'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim',
						'Kasım', 'Aralık' ],
				monthNamesShort : [ 'Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz',
						'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara' ],
				dayNames : [ 'Pazar', 'Pazartesi', 'Salı', 'Çarşamba',
						'Perşembe', 'Cuma', 'Cumartesi' ],
				dayNamesShort : [ 'Pz', 'Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct' ],
				dayNamesMin : [ 'Pz', 'Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct' ],
				weekHeader : 'Hf',
				firstDay : 1,
				isRTL : false,
				showMonthAfterYear : false,
				yearSuffix : '',
				timeOnlyTitle : 'Zaman Seçiniz',
				timeText : 'Zaman',
				hourText : 'Saat',
				minuteText : 'Dakika',
				secondText : 'Saniye',
				ampm : false,
				month : 'Ay',
				week : 'Hafta',
				day : 'Gün',
				allDayText : 'Tüm Gün'
			};
		</script>

<p:calendar id="birthdate"
									value="#{memberController.order.birthdate}"
									yearRange="c-70:c+10" placeholder="#{msg.member_birthdate}"
									locale="#{memberController.getCalendarLocale()}" pattern="dd/MM/yyyy" mask="true" effect="fold"
									widgetVar="birthdateVar"
									styleClass="#{not component.valid ? 'ui-date-invalid default-input-date' : 'default-input-date'}"
									required="true"
									mindate="#{memberController.getBirthdateBegin()}"
									maxdate="#{memberController.getBirthdateEnd()}"
									navigator="true">
									<f:convertDateTime pattern="dd/MM/yyyy" />
									<f:validator binding="#{birthDateValidator}" />

								</p:calendar>

</ui:define>

Backbean

public String getCalendarLocale() {
		if (sessionInformation.getLanguage().equals(Language.ENGLISH))
			return "en";
		else
			return "tr";
	}

Primefaces language entries

https://code.google.com/archive/p/primefaces/wikis/PrimeFacesLocales.wiki

Primefaces Calendar Showcase

http://www.primefaces.org/showcase/ui/input/calendar.xhtml