Develop Spring Boot applications and deploying them in the cloud with OpenShift directly from Eclipse

Develop Spring Boot applications and deploying them in the cloud with OpenShift directly from Eclipse

OpenShift is a brilliant and flexible cloud solution for small and larger enterprise applications. Setting up an application is as easy as 1-2-3. All you need to do is to create an account, generate SSH keys for the repository exchange and installing a JBoss OpenShift plugin (for Eclipse), basically. Of course you need to clone the application's repo and get a workflow going that works for you.

When you first clone the project structure from OpenShift, the project structure looks like something proprietary or maybe it came from a JBoss installation, it does not really matter and then again it might. Hang on!

One of the first thoughts you should have is how a workflow consisting of Git commit and push to the OpenShift server be like. Good question! You could start creating a new project under a local Tomcat server installation and then develop your website there. Then, for every change you need to deploy, your could copy all the changed files from that Tomcat installation to the locally cloned Git repo from OpenShit, which is probably another project in your workspace. The commit and push. This also means having to maintain duplicate instances of the same website. There is nothing scalable even smart about it, it is a waste of time, really. JHipster comes with some new ideas that you can borrow! More about that in a short while.

Spring Boot has very low starting costs due to clever configuration steps (almost none) before you can get an app up and running. To get started you just need to point your URL at start.spring.io and download a pre-configured Maven project, ready for import in your favorite IDE. If you include the Tomcat server in your app, starting up an embedded Tomcat server is as easy as right clicking the Application class and running a main method. If you even include the devtools, developing Spring Boot applications with AngularJS integrated into frontend pages gets really comfortable. You could even include the LiveReload plugin in the browser (for instance Chrome) and get the browser refreshing done for you. Maybe some will argue that Browsersync works better, but I do not want to be the judge of that. It is still marvellous.

But how does JHipster relate to deploying Spring Boot applications in the cloud with Openshift?

Well, you could develop a whole application using the opinionated JHipster framework, or you can borrow their Filter to get a Filter going in your webapp.

It fits very well with a standard OpenShift webapp, if you perform an outtake. The outtake is more specifically an initStaticResourcesProductionFilter method that takes a ServletContext and an EnumSet<DispatcherType> as arguments like this: 

private void initStaticResourcesProductionFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) { 

FilterRegistration.Dynamic staticResourcesProductionFilter = servletContext.addFilter("staticResourcesProductionFilter", new StaticResourcesProductionFilter());staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/src/main/webapp/*"); staticResourcesProductionFilter.setAsyncSupported(true);

}

 

This is not copying, simply borrowing, and it is not like the team behind JHipster invented FilterRegistration. 

This method resides in a @Configuration annotated class that implements ServletContextInitializer, EmbeddedServletContainerCustomizer. so that you can implement the onStartup method that will be called at server startup time. A convenience for the developer to insert some initializer code that we would like to run before any requests to the actual server. In the class you add a filter that will map a path consisting of the layout of your application to the filter. In this context the layout of the webapp. The good thing about this, is that you can arrange your own webapp to be laid out in a similar way to the layout structure of the default OpenShift application, and avoid having multiple instances of the same application elsewhere on your drive. So one project where you develop webapps locally – your cloned OpenShift default application inside your new application domain on OpenShift. One project where you develop code using Spring Boot, then committing the changes to Git when you are happy, then pushing them to the server, where the app will be deployed and you can see your changes in the cloud.

 

In order to depict this further, imagine you have an account on OpenShift with a standard Tomcat 7 server running a default application. This is your new application and you want to develop a new website, and start deploying that website from your local workspace.

A smart tool is JBoss OpenShift tools that provide tooling to deal with OpenShift. It is a plugin for Eclipse that allows you to perform certain operations in your OpenShift domain, and publish your site to the Openshift PaaS. That sounds good, so let us go ahead and use that. 

You want to clone the code you created with your new OpenShift application. First you need to make sure you have set up an SSH connection with the server. On Windows you need to install Ruby for key generation. There is an understandable guide on the OpenShift site, just go to Developers / Managing Your Applications / Remote Connection (SSH) in the guide section. Or click here https://developers.openshift.com/en/managing-remote-connection.html.

Once setup creating applications and fetching the source URL should be done in a matter of minutes. Go to OpenShift.com, log in and add an application. If you have not already created a domain, you may want to do that first. Add and application. Choose a Tomcat 7 application. Call it ”newtest.” The public URL will be http://newtest-domainname.rhcloud.com

Leave it at that, do not change any of the other settings (you may experiment with that later), click create application and let it process. Once processed a small presentation screen tells you what URL to clone to your local repository. Copy the URL to the clipboard or an empty notepad, or just go directly to your application overview page and copy it from there:

Back in Eclipse, you want to import projects from Git (right click in the package explorer → import):

The whole goal is to clone the repository to a folder stored locally on your computer:

You want to input your URI from the clipboard to the URI input field. The other fields should be filled in automatically, except the password:

Once connected and imported, just select the master branch.

If imported successfully, an area with Git Repositories should be visible in the lower left corner – this is your locally cloned repository of your new OpenShift application:

 

You can now exit the wizard, import the project as a Maven project or you can import the Git project as a Maven project right away. Once imported your new app structure in the package explorer should look something like this:

Go ahead and edit the index.html file and commit it to the repo, then push it to the server, go to the server URL and see your newly edited file deployed in the cloud. Milestone 1 reached!

Hopefully it should be evident that there is no local server attached to the application. How to go about this? Well you could copy the whole app structure to the webapps dir of a Tomcat installation, but that is very tedious and nobody likes to work that much, unless your really like configuring a Tomcat. You could also start editing right away, and then live with testing your changes in the production environment, but that is not a smooth process.

We can convert the OpenShift app to a Spring Boot application with an embedded Tomcat!

Open up the project's POM file, and adjust it so that it contains the dependencies needed for a Spring Boot application. Add

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.3.2.RELEASE</version><relativePath />

</parent>

 

 

Just before <repositories>and add

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

Somewhere in the <dependencies> section. Override the embedded Tomcat and logging versions, so that they fit with the Tomcat 7 server available on OpenShift

 

 

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-core</artifactId>

<version>7.0.55</version>

</dependency>

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-logging-juli</artifactId>

<version>7.0.55</version>

</dependency>

 

That should do it. We are almost done. Create a class and insert the minimum code needed in order to start up a Spring Boot application. We can call this class WebBootApplication:

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class WebBootApplication {

public static void main(String[] args) {

SpringApplication.run(WebBootApplication.class, args);

}

}

 

Now in order make the app recognize the directory structure, go ahead and add a class you annotate with @Configuration

First implement the filter class, that we borrow from JHipster

import org.apache.commons.lang.StringUtils;

 

import javax.servlet.*;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

public class StaticResourcesProductionFilter implements Filter {

@Override

public void init(FilterConfig filterConfig) throws ServletException {

}

 

@Override

public void destroy() {

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

HttpServletRequest httpRequest = (HttpServletRequest) request;

String contextPath = ((HttpServletRequest) request).getContextPath();

String requestURI = httpRequest.getRequestURI();

requestURI = StringUtils.substringAfter(requestURI, contextPath);

if (StringUtils.equals("/", requestURI)) {

requestURI = "/index.html";

}

String newURI = "/dist" + requestURI;

request.getRequestDispatcher(newURI).forward(request, response);

}

}

 

Then go ahead and add the component that registers the filter:

import java.util.EnumSet;

import javax.servlet.DispatcherType;

import javax.servlet.FilterRegistration;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;

import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;

import org.springframework.boot.context.embedded.ServletContextInitializer;

import org.springframework.context.annotation.Configuration;

@Configuration

public class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer {

private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);

@Override

public void customize(ConfigurableEmbeddedServletContainer container) {

// TODO Auto-generated method stub}

 

@Override

public void onStartup(ServletContext servletContext) throws ServletException {

log.info("Web application configuration, using profiles");

EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,DispatcherType.ASYNC);

initStaticResourcesProductionFilter(servletContext, disps);

log.info("Web application fully configured");

}

private void initStaticResourcesProductionFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {

System.err.println("Initializing filter");

log.info("Registering static resources production Filter");

FilterRegistration.Dynamic staticResourcesProductionFilter = servletContext

.addFilter("staticResourcesProductionFilter", new StaticResourcesProductionFilter());

staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/src/main/webapp/*");

staticResourcesProductionFilter.setAsyncSupported(true);

}

}

 

 

 

And that's it. Now you have a Spring Boot application with an embedded Tomcat you can startup and navigate to localhost:8080 and start working on. On top of that you even keep the same structure of the OpenShift default webapp structure you got when you checked out the source from Git. It is an OpenShift application converted to a local Spring Boot application and eventually it will turn out to be your application! All that remains for you is to invent a nice site, right click and commit and push your code to the cloud!

sounds like Spring Boot app has not started at all. I can help you. Send me info about how your setup is to me privately. we will figure it out. Thanks

Like
Reply

Hi Carl, I tried this approach but when starting local SpringBoot App I'm getting this output in the log: http://pastebin.com/6KMXekak and localhost:8080 is not serving anything. Do you now how to solve this? I used latest stable version of SpringBoot os if you can at least confirm that this kind of setup is working with it in your case. Thank you!

Like
Reply

Super cool. Thank for sharing...

Like
Reply

To view or add a comment, sign in

More articles by Carl Gustaf Hjelt Liebe

Others also viewed

Explore content categories