Tuesday 18 March 2014

How to put your code under test with Maven, Spring and Junit

So i worked a lot with maven, spring and junit, and on every project i faced the need to have my code under test and so i do each time. an i thought why not have a simple how to do so and so i do this post :D.

so let see what you need to have your own maven project running

  1. JDK 1.6+.
  2. Maven.
  3. IDE or any text editor.
so my pom.xml looks like

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.shereifhawary.spring</groupId>
<artifactId>testing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- testing dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>

</dependencies>
</project>

and i have a simple model and simple service that use this model

as

package com.shereifhawary.spring;
public class SimpleModel {
private String value = "some value";
public String getValue(){
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}

package com.shereifhawary.spring;
public class SimpleService {
private SimpleModel model;
public SimpleModel getModel() {
return model;
}
public void setModel(SimpleModel model) {
this.model = model;
}
public String getValue(){
return model.getValue();
}
}

inside the src/test/resources/beans.xml which carry the bean definition

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

         <bean id="simpleModel" class="com.shereifhawary.spring.SimpleModel">
             <property name="value" value="some value from Spring config"/>
         </bean>
 
<bean id="simpleService" class="com.shereifhawary.spring.SimpleService">
   <property name="model" ref="simpleModel"/>
</bean>
</beans>


and the test case should be like

package com.shereifhawary.spring.tests;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.shereifhawary.spring.SimpleService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/beans.xml" })
public class TestSpringContext {
         
         // the autowire will set the simpleSerice object with the one in the bean.xml
         // so you can use it inside the testcase without even using setup function
@Autowired
SimpleService simpleService;
@Test
public void testSimpleService(){
                // as you can see we set the value with "some value" in the class itself,
                // but inside the bean.xml we set it with "some value from Spring config
"
assertNotEquals("some value",simpleService.getValue());
assertEquals("some value from Spring config
",simpleService.getValue());
}
}

i hope you like it, if you have any questions please leave it below ;)

Sunday 7 April 2013

Optimizing tomcat 7 for best performance

I just had to optimize a Tomcat 7 server to handle a big load, so like any other developer i started to search google for result, and it was a big disaster but i had to do this task and so i started, and after a lot of work i (thanks to Allah) succeeded to gain some knowledge about this topic, so lets start

First of all we are speaking about optimizing tomcat 7, and it has 2 major issues to work with
  1. Optimizing Tomcat server.
  2. Optimizing your application.
So lets start with number 2, whatever how optimized was the server without an optimized code you will get a bad performance, so my advice before optimizing your server start with optimizing your application, not saying that you do not need to optimize your server but it's much more important to write an optimized code to work in an optimized server.

So let's start tuning our server 

How To optimize your Tomcat 7
  1. [Optimizing tomcat memory consumption] Set tomcat mode to be in a server mode, by default tomcat is in client mode, to set the server mode just add -server to your CATALINA_OPTS to be like
    CATALINA_OPTS="-server -Xms2G -Xmx2G $CATALINA_OPTS -XX:+UseConcMarkSweepGC -XX:NewSize=1G -XX:+UseParNewGC"
    also you need to set Xms and Xmx and XX:MaxPermSize to a suitable values depends on your machine, you can edit this line on catalina.(sh|bat).
    source : http://tomcat.apache.org/articles/performance.pdf
  2. [Optimizing JSP behaviour ]Set tomcat parameters for production on conf/web.xml,  on the servlet name jsp you can add <init-param>with each value of the following:
    1. development - To disable on access checks for JSP pages compilation set this to false. 
    2. genStringAsCharArray - To generate slightly more efficient char arrays, set this to true.
    3. modificationTestInterval - If development has to be set to true for any reason (such as dynamic generation of JSPs), setting this to a high value will improve performance a lot.
    4. trimSpaces - To remove useless bytes from the response, set this to true.Source :http://tomcat.apache.org/tomcat-7.0-doc/jasper-howto.html#Production_Configuration
  3. [Optimizing server behaviour] Knowing that tomcat server is a server built over java so it has some    of java problems regardless performance when comparing it with apache server (which is by default a native server), don't worry Tomcat is an Apache product and people in Apache also concerning with performance so they give us the power of APR, which allow tomcat to work with native library to achieve better performance, so this is the steps to make tomcat works with APR on linux (my server was a centos os ... for any other linux distribution you may edit some of the below commands to achieve the same result)
    1. Make sure that these packages are installed on the server machine gcc, openssl-devel, openssl, apr, apr-devel ..... if not search for them on yum and install them, and Sun JDK to be downloaded and installed 
    2. Go to CATALINA_HOME/bin and run this command "tar -zxf tomcat-native.tar.gz" you will find a new dir created with name tomcat-native-X.X.XX-src, so "cd tomcat-native-X.X.XX-src/jni/native"
    3. run the config command "./configure  --with-apr=/usr/bin/apr-1-config  --with-java-home=path-to-tomcat  --with-ssl=yes   --prefix=where-to-put-the-lib (i used /usr/java/jdk1.6.0_38/jre/lib/i386/)".
    4.  Run this command "make && make install".
    5.  After finishing the make install command change the connector protocol to "org.apache.coyote.http11.Http11AprProtocol".
    6.  restart your server and check that the line of missing APR lib is not on the log.
      Source :http://www.jroller.com/agileanswers/entry/configuring_apr_for_tomcat
  4. [Tune the read write buffer] edit this properties in conf/server.xml for tuning the app threads and buffer size this value are configurable base on your application nature 
    1. <Connector port="8080" connectionTimeout="200000" redirectPort="8443" maxThreads=" up to 32000" socket.appReadBufSize="1024" protocol="org.apache.coyote.http11.Http11NioProtocol" socket.appWriteBufSize="1024" bufferSize="1024"/>
      Source : http://blog.krecan.net/2010/05/02/cool-tomcat-is-able-to-handle-more-than-13000-concurrent-connections/comment-page-1/#comment-9636


    Thursday 6 May 2010

    JQuery Intro

    Hi There,
    If you are a web developer i am sure you must hear about JQuery if not it is a complete JavaScript library that can do what every you can think of into a web browser.

    I will give you some tips how to work with JQuery so let's go
    to work with JQuery do the following
    1) include the core library (download the jquery-X.X.X.js) file from http://jquery.com/
    2) include the file into you page as
    <script src="jquery-1[1].3.2.js" type="text/javascript">
    congratulation u now use jquery

    so how to use it ?
    very simple use jquery operator $(jqueryReference).jqueryFunction();
    let's take it step by step,

    the first part is $(jqueryReference) what is the jqueryReference ?
    it should be one of this 5 notation:

    1)no prefix  $('div') — Accesses all the div elements in the HTML(i.e any HTML tag :table,span,div,...)
    2)# prefix  (hash prefix) $('#A') — Accesses all the HTML elements with id='A'
    3). prefix(dot prefix) $('.b') — Accesses all the HTML elements with class='b'
    4)nonElement = $.somefunction();(used as independent function like $.ajax({...}); )
    5) a css selector which is a littel bit complex ($("div > div > span").doSomething() which will get all the spans that is inside div and this div is inside another div)
    jqueryReferences may add to them something called custom selectors like
    $('div : even'),$('div : odd') ,$('div : eq(0)') and  ......
    $('div : even').someFunction() that will select only the even div in the document and apply someFunction() to them so if your code is like
    <div> 0 </div>
    <div> 1 </div>
    <div> 2 </div>
    <div> 3 </div>
    <div> 4 </div>
    the select divs is the divs the contains 0,2,4 (the first ,third and fifth).
    $('div : odd').someFunction(); will select 1,3
    and $('div:eq(1)').Somefunction() will select only the div that contain 1 (the second div)
    (note: jquery count from 0)

    now we finish the first part let's go to the second part which is the functions
    $('jqueryReference').function();
    the function is can be categorized into 2 category and they are:
    1)on what they applied to ?
    2)where they come from ?

    let begin on the functions
    1) on what they applied to ?
    the functions is applied on 1 of 2 things html element or document
    so when we use $('div') or $('#id') or $('.class') we apply the function to those element's only like( $('#id').show() )
    but when we use $.function() we will use a function which not related to a spacial html element (like $.ajax({...}) )

    2)where they come from ?
    the come from 2 main source the engine or plugin
    - the engine is jquery-X.X.X.js which contain the most important function (i.e. ajax....) and u can use them once u include the core libaray
    - the plugin is any library the depend on jquery like fancyBox which u can call once u call their library (don't worry most of them are well documented ,tested and have how to use)

    finally if u need any thing about JQuery don't worry just call me on the mobile. hahaha i am kidding google it and u will found million of solution.
    nothing more to say so have a good day with jquery ;)
    More reference =====> http://www.jquery.com
    GOOD BYE

    Tuesday 4 May 2010

    MYSQL Data Base Encoding

    Hi there,
    Today i will talk about how to deal with Multiple language Data base.
    first i will talk how to build it from scratch and second how to modify a working copy of database
    NOTES:
    - in my case i worked with Arabic encoding so i used utf_general_ci as encoding category BUT if the language isn't supported in utf_general_ci choose the supported collection.
    - the default encoding for database latin1_swedish_ci.
    - My tools => phpMyAdmin , notepad++

    Build From Scratch
    1) When creating the DB specify the collection to utf_general_ci.
    2) When creating the table specify the collection to utf_general_ci.
    3) Now each field in the table you need to make it in Arabic make it's collection utf_general_ci.
    4) Finally in application to config the Arabic to work fine use this to you connection string :
    -General case:
    jdbc:mysql://yourhost/yourDB?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8

    second: modify a working copy to work with arabic
    in my case the database accept Arabic letters and the encoding was latin so i did the following

    1) Dump the Database (with phpMyAdmin)
    2) Create .txt file
    3) copy the dump and paste into the .txt file AND DON'T SAVE THE FILE
    4) change the file encoding ( i used the notepad++ encoding tab encode in UTF-8) and save the file
    5) you will find the Arabic letter appered :)
    6) change the encoding of the DB & tables & fields as the first section.
    7) Empty the table and then copy the insert statement from your dump in the .txt file and paste in the phpMyAdmin insert tab


    Done :)