Pages

Showing posts with label Tomcat. Show all posts
Showing posts with label Tomcat. Show all posts

Wednesday, August 20, 2014

HowTo:: Spring 4 Scala MVC without Web.XML - Tiles3 : static resources and front-end templating

Img.1.:: project structure - Tiles3 with localised messages and simple template 
This blogpost is fully focused on simple spring 4 scala project Tiles configuration and how to give access to the localised messages (see. Img.1.). 
In the WebConfig scala class is also configured:
1.  messageSource @Bean :
@Bean(name = Array("messageSource"))
def getMessageSource: MessageSource = {
  val msgSrc:ReloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource()
  msgSrc.setBasename("classpath:/messages/message")
  msgSrc
}
Such bean give us access to the messages place in the "resource" project folder.
2.  default displayed locale by the "localeResolver" bean:
@Bean(name = Array("localeResolver"))
def getLocaleResolver: LocaleResolver = {
  val cookieLocaleResolver: CookieLocaleResolver = new CookieLocaleResolver()
  cookieLocaleResolver.setDefaultLocale(new Locale("en"))
  cookieLocaleResolver
}
3. access to the static project resources as is mentioned in to one of previous posts 

Let's start on the front-end dev. with the default tiles.xml file in the ../pages directory

  
 
 
  
  
 
 
  
  
    
    
  

  The example project has two page to display based on "standardLayout" which consists from header and footer
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>


  
     <fmt:message>
 <tiles:insertAttribute name="title" />
     </fmt:message>
     <link rel="stylesheet" href="<c:url value="/app/css/style.css" />" >
  


Take a look into github example project
After having also *.jsp pages defined we can run our Tomcat7 container
container:start
and open the web browser and call the applicaiton: 
1. http://localhost:9090/?lang=de
2. http://localhost:9090/test/web?lang=de
3. http://localhost:9090/test/web?lang=en
4. http://localhost:9090/test/web

Enjoy Tiles 3 and take a look on my github example project to get more information around

Tuesday, August 19, 2014

Spring 4 Scala MVC without Web.XML - Tiles3 with SBT Tomcat7 configuration

  In the one of previously published blogposts I've written about Spring Container running on Jetty (Scala Spring 4 MVC without Web.XML configuration with static resources,  update: Scala Spring 4 MVC without Web.XML - logging with Log4j and SLF4j)

  The next example Spring 4 Scala MVC without Web.XML with Apache Tiles3 runs on Tomcat7 using Java Servlet 3.x but before we need to configure SBT to provide us such functionality: 

1. configure project build.sbt file in following example way
libraryDependencies ++= Seq(
  "org.springframework" % "spring-webmvc" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context-support" % "4.0.6.RELEASE",
  "org.apache.tiles" % "tiles-jsp" % "3.0.4",
  "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided",
  "javax.servlet" % "jstl" % "1.2" % "compile",
  "org.slf4j" % "jcl-over-slf4j" % "1.7.5" ,
  "org.slf4j" % "slf4j-api" % "1.7.5" ,
  "org.slf4j" % "slf4j-log4j12" % "1.7.5",
  "log4j" % "log4j" % "1.2.17" excludeAll(
        ExclusionRule(organization = "com.sun.jdmk"),
        ExclusionRule(organization = "com.sun.jmx"),
        ExclusionRule(organization = "javax.jms")
      ),
  "org.apache.tomcat.embed"% "tomcat-embed-core"% "7.0.40"% "container",
  "org.apache.tomcat.embed"% "tomcat-embed-logging-juli"% "7.0.40"% "container",
  "org.apache.tomcat.embed"% "tomcat-embed-jasper"% "7.0.40"% "container"
)

tomcat(port = 9090)
important part is about tomcat related libraries which allow us:

2. by having running sbt such configuration makes possible to use following command 
container:start
stopping server is by exchanging word after :

Enjoy SBT Tomcat 7 development !

project: miko-spring-scala on github

Spring 4 Scala MVC without Web.XML - Tiles3 with more services @Autowired

  Let's make one more update before I'll do the push of Spring 4 Scala Tiles 3 example project to my GiTHub. We know that Scala is kind of hype nowadays (which is great for any application evolution), true is that the functional approach is reachable with other languages (java, python, ruby .... javascript ;), only Scala has been developed in functional manner since its basics. Such fact could great to hear for JavaScript developers because it could be easier to enter back-end development world ;). Since my experiences with Scala it does make sense to push the mind into functional design pattern thinking -> makes whole life much easier.   

  The most of times is not impossible to start any enterprise project from scratch. The acceptable way is smart refactoring with possible new technologies or techniques usage and improving the code quality which should go hand in hand. 

  Spring stack (framework, integration, spring-data and more projects supporting dependency injection DI<IoC>) is well know in the enterprise world and it's also excited turning project parts into the Scala world. 

  Let's show how to use @Autowired annotation to give spring scala controller more responsibility. 
1. define example Service
//a. define interface ~ trait 
trait ExampleImportService {
  def name: String
}
...
//b. define class ~ service functionality 
@Service("exampleImportService")
class ExampleImportServiceImpl extends ExampleImportService{
  override def name: String = "Imported service over XML"
}
2. Autowire services with the Controller 
@Controller
@RequestMapping(Array("/"))
class HelloExampleController @Autowired() (exampleService: ExampleService, exampleImportService: ExampleImportService){

  private val logger = LoggerFactory.getLogger(getClass)

  @RequestMapping(method =  Array(RequestMethod.GET))
  def printMain( model: ModelAndView): ModelAndView = {
    model.addObject("message", "Here is Scala with ServiceName = " + exampleService.serviceName)
    model.addObject("importMessage", "Here is Scala with ServiceImportName = " + exampleImportService.name)
    model.setViewName("main")
    model
  }

  @RequestMapping(method =  Array(RequestMethod.GET), value = Array[String]{"/test/web"})
  def printTest(model: ModelMap): String = {
    logger.info("PrintTest Start")
    "test"
  }
}
  The controller "HellolExampleController" defines different return types (callbacks -> ModelAndView holder and String) based on specific request handling. Both return types are resolved then by our simple DispatcherServlet configuration.
 val servlet: Dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx))
 servlet.addMapping("/")
 servlet.setLoadOnStartup(1)
  The example project uses Java Servlet 3.0 (intro) with interface ServletRegistration.Dynamic and runs on Tomcat 7.x using SBT building tool (next blog post how to enable tomcat(port = 9090))
Let's start and stop:
1. sbt -> container:start
2. sbt -> container:stop
and Enjoy spring 4 scala!  

project: miko-spring-scala on github

Friday, August 8, 2014

HowTo:: Scala Spring 4 MVC without Web.XML configuration with static resources handling

This blog post is fully focused on Scala language and how to use it for Spring 4 based application development. I'll  modify application I've used over previous blog post series ("Spring4Netty without Web.XML configuration on Java 8.."). 

  Although Spring Framework is so popular in the Java land, there is no reason why not to use Scala language for the EE application development. 
In case when the Applicaiton front-end uses popular AngularJS Framework I personally find Scala usage much "easier" (ps: still lot of work :) and comfortable to understand back-end and front-end functionality as javascript uses callbacks. 

for building new Spring4 Scala application we use following tools: 
of course Jetty server can be change to the Tomcat one. 
  Whole sample application has been developed in IntelliJ IDEA 13.x IDE. 
After we have created the SBT project under IntelliJ we need to import some plugins.
Img.1.:: SBT Project Structure - plugins.sbt
  To import them we change sbt plugins setup by modifying appropriate file (Img.1.) in the following manner. 
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "1.0.0-M4")

addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.6.0")
  We have now added two plugins  xsbt-web-plugin and sbt-idea.  The xsbt-web-plugin is used for building web enterprise application. Both of them are extensions to SBT building tool.

  Next step is to add necessary libraries dependences into the build.sbt file. As we want to link also static resources, for the front-end development, the number of needed libraries will be bigger. 
  The build.sbt file will look after our modification like following example.
name := "miko-spring-scala"

version := "1.0"

scalaVersion := "2.10.3"

libraryDependencies ++= Seq(
  "org.springframework" % "spring-webmvc" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context-support" % "4.0.6.RELEASE",
  "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided",
  "javax.servlet" % "jstl" % "1.2" % "compile",
  "org.eclipse.jetty" % "jetty-webapp" % "9.1.0.v20131115" % "container, compile",
  "org.eclipse.jetty" % "jetty-jsp" % "9.1.0.v20131115" % "container"
)

jetty(port = 9090)
here is visible which kind of servlet engine provider will be used (in case of Tomcat change jetty() to tomcat()). 

  When the SBT application is ready we will use commands to start/stop it.
... SBT console ...
container:start

container:stop
...
  All libraries and plugins are ready and we can start building Spring4 Scala Application without using Web.XML and with linked static resources for the next front-end development. Web.xml file will look almost empty in contracts to XML configuration.
...
Miko Scala Spring 4 - Example without Web.xml 
...
  The application package structure is very similar to the previous ones. I want to keep consistency and get possibility to have the reference to the Java implementation (Img.2.) in case of possible comparison.
Img.2.:: Example Spring4 Scala application packages structure

Now I simply turn the Java into the Scala in several steps

1. Scala WebConfig will look like following

..
@Configuration
@ComponentScan(basePackages = Array("miko.scala.helloexample"))
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter{

  override def addResourceHandlers(registry: ResourceHandlerRegistry) = {
    registry.addResourceHandler("/app/**").addResourceLocations("/app/").setCachePeriod(31550522)
  }

  override def configureDefaultServletHandling(configurer: DefaultServletHandlerConfigurer) = {
    configurer.enable()
  }

  @Bean
  def viewResolver = {
    val viewResolver = new InternalResourceViewResolver
    viewResolver.setViewClass(classOf[JstlView])
    viewResolver.setPrefix("/WEB-INF/pages/")
    viewResolver.setSuffix(".jsp")
    viewResolver
  }
}
2. Scala WebInitializer which help us setup ServletContext at the starup 
class WebInitializer extends WebApplicationInitializer{

  override def onStartup(servletContext: ServletContext) = {
    val ctx = new AnnotationConfigWebApplicationContext
    ctx.register(classOf[WebConfig])

    ctx.setConfigLocation("META-INF/spring/app-spring-scala.xml")

    val servlet: Dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx))
    servlet.addMapping("/")
    servlet.setLoadOnStartup(1)
  }
}
3. Scala HelloExampleController class annotated by @Contoller annotation. The Annotation takes care about HttpServletRequest and Responses. This example controller also shows how Services are @Autowired when Scala language is used. 
@Controller
@RequestMapping(Array("/"))
class HelloExampleController @Autowired() (exampleService: ExampleService, exampleImportService: ExampleImportService){

  @RequestMapping(method =  Array(RequestMethod.GET))
  def hello( model: Model) = {
    model.addAttribute("message", "Here is Scala with ServiceName = " + exampleService.serviceName)
    model.addAttribute("importMessage", "Here is Scala with ServiceImportName = " + exampleImportService.name)
    "hello"
  }
}
4. Scala Example...Services used by HelloExampleController are done over quite powerful Traits implementation. Traits are very similar to Java Interfaces but they allows partial implementation which makes them much more powerful (out of blogpost scope ;).  
trait ExampleImportService {
  def name: String
}
-----
class ExampleImportServiceImpl extends ExampleImportService{
  override def name: String = "Imported service over XML"
}

after all those steps we've ready Scala Spring 4 application to test. We've also source code to compare with previous Java8 implementation. Scala does the great work because thinking in functions and callbacks intentions makes whole development more strait forward. 
Enjoy sample application ! (GitHub miko-spring-scala)

Friday, June 27, 2014

Spring4Netty without Web.XML configuration on Java 8 (JBoss WildFly and Tomcat 8) - part.5:: Application Servers and logging

  
img.1.: official log



  This part about selected application start normally, just by downloading both of them and setting them up in your favorite IDE (img.2.) which is in my case IntelliJ IDEA (img.1.)


img.2.: Application Serves bond with IDE
   So here we go, app servers inside (like the intel processor). What it good to point out already at the beginning is the servlet-api versions support. 

Don't try to run this example project (GiTHub repository) on Tomcat 6.x. Why ? It's because Tomcat 6.x supports servlet-api ver. 2.5, and as you can find in the parent pom.xml file, the version 3.x of servlet-api is required. It's because of features we have touched earlier  (part.4..

   Almost every project uses some logging framework, in project case we use Simple Logging  Facade (SLF4j) together with well known Log4j. I don't want to write a lot about application logging design it's the another story (this project is just hot setup of usage). 
   What I want to touch here is the topic "How to enable logging under JBoss WildFly per deployment for SLF4j" 
   It 's because by the default installation of WildFly it not allowed. You see actually any Logger output in your SystemOut or log file.  

Let's edit in following way the ../standalone.xml file that you can find in the WildFly directory
   ...
   
        
            
            <!-- IMPORTANT LINE --> 
            

            
                
                
                ...
                
                
            
            
        ...
        
   ...
   
   ...
The logging is not fully setup but important details are there so you can enjoy my project. 
s4netty project GiTHub repository



ps: Also I've not merged JUnit, Mockito  tests in case I didn't want to touch this topic in this blogpost. 

Spring4Netty without Web.XML configuration on Java 8 (JBoss WildFly and Tomcat 8) - part.4:: Base - Spring MVC without Web.xml usage 2

  
img.1.: s4netty-web deployment result

  The base web module s4netty-web is almost similar to  the previous worker module (s4netty-worker) from the perspective of the Spring MVC configuration. 

  The main difference is the Servlet Context setup. In the usage 1 (s4netty-worker) everything was defined by appropriate annotations. In the usage 2 (s4netty-web) the Servlet Context is defined in traditional XML way from perspective of servlet definition. 
   ...
   

   
     
     
   
   ...
  The WebApplicationContext is instantiated by XmlWebApplicationContext which (img.2.) extends AbstractRefreshableWebApplicationContext. Here we go deeper to all WebApplicationContext implementations which are supposed to instantiate themselves  according to the provided configuration over the interface. 
img.2.: s4netty-web module structure 
  The purpose of  XmlWebApplicationContext  class is to load WebApplicationContext from the XML configuration files.  
public class WebInitializer implements WebApplicationInitializer {
    ...
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        ...
        XmlWebApplicationContext ctx = new XmlWebApplicationContext();
        ctx.setConfigLocation("WEB-INF/spring/dispatcher-servlet.xml");
        ctx.setServletContext(servletContext);
        ...

  What was also earlier only briefly touched (part1:: img.0.) is the ability of s4netty-web module to communicate with s4netty-worker  module utilising JSON serialisation/deserialisation over the service and pre-defined port P.

  The s4netty-web module uses instantiation of the RestTemplate which simplifies communication with HTTP server, its synchronous and it enforces RESTful principles, what is obvious from it name RestTemplate ;), but honestly it's pretty handy to use. 
@Controller
@RequestMapping("/")
public class MainController {
    ...
    RestTemplate restTemplate = new RestTemplate();

    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
    ... 
  Let's ask s4netty-worker module for the car list using newly instantiated RestTemplate
    ...
   private List getSimpleCarList(){
        List result = new ArrayList<>();
        try{
            result = restTemplate.getForObject(S4_NETTY_WORKER_LINK, List.class);
            logger.debug("getSimpleCarList result= " + result);
        }catch (HttpClientErrorException e){
            logger.error("getSimpleCarList jsonCarList e= " + e);
        }
        return result;
   }
   ...

  Now we have ready two deployable war files and we can take a look at the result. But before we do so it's fair to mention why such configuration works.  The reason is that we do use for
 registering servlets in both cases  
   ...
   import javax.servlet.ServletRegistration.Dynamic
   ...

interface which uses one of addServlet()  methods into ServletContext. The interface is the part of javax.servlet-api imported previously by Maven into the project. 
  ...
  
        javax.servlet
        javax.servlet-api
        3.0.1
        provided
  
  ...
After this final hit we do know all and we can start with deployment on application servers (JBoss WildFly & Tomcat 8 were selected).
Let's make it in the Next part (Click Next

s4netty project GiTHub repository

  

Thursday, June 26, 2014

Spring4Netty without Web.XML configuration on Java 8 (JBoss WildFly and Tomcat 8) - part.3:: Worker - Spring MVC without Web.xml usage 1

  

  Now we are entering the last stage in case of s4netty-worker.  Although we have already enabled Netty usage under spring ecosystem, we still want to provide some simple web (Spring MVC) for this module to see the output from the Netty JSON service.  


s4netty-worker - spring mvc output
img.1.: Spring MVC output from s4netty-worker

  I won't go into the details how to build up the basic Spring MVC project because it's easy to find out by our friend google. What is interesting is how to not use web.xml (Deployment Descriptor Element which determinates the urls mapping to appropriate servlets ) definition alias get some freedom for Java web applications. In case of s4netty-worker we do almost everything over annotations, only beans will be defined in separate app-worker-config.xml file (viz. img.2).  


img.2.: s4netty-worker module structure 

  Before we initiate web application itself by WorkerWebInitializer, that implements WebApplicationInitializerwe need to do some configuration here. (ps. WebApplicationInitializer allows us to configure servlets, filters and etc. by @Override onStatrup method)
public class WorkerWebInitializer implements WebApplicationInitializer {
   ...
   @Override
   public void onStartup(ServletContext servletContext) throws ServletException {
       AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
       ctx.register(WorkerWebConfig.class);
       ctx.setConfigLocation("spring/app-worker-config.xml");
   ...
without such configuration our WorkerWebInitializer is useless because after WebApplicationContext instantiation Spring looks for Spring configuration files annotated by @Configuration annotation. For this purpose we create WorkerWebConfig class. 


@Configuration
@ComponentScan("com.miko.s4netty")
@EnableWebMvc
public class WorkerWebConfig {
   ...
   @Bean
   public UrlBasedViewResolver setupViewResolver() {
   ...

in WorkerWebConfig class we tell to the Spring where it should look for the rest of components (example: classes annotated by @Controller). By using @EnableWebMvc we import  the DelegatingWebMvcConfiguration which delegates us to all beans reliable for WebMvcConfigurer and our customisation.  At the end the method setupViewResolver allows us to briefly solve symbolic link name to the URL. Pretty cool, isn't it ?

  The one of the impact is that we can store our favorite ;) *.jsp pages in the appropriate directory (img.2.)

  Now we have ready s4netty-worker web output with appropriate Beans initialisation, which is done by ServletContext configuration definition located in the file spring/app-worker-config.xml

  

  
    
  
   And finally our result looks according to the img.1. mentioned at the beginning of this part. 
The big moment is here because we are moving to the stage 2 (s4netty-web).
The next part (Click Next

s4netty project GiTHub repository 
  

Spring4Netty without Web.XML configuration on Java 8 (JBoss WildFly and Tomcat 8) - part.2::netty and JSON

  

  In the introduction (part.1). we've pictured out the basic idea of the project  abstraction(car exchange;). In this part we are going to configure Netty as the part of maven spring module (s4netty-worker). 

  Let's draw the agenda that allows us to start netty server under the spring ecosystem:
  1. initiate serverBootstrap object and configure the Netty server from properties file (worker-server.properties).
  2. configure the group, channel, handler and some channel options (ps: keep alive signal has been ignored in this project)
  3. Channel initialisation  
  4. Netty JSON service response
  5. Netty JSON request handling
  Let's begin and configure WorkerNettyServer which contains the instance of the serverBootstrap bean (add.1.). ServerBootstrap definition can be found in WorkerNettyConfig class.
@Bean(name = "serverBootstrap")
public ServerBootstrap bootstrap() {
All necessary  properties for WorkerNettyConfig class used by serverBoostrap (add.1.) bean initialisation are taken from the config the file (worker-server.properties) 
@Configuration
@ComponentScan("com.miko.s4netty")
@PropertySource("classpath:worker-server.properties")
public class WorkerNettyConfig {
  To make possible reading from the *.properties file   
@Value("${tcp.port}")
private int tcpPort;
we need to have access to the current Spring Context. This goal we achieve by using property sources place holder :
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
   return new PropertySourcesPlaceholderConfigurer();
}
Now WorkerNettyConfig knows all values for its initiation 
@Bean(name = "serverBootstrap")
public ServerBootstrap bootstrap() {
   ServerBootstrap b = new ServerBootstrap();
After all those configuration steps, we get access, inside the WorkerNettyServer class, to the bean "serverBootstrap" by using Qualifier annotation for candidate Bean serverBootstrap (add.2.). 
@Component
public class WorkerNettyServer {
    ...
    @Autowired
    @Qualifier("serverBootstrap")
    private ServerBootstrap serverBootstrap;
    ...
and we can have quickly assign all serverBootstrap properties (add.2.
@Bean(name = "serverBootstrap")
public ServerBootstrap bootstrap() {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup(), workerGroup())
    .channel(NioServerSocketChannel.class)
    .childHandler(workerInitializer);
  So move forward and initiate the Channel and it's pipeline in the WorkerInitializer class (add.3.). Of course all according to our "master plan" to have JSON service listening on the specified port P and exchanging car list with base.
  In this case we need totell Netty how it should deal with such type of the request by utilising HttpServerCodec (add.4.). 
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(workerProviderHandler);
  Currently it looks like JSON service  is listening on the port P and everything is almost ready to go. Well not exactly, there is still a some work do. 
  One good question could be about some missing definition :) oh, yes, where is 
workerProviderHandler ? (add.5.)  and here we go.
@Component
@ChannelHandler.Sharable
@Qualifier("workerProviderHandler")
public class WorkerProviderHandler extends ChannelInboundHandlerAdapter {
  ...
  @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg; 
  ...
  The workerProviderHandler is the extension of ChannelInboundHandlerAdapter and it handles our request and provides the JSON response to the requestor (s4netty-web). 
The request itself consists from results provided by spring service. 
...
@Autowired
SimpleCarService simpleCarService;
...
Gson library has been used to serialise and deserialise POJO objects.

After defining handler and assigning to the pipeline we are done with Spring-Netty Configuration and ready to define module (s4netty-worker) Spring MVC without Web.xml usage. 
Sure, in the next part (Click Next

s4netty project GiTHub repository




Spring4Netty without Web.XML configuration on Java 8 (JBoss WildFly and Tomcat 8) - part.1::introduction

  
  Although I'm working with Netty for while ( in different scenarios ;) ,  I've not found so much examples how to use Netty 4.x together with Spring Framework 4.x. Honestly I've found mostly some pieces of the whole solution (maybe I was not search so much around). 
  My following project shows how to make it  run. Another purpose of it is to present Spring 4 configuration without web.xml.

  My idea at the beginning was that this blog post will be just only small description how to. Pretty soon I realised that there is no chance to sum everything up into one blog post. I'd rather split everything into smaller parts than long fuzzy text (hopefully this text won't be fuzzy :). So I've separated everything  and parts could be accessed individually if  it's needed.  

The project is also available over my GiTHub repository .


img.0.: s4netty results (s4netty-web, s4netty-worker and JSON)


agenda:

  1. Configure Netty as service provider (s4netty-worker) 
  2. Configure s4netty-worker Spring MVC without Web.xml usage 1
  3. Configure Spring MVC without web.xml (s4netty-web) usage 2
  4. Run everything on JBoss Wildfly or Tomcat 8 with logging
servers: 
  1. Tomcat 8
  2. JBoss WildFly

development IDE: IntelliJ IDEA 13.x
other technologies: JRebel 6.x Experimental 
building tool: Maven 3.2.x
libraries: see the maven pom.xml - the parent module

Introduction: 
  The basic abstraction behind the application is exchanging JSON object between web spring MVC BASE (s4netty-web) and s4netty WORKER (s4netty-worker) (img.1.). The object exchange is done over defined port P.  For this purpose JSON has been used as the type of object serialisation. 
img.1.: s4netty app abstraction
  Both Spring-Base (s4netty-web) and Netty-Worker (s4netty-worker) modules use Spring MVC Framework with different type of WebApplication context initialisation. Aside Netty-Worker uses Netty (asynchronous event-driven framework) to open the Port P to provide the result of the spring service to the Spring-Base (s4netty-web). Spring-Base uses restTemplate for communication with  Netty-Worker. 

  So let's start to exchanging cars and move to the PART 2. (click).



Friday, May 30, 2014

BIRT , Spring framework and Neo4j (BSN) - one more thing ~ Cypher

The main intent of the previous blog post (ref.1.: "BIRT , Spring framework and Neo4j (BSN)") was to describe sample BIRT integration into the Spring-Ecosystem with usage of Neo4j GraphDB over spring-data-neo4j project. 

GiTHub project: miko-spring-birt is waiting to be tested

I got some open questions there and some fun with running on different machines. The answer to the FeatureTwo (ref.1.), is still postponed, but it's coming, let's keep in mind. 

This additional blog post I would like to focuse on awesome features of Cypher and show some nice use-cases, how to get POJOs from Neo4j and deal with them. 
(moto: keep it simple just Cars and Garages)

Let's start with few words at the beginning. 
Cypher (intro) is a declarative graph query language which allows us to do lot of things (expressive and efficient queries , creating or updating GraphDB etc.). The main goal has been to create language suitable for developer and professionals (human readable declarations).  Cypher language has been also inspired by couple of different approaches (SQL, SPARQL for expressions and also some semantic details from other languages) as is visible from the updated demo (GiTHub miko-spring-birt)


BSN - Neo4jDB initial state
pic.1.:: initial state of Neo4jDB Cars are located in their Garages

By using Cypher language over native Neo4j interface (http://localhost:7474) written in AngularJS we can employ Cypher abilities to get specific NCar located in NGarage (pic.1.)
Let's find the 'Ford' node with its NGarage
CYPHER $: MATCH MATCH (ncar:NCar {make: 'Ford'})<-[:located]-(garage: NGarage {name:'GarageOne'}) return ncar, garage
Using defined command query we should get the following result (pic.2.)
pic.2.::NCar Ford is located in the GarageOne
We can also check which cars are located in the NGarege {name: 'GarageOne') by doing small changes into the Cypher query:
CYPHER $: MATCH MATCH (ncar:NCar {coreName: 'CAR'})<-[:located]-(garage: NGarage {name:'GarageOne'}) return ncar, garage
At the end we should get expected result (pic.3.):
pic.3.:: GarageOne has some cars
Now is good time to move to the next step. 

Let's merge Cypher abilities with Spring-Data-Neo4j GraphRepository interface implementation. Maybe it can be useful to make small comparison with Spring-Data-JPA project to see tiny differences between passing @Param into the @Query (service.3.)

To see how everything works we will create following simple services: 

1. service will find and return the Car made by Ford by using @Query annotation in repository service. We define 
public interface NeoCarService {
NCar findByMakeFord();
method which calls repository implemented service
@Query("MATCH (ncar:NCar) WHERE ncar.make = 'Ford' return ncar")
NCar findByMakeFord();
2. service is almost similar but the difference is new condition. It will return the car made by 'Ford' only if the car is located in the garage and return.  In this case we extend our service 1. by adding also reference to the car garage : 
public interface NeoCarService {
  ...
  NCar findByMakeFord();
  NCar findByMakeForWithGarage();
  ...
the service implementation
...
@Override
public NCar findByMakeForWithGarage() {
  NCar car = nCarEntityRepository.findByMakeFordWithGarage();
  car.setGarage(nGarageEntityRepository.findOne(car.getGarage().getId()));
  return car;
}
...
now do update to the related repository
public interface NCarEntityRepository extends GraphRepository<NCar> {
...
@Query("MATCH (ncar:NCar {make:'Ford'})<-[:located]-(garage) return ncar")
NCar findByMakeFordWithGarage();
...   
3. service will return the number of located cars in the chosen Garage by name. To do so is necessary to define new method provided by NeoGarageService
public interface NeoGarageService {
  ...
  int getCarNumberByName(String garageName);
  ...
and we can call over the repository directly Cypher query:
public interface NGarageEntityRepository extends GraphRepository<NGarage> {
  ...
  @Query("MATCH (g:NGarage)-->(nCar: NCar)-->(g_of_nCar) WHERE g.name = {name} RETURN count(g_of_nCar)")
  int getCarNumberByName(@Param("name") String name);
  ...
 
When you try Cypher query over Neo4j AngularJS interface you should see the following result (pic.4.)


pic.4.:: In the GarageOne are located following number of cars

Here is visible the tiny difference between passing @Param int the query in case of JPA CrudRepository
@Query("select c from Car c where u.make in :names")
Iterable<Car> findByNames(@Param("names")Set<String> makeList);
At the end of the story we create simple BIRT report by creating simple Report Design File (SampleNeCarGarage.rptdesing) and new link to the hellp.jsp to the BirtController.
The final result looks pretty cool, we know which model of Ford we do have. Additionally we know his location and Total number of Cars located at the same Garage (pic.5.). 

pic.5.:: Cypher in Action and giving us information where the Ford is and how many cars are located in the GarageOne => 3 (pic.3.)
Conclusion: 
Enjoy and have a fun with BIRT, Neo4j and Spring 

Thursday, May 29, 2014

BIRT , Spring framework and Neo4j (BSN)

Eclipse Business Intelligence and Reporting Tool simply BIRT is an open-source technology platform used to create data visualisation and cool reports that could be embedded into rich client and web application. Let’s make on step forward…

…The Spring Framework re-invented enterprise Java in the last decade, becoming the dominant programming model in Enterprise Java. Spring version 4 keeps it at the cutting edge of modern Java development and it works nicely with Java 8 and many other languages (Groovy, Scala …).
Let’s stay with Java 8 in this blog post and move forward …

Neo4j is the World leading graph database. The Graph databases are substantially different then RDBMS systems. Neo4j DB consists from the root node, child nodes, relationships, indexes , labels and properties. Probably the easiest way how to play and having a fun with Neo4j in JavaEE environment is to use spring-data-neo4j which enables POJOs based development. You get also access to Cypher Query langue… final move to the beginning  … 

GiTHub demo app : miko-spring-birt

@Query("MATCH (ncar:NCar) WHERE ncar.make = 'Ford' return ncar")
NCar findByMakeFord();
This blog post has been created as the side product of the BIRT integration into much bigger spring-ecosystem. In purposes of blog post I wanted to connect the example application with one of my favourite Graph Databases. Yeap, we are talking about Neo4j. The next reason was to test spring-data-neo4j project in case of operation up to the nodes. 

When you search internet for while you will maybe find couple of demos BIRT, Spring integration. Those demos are mostly out dated and no maven based. In purposes the my demo app I’ve taken official one done by Jason Weathersby and Josh Long. They have done great job! 
I’ve fully copied their *.rptdesign files which made whole demo much easier to prepare. 

You can go through theirs blog post HERE and get more information around as I’ve not touch BIRT, Spring Remote possibility  but it’s not hard to extend my demo app.

So what we do have in this demo: 

  • Integrating BIRT engines in Spring MVC
  • Accessing Spring Beans from the BIRT Viewer 
  • Creating simple BIRT, Spring and Neo4j eco-system.

and which versions we do use: 
Spring 4.0.2.RELEASE
Spring-Data-Neo4j 3.1.0.RELEASE
BIRT 4.3.1

Other technologies:
neo-community-server 2.0.0 and 2.0.3 
Tomcat 6.0.39
JBoss WildFly 8.1
Maven 3.2.1
JRebel 5.5.3
IntelliJ IDEA 13.1.2

The most important step is to share Spring ApplicationContext correctly. There are couple of ways how to achieve it. In our demo I have created Spring Controller bean BirtController that implements ApplicationContextAware.

@Controller
@RequestMapping("/reports")
public class BirtController implements ApplicationContextAware {

Over the spring beans instantiation process there is look up over couple of interfaces one of them is  ApplicationContextAware. This interface defines method setApplicationContext(ApplicationContext ctx) which we do use to catch  ApplicationContext  context and share it with BirtEngineFactory. 


public class BirtEngineFactory implements FactoryBean<IReportEngine>, ApplicationContextAware, DisposableBean { 

The class BirtEngineFactory has been created in purpose of BIRT Engine start up, proper shutdown. This class can used by other beans to get instance of the BIRT Engine. 

Let's jump to the another cool part. Neo4j Graph DB model. Here is Idea behind pretty simple. Sometime is everything about Cars. In our demo every Car needs to be in its Garage. 

in the package : com.miko.demo.birt.model.*

  • class Car represent face object provided by fake carService. This service is used by clicking on link 2. BIRT Report with FakeSpringService 
  • class NCar represents @NodeEntity with properties 
  • class NGarage represents @NodeEntity with properties and relation

  • NCar and NGarage are in relation. 
After deploying the demo app to the application server Tomcat or JBoss WildFly. You can test available options and see the appropriate result. 


Demo APP
pic. 1.: Deployed Demo app


I’ve created also couple of necessary JUnit tests in purpose to test correctness of app functionality. (TEST -> package: com.miko.demo.birt.repository.*). 
Before you run any test you should have your local Neo4j instance started and listening on http://localhost:7474

Conclusion
The demo provides guidelines how to integrate BIRT with Spring 4 eco-system based on MAVEN. Another great point is that the demo app provides the guide line how to use Neo4j to modelling Nodes, their relationships and display the result by using BIRT engine with Spring Beans. 

Some comment
pic. 2.: Correct relationships between Nodes
During demo app tests on different  neo-community-servers , I’ve discovered some “features”. The Feature One disallows to create expected relation between nodes (pic.2.) . The relationship then looks like one NGarage node contains all NCar nodes (pic.3.) which is completely incorrect.


pic.3.: Incorrect relationships between nodes


After having a discussion about Feature One with Neo4j team I decided next day to change my laptop (Laptop 1) and reproduce it again. On Laptop 1 I was able reproduce this Node Relation issue by simply switching between tested Neo4j servers. But on the Laptop 2 I was not able to reproduce it, this was big  surprise after so many successful reproduction tests. I left idea that Spring-Data-Neo4j contains bug/issue behind and focused my investigation on Java related problem (simply I took a look at my code ),  concretely Iterator Interface and its implementation. I don't want to go to the details maybe I'll come back to this topic latter but this is the result . 


public class NeoCarInGarageTest implements NGarageConsts {
...
//Iterrator Issue. Iterator over Collection has not been updated
NGarage tmpGarageOne = garages.iterator().next();
NGarage tmpGarageTwo = garages.iterator().next();
...

and here we have Iterator over Collection without losing updated references
public class NeoCarInGarageTest implements NGarageConsts {
...
//Correctly assigned
Iterator nGarageIterator = garages.iterator();
NGarage tmpGarageOne = nGarageIterator.next();
NGarage tmpGarageTwo = nGarageIterator.next();
...

Feature One is easy to fix. 

Let's move to the Feature Two which is probably the issue of spring-data-neo4j and fully reproducible on any of tested servers (pic.4.). The feature two is visible from the last line where NGarage has lost its name (name = null). This result is not according to the result from previous line (which looks correctly) but this line is done over the Id reference which I don't think is correct. 
@Service("neoCarService")
public class NeoCarServiceImpl
...
result.setGarage(nGarageEntityRepository.findOne(nCar.getGarage().getId()).getName());
...
pic. 4.: BIRT with Spring Beans And Neo4j

 
Final statement
I will keep you updated about the feature two, Enjoy and have a fun with BIRT, Spring and Neo4j :)