^ Click Here

Friday, September 14, 2012

Sending HTML (as) Mail through Java (Spring)

[This is basically an extension of the earlier post Sending Simple Mail through Java (Spring) ]

In this mail we will try to send HTML(and CSS) as mails.....please refer to the earlier post about simple mail as there is no point in repeating things, Moreover this would contain an example which would build on earlier post example. Just to make sure we don't miss anything.

So basically no changes in the Spring application context Spring.xml file.

<bean class="org.springframework.mail.javamail.JavaMailSenderImpl" id="mailSender">
    <property name="host" value="smtp.gmail.com">
    <property name="port" value="587">
    <property name="username" value="username">
    <property name="password" value="password">
    <property name="javaMailProperties">
       <props>
           <prop key="mail.smtp.auth">true</prop>
           <prop key="mail.smtp.starttls.enable">true</prop>
       </props>
    </property>
</bean>
But to send HTML in mail SimpleMailMessage won't work. That is actually too simple for the task. Hence for this we would need a MimeMessage. MimeMessage is very much different from SimpleMailMessage however one of the biggest and more likable advantage we have with MimeMessage is MimeMessageHelper.


package mimeSendMail;

import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MimeSendMail
{

 @Autowired
 private JavaMailSender mailSender; 

public void sendMimeMessage(String from, String[] to, String subject, String msg) throws Exception{
  MimeMessage mime = this.mailSender.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(mime, true);
  helper.setFrom(from);
  helper.setTo(to);
  helper.setSubject(subject);
  String htmlText = "<div style='background:#00FA9A;text-align:center;"+
                "font-size:12pt;font-weight:bold;color:#800000;padding:10px;'>"+
                "That feeling when......<br /><br />"+
                "You miss your spectacles while looking for your spectacles....<br /><br />"+
                "The person whom you secretly dislike, helps you......<br /><br />"+
                "The person whom you have crush on seems happy all the time....<br /><br />"+
                "the beggar recognizes you and stops asking for penny from you since you have never given....<br /><br />"+ 
                "</div>";
    helper.setText(htmlText,true);
    this.mailSender.send(mime);
    }
}

I guess this should do it. Yes, the HTML and inline css really looks nasty but I didn't find any way to transfer the css file to the mailing server and I doubt if there are any. Hence we have to live with inline css also a blessing in disguise about inline css is that it overrides other pre-defined css properties.

Here we saw that  from the JavaMailSender we create a MimeMessage and with that in turn we create MimeMessageHelper which does various task( much beyond rendering HTML text).

Now we are ready to give it a test.

package mimeSendMail;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mimeSendMail.MimeSendMail;

public class SendMailTest {

  @Test 
 public void mailTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("mimeSendMail/SpringMail.xml");

        MimeSendMail mm = (MimeSendMail) context.getBean("mimeSendMail");
        mm.sendMail("sender@gmail.com",
        new String[]{"recepient1@gmail.com","recepient2@rediffmail.com"},
        "Hello Friend", 
        "This is a test mail");
 } 
}

(Yeah I know the parameter msg is not being used and its redundant, you can get rid of that.)
Hope this helps.

Saturday, September 1, 2012

jQuery : Showing the text in typing (typewriter) effect

I was trying for it and came out with an idea so that we can show the text and messages as someone is typing it (of course that's an illusion like much of other things).

So here it goes. You have a text message and you want to show it with the effect, first of all we need to break the sentence for each single letter or alphabet and then would need to put it one after another with certain time-difference. the logic seems simple.

So here is the primary function for it :-

function demoTypeWriting(){
  var text = "Our whole theory of education is based on the absurd notion that we must learn to swim on land before tackling the water."
  var textArray = text.split("");
  $('div#resultDiv').append('<div id="typeText"></div>');
  timer = setInterval( function(){writeText(textArray)}, 500 ); 
}

Once it's done, I would provide for the function which will actually execute the task of typing the text :-

function writeText(textArray){
    if(textArray.length > 0){
    console.log(textArray[0]);
    $('div#newText').focus().append(textArray[0]);
    textArray.splice(0,1);
    }
    else{
        clearInterval(timer);
    }
}

So as you can see I am doing nothing great I am putting first element into the designated div and since it's already has been put, I am removing it from the array, So that next element can be put. Finally when array is empty I am stopping the timer. 

Try it here :-

Your Text:
Time Difference :

Result : -

Sunday, August 26, 2012

Sending Simple Mail through Java (Spring)

Seriously, there are plenty of examples for this available on net and mine isn't any different in that respect (well not this one). So here we go...

I am using a maven project but you can do it without that also though it would be bit pain to download the jar by yourself and putting them in buildpath.....still the concept that matters.

so first of all the dependency needed to be added is (I assume there is already a spring core, context and junit test dependency available).

<!-- Java Mail API -->
    <dependency>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
     <version>1.4.5</version>
    </dependency>

Secondly, since I am using maven and spring, I would define a bean in the Spring configuration xml file.

<bean class="org.springframework.mail.javamail.JavaMailSenderImpl" id="mailSender">
    <property name="host" value="smtp.gmail.com">
    <property name="port" value="587">
    <property name="username" value="username">
    <property name="password" value="password">
    <property name="javaMailProperties">
       <props>
           <prop key="mail.smtp.auth">true</prop>
           <prop key="mail.smtp.starttls.enable">true</prop>
       </props>
    </property>
</bean>

Now our java mail sender bean is ready (I don't need to tell that put your username and password value in the properties) we have define a gmail host smtp.gmail.com and port is 587 because that's the port gmail uses for smtp (though 25 is a default port for smtp). also we need to turn on few properties like auth and tls. but that's about configuration.

Now we will prepare for using this mailSender bean to send a simple message.

So here is my class for that -

package simpleSendMail;
 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
 
@Component
public class SendMail
{
    @Autowired
    private MailSender mailSender;
 
 public void sendMail(String from, String[] to, String subject, String msg) {
  SimpleMailMessage message = new SimpleMailMessage();
  message.setFrom(from);
  message.setTo(to);
  message.setSubject(subject);
  message.setText(msg);
  mailSender.send(message); 
 }
}

As you see I have autowired the mailSender bean to be used here, instead of it you very well can define this class as a bean and in xml configuration file link mailSender bean to the property of this one....if that is the case don't forget to put a setter......maybe this will help.

So as you can see there is a method which takes parameter for from, to addresses and subject and text to be sent then initiates the object of SimpleMessage class , sets the value and with our mailSender it sends that SimpleMessage

below is the Test class for that.

package simpleSendMail;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SendMailTest {

  @Test 
 public void mailTest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("simpleSendMail/SpringMail.xml");

       SendMail mm = (SendMail) context.getBean("sendMail");
           mm.sendMail("sender@gmail.com",
        new String[]{"recepient1@gmail.com","recepient2@rediffmail.com"},
        "Hello Friend", 
        "This is a test mail");
 } 
}

Again in test method you will provide valid mail addresses for to and from option

This might( and most surely) would fail if you are behind some proxy or firewall which doesn't let you use the specified port directly and blocks it considering it a threat. (Solution? I am still trying to find out.)

Thursday, August 9, 2012

[fixed] jQuery UI datepicker showing calendar when setting date.

For showing, choosing date jQuery UI datepicker is a great plugin, it provides a lot of functionality. However I feel it's little short on events, yet enough to fulfill almost all need of a basic application.

I was using that however I found an issue......with a few logic I was updating a date field which have a date picker when another field with datepicker was updated.

Problem : the primary datepicker was is visible and secondary is well say gets visible only when user wants. Since I was updating the secondary even when it was hidden.....it popped a calendar at the bottom of the page which of course was an annoying issue since it didn't use to disappear until and unless user clicks on some other datepicker enabled field.

I figured it out that the problem was with datepicker setDate function...I was using

$('.date-pick').datepicker('setDate', newDate)  //where date is a js date object.

I found that there is a hide function in datepicker, I tried that but it couldn't solve the problem

$('.date-pick').datepicker('setDate', newDate).datepicker('hide')   //failed miserably.

Hence I started to google it out......but didn't really got a satisfactory solution, but found out that few other people were facing the same problem. I got a hint from some site then I started looking into the datepicker js (I certainly am not a js expert).

there in the _setDateDatepicker function after setting the date value in the target it was calling _updateDatepicker which I assumed was popping the datepicker calendar but since the target was hidden it couldn't get the exact position hence it showed the calendar on the bottom left of the page.

So I commented that _updateDatepicker function out and it stopped popping the calendar while setting the date.



Monday, June 25, 2012

Creating a table in MySQL

Frankly, lots of tutorials and you can easily gather info regarding this with google......

Still I am putting it simply with an example and then defining the parts in it so that it can be understood easily.......Suppose you have to create a table 'employee' in MySQL......

CREATE TABLE IF NOT EXISTS EMPLOYEE (
        id INT(20) NOT NULL AUTO_INCREMENT UNIQUE PRIMARY KEY,
 email VARCHAR(50) NOT NULL UNIQUE,
 PASSWORD VARCHAR(40),
 NAME VARCHAR(50),
 dob DATETIME DEFAULT NULL,
 sex ENUM("M","F","N") DEFAULT "N",
 STATUS ENUM("Single","Married","Complicated","Divorced","Relationship","Widowed","Engaged","Undisclosed") DEFAULT "Undisclosed",
 TYPE ENUM("Admin","Registered","Unregistered","Anonymous") DEFAULT "Registered",
 department_id INT(20),
 is_deleted ENUM("True","False") DEFAULT "False",
 created_date TIMESTAMP DEFAULT '0000-00-00 00:00:00',
 modified_date TIMESTAMP DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
 
 FOREIGN KEY (department_id) REFERENCES department(id)
) ENGINE = INNODB;

Now Let's see it line by line

CREATE TABLE IF NOT EXISTS EMPLOYEE
          - it is self-explanatory this only creates the table when there is no table in the database with the same table name, if we just use CREATE TABLE tableName and suppose we already have a table in the database with the same table name, it will throw an error. Hence using 'IF NOT EXISTS' we prevent that error and also its a nice practice.

id INT(20) NOT NULL AUTO_INCREMENT UNIQUE PRIMARY KEY,
             - id is the column name its of type int with range 20 i.e. an int with 20 digit. the id should not be null i.e. insuring a legitimate value,
AUTO_INCREMENT is assigning MySQL to take care of increasing the id automatically so that we don't have to insert id explicitly and it vanishes the chance of duplicacies of id as while manually entering you might try to enter an id which is already there.
UNIQUE is used to ascertain that for each employee there should be a unique id however with AUTO_INCREMENT we are already fulfilling that condition yet from a developer's point of view its desirable to apply such condition.
PRIMARY KEY is used to tell that this column would be used as the primary key for this table.

email VARCHAR(50) NOT NULL UNIQUE,
              -email is the name of the column. the type is varchar which is short form of variable character, variable character can contain number or special character like @ which is needed while storing email with domain name. NOT NULL again make sure that no employee data should be there without an email. UNIQUE is to make sure that all employee should have a unique email id, hence this constraint is legitimate and necessary here since it helps us in having an organized, transparent and clean data in the table.

dob DATETIME DEFAULT NULL,
             -dob is short for date of birth, the data type is DATETIME and if no value is specified while insertion, by default it would take NULL as value. note that even if we don't specify it will take null as a default.

sex ENUM("M","F","N") DEFAULT "N",
             -for column sex we are using ENUM which contains three values "M" short for Male, "F" short for Female and "N" for Not Provided. Default is "N" hence when sex is not specified for an employee, it would by default take "N" as value.

created_date TIMESTAMP DEFAULT '0000-00-00 00:00:00',
        -created date should be a time stamp type and if not specified it would take 0000-00-00 00:00:00 value. note that while inserting you can use sysdate() in the query as it is to put the timestamp while creating the row.

modified_date TIMESTAMP DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
            -modified_date same like created_date should be a timestamp type and has a default 0000-00-00 00:00:00 value. however it has an extra clause ON UPDATE CURRENT_TIMESTAMP. This take the tough task of automatically updating the timestamp whenever the row is updated so that we don't have to specify that in query. An important point to note that you can't have more than one instance where you can use CURRENT_TIMESTAMP i.e. only one column will have this clause of ON UPDATE CURRENT_TIMESTAMP.

FOREIGN KEY (department_id) REFERENCES department(id)
             -department_id is a column in the table with type int, with this line we are assuring that department_id is actually a FOREIGN KEY which references the 'id' column of 'department' table in the same database. Hence it is actually linking of the employee table with department table where each employee's department data can be retrieved by mapping the department_id with the id in department table. Not only it links and makes it more organized it makes sure that you don't delete a row from department table if that row id is being used in employee table for any employee, hence it helps us from committing accidental deletes and makes the tables clean and healthy.

 ENGINE = INNODB;
              -not much on this it specifies as which MySQL engine to use for this table. More on MySQL engines here.

Hope this helps.

Thursday, March 29, 2012

get a random element from Set or Map

To get a random element from a list is quite easy......you just have to get the element t the nth position where n is a random number. But A Set is an unordered collection so there is no question of any definite element at definite position.

In this situation the way to get a random element from a Set might not have a straightforward way.......But the thing that can be done is iterate through the set and get the nth element where n is a random number. Conceptually it's the same as getting a random element from a List or array.


public String getRandomId(Set<String> idSet){
  int Size = idSet.size();
  int item = new Random().nextInt(Size);
  return (String) idSet.toArray()[item];
 }

 
Above method will return a random String from a Set of String........

Now suppose there is a Map with a String type as key and anything else say an Object as value...for example


Map<String,User> userMap = new HashMap<String,User>();

where User  is a Class and userMap holds the map between String id as key and user object as value.......to get a random user from this map we will use the above method in the example


String randomId = this.getRandomId(userMap.keySet());
User randomUser = userMap.get(randomId);

Hence we can get a random elements through this method. we just got a set of String of keys of the map and then used the previous getRandomId method to get a random key and got the corresponding value from the map.

Hope it helps.....

Saturday, March 17, 2012

Autowiring with annotation and autodiscovering Example

We have seen the examples where Autowiring (with .xml) was done. It's sort of magical comprehensibility of Spring Framework where it by itself chooses the proper candidate and connect it to the respective beans

In last example it was autowiring with configuration in xml file, Now we will see it with annotation and autodiscovering. Autodiscovering is meant to be the setting where beans are auto discovered by Spring Framework through Classes and the annotations are used for setting the value and autowiring.

I made a package named "annotationAutowire" and inside that I put the same Classes which were there in the previous example of Spring Basic. The only difference that this time the classes are annotated.

the Class Person.java

package annotationAutowire;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Person {
 @Value("Rahul")
 private String name;
 private IAnimal animal;
 
 public void setName(String name) {
  this.name = name;
 }
 public String getName() {
  return name;
 }
 public IAnimal getAnimal() {
  return animal;
 }
 @Autowired
 @Qualifier("dog")
 public void setAnimal(IAnimal animal) {
  this.animal = animal;
 }
 public String toString() {
  return name+" has a "+animal.toString();
 }
}


the interface IAnimal.java

package annotationAutowire;

public interface IAnimal {
 public void play();
}

the Class Dog.java

package annotationAutowire;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Dog implements IAnimal {
 @Value("Doug")
 private String name;
 public void play() {
  // TODO Auto-generated method stub
  System.out.println("Playing with "+name);
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String toString() {
  return " Dog with name "+name;
 }
}

the Class Cat.java

package annotationAutowire;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Cat implements IAnimal {
 
 private String name;
 public void play() {
  // TODO Auto-generated method stub
  System.out.println("Playing with "+name);
 }
 public String getName() {
  return name;
 }
 @Value("jejebel")
 public void setName(String name) {
  this.name = name;
 }
 public String toString() {
  return " Cat with name "+name;
 }
}


The annotation used are

@Component - use for declaring the instance of the class as bean, equivalent to bean tag in .xml file
@Autowired - declares that the element is autowired, equivalent to "autowire" attribute in xml file. The autowiring rules are unchanged. It could be placed at the declaration in the class as well as at the setter method.
@Qualifier - this annotation is used to tell that which component would qualify for autowiring, It can be related to autowire-candidate attribute in .xml file. it's safe to provide one to help in avoiding later conflicts.
@Value - this annotation is used to pass the value as String, it is the equivalent of property and p namespace equivalent in .xml file and can be placed at declaration as well as at setter method.

the config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<context:component-scan base-package="annotationAutowire"></context:component-scan>
</beans>


the context:component-scan is used for autodiscovering it will discover all the component (through @Component annotation) in the explicitly directed base-package annotationAutowire and while creating bean through those component it will do the job of autowiring with the help of @Autowired and @Qualifier annotations
Hence like earlier examples we didn't need to define bean and pass the values through property and p namespace. This all was taken care by annotations.
Element : component-scan
Scans the classpath for annotated components that will be auto- registered as Spring beans. By default, the Spring-provided @Component, @Repository, @Service, and @Controller stereotypes will be detected. Note: This tag implies the effects of the 'annotation-config' tag, activating @Required, @Autowired, @PostConstruct, @PreDestroy, @Resource, @PersistenceContext and @PersistenceUnit annotations in the component classes, which is usually desired for autodetected components (without external configuration). Turn off the 'annotation-config' attribute to deactivate this default behavior, for example in order to use custom BeanPostProcessor definitions for handling those annotations. Note: You may use placeholders in package paths, but only resolved against system properties (analogous to resource paths). A component scan results in new bean definition being registered; Spring's PropertyPlaceholderConfigurer will apply to those bean definitions just like to regular bean definitions, but it won't apply to the component scan settings themselves.
Content Model : (include-filter*, exclude-filter*)

the test Class PersonTest.java

package pkg;

import annotationAutowire.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonTest {
 @Test
 public void vehicleTest(){
  ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
  Person person = (Person) context.getBean("person");
  System.out.println(person);
 }
}

The Structure finally is


junit test result without doubt should be "Rahul has a  Dog with name Doug". because the qualifier is set to "dog".......and it can be changed to "cat" to get the autowiring of animal with cat component/bean.

Hope it helps.
 

Thursday, March 15, 2012

Spring Autowiring types with examples

 [ All the examples in this post are basically an extension from the previous post of Spring Basic ]

Autowiring is a feature in Spring through which we can pass the reference of any dependent bean automatically.......This is a step where we are telling the Spring framework to take care of the dependencies.
In that case when Application Context is created the Spring Framework will search for the beans on which it is dependent on according to set guidelines and if and when it finds the bean it will inject that automatically hence we no further need to take care of passing the reference.
Controls whether bean properties are "autowired". This is an automagical process in which bean references don't need to be coded explicitly in the XML bean definition file, but rather the Spring container works out dependencies. There are 4 modes: 1. "no" The traditional Spring default. No automagical wiring. Bean references must be defined in the XML file via the element (or "ref" attribute). We recommend this in most cases as it makes documentation more explicit. Note that this default mode also allows for annotation- driven autowiring, if activated. "no" refers to externally driven autowiring only, not affecting any autowiring demands that the bean class itself expresses. 2. "byName" Autowiring by property name. If a bean of class Cat exposes a "dog" property, Spring will try to set this to the value of the bean "dog" in the current container. If there is no matching bean by name, nothing special happens. 3. "byType" Autowiring if there is exactly one bean of the property type in the container. If there is more than one, a fatal error is raised, and you cannot use byType autowiring for that bean. If there is none, nothing special happens. 4. "constructor" Analogous to "byType" for constructor arguments. If there is not exactly one bean of the constructor argument type in the bean factory, a fatal error is raised. Note that explicit dependencies, i.e. "property" and "constructor-arg" elements, always override autowiring. Note: This attribute will not be inherited by child bean definitions. Hence, it needs to be specified per concrete bean definition

What did I mean by "set guidelines"?? for Spring Framework to find the correct bean we must set some rules.............well nothing speaks better than example....Hence going with our previous example

Our config.xml file will be

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


<bean class="pkg.Person" id="person" p:name="Rahul" autowire="byType">   
</bean>
<bean class="pkg.Dog" id="Dog" p:name="Doug" autowire-candidate="false"></bean>
<bean class="pkg.Cat" id="Cat" p:name="Jejebel"> 
 </bean></beans>
Note that the autowiring is "byType" , it simply means in the Person Class the type of "animal" is IAnimal......Hence the Spring framework in the Application Context will search for all beans with type IAnimal and will inject(connect) it to the animal and hence it's autowired. We don't need to explicitly pass the reference of any bean for animal property as in Spring Basic Example.

Now the question arises what if it finds more than one bean which have type IAnimal as in our case "Dog" and "Cat" both are of type IAnimal.........It certainly would throw an error due to indecision for which bean to use something like - "org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person' defined in class path resource [config.xml]: Unsatisfied dependency expressed through bean property 'animal': : No unique bean of type [pkg.IAnimal] is defined: expected single matching bean but found 2: [Dog, Cat]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [pkg.IAnimal] is defined: expected single matching bean but found 2: [Dog, Cat]".

If we would have used byName this problem won't have been there since two beans can't have same name(id) more on it later.........but we are not using that.
the solution is using an autowire-candidate property on beans as the bean "Dog" have autowire-candidate as false which simply means that this bean is not available for autowiring that simply means that only bean "Cat" is available for autowiring.
Indicates whether or not this bean should be considered when looking for matching candidates to satisfy another bean's autowiring requirements. Note that this does not affect explicit references by name, which will get resolved even if the specified bean is not marked as an autowire candidate.

Now when we run our test class it will give an output "Rahul has a  Cat with name Jejebel" 

It could be tedious to provide the kind of autowire for many beans specially when you are following a definite norm.......like you want all the beans to be autowired with "byName". Spring has provided the facility, all you need to do is in the configuration xml file set the default autowire as "byName". point to keep in mind that it will only work for one configuration file (you can have multiple) and not for the full application context. So you can organize all your same type autowired bean in one configuration file and set the default for that very xml file

test will again give you the same result .

But what If you need to have a default-autowire as "byType" in your configuration file but there are a few exceptions which needs to be autowired as "byName". Well in that case you can override the default autowiring just by specifically declaring it for the respective bean as "byName".

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd"
          default-autowire="byType">
   
<bean class="pkg.Person" id="person" p:name="Rahul">  
</bean>
<bean class="pkg.Dog" id="Dog" p:name="Doug" autowire-candidate="false"></bean>
<bean class="pkg.Cat" id="Cat" p:name="Jejebel">
</bean></beans>

Not just that you still can use the (older style) property with ref attribute for passing the dependency even if you are using an autowire tag on it. Hence its flexible.

Let's talk about the kind of autowiring

What we saw in the earlier example was "byType". have a look at the whole bunch :-

 > no - no autowiring should be done on the particular bean and the dependency
must be passed explicitly through "ref" attribute.

 > byNameAttempts to match all properties of the autowired bean with beans
that have the same name (or ID) as the properties. Properties for which there’s
no matching bean will remain unwired.

 > byTypeAttempts to match all properties of the autowired bean with beans
whose types are assignable to the properties. Properties for which there’s no
matching bean will remain unwired.

 > constructorTries to match up a constructor of the autowired bean with
beans whose types are assignable to the constructor arguments.

 > autodetectAttempts to apply constructor autowiring first. If that fails,
byType will be tried.


We have already seen the example of autowire as "byType"

now let's see an example with autowire equal to "byName"

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


<bean class="pkg.Person" id="person" p:name="Rahul" autowire="byName">  
</bean>
<bean class="pkg.Dog" id="animal" p:name="Doug"></bean>
<bean class="pkg.Cat" id="Cat" p:name="Jejebel">
</bean></beans>

run the test again and it will output "Rahul has a  Dog with name Doug".

Thing to notice is that the name of bean "Dog" has been changed to "animal" on purpose, this way the the IAnimal type "animal" variable of class Person is mapped with the bean named "animal" and hence the dependency is autowired by Spring Framework according to the name.

Hence when the application context is created the framework search for the bean named "animal" and inject it into the bean "person" since the autowiring is "byName"

Now let's see the autowiring by constructor......to display this I would need to alter the class as I need to add a constructor to the Person class

the Person Class

public class Person {
 private String name;
 private IAnimal animal;
 
 public Person(IAnimal animal) {
  this.animal = animal;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getName() {
  return name;
 }
 public IAnimal getAnimal() {
  return animal;
 }
 public String toString() {
  // TODO Auto-generated method stub
  return name+" has a "+animal.toString();
 }

changes are that there are no setter for IAnimal type animal.......instead it is set with the constructor.....in the constructor the reference is passed as an argument.

config.xml

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


<bean class="pkg.Person" id="person" p:name="Rahul" autowire="constructor">  
</bean>
<bean class="pkg.Dog" id="Dog" p:name="Doug" autowire-candidate="false"></bean>

<bean class="pkg.Cat" id="Cat" p:name="Jejebel">
</bean></beans>

Run the test and it will print "Rahul has a  Cat with name Jejebel".

Hence it is clear that when autowire is constructor.......Spring framework will search for the constructor with argument type as IAnimal and then will search for the bean type "IAnimal" and then passes that bean to set animal.

autowire-candidate="false" is used for the same reason as for it was used in autowire byType.

I am not providing any example of autowire as "autodetect" since this is nothing but a combination of autowire by constructor and byType respectively i.e. it looks for constructor with argument type and if there is none it looks for the type and searches the bean accordingly.


Well this is not all.....we still have "autowire with annotation" and autodiscover features....................but that in other post......

Thursday, March 8, 2012

Sticky columns/headers (Freeze pane) in tables through jQuery

Many times you have seen that the columns or headers freezes when you scroll horizontally or vertically respectively in a table. It looks rather cool but more than that its very useful hence nowhere you loses the track on any cell as which column and which header it belongs to irrespective of where the cell is in large table.
Let's see what can be done

the css


#resultTable{
    width:1000px;
    height:500px;
    clear:both;
    overflow:auto;
    position:relative;
}
.sticky-col-table{
    background-color: #eee;
    margin-left:0px !important;
}
.sticky-row-table {
    background-color: #eee;
    margin-top:0px !important;
}

.scrollTable{

    border:1px solid red;
    margin-top:5px;
    text-align:center;
}
.scrollTable td,.scrollTable th{
    width:60px;
    padding:5px;
    border:1px solid green;
}
now in the body let's put this structure


<div id="condDiv">
Columns : <input type="text" id="inputColumn" value="50"/> <br />
Rows : <input type="text" id="inputRow" value="50"/><br />
<input type="button" value="Create Table" onclick="return val_table();"/>
</div><br />
<div id="resultTable"  onscroll="movestickyColumn(this)">
<div id="sticky-column" style="position:absolute;display:none;"> </div>
<div id="sticky-row" style="position:absolute;display:none;"> </div>
</div>
let me describe it a bit in condDiv div I have two input elements where a person can provide the number of rows and columns for creating a dynamic table by clicking on the create Table button

the resultTable div is the div which will hold the dynamic table created and on scrolling of the div the function movestickyColumn(this) is called with passing the div object to it.

also note that it holds two empty and hidden div sticky-column and sticky-row (idea is to hold the frozen part of table in these divs).

Now the script part one by one, first for creating dynamic table we will have functions as follow

 validations -


function val_table(){
    var row= $('#condDiv #inputRow').val();
    var column = $('#condDiv #inputColumn').val();
    if(typeof row == "undefined" || row == null || row == "" || row <= 0 || isNaN(row) || typeof column == "undefined" || column == null || column == "" || column <= 0 || isNaN(column)){
        alert("Please provide valid positive value for rows and columns");
        return false;
        }
    else if(row>500 || column>500){
        alert("The column or row can not be more than 500");
        return false;
    }
    else{
        if($("#resultTable #myTable").length > 0){
            $("#resultTable #myTable").remove();
            }
        $("#resultTable").append(create_table(column,row));
        stickyColumnNew(2);
        stickyRow();
        }
}

first of all I am validating the number of row and columns provided in the input field, if it is I am calling three functions

for creating table


function create_table(column,row){
    var tableArray = [];
  
    var tableHead = [];
    var tableBody = [];
    tableHead.push("<thead><tr>");
    tableBody.push("<tbody>");
    var count = 0;
    for(ro=0; ro<row; ro++){  
        tableBody.push("<tr>");
            for(col=0; col<column; col++){
                if(ro==0){
                        tableHead.push("<th>Head "+(col+1)+"</th>")
                    }
                if((count%column) == 0){
                tableBody.push("<td> cell-"+(count+1)+" row-"+(ro+1)+"</td>");
                }
                else{
                    tableBody.push("<td> cell-"+(count+1)+"</td>");
                    }
                    count++;
                }
        }
    tableHead.push("</tr></thead>");
    tableBody.push("</tbody>");
    tableArray.push("<table id='myTable' class='scrollTable'>"+tableHead.join("")+tableBody.join("")+"</table>");
    return tableArray.join("");
}

then for getting the frozen columns to be formed in the sticky-column div, function stickyColumnNew(2) is called. note that I am passing 2 as an argument to freeze first 2 columns, you can pass more or less.


function stickyColumnNew(col) {
    $("#sticky-column").html('');
    // var trlength = $('table.table_sorter tbody tr').length;      
    var documentFragment =[];
    documentFragment.push('<table class="sticky-col-table scrollTable">');
    var docHead = [];
    docHead.push("<thead><tr>");
    var docBody = [];
    docBody.push("<tbody>")
    var count = 0;
    $("#myTable thead tr th").each(function(){
        if(count < col){
        docHead.push("<th style='height:"+$(this).outerHeight()+";'>"+$(this).html()+"</th>");  //use outerHeight() to get the height with padding, border and margin
        }
        count++;
    });
    docHead.push("</tr></thead>");
    $("#myTable tbody tr").each(function(){
    docBody.push("<tr>")
        if(col >= 1){
            docBody.push("<td style='height:"+$(this).find('td:first').outerHeight()+";'>"+$(this).find('td:first').html()+"</td>");
        }
        if(col >= 2){
        for(val=2; val<=col; val++){
            docBody.push("<td>"+$(this).find('td:nth-child('+val+')').html()+"</td>");
            }
        }
        docBody.push("</tr>")
    });
    docBody.push("</tbody>");
    documentFragment.push(docHead.join("")+docBody.join("")+'</table>');
    $("#sticky-column").append(documentFragment.join(''));  
    }

Basically I am creating a dummy table with only the 2 columns I have to freeze, It's cell should have the same height and content as the original table and I am simply putting that table in sticky-column div

In the same fashion I will create the table with dummy header with function stickyRow


function stickyRow() {
    $("#sticky-row").html('');
    // var trlength = $('table.table_sorter tbody tr').length;      
    var documentFragment =[];
    documentFragment.push('<table class="sticky-row-table scrollTable">');
    var docHead = [];
    docHead.push("<thead><tr>");
    $("#myTable thead tr th").each(function(){
      
        docHead.push("<th style='height:"+$(this).outerHeight()+";'><div style='width:"+$(this).width()+";'>"+$(this).html()+"</div></th>");  //use outerHeight() to get the height with padding, border and margin
      
    });
    docHead.push("</tr></thead>");
    documentFragment.push(docHead.join("")+'</table>');
    $("#sticky-row").append(documentFragment.join(''));
    }

Now the only part left is the movestickyColumn on the div


function movestickyColumn(tableDiv) {
    posX = tableDiv.scrollLeft;
    posY = tableDiv.scrollTop;
    if(posX > 50) {
        $('table.sticky-col-table,#sticky-column').css('display','block');
        $('table.sticky-col-table,#sticky-column').css('left',posX+'px');
    }
    else{
        $('table.sticky-col-table,#sticky-column').css('display','none');
        }
      
    if(posY > 50){
    console.log(posY);
        $('table.sticky-row-table,#sticky-row').css('display','block');
        $('table.sticky-row-table,#sticky-row').css('top',posY+'px');
    }
    else{
        $('table.sticky-row-table,#sticky-row').css('display','none');
    }  
}

So actually I am checking that as soon as the vertical or horizontal scroll crosses the 50px margin I am displaying the sticky-row and sticky-column divs respectively and accordingly.

feel free to play, customize or enhance upon it

hope it helps.

Try it here : -

[As far as I have checked there is some problem as in firefox header row width is not aligned and in chrome the columns height are not aligned. I guess some conflict with blogger css and css I am using. Trying to find the solution. However independently I have checked in both browser as working fine.]  



Columns :
Rows :

Wednesday, March 7, 2012

getting the HTML tags on jsp from a variable without turning into special characters

While working today I came across a strange situation.......

the requirement was something like I have to dynamically get some html elements and contents and put them in a variable which then I was supposed to put in a .jsp file.

It had to be dynamic so that the jsp would render different in different condition. Everything was working okay as supposed to but the dynamic HTML element which I was getting in String format was coming in such a way that it turned all the HTML tags in special characters.

i.e. <br /> was coming like &lt;br /&gt;, So eventually while getting rendered in jsp page instead of it being a hypertext it was actually special characters and in browser all the tags were visible.

Hence if in my jsp if there is
<div id="fixedDiv">
<b>Try this</b>
<c:out value="${myHtml}" />
</div>

and in my java code if there was -

String myHtmlVal = "<div id="variableDiv"><p><input type="text"/>Fill Something</p></div>";
response.add("myHtml",myHtmlVal);

then on browser it was showing this instead of proper rendering of hypertext tags -

Try this
<div id="variableDiv"><p><input type="text"/>Fill Something</p></div>

this was because the c:out was giving the value as-

&lt;div id="variableDiv"&gt;&lt;p&gt;&lt;input type="text"\/&gt;Fill Something&lt;\/p&gt;&lt;/div&gt;

Someone told me that I need to get it encoded and then decoded by url encoder or something but it was only getting more weird.......

However the help was here

after sometime what actually worked was this -

String myHtmlVal = "<div id="variableDiv"><p><input type="text"/>Fill Something</p></div>";
response.add("myHtml",StringEscapeUtils.unescapeHtml(myHtmlVal));

this unescapeHtml helped in preserving the hypertext values from turning into special character.

Also note that in the reverse case if you have to show the tags on browser but instead it's working as hypertext you can achieve it by StringEscapeUtils.escapeHtml(myHtmlVal); method.

Hope it helps

Saturday, March 3, 2012

Spring p:namespace example

Continuing with what we learnt in the Spring Basic we will move on to other functionality

for now our example would be same as the basic example i.e.

Person.java
IAnimal.java
Dog.java
Cat.java

Now we will see the p:namespace option in the Spring config file config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"     <!-- This line is required for p:namespace to work -->
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="person" class="pkg.Person" p:name="Rahul"> 
    <property name="animal" ref="Dog"/>    
</bean>

<bean id="Dog" class="pkg.Dog" p:name="Doug"/>
<bean id="Cat" class="pkg.Cat" p:name="Jejebel"/>

</beans>

If we run the test now it will print the same "Rahul has a Dog with name Doug"....So as you can see the third line initializes the p namespace function through which we get rid of extra property tag in .xml which made the file heavy.
as for p namespace does the same thing which property tag does, it passes the value to the setter method and it's more readable.

To make it more clear if the Person class has an integer age property, then we can pass avalue through p namespace as p:age="32"

But unfortunately we can't pass reference through p namespace. Hence still where we need to pass the reference we are passing other bean we still have to go with property tag.

Do we have anything where we can pass the reference to other bean without property tag?
The answer fortunately is "Yes" however that's a totally unique functionality and hence much more important than p namespace, It's called "Autowiring"

Tuesday, February 28, 2012

Spring Basic Example

I am providing a very basic example of Spring :-

Firstly I created a "Maven project"

Inside there is a person class person.java

package pkg;

public class Person {
    
    private String name;
    private IAnimal animal;
    
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public IAnimal getAnimal() {
        return animal;
    }
    public void setAnimal(IAnimal animal) {
        this.animal = animal;
    }
    public String toString() {
        return name+" has a "+animal.toString();
    }
}

the Interface IAnimal.java

package pkg;

public interface IAnimal {
    public void play();
}

the animal Dog.java

package pkg;

public class Dog implements IAnimal {
    private String name;
    public void play() {
        System.out.println("Playing with "+name);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String toString() {
        return " Dog with name "+name;
    }

}

the animal Cat.java

Tuesday, February 21, 2012

Starting/Stopping a timer (stopwatch) in jQuery/javascript

First of all we need to have a HTML container where we can define hour, minute and seconds. the different counter i.e. the values of hour, minute or second are put in div with id counterHour, counterMin and counterSec as can be seen below.
 <div>
Counter : &nbsp;</div>
<div id="counterHour" style="float: left;">
0</div>
<div style="float: left;">
&nbsp; Hours &nbsp;</div>
<div id="counterMin" style="float: left;">
0</div>
<div style="float: left;">
&nbsp; minutes &nbsp;</div>
<div id="counterSec" style="float: left;">
0</div>
<div style="float: left;">
&nbsp; seconds &nbsp;</div>

Also we need a button to start and stop the timer :

<input type="button" id="timer" class="start" value="Start Timer" onclick="check_timer()">
As we can see there is an onclick attribute and check_timer() function is attached to it. Hence in script (<script></script>) tag we will define below functions. 

function check_timer(){
 if($('#timer').hasClass('start')){
  $('#counterSec').fadeOut(500).html(0).fadeIn(500);
  $('#counterMin').fadeOut(500).html(0).fadeIn(500);
  $('#counterHour').fadeOut(500).html(0).fadeIn(500);
  $('#timer').val("Stop Timer");
  timer = setInterval ( "increaseCounter()", 1000 );
  $('#timer').removeClass('start')
 }
 else{
  if(typeof timer != "undefined"){
   clearInterval(timer);  
  }
  $('#timer').val("Start Timer");
  $('#timer').addClass('start')
 }
}
 
function increaseCounter(){
 
 var secVal ;
 var minVal ;
 secVal = parseInt($('#counterSec').html(),10) 
 minVal = parseInt($('#counterMin').html(),10)
 if(secVal != 59)
 $('#counterSec').html((secVal+1));
 else{
  if(minVal != 59){
   $('#counterMin').html((minVal+1)); 
  }
  else{
   $('#counterHour').html((parseInt($('#counterHour').html(),10)+1));
   $('#counterMin').html(0);
  }
  $('#counterSec').html(0);
 }
} 
in check_timer function I am checking if it's start timer or stop timer with the help of class 'start'. and I am alternately starting the set interval and stopping the set interval respectively with changing the value of button.

the logic is pretty simple...set an interval of one second to increase the value of counterSec div. Simultaneously I am checking if it is 60th second to increase the minute counter also if it is 60th minute to increase the hour counter.

Try it here :


Counter :  
0
  Hours  
0
  Minutes  
0
  Seconds  

Friday, February 17, 2012

Spring Security custom login page infinite redirect problem [Solved]

In Spring security we have an option so that we can define our own custom login page instead of one provided by Spring application context framework, this login page is used for determining the ROLE and authentication of certain user using the web application.

However I got into a problem using that when I tried the below security XML configuration :-


    <http>
            <intercept-url pattern="/**" access="ROLE_USER"/>
            <form-login login-page="/login"
            login-processing-url="/static/j_spring_security_check"
            authentication-failure-url="/login?error=t"/>
        </http>
       
        <authentication-manager>
         <authentication-provider>
          <user-service>
           <user name="rahul" password="rahul123" authorities="ROLE_ADMIN,ROLE_USER"/>
          </user-service>
         </authentication-provider>
        </authentication-manager>
       
when I hit the URL it was getting into an infinite redirect request for the login page, Firefox gave an error message like "Firefox has detected that the server is redirecting the request for this address in a way that will never complete".

When I looked into it I could get the real reason of the problem. Actually since the pattern for intercept-url security tag was "/**". It simply meant that any request which start with "/" should be intercepted and authenticated for ROLE_USER. For this authentication purpose Application Context searches for "/login" page but "/login" also start with "/" and hence it is again intercepted and should be authenticated for ROLE_USER for which it would again go for "/login". So it actually is a perfect example of Catch-22 situation. the request was kept redirecting to itself.

Now since we have understood the problem the solution should not be difficult. personally I think giving a pattern as "/**" has dangerous conundrum so instead one should use something like "/home/**" (or any other pattern which should not cover "/login")  for intercept-url so that "/login" should not be authenticated. doing this solved my problem.
     

        <intercept-url pattern="/home/**" access="ROLE_USER"/>

Budding Developer's Ground: SOQL - Learning the parent-child queries for Salesforce 1

Budding Developer's Ground: SOQL - Learning the parent-child queries for Salesforce 1

SOQL - Learning the parent-child queries for Salesforce 1

Well... Lots of time the need arises to show all the opportunities for one contact ( or similar parent child relationships )

Considering it, there are two major part of this first is the query part where we would call all the opportunities for the contacts
 and second is the concept of wrapper class which is actually the mapping of two or more entities.

In salesforce to have a join in a query you must have a parent-child relationship....it's pretty easy to understand that one parent can have many childs.

So Actually there can be two ways of writing a query

(i) Make the child as the central object of the query.
     ex. - [SELECT NAME, Contact.Account.NAME , Contact.Account.somefield FROM Contact];

(ii)Make the parent as the central object of the query.
     ex. - [SELECT NAME, somefield, (SELECT NAME FROM Account.Contacts) FROM Account];

Both the queries above will retrieve same data but in different format and both are used according to the need or requirements (ex - For which entity sorting etc. is needed).

Noticeable things are
  1.  while referring to parent the dot(.) notation is used (contact.account.name in first query).
  2.  while referring to child a subquery is used with the fields it is retrieving .
  3.  in second query the child subquery consist Account.Contacts (and not Account.Contact). Actually here the Contacts does not represent a object type instead it represents the relationship between the Account object type and Contact Object type.
  
Hence one important thing to note is that while referring to a child subquery we must use the name of the relationship and not the object.

P.S you can get the name of the relationship from looking into the 'wsdl' file (type="tns:queryResult" represent child relationship name
to be used in subquery).

Things which wouldn't work :

a> [SELECT * FROM Contact] . There is nothing like '*' in soql, you have to write the fieldnames you want to retrieve.

b> [SELECT id, name, (select name from Account.Contact where createdDate < 2010-01-01), (select name from Account.Contact where createdDate > 2010-12-31) FROM Account]
    You can't use two subqueries for same child relationship while retrieving.


c> [SELECT name,(select name,(select name from Opportunities) from Contacts) FROM Account], the subquery inside another subquery i.e. nested subqueries are not allowed.


   
Due to these reason you would have to frame the query according to your need.
   

This should be enough for the start, We would dwell into parent-child relationship query more in the next part.
   


Saturday, January 28, 2012

Showing Opportunities for each Contact (parent - child) through Map without using Wrapper Class

We can show map from controller on the visualforce page, We also can put one map inside another map or in other words nested map.

With the help of these two factors, I successfully showed the contact and corresponding opportunities without using the wrapper classes. Though it put some restriction however for
the purpose of showing all the opportunities corresponding to each Contact (or any parent - child relationship) it works fine.

The process is simple -
 -I created a map of Contact as key and another map of Opportunity with id as value say A.
 -I used a query which brings all the opportunities for Contacts.
 -Now in a loop get the list of opportunities for each Contact.
 -After checking if there are Opportunities put those Opportunities in a map with id say B.
 -And lastly the Contact and the map B was put into map A.



Visualforce Page :-

 <apex:page controller="MapClass" action="{!getValues}">
<apex:pageblock >
<apex:pageBlockTable value="{!checkMap}" var="con">
    <apex:column value="{!con.Name}"/>
    <apex:column headerValue="Opportunities">
        <apex:dataList value="{!checkMap[con]}" var="opp">
        <apex:outputField value="{!checkMap[con][opp].Name}"/>
        </apex:dataList>
    </apex:column>
    <apex:column value="{!con.Account.Name}"/>
    <apex:column value="{!con.createddate}"/>
   
</apex:pageBlockTable>
</apex:pageblock>
</apex:page>



Apex Class :-

public class MapClass{
  public transient Map<Contact,Map<id,Opportunity>> checkMap{get; set;}
  public void getValues(){
  checkMap  = new Map<Contact,Map<id,Opportunity>>();
  for(Contact s : Database.query('select id, name, Account.name, owner.Name,    createddate, (select id, name from Opportunities) from Contact')){
      List<Opportunity> opLi = s.getSobjects('Opportunities');
      map<id,Opportunity> opMap = new map<id,Opportunity>();
      if(opLi != null){
      for(Opportunity op: opLi){
      opMap.put(op.id,op);   
      }
      }
      checkMap.put(s,opMap);
  }   
}
}

 Last but not the least you can stretch this concept to look what else can be done. feel free to add on it.



Saturday, January 14, 2012

To get a list in different format as HTML / excel / pdf / word in Salesforce

More often than not we need to have an option where we can get a list in an excel or HTML or pdf format....specially for sending it in e-mails.

These formats are standards and presentable hence much desired most often than not.

I did an example where I can show a list of Contacts, Owner name and corresponding Accounts Name with the option to retrieve/download it in excel/HTML/pdf/word format (I tried for picture format also but it didn't work)

Things to notice are

- The file is downloaded with the current date in the name for the ease of distinguishing.

- In the controller the transient variable is being used so that it can show maximum number of records without the view-state error.

- The table is given different background colors for differentiation between rows but each format reads it differently so there is a variation.

Also this is just a raw presentation and a starter.....much can be improved upon this and different functionality or options can be added/modified into it.....

Click here for a demo of this.

The page (visualforce) code -