<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Thiranjith&#039;s Blog</title>
	<atom:link href="http://thiranjith.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://thiranjith.com</link>
	<description></description>
	<lastBuildDate>Thu, 11 Apr 2013 00:30:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Spring MVC Bean Validation with Annotations</title>
		<link>http://thiranjith.com/2013/04/11/spring-mvc-bean-validation-with-annotations/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=spring-mvc-bean-validation-with-annotations</link>
		<comments>http://thiranjith.com/2013/04/11/spring-mvc-bean-validation-with-annotations/#comments</comments>
		<pubDate>Thu, 11 Apr 2013 00:23:48 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=516</guid>
		<description><![CDATA[<p>Input data validation is a critical piece of functionality in any web application because we cannot always rely on users to enter valid data. We need to safeguard our data-stores and business processes against both malformed as well as malicious &#8230; <a href="http://thiranjith.com/2013/04/11/spring-mvc-bean-validation-with-annotations/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>Input data validation is a critical piece of functionality in any web application because we cannot always rely on users to enter valid data. We need to safeguard our data-stores and business processes against both malformed as well as malicious data.</p>
<p>Based on my experience with <a href="http://www.springsource.org/spring-framework#documentation" title="Spring Framework Overview" target="_blank">Spring</a>, I thought of writing a series of tutorials on different methods of validating form input when working with Spring MVC.</p>
<p>This is the first part of that series, and I will be focusing on <strong>basic form data (i.e. data submitted by the user) validation in Spring MVC 3 using declarative annotations</strong>. In the future, I am hoping to touch on more advanced topics such as:</p>
<ol>
<li>Displaying custom messages for validation errors</li>
<li>Writing custom annotations to validate view models (or fields)</li>
<li>Using JSR 303 <strong>groups</strong> to perform conditional validations</li>
<li>Validation using Spring&#8217;s Validator interface</li>
<li>Comparison of different validation methods in Spring MVC (pros, cons and when to use them)</li>
</ol>
<p>Hopefully by the end of the series, you will have a good idea about Spring validation mechanisms, and be able to pick the best option(s) for a particular problem.</p>
<p>Continue on to learn how to perform basic annotation-based validations in your Spring MVC 3.x web applications.</p>
<p><span id="more-516"></span></p>
<h3>Pre-requisits</h3>
<p>Before proceeding ahead, I assume that you have some basic understanding about Spring MVC. Also, I would recommend installing <a href="http://maven.apache.org/download.cgi" title="Maven" target="_blank">Maven</a> to build your projects if you fetch the sample code from GitHub.</p>
<h3>Problem Description</h3>
<p>Take a simple scenario where we are entering personal information in a web site, as shown in Figure 1. We want to ensure that we only accept the data if all of the following conditions are satisfied; otherwise we present the data back to the user with some helpful information to rectify the issues.</p>
<div id="attachment_518" class="wp-caption alignright" style="width: 310px"><a href="http://thiranjith.com/wp-content/uploads/2013/03/form-basic.png"><img src="http://thiranjith.com/wp-content/uploads/2013/03/form-basic-300x194.png" alt="" title="Form to enter personal information" width="300" height="194" class="size-medium wp-image-518" /></a><p class="wp-caption-text">Figure 1: Form to enter personal information</p></div>
<ul>
<li>All fields are mandatory except for &#8216;comments&#8217;.</li>
<li>Age must be greater than (or equal to) <code>10</code></li>
<li>Date of birth must be entered as &#8216;<strong>yyyy-MM-dd</strong>&#8216; format (e.g. <code>2000-10-22</code>) and must be in the past (i.e. can&#8217;t enter a date in future)</li>
<li>Comments can be at most <code>40</code> characters.</li>
</ul>
<h3>Step-by-step guide to implementing annotation-based validation in Spring MVC</h3>
<ol>
<li>
<h4>Enable annotations</h4>
<p>Declarative validations are specified as annotations (e.g. on field, method or class level). Therefore, we need to enable annotations in Spring in order for Spring MVC framework to pickup our declarative validations and apply them automatically when a form is submitted.</p>
<p>We do this by adding the <code><mvc:annotation-driven /></code> tag inside our <code>servlet context xml</code> file (typically under <code>WEB-INF\spring\appServlet</code> folder)</p>
<pre class="crayon-plain-tag"><code>&lt;!-- inside servlet-context.xml --&gt;
&lt;mvc:annotation-driven /&gt;

&lt;!-- rest omitted for brevity --&gt;</code></pre><p></li>
<li>
<h4>Additional Project Dependencies</h4>
<p>
We are relying mainly on <strong>JSR 303 javax.validation API</strong> to add declarative validation support to our Beans. In addition, I also tend to use the <code>hibernate validator API</code>s that provide more enhanced constraints. If you are using Maven, you will need to add the following dependencies to your project:</p>
<ul>
<li><code>validation-api jar</code></li>
<li><code>hibernate-validator jar</code></li>
</ul>
<p>Your <code>pom.xml</code> would contain the following dependencies (when using Maven):</p>
<pre class="crayon-plain-tag"><code>&lt;dependency&gt;
  &lt;groupId&gt;javax.validation&lt;/groupId&gt;
  &lt;artifactId&gt;validation-api&lt;/artifactId&gt;
  &lt;version&gt;1.0.0.GA&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
  &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;
  &lt;version&gt;4.1.0.Final&lt;/version&gt;
&lt;/dependency&gt;</code></pre><p></li>
<li>
<h4>Add validation rules to the Bean</h4>
<p>Before progressing further, let us have a look at our Bean object that handles the form submission:</p><pre class="crayon-plain-tag"><code>/**
 *
 * Simple form bean without any validations
 */
public class SimpleFormBean {

    private String firstName;
    private String lastName;
    private int age;
    private Date dateOfBirth;
    private String comments;

    // getters and setters omitted for brevity
}</code></pre><p><p>
<p>This is just a plain old Java Object/Bean (POJO). Let us now define the constraints we described earlier using annotations from javax.validation, hibernate.validator and springframework.format.annotation packages.</p>
<pre class="crayon-plain-tag"><code>import javax.validation.constraints.Min;
import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

/**
 * Simple form bean with declarative validation rules
 * (using JSR 303 annotations)
 */
public class SimpleFormBean {

    // must be at least of length 1
    @NotEmpty
    private String firstName;
    // is not blank (i.e. doesn't accept &quot;   &quot;)
    @NotBlank
    private String lastName;
    // defines the minimum age to be 10
    @Min(10)
    private int age;
    // ISO.DATE format is defined as 'yyyy-MM-dd'
    // e.g. 2012-02-16
    @DateTimeFormat(iso = ISO.DATE)
    @Past
    private Date dateOfBirth;
    // at most 40 characters. Accepts null/empty
    @Length(max = 40)
    private String comments;

    // getters and setters omitted for brevity</code></pre><p><p><p>
<p>Have a look at the <a href="http://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-summary.html" title="javax validation API documentation" target="_blank">Javax Validation API</a> and <a href="http://docs.jboss.org/hibernate/validator/4.3/api/" title="Hibernate Validator API" target="_blank">Hibernate Validator documentation</a> for more details on what other annotations are available.</p>
</li>
<li>
<h4>@Valid annotation on the request handler</h4>
<p>Next, we need to update our <code>Controller</code>, so that Spring framework will automatically perform Bean validation when the form is submitted. This happens before it reaches our <code>Controller</code>&#8216;s handler method, which allows us to do special things if there are any validation errors (such as redirecting to a generic error page, or resetting form fields etc.).</p>
<p>The code for the <code>Controller</code> shows the method that processes form submission.</p>
<pre class="crayon-plain-tag"><code>@Controller
public class SimpleFormValidationController {

    @RequestMapping(value = &quot;/simpleValidationExample&quot;, method = RequestMethod.POST)
    public ModelAndView processFormSubmissionWithValidation(@Valid SimpleFormBean formBean, 
                BindingResult result) {
        ModelAndView mv = new ModelAndView(ViewNameConstants.VIEW_SIMPLE_FORM_VALIDATION);
        
        if (result.hasErrors()) {
            mv.addObject(&quot;message&quot;, &quot;Some message you add on error&quot;);
            mv.addObject(&quot;errors&quot;, result.getAllErrors());
            return mv;
        }

        // Do any other normal processing you might do when the user input is valid
        mv.addObject(&quot;message&quot;, &quot;Some message you add if everything is ok&quot;);
        return mv;
    }
}</code></pre><p><p><p><p>
<p>There are a couple of important things happening in the above code snippet:</p>
<ol>
<li><strong>Line #5</strong>: Mark the Bean representing the form data (<code>SimpleFormBean</code>) with <strong><code>@Valid</code></strong> annotation. Spring framework will pick up this annotation as part of its request handling pipeline, and apply all the JSR 303 annotations on that object to validate the bean. We, as developers, do not have to worry about anything other than specifying the validation rules via annotations!</li>
<li><strong>Line #9</strong>: The <code>org.springframework.validation.BindingResult</code> object contains the results of Spring validation. In this particular case, I am checking to see if there are any validation errors, so I can add some special message to be displayed when the page is refreshed. See the <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/validation/BindingResult.html" title="BindingResult API" target="_blank">Spring API</a> for more details.</li>
</ol>
<p><br/><br />
If you feel adventurous, write a handler similar to above, but without the <code>@Valid</code> annotation. You will see that your Bean is no longer validated by Spring despite your Bean having all the annotations!</p>
</li>
<li>
<h4>Re-displaying form with error messages</h4>
<p>It is all good to validate your Bean, but it would be better if you can tell the user what he/she did wrong so their mistakes can be corrected.</p>
<div id="attachment_526" class="wp-caption alignright" style="width: 310px"><a href="http://thiranjith.com/wp-content/uploads/2013/03/form-basic-validation-errors.png"><img src="http://thiranjith.com/wp-content/uploads/2013/03/form-basic-validation-errors-300x295.png" alt="" title="Form with validation errors" width="300" height="295" class="size-medium wp-image-526" /></a><p class="wp-caption-text">Figure 2: After submitting the form with errors</p></div>
<p><strong>Figure 2</strong> shows the errors you get when the user enters incorrect information. Note that it doesn&#8217;t complain about &#8216;Comments&#8217; field because it can accept null/empty values.</p>
<p>We can use the <code>form:errors</code> tag to display <em>field-specific validation errors</em> to the user. For example, the snippet below displays the error if the user submits an empty &#8216;firstName&#8217; field.</p><pre class="crayon-plain-tag"><code>&lt;form:errors path=&quot;firstName&quot; cssClass=&quot;error&quot; /&gt;</code></pre></p>
<p>The full code snippet for generating the form is shown below:</p>
<pre class="crayon-plain-tag"><code>&lt;%@ taglib uri=&quot;http://java.sun.com/jsp/jstl/core&quot; prefix=&quot;c&quot; %&gt;
&lt;%@ taglib uri=&quot;http://www.springframework.org/tags/form&quot; prefix=&quot;form&quot; %&gt;

...

&lt;form:form id=&quot;form&quot; method=&quot;post&quot; modelAttribute=&quot;simpleFormBean&quot;&gt;
	&lt;div id=&quot;formContent&quot;&gt;
		&lt;div class=&quot;header&quot;&gt;
	  		&lt;h2&gt;Form&lt;/h2&gt;
	  		&lt;c:if test=&quot;${not empty message}&quot;&gt;
				&lt;div id=&quot;message&quot; class=&quot;success&quot;&gt;${message}&lt;/div&gt;	
	  		&lt;/c:if&gt;
	  		&lt;s:bind path=&quot;*&quot;&gt;
			&lt;c:if test=&quot;${status.error}&quot;&gt;
		  		&lt;div id=&quot;message&quot; class=&quot;error&quot;&gt;Form has errors&lt;/div&gt;
			&lt;/c:if&gt;
	  		&lt;/s:bind&gt;
		&lt;/div&gt;
		&lt;fieldset&gt;
	  		&lt;legend&gt;Personal Info&lt;/legend&gt;
	  		&lt;form:label path=&quot;firstName&quot;&gt;First Name &lt;form:errors path=&quot;firstName&quot; cssClass=&quot;error&quot; /&gt;&lt;/form:label&gt;
	  		&lt;form:input path=&quot;firstName&quot; /&gt;
		  		
	  		&lt;form:label path=&quot;lastName&quot;&gt;Last Name &lt;form:errors path=&quot;lastName&quot; cssClass=&quot;error&quot; /&gt;&lt;/form:label&gt;
	  		&lt;form:input path=&quot;lastName&quot; /&gt;
	  		&lt;form:label path=&quot;age&quot;&gt;Age &lt;form:errors path=&quot;age&quot; cssClass=&quot;error&quot; /&gt;&lt;/form:label&gt;
	  		&lt;form:input path=&quot;age&quot; /&gt;
	  		&lt;form:label path=&quot;dateOfBirth&quot;&gt;
				Date of Birth (in form yyyy-mm-dd) &lt;form:errors path=&quot;dateOfBirth&quot; cssClass=&quot;error&quot; /&gt;
	 		&lt;/form:label&gt;
	  		&lt;form:input path=&quot;dateOfBirth&quot; /&gt;
	
			&lt;form:label path=&quot;comments&quot;&gt;Comments (40 letters max) &lt;form:errors path=&quot;comments&quot; cssClass=&quot;error&quot; /&gt;&lt;/form:label&gt;
	  		&lt;form:input path=&quot;comments&quot; /&gt;
	  	&lt;/fieldset&gt;
	  	&lt;p&gt;&lt;button type=&quot;submit&quot;&gt;Submit (with validations)&lt;/button&gt;&lt;/p&gt;
	 &lt;/div&gt;
&lt;/form:form&gt;</code></pre></p>
<p>Things of interest about the above html snippet include:</p>
<ol>
<li><strong>Use of Spring form taglib</strong> to construct the form, labels and input fields. This enables Spring to bind our Bean object to the form data.</li>
<li><strong>Use of <code>form:errors</code> attribute</strong> to display errors, if there are any. This is a special attribute that is part of the Spring tag library that displays validation errors based on the field that is wrong.
</li>
</ol>
</li>
<li>
<h4>Customising validation error messages</h4>
<p>The messages that you see in red &#8211; in <strong>Figure 2</strong> above &#8211; are default error messages generated by the validators we used. As you can see some of the validator error messages are straightforward, but others are way too verbose to be displayed to an end-user (e.g. error message for date validation above).</p>
<p>The final part is to customise the error messages displayed. There are a couple of ways in which you can modify the validation messages.</p>
<ol>
<li><strong>Specifying the custom message when you define the constraint</strong> &#8211; This is the simplest, and possibly the least elegant of solutions. The code snippet below show us customising the error message when the user doesn&#8217;t enter any value for the &#8216;First name&#8217; field.<br />
<pre class="crayon-plain-tag"><code>public class SimpleFormBean {

    @NotEmpty(message = &quot;Hi, first name cannot be empty. Please enter something here :)&quot;)
    private String firstName;

    // ... omitted for brevity
}</code></pre><p><p><p><p><p><p><p>
<p>Now, instead of &#8220;<code>may not be empty</code>&#8221; (as shown in <strong>Figure 2</strong> above), you will see &#8220;<code>Hi, first name cannot be empty. Please enter something here :)</code>&#8221; as the error message.</p>
<p>The reason why I said this approach is not elegant is that you cannot display locale specific messages easily with this approach. This where the 2nd solution for this problem comes in handy!
</li>
<li><strong>Use a properties file to manage messages and customise the message key</strong> &#8211; In short, we define our messages in a <code>.properties</code> file (e.g. <code>webapps\resources\messages.properties</code>) as key-value pairs. Instead of the actual message, we define the key as part of the message attribute for the annotation. The code below illustrates how we can display the same custom message as above using this approach:
<p></p><pre class="crayon-plain-tag"><code>## messages.properties file
NotEmpty.SimpleFormBean.FirstNameField = Hi, first name cannot be empty. Please enter something here :)</code></pre>
<p>And our Bean would look like:</p><pre class="crayon-plain-tag"><code>public class SimpleFormBean {

    @NotEmpty(message = &quot;NotEmpty.SimpleFormBean.FirstNameField&quot;)
    private String firstName;

    // ... omitted for brevity
}</code></pre><p><p><p><p><p><p><p><p><p>
<p>We need to do bit more configuration to Spring in order to allow Spring to find these messages. Rather than deviating from the main topic, I will write another article soon describing how to achieve this.</p>
</li>
</ol>
</li>
</ol>
<h3>Conclusions</h3>
<p>In this tutorial I&#8217;ve covered the following aspects related to validating form attributes/data (also known as form backing objects) using JSR 303 compliant declarative annotations in Spring MVC.</p>
<ol>
<li>Enabling annotations in Spring MVC</li>
<li>Using @Valid to enable Spring validation on form objects</li>
<li>Defining validations on Beans using JSR 303 compliant annotations</li>
<li>Writing jsp/html to display validation errors on screen</li>
<li>Customising default validation messages</li>
</ol>
<p>Hope you found the article informative, and let me know if you want me to clarify anything.</p>
<p>A fully working sample project can be found at GitHub if you are interested in playing around.</p>
<p>Thanks!</p>
<h3>References</h3>
<ul>
<li>Source code for GitHub project at :</li>
<li><a href="http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/validation.html#validation-beanvalidation" title="Spring Validation Documentation" target="_blank">Spring Validation Documentation</a> &#8211; for more in-depth details about Spring validation.</li>
</ul>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2013/04/11/spring-mvc-bean-validation-with-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Log4j property file examples</title>
		<link>http://thiranjith.com/2013/03/06/log4j-property-file-examples/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=log4j-property-file-examples</link>
		<comments>http://thiranjith.com/2013/03/06/log4j-property-file-examples/#comments</comments>
		<pubDate>Tue, 05 Mar 2013 19:25:38 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[log4j]]></category>
		<category><![CDATA[log4j properties file]]></category>
		<category><![CDATA[logging examples]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=498</guid>
		<description><![CDATA[<p>There aren&#8217;t too many clear examples of log4j.properties configuration examples around on the net. So, I thought of compiling a list of sample configurations to help anyone who might be looking to configure log4j. In this article I will be &#8230; <a href="http://thiranjith.com/2013/03/06/log4j-property-file-examples/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>There aren&#8217;t too many clear examples of log4j.properties configuration examples around on the net. So, I thought of compiling a list of sample configurations to help anyone who might be looking to configure log4j.</p>
<p>In this article I will be covering the following scenarios with examples:</p>
<ol>
<li>Logging to Console</li>
<li>Logging to a File</li>
<li>Logging to multiple <strong>Appenders</strong> (or log files)</li>
<li>Restricting logging levels by package name</li>
<li>Having multiple appenders with different log levels</li>
<li>Logging the output of a specific class or a package to a specific Appender</li>
</ol>
<p><span id="more-498"></span></p>
<h3>Logging to Console</h3>
<p>The example below will send all log messages with a level of INFO or higher to the console (e.g. DOS prompt). The <code>ConversionPattern</code> determines how the output will be displayed on-screen.</p>
<pre class="crayon-plain-tag"><code>#
## Create a single appender called 'stdout' with 
## a log level of 'INFO'
log4j.rootLogger=INFO, stdout

## Log to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p: %c - %m%n</code></pre>
<h3>Logging to a File</h3>
<p>There are various different File appenders that come out of the box with log4j library. These include <code>FileAppender</code> (for continuously appending to a single file), and more advanced file-appenders such as <code>RollingFileAppender</code> that automatically start a new file after reaching a pre-specified size.</p>
<p>See the <a href="http://logging.apache.org/log4j//1.2/apidocs/org/apache/log4j/FileAppender.html" title="File Appender API" target="_blank">API for File Appender</a> for more information about possible configuration options.</p>
<pre class="crayon-plain-tag"><code>#
## Create a single appender called 'R' with 
## a log level of 'INFO'. This will create new
## files whenever the current file reaches 100KB
log4j.rootLogger=INFO, stdout

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=rolling-log.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-5p: %c - %m%n</code></pre><p><h3>Logging to multiple <strong>Appenders</strong> (or log files)</h3>
<p>The example below illustrates how we can have multiple appenders simultaneously. In the example below, all logs with a level INFO or higher will be logged to both the console and a file (<code>file-log.log</code>).</p>
<pre class="crayon-plain-tag"><code>log4j.rootLogger=INFO, stdout, F

# Console appender configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p: %c - %m%n

# File appender configuration
log4j.appender.F=org.apache.log4j.FileAppender
log4j.appender.F.File=file-log.log
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%-5p: %c - %m%n</code></pre><p><p>
<h3>Restricting logging levels by package name</h3>
<p>Oftentimes you have 3rd party libraries that do their own logging, which can quickly fill up your log. In such cases, you want to restrict logging for some (or all) of those libraries so your logs only show what really matters. Log4j provides a mechanism to do this by restricting log levels on a per-package level. This allows us to specify the logging level on the specified package (including the sub-packages within  it).</p>
<p>In the following example, the packages <code>org.springframework.core</code> and <code>org.springframework.web</code> will only log ERROR messages, while the rest of the application will log DEBUG or higher messages. For example, only ERROR logs by <code>org.springframework.web.servlet.mvc.AbstractController</code> class will be logged by our application.</p>
<pre class="crayon-plain-tag"><code>log4j.rootLogger=DEBUG, stdout

# Console appender configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p: %c - %m%n

# Restrict logging for some of the Spring MVC libraries
log4j.logger.org.springframework.core=WARN
log4j.logger.org.springframework.web=WARN</code></pre><p><p><p>
<h3>How to configure multiple appenders with different log levels</h3>
<p>Imagine you want to log <strong>INFO</strong> and <strong>ERROR</strong> logs to different files; for example, have <code>file-info.log</code> with all messages of level <strong>INFO</strong> or higher, and <code>file-error.log</code> to have only <strong>ERROR</strong> messages.</p>
<p>The log4j.properties file below shows how to accomplish the above task by outputting different levels of logging to different files using the <code>log4j.appender.FError.Threshold</code> attribute.</p>
<pre class="crayon-plain-tag"><code>#
# Initilise the two appenders
# FInfo - Log INFO messages and above
# FError - Log ERROR messages and above
log4j.rootLogger=INFO, FInfo, FError

# FInfo appender will log at default log level (INFO)
log4j.appender.FInfo=org.apache.log4j.FileAppender
log4j.appender.FInfo.File=file-log.log
log4j.appender.FInfo.layout=org.apache.log4j.PatternLayout
log4j.appender.FInfo.layout.ConversionPattern=%-5p: %c - %m%n

# FError appender will log ERROR and above
log4j.appender.FError=org.apache.log4j.FileAppender
# &quot;log4j.appender.FError.Threshold&quot; allows us to customise
# the log level for a specific appender
log4j.appender.FError.Threshold=ERROR
log4j.appender.FError.File=file-log.log
log4j.appender.FError.layout=org.apache.log4j.PatternLayout
log4j.appender.FError.layout.ConversionPattern=%-5p: %c - %m%n</code></pre><p><p><p><p>
<h3>Logging the output of a specific class to a specific Appender</h3>
<p>The example below shows how to output the logs from a specific class (<code>PerformanceProfiler</code> class in <code>com.thira.example</code> package) to a dedicated logger/appender.</p>
<pre class="crayon-plain-tag"><code>log4j.rootLogger=DEBUG, stdout

# Console appender configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p: %c - %m%n

# Define another appender for the specified class
log4j.logger.com.thira.example.PerformanceProfiler=INFO, Performance
log4j.additivity.com.thira.example.PerformanceProfiler=false
log4j.appender.Performance=org.apache.log4j.RollingFileAppender
log4j.appender.Performance.File=client-portal-performance.log
log4j.appender.Performance.MaxFileSize=2MB
log4j.appender.Performance.MaxBackupIndex=10
log4j.appender.Performance.layout=org.apache.log4j.PatternLayout
log4j.appender.Performance.layout.ConversionPattern=%-5p: %c - %m%n</code></pre><p><p><p><p><p>
<p>The highlighted <strong>line #9</strong> (<code>log4j.logger.com.thira.example.PerformanceProfiler=INFO, Performance</code>) tells log4j to redirect all  to redirect all <code>INFO</code> (or higher) log messages to the appender called &#8216;<strong>Performance</strong>&#8216;.</p>
<p>The <code>additivity</code> option in the next line (i.e. <strong>line #10</strong>) ensures that the INFO (or higher) log messages from <code>com.thira.example.PerformanceProfiler</code> class will not show up on the <code>rootLogger</code> (i.e. <strong>stdout</strong> appender in the above example). Note that by default, <code>additivity</code> for all appenders are set to <code>true</code>, implying the log messages will appear on all loggers.</p>
<h3>References and Resources</h3>
<p>Checkout the following resources if you want to find more about log4j:</p>
<ul>
<li><a href="http://logging.apache.org/log4j/1.2/manual.html" title="Log4J Manual" target="_blank">Log4j Overview</a></li>
<li><a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html" title="Log4j Pattern Layout" target="_blank">API for Log4j Pattern Layout</a> (to learn more about how to change the output of your log file)</li>
</ul>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2013/03/06/log4j-property-file-examples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Configure Maven to work with NTLM proxies</title>
		<link>http://thiranjith.com/2012/10/31/how-to-configure-maven-to-work-with-ntlm-proxies/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-configure-maven-to-work-with-ntlm-proxies</link>
		<comments>http://thiranjith.com/2012/10/31/how-to-configure-maven-to-work-with-ntlm-proxies/#comments</comments>
		<pubDate>Tue, 30 Oct 2012 20:13:11 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Guides]]></category>
		<category><![CDATA[Maven Proxy settings]]></category>
		<category><![CDATA[NTML Proxy]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=475</guid>
		<description><![CDATA[<p>I recently installed Maven at a client site that had a NTLM proxy, and ran into issues because it was failing to download maven dependencies. I was following the instructions provided by Maven to correctly setup my proxy settings, without &#8230; <a href="http://thiranjith.com/2012/10/31/how-to-configure-maven-to-work-with-ntlm-proxies/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>I recently installed Maven at a client site that had a NTLM proxy, and ran into issues because it was failing to download maven dependencies. I was following the <a href="http://maven.apache.org/guides/mini/guide-proxies.html" title="How to enable Proxy Settings in Maven" target="_blank">instructions provided by Maven</a> to correctly setup my proxy settings, without any luck!</p>
<p>I kept getting the following error when attempting to run <code>mvn install</code> goal to set up the project:</p><pre class="crayon-plain-tag"><code>C:Dev\MavenTest&gt; mvn clean install


[ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.4.1 or one of its dependencies could not be resolved: Failed to read artifa
escriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.4.1: Could not transfer artifact org.apache.maven.plugins:maven-clean-pl
:pom:2.4.1 from/to central (http://repo.maven.apache.org/maven2): Not authorized by proxy, ReasonPhrase:Proxy Authentication Required (
ISA Server requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  ). -&gt; [Help 1]

...</code></pre>
<p>After few hours of Googling and trial and error, I finally found two methods of getting Maven to work with NTLM proxies.</p>
<p><span id="more-475"></span></p>
<h2>Step #1: Add proxy settings to your Maven configuration file</h2>
<ol>
<li>Open the Maven configuration file at <code>%M2_HOME%/conf/settings.xml</code>. For Linux, this is typically found at<br />
<pre class="crayon-plain-tag"><code>${user.home}/.m2/settings.xml)</code></pre><br />
For Windows, this can be found in one of the following locations:<br />
<pre class="crayon-plain-tag"><code># In Win XP, Vista
C:\Documents and Settings\username\.m2\settings.xml

# In Windows 7/8
C:\users\username\.m2\settings.xml</code></pre><p><p><p></li>
<li>Find the section within <code>settings.xml</code> file that defines the <code>proxies</code> node. This should look something like:</p><pre class="crayon-plain-tag"><code>&lt;proxies&gt;
    &lt;!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    &lt;proxy&gt;
      &lt;id&gt;optional&lt;/id&gt;
      &lt;active&gt;true&lt;/active&gt;
      &lt;protocol&gt;http&lt;/protocol&gt;
      ...
    &lt;/proxy&gt;
    --&gt;
&lt;/proxies&gt;</code></pre>
</li>
<li>Comment out the proxy node and enter your proxy information. Afterwords, the proxies node should look similar to:<br />
<pre class="crayon-plain-tag"><code>&lt;proxies&gt;
    &lt;proxy&gt;
      &lt;!-- id field is optional --&gt;
      &lt;id&gt;something-descriptive-to-identify-your-proxy&lt;/id&gt;
      &lt;!-- Tells Maven to use this proxy. Specify 
           'false' if you want to turn it off. --&gt;
      &lt;active&gt;true&lt;/active&gt;
      &lt;protocol&gt;http&lt;/protocol&gt;
      &lt;!-- ENTER YOUR PROXY HOST NAME --&gt;
      &lt;host&gt;company.proxy.host.com&lt;/host&gt;
      &lt;!-- ENTER YOUR PROXY HOST'S PORT NUMBER --&gt;
      &lt;port&gt;8080&lt;/port&gt;
      &lt;!-- ENTER YOUR USER NAME TO LOGIN TO THE HOST --&gt;
      &lt;username&gt;myUserName&lt;/username&gt;
      &lt;!-- ENTER YOUR PASSWORD ASSOCIATED WITH THE USERNAME --&gt;
      &lt;password&gt;myPassword&lt;/password&gt;
      &lt;!-- Any URLs that you want to filter out 
          (e.g. local repository?). 
           Otherwise just keep this as it is --&gt;
      &lt;nonProxyHosts&gt;local.net|some.host.com&lt;/nonProxyHosts&gt;
    &lt;/proxy&gt;
  &lt;/proxies&gt;</code></pre><br />
<strong>IMPORTANT: </strong> Ensure that you change the <strong>host</strong>, <strong>port</strong>, <strong>username</strong> and <strong>password</strong> fields to match your environment/proxy setup.</p>
<p>If the above settings doesn&#8217;t work, then you might want to change the username field to include the domain that the user belongs to. e.g.</p><pre class="crayon-plain-tag"><code>&lt;username&gt;myDomain\myUserName&lt;/username&gt;</code></pre><p></li>
</ol>
<h2>Step #2: Add wagon-http-lightweight extension</h2>
<p><strong>Wagon HTTP lightweight library</strong> allows us to overcome authentication limitations in Maven (3.0.4) when working with NTLM proxies. We can follow the steps below to add the <strong>Wagon HTTP lightweight library</strong> as a Maven extension:</p>
<ol>
<li>Download the <code>wagon-http-lightweight-2.2.jar</code> from <a href="http://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-http-lightweight/2.2/wagon-http-lightweight-2.2.jar" title="Download link for WAGON Maven Extension" target="_blank">http://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-http-lightweight/2.2/wagon-http-lightweight-2.2.jar</a></li>
<li>Copy the <code>wagon-http-lightweight-2.2.jar</code> to <strong><code>%M2_HOME%/lib/ext</code></strong> folder.</li>
</ol>
<h3>Example POM.xml to test the solution</h3>
<p>To test our approach, first create a simple Maven project with the following pom.xml:</p><pre class="crayon-plain-tag"><code>&lt;!-- pom.xml --&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; 
  xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; 
  xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;com.thira.testmavenplugindl&lt;/groupId&gt;
  &lt;artifactId&gt;test-maven-plugin-dl&lt;/artifactId&gt;
  &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;name&gt;Test Maven Plugin Download Issue&lt;/name&gt;
  &lt;description&gt;Example pom file to test Maven dependency download with NTLM proxies&lt;/description&gt;
&lt;/project&gt;</code></pre><br />
The run the Maven goal described below. This should execute successfully and download all Maven dependencies:<br />
<pre class="crayon-plain-tag"><code>mvn clean install</code></pre></p>
<p>Check your local repository directory (as defined in <code>settings.xml</code> file) to ensure all the dependencies are correctly downloaded.</p>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2012/10/31/how-to-configure-maven-to-work-with-ntlm-proxies/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to check network connectivity in Android</title>
		<link>http://thiranjith.com/2012/10/19/how-to-check-network-connectivity-in-android/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-check-network-connectivity-in-android</link>
		<comments>http://thiranjith.com/2012/10/19/how-to-check-network-connectivity-in-android/#comments</comments>
		<pubDate>Fri, 19 Oct 2012 03:42:39 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[check current network]]></category>
		<category><![CDATA[ConnectivityManager]]></category>
		<category><![CDATA[Guides]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=466</guid>
		<description><![CDATA[<p>This tutorial shows how to check whether your Android phone is currently connected to a network or not (e.g. Wi-Fi, 3G etc.). A while back, I wrote a tutorial on how to dynamically monitor network connectivity in Android. However, sometimes &#8230; <a href="http://thiranjith.com/2012/10/19/how-to-check-network-connectivity-in-android/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>This tutorial shows how to check whether your Android phone is currently connected to a network or not (e.g. Wi-Fi, 3G etc.).</p>
<p>A while back, I wrote a tutorial on <a href="http://thiranjith.com/2011/03/31/how-to-monitor-network-connectivity-in-android/" title="How to monitor network connectivity in Android" target="_blank">how to dynamically monitor network connectivity in Android</a>. However, sometimes all you want is to check if your phone has an active network connection at any given time (i.e. not to constantly monitor its status).</p>
<p><span id="more-466"></span></p>
<p>The simplest way to check network connectivity at any given point in time is to:</p>
<ol>
<li>Create a utility function to check network status as shown below<br />
<pre class="crayon-plain-tag"><code>public static boolean isOnline(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        
        return activeNetwork != null &amp;&amp; activeNetwork.isConnectedOrConnecting();
}</code></pre><p></li>
<li>Add the following permission to the Android Manifest in order to monitor current network state</p><pre class="crayon-plain-tag"><code>&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;</code></pre><p></li>
</ol>
<h4>Explaining the utility function</h4>
<p>There are several key discussion points above the <code>isOnline(Context)</code> utility function I described earlier:</p>
<ul>
<li><code>ConnectivityManager#getActiveNetworkInfo()</code> method can return <code>null</code> if the phone is either in Airplane mode or all network interfaces are turned off manually. Therefore, we need to do the null check (<code>activeNetwork != null</code>) before invoking <code>isConnectedOrConnecting()</code> method.</li>
<li><a href="http://developer.android.com/reference/android/net/NetworkInfo.html#isConnectedOrConnecting()" title="Android API for checking connectivity status for a given networkInfo" target="_blank"><code>isConnectedOrConnecting()</code></a> method checks for networks that are in the process of being connected. Depending on the requirements, you might want to use a more strict version where the method returns <code>true</code> only if the network is already connected. This can be achieved by replacing <code>isConnectedOrConnecting()</code> method with <code>isConnected()</code>. See <a href="http://developer.android.com/reference/android/net/NetworkInfo.html#isConnected()" title="Android API to check if current network is connected or not" target="_blank">the Android SDK</a> for more details about the method.</li>
</ul>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2012/10/19/how-to-check-network-connectivity-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to working with kSOAP2 in Android</title>
		<link>http://thiranjith.com/2012/10/15/introduction-to-working-with-ksoap2-in-android/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=introduction-to-working-with-ksoap2-in-android</link>
		<comments>http://thiranjith.com/2012/10/15/introduction-to-working-with-ksoap2-in-android/#comments</comments>
		<pubDate>Mon, 15 Oct 2012 04:23:20 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[kSOAP2]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[web services]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=430</guid>
		<description><![CDATA[<p>This is an introductory tutorial showing how to consume SOAP-based web services in Android using the kSOAP2 library. Despite rising popularity of RESTful services, there are still a significant number of SOAP-based web services around that are being consumed by &#8230; <a href="http://thiranjith.com/2012/10/15/introduction-to-working-with-ksoap2-in-android/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>This is an introductory tutorial showing how to consume SOAP-based web services in Android using the <a title="kSOAP2 Home Page" href="http://code.google.com/p/ksoap2-android/" target="_blank">kSOAP2 library</a>.</p>
<p><a href="http://thiranjith.com/wp-content/uploads/2012/10/web_services_wheels_and_globe.png"><img src="http://thiranjith.com/wp-content/uploads/2012/10/web_services_wheels_and_globe-300x194.png" alt="How to use kSOAP2 library in Android" title="Using kSOAP2 with Android" width="300" height="194" class="alignright size-medium wp-image-460" /></a></p>
<p>Despite rising popularity of RESTful services, there are still a significant number of SOAP-based web services around that are being consumed by mobile applications; specially when working in the enterprise world. Android does not have native support for web service consumption, and this handy light-weight library called <strong>kSOAP2</strong> allows Android applications to easily and efficiently consume SOAP-based web services.</p>
<p>In this tutorial I will show you how to use kSOAP2 in Android to consume a publicly available SOAP-based web service. A fully working example of an Android project illustrating the use of kSOAP2 can be found at <a href="https://github.com/thira/blog-demos/tree/master/android-kSOAP2-example" title="GitHub repository for Android example project" target="_blank">GitHub</a>.</p>
<p><span id="more-430"></span></p>
<h3>Introducing the service and operations</h3>
<p>I am using a publicly available web service from <a title="Public Weather Service" href="http://www.service-repository.com/service/overview/1132083200" target="_blank">www.service-repository.com</a> that allows us to view weather information. I will be focusing on two specific operations to highlight the basic features of using kSOAP2:</p>
<ol>
<li><strong><code>GetWeatherInformation</code></strong>: A zero-argument operation that return weather information managed by the service (You can have a look at the request and response XML from <a href="http://www.service-repository.com/operation/show?operation=GetWeatherInformation&amp;portType=WeatherSoap&amp;id=58" target="_blank">here</a>)</li>
<li><strong><code>GetCityForecastByZIP</code></strong>: A single argument operation that returns weather forecast for a city (argument specifies the US Zip code). You can have a look at the request and response XML from <a href="http://www.service-repository.com/operation/show?operation=GetCityForecastByZIP&amp;portType=WeatherSoap&amp;id=58" target="_blank">here</a></li>
</ol>
<p>The service definition can be downloaded/viewed from <a title="WSDL for Weather Service" href="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL" target="_blank">this link</a> (open it in Notepad or any other text-editor to view the content).</p>
<h3>Creating a new Android project with kSOAP2</h3>
<ol>
<li>Create a standard Android project</li>
<li>Download the <code>ksoap2-android-assembly-jar-with-dependencies.jar</code> from <a title="kSOAP2 Android library jar file" href="http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.6.5/ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar">kSOAP2 home page</a></li>
<li>Copy the downloaded <code>jar</code> file to your Android project&#8217;s <code>libs</code> folder. This will enable your Android application to automatically pick up this library when it generates the final artefacts (i.e. the APK file)</li>
<li>Add the <code>android.permission.INTERNET</code> permission to your application&#8217;s <code>Manifest.xml</code> file to allow your application to talk to web services. Add the following code snippet to your application&#8217;s MANIFEST:<br />
<pre class="crayon-plain-tag"><code>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</code></pre>
</li>
</ol>
<p><strong>NOTE:</strong> There are multiple ways in which you can include kSOAP2 in your Android project, and the method I described above is the most simplest. You can read about other options (e.g. in Maven builds or as an Android library etc.) at <a title="How to use kSOAP2" href="http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2" target="_blank">here</a>.</p>
<h3>Invoking a web service request</h3>
<p>Invoking a web service with kSOAP2 involves the following steps:</p>
<ol>
<li><strong>Create a SOAP Envelope</strong> using the <code>org.ksoap2.serialization.SoapSerializationEnvelope</code> class.</li>
<li><strong>Set the request information</strong> for the <code>SOAP Envelope</code>. The request information will be represented by a org.ksoap2.serialization.SoapObject object. I will show how to create request objects shortly in the <a title="How to create a SOAP request" href="#create-service-request">next section</a>.</li>
<li><strong>Create an HTTP Transport request object</strong> to deliver the SOAP request (<code>org.ksoap2.transport.HttpTransportSE</code>)</li>
<li><strong>Send the SOAP request over HTTP</strong> using the HTTP Transport and SOAP Envelope objects created earlier. This call is a synchronous call.</li>
<li>Process the web service response (or handle any unexpected errors). A detailed example of processing a relatively complex web service response can be found <a title="How to process a web service response in kSOAP2" href="#process-service-response">later in the article</a>.</li>
</ol>
<p>The code snippet below summarises the above steps in Android:</p><pre class="crayon-plain-tag"><code>SoapObject parameter = getSOAPRequestParameter();
// 1. Create SOAP Envelope 
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// 2. Set the request parameters
envelope.setOutputSoapObject(parameter);

// 3. Create an HTTP Transport object to send the web service request
HttpTransportSE httpTransport = new HttpTransportSE(WSDL_URL);
httpTransport.debug = true; // allows capture of raw request/respose in Logcat

// 4. Make the web service invocation
httpTransport.call(WS_NAMESPACE + WS_METHOD_NAME, envelope);

// Logging the raw request and response (for debugging purposes)
Log.d(TAG, &quot;HTTP REQUEST:\n&quot; + httpTransport.requestDump);
Log.d(TAG, &quot;HTTP RESPONSE:\n&quot; + httpTransport.responseDump);

// 5. Process the web service response
if (envelope.bodyIn instanceof SoapObject) { // SoapObject = SUCCESS
    SoapObject soapObject = (SoapObject) envelope.bodyIn;
    T processedResponse = parseSOAPResponse(soapObject);
    // ... do whatever you want with this object now
} else if (envelope.bodyIn instanceof SoapFault) { // SoapFault = FAILURE
    SoapFault soapFault = (SoapFault) envelope.bodyIn;
    throw new Exception(soapFault.getMessage());
}</code></pre><p><p>
As mentioned above, your SOAP requests are synchronous and depending on network conditions it can take a while before even a simplest of requests can be invoked. This can cause application freezes and crashes. Therefore, it is <strong>highly recommended</strong> to do both the service invocation and request processing within a background thread in Android.</p>
<p>This can be achieved using an <a title="AsyncTask" href="http://developer.android.com/reference/android/os/AsyncTask.html"><code>AsyncTask</code></a>, and putting the above code inside its <code>doInBackground</code> method. You can have a look at how this is incorporated into the solution in my sample project at Github.</p>
<p><a name="create-service-request"></a></p>
<h3>Creating a service request</h3>
<p>All SOAP requests are created in kSOAP2 using a <code>org.ksoap2.serialization.SoapObject</code> object. You need to specify the web service namespace, and the service method name when constructing a <code>SoapObject</code>. You can find the namespace and method name details in the <code>wsdl</code> file itself, or in the documentation provided by the service provider.</p>
<h4>Example SOAP request with no arguments</h4>
<p>For example, you can create a zero-argument SOAP request required for the <strong><em>GetWeatherInformation</em></strong> service method as follows:</p><pre class="crayon-plain-tag"><code>// see com.example.ksoap2.wsclient.weather.GetWeatherInformationTask class
// for full source code
SoapObject request = new SoapObject(&quot;http://ws.cdyne.com/WeatherWS/&quot; /* namespace */, 
                                    &quot;GetWeatherInformation&quot; /* web service method */);
// set the request in the envelope (shown in the previous section)
envelope.setOutputSoapObject(parameter);</code></pre>
<h4>Example SOAP request with an argument</h4>
<p>Lets have a look at a slightly more complex scenario that involves passing in arguments to a web service request, such as the case with <strong><em>GetCityForecastByZIP</em></strong> service method. As per <a title="Service definition for GetCityForecastByZIP operation" href="http://www.service-repository.com/operation/show?operation=GetCityForecastByZIP&amp;portType=WeatherSoap&amp;id=58" target="_blank">its service definition</a>, it accepts a single argument that describe the zip code of a city.</p>
<p>The only step different from the above no-argument scenario, is that now we are adding request properties to our <code>SoapObject</code> using <code>PropertyInfo</code> class. org.ksoap2.serialization.PropertyInfo class enables us to add property name-value pairs as illustrated in the code snippet below.</p>
<p><strong>NOTE</strong>: Adding complex request objects is out of scope for this article. I will be writing another article soon about that soon.</p><pre class="crayon-plain-tag"><code>String zipCode = 12345; // example zip code
// 1. Create the SoapObject 
SoapObject request = new SoapObject(&quot;http://ws.cdyne.com/WeatherWS/&quot; /* namespace */, 
                                    &quot;GetCityForecastByZIP&quot; /* web service method */);
// 2. Define the property
PropertyInfo property = new PropertyInfo();
property.setNamespace(&quot;http://ws.cdyne.com/WeatherWS/&quot;); // namespace to ensure that the element-name is prefixed with the namespace
property.setName(&quot;ZIP&quot;); // name of the argument as per wsdl document
property.setValue(zipCode); // value of the property

// 3. Add the property to the request object        
request.addProperty(property);

// .. this request will then be passed in to the SoapEnvelope
// e.g. envelope.setOutputSoapObject(parameter);</code></pre><p><p><p>
<p><a name="process-service-response"></a></p>
<h3>Processing service response</h3>
<p>Now to the final part of the process; deciphering the service response received from the provider.</p>
<ol>
<li><b>Detecting the validity of the response: </b> Firstly, we have to detect whether our service request succeeded or not. The following code snippet shows how to detect this:
<pre class="crayon-plain-tag"><code>// after calling the web service using HTTP Transport ..

if (envelope.bodyIn instanceof SoapObject) { // SoapObject = SUCCESS
   SoapObject soapObject = (SoapObject) envelope.bodyIn;
   result = parseSOAPResponse(soapObject);
} else if (envelope.bodyIn instanceof SoapFault) { // SoapFault = FAILURE
   SoapFault soapFault = (SoapFault) envelope.bodyIn;
   throw new Exception(soapFault.getMessage());
}

...
private CityForecastBO parseSOAPResponse(SoapObject response) {
        CityForecastBO cityForecastResult = null;
        SoapObject cityForecastNode = (SoapObject) response.getProperty(&quot;GetCityForecastByZIPResult&quot;);

        // ... 
        // more code in here to populate the CityForecastBO object from the 
        // response object (illustrated in the steps below)

        return cityForecastResult;
}</code></pre><p><p><p><p><p>
</li>
<li><b>Parsing the web service response in a success case: </b> The code for parsing depends on web service you invoke (i.e. wsdl specification).<br />
A snippet of the SOAP response received is shown below (you can test this out by entering the zip code <code>12345</code> into the request parameter <a href="http://www.service-repository.com/operation/show?operation=GetCityForecastByZIP&#038;portType=WeatherSoap&#038;id=58" taget="_new">here</a>:</p><pre class="crayon-plain-tag"><code>&lt;soap:Body&gt;
    &lt;GetCityForecastByZIPResponse xmlns=&quot;http://ws.cdyne.com/WeatherWS/&quot;&gt;
      &lt;GetCityForecastByZIPResult&gt;
        &lt;Success&gt;true&lt;/Success&gt;
        &lt;ResponseText&gt;City Found&lt;/ResponseText&gt;
        &lt;State&gt;NY&lt;/State&gt;
        &lt;City&gt;Schenectady&lt;/City&gt;
        &lt;WeatherStationCity&gt;Albany&lt;/WeatherStationCity&gt;
        &lt;ForecastResult&gt;
          &lt;Forecast&gt;
            &lt;Date&gt;2012-10-16T00:00:00&lt;/Date&gt;
            &lt;WeatherID&gt;2&lt;/WeatherID&gt;
            &lt;Desciption&gt;Partly Cloudy&lt;/Desciption&gt;
            &lt;Temperatures&gt;
              &lt;MorningLow&gt;45&lt;/MorningLow&gt;
              &lt;DaytimeHigh&gt;55&lt;/DaytimeHigh&gt;
            &lt;/Temperatures&gt;
            &lt;ProbabilityOfPrecipiation&gt;
              &lt;Nighttime&gt;30&lt;/Nighttime&gt;
              &lt;Daytime&gt;20&lt;/Daytime&gt;
            &lt;/ProbabilityOfPrecipiation&gt;
          &lt;/Forecast&gt;
        &lt;/ForecastResult&gt;
      &lt;/GetCityForecastByZIPResult&gt;
    &lt;/GetCityForecastByZIPResponse&gt;
  &lt;/soap:Body&gt;</code></pre><p>The following code snippets demonstrate how we can use kSOAP library to parse the response xml.</li>
<li><b>Reading simple (top-level) parameters: </b></p><pre class="crayon-plain-tag"><code>SoapObject cityForecastNode = (SoapObject) response.getProperty(&quot;GetCityForecastByZIPResult&quot;);
// see the wsdl for the definition of &quot;ForecastReturn&quot; (which can be null/empty)
// i.e. &lt;s:element name=&quot;GetCityForecastByZIPResponse&quot;&gt; element 
if (cityForecastNode != null) {
    // see &lt;s:complexType name=&quot;ForecastReturn&quot;&gt; element for definition of &quot;ForecastReturn&quot;
           
    // &quot;Success&quot; is a mandatory node, so no need to do any null checks.
    boolean isSuccess = Boolean.parseBoolean(cityForecastNode.getPrimitivePropertySafelyAsString(&quot;Success&quot;));
                    
    String responseText =  cityForecastNode.getPrimitivePropertySafelyAsString(&quot;ResponseText&quot;);
    String state =  cityForecastNode.getPrimitivePropertySafelyAsString(&quot;State&quot;);
    String city =  cityForecastNode.getPrimitivePropertySafelyAsString(&quot;City&quot;);
    String weatherStationCity =  cityForecastNode.getPrimitivePropertySafelyAsString(&quot;WeatherStationCity&quot;);
}</code></pre><p><p><p><p><p><p><p>
The <code>getPrimitivePropertySafelyAsString(String)</code> method allows us to extract any primitive property of the <code>SoapObject</code> as a String. If the property value is not present (which is the case if the attribute is optional), then we will get a <code>null</code> value back from this method.
</li>
<li><b>Reading array objects: </b> If you take a closer look at the <code>XML</code> snippet for the service response, you will see that the <code>ForecastResult</code> node is an array consisting of zero or more <code>Forecast</code> nodes. We can iterate through these array structures using a simple <code>for loop</code> as shown below:</p><pre class="crayon-plain-tag"><code>// &quot;ForecastResult&quot; (an array) can be empty according to the wsdl definition. Therefore, we do a null check before processing
// any data.
SoapObject forecastResultsNode = (SoapObject) cityForecastNode.getPropertySafely(&quot;ForecastResult&quot;);
if (forecastResultsNode != null) {
    // Definition for Forecast node can be found at &lt;s:complexType name=&quot;Forecast&quot;&gt; element in wsdl
    for (int idx = 0; idx &lt; forecastResultsNode.getPropertyCount(); idx++) {
         SoapObject forecastNode = (SoapObject) forecastResultsNode.getProperty(idx);
                    
         String date =  forecastNode.getPrimitivePropertySafelyAsString(&quot;Date&quot;);
         short weatherId =  Short.parseShort(forecastNode.getPrimitivePropertySafelyAsString(&quot;WeatherID&quot;));
    }
}</code></pre><p><p><p><p><p><p><p><p>
There are few interesting points about the code snippet above:</p>
<ol>
<li><code>getPropertyCount()</code> method allows us to get the total number of child nodes within a <code>SoapObject</code>; in this case it happens to be the same as the number of <code>Forecast</code> nodes.</li>
<li><code>forecastResultsNode.getProperty(idx)</code> allows us to retrieve a child node (i.e. <code>SoapObject</code>) at a given position.</li>
<li>According to the <a href="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL" target="_new">wsdl for the weather service</a>, <code>ForecastResult</code> is an optional node. Therefore, we need to do a <code>null check</code> before parsing the <code>forecastResultsNode</code> object.</li>
</ol>
</li>
<li><b>Reading values from nested nodes: </b> As per <a href="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL" target="_new">wsdl definition</a>, both &#8220;Temperatures&#8221; and &#8220;ProbabilityOfPrecipiation&#8221; nodes are nested complex types within a <code>Forecast</code> node. We can extract nested complex types within a <code>SoapObject</code> using the <code>getProperty(String nodeName)</code> method as illustrated below.<br />
<pre class="crayon-plain-tag"><code>// &quot;Temperatures&quot; and &quot;ProbabilityOfPrecipiation&quot; nodes are mandatory within a &quot;Forecast&quot; node
    //      &lt;s:element minOccurs=&quot;1&quot; maxOccurs=&quot;1&quot; name=&quot;Temperatures&quot; type=&quot;tns:temp&quot;/&gt;
    //      &lt;s:element minOccurs=&quot;1&quot; maxOccurs=&quot;1&quot; name=&quot;ProbabilityOfPrecipiation&quot; type=&quot;tns:POP&quot;/&gt;
    SoapObject temperatureNode = (SoapObject)forecastNode.getProperty(&quot;Temperatures&quot;);
    String moringLowTemp =  temperatureNode.getPrimitivePropertySafelyAsString(&quot;MorningLow&quot;);
    String daytimeHighTemp =  temperatureNode.getPrimitivePropertySafelyAsString(&quot;DaytimeHigh&quot;);
    forecast.setTemperature(moringLowTemp, daytimeHighTemp);
                    
    SoapObject precipicationProbabilityNode = (SoapObject)forecastNode.getProperty(&quot;ProbabilityOfPrecipiation&quot;);
    String nightTimePercentage =  precipicationProbabilityNode.getPrimitivePropertySafelyAsString(&quot;Nighttime&quot;);
    String dayTimePercentage =  precipicationProbabilityNode.getPrimitivePropertySafelyAsString(&quot;Daytime&quot;);
    forecast.setPrecipiationProbability(nightTimePercentage, dayTimePercentage);</code></pre><p><p><p><p><p><p><p><p><p>
</li>
</ol>
<h3>Wrap up</h3>
<p>In this totorial, I have demonstrated how to:</p>
<ol>
<li>Set up an Android project with kSOAP2 library</li>
<li>How to create a SOAP request (with an without parameters) and invoke a web service</li>
<li>How to parse the web service response (extracting both simple and complex types)</li>
</ol>
<p>The full source code for the above code snippets can be found at <a href="https://github.com/thira/blog-demos/tree/master/android-kSOAP2-example" title="GitHub repository for Android example project" target="_blank">my GitHub repository</a>. The <code>GetCityForecastByZipCodeTask.java</code> and <code>GetWeatherInformationTask.java</code> classes (in <code>com.example.ksoap2.wsclient.weather</code> package) contains the core logic of using kSOAP2 library to invoke web services.</p>
<p>Please feel free to get in touch with me if you have any questions or suggestions.</p>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2012/10/15/introduction-to-working-with-ksoap2-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unveiling Bazaarfind NZ: A Price comparison site for sports supplements</title>
		<link>http://thiranjith.com/2012/09/05/release-of-my-latest-project-bazaarfind/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=release-of-my-latest-project-bazaarfind</link>
		<comments>http://thiranjith.com/2012/09/05/release-of-my-latest-project-bazaarfind/#comments</comments>
		<pubDate>Wed, 05 Sep 2012 03:52:19 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[bazaarfind]]></category>
		<category><![CDATA[health and fitness]]></category>
		<category><![CDATA[price comparison stores]]></category>
		<category><![CDATA[protiene supplements]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=417</guid>
		<description><![CDATA[<p>Over the weekend I released my latest web site: BazaarFind Supplements. Bazaarfind is a price comparison site for sports and nutritional supplements. Currently the comparison data is sourced from stores within New Zealand. Give it a go next time you &#8230; <a href="http://thiranjith.com/2012/09/05/release-of-my-latest-project-bazaarfind/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>Over the weekend I released my latest web site: <a href="http://www.bazaarfind.co.nz" title="Bazaarfind Supplements New Zealand" target="_blank">BazaarFind Supplements</a>.</p>
<p><a href="http://thiranjith.com/wp-content/uploads/2012/09/FB_Profile.png"><img src="http://thiranjith.com/wp-content/uploads/2012/09/FB_Profile.png" alt="BazaarFind New Zealand" title="FB_Profile" width="282" height="282" class="alignright size-full wp-image-419" /></a></p>
<p><strong>Bazaarfind</strong> is a price comparison site for sports and nutritional supplements. Currently the comparison data is sourced from stores within New Zealand. Give it a go next time you happen to be in the online market to purchase supplements!</p>
<p>We are hard at work to add new features, and I would greatly appreciate if you can take few minutes to checkout the site and give me your feedback :)</p>
<p>If you like what you see, and want to be kept up to date of the site&#8217;s progress and latest deals:</p>
<ol>
<li>Like us on Facebook at <a href="http://www.facebook.com/BazaarFindNZ" title="Facebook page for BazaarFind New Zealand" target="_blank">http://www.facebook.com/BazaarFindNZ</a>, and/or</li>
<li>Follow us on <a href="https://plus.google.com/u/0/101530978928542541380/posts" title="Google+ page for BazaarFind" target="_blank">Google+</a></li>
</ol>
<p>Feel free to share the news with your friends and family!</p>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2012/09/05/release-of-my-latest-project-bazaarfind/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to Root HTC One X</title>
		<link>http://thiranjith.com/2012/08/08/how-to-root-htc-one-x/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-root-htc-one-x</link>
		<comments>http://thiranjith.com/2012/08/08/how-to-root-htc-one-x/#comments</comments>
		<pubDate>Wed, 08 Aug 2012 04:06:42 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[root android]]></category>
		<category><![CDATA[root htc one x]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=385</guid>
		<description><![CDATA[<p>Following on from the last article on what does it mean to root your Android phone, I thought of providing a step-by-step guide to root a HTC One X phone. If you are new to rooting, or not 100% sure &#8230; <a href="http://thiranjith.com/2012/08/08/how-to-root-htc-one-x/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>Following on from the last article on <a href="http://thiranjith.com/2012/07/10/the-basics-of-rooting-android-phone/" title="Rooting your Android phone: The Basics" target="_blank">what does it mean to root your Android phone</a>, I thought of providing a step-by-step guide to root a HTC One X phone.</p>
<p><a href="http://thiranjith.com/wp-content/uploads/2012/08/HTC-One-X_root.jpg"><img src="http://thiranjith.com/wp-content/uploads/2012/08/HTC-One-X_root-300x150.jpg" alt="" title="How to root HTC One X Android Phone" width="300" height="150" class="alignright size-medium wp-image-413" /></a></p>
<p><span id="more-385"></span><br />
If you are new to rooting, or not 100% sure what it means, I highly recommend to read <a href="http://thiranjith.com/2012/07/10/the-basics-of-rooting-android-phone/" title="Rooting your Android phone: The Basics" target="_blank">this article</a> before proceeding ahead.</p>
<p><strong>Disclaimer: </strong> Rooting and installing custom ROMs void your phone&#8217;s warranty in most scenarios. I am not responsible for any damages that may incur (however unlikely it may be) by following the instructions on this blog post. It is important to keep in mind that <b>rooting your phone does not wipe out your stock ROM</b> (e.g. HTC Sense for HTC devices, TouchWiz for Samsung etc). Bottom line is <strong>only attempt to root your phone if you are comfortable with it;</strong> otherwise find someone who knows what they are doing rather than potentially bricking your phone :)</p>
<p>Having said that, I successfully managed to root several HTC One X phones by following the steps outlined below.</p>
<h2>Rooting the HTC One X</h2>
<ol>
<li><u>Unlocking the <strong><em>Bootloader</em></strong></u>: Android bootloader can be thought of as a protected area of your phone that controls what you can do with it. First, we need to unlock this portion so we can unlock other parts of the phone (i.e. root your phone). You can read more about bootloaders <a href="http://www.androidcentral.com/what-is-android-bootloader" title="What is Android Bootloader" target="_blank">here</a>.<br />
<br/></p>
<p><strong>WARNING</strong>: Unlocking the bootloader will wipe all the application-data on your phone (e.g. application-specific information stored within the phone, SMS messages etc.). Please back up all your data before proceeding ahead</p>
<ol>
<li>Download HTC Sync (from <a href="http://www.htc.com/www/software/htc-sync-manager/#download" title="HTC Sync" target="_blank">here</a>) and ensure you have the latest Java runtime (from <a href="http://java.com/" title="Java Runtime" target="_blank">http://java.com/</a>) and Android SDK (can be downloaded and installed from <a href="http://developer.android.com/sdk/index.html" title="Android SDK" target="_blank"></a>).</li>
<li>Go to <a href="http://www.htcdev.com" title="HTC Developer Centre" target="_blank">HTC Dev Centre</a> and register (you need to enter a valid email address here because HTC will use that to send your unlock code)</li>
<li>Go to <a href="http://www.htcdev.com/bootloader/" title="HTC Unlock Bootloader" target="_blank">http://www.htcdev.com/bootloader/</a></li>
<li>Select &#8216;<code>All other supported devices</code>&#8216; option for <em>Supported Devices</em>, and click &#8216;<strong>Begin Unlock Bootloader</strong>&#8216; button</li>
<li>Follow the steps exactly as instructed (there are about 12 steps and the process won&#8217;t take more than 5 minutes)</li>
<p>Once you are done with all the steps, you will have an Unlocked Bootloader.
</ol>
</li>
<li><u>Installing the <strong>ClockwordMod</strong> image </u>: Even after unlocking, the default bootloader for HTC lacks features that allows us to root and install custom ROMs. That is where <strong>ClockwordMod</strong> comes in handy. It is a custom bootloader that allows you to root your phone, install custom ROMs, patch ROMs, backup your phone (similar to ISO images on PCs) and restore your backups.
<ol>
<li>Download the latest ClockwordMod image from <a href="http://download.clockworkmod.com/recoveries/recovery-clockwork-touch-5.8.4.0-endeavoru.img " title="ClockworkMod recovery" target="_blank">http://download.clockworkmod.com/recoveries/recovery-clockwork-touch-5.8.4.0-endeavoru.img</a></li>
<li>Please the <code>recovery-clockwork-touch-5.8.4.0-endeavoru.img</code> file in the folder containing <code>fastboot.exe</code> file (from step #1 above in unlocking the bootloader). The remainder of this article will refer to this folder as <code>C:\%HTC_ROOT_FILES%</code></li>
<li>Ensure your phone is not connected to the PC, and reboot your HTC One X phone (i.e. press on the power button, and then select &#8216;Reboot&#8217;) while holding down the &#8216;Volume Down&#8217; button. This will take you to the &#8220;HBOOT&#8221; screen (bunch of options in a white background).</li>
<li>Use the Volume up and down keys to navigate up/down and select &#8216;<strong><em>FASTBOOT</em></strong>&#8216; option. Press the phone&#8217;s power button to select the option.</li>
<li>Connect your phone to the PC using the USB cable</li>
<li>Open a command prompt at <code>C:\%HTC_ROOT_FILES%</code> folder and type the following and press enter:<br/><br />
<code>fastboot flash recovery recovery-clockwork-touch-5.8.4.0-endeavoru.img</code><br/> This will install the ClockworkMod recovery onto your phone.</li>
<li>Reboot the phone, once the above command is successfully completed. You will have to go through setting up the phone/wi-fi at this point, but don&#8217;t spend too much time on it if you are planning to install a custom ROM after rooting the phone.</li>
</ol>
</li>
<li><u>Granting <em>super-user</em> permissions (a.k.a. rooting your HTC One-X)</u> : We rare almost done with rooting your phone and at the final step.
<ol>
<li>Download ClockworkMod compatible SuperUser installer from <a href="http://forum.xda-developers.com/attachment.php?attachmentid=1144696&#038;d=1340268294" title="XDA Developers" target="_blank">XDA Developers forum</a>, and save the file on to your phone&#8217;s external memory. More information about the superuser app can be found at <a href="http://forum.xda-developers.com/showthread.php?t=1538053" title="Superuser for HTC One X" target="_blank">http://forum.xda-developers.com/showthread.php?t=1538053</a>.</li>
<li>Reboot the phone to the &#8220;HBOOT&#8221; menu (Power down and restart while holding the volume down key)</li>
<li>Select &#8220;<em>Recovery</em>&#8221; and press the Power button to make the selection. After few seconds (5-30s) you will go to the <em>&#8216;ClockworkMod Recovery&#8217; console</em>.</li>
<li>Make a backup of your phone at this point (so we can recover it back if something goes wrong) by going to &#8216;<strong>backup and restore</strong>&#8216; and following the appropriate steps. (use volume up/down to navigate between different items and power button to make the selection)</li>
<li>Once the backup is completed, go back to the <em>&#8216;ClockworkMod Recovery&#8217; console</em></li>
<li>Select &#8216;Install zip from sd card&#8217; </li>
<li>Select &#8216;Choose zip from sdcard&#8217;</li>
<li>Now you will be presented with the sdcard content for your phone. Navigate the folders and select the <code>superuser zip file</code> you copied earlier. At this point you will be presented with a confirmation screen. Select &#8216;<em>YES/Install</em>&#8216; to proceed ahead. Wait until the process is done (can take few minutes)</li>
<li>Once the superuser app is installed, navigate back to the main clockwordmod console.</li>
<li>You can either create another backup at this point, or simply select &#8216;<strong>reboot system now</strong>&#8216;. Rebooting first time could take several minutes (ranging between 2-5 minutes), so be patient.</li>
</ol>
</li>
</ol>
<p>That is it! Now you have a rooted <strong>HTC One X</strong>!</p>
<p>Here are few links to get you started on making good use of your newly rooted device. Remember to make a new backup through CWM before installing any new ROM, theme or a mod. You can find an extensive list of themes and mods from <a href="http://forum.xda-developers.com/showthread.php?t=1728965" title="List of themes and mods for HTC One X" target="_blank">here</a>.</p>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2012/08/08/how-to-root-htc-one-x/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rooting your Android phone: The Basics</title>
		<link>http://thiranjith.com/2012/07/10/the-basics-of-rooting-android-phone/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-basics-of-rooting-android-phone</link>
		<comments>http://thiranjith.com/2012/07/10/the-basics-of-rooting-android-phone/#comments</comments>
		<pubDate>Tue, 10 Jul 2012 04:14:26 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[benefits of rooting]]></category>
		<category><![CDATA[root android]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=391</guid>
		<description><![CDATA[<p>If you own an Android phone, chances are that you&#8217;ve heard of rooting. However, most of us are bit reluctant to tinker too much with our phones because of the risks involved and are not 100% sure exactly what we &#8230; <a href="http://thiranjith.com/2012/07/10/the-basics-of-rooting-android-phone/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>If you own an Android phone, chances are that you&#8217;ve heard of <strong>rooting</strong>. However, most of us are bit reluctant to tinker too much with our phones because of the risks involved and are not 100% sure exactly what we are getting into by rooting android phones.</p>
<p><a href="http://thiranjith.com/wp-content/uploads/2012/07/root-android.jpg"><img src="http://thiranjith.com/wp-content/uploads/2012/07/images1.jpg" alt="Android Rooting Basics" title="How to Root Android" width="214" height="235" class="alignright size-full wp-image-399" /></a></p>
<p>I thought of answering some basic questions such as <strong>what exactly is &#8220;Rooting&#8221;?</strong>, and <strong>what benefits do you get by rooting your phone</strong>? Hopefully this will clear some misconceptions floating around and give you a clearer picture about what rooting is all about.</p>
<p><span id="more-391"></span></p>
<h2>What is &#8220;rooting&#8221;?</h2>
<p>Android is a Linux-based operating system, and have different <strong>&#8220;user classes&#8221;</strong> that have different privileges that determines what you can do with your phone. As a normal Android user, you have access to install/uninstall applications, work with certain hardware features like compass, camera, phone radio etc. and just work with it in general. However, you are restricted from interacting with the low-level operating system features that require elevated &#8220;access&#8221; (rights).</p>
<p>Without getting too technical, <strong>rooting</strong> your Android phone can be thought of as <em>the act of elevating your system privileges so you can do things that your carrier and/or the phone manufacturer doesn&#8217;t allow you to do</em>. Essentially, rooting your phone gives you the opportunity to do things that were previously not possible (i.e. restricted) with your Android phone.</p>
<p>It is important to keep in mind that <b>rooting your phone does not wipe out your stock ROM</b> (e.g. HTC Sense for HTC devices, TouchWiz for Samsung etc); you will still get to use the stock ROM you had before rooting the phone. Often you can still get carrier updates after rooting the phone (at least in my experience with Nexus One and Samsung Galaxy S2), but this will vary depending on your phone model.</p>
<h2>Why would you &#8220;want&#8221; to root your Android phone?</h2>
<p>The restrictions imposed by carriers and phone manufactures are good enough (or tolerable) for majority of the users to just get on with their normal day-to-day tasks with their smart-phones. Majority of the time these restrictions ensure you can&#8217;t crash/brick your phone by accident.</p>
<p>However, there are quite a few functions and features that are severely limited or even blocked, due to the &#8220;locking&#8221; by the mobile carriers and/or phone manufacturers. I&#8217;ve listed a few of those carrier/manufacturer imposed limitations based on the experiences of my friends:</p>
<ul>
<li>Inability for customers to move between carriers, or even between different plans (within the same carrier), due to &#8220;locked&#8221; handsets (specially in USA)</li>
<li>Inability to change the boot-up animations as these are set to display the carrier logo in most cases.</li>
<li>Software limitations imposed to boost carrier specific offerings. These include blocked VOIP applications (e.g. Skype, Google Voice etc.) and tethering.</li>
</ul>
<p>A more in-depth discussion about these limitations can be found <a href="http://wiki.cyanogenmod.com/wiki/What_is_CyanogenMod" title="Restrictions on stock devices by carriers and device manufacturers" target="_blank">here</a>.</p>
<p>The way to get around this is to acquire &#8216;root&#8217; (i.e. Administrator) access on the device, so you can install/modify/fix/break anything you want.</p>
<h2>Benefits of rooting Android phone</h2>
<p><strong>Rooting your Android device</strong> helps you to get around aforementioned issues, as well as allowing you to do a plethora of other interesting things with your phone, that are otherwise not possible. This is because rooting allows you to install/modify/fix/break anything you want on your phone!</p>
<p>Few of the other things you can do, after rooting your phone includes:</p>
<ul>
<li>Ability to install custom ROMs that provides different experience/benefit to your stock ROM. Pros/cons of custom ROMs is a whole different topic and I will save it for another post!</li>
<li>Ability to install applications that allows you to do things that are not possible on non-rooted devices. These include:
<ul>
<li>Ability to browse the whole folder structure of your phone (as opposed to just the external memory) using apps such as<a href="https://play.google.com/store/apps/details?id=com.speedsoftware.rootexplorer" title="Root Explorer" target="_blank">Root Explorer</a>.</li>
<li>Ability to back up and restore your applications (including the local data/state) using apps such as <a href="https://play.google.com/store/apps/details?id=com.keramidas.TitaniumBackup" title="Titanium Backup Lite" target="_blank">Titanium Backup</a>.</li>
<li>Ability to overclock your phone to get some extra oomph out of those low-mid range phones (e.g. <a href="https://play.google.com/store/apps/details?id=com.mhuang.overclocking" title="SetCPU for Root Users" target="_blank">SetCPU for Root Users</a>)</li>
<li>Synchronize your phone&#8217;s clock with NTP servers using apps like <a href="https://play.google.com/store/apps/details?id=ru.org.amip.ClockSync" title="ClockSync" target="_blank">ClockSync</a>.</li>
</ul>
</li>
<li>Ability to get rid of bloat-ware applications that are otherwise impossible to get rid of; specially if you are on a pre-ICS (Android 4+) ROM.</li>
<li>Connect to your phone via SSH/ADB to recover any data if your phone doesn&#8217;t start-up properly</li>
</ul>
<p>In short, rooting opens up a whole set of possibilities and options while giving you complete control of the system</p>
<h2>Drawbacks of rooting your phone</h2>
<p>There are two main drawbacks/risks of rooting Android phones:</p>
<ol>
<li>It almost always voids the phone warranty (I&#8217;d like to hear about exceptions to this!)</li>
<li>Not correctly completing the rooting process can cause anything from just wiping all your data on the phone (messages, contacts etc.) to completely bricking it! So make sure you read the rooting instructions VERY carefully and read reviews before following instructions to root your phone.</li>
</ol>
<h2>Where to from here?</h2>
<p>So have you decided to give it a go and root your phone? The first step is to find out <strong>how to root your phone</strong>. The instructions often vary from one model to another and the best place to check is the <a href="http://forum.xda-developers.com/index.php" title="XDA-Developer Forums" target="_blank">xda-developer forums</a>. Go to the thread marked &#8220;Android Development&#8221; for your phone model. It is an active community and you are sure to find instructions for rooting and installing custom ROMs on popular phone models. Otherwise Google is your friend!</p>
<p>Here are few links to <strong>popular Android applications for rooted devices</strong>:</p>
<ul>
<li>A series of articles presenting <a href="http://www.androidpolice.com/2012/01/16/top-android-apps-every-rooted-user-should-know-about-part-5-apps-34-41/" title="Top Androidid Apps for Rooted Users" target="_blank">top applications for rooted devices</a></li>
<li><a href="http://www.geek.com/articles/mobile/the-best-root-apps-for-android-20120227" title="The best apps for rooted Android phones" target="_blank">10 applications highly recommended for rooted users</a></li>
<li>Another list of 10 applications for rooted Android devices by <a href="http://lifehacker.com/5806135/the-10-best-android-apps-that-make-rooting-your-phone-worth-the-hassle" title="The 10 Best Android Apps that Make Rooting Your Phone Worth the Hassle" target="_blank">Life Hacker</a></li>
</ul>
<p>NOTE: I take no responsibility for any damage caused by rooting your phone. Please do it at your own risk or get someone who knows what they are doing to root your phone!</p>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2012/07/10/the-basics-of-rooting-android-phone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to manually disable WordPress plugins</title>
		<link>http://thiranjith.com/2012/03/03/how-to-manually-disable-wordpress-plugins/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-manually-disable-wordpress-plugins</link>
		<comments>http://thiranjith.com/2012/03/03/how-to-manually-disable-wordpress-plugins/#comments</comments>
		<pubDate>Fri, 02 Mar 2012 19:17:41 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Guides]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[manual plugin delete]]></category>
		<category><![CDATA[remove wordpress plugin]]></category>
		<category><![CDATA[uninstall plugin]]></category>
		<category><![CDATA[wordpress plugins]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=380</guid>
		<description><![CDATA[<p>I recently tried to update one of my WordPress plugins that somehow managed to bring my whole site down. I was unable to go to wp-admin to disable the plugin. I had to first disable all the WordPress plugins manually &#8230; <a href="http://thiranjith.com/2012/03/03/how-to-manually-disable-wordpress-plugins/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>I recently tried to update one of my WordPress plugins that somehow managed to bring my whole site down. I was unable to go to wp-admin to disable the plugin. I had to first disable all the WordPress plugins manually (through phpMyAdmin on my server) so I can get to wp-admin page, and then reinstall the plugin that caused the problem.</p>
<p>The best thing about this approach is that you don&#8217;t lose your existing configuration settings for the WordPress plugins (except for the one that caused issues in the first place).</p>
<p>Here are the detailed steps on how I went about getting my site back up.<br />
<span id="more-380"></span></p>
<h3>1. Disable all the WordPress plugins manually</h3>
<ol>
<li>Go to the <strong>cPanel</strong> of your web-server, and click on <strong>phpMyAdmin</strong>.</li>
<li>Click on the database for your wordpress</li>
<li>All the wordpress plugins are specified in the <code>wp_options</code> table&#8217;s &#8216;<strong>active_plugins</strong>&#8216; row. We need to remove the entry for the problematic plugin from this row&#8217;s &#8216;option_value&#8217; column, so WordPress will disable all the plugins. Run the following sql statement to obtain the &#8216;active_plugins&#8217; row.<br />
<pre class="crayon-plain-tag"><code>SELECT option_value FROM  wp_options
      WHERE option_name LIKE '%active_plugins%'</code></pre><br />
You should get something like below that defines all the active plugins you had.<br />
<pre class="crayon-plain-tag"><code>a:9:{i:0;s:19:&quot;plugin1/plugin1.php&quot;;i:1;s:45:&quot;plugin2/plugin1.php&quot;;}</code></pre>
</li>
<li>Update the <strong>active_plugins</strong> after removing the value for the pulgin that caused issues from the value above. In my case it was plugin1, so the sql to update the row looked as follows:<br />
<pre class="crayon-plain-tag"><code>UPDATE  wp_options 
  SET option_value = 'a:9:{i:1;s:45:&quot;plugin2/plugin1.php&quot;;}' 
  WHERE wp_options.option_name = 'active_plugins';</code></pre></p>
<p>Note that I removed the part that says &#8220;<strong>i:0;s:19:&#8221;plugin1/plugin1.php&#8221;;</strong>&#8221; from the original result I got.
</li>
</ol>
<h3>2. Go to wp-admin section of your WordPress blog</h3>
<p>If you followed all the above steps, you should now be able to go back to your WordPress blog and get it to load without any errors. Navigate to the wp-admin page for your blog and login as the WordPress administrator.</p>
<h3>3. Re-enable all the plugins</h3>
<p>At this point, WordPress would have disabled all your other plugins.</p>
<ol>
<li>Go to <code>Plugins->Installed Plugins</code> section under your Dashboard</li>
<li>Activate all the plugins, except for the one that caused problems</li>
<li>Load the live site on a different browser/tab to make sure those plugins are workings</li>
</ol>
<h3>4. Fix the problematic plugin</h3>
<p>If you want to keep using that plugin, the best way is to just delete the plugin and reinstall it. The downside is you will have to reconfigure the plugin to suit your needs!</p>
<p>Let me know if you have used any other means to solve the same issue!</p>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2012/03/03/how-to-manually-disable-wordpress-plugins/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>How to prevent screen timeout in Android</title>
		<link>http://thiranjith.com/2012/02/22/android-prevent-screen-timeout/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=android-prevent-screen-timeout</link>
		<comments>http://thiranjith.com/2012/02/22/android-prevent-screen-timeout/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 19:43:33 +0000</pubDate>
		<dc:creator>Thiranjith Weerasinghe</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[screen timeout]]></category>
		<category><![CDATA[stop screen dimming]]></category>

		<guid isPermaLink="false">http://thiranjith.com/?p=371</guid>
		<description><![CDATA[<p>There are several mechanisms available for Android applications to stop the phone&#8217;s screen from being turned off. These methods override the default &#8216;screen timeout&#8217; behaviour of your phone (typically found under Settings -> Display), and will keep the screen on &#8230; <a href="http://thiranjith.com/2012/02/22/android-prevent-screen-timeout/">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></description>
			<content:encoded><![CDATA[<p>There are several mechanisms available for Android applications to stop the phone&#8217;s screen from being turned off. These methods override the default &#8216;screen timeout&#8217; behaviour of your phone (typically found under <code>Settings -> Display</code>), and will keep the screen on while your application is running.</p>
<p>I will be introducing two methods to stop the screen from being dimmed. The two methods provide means of accomplishing this depending on the current state of your application; i.e. whether it has an Activity on the foreground (visible on screen) or running on the background (as a Service).</p>
<ol>
<li>Use of <code>FLAG_KEEP_SCREEN_ON</code> option for your Activity.</li>
<li>Use of a WakeLock.</li>
</ol>
<p><span id="more-371"></span></p>
<h3>1. Use of FLAG_KEEP_SCREEN_ON option</h3>
<p>This is the recommended way to prevent screen timeout for an Android <a href="http://developer.android.com/reference/android/app/Activity.html" title="Activity SDK" target="_blank">Activity</a>. Doing so would keep your screen turned on as long as your Activity is visible (i.e. on the foreground).</p>
<p>The <strong>advantages of this method</strong> include:</p>
<ul>
<li>Do not need any special permissions to implement the solution</li>
<li>Gives you greater control by having the screen on only for selected Activities, rather than for the whole application.</li>
<li>A more power-efficient solution compared to alternate methods.</li>
<li>Developer does not have to explicitly manage screen visibility, as the behaviour will automatically be reverted back to default once the Activity is no longer visible on screen (e.g. user pressed the back button, or another application was opened on top).</li>
</ul>
<p>There are two ways that you can achieve this.</p>
<ol>
<li><b>Using <code>android:keepScreenOn</code> XML attribute on the Activity&#8217;s layout</b> (see line #5).
<p>You don&#8217;t have to do anything special in the Activity class. Another benefit of this particular method is that you can control screen timeout on a per View basis as opposed to per-Activity basis.</p>
<pre class="crayon-plain-tag"><code>&lt;!-- main_layout.xml file --&gt;
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout
  xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot;
  android:keepScreenOn = &quot;true&quot;
  android:orientation = &quot;vertical&quot;
  android:layout_width = &quot;fill_parent&quot;
  android:layout_height = &quot;fill_parent&quot;&gt;
  &lt;!-- other views ommitted for brievity --&gt;
&lt;/LinearLayout&gt;</code></pre>
<pre class="crayon-plain-tag"><code>public class MyActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);
		// ...
    }
}</code></pre><p><p>
</li>
<li><b>Using the <code>FLAG_KEEP_SCREEN_ON</code> flag within your Activity</b>
<p>You set up the flag in your Activity&#8217;s onCreate (or onStart depending on the desired effect) method to keep the screen on programatically. This allows you the option to easily switch back to the default screen timeout behaviour by invoking the stopForceScreenOn() method in the example below.</p>
<pre class="crayon-plain-tag"><code>&lt;!-- main_layout.xml file --&gt;
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout
  xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot;
  android:orientation = &quot;vertical&quot;
  android:layout_width = &quot;fill_parent&quot;
  android:layout_height = &quot;fill_parent&quot;&gt;
  &lt;!-- other views ommitted for brievity --&gt;
&lt;/LinearLayout&gt;</code></pre>
<pre class="crayon-plain-tag"><code>public class MyActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void stopForceScreenOn() {
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}</code></pre><p><p><p><p>
</li>
</ol>
<h3>2. Use of a WakeLock.</h3>
<p>A <a href="http://developer.android.com/reference/android/os/PowerManager.html" title="WakeLock" target="_blank">WakeLock</a> can be used by your application to turn the screen on (amongst other things), and keep it on until the WakeLock is released. <strong>Use of WakeLocks drain your battery life significantly</strong>. Therefore WakeLocks are only recommended to be held for short periods of time and must be released as soon as possible.</p>
<p>Moreover, use of a WakeLock is the only way to programatically turn the screen on when the phone is already sleeping (e.g. when responding to a message received over the web etc.).</p>
<p><strong>Using a WakeLock</strong> is a 3-step process consisting of the following:</p>
<ol>
<li>Grant the application permission to use WakeLocks by including the following in your manifest<br />
        <pre class="crayon-plain-tag"><code>&lt;uses-permission android:name=&quot;android.permission.WAKE_LOCK&quot; /&gt;</code></pre>
</li>
<li>Acquire a WakeLock.
<p>The code snippet below demonstrate how to obtain a WakeLock that will cause the screen to be lit (but dimmed) until the lock is released.</p><pre class="crayon-plain-tag"><code>PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
	PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, &quot;My Tag&quot;);
	wl.acquire();</code></pre><p></li>
<li>Release the WakeLock once no longer necessary. The screen will continue to stay on until it is released.</p><pre class="crayon-plain-tag"><code>wl.release();</code></pre><p></li>
</ol>
<p>Please refer to the <a href="http://developer.android.com/reference/android/os/Poanager.html" title="WakeLocks" target="_blank">Android SDK documentation</a> if you want to know more about WakeLocks.</p>
<h3>Conclusions:</h3>
<p>As a rule of thumb, don&#8217;t forcefully keep the screen on for long periods unless you have a visible Activity. Having the screen on will use more power regardless of the method you use to accomplish it!</p>
<p>Due to the high power consumption by WakeLocks, I would recommend using them only via background <a href="http://developer.android.com/reference/android/app/Service.html" title="Service SDK" target="_blank">Services</a> to give a cue to the user. You must ensure that the WakeLock is released soon to prevent battery drain.</p>
<p>If you want to keep the screen on when running an Activity, always use the <code>FLAG_KEEP_SCREEN_ON</code> flag (either in your Activity or in XML layout).</p>
<p>As always, please let me know if you have any questions and your feedback is always appreciated!</p>
<p>Thanks!</p>
<p><a rel="author" href="http://thiranjith.com/author/thiranjith/">Thiranjith Weerasinghe</a></p>]]></content:encoded>
			<wfw:commentRss>http://thiranjith.com/2012/02/22/android-prevent-screen-timeout/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
