Friday, December 13, 2013

Internationalization Spring MVC with Java Config

I will post parts of code from an application to show how to integrate this feature using the new current in Spring: Java Configurations. Sometimes it can be a challenge to update your old xml config to this pretty new config type.



1. Create in WEB-INF folder a new folder messages and add to this folder some files with a base name and suffix(without suffix is the default file).

2. Add to these files, key-value records like:

                 facebook.displayName=English Facebook -> messages.properties
                 facebook.displayName=China Facebook   -> messages_zh_CN.properties

    *You can also add other suffixes like fr for French

3. Now, i think it's time for some Java Config:)


@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
 
 @Bean 
 public LocaleChangeInterceptor localeChangeInterceptor(){
     LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
     localeChangeInterceptor.setParamName("language");
     return localeChangeInterceptor;
 }

 @Bean(name = "localeResolver")
 public LocaleResolver sessionLocaleResolver(){
     SessionLocaleResolver localeResolver=new SessionLocaleResolver();
     localeResolver.setDefaultLocale(new Locale("en"));
     
     return localeResolver;
 }  
 
 public void addInterceptors(InterceptorRegistry registry) {
     registry.addInterceptor(localeChangeInterceptor());
 }
 
    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages/messages");
        return messageSource;
    }
    
    
   //...
}

* Note that "SessionLocalResolver" has a name. I don't know why, but declaring this without a name caused me some problems

* "language" will be the parameter that will have to be in request url for getting values from a different file

       **language=fr will load values from messages_fr

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"

      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

    <head>

        <title>Spring Security Example </title>

    </head>

    <body>

 <p th:text="#{facebook.displayName}">Welcome to our grocery store!</p>

</body>

</html>
Because we have only two files, we have only 2 choises:

*call without paramater will result:


*call with ?language=zh_CN:



I think the most important part and unknown part is Java Config, others are the same as in older spring versions. This kind of implementation is also a beginning for adding other custom interceptors. You can implement HandlerInterceptor  and create a bean that will return an instance, than register that bean in addInterceptors method and will work. Before we did this between <mvc:interceptors> tags in xml configs. I can't say which alternative is the best, both are great because we talk about Spring:D OOP, Java, groovy, java frameworks, java language, Spring, internationaliztion, Java Config, Spring 3, Spring Java Config

Friday, September 20, 2013

Producer -- Consumer in Groovy

Last days, I've got a feeling that is time to learn some new in programming languages domain and I started to work with Groovy and even if it has problems with encapsulation, I liked a lot the idea. You can write a very light and clean code if you are not trying to create a strange combination between Java and Groovy. Another great thing related to Groovy is that Grails is based on Groovy, and Grails is really awesome.

So, let's start with a very basic example of multi-threading...a producer consumer implementation in Groovy in a classical way, with threads and synchronized blocks of code

**Producer class

class Producer {
 def name
 def products=[]
 private def Object lock;

 def Producer(name,products) {
  this.name = name;
  this.products=products
 }
 
 def produce()
 {
  def i=0
  synchronized (this.lock) {
   
   println this.name + " starting to produce"
   
   while(true)
   { 
    if (this.products.size()==2)
    {
     println this.name+" full stock, so wait"
     
     this.lock.notify()
     this.lock.wait()
     
     println this.products.size()+" more integers please"
    }
    else
    {
     i++
     this.products.add("product "+i)
    }
    
   }
  }
 }
}


**Consumer class

class Consumer {
 def name
 def products=[]
 def Object lock;

 def Consumer(name,products) {
  this.name = name;
  this.products=products
 }
 
 def consume()
 {
  synchronized (this.lock) {
   println ""
   println this.name + " starting to consume"
   while(true)
   {  
    sleep(2000)
    if (this.products.size()>0)
    {
     def index=this.products.size()-1
     println this.name+" consume "+this.products[index]
     this.products.remove(index)
     println "remains "+this.products.size()
    }
    else
    {
     println "is time for more integers"
     this.lock.notify()
     this.lock.wait()
    }
    
   }
  }
 }
}


**And the main program which is the factory, the supermarket or something like this:). Of course for these example I am producing only some integers, not potatoes
class MainApplication {

 static main(args) {
 
  println "Hello world"
  
  def products=[]
  
  def a=new Producer("Producer",products)
  
  def lock=new Object();
  
  def b=new Consumer("Consumer", products)
  
  a.lock=lock
  b.lock=lock
  
  def prodthread=Thread.start {
   a.produce() 
  }
  
  
  def consThread=Thread.start {
   b.consume()
  }
  
 }

}



Note: I'm not setting the lock object within the constructor, because i wanted to show you that private is just a simple word for the moment. This is a problem, but we can live with it right now... OOP, Java, groovy, producer consumer, grails, java frameworks, java language, groovy tutorial

Friday, August 30, 2013

Spring Data, Mongo and Play 2.1

Ok we will go back in this post to Java and the idea for today is to integrate Mongo + Spring Data, with a great framework, called Play(version will be 2.1)

Of course, we talk about Spring, it means we start with some configurations...
Because we are working with play, please forget for a moment about Maven and we have two solutions for adding dependecies
1.Create a lib folder and add every jar you want
                              or
2.Update appDependencies from Project/Build.scala file in a Maven style
GroupArtifactVersion
"org.springframework""spring-core""3.2.2.RELEASE"

import sbt._
import Keys._
import play.Project._

object ApplicationBuild extends Build {

  val appName         = "MongoPlayExample"
  val appVersion      = "1.0-SNAPSHOT"

  val appDependencies = Seq(
    // Add your project dependencies here,
    "org.springframework" % "spring-core" % "3.2.2.RELEASE",
    "org.springframework" % "spring-context" % "3.2.2.RELEASE",
    "org.mongodb" % "mongo-java-driver" % "2.11.0",
    "org.springframework.data" % "spring-data-mongodb" % "1.2.0.RELEASE",
    "cglib" % "cglib" % "2.2.2",
    javaCore,
    javaJdbc,
    javaEbean
  )

  val main = play.Project(appName, appVersion, appDependencies).settings(
    // Add your own project settings here      
  )

}
Now because we don't really like today old Spring xml configurations, we have to create a SpringConfiguration class annotated with @ Configuration and a Global class for accessing ApplicationContext

 **Global.java
public class Global extends GlobalSettings{

    private static ApplicationContext applicationContext;

    @Override
    public void onStart(Application application) {
     System.out.println("on start");
        applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    }
    public static ApplicationContext getContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("application context is not initialized");
        }
        return applicationContext;
    }
}
**SpringConfiguration.java
@Configuration
public class SpringConfiguration {
 
 public @Bean
 MongoDbFactory mongoDbFactory() throws Exception {
  return new SimpleMongoDbFactory(new MongoClient(), "PlayDB");
 }
 
 public @Bean(name="mongoTemplate")
 MongoTemplate mongoTemplate() throws Exception {
 
  MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());

  return mongoTemplate;
 
 }
 
 public @Bean(name="repositoryUser")
 RepositoryUser repositoryUser() throws Exception
 {
  return new RepositoryUserImpl(mongoTemplate());
 }
}
As you can see we use some Spring Data features for connectiong to a Mongo Database and we define the beans in the code not in xml files.

After finishing the configuration part, the next step, is to create an entity(document) and a repository layer to show how to work with spring data mongo operations.

**User class
@Document(collection = "users")
public class User {
 
 @Id
 private String id;
 
 private String username;
 
 private String password;
 
 private String role;

 public User(String username, String password, String role) {
  super();
  this.username = username;
  this.password = password;
  this.role = role;
 }
       /*please implement getters and setters*/


**RepositoryUser interface
public interface RepositoryUser {

 List getAll();
 void save(User user);
 void delete(User user);
 User findById(String id);
}


**RepositoryUserImpl class
public class RepositoryUserImpl implements RepositoryUser {

 private MongoOperations mongoOperations;
 
 public RepositoryUserImpl(MongoOperations mongoOperations)
 {
  this.mongoOperations = mongoOperations;
 }
 @Override
 public List getAll() {
  // TODO Auto-generated method stub
  return mongoOperations.findAll(User.class);
 }

 @Override
 public void save(User user) {
  // TODO Auto-generated method stub
  mongoOperations.save(user);
 }

 @Override
 public void delete(User user) {
  // TODO Auto-generated method stub

 }

 @Override
 public User findById(String id) {
  // TODO Auto-generated method stub
  return null;
 }

}


Using Spring Data with Mongo offers the possibility to work with entities like any other ORM framework for relational databses like Hibernate for example...

** Controller for integrating our beans
public class Application extends Controller {
 
 private RepositoryUser repositoryUser=(RepositoryUser) Global.getContext().getBean("repositoryUser");
    
 public Result index() {
        //return ok(views.html.index.render("Your new application is ready."));
     //this.repositoryUser.save(new User("ionel", "abcd", "user"));
     return ok(this.repositoryUser.getAll().get(0).toString());
    }
  
}


And this is it! I created a short but strong example working with Spring Data, Mongo DB and Play Framework. In the future I hope we will come back to Play because it deserves many articles and a huge space in software development.I think Play can compete in the future with Wicket or Spring without any problems.Good luck! MVC, java, dependency injection, mongo, spring, spring data, play framework, play 2.1, play GlobalSettings

Friday, August 23, 2013

@Ajax.Actionlink ASP MVC

This HTML helper offers the possibility to create ajax requests by writing less code than in a jquery classical way. I spent some time trying to integrate this pretty feature in my application and I want to share with you how tot this very quickly. So, I want to show how set the Http method, the parameters and other options.

 First I will present an action from the previous tutorial(where I used mongo). The action provides details for a book(attributes name and publisher) and is returning a JSON if the book exists, else just simple message.

        [HttpPost]
        public ActionResult Details(string id)
        {
            try
            {
                var book = repBook.findById(id);

                return Json(book);
            }
            catch(Exception e)
            {
                return Content("not found");
            }
        }
Then let's try to create an ajax request in Index view to display some information about a book. Very simple...
@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create")
@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.name) @Html.DisplayNameFor(model => model.publisher)
@Html.DisplayFor(modelItem => item.name) @Html.DisplayFor(modelItem => item.publisher) @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @*@Html.ActionLink("Details", "Details", new { id=item.Id }) |*@ @Html.ActionLink("Delete", "Delete", new { id=item.Id }) @{ var options = new AjaxOptions { UpdateTargetId = item.name, InsertionMode = InsertionMode.Replace, OnSuccess = "success(data," + item.name + ")", OnFailure = "failure()", HttpMethod = "Post" }; } @Ajax.ActionLink("Ajax details","Details",new {id="fdsf"},options)
@section scripts{ }
And that's all! ASP.NET MVC, .Net, MVC, HTML helpers, Ajax, @Ajax.ActionLink, JSON, JsonResult

Thursday, August 22, 2013

ASP.NET and Mongo Databases

In this post I will try to show you how to use MongoDB in your .Net MVC project and how to simplify your life in repositories development, by using MongoRepository NuGet. 

  1. Install NuGet Packages for Mongo usage

Go to Manage NuGet Packages and search mongo, then install Official MongoDB driver and MongoRepository



Before starting to write code, please look in your web.config file and set you database name:
  
    
    
    
  

2. Create some entities...

**Author entity

    public class Author:Entity
    {
        [Required]
        //[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid name")]
        public string name { get; set; }
        public HashSet books { get; set; }

        public Author()
        {
            this.books=new HashSet();
        }

        public override int GetHashCode()
        {
            return this.name.GetHashCode()*2;
        }

        public override bool Equals(object obj)
        {
            if (obj is Author)
            {
                Author a = (Author)obj;
                if (a.Id == this.Id)
                {
                    return true;
                }
            }

            return false;
        }

        public override string ToString()
        {
            return this.Id + " " + this.name;
        }
    }
**Book entity
    public class Book:Entity
    {
        public string name { get; set; }
        public string publisher { get; set; }
        public List authors { get; set; }

        public Book()
        {
            this.authors = new List();
        }

        public override int GetHashCode()
        {
            return this.name.GetHashCode() * 2;
        }

        public override bool Equals(object obj)
        {
            if (obj is Book)
            {
                Book b = (Book)obj;
                if (b.Id == this.Id)
                {
                    return true;
                }
            }

            return false;
        }

        public override string ToString()
        {
            return this.Id + " " + this.name;
        }
    }
1) Note that I created a many-to-many relationship between entities

2) Our entities extends Entity class and we do this because that's how MongoRepository works and this helps for automatically creating ObjectId for every document

3.Repository layer

I'm not gone show you the entire code for both repositories because the idea is the same

**IRepositoryAuthor interface
    public interface IRepositoryAuthor
    {
        IList getAll();
        void save(Author author);
        void update(Author author);
        void delete(Author author);
        Author findById(string id);
        void deleteAll();
    }
**RepositoryAuthor implementation
    public class RepositoryAuthor:IRepositoryAuthor
    {
        private MongoRepository repository;

        public RepositoryAuthor()
        {
            this.repository = new MongoRepository();
        }

        public IList getAll()
        {
            return repository.ToList();
        }

        public void save(Models.Author author)
        {
            this.repository.Add(author);
        }

        public void update(Models.Author author)
        {
            this.repository.Update(author);
        }

        public void delete(Models.Author author)
        {
            repository.Delete(author.Id);
        }

        public Models.Author findById(string id)
        {
            return repository.GetById(id);
        }

        public void deleteAll()
        {
            repository.DeleteAll();
        }
    }
I created a MongoRepository object which helps us to perfom CRUD operations.This is the idea of MongoRepository NuGet and I think is very useful

3.Last thing is to create a controller which use the repository

  I agree that this not the best approach to use repositories in controllers, but this is just a basic example

**Controller class
    public class AuthorController : Controller
    {
        //
        // GET: /Author/ 
        private IRepositoryAuthor repAuthor;
        private IRepositoryBook repBook;

        public AuthorController(IRepositoryAuthor repAuthor,IRepositoryBook repBook)
        {
            this.repAuthor = repAuthor;
            this.repBook = repBook;
        }

        public ActionResult Index()
        {
            return View(repAuthor.getAll());
        }

        //
        // GET: /Author/Details/5

        public ActionResult Details(string id)
        {
            var author=repAuthor.findById(id);
            if (author == null)
            {
                return HttpNotFound();
            }
            return View(author);
        }

        //
        // GET: /Author/Create

        public ActionResult Create()
        {
            ViewBag.Books = repBook.getAll().Select(i=>new SelectListItem { 
                Value=i.Id,
                Text=i.name
            });
            return View();
        }

        //
        // POST: /Author/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Author author,string[] books)
        {
            try
            {
                // TODO: Add insert logic here
                ViewBag.Books = repBook.getAll().Select(i => new SelectListItem
                {
                    Value = i.Id,
                    Text = i.name
                });

                ModelState.Remove("books");

                if (ModelState.IsValid)
                {
                    HashSet author_books = new HashSet();

                    if (books != null)
                    {
                        foreach (var id in books)
                        {
                            var book = repBook.findById(id);
                            if (book != null)
                            {
                                author_books.Add(book);
                            }
                        }
                    }

                    author.books = author_books;
                    repAuthor.save(author);

                    return RedirectToAction("Index");
                }

                return View(author);
            }
            catch
            {
                return View(author);
            }
        }

        //
        // GET: /Author/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Author/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Author/Delete/5

        public ActionResult Delete(string id)
        {
            var author = repAuthor.findById(id);
            if (author == null)
            {
                return HttpNotFound();
            }
            return View(author);
        }

        //
        // POST: /Author/Delete/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(Author author)
        {
            try
            {
                // TODO: Add delete logic here
                repAuthor.delete(author);

                return RedirectToAction("Index");
            }
            catch
            {
                return View(author);
            }
        }
    }
The views and the controllers are the same as when we work with enity framework or nhibernate. The only problem is that we can't use scaffolding so quickly, but we can generate first controllers, update the actions and then create views from templates.  And for views I will give you an example of how it looks the HTML for Create page:
@model MongoMVC.Models.Author

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true)
Author
@Html.LabelFor(model => model.name)
@Html.EditorFor(model => model.name) @Html.ValidationMessageFor(model => model.name)
@Html.Label("books") @* @{ var items=Model.books.Select(i => new SelectListItem { Value = i.Id, Text = i.name }); }*@ @Html.ListBox("Books",null, new { style="width:70px"})
}
ASP.NET MVC, .Net, MVC, HTML helpers, ASP.MVC Forms, Models, SelectList, Mongo Database, NoSql, MongoRepository, RedirectToAction

Thursday, July 25, 2013

ASP MVC and Spring.Net basic example

1. First step, launch Manage NuGet Packages

2. Search for Spring and install the features presented below



3. Now all references you need are added to your project for using Spring.Net, but I prefer to do something more and add Spring.CodeConfig



4. By using Spring.CodeConfig, we have the chance to change xml configurations with .Net code configurations


4.1.Create a HelloService interface

    public interface HelloService
    {
        string sayHello(string name);
    }

4.2. The implementation of HelloService

    public class HelloServiceImpl:HelloService
    {
        public string sayHello(string name)
        {
            return "Hello " + name;
        }
    }

4.3. The last step...create the application context and inject the service in you controller


**Create the configuration for Service injection
    [Configuration]
    public class ServiceInjectorConfiguration
    {
        [Definition]
        public virtual HelloService GetHelloService()
        {
            return new HelloServiceImpl();
        }
    }

**Update Global.aspx

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));

            var appContext = new CodeConfigApplicationContext();

            appContext.ScanAllAssemblies();
            appContext.Refresh();

            Application["appContext"] = appContext;
        }
    }

**Use your HelloService in controller
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        private HelloService service;
        private GenericApplicationContext appContext;

        public ActionResult Index()
        {
            appContext = (CodeConfigApplicationContext)HttpContext.Application["appContext"];

            service = (HelloService)appContext.GetObject("GetHelloService");

            ViewBag.HelloMessage = service.sayHello("Alex");
            return View();
        }

    }

ASP.NET MVC, .Net, MVC, HTML helpers, Spring.net, Spring, services, ViewBag, applicationContext, dependency injection, spring code config

Tuesday, July 23, 2013

Wicket+Spring Basic Example

Welcome to my first post on this blog!
The purpose of  my first tutorial will be to present a basic example of how to use some of the most popular Java frameworks, at the same time: Spring & Wicket. So we start step by step...

1. We need to create a Maven-webapp



2. Update Maven dependencies

Open your pom.xml file and update your dependencies section as below:



    
      junit
      junit
      3.8.1
      test
    
    
     org.apache.wicket
     wicket
     6.9.1
     pom
    
    
     javax.servlet
     javax.servlet-api
     3.1.0
    
    
     org.springframework
     spring-context
     3.2.3.RELEASE
    
    
     org.springframework
     spring-web
     3.2.3.RELEASE
    
    
     org.apache.wicket
     wicket-spring
     6.9.1
    
    
     org.apache.wicket
     wicket-request
     6.9.1
    
    
     org.slf4j
     slf4j-log4j12
     1.7.5
    
  
    


3. Now take a look on the project structure to make things a little bit clear


4. Last thing about configuration is the spring application context file and then everything will be great and we'll start talking about code, but we have to agree that in this case the configuration is a very important part of our project and we need to do it very carefully


WEB-INF/applicationContext.xml file should be something like this

 
 
 


5. Now it's code time...

First, please update the main web application file and override the init method from org.apache.wicket.protocol.http.WebApplication class and then  the web.xml file:
public class WicketApp extends WebApplication{

 @Override
 public Class getHomePage() {
  // TODO Auto-generated method stub
  return Index.class;
 }

 @Override
 protected void init()
 {
  super.init();
  //getDebugSettings().setDevelopmentUtilitiesEnabled(true);
  getComponentInstantiationListeners().add(new SpringComponentInjector(this));
 }
}

File: web.xml

 Wicket Web Application
 
 
  wicket.wicketTest
  org.apache.wicket.protocol.http.WicketFilter
  
   applicationClassName
   com.wicket.tutorials.blogspot.WicketApp
  
 
 
 
  wicket.wicketTest
  /*
 
 
  
  
           org.springframework.web.context.ContextLoaderListener
        
 

Next I will create a very simple service example, with only one method which will return a Hello entity

**Service interface
public interface HelloService {

 Hello getHelloMessage(String name); 
}

**Service implementation
@Service
public class HelloServiceImpl implements HelloService {

 public Hello getHelloMessage(String name) {
  // TODO Auto-generated method stub
  
  return new Hello(name);
 }

}


Notes
*You can also create other components writing your own beans in applicationContext.xml file, or using annotations like @Repository or @Component and inject them in the same way, with @SpringBean

We are so close to finish this long example and for this we need only web pages and everything will be done. I will not start to explain to much the wicket code, how can we add page parameters or how can we add events on input for example, but Index page is an example of how to use this wicket features

File: Index.html
<html>
<head>
 
</head>
<body>
</body> </html>

File: Index.java
public class Index extends WebPage{
 
 public Index()
 {
  this(new PageParameters());
 }
 
 public Index(PageParameters parameters)
 {
  final PageParameters helloPage_Parameters=new PageParameters();
  helloPage_Parameters.add("message", "");
  
  add(new Label("PageTitle", "Index Page"));
  
        Form form = new Form("form");
        add(form);

        final TextField field = new TextField("person", new Model(""));
        form.add(field);
  
        
        OnChangeAjaxBehavior onChangeAjaxBehavior = new OnChangeAjaxBehavior()
        {
            @Override
            protected void onUpdate(AjaxRequestTarget target)
            {
                helloPage_Parameters.set("message", field.getValue());
            }
        };
        field.add(onChangeAjaxBehavior);
        
  Link link=new Link("action-link") {

   @Override
   public void onClick() {
      
       setResponsePage(new HelloPage(helloPage_Parameters));
    
   }
  };
  
  link.add(new Label("message","Say Hello"));
  
  add(link);
 }
}

File: HelloPage.html
<html>
<head>
 
</head>
<bodyl>

</body>
</html>



File: HelloPage.java


public class HelloPage extends WebPage{

 @SpringBean
 private HelloService helloService;
 
 public HelloPage()
 {
  
 }
 
 public HelloPage(PageParameters pageParameters)
 {
  add(new Label("PageTitle", "Hello Page"));
  
  Hello hello=helloService.getHelloMessage(pageParameters.get("message").toString());
  
  add(new Label("hello-message",hello.toString()));
 }
}


And here we have a great example of using dependency injection with Wicket and Spring. We can refer every bean we created,  using just @SpringBean annotation




Have a nice day with Java Frameworks!