Fronting Liferay Tomcat with Apache HTTPd daemon Revisted

Technical Blogs March 6, 2018 By David H Nebinger


So originally I presented the blog post, Fronting Liferay Tomcat with Apache HTTPd daemon, but this post featured my partiality for using mod_jk to connect HTTPd and Tomcat.

Personally I think it is much easier to do the JkMount and JkUnmount mappings to point to Tomcat, plus Liferay sees the original request so when it generates URLs, it can generate them using the incoming request URL.

Remember that Liferay generates URLs for other assets such as stylesheets, javascripts, images, etc. Rather that being hard-coded, Liferay will create URLs based on the incoming request URL. This should mean that the host, port and protocol it uses for the generated URLs will correctly resolve back to the Liferay server.

When you front with HTTPd, it gets the actual request, not Tomcat. If you use the AJP binary protocol with mod_jk, the original URL goes to Liferay and it can generate URLs using the normal logic.

But when you use mod_proxy, things can be challenging. The URL that goes to Tomcat and Liferay is the URL request from HTTPd, not the external client browser. So if you are proxying from HTTPd to localhost:8080, a defaut Liferay configuration will end up generating URLs with localhost:8080 in them even though they will not be valid in the external client browser.

The challenge is getting the protocol, host and port correct when Liferay generates URLs.

Option 1 - Handle It In Liferay

The first way to get this right is to do it in Liferay.  By setting the following properties in, you control how Liferay generates URLs:

# Ports that apache HTTPd will be listening on
# Host name to use in generated URLs, will typically be the name used to get to HTTPd
# Force all generated URLs to use the HTTPS protocol
# If not set, will use the protocol from the connection from HTTPd to Tomcat.

As specified above, regardless of the incoming request URL, Liferay will generate URLs in the form of

In your httpd.conf file, all that is missing is the ProxyPass directives to send traffic to the local tomcat instance. Personally I want to send all traffic to Tomcat and specifically exclude those paths that should not go to Tomcat. I find this to be easier to manage rather than trying to figure out all URL patterns that Liferay might use to send traffic selectively to Tomcat:

# Serve /excluded from the local httpd data
ProxyPass /excluded !
# Pass all traffic to a localhost tomcat.
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
# This would be the configuration to invoke a tomcat on another server
# ProxyPass /
# ProxyPassReverse /

This is a very, very simplistic HTTPd configuration. It doesn't deal at all with virtual host configurations, http/https configurations, etc.

Also on the Liferay side it will generate URLs w/ and may not use the Liferay configured virtual hosts correctly either.

Option 2 - Handle It In HTTPd

The second way to handle things is to push the heavy lifting to HTTPd.

We start by configuring httpd.conf (and the child files) to use the Virtual Hosts:

<VirtualHost *:80>
    # Set the header for the http protocol
    RequestHeader set X-Forwarded-Proto "http"
    # Serve /excluded from the local httpd data
    ProxyPass /excluded !
    # Preserve the host when invoking tomcat
    ProxyPreserveHost on
    # Pass all traffic to a localhost tomcat.
    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/
    # This would be the configuration to invoke a tomcat on another server
    # ProxyPass /
    # ProxyPassReverse /
<VirtualHost *:443>
    # Set the header for the https protocol
    RequestHeader set X-Forwarded-Proto "https"
    # Serve /excluded from the local httpd data
    ProxyPass /excluded !
    # Preserve the host when invoking tomcat
    ProxyPreserveHost on
    # Pass all traffic to a localhost tomcat.
    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/
    # This would be the configuration to invoke a tomcat on another server
    # ProxyPass /
    # ProxyPassReverse /

So this sets up two virtual hosts, but using wildcards so they will actually handle all incoming requests that get to HTTPd. Each virtual host is tied to the HTTP or HTTPS protocol and set a header, X-Forwarded-Proto with the protocol to use.

Also it includes the ProxyPreserveHost directive which will preserve the incoming host when sending the request to Tomcat (it will get the incoming host instead of the localhost from the ProxyPass directive).  The X-Forwarded-Host header will also be set.

On the Liferay side, the changes are simpler since we didn't change the expected header names:

# Set this to true to use the property "" to
# get the host. The property "" must be set its default
# value.

# Set this to true to use the property "web.server.forward.port.header" to
# get the port.
# Set this to true to use the property "web.server.forward.protocol.header"
# to get the protocol. The property "web.server.protocol" must not have been
# overriden.

This configuration elegantly handles virtual hosts correctly in HTTPd and in Liferay, it respects the incoming protocol correctly (to support mixed mode requests) and it is just easy to set up and validate, plus it won't require property changes when you add a new virtual host to Liferay.


So here's two options for configuring your server to support fronting Tomcat with HTTPd but using mod_proxy instead of mod_jk.

Personally I recommend using mod_jk, but if I had to go with mod_proxy, I would lean towards implementing it using Option 2 above.


OSGi Version Details

Technical Blogs March 6, 2018 By David H Nebinger

A good friend of mine, Minhchau Dang, pointed out to me that I have frequently used OSGi version ranges in my blogs.

I explained that I was concerned that I didn't want to bind to a specific version, I often wanted my code to work over a range of versions so I wouldn't have to go back and update my code.

He pointed me at the specifications,, which indicate that I didn't understand that a standalone version also work as a range. Yes this link is for the 7.0 specs and we're not at 7.0, but the 6.0 and 5.0 specs echo the same thing, I just didn't have a working link to that section.

So, in case you don't want to spin out to the specs document, I'll summarize here...

You can specify a range like version="[1.2.3,2)" to supply a fixed range, or 1.2.3 <= x < 2. This range specifies both the lower and upper bounds and allows you to be inclusive or exclusive of values.

But, if you simply use version="1.2.3", you are also using an unlimited range, or 1.2.3 <= x. This range only specifies the minimum version, anything greater is just fine.

Well, technically, that is. As far as OSGi is concerned, if 4.0.0 is available, it will happily mark the dependency as satisfied. You have to keep in mind, though, that there is never a guarantee of backwards compatibility on higher version numbers. So while OSGi will resolve the dependency with 4.0.0, it may not at all be compatible with what you need as a dependency. You are likely going to be okay if 1.3.4 is deployed, or 1.6.7, but you will likely encounter failure with version 2.0.0. So keep in mind that ranges, although not necessary, will help to constrain your module to platforms that will actually successfully host your module.

Now, I suppose we can still have a discussion of what to do with respect to Liferay releases. I mean, I don't know how Liferay will version portal-kernel for the upcoming 7.1 release, but let's consider the following...

Normally the Liferay tooling will start you with portal-kernel version 2.0.6 which we now know means 2.0.6 <= x, so any higher number is fine. But it actually likely will not be for 7.1. We might actually need to use a version range like [2.0.6,2.1) if 7.1 uses a minor version bump or [2.0.6,3) if 7.1 does a major version bump and our code doesn't work on 7.1.

I guess we'll cross that bridge when we get there...



How to Upgrade to Liferay 7.0+

General Blogs February 23, 2018 By David H Nebinger

So the question comes up how to do Liferay upgrades.

I'm not talking here about the technical details of how you upgrade one particular plugin to another type of plugin, what kinds of API changes have to be made, etc.

Instead, I'm thinking more about the general process of how to upgrade, what choices you're presented with and what the ramifications are for making certain choices.

Upgrades Are Projects

The first thing to remember is that upgrades are projects. You should totally build them out as projects, you should have a project plan, you should have a project team, ... Having a full project plan forces you to define scope for the upgrade and time box all activities so you will know how the project is proceeding.

As a project, you also should have a risk assessment/mitigation plan. Know in advance what you will do if the project runs long or runs into issues. Will you just stretch the timeline? Will you seek help from Liferay GS or a Liferay Partner? Are you sending your development team to Liferay training in advance or only if they seem to struggle? Will you rely on LESA tickets, Liferay documentation, community support via the forums or slack?

Liferay GS offers an Upgrade Assessment package where an experienced Liferay GS consultant will come onsite to review your environment and build a customized report outlining what your upgrade effort will be. This assessment can become the foundation of your project planning and can help set your upgrade in the right direction.

Upgrades Have Scopes

Upgrading from Liferay 6.2 to Liferay DXP 7.1, there will be scope to this project and the project is susceptible to scope creep.

For example, you might decide going in that your project is simply to get what you currently have migrated and running under DXP. During the upgrade project, though, you might decide to add some backlogged features or refactor your codebase or rework legacy portlet wars into OSGi portlet modules. Each of these things would be considered scope creep. Each change like these that the team takes on will negatively impact your project plan and schedule.

Upgrades Expose Bad Practices

The one thing I've found is that upgrades tend to expose bad practices. This could be bad practices such as using an ORM package instead of Service Builder for data access. It could be a non-standard way of decoupling code such as making all service calls via remote web services where a local service implementation would have been an easier path. It can expose when standard design practices such as design by interface were not fully leveraged. It could be as simple as having used an EXT plugin to do something that should have been handled by a JSP hook or a separate custom implementation.

Exposing bad practices may not seem very important, but upgrading bad practices will always add to a project plan. Something done initially as a shortcut or a hack, these things get difficult to carry forward in an upgrade.

The one thing I've found in 10+ years of experience with Liferay, it is often better to do things "The Liferay Way". It is not always easy and may not seem like the right way, but it usually ends up being the better way generally to develop for the platform.

Upgrade Project Recommendations

To facilitate your upgrade project, I offer the following recommendations:

  • Limit scope. As far as the upgrade is concerned, limit the project scope to getting what you currently have running under the later version. Do not consider refactoring code, do not consider reworking portlet wars as OSGi modules, etc. Limit the scope to just get on the new version. If you want to refactor or rework wars as OSGi modules, save that for a later project or phase.


  • Leave portlet wars as portlet wars. I can't say this strongly enough. It is absolutely not necessary for your legacy portlet wars to be refactored as OSGi modules. Your legacy portlet wars can be deployed to DXP (after necessary API changes) and they will automagically be converted into an OSGi WAB for you. Do not spend your upgrade cycles reworking these into OSGi bundles yourself, it is a complete waste of your time and effort.


  • Only rework what you have to rework. You'll have to touch legacy hooks and EXT plugins, there is no way around that. But that is where your upgrade cycles need to be spent. So spend them there.


  • Rethink upgrading bad practices. I know, I said limit scope and migrate what you have. The one exception I make to this rule is if you have exposed some really bad practices. In the long run, it can often be a smaller level of effort to rework the code to eliminate the bad practice first or as part of the upgrade. Cleaner code is easier than spaghetti to upgrade.


  • Use Liferay IDE tooling. The Liferay IDE comes with a built-in upgrade assistant tool. While the tool is not perfect, it can help you upgrade your Maven and Plugin SDK projects to be compatible with the later version, including suggesting and making necessary API changes for you. If you do not use the upgrade assistant, you are willfullly missing out on an automated way to start your upgrade.


  • Have a Backup Plan. Know in advance if you are going to leverage Liferay GS or a Liferay Partner to help complete your upgrade in case you are seeing delays. If you wait until you are behind the eight-ball before mitigating your risk, you will be less prepared to get the project back on track if it is going off the rails.


  • Get a Liferay Upgrade Assessment Package. Even if you are going to do all of the work in house, an upgrade assessment can highlight all of the aspects you and your team will need to consider.

That's pretty much it.  Have any horror stories or suggestions you'd like to share? Please add them below...

Why You Should Join the 7.1 Community Beta Program

General Blogs February 20, 2018 By David H Nebinger

So Jamie just announced the new Liferay 7.1 Community Beta Program here:

I recommend everyone who has working code in Liferay 7.0 or Liferay DXP should join the 7.1 beta sooner rather than later.

Why? Well, mostly because Liferay's engineering team is focused on the 7.1 release, so anything that you find in beta, well that will be something that they will want to fix before release. Without those bug reports, some incompatibility that you encounter later on falls under the regular release process and that will only work against your release schedule.

Let's say, for example, that you have spent time building out a comprehensive audit solution for your Liferay 7.0/DXP environment where you have a slew of model listeners and a custom output mechanism to route the audit details to an ElasticSearch instance that you report on using Kibana. You've got a decent investment in your auditing solution, one that you plan on leveraging in 7.1 on.

You're basically looking at two choices.  Choice #1 is to do nothing; wait for the official 7.1 GA to come out and for your organization to decide it is time to consider an update to 7.1. Now I can't predict what might be part of 7.1, but let's argue that it has one or more bugs related to the audit mechanisms.  Perhaps the model listeners registration has changed or the audit messages are broken or the output mechanism isn't invoked consistently, ... I don't know, some sort of bug that maybe could have been caught sooner but ended up getting by. But now that you're looking at the upgrade, you've found the bug and want to report it. That's fine, Liferay wants you to report bugs, but at the time you've found it 7.1 is out and fixing the bug ends up becoming part of the release process.

Choice #2 is to join the Beta program. Now you dedicate a little bit of time to test your code under 7.1 before it goes out and you find and report the issue. Now Liferay has this list of things that they want to knock out for the first GA, so your report becomes one of many that Liferay really wants to deal with for a solid initial release. Your bug gets dealt with before it can impact your own upgrade schedule, and this actually helps you from the early reporting.

So please, please, please sign up for the 7.1 beta program.

Get the 7.1 beta and beat on it as much as you can.

Run the DB upgrade against your current database. Update and deploy your custom modules, make sure features, functionality and APIs are still there that you depend on. Point your load test tool at your instance and see if you have a measurable difference in performance or capacity vs your current environment.

Just bring it. Find and report the problems.

Together we can make the next release one of the best ever, all that's missing is you.

OSGi Fragment Bundles

Technical Blogs February 15, 2018 By David H Nebinger

Okay, in case it is not yet clear, Liferay 7 uses an OSGi container.

I know what you're thinking: "Well, Duh..."

The point is that OSGi is actually a standard and anything that works within OSGi will work within Liferay. You just need to understand the specs to make something of it.

For example, I'd like to talk about OSGi Fragment Bundles. There's actually stuff in the specs that cover what fragment bundles can do, how they will be treated by the container, etc.

The only way that Liferay typically presents a fragment bundle as a solution is for a JSP fragment, but there's actually some additional stuff that can be done with them.

OSGi Fragment Bundles

Fragment bundles are covered in chapter 3.14 of the OSGi Core 6.0.0 specification document.  In technical terms,

Fragments are bundles that can be attached to one or more host bundles by the framework. Attaching is done as part of resolving: the Framework appends the relevant definitions of the fragment bundles to the host's definitions before the host is resolved. Fragments are therefore treated as part of the host, including any permitted headers.

The idea here is that fragments can supplement the content of a host bundle, but cannot replace files from the host. Since the fragment is appended to the host, resources will always be loaded from the host bundle before they are loaded from the fragment.

This is counter to the old way Liferay used to do JSP hooks, where these hooks could actually replace any JSP or static file from the original bundle.  Fragments can only add new files, but not replace existing ones.

So you might now be wondering how the JSP files from a fragment bundle actually do override the files from the host bundle. The answer? Liferay magic. Well, not magic, per se, but there is special handling of JSP files by the Liferay systems to use a JSP file from a fragment before the host, but this is not normal OSGi Fragment Bundle behavior.

What good are they if they can only add files?

Actually you can do quite a bit once you understand that bit.

For example, I was recently trying to help a team override the notification template handling from the calendar-service module, a ServiceBuilder service module for the Liferay calendar. The team needed to replace some of the internal classes to add some custom logic and had been unsuccessful. They had seen my blog post on Extending Liferay OSGi Modules, but the warnings in the blog were taken to heart and they didn't want to go down that road unless it became necessary.

The calendar-service module has a bunch of internal classes that are instantiated and wired up using the internal Spring context set up for ServiceBuilder service modules. So the team needed to provide new template files, but in addition they needed custom classes to replace the instances wired up by Spring when setting up the context, a seemingly difficult ask.

The Spring aspects of the host module in addition to the appending nature of the fragment bundle handling actually makes this pretty easy to do...

First, create a fragment bundle using the host and version from the original.  For this override, it is com.liferay.calendar.service and rather than use a specific version, I opted for a range [2.3.0,3.0.0).

Next I added a new class, src/main/java/com/liferay/calendar/notification/impl/  It was basically a copy of the original EmailNotificationSender class from the same package, I just added in a bunch of log statements to see that it was being used.  Note that I was actually free to use any package I wanted to here, it really wasn't that important.

Next I added a src/main/resources/META-INF/spring/calendar-spring-ext.xml file to the fragment bundle with a replacement bean definition.  Instead of instantiating the original EmailNotificationSender, I just had to instantiate my custom class:

<?xml version="1.0"?>

	<!-- Replace the Liferay bean definition with our own. -->
	<bean class="com.liferay.calendar.notification.impl.NotificationSenderFactory" id="com.liferay.calendar.notification.impl.NotificationSenderFactory">
		<property name="notificationSenders">
				<entry key="email">
					<bean class="com.liferay.calendar.notification.impl.CustomEmailNotificationSender" />
				<entry key="im">
					<bean class="com.liferay.calendar.notification.impl.IMNotificationSender" />

So while I couldn't replace the old class, I could add a new class and a new Spring configuration file to replace the old definition with one that used my class.

Once the fragment was built and deployed, it was working as expected.  The project at this state is available here:

Additionally the team needed to alter the template files.  This was accomplished by adding a src/main/resources/ file with a replacement property key for the template to replace pointing to a new file also included in the fragment bundle.  Since the original file has an "include-and-override" line to pull in, when the fragment bundle is appended to the host the replacement property key will be used and the new file from the fragment bundle will be loaded.

What Else Can I Use Fragments For?

While I don't have working code to demonstrate each of these, the working example makes me think you can use a fragment bundle to extend an existing Liferay ServiceBuilder service module.

Since ServiceBuilder modules are Spring-based and the default Spring configuration declaring the service is in META-INF/spring/module-spring.xml, we can use a fragment bundle to add a META-INF/spring/module-spring-ext.xml file and replace a default wiring to a service instance to a custom class, one that perhaps extends the original but overrides whatever code from the original. Spring would instantiate our class, it would have the right heirarchy and should make everything work.

This wouldn't work for services from portal-impl since they are not loaded by OSGi ServiceBuilder host modules, but it should work for those that are deployed this way.

Another idea is that it could be used to override static .css and/or .js files from the host bundle. Well, not override per se, but introduce new files that, in addition to a Configuration Admin config file, could use the replacements in lieu of the originals.

So, for example, calendar-web has a /css/main.css (actually main.scss file, but it will be built to main.css) file that is pulled in by the portlet. We could use a fragment bundle to add a new file, /css/main-ext.scss file. It could either have everything from main.scss with your changes or it could just contain the changes depending upon how you wanted to manage it going forward.  As a new file, it could be loaded if the portal was going for the file.

The original file is pulled in by the portal due to the properties on the CalendarPortlet annotation:

	immediate = true,
	property = {
		"" + CalendarPortletKeys.CALENDAR,
	service = Portlet.class
public class CalendarPortlet extends MVCPortlet {

So we would need the portlet to use a new set of properties that specifically changed from /css/main.css to /css/main-ext.css. This we can do by adding a file to $LIFERAY_HOME/osgi/configs/com.liferay.calendar.web.internal.portlet.CalendarPortlet.cfg file. This file format as defined here: and basically allows you to create a file to replace configuration property key values w/ custom versions.

So in our file we would add a line, com.liferay.portlet.header-portlet-css=["/css/main.css","/css/main-ext.css"]. This is the format for including both files, if you just wanted the one file it would simply be com.liferay.portlet.header-portlet-css="/css/main-ext.css". This file would need to be manually deployed to the osgi/configs directory, but once it is done and combined with the fragment bundle, the main.css file and main-ext.css file would be included.

This is the same kind of process that you would use to handle static javascript files pulled in by the portlet's @Component annotation properties.


So OSGi Fragment Bundles can be used for things beyond simple JSP fragment bundles.

I'm hoping what I presented here gives you some ideas on how you might solve problems that you're facing with "overriding" Liferay default functionality.

If you have some ideas, please share below as they may be helpful to others struggling w/ similar issues.


Angular 2+ Portlets in DXP

Technical Blogs February 8, 2018 By David H Nebinger

So I've been working a lot more with Angular 2+ recently (Angular 4 actually, but that is not so important) and wanted to share some of my findings for those of you whom are interested...

Accessing the Liferay Javascript Object

So TypeScript is sensitive to defined variables, classes, objects, etc.  Which is good when you want to make sure you are building complex apps, type safety and compilation help to ensure that your code starts on a solid foundation.

However, without a corresponding .ts file to support your import of the Liferay javascript object, TypeScript will not be able to compile your code if you try to use the Liferay object.

That said, it is easy to get access to the Liferay object in your TypeScript code.  Near the top of your .ts file, add the following line:

declare var Liferay: any;

Drop it in like after your imports but before your class declaration.

This line basically tells Angular that there is an object, Liferay, out there and it is enough to pass the compile phase.

Alternatively you can use the following syntax:


to get to the object, but to me this is not really the cleanest looking line of code.

Supplying Callback Function References to Liferay

So much of the Liferay javascript functions take callback functions.  For example, if you wanted to use the and Liferay.on() mechanism for in-browser notification, the Liferay.on() function takes as the second argument a Javascript function.

But, when you're in your TypeScript code, your object methods are not pure javascript functions, plus as an object instance, the method is for a particular object, not a generic method.

But you can pass a bound pointer to an object method and Liferay will call that at the appropriate points.

For example, if you have a method like:

myAlert(event) {
  alert('Received event data ' +;

So if you want it to be called on a 'stuff-happened' event, you could wire it up like:

ngOnInit() {
  Liferay.on('stuff-happened', this.myAlert.bind(this));

The this.myAlert.bind(this) is used to bind up sort of a proxy to invoke the myAlert() method of the particular instance. If someone does a:'stuff-happened', { data: 'Yay!'});

Liferay will end up invoking the myAlert() method, providing the event object, and the method will invoke the alert() to show the details.

Sometimes it is advantageous to have the callback run inside of a zone.  We would change the above ngOnInit() method to:

constructor(private ngZone: NgZone) {}
myZoneAlert(event) { => this.myAlert(event));
ngOnInit() {
  Liferay.on('stuff-happened', this.myZoneAlert.bind(this));

Using NgRoute w/o APP_BASE_HREF Errors

When using NgRoute, I typically get runtime browser errors complaining Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.

This one is pretty easy to fix.  In your @NgModule declaration, you need to import the APP_BASE_HREF and declare it as a provider. For example:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { APP_BASE_HREF } from '@angular/common';

import { AppComponent } from './app.component';

  declarations: [
  imports: [
  providers: [{provide: APP_BASE_HREF, useValue : '/' }],
  bootstrap: [AppComponent]
export class AppModule { }

The important parts above are (a) the import of APP_BASE_HREF and (b) the declaration of the providers.

NgRoute Without Address Bar Changes

Personally I don't like NgRoute changing the address bar as it gives the really false impression that those URLs can be bookmarked or referenced or manually changed.  The first time you try this, though, you'll see the Liferay error page because Liferay has no idea what that URL is for, it doesn't know that Angular might have taken care of it if the page were rendered.

So I prefer just to block the address bar changing.  This doesn't give false impressions about the URL, plus if you have multiple Angular portlets on a page they are not fighting to change the address bar...

When I'm routing, I always include the skipLocationChange property:

this.router.navigateByUrl('path', { skipLocationChange: true });

Senna and Angular

Senna is Liferay's framework that basically allows for partial-page updates for non-SPA server side portlets. Well, it is actually a lot more than that, but for a JSP or Struts or Spring MVC portlet developer, it is Senna which is allowing your unmodified portlet to do partial page updates in the rendered portal page w/o a full page refresh.

Senna may or may not cause you problems for your Angular apps. I wouldn't disable it out of the gate, but if during testing you find that hokey things are happening, you might try disabling Senna to see if things clear up for you.

Find out how to disable Senna here:

I say try your app w/o disabling Senna first because, well, if you disable Senna globally then your non-SPA portlets revert to doing full page refreshes.


So that's really all of the tips and tricks I have at this point.

I guess one final thing I would leave you with is that the solutions presented above really have nothing to do with Liferay. That's kind of important, I found these solutions basically by googling for an answer, but I would leave Liferay out of the search query.

When you think about it, at the end of the day you're left with a browser with some HTML, some CSS, some Angular and non-Angular Javascript. Whatever problems you run into with Angular, if you try to solve them generically that solution will likely also work for fixing the problem under Liferay.

Don't get too hung up on trying to figure out why something in Angular is not working under Liferay, because you are not going to find a great deal of articles which talks about the two of them together.


The Power of Patience

Technical Blogs February 2, 2018 By David H Nebinger

So, as a developer, I'm like usually whacking my whole runtime environment and starting over.

Why? Well, regardless how much I try to keep it clean, cruft will find its way into the environment. I'm left with users I don't want, content I don't want, pages I'm not using any more, sites created to demo something I'm not demoing any more...

So I'll throw out my data directory, drop my database and create a new one, purge old logs, modules, osgi/state and the work directories, ... Basically I get back to a point where I am starting up a brand new bundle, all shiny and new.

One of the things I often find when I do this, though, is that I'm a lazy developer.

So for awhile I was actually writing code that had dependencies on some environmental aspect. For example, my code would assume that a custom field had been created, roles or organizations were defined, ...

When I would bring up the environment, my code would fail because I had forgotten to create the dependent data.

So I got a little smarter, and I learned about the Liferay Upgrade framework. I now use this framework when writing my modules so I can just deploy my modules and, if the dependent data is missing, it will be created automagically. This works really great and, from a deployment perspective, I can promote my modules to test, QA, and prod knowing that my modules will create whatever they have to have to function properly.

This has been working really well for me, well, until today.

Today I did one of my purges and then fired up the environment and my upgrade process was failing.

I had created an upgrade process that was creating a custom field for the User model object. The code totally works when deploying to a previously-running instance, but I was getting an error during startup after the purge because my code was executing before the portal finished loading all of the default data. So one of the things you need for a custom field is a company id to bind them to, but my upgrade process was running before the first Company record was created.

Not company record, no company ID, and my code was just throwing all kinds of exceptions.

So I was effectively still being lazy. I was assuming that my code always ran at a particular time and that certain things were already available, and I found that when starting up from a clean state my assumptions caused my code to fail.

Basically I wasn't waiting for a good time for my code to execute (well, I didn't think I had to wait).  As a module developer, we can all often assume that if our code works on a hot deploy, well then it will always work. The problem, of course, is that environment startup we really don't have control over when our modules load, when our components start. As far as OSGi is concerned, if the references have been resolved and injected, the component is good to go.

But often times our components may have some sort of dependency that is hard to declare. For me, I was dependent upon the initial Company record being available, and I can't really declare a dependency on that which OSGi would be able to verify. In this forum thread, the code wanted to unload a component that had not been loaded/started when the componen t was activated, so sometimes the right thing happened and sometimes it didn't.

So the key is to identify when you have code that really needs to wait on something, but also to have something identifiable to OSGi to wait on.

What if you can't identify something for OSGi such as the initial Company record? Or the creation of some service in a different module that you don't want to declare as an @Reference in your component?

One trick I like to do to solve this case is to add a final dependency on portal startup. By adding the following to your @Component class, you will typically get the right outcome:

@Reference(target = ModuleServiceLifecycle.PORTAL_INITIALIZED, unbind = "-")
protected void setModuleServiceLifecycle(ModuleServiceLifecycle moduleServiceLifecycle) { }

That's it. This code basically has OSGi wait to start your component until the portal has been initialized. Note that I'm not doing anything with the injected object; I'm just forcing OSGi to delay the start of my component until it can be injected.

Adding this line to my Upgrade class, I did my purge stuff and started up the portal. After the portal was initialized, the Company record is guaranteed to be available, and my Upgrade had no problem creating the custom field.


So, keep this in mind if you need to ensure that some component doesn't try to do its thing too early in the startup process.

Oh, and if you just need to enforce a start sequence between your own components? Well, just remember that OSGi will not start a component until its @References can be injected. So if B depends on A, and C depends on B, just add the necessary @Reference guys to B and C. At startup, OSGi will be able to start A (since it has no dependencies), which means it can then start B and finally start C, guaranteeing the startup sequence that you need to have.

DevCon 2017

General Blogs October 14, 2017 By David H Nebinger

So I've been home for almost a week now after having attended Devcon 2017 in Amsterdam.

I have to give a shout out to Pascal Brusset and his entire team for putting on a great event. The venue was great, the sessions were great, and the speakers were great too. I especially want to thank them and all of Liferay for letting me attend and give a presentation, it has been one of the things on my bucket list for a while now that I can now check off of the list.  cool  Note this doesn't mean I don't want to go again to a future one, hint hint hint...

And another shout out to my good friend, Olaf Kock, who organized the sold-out Unconference. I'm glad I was able to attend, and I'm going to be sure to sign up as early as I can next year so I can make the cut wink

I want to thank my friend Ray Auge for the idea about OSGi Subsystems; they solve a problem I've been concerned about, and once he planted the idea in my head I was able to burn the midnight oil and turn it into a new blog post.

For all of those who I had a chance to talk with and hopefully help a little, it was truly my honor. And to those that I didn't get a chance to, well that's something I hope to reconcile at a future event.

To those that attended my session on Development Pitfalls, thanks for attending. Remember if you have any questions or concerns, you can usually get a response from me in the forums.

Now I'm getting ready for next week's LSNA in Austin. I'm looking forward to catching up with some of my old friends and hopefully making some new ones.

If you're going to LSNA, feel free to stop me and say Hi or ask a question or whatever. To me, that's the best part of attending the events and getting to hear your problems and issues and potentially turning those into a new blog post.


OSGi Subsystems and Why You Want Them

Technical Blogs October 9, 2017 By David H Nebinger

So last week I'm sitting in an Unconference session at DevCon in a group talking about OSGi. I don't remember how it came up, but we got on a discussion about deployment issues and someone asked about creating an LPKG file (the format Liferay uses to distribute a single artifact containing many bundles). I explained that it might be possible to create a file, but the problem was that the format (outside of being a zip file) is not documented and subject to change at any moment.

That's when Ray Auge jumped in and stated that we didn't want to use LPKG files anyway. Instead we should be using Subsystems, an OSGi specification for packaging many bundles in a single artifact.

Well I had not heard of Subsystems before, so I jotted down a note to myself to do some research on them to see just what they were and how I could use them...


OSGi Subsystems is part of the R5 specification for OSGi.

"So What?" you might ask. Well, it turns out they are really useful.

For example, Liferay actually distributes all of their bundles as .lpkg files because it can be hard to distribute and deploy over 500 bundles, but it's actually pretty easy to distribute and deploy 7 .lpkg files.

The problem for us, though, is that the .lpkg file is undocumented and generally not for our use as developers and deployers.

Fine, but when it comes time for you to deploy your own app that consists of, say, 30 bundles, that deployment process can easily become a point of failure. It is all too easy to deploy 29 of the 30 files (without even knowing that one has been missed) or using the wrong version of one of the bundles...

As soon as the number of deployment artifacts grows that large, the risk of deployment failure or issue rises along with the artifact count.

What we need is an .lpkg-like mechanism to package all of our own custom artifacts into one or a small number of deployment artifacts.  This way we can keep the level of modularity we want with the bundles, but we can package them and deploy them together in a managable number of artifacts.

Enter the OSGi Subsystem Specification...

OSGi Subsystems

In case you haven't guessed it, subsystems represent a package or container of other bundles, fragments or even other subsystems.

Subsystems break down into three different types:

  1. Feature - A Feature subsystem is the simplest type and represents basically a container of bundles. All of the bundles in the feature subsystem are accessible from outside of the feature, and all of the bundles inside the feature can access outside bundles.
  2. Application - An Application subsystem is a container of bundles, but these bundles can only access bundles outside of the application; no outside bundles can use or leverage bundles or services inside of the application.
  3. Composite - A Composite subsystem is the most complex type, it is a container of bundles with fine-grained access control for bundles inside and outside of the subsystem.

While each of these types represent a container of bundles, the differences lie in accessibility inside of the subsystem or outside of the subsystem.

Although Subsystems has a lot of available features and functionality, I'm going to limit scope here to a discussion of feature subsystems. I see great value in being able to create a single artifact out of multiple bundles for deployment, but I tend to question the value in limiting or controlling access to the bundles. For most projects, that kind of (micro)management seems to be overkill; I'm guessing that these other types start to show their benefits as the project size increases.

That said, this blog post will help you get started with the simplest of subsystems, the Feature subsystem, but you'll have all of the necessary stuff installed as a foundation for your self-education on the other subsystem types.

You can find out about the full Subsystems specs and usage here:

Benefits of Feature Subsystems

Why do I see value in Feature Subsystems? Because they bring the following benefits to the table:

  • Simplifies deployment by reducing bundle count. Instead of pushing out 30 bundles for deployment, maybe I can reduce that to 5 or even 1.
  • Defines a named and semanticaly-versioned grouping of the contained bundles. Want to release version 1.1 of your portlet? Fine, it may consist of 1.3 of an api, 1.22 of an impl bundle and 1.8 of the portlet module, but they can all version together inside the subsystem.

These are the benefits that are clear to me. There may be others related to management (and scope control if you build an Application or Composite subsystem), plus others that you might see that I'm missing.

Installing Subsystems into Liferay

Okay, so there are a number of bundles you'll need to download and drop into your Liferay deploy folder:

Group ID Artifact ID Version Link
org.apache.aries.subsystem org.apache.aries.subsystem.api 2.0.6
org.apache.aries.subsystem org.apache.aries.subsystem.core 2.0.6
org.apache.aries org.apache.aries.util 1.1.1
org.apache.felix org.apache.felix.coordinator 1.0.0
org.eclipse.equinox org.eclipse.equinox.region 1.2.101.v20150831-1342
org.slf4j slf4j-api 1.7.12
org.apache.aries.subsystem org.apache.aries.subsystem.gogo-command 1.0.0

Note: You may want to check to see if there are newer versions you might want to use.

When using SLF4J, you also need to provide a binding to an actual logging implementation. I want the messages to go to the Liferay logging system, so I created an SLF4J binding for the Liferay logging system. You can get the project here:

After they have deployed, you can drop into the Gogo shell to check their status:

g! lb | grep slf4j        
  534|Active     |   10|slf4j-liferay (1.7.12)
  535|Active     |   10|slf4j-api (1.7.12)
g! lb | grep Apache       
   25|Active     |    6|Apache Commons FileUpload (1.3.2)
   27|Active     |    6|Apache Felix Bundle Repository (2.0.2.LIFERAY-PATCHED-1)
   28|Active     |    6|Apache Felix Configuration Admin Service (1.8.8)
   29|Active     |    6|Apache Felix Dependency Manager (3.2.0)
   30|Active     |    6|Apache Felix Dependency Manager Shell (3.2.0)
   31|Active     |    6|Apache Felix EventAdmin (1.4.6)
   32|Active     |    6|Apache Felix File Install (3.5.4.LIFERAY-PATCHED-1)
   33|Active     |    6|Apache Felix Gogo Command (0.12.0)
   34|Active     |    6|Apache Felix Gogo Runtime (0.10.0)
   35|Active     |    6|Apache Felix Gogo Shell (0.10.0)
   36|Active     |    6|Apache Felix Declarative Services (2.0.6)
  537|Active     |   10|Apache Aries Util (1.1.1)
  538|Active     |   10|Apache Felix Coordinator Service (1.0.0)
  539|Active     |   10|Apache Aries Subsystem Core (2.0.6)
  540|Active     |   10|Apache Aries Subsystem API (2.0.6)
  542|Active     |   10|Apache Aries Subsystem Gogo command (1.0.0)
g! lb | grep region       
  541|Active     |    1|org.osgi.service.subsystem.region.context.0 (1.0.0)

I've highlighted the new bundles that we loaded.

Part of the deployed bundles includes a new Gogo command for subsystems:

g! subsystem:list
0	ACTIVE	org.osgi.service.subsystem.root 1.0.0

At this point you've installed subsystems, so lets go on to building and deploying one.

Building an Enterprise Subsystem Archive

Hey, before you start on this step, do yourself a favor and make sure your bundles deploy outside of Subsystems. My first pass at this was based off of using some modules I built out of the Blade Samples. I used those to create an esa archive and tried to deploy it and got some errors. Thinking they were Subsystem errors, I spent some time trying to resolve them. Eventually I decided just to make sure they would work and deploy them directly and all of the errors I was seeing were still there. The modules I had built were not complete and they wouldn't activate whether as normal bundles or within a Subsystem. I started over with clean projects, got them working by deploying directly and only when that was all working did I proceed to work this step.

Moral of the story - Only build an ESA archive out of working, deployable modules.

So, in case you haven't guessed it yet, we need to build a zip file (it is an archive after all) with the extension .esa, this is our Enterprise Subsystem Archive.

Building an esa archive is actually kind of easy.

If you're using Maven, you're going to be leveraging the ESA Maven Plugin. If you're using Ant or Gradle, you're going to be leveraging the ESA Ant Task. For those of you who are new to Gradle, you might want to check out how to invoke Ant from within your Gradle build script.

I created a rather simple set of modules available via this Github repo for a maven workspace: There's two ServiceBuilder modules, one an API and one a service jar, and there's also a portlet module to do CRUD operations. The entities represent and extremely simple "event" system for booking events for conference rooms.

Each of the three modules were deployed directly into a local dev environment to ensure they could start and be active in the portal.

Our go at this is going to be based on pulling in dependencies to be part of the esa archive. I created a new submodule in the project, subsystem-events-esa, to pull in the dependencies. I like to use mvn archetype:generate to start a new project, but you can create one however you'd like.

Then we need to update the pom. This is the one I came up with:

<?xml version="1.0"?>
<project xsi:schemaLocation="" xmlns=""






Now when you build this guy, you will get a foo-1.0.0.esa file in the target folder. Peel him open with your zip tool and you should see something like:

Subsystems ESA Archive Contents

So what did we end up with?

Well, we have our three dependencies that were listed in the pom. There's a couple of Maven pom artifacts that we don't really worry about. The other thing we have is the SUBSYSTEM.MF file:

Subsystem-ManifestVersion: 1
Subsystem-SymbolicName: com.dnebinger.subsystem-events-esa
Subsystem-Version: 1.0.0
Subsystem-Name: subsystem-events-esa
Subsystem-Type: osgi.subsystem.feature

If you check the pom, I asked for the file to be generated. You can just as easily specify your own if you wanted to.

This file defines the subsystem, the modules it contains and has the semantic versioning details for the esa.

Deploying the esa Archive

So we built it, let's deploy it. Note that I'm using a clean bundle here, not one where the foo Blade samples have already been deployed to.

Drop the foo-1.0.0.esa file in the Liferay deploy folder and...

Nothing. Which is kind of what I expected. You see, Liferay has an extension point for the Felix FileInstall module to handle .lpkg files and, well, we need a similar extension to support the esa Archives.

Fortunately for everyone, I've already created it. The whole project is available at Build the module and drop it into your Liferay deploy folder. Any .esa file dropped in the Liferay deploy folder will be picked up by the module and moved to the osgi/modules directory where it will be processed by OSGi and the Felix FileInstall service.

With this module in place, the .esa file will be picked up and processed. With our new subsystem Gogo command, we can now see the following:

g! subsystem:list
0	ACTIVE	org.osgi.service.subsystem.root 1.0.0
3	ACTIVE	com.dnebinger.subsystem-events-esa 1.0.0

So the subsystem looks good, but how about our bundles?

g! lb | grep subsystem-events
  548|Active     |    1|subsystem-events-service (1.0.0)
  549|Active     |    1|subsystem-events-api (1.0.0)
  550|Active     |    1|subsystem-events-web (1.0.0)

That's exactly what we hope to see! Since the bundles are all valid, you can now log into the portal and place the portlet on a page and try it out.


So that's really it. We can now leverage OSGi Subsystems in our portal. This allows us to build an esa archive file containing multiple files (bundles, fragments or other subsystem esa files) and deploy them as a single unit.

Here I've presented how to use the Feature subsystem type that has no limits on using bundles in the subsystem or bundles outside the subsystem it can use.

The two other subsystem types, the Application and Composite types, I didn't do anything with. If you come up with a valid use case or some example code, please share as I'm sure we'd like to hear about your successes.

Necessary SiteMinder Configuration...

Technical Blogs September 8, 2017 By David H Nebinger

A quick note for those using SiteMinder and Liferay...

Liferay likes the Tilde (~) character, and uses it quite often for friendly URLs and other reasons.

When fronting with SiteMinder, though, you may run into return code 500 for URLs with the tilde character in them.

This is actually a default SiteMinder configuration thing, SiteMinder treats tilde (and others) as "bad characters" and will return a 500 when they are found.

The default SiteMinder configuration has this setting:

BadUrlChars       //,./,/.,/*,*.,~,\,%00-%1f,%7f-%ff,%25

You want to override the default configuration to allow the tilde character:

BadUrlChars       //,./,/.,/*,*.,\,%00-%1f,%7f-%ff,%25

After making this change, restart the daemons and you should be back in business.

Leveraging Maven Proxies

Technical Blogs July 12, 2017 By David H Nebinger

Taking a short break from the Vue.js portlet because I had to implement a repository proxy. Since I was implementing it, I wanted to blog about it and give you the option of implementing one too. Next blog post will be back to Vue.js, however...


I love love love Maven repositories. I can distribute a small project w/o all of the dependencies included and trust that the receiver will be able to pull the dependencies when/if they do a build.

And I like downloading small project files such as the Liferay source separately from the multitude of dependencies that would otherwise make the download take forever.

But you know what I hate? Maven repositories.  Well, downloading from remote Maven repositories. Especially if I have to pull the same file over and over. Or when the internet is slow or out and development grinds to a halt. Or maintenance on the remote Maven repositories makes them unavailable for some unknown period of time.

Now, of course the Maven (and Gradle and Ivy) tools know about remote repository download issues and will actually leverage a local repository cache so you really only have to download once. Except that they made this support optional, and frankly it gets overlooked a lot. The default Liferay Gradle repository references don't list mavenLocal() in the repo list and it is not used by default.

Enterprise or multi-system users (like myself) have additional remote repository issues.  First, a local repo on one user's system is not shared w/ a team or multiple systems, so you end up having to pull the file to your internal network multiple times, even if it has already been pulled before.

A complete list of use cases would include:

  • Anyone developing behind an HTTP proxy (typical corporate users). Using a repository proxy removes all of the necessary proxy configuration from your development tools, the repository proxy needs to know how to connect through the HTTP proxy, but your dev tools don't.
  • Anyone developing in teams. Using a repository proxy, you will only pay for downloading to your network once, then all developers will be able to access the artifact from the proxy and not have to download on their own.
  • Anyone using an approved artifact list. Using a repository proxy populated with approved artifacts and versions, you have automatic control over the development environment to ensure that an unapproved version does not get through.
  • Anyone developing in multiple workspaces, projects, or machines. Shares the benefits from the team development where you only download once, then share the artifact.
  • Anyone who suffers network outages. Using a repository proxy, you can pull previously loaded artifacts even when the external network is down. You can't pull new artifacts, but you should have most of the ones you regularly use.
  • Anyone who needs to publish team artifacts. A repository proxy can also hold your own published artifacts, so it is easy to share those with the team and use each others artifacts as dependencies.
  • Anyone using a secured continuous integration server. CI servers should not have access to the interweb, but they still need to pull dependencies for builds. The repository proxy gives your CI server a repository to pull from without having direct internet access.
  • Anyone behind a slow internet link. Your internal network is typically always faster than your uplink, so having a local proxy cache of artifacts reduces or eliminates lag issues from your uplink.
  • Anyone interested in simplifying repository references. Liferay uses two repositories, a public mavenCentral mirror and a release repository. Then there's mavenCentral, of course, and there are other repositories out there too. By using a proxy, you can have a single repository reference in your development tools, but that reference could actually represent all of these separate repositories as a single entity.

So I'm finally giving up the ghost, I'm moving to a repository proxy.

What Is A Repository Proxy?

For those that don't know, a repository proxy is basically a local service that you're going to run that proxies artifact requests to remote Maven repositories and caches the artifacts to serve back later on. It's not a full mirror of the external repositories because it doesn't pull and cache everything from the repository, only the artifacts and versions you use.

So for most of us, our internal network is usually significantly faster than the interweb link, so once the proxy cache is fully populated, you'll notice a big jump when building new projects. And for team development, the entire team can benefit from leveraging the cache.

Setting Up A Repository Proxy

There are actually a bunch of freely-available repository proxies you can use. One popular option is Artifactory.  But for my purposes, I'm going to set up Apache Archiva. It's a little lighter than Artifactory and can be easily deployed into an existing Tomcat container (Artifactory used to support that, but they've since buried or deprecated using a war deployment).

The proxy you choose is not so important, it will just impact how you go about configuring it for the various Liferay remote repositories.

Follow the instructions from the Archiva site to deploy and start your Archiva instance. In the example I'm showing below, I have a local Tomcat 7 instance running on port 888 and have deployed the Archiva war file per the site instructions. After starting it up, I created a new administrator account and was ready to move on to the next steps.

Once you're in, add two remote repositories:

These two repositories are used by Liferay for public and private artifacts.  Order the liferay-public-releases guy first, then the public one second.

In Archiva, you also need to define proxy connectors:

Once these are set, you can then define a local repository:

Initially if you browse your artifacts, your list will be empty. Later, after using your repo proxy, when you browse you should see the artifacts.

And finally you may want to use a repository group so you only need a single URL to access all of your individual repositories.

Configuring Liferay Dev Tools For The Repository Proxy

So this is really the meat of this post, how to configure all of the various Liferay development tools to leverage the repository proxy.

In all examples below, I'm just pointing at a service running on localhost port 888; for your own environment, you'll just make necessary changes to the URL for host/port details, but otherwise the changes will be similar.

Liferay Gradle Workspace

This is handled by changing the root settings.gradle file.  You'll take out references to and instead just point at your local proxy as such:

buildscript {
  dependencies {
    classpath group: "com.liferay", name: "com.liferay.gradle.plugins.workspace", version: "1.0.40"

  repositories {
    maven {
      url "http://localhost:888/archiva/repository/liferay/"

apply plugin: "com.liferay.workspace"

Now if you happen to have other repositories listed, you may want to make sure that they too are pushed up to your repository proxy. No reason to not do so. And by using the repository group, we can simplify the repository list in the settings.gradle file.

This is the only file that typically has repositories listed, but if you have an existing workspace you might have added some references to the root build.gradle file or a build.gradle file in one of the subdirectories.

Liferay Gradle Projects

For standalone Liferay Gradle projects, your repositories are listed in the build.gradle file, these will also change to point at the repository proxy:

buildscript {
  dependencies {
    classpath group: "com.liferay", name: "com.liferay.gradle.plugins", version: "3.1.3"

  repositories {

    maven {
      url "http://localhost:888/archiva/repository/liferay/"

apply plugin: "com.liferay.plugin"

dependencies {
  compileOnly group: "org.osgi", name: "org.osgi.core", version: "6.0.0"
  compileOnly group: "org.osgi", name: "org.osgi.service.component.annotations", version: "1.3.0"

repositories {

  maven {
    url "http://localhost:888/archiva/repository/liferay/"

Global Gradle Mirrors

Gradle supports the concept of "init" scripts.  These are global scripts that are executed before tasks and can tweak the build process that the build.gradle or settings.gradle might otherwise define. Create a file in your ~/.gradle directory called init.gradle and set it to the following:

allprojects {
  buildscript {
    repositories {
      maven { url "http://localhost:888/archiva/repository/liferay" }
  repositories {
    maven { url "http://localhost:888/archiva/repository/liferay" }

This should normally have all Gradle projects use your local Maven repository first and your new proxy repository second.  Any repositories listed in the build.gradle or settings.gradle file will come after these. This also sets repository settings for both Gradle plugin lookups as well as general build dependency resolution.

Liferay SDK

The Liferay SDK leverages Ant and Ivy for remote repository access. Our change here is to point Ivy at our repository proxy.

Edit the main ivy-settings.xml file to point at the repository proxy:

  <settings defaultResolver="default" />

    <ibiblio m2compatible="true" name="liferay" root="http://localhost:888/archiva/repository/liferay/" />
    <ibiblio m2compatible="true" name="local-m2" root="file://${user.home}/.m2/repository" />

    <chain dual="true" name="default">
      <resolver ref="local-m2" />

      <resolver ref="liferay" />

Liferay Maven Projects

For simple Liferay Maven projects, we just have to update the repository like we would for any normal pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">



Liferay Maven Workspace

The Liferay Maven Workspace is a new workspace based on Maven instead of Gradle. You can learn more about it here.

In the root pom.xml file, we're going to add our repository entry but we also want to disable using the Liferay CDN as the default repository:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">




Global Maven Mirrors

Maven supports the concept of mirrors, these can be local repositories that should be used in place of other commonly named repositories.  Create (or update) your ~/.m2/settings.xml file and make sure you have the following:

<settings xmlns=""

      <name>Repo Proxy</name>

The <mirrorOf /> tag using the wildcard means that this repository is a mirror for all repositories and Maven builds will go to this repository proxy for all dependencies, build or otherwise.

Configuring Liferay Source For The Repository Proxy

We took care of all of your individual project builds, but what about if you have the source locally and want to build it using the repository proxy?

I actually combined a bunch of the previous listed techniques. For the maven portion of the build (if there is one), my settings.xml mirror declaration ensures that my repo proxy will be used. For the Gradle portion of the build, I used the init.gradle script (although I copied my ~/.gradle/init.gradle to the .gradle directory created inside of the folder as the ~/.gradle/init.gradle script was ignored).

In addition, in my build.<username>.properties file, I set basejar.url=http://localhost:888/archiva/repository/liferay.

And I also had to set my ANT_OPTS environment variable, so I used "-Xmx8192m -Drepository.url=http://localhost:888/archiva/repository/liferay".

With all of these changes, I was able to build the liferay-portal from master with all dependencies coming through my repository proxy.

You might be wondering why you would want to go through this exercise. For me, it seemed like an ideal way to pre-populate my proxy with most of the necessary public dependencies and Liferay modules. Sure this isn't necessary because, since we're using a proxy, if we need an updated version later on the proxy will happily fetch it for us. It's just a way to pre-populate with a lot of the artifacts that you'll be needing.

Publishing Artifacts

The other big reason to use a local repository service is the ability to publish your own artifacts into the repository. When you're working in teams, being able to publish artifacts into the repository so teammates can use the artifacts without building themselves can be quite valuable. This will also force you to address your versioning strategy since you need to bump versions when you publish; I see this as a good thing because it will force you to have a strategy going into a project rather than trying to create one in the middle or at the end of the project.

So next we'll look into the changes necessary to support publishing from each of the Liferay development environments to your new repository service.

Note that we're going to assume that you've set up users in the repository service to ensure you don't get uploads from unauthorized users, so these instructions will include the details for setting up the repository with authenticated access for publishing.

Finally, during the research for this blog post I have quickly come to find that there different ways to publish artifacts, sometimes even based on the repository proxy you're using. For example, the fine folks at JFrog actually have their own Gradle plugin to support Artifactory publication. I didn't try it since I'm currently targeting Archiva, but you might want to look it over if you are targeting Artifactory.

These instructions are staying with the generic plugins so they might work across repositories w/o much change, but obviously you should test them out for yourself.

Liferay Gradle Workspace

The Liferay workspace was actually the most challenging configuration out of all of these different methods if only because tweaking the various build.gradle files to support the subproject publication can take a while.

In fact, Gradle has an older uploadArchives() method that has since been replaced by a newer maven-publish plugin, but for the life of me I couldn't get the submodules to work right with it. I could get submodules to use maven-publish if each submodule build.gradle file had the full stanzas for individual publication, but then I couldn't get the gradlew publish command to work in the root project.

So the instructions here purposefully leverage the older uploadArchives() method because I could get it working with the bulk of the configuration and setup in the root build.gradle and minor updates to the submodule build.gradle files.

Add Properties

The first thing we will do is add properties to the root file. This will isolate the URL and publication credentials and keep them out of the build.gradle files. For SCM purposes, you would not want to check this file into revision control as it would expose the publishers credentials to those who have access to the revision control system.

# Define the URL we'll be publishing to

# Define the username and password for authenticated publish

Root build.gradle Changes

The root build.gradle file is where the bulk of the changes go. By adding the following content to this file, we are adding support for publishing to every submodule that might be added to the Liferay Workspace.

// define the publish for all subprojects
allprojects {

  // all of our artifacts in this workspace publish to same group id
  // set this to your own group or override in submodule build.gradle files
  // if they need to change in the submodules.
  group = 'com.dnebinger.gradle'
  apply plugin: 'java'
  apply plugin: 'maven'
  // define a task for the javadocs
  task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from 'build/docs/javadoc'
  // define a task for the sources
  task sourcesJar(type: Jar) {
    classifier = 'sources'
    from sourceSets.main.allSource
  // list all of the artifacts that will be created and published
  artifacts {
    archives jar
    archives javadocJar
    archives sourcesJar
  // configure the publication stuff
  uploadArchives {
    // disable upload, force each submodule to enable
    enabled false
    repositories.mavenDeployer {
      repository(url: project.publishUrl) {
        authentication(userName: project.publishUsername, password: project.publishPassword)

The instructions in this file will have you building a source jar and a javadocs jar. These and the build artifacts will all be published to the repository from the file using the credentials from that file.

Note that by default the upload is disabled for all subprojects. This forces us to enable the upload in those individual submodules we want to set it up for.

Submodule build.gradle Changes

In each submodule where we want to publish to the repo, there are two sets of simple changes to make.

// define the version that we will publish to the repo as
version = '1.0.0'

// change group value here if must differ from the one in the root build.gradle.

dependencies {

// enable the upload
uploadArchives { enabled true }

We specify the version for publishing and enable the uploadArchives for the submodule.

Publish Archives

That's pretty much it.  In both the root directory as well as in the individual module directories you can issue the command gradlew uploadArchives and (if you get a good build) the artifacts will be published to the repository.

Liferay Gradle Projects

Liferay gradle projects get a similar modification as the Liferay Gradle Workspace modifications, but they're a little easier since you don't have to worry about submodules.

From the previous Liferay Gradle Workspace section above, add the same property values to the file. If you don't have a file, you can create one with the listed properties.

Build.gradle Changes

The changes we make to the build.gradle file are similar, but are still different enough:

buildscript {
  dependencies {
    classpath group: "com.liferay", name: "com.liferay.gradle.plugins", version: "3.3.9"

  repositories {
    maven {
      url "http://localhost:888/archiva/repository/liferay"

apply plugin: "com.liferay.plugin"
apply plugin: 'java'
apply plugin: 'maven'

repositories {

  maven {
    url "http://localhost:888/archiva/repository/liferay"

// define the group and versions for the artifacts
group = 'com.dnebinger.gradle'
version = '1.0.3'

dependencies {

// define a task for the javadocs
task javadocJar(type: Jar, dependsOn: javadoc) {
  classifier = 'javadoc'
  from 'build/docs/javadoc'

// define a task for the sources
task sourcesJar(type: Jar) {
  classifier = 'sources'
  from sourceSets.main.allSource

// list all of the artifacts
artifacts {
  archives jar
  archives javadocJar
  archives sourcesJar

// configure the publication stuff
uploadArchives {
  repositories.mavenDeployer {
    repository(url: project.publishUrl) {
      authentication(userName: project.publishUsername, password: project.publishPassword)

That's pretty much it.  Like the previous section, this build.gradle file supports creating the javadoc and source jars and will upload those using the same gradlew uploadArchives command.

Liferay SDK

In the Liferay SDK we have to configure Ivy to support the artifact publication. And actually this is quite easy because Liferay has already configured ivy to support their internal deployments to an internal Sonatype server, we just have to override the properties.

In your file in the root of the SDK, you need to just add some property overrides:


That is your configuration for publishing. After building your plugin, i.e. using the ant war command, just issue the ant publish command to push the artifact to the repository. If you run ant jar-javadoc before the ant publish, your javadocs will be generated so they'll be available for publishing too. There's also an ant jar-source target available, but I didn't see where it was being uploaded to the repository, so that might not be supported by the SDK scripts.

One thing I did find, though, is that in each plugin you plan on publishing, you should edit the ivy.xml file in the plugin directory. The ivy.xml file has, as the first tag element, the line:

<info module="hello-portlet" organisation="com.liferay">

The organisation attribute is actually going to be the group id used during publishing so, unless you want all of your plugins to be in the com.liferay group, you'll want to edit the file to set it to what you need it to be.

I did check the templates and there doesn't seem to be a way to configure it.  The templates are all available in the SDK's tools/templates directory, so you could go into all of the individual ivy.xml files and set the value you want, that way as you create new plugins using the templates the default value will be your own.

Note that this only applies if you create plugins using the command line; I'm honestly not sure if you are using the Liferay IDE that the templates in the SDK folder are actually the ones the IDE uses for new plugin project creation.

Liferay Maven Projects

Liferay Maven projects are, well, simple projects based on Maven.  I'm not going to dive into all of the files here, but suffice it to say you add your repository servers, usually in your settings.xml file, and then you add to the pom file:

    <name>Internal Release Repository</name>
    <name>Internal Snapshot Repository</name>

With just this addition, you can use the mvn deploy command to push up your artifacts. Additionally, you can add support for publishing the javadocs and sources too:

Liferay Maven Workspace

For publishing purposes, the Liferay Maven workspace is merely a collection of submodules. This means that Maven pretty much is going to support the publication of submodules after you complete the configuration and pom changes mentioned in the previous Liferay Maven Projects section.

Normally the mvn deploy command will publish all of the submodules, but you can selectively disable submodule publish by configuring the plugin in the submodule pom:


This blog post ended up being a lot bigger than what I originally planned, but it does contain a great deal of information.

We reviewed how to set up an Archiva instance to use for your repository proxy.

We checked out the changes to make in each one of the Liferay development frameworks to leverage the repository proxy to pull all dependencies from the repository proxy, whether that proxy is Apache Archiva, Artifactory or Nexus.

We also learned how to configure each of the development frameworks to support publishing of the artifacts to share with the development team.

A lot of good stuff, if you ask me. I hope you find these details useful and, of course, if you have any comments leave them below and any questions, well post them to the forum and we'll help you out.

As a test, I timed the complete build of the after deleting my ~/.m2/repository folder (purging my local system repository). Without the repository proxy, downloading all of the dependencies and completing the build took 69 seconds (note I have gigabit ethernet at home, so your numbers are going to vary from that). After purging ~/.m2/repository again and configuring for the repository proxy (pre-populated with artifacts), downloading all of the dependencies and completing the build took 45 seconds.

That is almost a 35% reduction in build time, and it means that 35% of the total build is taken to download artifacts even over my gigabit ethernet.

If you do not have gigabit ethernet where you're at, it would not surprise me to see that time to download increase, taking the % of reduction up along with it.

Building JS Portlets Part 2

Technical Blogs June 27, 2017 By David H Nebinger


In part 1 of the blog series, we started a Vue.js portlet based in the Liferay Workspace, but actually there was no JS framework introduced just yet.

We're actually going to continue that trend here in part 2, but in this part we're going to tackle some of the important parts that we'll need in our JS portlets to fit them into Liferay.

Passing Portlet Instance Configuration

In part 1 our view.jsp page used the portlet instance configuration, displayed as two text lines:

<%@ include file="/init.jsp" %>

  <b><liferay-ui:message key="vue-portlet-1.caption"/></b>
<p><liferay-ui:message key=""/> <%= 
  String.valueOf(portletInstanceConfig.flagOne()) %></p>
<p><liferay-ui:message key="caption.flag.two"/> <%= 
  String.valueOf(portletInstanceConfig.flagTwo()) %></p>

We're actually going to continue this, but we're going to leverage our <aui:script /> tag to leverage it in a new addition to the JSP:


var <portlet:namespace/>portletPreferences = {
	flag: {
		one: <%= portletInstanceConfig.flagOne() %>,
		two: <%= portletInstanceConfig.flagTwo() %>


Using <aui:script />, we're embedding javascript into the JSP.

Inside of the script tag, we declare a new variable with the name portletPreferences (although this name is namespaced to prevent a name collision with another portlet on the page).

We initialize the variable as an object which contains our portlet preferences. In this example the individual flags have been set underneath a contained flag object, but the structure can be whatever you want.

The goal here is to create a unique Javascript object that will hold the portlet instance configuration values. We need to extract them in the JSP because once the code is over and running in the browser, it will not have access to the portlet config. Using this technique, we get all of the prefs in a Javascript variable so they will be available to the running JS portlet in the browser.

Passing Permissions

We're actually going to continue this technique to pass permissions from the back end to the JS portlet:

var <portlet:namespace/>permissions = {
	<c:if test="Validator.isNotNull(permissionChecker)">
		isSignedIn: <%= permissionChecker.isSignedIn() %>,
		isOmniAdmin: <%= permissionChecker.isOmniadmin() %>,
		hasViewOrgPermission: <%= permissionChecker.hasPermission(null, 
		  Organization.class.getName(), Organization.class.getName(), 
		  ActionKeys.VIEW) %>
	<c:if test="Validator.isNull(permissionChecker)">
		isSignedIn: false,
		isOmniAdmin: false,
		hasViewOrgPermission: false

Here we're trying to use the permission checker added by the init.jsp's <liferay-theme:defineObjects /> tag.

Although I'm confident I should never get a null permission checker instance, I'm using defensive programming to ensure that I can populate my permissions object even if the checker is not available.

When it is, I'm basically populating the object with keys for the permissions and then a scriptlet to evaluate whether the current user has the permission details.

Since we are building this as a Javascript object, we will be able to collect all of the permissions when the JSP is rendering the initial HTML fragment and allows us to ship the permissions back to the browser so the portlet can use the permissions to make decisions on what to view and what to allow editing on.

The only thing you need to figure out is what permissions you will need on the front end; once you know that, you can use this technique to gather those permissions and ship them to the browser.

NOTE: This does not replace the full use of the permission checker on the back end when processing requests. This technique passes the permissions to the browser, but as we all know it is easy for hackers to adjust these settings once retrieved in order to try to circumvent the permissions. These should be used to manage the UI, but in no way, shape or form should the browser control permissions when invoking services on the backend.


The previous sections have been fairly straight-forward; we have data on the backend (prefs and permissions) we need to have on front end but really only one way to pass them.

Handling the I18N in the JS portlets comes with a couple of alternatives.

It would actually be quite easy to continue the technique we used above:

var <portlet:namespace />languageKeys = {
	accessDenied: '<liferay-ui:message key="access-denied" />',
	active: '<liferay-ui:message key="active" />',
	localCustomMessage: '<liferay-ui:message key="local-custom-message" />'

I can tell you that this technique is extremely tedious. I mean, most apps have tens if not hundreds of language keys for buttons, messages, labels, etc. Itemizing them here will get the job done, but it is a lot of work.

Fortunately we have an alternative. Liferay actually provides the Liferay.Language.get(key) Javascript function. This function will conveniently call the back end to translate the given key parameter using the backend language bundle resolution. It is backed by a cache on the browser side so multiple calls for the same key will only call the backend once.

So, rather than passing the 'access-denied' message like we did above, we could just remember to replace hard-coded strings from our JS portlet's template code with calls like Liferay.Language.get('access-denied'). We would likely see the following for Vue templates:

var app5 = new Vue({
  el: '#app-5',
  data: {
    message: Liferay.Language.get('access-denied')
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')

Although this is convenient, it too has a problem. Because of how the backend resolves keys, only resource bundles registered with the portal can be resolved. If you are only going after Liferay known keys, that's no problem. But to use your local resource bundle, you will need to register it into the portal per instructions available here: Note that you're not overriding so much as adding your local resource bundle into the mix to expose your language bundle.

So actually to keep things simple I would recommend a mixed implementation. For existing Liferay keys, use the Liferay.Language.get() method to pull the value from the backend. But instead of registering an additional resource bundle in the portal, just use the script-based technique above to pass your local keys.

This will minimize your coding impact, but if your local bundle has tens or hundreds of your own keys, well you might find it easier to just register your language bundle and stick with Liferay.Language.get().


What what? We're at the end of part 2 and still no real Javascript framework integration?

That is correct, we haven't pulled in Vue.js yet, although we will be doing that in Part 3.

I think that it is important to note that from our original 6 prerequisites, we have already either fully or partially satisfied:

  • Prereq #1 - Using the Liferay Workspace.
  • Prereq #6 - Using the Liferay Environment.

The big conclusion here is that we can use this pattern to preload data from the portal side to include in the JS applications, data which is otherwise not available in the browser once the JS app is running.  You can apply this pattern for collecting and passing data that you want available to the JS app w/o providing a runtime fetch mechanism or exposing portal/portlet data.

Note: Of course in my JSP/Javascript stuff above, there is no verification of JS, no proper handling of string encoding and other protections you might use to ensure you are not serving up some sort of JS attack. Just because I didn't present it, doesn't mean that you shouldn't include it in your production apps.

See you in Part 3...


Building JS Portlets Part 1

Technical Blogs June 27, 2017 By David H Nebinger


In Liferay 7 CE / Liferay DXP, there are new facilities in place to help us create JS portlets. In this blog series I'm going to present a new project to demonstrate how to build Vue.js portlets.

Vue.js is a lightweight JS framework similar to React or Angular or ... I'm actually picking Vue.js for this series not so much because I think it is better than the other frameworks, but mostly because I want to focus on building JS portlets and I don't want to get hung up on perfect React or Angular implementation. I figured that by picking a newer framework I could present topics that affect all implementations and avoid the framework debates.

And who knows, maybe this will start a big trend of adopting Vue.js in Liferay. We'll just see how it goes.


So I'm going to lay down some prerequisites, but they are not requirements per se, they're just things that I want to have being a regular portlet developer.

So prereq #1 is that the portlet has to fit into my Liferay Workspace. I mean, I'm building all kinds of modules in there: JSP fragment bundles, Service Builder modules, Liferay MVC portlet modules, etc. I don't want to maintain two separate repositories for normal stuff and JS stuff. So the JS portlets must fit into the Gradle-based Liferay Workspace for the general build process. I'm okay with the module leveraging other tools (gulp, npm, etc.) the portlets might need, but the Gradle build must rule them all.

Prereq #2 is that I need open and unfettered access to the internet. I know a lot of developers sit behind proxies and that's okay, as long as they can get to the web for plugins and projects from GitHub, open maven repositories, NPM repositories, etc. If you find yourself in a secured environment that needs approval for all external tools, libraries, etc., you might want to stop now and rethink following along here. All of the JS-based portlets are going to leverage a lot of new stuff from NPM, new build tools such as Gulp, new build plugins from Liferay GitHub repositories, etc.  There's going to be a long list of external sites to pull from, and if you need to get permissions for each one there is going to be a ton of red tape in your future. You might be better served just sticking with Liferay MVC portlet implementations and rely on the built-in SennaJS support to provide the ajaxy-sort of responsiveness we all expect now.

For the record, there really is nothing wrong with sticking with Liferay MVC and SennaJS. When you do a Liferay DXP trial walkthru and use the portlets on a page, you'll see that there are few full page refreshes, and when there are they are usually a result of page navigation within the portal. The portlets themselves are still using the regular Portlet Lifecycle, they're just getting invoked via AJAX and the browser is going to be doing partial DOM updates in the page. So you can get most of the benefits from the new whiz-bang JS frameworks without retooling yourself or your team.

Prereq #3 concerns deployment; I'd like to be able and build and deploy my portlet independently without requiring supporting theme work. As of right now I'm not 100% confident that will work or even that it is the best path, but it is something that I'd like to shoot for. To me, the more things that make a portlet deployment difficult, the more things there are that can go wrong during deployment.

Prereq #4 is that I am really only targeting JS portlets. I have no plan on co-running my Vue.js apps as both portlets and straight-up web apps, so I have no plans on testing, styling or running these guys outside of the portal.

Prereq #5 is that since they are running within the portal, I expect the UI to be consistent with the rest of the portal; buttons should look the same, fonts, etc. I don't want to have a portlet that stands out just because it is from some other framework type.

And finally, prereq #6 is that they must take advantage of the Liferay environment. I expect them to support portlet preferences via the Configuration panel. I expect them to respect the Liferay permissioning framework. I expect them to support localization through standard Liferay techniques. After all, I don't want to be doing things one way for standard Liferay stuff and some other way for JS portlets.

So let's get started...

Starting The Project

As per usual I'm going to be sticking with the Blade CLI for everything to highlight that you don't need an IDE to get these things started.

blade init liferay-vuejs

This will give me the new Liferay Workspace to build everything in. If you have an existing workspace, you're all good.

So this is really all you need to do from a workspace level.  Everything else goes into the individual modules.

I am planning on demonstrating remote services in the JS portlet, so eventually our modules folder will contain some Service Builder modules as well as a REST module, but we'll worry about creating those later.

In our modules folder we want to start the JS portlet itself.  Navigate to liferay-vuejs/modules to create the new module:

blade create -t mvc-portlet -p com.dnebinger.vue vue-portlet-1

So you might be wondering why we're using the Liferay MVC portlet template since we're building a JS portlet.

We use the Liferay MVC portlet as a template because we need to be able to kick off the JS inside of our portlet frame, we need to be able to declare and pull in resources, etc. The Liferay MVC portlet template will give that to us, plus a lot more.

Creating The Portlet Instance Preferences

Since we have a new Liferay MVC portlet, let's take a moment to create a configuration page.

What? We're not starting with the JS directly?

Well, no. Like I said in the prereqs, one of my goals is to include portlet prefs in order to be a proper Liferay portlet. To support that, we'll create a simple JSP configuration page for our portlet and worry about wiring it into JS later on...

Our configuration is going to be pretty simple. We're just going to have a couple of checkboxes to capture two flag values. Here's the full src/main/resources/META-INF/resources/configuration.jsp file:

<%@ include file="/init.jsp" %>

  portletInstanceConfig = ConfigurationProviderUtil.getConfiguration(
      new ParameterMapSettingsLocator(request.getParameterMap(),
          new PortletInstanceSettingsLocator(themeDisplay.getLayout(), 
<liferay-portlet:actionURL portletConfiguration="<%= true %>" var="configurationActionURL" />

<liferay-portlet:renderURL portletConfiguration="<%= true %>" var="configurationRenderURL" />

<aui:form action="<%= configurationActionURL %>" method="post" name="fm">
  <aui:input name="<%= Constants.CMD %>" type="hidden" value="<%= Constants.UPDATE %>" />
  <aui:input name="redirect" type="hidden" value="<%= configurationRenderURL %>" />

  <div class="portlet-configuration-body-content">
    <div class="container-fluid-1280">
      <aui:fieldset-group markupView="lexicon">
          <aui:input label="" name="preferences--flagOne--" 
              type="toggle-switch" value="<%= portletInstanceConfig.flagOne() %>" />
          <aui:input label="config.flag.two" name="preferences--flagTwo--" 
              type="toggle-switch" value="<%= portletInstanceConfig.flagTwo() %>" />

    <aui:button cssClass="btn-lg" type="submit" />

This is going to give us two boolean portlet preferences leveraging the new Liferay Config Admin services. They will be instance parameters so, if we choose to create an instanceable portlet, each one will have its own preferences.

We will use our view.jsp page to show the values:

<%@ include file="/init.jsp" %>

  <b><liferay-ui:message key="vue-portlet-1.caption"/></b>
<p><liferay-ui:message key=""/> <%= 
  String.valueOf(portletInstanceConfig.flagOne()) %></p>
<p><liferay-ui:message key="caption.flag.two"/> <%= 
  String.valueOf(portletInstanceConfig.flagTwo()) %></p>

Since we're showing the JSP, here's the init.jsp:

<%@ taglib uri="" prefix="c" %>
<%@ taglib uri="" prefix="portlet" %>
<%@ taglib uri="" prefix="aui" %>
<%@ taglib uri="" prefix="liferay-portlet" %>
<%@ taglib uri="" prefix="liferay-theme" %>
<%@ taglib uri="" prefix="liferay-ui" %>
<%@ taglib uri="" prefix="liferay-frontend" %>

<%@ page import="com.dnebinger.vue.portlet.configuration.VuePortlet1PortletInstanceConfiguration" %>
<%@ page import="com.liferay.portal.kernel.module.configuration.ConfigurationProviderUtil" %>
<%@ page import="com.liferay.portal.kernel.settings.PortletInstanceSettingsLocator" %>
<%@ page import="com.liferay.portal.kernel.util.Constants" %>
<%@ page import="com.liferay.portal.kernel.settings.ParameterMapSettingsLocator" %>

<liferay-frontend:defineObjects />

<liferay-theme:defineObjects />

<portlet:defineObjects />

  VuePortlet1PortletInstanceConfiguration portletInstanceConfig =
      new PortletInstanceSettingsLocator(themeDisplay.getLayout(), portletDisplay.getId()));

Okay, so we now have basically a simple Liferay MVC portlet project that has portlet preferences and initial support for the language bundle (as seen in the view.jsp file).

If we build and deploy the portlet, this is what we currently will see (after changing one of the toggles on the configuration panel):


Hey, wait a minute, there's no Javascript frameworks in here! I don't see any Vue.js stuff, no node, in fact this looks like a simple Liferay MVC portlet! What's going on here?

Well, I should have said that this is actually going to be a blog series. In this first post, we're basically going to stop here since our portlet is ready to start overlaying the key parts for building out our Javascript portlet.

You can find the sample project checked in here:

See you in Part 2!

Responsive Responsibility

General Blogs June 26, 2017 By David H Nebinger

According to Liferay:

Digital Experience Platform (DXP) is an emerging category of enterprise software seeking to meet the needs of companies undergoing digital transformation, with the ultimate goal of providing better customer experiences.

The focus here is the customer experience.  Better experiences, regardless of whether they come to you from a desktop computer or a mobile device, lead to better outcomes (happier customers, returning viewers, more sales, etc.). That is why the DXP is garnering more focus from the enterprise than ever before.

So part of the better customer experience is the recognition that your site, whether as an intranet, extranet, corporate internet site or even a B2B bridge, must acknowledge the strength and reach of mobile as a platform, and mobile support must be considered as an unwritten requirement for our projects.

For most developers, this often gets reduced down to needing to support responsive in the website.  If the website supports responsive design, as the screen size is reduced the view changes to better serve the device.

It is easy to assume that the theme and layout developer(s) are the only ones responsible for managing the responsive aspects of your website. After all, that is the primary place where your responsive design is implemented to manage how your navigation is presented, how the multi-column layout adjusts to the shrinking size, etc. That is handled by the theme and layout developers, so they are the only ones that have to worry about responsive design.

But that really isn't true. Responsive is a responsibility of content creators and portlet developers too.

As a content creator, you may have some fancy ADTs or web content templates that look great under the desktop view. You have your content, you have a side bar with some details, ... But here's a question - have you tried looking at your page on a mobile device? Does your side bar or localized grid look as good in the mobile view as it does on the desktop view?

As a content creator, it is your responsibility to incorporate responsive and mobile-first design rules into your ADTs and templates. After all, the theme/layout developer is only going to manage the outer column that your content is in, they will not have any responsibility for restructuring content within the column, that is your job.

And portlet authors are not off the hook here either. As a portlet developer it is easy to fall into a pattern of testing your portlet on the desktop and verifying it works there. Even the testing team, unless they have a mandate to test for mobile, can miss this kind of verification. But if you currently have mobile support requirements or you believe that will have mobile in your future, developing with responsive in mind and testing for responsive and a good mobile-friendly experience is important.

If you use the Liferay AUI tag framework appropriately, you're likely a good way towards being mobile friendly. If you're using another framework, well then responsive is totally up to you and your framework.

In either case, you should take some time to test your app, including your tables and forms, in a mobile view and verify that it is still usable. After all, a form that looks great and works great in a desktop orientation can easily become unusable in a mobile presentation. Take Liferay's OOTB login portlet - that portlet works whether shown in a full page view or if it is dropped in the small column of the 30/70 layout - it is fully responsive and adjusts to the space it has available. Are your portlets equally as responsive?

How do you know when responsive is your responsibility? There are some key indicators that you can look for. Are you using a one column layout? That is the clearest indication that you are taking over responsive since you are trying to take advantage of the full page width. Even if you are only targeting the large column (the 70 in the 70/30 or 30/70 layouts for example), you also have responsive aspects that you should consider.

So responsive is everyone's responsibility. It's also one that many of us forget to consider unless it is a requirement of the project that we're currently on.

Incorporating responsive tests and creating sites that are mobile-first/mobile-friendly in every phase of development or content creation is a key aspect of implementing your own digital experience platform.

Remember, this is all about the user's digital experience, not your development project convenience.

Disabling LPKG Index Validation

Technical Blogs June 21, 2017 By David H Nebinger

Just a quick blog today...

When you start up LR 7 CE/LR DXP, you'll often see it stop while trying to validate LPKGs. This is a security measure which is used to verify that the LPKG files have not been tampered with.

In development, though, this delay is just painful.

Fortunately it can be disabled. Add the following line to

That's all there is to it.

Note that I probably would not do this in my production environments. It is, after all, in there to protect your environment. Disabling it in production removes that small bit of protection and doesn't seem wise.

Fixing Module Package Access Modifiers

Technical Blogs June 16, 2017 By David H Nebinger

If you're a Java Architect or Senior Developer, you know just how important the Java access modifiers are.

Each choice about what to make public, protected, private or package protected is important from an architectural perspective. If you make the wrong choices you can expose too much of your implementation or not enough, you can give subclasses unlimited ability to change internal functionality or little access at all.

If you've ever worked on a library or framework project, either public or a company internal project, you know that these decisions are even more important. With these types of projects, if you make the wrong decision about access modifiers you can end up with irate users or an unused library.

So there exists two different sets of rules, one for app developers and one for lib developers.  App developers are going to use a lot of private to hide stuff and public to expose; they'll define pojos w/ getters but no setters and perhaps a package private constructor to initialize final fields. Methods are typically public or private and protected only comes into play if there are known plans to subclass.

Library developers swing the other way, allowing for every class to potentially be subclassed, extensive use of protected over private, no use of package protected, etc. Basically implementation details will be protected from those using the class yet exposed for subclasses to extend or override.

Rules for lib developers are not hard and fast, some libraries certainly do a better job than others for exposing necessary access points.

I'm sure most of us have been there... Using a class in someone's jar where they declare, for example, a private field with a public getter but no setter, resulting in a class that is difficult to extend and customize. Then we have to break out our Reflection skills to access the field, change the access and update the value. Obviously we don't want to do these things, but we get forced into it because the library developer used application developer rules when defining the access modifiers.

OSGi Access Modifiers

OSGi bundles has its own set of "access modifiers".  We've seen those in the bnd.bnd files, at a package level you can choose to export packages or mark them as private.

Choices you make along these lines affect what you can extend/override in other bundles. If you mark a package as private, the classes are not available to another bundle to leverage and use.

Just like app vs lib developer access modifier rules, there is a similar distinction for OSGi application bundle developer rules and OSGi library bundle developer rules.  For the app bundle developer, packages are exported if they can be used by other modules, otherwise they are private to protect them. For lib bundle developers, you're going to export pretty much every package because you can never know how your library module will be used.

What I Think is Wrong

Probably my biggest complaint with the Liferay 7 CE / Liferay DXP modules is that I believe the developers were creating modules as though they are app bundle developers when, in fact, they should have been library bundle developers.

For example, the Liferay chat portlet... The Liferay chat portlet does not export a single package; every package in the module is private. As an application portlet bundle developer, this is probably exactly the decision I would make to protect my code, it won't need to be extended or overridden, as the developer if that comes up in the future I can just do it.

But the Liferay developers, they should not have built it this way in my opinion. Me, I may have a need to make some significant changes to the chat portlet, not just for JSP changes but perhaps also some logic. From that point of view, the Liferay chat portlet is a library bundle, a "base" bundle that I want to be able to extend or override. The is not full Liferay MVC, so all business logic is tied up in that class. If I want to customize the chat portlet, I need to copy the class and make my change and hope that Liferay doesn't update the portlet.

In order to complete my customization, I might need to change a method in the ChatPortlet itself. Sure, with OSGi I can replace the OOTB portlet class with my own, but I really want to be able to do something like:

public class MyChatPortlet extends ChatPortlet {...}

This would allow me to replace the OOTB portlet using a higher service ranking for mine, yet I can keep as much of the original logic as-is without taking over responsibility for maintaining the full class myself.

For another concrete example, take the Liferay Login portlet.  This portlet is full-on Liferay MVC so, if I want to override the create account action, I just need to register an instance of MVCActionCommand with the right and a higher service ranking. But again, since most of the packages in the Liferay Login portlet are private, I cannot do something like:

public class CustomCreateAcountMVCActionCommand extends CreateAccountMVCActionCommand {...}

If my requirement is just to do some additional work in the addUser() method, I don't want to copy the whole Liferay class just to be able to tweak one method.  What happens when the next release comes out? I'd have to copy the whole class in and release again. At least by extending I only have to worry about keeping in sync the stuff I change, everything else is extended.

Can We Fix It?

As Bob the Builder says, "Yes We Can!", and it turns out it is really, really easy!

Let's say we want to tackle being able to extend Liferay's CreateAccountMVCActionCommand class. Our requirement is that we need to log whenever an account is being created. I know, pretty lame, but the point here is to extend a class which Liferay didn't plan on our extending - once we're over that hump, any additional requirements will be easy to tackle.

So let's get started. The first thing we need is a Fragment bundle. That's right, you read correctly, a Fragment bundle.

blade create -t fragment -h com.liferay.login.web -H 1.0.0 open-liferay-web

That gets us started. We need to open the bnd.bnd file and we're going to be doing two basic things:

  1. Copy in most of the stuff from the original bnd.bnd file. The only change we want to make is with the exported packages, so we want to keep everything else.
  2. Change the exported package line (or add one) to include the packages we want to export, and we'll also change to a version range.

I've gone ahead and done this, and here's what I ended up with:

Bundle-Name: Open Liferay Login Web
Bundle-SymbolicName: open.login.web
Bundle-Version: 1.1.19
Fragment-Host: com.liferay.login.web;bundle-version="[1.0.0,2.0.0)"

Export-Package: com.liferay.login.web.constants,\

So you can see that I satisfied #1 above, I've kept the import packages and the Liferay-Releng guys.

For #2, my export package statement was updated so now we're going to be exporting the com.liferay.login.web.internal.portlet.action package. This will allow us to subclass Liferay's action command by making it visible.

I also tweaked the Fragment-Host version. Instead of using a single version, I've changed it to a version range. Why? Because this fragment bundle doesn't care what version is actually deployed, we're just planning on exporting the package regardless of version.

And that's it! See, I said it was easy. You don't really need any other files, you're basically just going to be building and deploying a jar w/ the overriding OSGi manifest information.


Testing is also kind of easy. We know we want to extend the CreateAccountMVCActionCommand, so we just create a bundle and specify the contents. I did that already, too, and here's what I got:

	property = {
		"" + LoginPortletKeys.FAST_LOGIN,
		"" + LoginPortletKeys.LOGIN,
	service = MVCActionCommand.class
public class CustomCreateAccountMVCActionCommand extends CreateAccountMVCActionCommand {

	protected void addUser(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {"About to create a new account.");

		super.addUser(actionRequest, actionResponse);

	@Reference(unbind = "-")
	protected void setLayoutLocalService(
		LayoutLocalService layoutLocalService) {

	@Reference(unbind = "-")
	protected void setUserLocalService(UserLocalService userLocalService) {

	@Reference(unbind = "-")
	protected void setUserService(UserService userService) {

	@Reference(unbind = "-")
	protected void setAuthenticatedSessionManager(AuthenticatedSessionManager sessionMgr) {
		update("_authenticatedSessionManager", sessionMgr);
	@Reference(unbind = "-")
	protected void setListTypeLocalService(ListTypeLocalService listTypeLocalService) {
		update("_listTypeLocalService", listTypeLocalService);
	@Reference(unbind = "-")
	protected void setPortal(Portal portal) {
		update("_portal", portal);

	protected void update(final String fieldName, final Object value) {
		try {
			Field f = getClass().getSuperclass().getDeclaredField(fieldName);


			f.set(this, value);
		} catch (IllegalAccessException e) {
			_log.error("Error updating " + fieldName, e);
		} catch (NoSuchFieldException e) {
			_log.error("Error updating " + fieldName, e);

	private static final Log _log = LogFactoryUtil.getLog(CustomCreateAccountMVCActionCommand.class);

Oh, crap. What is all of this junk?

Well, first let's get the necessary stuff out of the way. Our @Component reference has the necessary properties and service ranking so OSGi will use our action command class, which we are now extending Liferay's CreateAccountMVCActionCommand. We also have the overriding addUser() method to log when we are about to create an account, so we have satisfied our requirement.

The rest of the class, well that is necessary to inject the right OSGi references into the super class that it expects. Some of these are easy, such as the layout service and the two user services. The others are hard, the authenticated session manager, list type service and the portal instance.

Remember I started this blog saying that the rules for a library developer are different than an app developer, and when you have a bad library class you're left to using Reflection to update a super class? Yep, here's an example. Now, I can't really fault Liferay here for this because they created the module as though they were an app module developer, so the fact that they used app developer rules here is no surprise. Fortunately though I could use Reflection to get to the super field and update it appropriately.


So, when we build and deploy these two modules and create a new account, we find we have been successful:

13:30:31,360 INFO  [http-nio-8080-exec-6][CustomCreateAccountMVCActionCommand:39] About to create a new account.

Through a simple (really simple) fragment bundle we were able to export a package that Liferay did not export. From there, we can extend classes from that package to introduce our own modifications without having to copy everything from the original.

It's important to note the hurdles we had to bypass for the OSGi stuff, especially the Reflection usage to update the super class.

If you're going to go down this path, you will be doing things like this. There's no way around it, not all @Reference usage in Liferay classes are tied to methods; when they are, great, but when they're not you'll have to peel them open yourself.

Hope this helps you on your Liferay 7 CE / Liferay DXP developer journey!


REST Custom Context Providers

Technical Blogs June 16, 2017 By David H Nebinger

So a question came up today how to access the current user as part of a REST method body.

My friend, Andre Fabbro, was trying to build out the following application:

@Component(immediate = true, service = Application.class)
public class MyApplication extends Application {

    public String getUserFullName() {

        User user = ????;

        return user.getFullName();

He was stuck trying to get the current user in order to finish the whoami handler.

So, being a long-time Liferay guy, I fell back on what I knew, and I pointed him towards the PrincipalThreadLocal and the getName() method to get the current user id.  Of course ThreadLocals kind of smell, they're almost like global variables, but I knew it would work.

My other friend, Rafael Oliveira, showed us both up and introduced me to the new concept of a custom context provider. You see, he knew that sometime soon a new module, was coming and it was going to bring with it a new class, He did us one better by providing an implementation of Andre's app using @Context and the new UserContextProvider:


@Component(immediate = true, service = Application.class)
public class MyApplication extends Application {

    public String getUserFullName(@Context User user) {
        return user.getFullName();

I was kind of blown away having learned something completely new with DXP and I needed to know more.

Before going on, though, all credit for this blog post goes to Rafael, all I'm doing here is putting it to electronic paper for us all to use for Liferay REST application implementations.

Basic @Context Usage

So when you create a new module using "blade create -t rest myapp", BLADE is starting a new JAX-RS-based RESTful application that you can build and deploy as an OSGi module. Using JAX-RS standard conventions, you can build out your RESTful methods using common annotations and (hopefully) best practices.

JAX-RS actually provides the annotation and is used to inject common servlet-based values. Using @Context, you can define a method parameter that is not part of the RESTful call but are injected by the JAX-RS framework, kind of like the automagic ServiceContext injection in ServiceBuilder remote services.

Out of the box, JAX-RS Context annotation supports injecting the following parameters in methods:

Type Description Provides access to metadata information on the JAX-RS application. Provides access to application and request URI information. Provides access to the request used for the method. Provides access to the HTTP header information for the request. Provides access to the security-related information for the request. Provides runtime lookup of provider instances.

To use these, you just add appropriately decorated parameters to the REST method. If necessary, we could easily add a method to the application above such as:

public String getStuff(@Context Application app, @Context UriInfo uriInfo, @Context Request request,
        @Context HttpHeaders httpHeaders, @Context SecurityContext securityContext, @Context Providers providers) {

The above getStuff() method will be handling all requests to the /neato path, but all of the parameters are injected, none are provided in the URL or as parameters; they are injected automagically by JAX-RS.

Custom @Context Usage

So these types are really nice, but they really don't do anything for our Liferay integration. What would be really cool is if we could use @Context to inject some Liferay parameters.

And we can! As Rafael pointed out, there is a new module in the pipeline for workflow to invoke RESTful methods on the backend. The new module is the portal-workflow-rest project. I'm not sure, but I believe this is going to be part of the upcoming GA4 release, but don't hold me to that.

Once available, this project will provide three new types that can be injected into RESTful method parameters:

Type Description
com.liferay.portal.kernel.model.Company The Liferay Company associated with the request.
java.util.Locale The locale associated with the request.
com.liferay.portal.kernel.model.User The Liferay User associated with the request.

So, like the out of the box parameters, we could extend our getStuff() method with these parameters too:

public String getStuff(@Context Application app, @Context UriInfo uriInfo, @Context Request request,
        @Context HttpHeaders httpHeaders, @Context SecurityContext securityContext, @Context Providers providers,
        @Context Company company, @Context Locale locale, @Context User user) {

Just pick from all of these different available types to get the data you need and run with it.

Remember these will not be available in GA3 nor in DXP just yet - I'm sure they'll make it in soon, but I'm not aware of the schedule for either product lines.

Writing Custom Context Providers

So to me, the biggest value of this new module is this package:

Why? Because they expose how we can write our own custom context provider implementations so we can inject custom parameters into REST methods.

Say, for example, that we want to inject a ServiceContext instance. I'm not sure if the portal source already has one of these fellas, but if so let's pretend it doesn't exist and we want to write our own. Where are we going to start?

So first you need a project, we'll create a blade workspace:

blade init custom-context-provider

We also need a new module to develop, so we'll change to the custom-context-provider/modules directory to create an initial module:

blade create -t api -p service-context-context-provider

This will give us a nearly empty API module. We'll end up cleaning out most of the generated files, but we will end up with the class:


import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.ServiceContextFactory;
import org.apache.cxf.jaxrs.ext.ContextProvider;
import org.apache.cxf.message.Message;
import org.osgi.service.component.annotations.Component;

import javax.servlet.http.HttpServletRequest;

 * class ServiceContextContentProvider: A custom context provider for ServiceContext instantiation.
 * @author dnebinger
@Component(immediate = true, service = ServiceContextContentProvider.class)
public class ServiceContextContentProvider implements ContextProvider {
	 * Creates the context instance
	 * @param message the current message
	 * @return the context
	public ServiceContext createContext(Message message) {
		ServiceContext serviceContext = null;

		// get the current HttpServletRequest for building the service context instance.
		HttpServletRequest request = (HttpServletRequest) message.getContextualProperty(PROPKEY_HTTP_REQUEST);

		try {
			// now we can create a service context
			serviceContext = ServiceContextFactory.getInstance(request);

			// done!
		} catch (PortalException e) {
			_log.warn("Failed creating service context: " + e.getMessage(), e);

		// return the new instance.
		return serviceContext;

	private static final String PROPKEY_HTTP_REQUEST = "HTTP.REQUEST";

	private static final Log _log = LogFactoryUtil.getLog(ServiceContextContentProvider.class);

So this is pretty much the whole module. Easy, huh?


Now that we can create custom context providers, we can use this one for example in the original code:

@Component(immediate = true, service = Application.class)
public class MyApplication extends Application {

    public String getUserFullName(@Context ServiceContext serviceContext) {

        User user = _userLocalService.fetchUser(serviceContext.getUserId());

        return user.getFullName();

    private UserLocalService _userLocalService;

These custom context providers become the key for being able to create and inject non-REST parameters into your REST methods.

Check out the code from GitHub:


Resolving Missing Components

Technical Blogs June 15, 2017 By David H Nebinger

So if you've started developing for Liferay 7 CE / Liferay DXP, I'm sure you've been hit at one point or another with the old "unresolved reference" issue that prevents your bundle from starting.

You would have seen it by now, the Gogo shell where you list the beans and find your bean there stuck in the Installed state. You try starting it and Gogo tells you about the unresolved reference you have and you're stuck going back to your bnd.bnd file to resolve the dependency issue.

This is so common, in fact, that I wrote a blog post to help resolve them:

While this will be your issue more often than not, there's another form of "unsatisfied reference" problem that leads to missing components rather than non-started bundles.

The Case of the Missing Component

You can have a case where your module starts but your component is not available. This sounds kind of strange, right? You've taken the time to resolve all of those 3rd party dependency jars, the direct and transitive ones, and your bean starts cleanly and there are no errors.

But your component is just not available. It seems to defy logic.

So, here's the skinny... Any time your component has an @Reference with default binding, you are basically telling OSGi that your component just has to have the reference injected or else it cannot be used.

That's where this comes from - you basically have an unsatisfied reference to some object that was supposed to be @Reference injected but could not be found; since the reference is missing, your component cannot start and it is therefore not available.

There's actually a bunch of different ways that this scenario can happen:

  • The @Reference refers to an object from another module that was not deployed or has not started (perhaps because of normal unresolved references). This is quite common if you deploy your Service Builder API module but forget to deploy the service module.
  • You have built in circular references (more below).
  • You use a target filter for the @Reference that is too narrow or incorrect, such that suitable candidates cannot be used.

In all of these cases you'll be stuck with a clean component, just one that cannot activate because of unsatisfied references.

Sewing (@Reference) Circles

Reference circles are real pains to resolve but they rise out of your own code. Understanding reference circles is probably best started through an example.

Let's say we are building a school planning system. We focus on two major classes, a ClassroomManager and an InstructorManager. The ClassroomManager has visibility on all classrooms and is aware of the schedule and availability. The InstructorManager has the instructor roll and is aware of their schedule and availability.

It would be quite natural for a ClassroomManager to use an InstructorManager to perhaps find an available instructor to substitute in a class. Likewise it would be natural for an InstructorManager to need a ClassroomManager to try to reschedule a class to another time in an available room.

So you might find yourself creating the following classes:

public class ClassroomManager {

  private InstructorManager instructorManager;

public class InstructorManager {

  private ClassroomManager classroomManager;

If you look at this code, it seems quite logical.  Each class has a need for another component, so it has been @Reference injected. Should be fine, right?

Well actually this code has a problem - there's a circular reference.

When OSGi is processing the ClassroomManager class, it knows that the class cannot activate unless there's an available, activated InstructorManager instance to inject. Which there isn't yet, so this class cannot activate.

When OSGi is processing the InstructorManager class, it knows that the class cannot activate unless there's an available, activated ClassroomManager instance to inject. Which there isn't yet, so this class cannot activate.

But wait, you say, we just did the ClassroomManager, we should be fine! We're stuck, though, because the ClassroomManager could not activate because of the unsatisfied reference.

This is your reference circle - neither component can start because they are circularly dependent upon each other.

Resolving Component Unsatisfied References

Resolution is not going to be the same for every unsatisfied component reference.

If the problem is an undeployed module, resolving is as simple as deploying the missing module.

If the problem is an unstarted module, resolving is a matter of starting the module (perhaps fixing whatever problem that might be preventing it from starting in the first place).

For a reference target filter issue, well those are going to be challenging. You'll have to figure out if the target is not right or too narrow and make appropriate adjustments.

The circular reference resolutions can be resolved by refactoring code - instead of big ClassroomManager and InstructorManager classes, perhaps use a bunch of smaller classes that don't result in similar reference circles.

Another option is to use different ReferenceCardinality, ReferencePolicy and ReferencePolicyOption values (see my blog post on annotations, specifically the section on the @Reference annotation). You could switch both from MANDITORY to OPTIONAL ReferenceCardinalities, DYNAMIC for the ReferencePolicy, ...  The right set is usually mandated by what the code can handle and requires, but the outcome would allow the components to activate without the initial references being satisfied, but once activated the references will be post-injected.

How Do You Fix What You Can't Find?

This, for me, has been kind of a challenge. Of course the answer lies within one of the Gogo shell commands, but I've always found it hard to separate the wheat (the components with unsatisfied references) from the chaff (the full output with all component status details from the bundle).

For me, I've found it easiest to use TripWire CE or TripWire DXP. After going to the TripWire panel in the control panel, click on the Take Snapshot card and you can actually drill into and view all unsatisfied references.  The following screen capture is an actual view I used to resolve an unsatisfied reference issue:

The issue I was looking at was the first unsatisfied reference line for my component. It just wouldn't activate and I didn't know why; I knew it wasn't available, it wasn't doing its thing, but the module was successfully started so what could the problem be?

Well the value for the key spells it out - I have two unsatisfied references for two different gauge instances. And you know what? it is totally true. Those two missing references happen to be the 2nd and 3rd lines in the list above, and they in turn had unsatisfied references that needed to be resolved, ...


The point here is that in order to resolve unsatisfied references, you need to be able to identify them. Once you can identify the problem, you can resolve them and move on.

For me, I've found it easiest to use TripWire CE or TripWire DXP to identify the unsatisfied references, it does so quickly, easily, and doesn't require memorizing Gogo shell commands to get it done.


Securing The /api/jsonws UI

Technical Blogs June 12, 2017 By David H Nebinger

The one thing I never understood was why the UI behind the /api/jsonws is publicly viewable.

I mean, there's lots of arguments for it to be secured:

  • Exposing all of your web service APIs exposes attack vectors to hackers. Security by obscurity is often one of the best and easiest form of security that you can have1.
  • Just because users may have permission to do something, that doesn't mean you want them to. They might not be able to get to a portlet to delete some web content or document, but if they can get to /api/jsonws and know anything about Liferay web services and parameters, they might have fun trying to do it.
  • It really isn't something that non-developers should ever be looking at.

I'm sorry, but I've tried really hard and I can't think of a single use case where making the UI publicly available is a good thing. I guess there might be one, but at this point it seems like it should just be an edge case and not a primary design requirement.

A client recently asked about how to secure the UI, and although I had wondered why it wasn't secured, I decided it was time for me to figure out how to do it.

The UI Implementation

It was actually a heck of a lot easier than what I thought it was going to be.

I had in my head some sort of complicated machinery that was aware of all locally deployed remote services and perhaps was leveraging reflection and stuff to expose methods and parameters and ...

But it wasn't that complicated at all.

The UI is implemented as a basic JSP-based servlet. Whether in Liferay 6.2 or Liferay 7 CE or Liferay DXP, there are core JSPs in /html/portal/api/jsonws that implement the complete UI servlet code.

For incoming remote web service calls, the portal will look at the request URI - if it is targeting a specific remote service, the request is handed off to the service for handling. However, if it is just /api/jsonws, the portal passes the request to the /html/portal/api/jsonws/index.jsp page for presentation.

Securing the UI

All I'm going to do is tweak the JSP to make sure the current user is an OmniAdmin if they get to see the UI. Nothing fancy, I admit, but it gets the job done. If you have more complicated requirements, you're free to use this blog as a guide but you're on your own for implementing them.

My JSP change is basically going to be wrapping the content area to require OmniAdmin to view the content, otherwise you will see a permission failure. Here's what I came up with:

<div id="content">
	<%-- Wrap content in a permission check --%>
	<c:if test="<%= permissionChecker.isOmniadmin() %>">
		<div id="main-content">
				<aui:col cssClass="lfr-api-navigation" width="<%= 30 %>">
					<liferay-util:include page="/html/portal/api/jsonws/actions.jsp" />

				<aui:col cssClass="lfr-api-details" width="<%= 70 %>">
					<liferay-util:include page="/html/portal/api/jsonws/action.jsp" />
	<c:if test="<%= !permissionChecker.isOmniadmin() %>">
		<liferay-ui:message key="you-do-not-have-permission-to-view-this-page" />

This code I took mostly from the DXP version of the file, so use the file from the version of Liferay you have so you don't introduce some sort of source issue. I've highlighted the real code that I added so you can work it into your override.

Creating the Project

So regardless of version, we're going to be doing a JSP hook, they just get implemented a little differently.

For Liferay 6.2, it is just a JSP hook. Build a JSP hook and pull in the original /html/portal/api/jsonws/index.jsp file and edit in the change outlined above. I'm not going to get into details for building a 6.2 JSP hook, those have been rehashed a number of times now, so there's no reason for me to rehash it again. Just build your JSP hook and deploy it and you should be fine.

For Liferay 7 CE, well let me just say that what I'm about to cover for DXP is how you will be doing it once GA4 is released.  Until then, the path I'm using below won't be available to you.

For Liferay DXP (and CE GA4+), we'll follow the instructions from to override the core JSPs using an OSGi module.

So first I created a new workspace using the command "blade init api-jsonws-override".

Then I entered the api-jsonws-override/modules directory and created my new module using the command "blade create -t service -p com.liferay.portal.jsonwebservice.override api-jsonws-override".

I don't like building code myself, so the first thing I did was add a dependency to a module which has a base implementation of the CustomJspBag in my build.gradle file:

dependencies {
    compileOnly group: "com.liferay.portal", name: "com.liferay.portal.impl", version: "2.0.0"
    compileOnly group: "com.liferay.portal", name: "com.liferay.portal.kernel", version: "2.6.0"
    compileOnly group: "com.liferay", name: "com.liferay.portal.custom.jsp.bag", version: "1.0.0"
    compileOnly group: "org.osgi", name: "org.osgi.core", version: "5.0.0"
    compileOnly group: "org.osgi", name: "org.osgi.service.component.annotations", version: "1.3.0"

It's actually that com.liferay.portal.custom.jsp.bag guy which makes my project not work for Liferay 7 CE, it's not available in GA3 but I expect it to be released with GA4. If you don't want to wait for GA4, you can of course not extend the BaseCustomJspBag class like I'm about to and can build out the complete CustomJspBag interface in your class.

NOTE: I really, really dislike the fact that I have to pull in the com.liferay.portal.impl dependency above. I have to do that because for some reason the CustomJspBag interface is only in the portal-impl project and not portal-kernel as we would normally expect.
Do not import this dependency yourself unless you are really, really, really sure that you gotta have it. 95% of the time you're actually going to be wrong, so if you think you need it you really have to question whether that is true or whether you're perhaps missing something.

Since I have the module with the base class, I can now write my JsonWsCustomJspBag class:

package com.liferay.portal.jsonwebservice.override;

import com.liferay.portal.custom.jsp.bag.BaseCustomJspBag;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;

 * class JsonWsCustomJspBag: This is the custom jsp bag used to replace the core JSP files for the jsonws UI.
 * @author dnebinger
	immediate = true,
	property = {
		" Permissioning Custom JSP Bag",
public class JsonWsCustomJspBag extends BaseCustomJspBag implements CustomJspBag {

	protected void activate(BundleContext bundleContext) {
		// we also want to include the jspf files in the list
		Enumeration enumeration = bundleContext.getBundle().findEntries(
			getCustomJspDir(), "*.jspf", true);
		while (enumeration.hasMoreElements()) {
			URL url = enumeration.nextElement();

Pretty darn simple, huh? That's because I could leverage the BaseCustomJspBag class. Without that, you need to implement the CustomJspBag interface and that makes this code a lot bigger. You'll find help for implementing the complete interface from

Don't forget your override file in src/main/resources/META-INF/resources/custom_jsps/html/portal/api/jsonws/index.jsp file with the override code as discussed previously.


That's it. Build and deploy your new module and you can hit the page as a guest and you'll get the permission message. Hit the page as a non-OmniAdmin user and you get the same. Navigate there as the OmniAdmin and you see the UI so you can browse the services, try them out, etc. as though nothing changed.

I'm making the project available in GitHub:



1 A friend of mine called me out on the "security by obscurity" statement and thought that I was advocating for only this type of security.  Security by obscurity should never, ever be your only barrier to prevent folks with malicious intent from hacking your site. I do see it as a first line of defense, one that can keep script kiddies or inexperienced hackers from discovering your remote APIs. But you should always be checking permissions, securing access, monitoring for intrusions, etc.

ServiceBuilder and Upgrade Processes

Technical Blogs May 17, 2017 By David H Nebinger


Today I ran into someone having issues with ServiceBuilder and the creation of UpgradeProcess implementations. The doco is a little bit confusing, so I thought I'd do a quick blog post sharing how the pieces fit...

Normal UpgradeProcess Implementations

As a reminder, you register UpgradeProcess implementations to support upgrading from, say, 1.0.0 to 2.0.0, when there are things that you need to code to ensure when the upgrade is complete that the system is ready to use your module. Say, for example, that you're storing XML in a column in the DB and in 2.0.0 you've changed the DTD; for those folks that already have 1.0.0 deployed, your UpgradeProcess implementation would be responsible for processing each existing record in the database to change the contents over to the 2.0.0 version of the DTD. For non-ServiceBuilder modules, it is up to you to write the initial UpgradeProcess code for the 0.0.0 -> 1.0.0 version.

Through the lifespan of your plugin, you continue to add in UpgradeProcess implementations to handle the automatic update for dot releases and major releases. The best part is that you don't have to care what version everyone is using, Liferay will apply the right upgrade processes to take the users from what version they're currently at all the way through to the latest version.

This is all good, of course, but ServiceBuilder, well it behaves a little differently.

ServiceBuilder service.xml Development

As you go through development and you change the entities in service.xml and rebuild services, ServiceBuilder will update the SQL files used to create the tables, indices, etc. When you deploy the service the first time, ServiceBuilder will happily identify the initial deployment and will use the SQL files to create the entities.

This is where things can go sideways... If I deploy version 1.0.0 of the service and version 2.0.0 comes out, the service developer needs to implement an UpgradeProcess that makes the necessary changes to the tables to get things ready for the current version of the service. If you did not deploy version 1.0.0 but are starting out on 2.0.0, you don't want to have to execute all of the upgrade processes individually, you want ServiceBuilder to do what it has always done and just use the SQL files to create the version 2.0.0 of the entities.

So how do you support both of these scenarios correctly?

By using the Liferay-Require-SchemaVersion header¹ in your bnd.bnd file, that's how.

Supporting Both ServiceBuilder Upgrade Scenarios

The Liferay-Require-SchemaVersion header defines the current DB schema version number for your service modules. This version number should be incremented as you change your service.xml in preparation for a release.

There's code in the ServiceBuilder deployment which injects a hidden UpgradeProcess implementation that is defined to cover the "0.0.0" version (the version which represents the "new deployment") to the Liferay-Require-SchemaVersion version number.  So your first release will have the header set to 1.0.0, next release might be 2.0.0, etc.

So in our previous example with the 2.0.0 service release, when you deploy the service Liferay will match the "0.0.0" to "2.0.0" hidden upgrade process implementation provided by ServiceBuilder and will invoke it to get the 2.0.0 version of the tables, indices, etc. created for you using the SQL files.

The service developer must also code and register the manual UpgradeProcess instances that support the incremental upgrade. So for the example, there would need to be a 1.0.0 -> 2.0.0 UpgradeProcess implementation so when I deploy 2.0.0 to replace my 1.0.0 deployment, the UpgradeProcess will be used to modify my DB schema to get it up to version 2.0.0.


As long as you properly manage both the Liferay-Require-SchemaVersion header in the bnd.bnd file and provide your corresponding UpgradeProcess implementations, you will be able to easily handle the first time deployment as well as the upgrade deployments.

An important side effect to note here - you must manage your Liferay-Require-SchemaVersion correctly.  If you set it initially to 1.0.0 and forget to update it on future releases, your users will have all kinds of issues.  For initial deployments, the SQL scripts would create the entities using the latest SQL files and then try to apply UpgradeProcess implementations to get to new versions trying to make modifications they really don't have to worry about. For upgrade deployments, Liferay may not process upgrades because it believes the schema is already at the appropriate version.

¹ If the Liferay-Require-SchemaVersion header is missing, the value for the Bundle-Version will be used instead.

Showing 1 - 20 of 70 results.
Items 20
of 4