Pages

Showing posts with label Scala. Show all posts
Showing posts with label Scala. Show all posts

Thursday, September 18, 2014

thoughts: GeeCON 2014 - Prague Edition with Registration Open and 1st Draft of the Schedule

Hi Everyone, 
   it was always my dream to have GeeCON in Czech country although I'm not living there for few years and nor in Poland (never lived there). 
   Being driven by American start-up dream from San-Francisco we have made in 2009 under really hard conditions 1st GeeCON edition . Even more awesome was community behind we've created (so many amazing people sharing the same interest about JavaWorld ).

   It was excited although we've failed in some details, but it is life. We were working really hard to make it real and the result of our big effort was captured by this video. 
  I'm sure, I'm not far away when I write that this video almost perfectly matches whole atmosphere there (be present at this time was much better).

   So back to the REALITY
   I'm proud to announce that we've started, supported by YSoft company, the GeeCON Prague edition
It's really here and real!

here is 1st Schedule Draft  & the Registration Form to make possible being with US in Prague 
  
Enjoy and See you there

Sunday, September 14, 2014

HowTo:: Design patterns with Scala or Java: GoF behavioural pattern Chain of Responsibilities

   
Img.1.: Chain Responsibilities pattern concept

   This pattern is really useful it allows the sender (sends the request) to be decoupled from the receivers. Those receivers are organised into a sequence. 
Inside such sequence every member has a opportunity to process the request or not and forward it to the next one.
  In this blog post I want to compare Java vs. Scala implementations of "Chain of Responsibilities pattern" and its possible implementation (Img.1.).

1. Java 
In following Java implementation is important point  abstract class AbstractHandler1 which has access to the successor property. The successor property provides concrete AbstractHandler1 handler implementation (creates the chain of different handlers).
a) AbstractHandler1:
public abstract  class AbstractHandler1 {
    AbstractHandler1 successor;

    public void setSuccessor(AbstractHandler1 successor){
        this.successor = successor;
    }

    abstract public  void handleRequest(ReqTypeEnum request);
}
Now we create ReqTypeEnum object which is thread-safe and its implementation guarantee that initialisation happens only ones and is immutable. In other hand implementation makes the Java code more readable. 
b) ReqTypeEnum
public enum ReqTypeEnum {
    typeOne(0),
    typeTwo(1),
    typeThree(2);

    private int code;

    private static final Map<Integer, ReqTypeEnum> codeToRequestTypeMapping = new HashMap<Integer, ReqTypeEnum>();
    static{
        for(ReqTypeEnum rt: ReqTypeEnum.values()){
            codeToRequestTypeMapping.put(rt.getCode(), rt);
        }
    }

    private ReqTypeEnum(int c){
        code = c;
    }

    public int getCode(){
        return code;
    }

    public static ReqTypeEnum getRequestType(int code) {
        return codeToRequestTypeMapping.get(code);
    }

}
   After having request handler skeleton (AbstractHandler1defined  and request type (ReqTypeEnum) we can make step forward and create couple of concrete hanlder implementations (example 3):
***************************
public class ConHandler1 extends AbstractHandler1 {
    private static final Logger logger = LoggerFactory.getLogger(ConHandler1.class);
    @Override
    public void handleRequest(ReqTypeEnum request) {
        if(request == ReqTypeEnum.typeOne){
            logger.debug("Concrete Handler 1 = " + request);
        } else {
            logger.debug("Concrete Handler 1 -> Doesn't handle request= " + request);
            if(successor != null){
                successor.handleRequest(request);
            }
        }
    }
}
***************************
public class ConHandler2 extends AbstractHandler1 {

    private static final Logger logger = LoggerFactory.getLogger(ConHandler2.class);

    @Override
    public void handleRequest(ReqTypeEnum request) {
        if(request == ReqTypeEnum.typeTwo){
            logger.debug("Concrete Handler 2 = " + request);
        } else {
            logger.debug("Concrete Handler 2 -> Doesn't handle request= " + request);
            if(successor != null){
                successor.handleRequest(request);
            }
        }
    }
}
***************************
public class ConHandler3 extends AbstractHandler1 {

    private static final Logger logger = LoggerFactory.getLogger(ConHandler3.class);

    @Override
    public void handleRequest(ReqTypeEnum request) {
        if(request == ReqTypeEnum.typeThree){
            logger.debug("Concrete Handler 3 = " + request);
        } else {
            logger.debug("Concrete Handler 3 -> Doesn't handle request= " + request);
            if(successor != null){
                successor.handleRequest(request);
            }
        }
    }
}
and prepare demo setup:
private static AbstractHandler1 setDemoUp(){
   ConHandler1 conHandler1 = new ConHandler1();
   ConHandler2 conHandler2 = new ConHandler2();
   ConHandler3 conHandler3 = new ConHandler3();

   conHandler1.setSuccessor(conHandler2);
   conHandler2.setSuccessor(conHandler3);

   return conHandler1;
}
  Java implementation is ready to launch  
public static void main(String... args){
   ...
   AbstractHandler1 responsibilityChain = setDemoUp();

   responsibilityChain.handleRequest(ReqTypeEnum.typeOne);
   responsibilityChain.handleRequest(ReqTypeEnum.typeTwo);
   responsibilityChain.handleRequest(ReqTypeEnum.typeThree);
   ...
}
  The demo output shows the chain of request handling:
ChainDemo1 - ***Start Chain of Responsibility Demo***
ConHandler1 - Concrete Handler 1 = typeOne
ConHandler1 - Concrete Handler 1 -> Doesn't handle request= typeTwo
ConHandler2 - Concrete Handler 2 = typeTwo
ConHandler1 - Concrete Handler 1 -> Doesn't handle request= typeThree
ConHandler2 - Concrete Handler 2 -> Doesn't handle request= typeThree
ConHandler3 - Concrete Handler 3 = typeThree


2.Scala
  As Java is up, let's move to the Scala possible implementation. This implementation should allow runtime configuration of registered handlers in the chain. Each handler is implemented as Scala object:
object ConHandler1 extends ChainHandler[String]{
  private val name: String = "Concrete Handler One"
  private val logger = LoggerFactory.getLogger(getClass)
  def accept(obj: String) = obj equals name
  def handle(obj: String) = logger.debug("SERVUS " + name)
}
***************************
object ConHandler2 extends ChainHandler[String]{
  private val name: String = "Concrete Handler Two"
  private val logger = LoggerFactory.getLogger(getClass)
  def accept(obj: String) = obj equals name
  def handle(obj: String) = logger.debug("HALLO " + name)
} 
  The ChainHandler is implemented as the generic trait and indicates that every concrete handler implementation, inside the chain, is able to decide whether is able to handle the request.
trait ChainHandler[T] {
  def accept(obj: T): Boolean
  def handle(obj: T): Unit
}
Each request is passed as the parameter which concrete handler uses for processing.
  The process of the requests chain is controlled by ChainManager Scala class. ChainManager groups all assigned concrete handlers and put them into the ListBuffer (chain). 
case class ChainManager[T](n: String) {
  private val logger = LoggerFactory.getLogger(getClass)
  val name: String = n
  private val chain = new ListBuffer[ChainHandler[T]]
  def add(h: ChainHandler[T]) = {
    chain += h
    ChainManager.this
  }
  def apply(obj: T) = {
    val handler = Option(chain.filter(n => n accept obj) head)
    handler match {
      case Some(chainElement) => chainElement handle obj
      case None => logger.error("no handler")
    }
  }
}
As the add() handler methods returns references to the ChainManager itself. It allows linking add() method to simplify the construction.  
controller.add(ConHandler1).add(ConHandler2)
Now we have all elements to run the sample program: 
object ChainOfRespManagerTest {
  private val logger = LoggerFactory.getLogger(getClass)
  def main(args: Array[String]): Unit = {
    val controller = ChainManager[String]("Manager Approach")
    logger.debug("---Chain of Responsibility: "+ controller.name +"---")
    controller.add(ConHandler1).add(ConHandler2)
    controller apply "Concrete Handler One"
    controller apply "Concrete Handler Two"
  }
}
and observe the out put of it:
ChainOfRespManagerTest$ - ---Chain of Responsibility: Manager Approach---
ConHandler1$ - SERVUS Concrete Handler One
ConHandler2$ - HALLO Concrete Handler Two
  

  Conclusion: Although java is cool language such implementation shows necessity to write not only little more code to achieve the similar result but also the solution is not, in some parts, generics enough. 
   The Scala solution illustrates how the invocation of the chain behaviour can be made to look like the part of the language product.   
Enjoy ! 

Sunday, September 7, 2014

HowTo:: Design patterns with Scala: GoF Structural Pattern Adapter and power of Trait

  
Img.1.:: Parts of Adapter patterns

   In this example I want to show power of trait usage in 2 different ways of Adapter Structural pattern implementations. There are couple of reasons why could be worth to think about the Adapter pattern. Basically the intent is to convert interface of the one type into the interface that client expects to use.
Pattern can be divided into the following parts (Img.1.):
1. Client - is an object that requires functionality provided by Adaptee but it's exposed by Adapter
2. Adapter - is an object that converts the interface expected by the client into the interface provided by Adaptee 
3. Adaptee - is an object that provides the implementation and the interface invoked by the Adapter

in both Adapter examples we do use same Client implementation: 
class Client(service: Service) {
  def doWork = {
    service.invoke
  }
}
and Service trait which defines method process:
trait Service {
  def process(): Unit
}
  Already from the Main Scala Object AdapterTest.scala is noticeable the 1st warm up of the Scala trait power which will be fully exposed by AdaptorTrait latter.
object AdapterTest {

  private val logger = LoggerFactory.getLogger(getClass)

  def main(args: Array[String]) ={
    logger.debug("Test Adapter pattern")
    val adaptor = new AdaptorOne
    val clientWithoutTrait = new Client(adaptor)
    clientWithoutTrait.doWork()

    val adaptorTraitOne = new AdapteeOne with AdaptorTrait
    val adaptorTraitTwo = new AdapteeTwo with AdaptorTrait
    val clientWithTrait1 = new Client(adaptorTraitOne)
    clientWithTrait1.doWork()

    val clientWithTrait2 = new Client(adaptorTraitTwo)
    clientWithTrait2.doWork()
  }

}

1. Object based implementation without trait we do use classical scala class definition of the AdapteeOne that provides implementation to the action() that Client wants.
class AdapteeOne extends Adaptee{
  private val logger = LoggerFactory.getLogger(getClass)
  def action() = { logger.debug("Adaptee One Action One")}
}
  The Adapee trait is used to make code standardised and also to point out limits of the presented Object implementation .
trait Adaptee {
  def action()
}
  Currently has been implemented 1st part of the blog post -> Adapter in the classical object way.

2. trait based approach is inspired by having two, almost same, objects (example: CAR1, CAR2) and both has different implementation of the action() function (example: both cars can ride). We again use AdapteeOne (previously implemented) and we create AdapteeTwo scala class.
class AdapteeTwo extends Adaptee{
  private val logger = LoggerFactory.getLogger(getClass)
  def action() = { logger.debug("Adaptee Two Action")}
}
   Both classes extend Adaptee trait which method is served to the AdaptorTrait that extend the Service (also previously defined)
trait AdaptorTrait extends Service{
  self: Adaptee =>
  def process() = action()
}
   Now we are ready also with 2nd Adapter pattern example usage. Trait usage (AdaptorTrait) allows to be mixed into a type either directly at the type declaration time or an object creation time.  This simply allows latter object behaviour extension. 
Traits go ahead! implementation with them is much easier, readable and extendable  + testable, less code

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 : 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

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

Thursday, August 14, 2014

Multithreading with Scala and Akka-Actor : PingPong game example

  This small blog post is not only for those who have read/reading cool Scala Cookbook and more specifically chapter about how to use Akka toolkit. Akka with Actors helps to build up highly concurrent, distributed and fault tolerant event-driven application ("we are reactive") on the JVM.

 I'll little modify example which comes from the Scala Cookbook and make new SBT based project out of it to show multi-threading outcome. The build.sbt file:
name := "miko-scala-akka"
version := "1.0"
libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor" % "2.4-SNAPSHOT",
  "com.typesafe.akka" %% "akka-testkit" % "2.4-SNAPSHOT",
  "org.slf4j" % "jcl-over-slf4j" % "1.7.7" ,
  "org.slf4j" % "slf4j-api" % "1.7.7" ,
  "org.slf4j" % "slf4j-log4j12" % "1.7.7",
  "org.apache.logging.log4j" % "log4j" % "2.0" excludeAll(
      ExclusionRule(organization = "com.sun.jdmk"),
      ExclusionRule(organization = "com.sun.jmx"),
      ExclusionRule(organization = "javax.jms")
      ),
  "org.scalatest" % "scalatest_2.11" % "2.2.1" % "test",
  "junit" % "junit" % "4.11" % "test"
)
resolvers += "Akka Snapshot Repository" at "http://repo.akka.io/snapshots/"
  Every Actor from Akka toolkit should send immutable messages (note: we will check it). For such purpose is used binary operator "!" after which the message is passed as an argument.
Ping Actor:
class Pong extends Actor{
  val name: String = "pongActor"
  def receive = {
    case PingMessage =>
      println(" pong")
      sender ! PongMessage
    case StopMessage =>
      println(" pong stopped")
      context.stop(self)
  }
}
Pong Actor:
class Pong extends Actor{
  def receive = {
    case PingMessage =>
      println(" pong")
      sender ! PongMessage
    case StopMessage =>
      println(" pong stopped")
      context.stop(self)
  }
}
our Ping and Pong actors are defined but used messages not. We create 4 case object (case object can be serialized, pattern matching support, default implementation of equals and hashCode ...
case object PingMessage {
  println("This is PingMessage")
}
case object PongMessage {
  println("This is PongMessage")
}
case object StartMessage {
  println("This is StartMessage")
}
case object StopMessage {
  println("This is StopMessage")
}
  Now we have everything ready to create final object PingPongTest:
object PingPongTest{
  private val logger = LoggerFactory.getLogger(getClass)
  def main(args: Array[String]): Unit = {
    logger.debug("---PingPong Game Start---")
    val system = ActorSystem("PingPongSystem")
    val pong = system.actorOf(Props[Pong], name = "pong")
    val ping = system.actorOf(Props(new Ping(pong)), name = "ping")

    // Start the game
    ping ! StartMessage
    logger.debug("---PingPong Game Stop---")
    system.shutdown()
  }
}
  The main purpose of updating the PingPong game is to show how Reactive Application (multi-threading) works . The Simple Logging Facade (SLF4j) Logger is used here to hightlight the simple reactive application flow.
DEBUG: miko.scala.akka.pingpong.PingPongTest$ - ---PingPong Game App Start---
This is StartMessage
DEBUG: miko.scala.akka.pingpong.PingPongTest$ - ---PingPong Game App End---
ping
This is PingMessage
 pong
This is PongMessage
ping
 pong
ping
 pong
ping
 pong
ping
 pong
ping
 pong
ping
 pong
ping
This is StopMessage
ping stopped
 pong stopped
  From the file output is visible how exciting multi-threading environment is. The event-driven distributed system design could more fit to the nature reality of the world around us. 
Enjoy with GiTHub example

Design Patterns with Scala: GoF Creational Pattern - Factory Operation (GoF: Factory)

  Factory operation design pattern provides the way how to construct object of the specific type. The intent is to hide an object instantiation from a client which support flexibility in such instantiation process (decide which class will be instantiated).
  Let's show over the simple example how such Factory method deals with the issue of the different type of object creation

  UnivProduct trait is the abstract super type of objects which will be produced by object ProductFactory.
trait UnivProduct {
  val name: String
  val value: Any
}
  By having defined abstraction UnivProduct we can create two concrete classes which can be instantiated by object ProductFactory latter.
UnivProductOne:
case class UnivProductOne(i: Int) extends UnivProduct{
  val name:String = "MyIntegerProduct"
  val value:Int = i

  override def toString = "name= "+ name +" val= " + value
}
  UnivProductTwo:
case class UnivProductTwo(s: String) extends UnivProduct {
  val name:String = "MyStringProduct"
  val value:String = s

  override def toString = "name= "+ name +" val= " + value
}
  Now we create FactoryOperation trait which provides us the specification of the methods (behaviour) that ProductFactory object must provide.
trait FactoryOperation {
  def create(a: Any): UnivProduct
}
  Then we define ProductFactory object in following way:
object ProductFactory extends FactoryOperation{
  implicit def create(a: Any): UnivProduct = a match {
    case s: String => UnivProductTwo(s)
    case i: Int => UnivProductOne(i)
  }
}
which simplifies the access to the Factory with limiting ability to employ different Product Factories (can by fixed by implementing factory of factories). The methods create in ProductFactory object is marked as implicit (inserted by compiler).
  At the end we create the singleton Scala object FactoryTest to put all together and see the result.
object FactoryTest {
  private val logger = LoggerFactory.getLogger(getClass)

  def main(args: Array[String]): Unit = {
    val productA: UnivProduct = ProductFactory.create("Mirage")
    logger.debug("ProductA name= " + productA.name + " value= " + productA.value)
    logger.debug("ProductA toString= " + productA)

    val productB:UnivProduct = ProductFactory.create(22)
    logger.debug("ProductB name= " + productB.name + " value= " + productB.value)
    logger.debug("ProductB toString= " + productB)

    val productC: UnivProduct = "Tanja"
    logger.debug("ProductC name= " + productC.name + " value= " + productC.value)
    logger.debug("ProductC toString= " + productC)

    val productD: UnivProduct = 5
    logger.debug("ProductD name= " + productD.name + " value= " + productD.value)
    logger.debug("ProductD toString= " + productD)
  }
}

expected output:
ProductA name= MyStringProduct value= Mirage
ProductA toString= name= MyStringProduct val= Mirage
ProductB name= MyIntegerProduct value= 22
ProductB toString= name= MyIntegerProduct val= 22
ProductC name= MyStringProduct value= Tanja
ProductC toString= name= MyStringProduct val= Tanja
ProductD name= MyIntegerProduct value= 5
ProductD toString= name= MyIntegerProduct val= 5
  Enjoy using Factory Operation Design patter and my GiTHub is still in progress as I want to much more to share.

Tuesday, August 12, 2014

Design Patterns with Scala: Fundamental Pattern - Marker Trait

The Marker Trait pattern is the fundamental pattern in Scala. The main point is in using trait which are free on any declaration (method, function etc.) to indicated additional type logical semantic within the domain. The Marker Trait pattern adds ability to be treated as part of Scala type system. For example such approach is used in scala.Mutable or scala.Immutable traits to distinguish between them to indicate the semantic.

In the example we define trait MarkerTrait which will be mixed into any other classes
trait MarkerTrait {
}
Then we define two example classes with some methods.
ClassOne:
case class ClassOne(id: String) extends MarkerTrait{
  def name: String = "ClassOne ID= " + id
}
and ClassTwo:
case class ClassTwo(value: String) extends MarkerTrait{
  def name: String = "ClassTwo value= " + value
}

After having defined classes we define the universal printer UnivPrinter object (note: is singleton) with methods print where MarkerTrait can be passed and printed out.
object UnivPrinter {
  private val logger = LoggerFactory.getLogger(getClass)
  def print(o: MarkerTrait) = {
    logger.debug("MarkerTrait " + o)
  }
}
As the last step we can define object MarkerTest with main method. Inside the main method we instantiate our two classes (ClassOne, ClassTwo) and pass them to the UnivPrinter.print method
object MarkerTest {
  private val logger = LoggerFactory.getLogger(getClass)
  def main(args: Array[String]): Unit = {
    logger.debug("Marker Trait Fundamental Pattern")
    UnivPrinter.print(new ClassOne("ID"))
    UnivPrinter.print(new ClassTwo("Value"))
  }
}
As the alternative connection to the Java world can be taken Annotation. The Annotation is not part of the Scala type system. The trait itself is much powerful in Scala then interfaces in Java as trait can define additional behaviour. This trait power can cause some implementation mixing issues.


Design Patterns with Scala: Creational Pattern - Singleton

  The singleton design pattern is probably most known one from GoF Creational Pattern list. The singleton pattern says that only one instance of the specific class will be ever created per ClassLoader. 
ps: "This is little bit different in Spring Framework. The Spring Singleton is unique per Spring IoC container per bean which means single instance per Spring context. It also means it's not the singleton pattern" (note) 

  In Java is quite easy to create Singleton pattern and as the whole world is Multi-Threading I'd recommend to reflect this fact and use any of thread-safe implementation double-check-locking or volatile keyword (value is taken then from the main memory and follows happens-before relationship on visibility of among multiple threads). 
The initialisation process is necessary only when the instance is created (by calling getInstance() method). 

In Scala is situation less complicated because in Scala there are no static members (ps: static members concept in Java goes a bit against the OOP principle where everything is an object). Scala has singleton objects done by usage of keyword object
object Singleton {
  val id = "singleton"
  override def toString = "this is the Singleton object"
}
The example shows how easy it is to achieve the singleton pattern is in Scala.
More patterns are on the way and they will be soon on my github soon.

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!


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)

Thursday, May 29, 2014

bright future ... alias ... future posts

Whole life is one big studY
pic.1.: student for ever ~ we are all students
I was not active in blogging for last few years (pic.1.), I've been almost completely overloaded by work and focused on project to kick them out or make them just work. Some of them were mine and the rest for companies (pic.2.). 


connect dots together and move things forward
pic.2.: retrospective at GeeCON : connecting dot's together and moving forward
Overall big part of my heart belongs to cutting-edge technologies ... just like small child (never stop discovering bright future) (pic.2.). I've spent big portion of my time by studying Machine Learning possibilities because behind all this will be always clear math. (algebra, probability, statistics ... just fun and getting better in various predictions)(pic.3.)

pic.3.: One day the result of our investigations -> it just works (maybe)
This area is in one hand pretty awesome because it connects many branches together, not  just only math. world but also langues or any other technologies, concepts or methodologies (servers, databases , big data, map reduce etc.)

RaspberryPI traveler package
pic.4.: one of RaspberryPI traveler packages

This blog I would like to focuse on small powerful systems (RaspberryPi, CuBox ...), spring projects, redhat projects (Netty, Vert.x, WildFly, Infinispan etc.) , JetBrains (IntelliJ IDEA, etc.), ZeroTurnaround technologies (JRebel, etc.), GraphDatabases ( Neo4j, etc.), Languages (Java, Scala, Groovy, Ruby, Python etc.)  and many other opensource technologies like JavaFx or NetBeans....(MineCraft) ps: List is too Long (StackOverflow ;)  

Another intent of this blog is to create utilized collection of links I may need currently or in near future with demo apps.

And at the and of course to share some cool news from the Java Virtual Machine World
 (GeeCON: Let's move the Java World!)