This blog post describes how to create a windows service from a Java application, it is a slightly more fleshed out version of the JavaZone 2016 lightning talk "A Java windows service in 10 minutes".

A problem sometimes encountered by a Java programmer, is to make your Java program into a Windows Service. This is may be a bump in your project, particularly if you don't know anything about windows services, or much about windows for that matter.

The demo created a running, working, Windows service server using 14 lines of Java code, and some maven configuration.

Before starting on the demo, a few words on what windows services are (from a GNU/linux/UNIX perspective):

  • Windows services are the "daemons" of the windows world
  • Windows services are normally started when the windows system starts, and stopped when the windows system shuts down
  • Windows services can be stopped and started by administrator users, both using a GUI and using command line commands
  • Windows services can be configured to run with a particular user, restricting what the service can do (default is the local user "Local System")

To create the installer the demo use a maven plugin called maven-windows-service-installer-plugin. The maven plugin in turn relies on izpack for the installer and uses the apache commons daemon to execute the Java program.

The Java program turned into a windows service during the demo, is the Wiser test SMTP server. Wiser was picked, because:

  1. It has an appropriate API
  2. An SMTP service is easy to demonstrate, and it is something other than yet another HTTP service

Since the demo might be hard to follow (a lot of information in 10 minutes), this blog post describes all steps of the demo (note: the complete code can be found on github at https://github.com/sbang/ansmtpserver ).

Required prior knowledge:

  • Java programming
  • Apache maven

Required software to retrace the demo:

  • Apache maven (any maven 2 or 3 will do)
  • A Java SDK (I'm using the newest Java 1.8, but any Java SDK 1.7 will probably do)
  • An eclipse IDE (I'm using Eclipse Neon, but any recent eclipse will probably do)
  • A telnet command line application (since this is for windows, just use Windows cygwin bash with the inetutils package, just run the installer and include inetutils)

To retrace the demo, do the following operations:

  1. Start eclipse and open the Workspace "C:\workspace"
  2. Right click the package explorer and select New->Other…
  3. In the "New" dialog box:
    1. Select Maven->Maven Project
    2. Click the "Next>" button
    3. Checkmark the checkbox "Create a simple project (skip archetype selection)" at the to of the dialogbox
    4. Click the "Next>" button
    5. In the "Group id" text box, type
      ansmtpserver
    6. In the "Artifact id" text box, type
      ansmtpserver
    7. Click the "Finish" button
  4. Open the "ansmtpserver" project and double click "pom.xml" to open it
  5. In the pom.xml editor (title "ansmtpserver/pom.xml"):
    1. Select the Dependencies tab
    2. Click the "Add…" button
    3. In the "Select Dependency" dialog box:
      1. In the field "Enter groupId, artifactId or sha1 prefix or pattern (*)", type
        windows-installer
      2. Select "com.alexkasko.installer windows-service-installer-common"
      3. Click the "OK" button
    4. Click the "Add…" button
    5. In the "Select Dependency" dialog box:
      1. In the field "Enter groupId, artifactId or sha1 prefix or pattern (*)", type
        subethamail
      2. Select "org.subethamail subethasmtp"
      3. Click the "OK" button
    6. Click the "Add…" button
    7. In the "Select Dependency" dialog box:
      1. In the field "Enter groupId, artifactId or sha1 prefix or pattern (*)", type
        slf4j-simple
      2. Select "org.slf4j slf4j-simple"
      3. Click the "OK" button
    8. Save the pom.xml file
  6. Right-click ansmtpserver->src/main/java in the "Package Explorer" and select New->Package
  7. In the "New Java Package" dialog box:
    1. Let the "Name" field have its default ("ansmtpserver")
    2. Click the "Finish" button
  8. Right-click the ansmtpserver->src/java/main->ansmtpserver package in the "Package Explorer" and select New->Class
  9. In the "New Java Class Dialog"
    1. In the "Name" field, type
      AnSmtpServer
    2. In "Interfaces", click the "Add…" button
    3. In the "Implemented Interfaces Selection" dialog box:
      1. In "Choose interfaces", type
        dae
      2. In "Matching items", select "DaemonLauncher – com.alexkasko.installer"
      3. Click the "OK" button
    4. Click the "Finish" button
  10. Modify the generated AnSmtpServer.java file in the following way
    package ansmtpserver;  import org.subethamail.wiser.Wiser;  import com.alexkasko.installer.DaemonLauncher;  public class AnSmtpServer implements DaemonLauncher {  	private Wiser server;  	public AnSmtpServer() { 		super(); 		server = new Wiser(); 		server.setHostname("javazone"); 		server.setPort(2200); 	}  	public void startDaemon() { 		server.start(); 	}  	public void stopDaemon() { 		server.stop(); 	}  }
    1. Add a Wiser field
    2. In the constructor, create an Wiser instance, set the host name, and the port number
    3. In the startDaemon() method start the Wiser server
    4. In the stopDaemon() method stop the Wiser server
  11. Save the modified AnSmtpServer.java file
  12. Right-click ansmtpserver->src/main/resources in the "Package Explorer" and select New->File
  13. In the "New File" dialog box
    1. In "File name", type
      simplelogger.properties
    2. Click the "Finish" button
  14. Modify the "simplelogger.properties" file to have the following content
    org.slf4j.simpleLogger.defaultLogLevel=debug

    and save the file

  15. Select the "ansmtpserver/pom.xml" editor, and select the "pom.xml" tab, and paste the following before the </project> end tag. This configuration will be the same for all installers with the exception of the <prunsrvDaemonLauncherClass> tag
                        <build>   <plugins>    <plugin>     <groupId>com.alexkasko.installer</groupId>     <artifactId>maven-windows-service-installer-plugin</artifactId>     <version>1.0.6</version>     <dependencies>      <dependency>       <groupId>com.alexkasko.installer</groupId>       <artifactId>windows-service-installer-common</artifactId>       <version>1.0.6</version>      </dependency>     </dependencies>     <configuration>      <prunsrvDaemonLauncherClass></prunsrvDaemonLauncherClass>      <use64BitJre>true</use64BitJre>     </configuration>     <executions>      <execution>       <id>build-installer</id>       <phase>package</phase>       <goals>        <goal>installer</goal>       </goals>      </execution>     </executions>    </plugin>   </plugins>  </build>
  16. Open ansmtpserver->src/main/java->ansmtpserver->AnSmtpServer.java in the "Package Explorer", right-click the "AnSmtpServer" class, and select "Copy Qualified Name" and paste the name into the <prunsrvDaemonLauncherClass> element
  17. Save the pom.xml file
  18. Open a cmd.exe window, and type the following commands to build the installer
    cd c:\windows\ansmtpserver mvn clean install
  19. Open a windows explorer on C:\Windows\ansmtpserver\target
  20. Right click the ansmtpserver-0.0.1-SNAPSHOT-installer.zip file and select "Extract all…" to the folder "C:\workspace\ansmtpserver\target"
  21. Open the folder "C:\workspace\ansmtpserver\target\ansmtpserver-0.0.1-SNAPSHOT-installer", right-click the "install.exe" file and select "Run as administrator"
  22. Open a "Cygwin 64 terminal" window and type the following command
    telnet localhost 2022

    The expected response is

    Trying 127.0.0.1... telnet: Unable to connect to remote host: Connection refused

    since nothing is listening to port 2200

  23. Click the installer all the way to the end, using defaults for everything
  24. Open the windows services window and there will be a new windows service "ansmtpservice" shown as "Running"Windows services with the ansmtpserver shown
  25. Try the "telnet localhost 2200" command again, and this time there will be a response, and it will be possible to talk SMTP over the connectiontelnet_session
  26. Stop the "ansmtpservice" service and the telnet connection will be disconnected

Thus ends the installer part.

Some simple improvements to this installer are possible:

  • Better descrption for the service in "Windows Services"
    • Just add the following to the <configuration> setting of the maven-windows-service-installer-plugin:
      <prunsrvServiceName>AnSmtpServer</prunsrvServiceName> <prunsrvDisplayName>An SMTP server</prunsrvDisplayName> <prunsrvDescription>This service responds to incoming STMP connections on port 2200.</prunsrvDescription>
  • Install the service under "C:\Programs and Files"
    • Just add the following to the <configuration> setting of the maven-windows-service-installer-plugin:
      <izpackDefaultInstallDir>$APPLICATIONS_DEFAULT_ROOT\ansmtpserver</izpackDefaultInstallDir>
  • Attach the zip file containing the installer to the maven artifact, so that the installer can be deployed to a maven repository, where other maven files can download and unpack the installer from (easy distribution)
    • Add the following inside <build><plugins></plugins></build> of the pom.xml build
                              <plugin>     <groupId>org.codehaus.mojo</groupId>     <artifactId>build-helper-maven-plugin</artifactId>     <version>1.10</version>     <executions>      <execution>       <id>attach-artifacts</id>       <phase>package</phase>       <goals>        <goal>attach-artifact</goal>       </goals>       <configuration>        <artifacts>         <artifact>          <file>target/${project.artifactId}-${project.version}-installer.zip</file>          <type>zip</type>          <classifier>installer</classifier>         </artifact>        </artifacts>       </configuration>      </execution>     </executions>    </plugin>   </plugins>                      

A windows-service-installer that contains the above improvements and more, is this installer for Apache Jena Fuseki.