199 Lotus blogs updated hourly. Who will post next? Home | Blogs | Search | About 
 
Latest 7 Posts
Quick-n-Dirty: Hotfix for DateTimeHelper
Mon, Jun 12th 2017 4
High Performance REST Applications (4) – Looking into OSGi
Thu, May 4th 2017 5
High Performance REST Applications (3) – Importing the Starter Project
Mon, Apr 24th 2017 6
High Performance REST Applications (2) – Dev Environment
Sun, Apr 23rd 2017 5
High Performance REST Applications (1) – Intro
Fri, Apr 21st 2017 7
Re: Domino REST performance analysis
Thu, Mar 16th 2017 4
Domino & Java 1.8: Thank you, IBM!
Tue, Mar 14th 2017 8
Top 10
Hardening SSH vs. Eclipse RSE
Tue, Jan 13th 2015 12
XPages: WebContent Files (3) – Create a Minimizer Servlet
Thu, Nov 27th 2014 10
Security: Usefull HTTP Response Headers
Wed, Jan 14th 2015 10
Domino & Java 1.8: Thank you, IBM!
Tue, Mar 14th 2017 8
Rest & Security: A Stateless Token Servlet
Tue, Feb 10th 2015 7
High Performance REST Applications (1) – Intro
Fri, Apr 21st 2017 7
XPages: WebContent Files (1) – Create a file using the Java NAPI
Tue, Nov 18th 2014 6
HowTo: Vaadin on Domino (2)
Sat, Jan 24th 2015 6
Things I never blogged about: XPages & Google’s EventBus
Tue, Dec 1st 2015 6
Jackson: Skip Objects conditionally
Wed, Feb 8th 2017 6


XPages: WebContent Files (3) – Create a Minimizer Servlet
Twitter Google+ Facebook LinkedIn Addthis Email Gmail Flipboard Reddit Tumblr WhatsApp StumbleUpon Yammer Evernote Delicious
Sven Hasselbach    

Because of Stefano Fois comment I decided to write an example about how to create a minimizer servlet for Domino which cmpresses JavaScript resources on the fly. This is, again, a simple Proof-Of-Concept, nothing more and nothing less.

First, I downloaded the YUICompressor, a Java based minimizer for JavaScript code from the project page. There are other compressors outside, I decided to use this one because it was the first result in my StartPage.com search.

The project is a single jar file and can be easily imported into an existing Domino database, in my case to my demonstration NAPI.nsf.

The next step is to create a servlet and a servlet factory, the basics are described here. To enable the servlet, an additional service file is required.

The file com.ibm.xsp-adapter.servletFactory contains the name of the factory class:

ch.hasselba.jsf.servlet.MinimizerServletFactory

The servlet factory is simple, it just defines the servlet class to use and the path which the servlet listens to requests:

package ch.hasselba.jsf.servlet;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import com.ibm.designer.runtime.domino.adapter.ComponentModule;
import com.ibm.designer.runtime.domino.adapter.IServletFactory;
import com.ibm.designer.runtime.domino.adapter.ServletMatch;

public class MinimizerServletFactory implements IServletFactory {

    private static final String SERVLET_WIDGET_CLASS = "ch.hasselba.jsf.servlet.MinimizerServlet";
    private static final String SERVLET_WIDGET_NAME = "JS Minimizer";

    private ComponentModule module;

    public void init(ComponentModule module) {
        this.module = module;
    }

    public ServletMatch getServletMatch(String contextPath, String path)
            throws ServletException {

        String servletPath = "";

        if (path.contains("/minimizer")) {
            String pathInfo = path;
            return new ServletMatch(getWidgetServlet(), servletPath, pathInfo);
        }

        return null;
    }

    public Servlet getWidgetServlet() throws ServletException {
        return module.createServlet(SERVLET_WIDGET_CLASS, SERVLET_WIDGET_NAME, null);
    }

}

The servlet is now reachable by the following URL

http://example.com/path/to/db.nsf/xsp/minimizer/

How does the minimizer servlet work? It appends all required files into a single string and compresses the string before sending the result to the browser. So the first information needed is which files should be used. This can be done with the parameter “files“, the list of files is concatenated with “+“:

http://example.com/path/to/db.nsf/xsp/minimizer/?files=file1.js+file2.js+ ...

The given files are then loaded via NAPI into a large StringBuffer and then compressed and mimimized by YUI and GZIP.

package ch.hasselba.jsf.servlet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;

import ch.hasselba.napi.NAPIUtils;

import com.ibm.xsp.webapp.DesignerFacesServlet;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

public class MinimizerServlet extends DesignerFacesServlet implements
        Serializable {

    private static final long serialVersionUID = -1L;

    @Override
    public void service(ServletRequest servletRequest,
            ServletResponse servletResponse) throws ServletException,
            IOException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        ServletOutputStream out = servletResponse.getOutputStream();

        try {
            res.setContentType("application/x-javascript");
            res.setCharacterEncoding("utf-8");
            res.addHeader("Content-Encoding", "gzip");

            // load the js requested files
            StringBuffer fileData = new StringBuffer();
            String tmpFile = "";
            String paramFiles = req.getParameter("files");
            String[] files = paramFiles.split(" ");

            // and add them to a buffer
            for (String file : files) {

                try {
                    tmpFile = NAPIUtils.loadFile("DEV01", "NAPI.nsf", file);
                    fileData.append(tmpFile);
                } catch (Exception e) {
                    // ignore errors
                    e.printStackTrace();
                }

            }

            // Compress the JS Code with compressor
            StringWriter sWriter = new StringWriter();
            compress(stringBufferToInputStreamReader(fileData), sWriter);

            // and GZIP it
            ByteArrayOutputStream obj = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(obj);
            gzip.write(sWriter.toString().getBytes("UTF-8"));
            gzip.close();

            // send it to the client
            out.write(obj.toByteArray());

        } catch (Exception e) {
            e.printStackTrace(new PrintStream(out));
        } finally {
            out.close();
        }
    }

    /**
     * Helper to convert a StringBuffer to an InputStreamReader
     * 
     * @param strBuffer
     *            the StringBuffer to convert
     * @return the converted InputStreamReader
     */
    public static InputStreamReader stringBufferToInputStreamReader(
            final StringBuffer strBuffer) {
        return new InputStreamReader(new ByteArrayInputStream(strBuffer
                .toString().getBytes()));
    }

    /**
     * compresses the JS code using YUI
     * 
     * @param in
     *            the InputStreamReader containing the JS
     * @param out
     *            the Writer Object
     * @throws EvaluatorException
     * @throws IOException
     */
    public static void compress(final InputStreamReader in, Writer out)
            throws EvaluatorException, IOException {
        JavaScriptCompressor compressor = new JavaScriptCompressor(in,
                new ErrorReporter() {
                    public void warning(String message, String sourceName,
                            int line, String lineSource, int lineOffset) {

                        System.out.println("n[WARNING]");
                        if (line < 0) {
                            System.out.println(" " + message);
                        } else {
                            System.out.println(" " + line + ':' + lineOffset
                                    + ':' + message);
                        }
                    }

                    public void error(String message, String sourceName,
                            int line, String lineSource, int lineOffset) {
                        System.out.println("[ERROR] ");
                        if (line < 0) {
                            System.out.println(" " + message);
                        } else {
                            System.out.println(" " + line + ':' + lineOffset
                                    + ':' + message);
                        }
                    }

                    public EvaluatorException runtimeError(String message,
                            String sourceName, int line, String lineSource,
                            int lineOffset) {
                        error(message, sourceName, line, lineSource, lineOffset);
                        return new EvaluatorException(message);
                    }
                });

        // call YUI
        compressor.compress(out, 0, true, false, false, false);
    }
}

For testing purposes I imported an uncompressed version of jQuery and created a file named helloWorld.js. The helloWorld.js contains a single function only, just to test and verify the outcome of the servlet.

Then, I created a test.html, a simple HTML page which loads the mimimized JavaScript files:

<html>
 <body>
   <h1>Test</h1>
   <script src="./xsp/minimizer/?files=jquery-1.11.1.js+helloWorld.js">
   </script>
 </body>
</html>

This is how the WebContent folder looks like in package explorer:

When opening the test.html page, you can see that only a single request is made to load the data from the servlet:

http://hasselba.ch/blog/?p=1769
Nov 26, 2014
11 hits



Recent Blog Posts
4
Quick-n-Dirty: Hotfix for DateTimeHelper
Mon, Jun 12th 2017 3:04p   Sven Hasselbach
This weekend I stumbled over a bug of the DateTimeHelper: If the value of the field is empty, no actions and/or action listeners connected with a managed bean will be executed anymore. Here is an example of a small XPage to illustrate the problem: It does not matter if you set the disableValidators property for the text field to true, even an immediate=true won’t help here. The reason for the problem is that the renderer of the dateTimeHelper al
5
High Performance REST Applications (4) – Looking into OSGi
Thu, May 4th 2017 9:41a   Sven Hasselbach
Before going any deeper into the the servlet project, let’s have a look at the imported projects and talk about some OSGi basics. First you will notice that for every cloned repository three Eclipse projects have been imported: A plugin project A feature project An updatesite project The plugin project contains the code and all the relevant resources of the servlet. It defines extension points provided or describes which extension points are used by the plugin. A feature project is basi
6
High Performance REST Applications (3) – Importing the Starter Project
Mon, Apr 24th 2017 9:03a   Sven Hasselbach
Now you can import the projects required from Git. First, go to „File > Import…“ Import Project Then select „Projects from Git“ Projects from Git and „Clone URI“ to clone an existing repository: Clone existing respository To get the URI, you have to open https://github.com/hasselbach/ and select the repository „ch.hasselba.concurrent„. Click the „Clone or download„-Button and copy the URI from the opening box: Get the repositor
5
High Performance REST Applications (2) – Dev Environment
Sun, Apr 23rd 2017 8:55a   Sven Hasselbach
Before you can start developing a Servlet as an OSGi Plugins, you must set up a development environment first. To do this, download Eclipse IDE (Eclipse IDE for Java EE Developers) and XPages SDK from OpenNTF (The XPages SDK is a helper to create the JRE environment and the Target Platform). For development it is the best to have a (local) development server, because during development you might want to restart and/or modify it, and debugging is a lot easier if have control over the whole server
7
High Performance REST Applications (1) – Intro
Fri, Apr 21st 2017 9:33a   Sven Hasselbach
This is a new serie about developing high performance REST applications on top of Domino. It will contain my presentations from SNoUG and EntwicklerCamp this year and descripe all required steps to develop, build and deploy these servlets on a basic level. The code used in this serie is already available at GitHub: https://github.com/hasselbach/domino-rest-servlet/tree/highperformance https://github.com/hasselbach/ch.hasselba.concurrent (The high performance part is in a branch of my example D
4
Re: Domino REST performance analysis
Thu, Mar 16th 2017 8:51p   Sven Hasselbach
I have created a Quick-n-Dirty performance test for Csaba’s „10K record test“: Loading time 200 ms overall, 60 ms TTFB. Do you want to know how this works? Feel free to come to SNoUG next week or to Rudi’s EntwicklerCamp and join my sessions.
8
Domino & Java 1.8: Thank you, IBM!
Tue, Mar 14th 2017 1:16p   Sven Hasselbach
For years it was a lot of pain when developing for the Domino platform using Java 1.6 only. But now, Java 1.8 is available, and this allows to use the latest versions for a lot of libraries and development tools. After installing FP8 to the Client, Eclipse allowes to use the Domino JRE in a JavaSE-1.8 environment: This gives access to the latest M2Eclipse plugin (1.7.0). The old version problem when running with JRE 1.6… … is solved: Eclipse Updates? No problem, just do it! Latest
3
Domin & REST: Debug your Plugin
Tue, Mar 7th 2017 11:14a   Sven Hasselbach
When developing OSGi Plugins, you should have your own development server running on your local machine. Not only because of the faster deployment of changes (a new version of a plugin must always deployed with a HTTP restart), but because of the Java debugging posibilities: Only one Eclipse instance can connect to the JVM, and every request processed by the server will start the debugger. If multiple users a accessing the server while you are debugging, your Eclipse will try to debug every inco
1
Domino & REST: More about Jackson
Fri, Mar 3rd 2017 10:16a   Sven Hasselbach
When creating a REST API servlet, Jackson provides a huge list of possibilities to manipulate the JSON data, mostly using annotations. Let’s demonstrate some of them with this little class, which has only two properties: public class Demo { private String foo; private String bar; public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } public String getBar() { return bar; } public void setBar(String bar) { this.bar = ba
0
Domino & REST: Accessing Domino’s Environment / Check Authentication
Thu, Mar 2nd 2017 11:00a   Sven Hasselbach
If we want to access Domino’s Environment, it is the ContextInfo class which gives us all we need. Everything you need to do to use the class is described in an earlier blog post. The class gives mainly access to the following methods: Method Description getDataDirectory() Path to notes data directory getEnvironmentString(String envName) Returns the environment variable getServerDatabase() The actual database as NAPI object, if any getServerVariable(String varName) Variables




Created and Maintained by Yancy Lent - About - Planet Lotus Blog - Advertising - Mobile Edition