Moved to new website

I started my own website one http://www.menukanows.com ūüėÄūüėÄ

Advertisements

How to create Multi Module Spring boot Project using dependency Management

We often need to create multi modules for a project under several reasons. Today Let see How to create Spring boot Multi module project to use <dependencyManagement> using Intellij  IDEA .

Normally when we create spring boot project(using https://start.spring.io/) project generate parent as Spring boot. but if spring boot project is child module we can’t point out the main pom as because it already have parent pom added. This is a one reason ¬†we need to use Depedency Management in maven.

What is Dependency Management?¬†Dependency Management allows to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. This is especially useful when you have a set of projects (i.e. more than one) that inherits a common parent. So we Can add Spring boot as Centralized ¬†no need to add it as parent. Let’s see some actions.

First you need to create main pom as maven project.  Go to create New Project in Intellij and Select Maven from Left side. Then click next.

The Give any group id and artifact name in relevant fields like below.

On next window give a place to create the project and refactor name if necessary. Then click finish. Since we aren’t going to create anything in ¬†main project folder we don’t need src folder in there. So delete it. After that open pom.xml

Then add

<packaging>pom</packaging>

into the pom.xml like below

Now we need to add spring boot.

<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

Now we need to child modules to the project.

Right click on main folder and New -> Module 

Then click next. ¬†As you can see below the module already inherited from parent pom. You only¬†need give the child module name ūüôā

Next window you will ask place you want save the child module. Then click the Finish.

Now we have a child module. let’s enter Spring boot to the child module. Like below.


<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Now we need to add spring-boot-maven-plugin to the pom.xml

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

Now you are ready to use Spring boot on your child module. Create a spring boot application starter class

After that run below command in terminal (where child pom.xml is)

mvn spring-boot:run

If you type localhost:8080¬†on web browser and white label error in web browser that mean you child worked (of course errors because we didn’t configure the spring to return anything ūüėÄ )

If you want full pom.xml files of modules check below.

  1. Parent Pom.xml
  2. Child Pom.xml

 

 

How add Japanese IME to Ubuntu 16.04 (Japaneses Anthy)

When you learning Japanese it’s very useful to have Japanese IME to write Japanese Letters on Computer. Today lets see how we can install Japanese IME on Ubuntu 16.04.

First you need to go to Language Support. Easiest way to go there is type Language support on Ubuntu Dash like below. (Dash is Left Up most icon in Ubuntu)

Note: If you get the language support is not installed completely dialog box at this point, press Install to install them now.

On the Language tab of the Language Support screen, press Install / Remove Languages

On the Installed Languages screen, scroll down to Japanese and check Installed, and then press Apply Changes.

The Ubuntu will prompt you to add the Password. Give your password there. After that Ubuntu will download necessary packages for IME. When downloads finished you need to Go back to Language Support. 

There you should give IBus, for Keyboard input method system

By default when you install the japaneese language on Ubuntu 16.04 uses the mozc method. But we need to install Japanese Anthy which is more convenient to use. For that you need run below command in the terminal.

sudo apt-get install anthy anthy-common anthy-el libanthy0:amd64 ibus-anthy

Now you need to log out and log in back in Ubuntu. After that click on language button (En) on top right corner.

On the Text Entry screen, click the + icon on the button left of the Input sources to use area.

On the Choose an input source screen, scroll down and select Japanese (Anthy)(IBus).

Press Add. The Japanese Anthy input method will now be available from the language icon in the top panel. Open up any application with a text box such as gedit and place the cursor in the text box. Press the language icon on the tap panel and select Anthy. (Otherwise use short cut buttons in Text Entry dialog.  My are Windwos key and Space)

The language icon will now change to the A„Ā° icon.

 

How to add Github authentication to Maven Release Plugin

If you are trying to configure the Maven Release plugin for you project, you might wander how you add the github credentials to the plugin when it trying to push a commit to the github. Well you have to put them in settings.xml in maven not in the project.

So first of all where is the settings.xml is? it reside in maven folder inside conf directory. ( maven -> conf -> settings.xml )

Next is how we define our credentials there? As (https://maven.apache.org/settings.html#Servers) says we have to define them inside <servers> tags as below

<server>
<id>githubcredentials</id>
<username>githubusername</username>
<password>githubpassword</password>
</server>

now we have to add a property indicating that into pom.xml. So Maven release plugin will get it. It should like below.

<properties>
<project.scm.id>githubcredentials</project.scm.id>
</properties>

id should be same one you put in settings.xml. Now run Maven release plugin to check it works correctly.

 

 

 

How use git with Intellij IDEA

Today we are going to use Git with Intellij.

First you need a repository with git. (If you don’t know to do that please create empty repository on github and you’ll see the instructions) Let’s Open that project with IDEA.

The first thing I want to do is remove unwanted files going to git. For example .idea folder, .iml file etc. For that we need to add .ignore plugin to the IDEA. so

File -> Settings -> Plugins 

Then search for .ignore plugin the click Search in repositories

The Click Install it. After that you’ll need to restart the IDEA.

After that we need to add .gitignore file to describe, what are the files we need to remove from tracking. First Add .gitignore file to project root.

And type the file names to ignore.

Let’s see how to commit changes. Let’s think that I changed the Copier.java First I need to add it (Or any thing you want to add). Easiest way is Use Right click -> Git -> Add

Now Let’s Commit it. Here I commit whole project. (You can use right click and add commit only a file)

As you can see, on upper dialog box you can see which files you need to commit. You’ll need to give commit message. Right side, there are some functionalities if you want to execute before commit. ¬†If everything looks clear press commit. Now we need to Push it.

VCS -> Git -> Push 

Then  you can see below dialog box.

Next window you need to give github credentials.

If push successful, you can see below message in Left bottom corner.

If we went to github and check commits on relevant repository, you can see the commit there.

 

 

 

How to add localization to Hibernate Validator messages (Java Configurations)

Today we are going to discuss about Localization in the Hibernate validator messages. As mentioned above this example about Java configurations.

First of all you need to create necessary files in your projects Resources folder. Here we create lang folder inside of $PROJECT/src/main/resources to store our validation error messages. After that create proper language files for localization (http://www.i18nguy.com/unicode/language-identifiers.html) Here We use name validator for our files.

After that you must go to your webconfig file for Spring MVC here mine name is WebConfig. java.

@Configuration
@EnableWebMvc
@ComponentScan("hsenid.web")
public class WebConfig extends WebMvcConfigurerAdapter {

/*
* Other configurations here*/

@Bean
 public ReloadableResourceBundleMessageSource validationMessageSource() {
 ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
 messageSource.setBasename("classpath:lang/validation");
 messageSource.setCacheSeconds(10); // reload messages every 10 seconds
 return messageSource;
 }

 @Override
 public Validator getValidator(){
 LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
 validator.setValidationMessageSource((MessageSource)validationMessageSource());
 return validator;
 }
}

Now your Hibernate Validators are ready to use localization.

Let Suppose we have

error.testclass.testvariable=Test error

in validator_en.properties file. In you model Your Error message should be change into

@Size(min = 6, message = "{error.testclass.testvariable}")
private String currentPassword;

Now your validation error ready to go (This web page created assuming that you have prior knowledge of Localization)

 

 

TestNG and Spring Test Framework for Testing

The Spring MVC Test framework provides first class support for testing Spring MVC code using a fluent API that can be used with JUnit, TestNG, or any other testing framework. Today We are going to talk about Spring MVC integrated testing with TestNG. Here I going to use Intellij IDEA as my ide. So if you are beginner to TestNG refer this link https://menukablog.wordpress.com/2016/03/29/how-to-setup-testng-with-intellij-idea-beginners-guide/

First of all lets add dependencies to pom.xml.

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.8</version>
    <scope>test</scope>
 </dependency>
 <!--We are using Spring Test Framework as Intergration testing enviroment-->
 <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
    <scope>test</scope>
 </dependency> 
 <!-- jsonassert is needed to json comparing in unit testing-->
 <dependency>
    <groupId>org.skyscreamer</groupId>
    <artifactId>jsonassert</artifactId>
    <version>1.2.3</version>
 </dependency>
 <!--This dependency is need for jsonpath in MockMvc to test inside the response json-->
 <dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.2.0</version>
 </dependency>
 <!--This dependency is to use jsonpath().is() in response json value checking-->
 <dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-core</artifactId>
    <version>1.3</version>
 </dependency>

You can see each dependency have comment regarding what it do.

Lets take a example test case which test a simple controller which return a view.

@Test
@WebAppConfiguration
@ContextConfiguration(classes = WebConfig.class)
public class HomeControllerTest extends AbstractTestNGSpringContextTests {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Test
public void homeTest() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
this.mockMvc.perform(get("/home", "/")
.accept(MediaType.ALL))
.andExpect(status().isOk())
.andExpect(view().name("/home/self-care-home"));
}

(Dependencies of above code remove to improve visibility if you want complete code click here )

@Test

This annotation for notify this is test case
@WebAppConfiguration

class-level annotation that is used to declare that the ApplicationContext loaded for an integration test
@ContextConfiguration(classes = WebConfig.class)

ContextConfiguration is to show TestNG where are Spring beans are. Here I configure my Spring project using java config but if you config yours with xml yours should be like¬†@ContextConfiguration(“base-context.xml”)

 

To use WebAppConfiguration in you Test class you have to extend is with AbstractTestNGSpringContextTests

To mock the MVC pattern in spring first we have to autowire the WebApplicationContext like this

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

After that you have to Build you MockMvc including requirements of the controller here below code is for simple controller which send view.

this.mockMvc.perform(get(“/home”, “/”)
.accept(MediaType.ALL))
.andExpect(status().isOk())
.andExpect(view().name(“/home/self-care-home”));

Let assume you receiving json reply, then .accept(MediaType.ALL)) should be .accept(MediaType.APPLICATION_JSON)) If you want see whole media type please refer this link http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/MediaType.html

status().isOk() is useful when you are expecting http status code for confirm (such as 200 for success 302 for redirect etc). Refer this link to know other status codes that can use MockMvc http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/web/servlet/result/StatusResultMatchers.html#status

view().name(“your_view_name”) is to check view name (the string returns in controller) get back as a response.

Other tha those you can¬†.andExpect(content().json(“{‘userAvailable’:true}”)) to check the response json. But for that to use you will need¬†jsonassert dependency

.andExpect(jsonPath(“$.username”, is(“testre”))) this will allow ¬†you to check a value of json object received as reply.

If you send a form data to a controller by serializing data or in HttpServletRequest you can mock them using ¬†.param(“username”, “testre”)¬†If you serialized a form you have to add each individual data field using .param