Installing External Jars to Local Maven Repository

Reading Time: 1 minute

Central Maven repository has a large variety of libraries https://mvnrepository.com however there are times that we may be in need of installing such 3rd party jars that are not offered in the central in mavenized projects. This command will allow you to install such jars to your local M2 folder. You need to make sure that if multiple developers are working on the project that experiences this situation, the participants must also carry out the same procedure.

The Command

[bash lang=”bash” smarttabs=”true” tabsize=”4″ wraplines=”true”]mvn install:install-file -Dfile={FILELOCATION}
-DgroupId=GROUPID/KNOWNASPACKAGENAME -DartifactId=ARTIFACTID
-Dversion=VERSION -Dpackaging=PACKAGINGTYLE[/bash]

Example Command

[bash smarttabs=”true” tabsize=”4″ wraplines=”true”]mvn install:install-file -Dfile=C:\myjar1-0.jar
-DgroupId=com.tugrulaslan -DartifactId=MyJar
-Dversion=1.0 -Dpackaging=jar[/bash]

Usage in pom.xml

<dependency>
<groupId>com.tugrulaslan</groupId>
<artifactId>MyJar</artifactId>
<version>1.0</version>
</dependency>

External Links
https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html

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

JVMCFRE003 bad major version; class=javax/servlet/ServletContextListener

Reading Time: 1 minute

This is issue recently occurred at work while I was working on the migration to IBM WAS 8.5. The migration was from WAS 7.0 and JDK 1.6 to WAS 8.5 JDK1.8. The issue rises if you compile the project with a different(in my case lower) JDK version that the installed on the server. To resolve this issue compile the project with the proper java version.

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/