Sunday, October 23, 2011

Using Jackson with Apache CXF - JAX-RS

Apache CXF uses Jettison for generating JSON generation. By default, Jettison adds the class name as well in JSON representation. To remove the class name from the json, there is some extra configuration required, which I will tell you some other time. Another solution to this problem is to use Jackson.

public class Error{

   Integer code;
   String reason;

   /*
    * getters and setters 
    */
   
}

Jettison's JSON:



{ "error" : { code: "CODE", reason: "REASON } }

Jackson's JSON:

{ code: "CODE", reason: "REASON" }




Now I will explain how to tell CXF to use Jackson instead of Jettison. Following are the required steps:

  1. You need to add Jackson in your classpath. If you are using Maven, you just need to add following lines in your pom.xml:
  2.       
             org.codehaus.jackson
             jackson-jaxrs
             1.9.0
          
    
  3. Next thing is to tell CXF to use Jackson. If you using Spring, you can add following lines in your bean configuration xml:
  4.         
               
            
        
       
    

Friday, September 23, 2011

Writing custom filter for jersey


If we want to intercept all the request coming to jersey controller. For example if we want to check if user is authenticated before each request, we will do this in each method. So to achieve this functionality we would prefer writing a filter, which will intercept each request and check for authentication.

Writing a filter:
We need to implement ContainerRequestFilter interface for creating Jersey filter. Following is the code sample for intercepting and modifying a request using jersey filter:



import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.log4j.Logger;
/**
 *
 * @author arnav
 */
public class MyAppFilter implements ContainerRequestFilter{


   public ContainerRequest filter(ContainerRequest request) {

      MultivaluedMap<String, String> headers = request.getRequestHeaders();

      headers.add("code", "MY_APP_CODE");
      request.setHeaders((InBoundHeaders)headers);

      return request;
   }
}

In the above class, I have intercepted the request and added a "code" into HTTP Header.


After adding this class, we need to register this filter for our web application. So now we will add following lines in our web.xml:



    
        Jersey Spring Web Application
        com.sun.jersey.spi.spring.container.servlet.SpringServlet
      
         com.sun.jersey.spi.container.ContainerRequestFilters
         package.MyAppFilter
              
    
@GET
	@Produces("application/xml")
	public PersonList getIt(@HeaderParam("code") String code) {

		System.out.println(code);
	}
This will have access to the "code", we have set in our MyAppFilter class.

Wednesday, October 20, 2010

Screen orientation handling in iphone/android

var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

//adding event listener
window.addEventListener(orientationEvent, function() {
var orientation = window.orientation;
switch(orientation) {
case 0:
//your code goes here.
break;

case 90: //landscapeLeft
case -90: //landscapeRight
//your code goes here.
break;
}

}, false);

Sunday, January 10, 2010

Search Engine Optimization (SEO)

Usually people thought of SEO (search engine optimization) once they are done with website. What I say is: You should be keep some of the points in mind before you start building your website. Here I will summarise some of the keypoints to be taken care of for better "Search Engine Optimization":

1) Add good descriptive content to your website. This will create keywords for search engine. Another tip that gets generated from this tip is: If you are using images to explain something in your website, don't forgot to 'alt' sub-element of 'image' element. In the 'alt' sub-element you can explain your the content of your image.

2) Try to reduce parameters in the URL, in any case you will need parameters in you url. So prefer to RESTful urls. Using RESTful urls will let you pass parameters without adding parameters in the url. For example: normal url >> www.website.com?uid=xxxxx&email=xxxxx@xxx.xxx and rest url would be "www.website.com/xxxxx/xxxxx@xxx.xxx" and your url handler component would actually grab uid & email and pass them to your controller.

3) Generally your url describes which page is being accessed. Prefer using hyphens instead of underscores in the long word in url. Following is the example how search engine would interpret the words in the each of the urls:
arnav-awasthi.html would be interpreted as arnav awasthi.html
arnav_awasthi.html would be interpreted as arnavawasthi.html

4) "title" tag of page: Your html page has a element "title". Use this element to define your page in fewer words. Search engines use this element to a great extent. For example if your webpage give weather report of Pune, you may give title of page as "Youwebsite: Pune: Weather report".

5) Meta tags: There are two meta tags which you can use to describe the content of your webpage. They are "description" and "keywords". You can take a look at any popular website how they have used these tags to describe their content.

By following these tips, you will be able to create a well illustrated website with clean search engine friendly urls.

So now you have created your search engines friendly website. It's time to collect all the public links of your website, put them together and hand it over to search engines. So here is a protocol which will tell you how would be collecting your links and how you can tell search engines about this url document.

You will have to create a sitemap xml. http://www.sitemaps.org/protocol.php tells you how your sitemap should look like.
Useful tip while you create sitemap: Stick to either www or non-www type of url.

Now I will tell you after creating sitemap, what else needed to be done and how would you do that.

Whenever search bot comes to your website, it first looks at the robots text file at the root of your website. This file tells robots where your sitemap xml is and which pages/directories it doesn't need to crawl. You can create a robots.txt file using google webmasters tools.

So here I summarise the steps after you have created sitemap.

1) update your robots.txt file. Add this line to your robots.txt: Sitemap: http://www.example.com/sitemap.xml

2) Submit your sitemap to the popular search engines. You can submit your sitemap to google, yahoo and bing.
a) Submit to Google: To submit the sitemap to google URL should be like this:
http://www.google.com/webmasters/tools/ping?sitemap="your sitemap's encoded url", or easy way is to submit your sitemap using google webmasters tools.

b) Submit to Yahoo: For submitting your sitmap to you need to generate Yahoo API key. Your final url would look like:
http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid="APPID&"url="your sitemap's encoded url"

c) Submit to Bing: For bing your url would look like:
http://www.bing.com/webmaster/ping.aspx?siteMap="your sitemap's encoded url"

After all these you are almost done. Now you can give some thought to canonical urls. As I have said that you must stick to either www or non-www form of url. Now it's the time to tell search engines which one you prefer. You can use your server redirect to do so. Like in apache you can use mod_rewrite to do a redirect every request to strictly to the one form (either www or non-www) of url. Apache: Redirect from non-www to www form is the link of my another blog post which tells how you can do that.

Start Using google webmasters tools: Create an account in google webmasters tools and add your website url to it.
1) Add both forms (www and non-www) of urls, it will generate piece of code which you should add into your html code. And then you can verify your website with google webmasters tools.
2) Tell google which url you prefer: Site Configuration > Settings > preferred domain.

Now you are done with search engine optimization. Do keep checking your website's performance in google webmasters tools.

Thursday, January 7, 2010

Apache: Redirect from non-www to www form

Here is a reason when you need to redirect users coming to your site without "www" to the one with "www": You have submitted your sitemap to the search engine with your website name as "http://www.yourwebsite.com". Now you need to tell the search engines which url you prefer to be canonical. So you need to redirect the "http://yourwebsite.com" to "http://www.yourwebsite.com".

So now here is a way to do that with apache.

1) Enable mod_rewrite in your apache config file.

2) Write following lines in you .htaccess file:



RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,QSA,L]



So, you are done.

If you don't know what the .htaccess file is. Here is a small information about it. It is placed at the root folder of your web application. And it overrides the configuration of the your apache server's main config file. So for shared hosting when you don't have access to main config file, you can do your application specific settings in this .htaccess file.

Wednesday, January 6, 2010

"Created on" and "Updated on" columns in Mysql

In mysql there is a limitation: You can have only one time stamp column with "Default" value "now()". Almost every table is system has created_on and updated_on columns. So how we can manage to have both with minimum efforts in our coding and mysql queries. Here is a way which I use to do this:

create table dummy_table(
id integer not null auto_increment primary key,
created_on timestamp NOT NULL default '0000-00-00 00:00:00',
updated_on timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
);

Insert data:
insert into dummy_table(created_on) values(null);

Data inserted:
+----+---------------------+---------------------+
| id | created_on | updated_on |
+----+---------------------+---------------------+
| 1 | 2010-01-06 23:22:16 | 2010-01-06 23:22:16 |
+----+---------------------+---------------------+

Update Data:
update dummy_table set id = 3;

Data updated:

+----+---------------------+---------------------+
| id | created_on | updated_on |
+----+---------------------+---------------------+
| 3 | 2010-01-06 23:22:16 | 2010-01-06 23:23:26 |
+----+---------------------+---------------------+

So without using updated_on column in update query, it is being automatically updated. I hope this would be helpful for lots of the new mysql users.

Tuesday, January 5, 2010

Mysql optimization: Schema Optimization

Very first step to optimization: Give a thought to your schema design
Arnav Awasthi: Mysql Schema Optimation

Avoid NULL if possible:
  • A nullable column uses more storage space and requires special processing inside MySQL.
  • When a nullable column is indexed, it requires an extra byte per entry and can even cause a fixed-size index (such as an index on a single integer column) to be converted to a variable-sized one in MyISAM.
  • The performance improvement from changing NULL columns to NOT NULL is usually small, so don’t make finding and changing them on an existing schema a priority unless you know they are causing problems. However, if you’re planning to index columns, avoid making them nullable if possible.

Whole Number:

  • Your choice determines how MySQL stores the data, in memory and on disk. However, integer computations generally use 64-bit BIGINT integers, even on 32-bit architectures. (The exceptions are some aggregate functions, which use DECIMAL or DOUBLE to perform computations.)

Floating point number:
  • Floating-point types typically use less space than DECIMAL to store the same range of values. A FLOAT column uses four bytes of storage. DOUBLE consumes eight bytes and has greater precision and a larger range of values. As with integers, you’re choosing only the storage type; MySQL uses DOUBLE for its internal calculations on floating- point types.

String type:

  • Use varchar instead of char.
  • Don't be generous while giving the length of varchar column. Keep some characters extra. Also don't give it extremely high. When you know 50 characters are fine, there is no need to give 255 characters for that column. Also max length of columns has some role in indexing (Biggest player in query optimization.) So keep this in mind.
To be continued .....