Pages

Showing posts with label log4j. Show all posts
Showing posts with label log4j. Show all posts

Tuesday, August 19, 2014

Spring 4 Scala MVC without Web.XML - Tiles3 : WebConfig class configuration with Localisation


Img.1.:: Spring 4 Scala project structure with Tiles 3 and l18n(l10n) 
  Enabling Apache Tiles3 needs little more changes in the project (Img.1.) configuration. The WebConfig scala class needs to extended by WebMvcConfigurerAdapter (already touched in the previous post: Scala Spring 4 MVC without Web.XML configuration with static resources handling). 
  We also define the set of annotations we do need to be scanned over the project package. The reason of such definition is to show possibilities of Scala configuration of the Spring Framework itself.
@Configuration
@ComponentScan(basePackages = Array("miko.scala.helloexample"), useDefaultFilters = false, includeFilters = Array(
  new ComponentScan.Filter(`type` = FilterType.ANNOTATION,
    value = Array(classOf[Controller], classOf[Service]))))
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter{
...
  In WebConfig we do replace @Bean setupViewResolver(), which implements the ViewResolver interface that allows directly resolved symbolic view names,  by getTilesConfigurer @Bean, which provide TilesConfigurer
  The TilesConfigurer class provide the tempting mechanism for web project (application) using JSP and other front-end engines. 
@Bean
def getTilesConfigurer: TilesConfigurer = {
  val configurer:TilesConfigurer = new TilesConfigurer()
  configurer.setCheckRefresh(true)
  configurer.setDefinitions({"/WEB-INF/pages/tiles.xml"})
  configurer
}
 And additionally we have  to define ViewResolver for Tiles by getTilesViewResolver @Bean definition
@Bean
def getTilesViewResolver: ViewResolver = {
  val resolver:TilesViewResolver = new TilesViewResolver()
  resolver.setContentType("text/html")
  resolver
}
The full configuration needs to define and override also couple of other Beans connected with our localisation (l10n/l18n) intent. The final WebConfig Scala class will look in following manner. 
@Configuration
@ComponentScan(basePackages = Array("miko.scala.helloexample"), useDefaultFilters = false, includeFilters = Array(
  new ComponentScan.Filter(`type` = FilterType.ANNOTATION,
    value = Array(classOf[Controller], classOf[Service]))))
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter{

  private val logger = LoggerFactory.getLogger(getClass)

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

  override def addViewControllers(registry: ViewControllerRegistry): Unit ={
    registry.addViewController("/")
  }

  @Bean
  def getTilesViewResolver: ViewResolver = {
    val resolver:TilesViewResolver = new TilesViewResolver()
    resolver.setContentType("text/html")
    resolver
  }

  @Bean
  def getTilesConfigurer: TilesConfigurer = {
    val configurer:TilesConfigurer = new TilesConfigurer()
    configurer.setCheckRefresh(true)
    configurer.setDefinitions({"/WEB-INF/pages/tiles.xml"})
    configurer
  }

  override def addInterceptors(registry:InterceptorRegistry) = {
    val localeChangeInterceptor = new LocaleChangeInterceptor()
    localeChangeInterceptor.setParamName("lang")
    registry.addInterceptor(localeChangeInterceptor)
  }

  /**
   * equivalents for  tags
   * @param registry
   */
  override def addResourceHandlers(registry: ResourceHandlerRegistry) = {
    logger.debug("Resources HANDLER")
    registry.addResourceHandler("/app/**").addResourceLocations("/app/").setCachePeriod(31550522)
    registry.addResourceHandler("/WEB-INF/layouts/**").addResourceLocations("/WEB-INF/layouts/").setCachePeriod(31550522);
    registry.addResourceHandler("/WEB-INF/pages/template/**").addResourceLocations("/WEB-INF/pages/template/").setCachePeriod(31550522);
  }

  @Bean(name = Array("localeResolver"))
  def getLocaleResolver: LocaleResolver = {
    val cookieLocaleResolver: CookieLocaleResolver = new CookieLocaleResolver()
    cookieLocaleResolver.setDefaultLocale(new Locale("en"))
    cookieLocaleResolver
  }

  override def configureContentNegotiation(configurer: ContentNegotiationConfigurer) = {
    configurer.favorPathExtension(true).ignoreAcceptHeader(true)
        .useJaf(false).defaultContentType(MediaType.TEXT_HTML)
        .mediaType("html", MediaType.TEXT_HTML)
        .mediaType("xml", MediaType.APPLICATION_XML)
        .mediaType("json", MediaType.APPLICATION_JSON)
  }

  @Bean(name = Array("messageSource"))
  def getMessageSource: MessageSource = {
    val msgSrc:ReloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource()
    msgSrc.setBasename("classpath:/messages/message")
    msgSrc
  }
}
  After having enabled Tiles with l10n/l18n on the back-end side we can move to front-end and tell Tiles which kind of template it should use to display pages correctly to the user (Img.1. ~ project structure). Of course, with CSS or possible JavaScript libraries. 
But I'll do this in next blog post. 
  Now Enjoy configuring your WebConfig scala class. 

project: miko-spring-scala on github

Saturday, August 9, 2014

update: Scala Spring 4 MVC without Web.XML - logging with Log4j and SLF4j

  This is small update to the previous blogpost (Scala Spring 4 MVC without Web.XML). It shows how to add commonly used Java libraries into the Spring scala project. 
In this example is log4j 1.x used but any change can be easily done when you clone my git hub project. Basically this post shows how to add commonly used libraries into any scala project.

  Let's import last version of Simple Logging Facede 4 Java (SLF4J) and not thin Scala (SLF4S) wrapper to it which is written by Heiko Seeberger.

  We do whole example update in several steps:
1. we need to update our build.sbt file and import appropriate library dependencies
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.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.eclipse.jetty" % "jetty-webapp" % "9.1.0.v20131115" % "container, compile",
  "org.eclipse.jetty" % "jetty-jsp" % "9.1.0.v20131115" % "container"
)

2. in the resources folder we configure log4j logger and some properties (Img.1.). Example configuration is done for Tomcat server.
Img.1.:: Spring 4 Scala project structure with logging configuration
 3. org.slf4j.LoggerFactory is now available for import into HelloExampleController and to log Controller behaviour.
...
private val logger = LoggerFactory.getLogger(getClass)

@RequestMapping(method =  Array(RequestMethod.GET))
def hello( model: Model) = {
  logger.info("Info Test")
  logger.debug("Debug Test")
  logger.error("Error Test")
...

All code is available over my github for testing. Small hint could be Log4j 2 which promises significant improvements over its predecessor, logback and etc.
Enjoy!


Monday, July 21, 2014

Lego Mindstorm EV3 -> Java8, LeJOS and Gradle with taste of Maven

Img.1. - Let's turn on the LegoBrick again and make remote project based on Gradle
The previous post about Lego MindStorm EV3 has been focused on its installation. I've touched how to install JavaJDK setup Wifi on LegoBrick + small sample "hello world" project.
This blog post is about setting up little more advanced project.

The simple HelloWorldGradle Remote project uses:
The legoBrick, connected to the WiFi, is possible to access remotely without problem using Java Remote Method Invocation, shortly RMI.
RemoteEV3 ev3Brick = new RemoteEV3(EV3BRICK_IP);
ev3Brick.setDefault();
Before we start working on the sample source code we create Gradle project. We can randomly choose the project as HelloWorldGradle. Important is to setup Gradle property file "build.gradle" correctly
apply plugin: 'java'
apply plugin: 'idea'
sourceCompatibility = 1.8
version = '1.0'
repositories {
    mavenCentral()
    mavenLocal()
}
dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'lejos:ev3classes:1.0-SNAPSHOT'
    compile ('log4j:log4j:1.2.17'){
        exclude group: "com.sun.jdmk", module: "jmxtools"
        exclude group: "javax.jms", module: "jms"
        exclude group: "com.sun.jmx", module: "jmxri"
    }
    compile 'org.slf4j:slf4j-log4j12:1.7.5'
}
jar library "ev3classes" is very important!
This library creates the gateway into the lego hardware by using RMI because EV3 acts as the RMI Registry. You need to create it by yourself.
lejos
  ev3classes
  jar
  1.0-SNAPSHOT
  
    
      lejos
      dbusjava
      1.0-SNAPSHOT
    
    
      net.java.dev.jna
      jna
      3.2.7
    
  
  
    ${basedir}/src
    ev3classes
    install
    
      
        maven-compiler-plugin
        ${maven.compiler.version}
        
          ${java.version}
          ${java.version}
        
      
      
        org.apache.maven.plugins
        maven-jar-plugin
        ${maven.jar.version}
      
      
        maven-assembly-plugin
        ${maven.assembly.version}
        
          ${project.build.finalName}-${project.version}.jar
          
            jar-with-dependencies
          
        
        
          
            make-assembly
            package
            
              single
            
          
        
      
    
  
This library can be created by maven with usage of maven-assembly-plugin. The final *.jar file can then easily imported into the local maven cache.
Now we are ready to remotely access our Lego MindStorm robot and in our case let him to play some short song.
RemoteEV3 ev3Brick = new RemoteEV3(EV3BRICK_IP);
            ev3Brick.setDefault();
            Audio soundProcessor = ev3Brick.getAudio();
            List tones = new ArrayList<>(asList(0,1,2,3,4,5));
            tones.forEach(tone -> {
                soundProcessor.systemSound(tone);
            });
The sample LejOS remote project HelloWorldGradle is available here (GITHub).
Enjoy !

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.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).