Tuesday 31 March 2015

JavasScript Remoting using VisualForce and Apex (SalesForce)

Remoting allows us to perform almost any apex logic via Javascript.

Let's consider Javascript remoting as similar as AJAX call done in normal websites built using PHP, ASP.NET or so.

So, let's see how we can do this.

In this demo, I have attempted to create a drop-down list having
options created dynamically based on the data from a custom object
and then calling a javascript function(at onchange event) which
refers to a remote action of the controller positionController written in apex.


The VisualForce Page Contains the code as below

<apex:page controller="poistionController" showHeader="false">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
//Function that calls the controller written in Apex and returns the required data.

function selectPosition(id){
 
var pos = document.getElementById(id).value;

    poistionController.getPositionDetails( pos,

    function(result, event){

         if (event.status && event.result) {

         // Creating the HTML content based on

         //the data returned from positionController and getPositionDetails method.

              var html = '<table>';

           html = html + '<tr><td>Position Name :</td>';

            html = html + '<td>'+event.result[0].Name+'</td></tr>';

            html = html + '<tr><td>Min Pay :</td>';

            html = html + '<td>'+'$'+event.result[0].Min_Pay__c+'</td></tr>';

            html = html + '<tr><td>Max Pay :</td>';

            html = html + '<td>'+'$'+event.result[0].Max_Pay__c+'</td></tr>';

            html = html + '</table>';

            $('#positionDetails').html(html);

      } else {

             alert(event.message);

      }

}, {escape:true});

}

 </script>

   <div align="center" width="550px">

      <h1>Congratulations</h1>

      This is my new Page : <b>VisualForce & Apex !!!</b><br />
  <apex:outputText value="Your maximum salary could be AT MAXIMUM {!pos.Max_Pay__c}"/>

      </b>

      <apex:form >

        <apex:selectList value="{!pos}" multiselect="false" size="1" id="positionTitle" onchange="selectPosition('{!$component.positionTitle}');">

         <apex:selectOptions value="{!options}"/>

         </apex:selectList>

      </apex:form>

   </div>

   <div id="positionDetails" align="center">

         <!-- Position details is displayed here. -->

   </div>

</apex:page>

 positionController contains codes as below.

global with sharing class poistionController {

      public Position__c pos{get;set;}
      public List<Position__c> title{get;set;}
      public List<Position__c> positions{get;set;}

      public poistionController() {

         pos = [select Max_Pay__c from Position__c where Name = 'Sr. Java Developer'];
      }
       /**

      * Method that creates the select option dynamically.

      **/

      public List<SelectOption> getOptions() {

          List<SelectOption> options = new List<SelectOption>();
          title = [select Position__c.Name from Position__c];
         //Creating an NULL option.
         options.add(new SelectOption('none','--Select--'));
         for( Position__c a :title ){

            options.add(new SelectOption(a.Name,a.Name));
         }
         return options;
      }

      /**

      * Remote action involved with Javascript remoting and is made global

      **/

      @RemoteAction
      global static Position__c[] getPositionDetails(String pos) {
          return [select Position__c.Name, Max_Pay__c, Min_Pay__c, Days_Open__c from Position__c WHERE                         Position__c.Name =: pos];

      }

}

In the above code for positionController, method named getOptions() is involved with creating options for drop-down list and getPositionDetails() is involved with fetching position details and acts as the remote action and is made global.

In the VisualForce page the javascript method selectPosition() refers to the remote action getPositionDetails() of positionController.

The portion of selectPosition() method in grey and italics is used for javascript remoting.

escape specifies whether the response from the Apex method will be escaped or not.

By default it's TRUE.

The syntax for javascript remoting is as given below,

[<namespace>.]<controller>.<method>([params...,] <callbackFunction>(result, event) {

     // callback function logic

}, {escape:true});

Here, namespace is optional and is required if the class comes from an installed package.

In the controller, the Apex method declaration must be preceded with @RemoteAction annotation as shown below.

@RemoteAction

global static String methodName(String objectName) {

   //Logic written in Apex.

}

The methods with @RemoteAction annotation must be global and static.

The response from the server is in JSON format.

For this demo, it's something like as given below.

[{"type":"rpc","tid":3,"action":"poistionController",

"method":"getPositionDetails","result":{"serId":1,

"value":[{"serId":2, "value":{"Days_Open__c":142,"Name":"Sr. PHP Developer",

"Max_Pay__c":2500000.00,"Id":"a0190000002RNUJAA4", "Min_Pay__c":1500000.00}}]}}]

Enable Google Talk Sidebar in Salesforce


Let's see how we can enable the google talk sidebar component in Salesforce.

Go to http://www.google.com/a to sign up your domain for Google apps.
Log in to your salesforce account.
Click on the user menu (Your name at top-right of the salesforce page.) > Setup > Administration Setup > Google Apps > Settings

Click on "Edit" in the "Configure Google Apps Domain" section and fill up the "Google App Administrative Contacts" and your "Google Apps Domain" input fields. Now click save.
Now, in the "Activate Google Apps Services" section click on "Edit" link next to "Google Talk Sidebar Component".

Select the two checkboxes "Add the Google Talk component to salesforce.com sidebar." & "I agree to the salesforce.com Terms of Use for Google Apps."


Similarly, we can enable other Google Apps like Gmail, Google Docs etc. in salesforce.

These are some of the already available features in salesforce.com and we need to enable them for use. :-)

Uploading a Document in Salesforce Using Visualforce Page


Some times we need to upload files such as image files,word document etc, and also need to use its reference to use it in our VF page .

In that case we have to follow these steps

In that case we have to follow these steps

Step 1: Click on the document Tab

Step 2: Select the file from your local system to upload & also choose the folder in which you want to save it

Step 3: Keep its reference as a record to use it, if you want to access it directly form record

Instead of following these above steps, we can do these in only one visual-force page.

In this tip we will be understanding the procedure to upload a file into "Documents" using a Visual-force Page.

Hence, this topic would only cover uploading a file to "Documents" under a folder you desire.

<apex:inputfile>
 is the tag that is used to upload a file.



Sample Code

 FileUpload : Sample Visual-force page


 <apex:page controller="FileUploadController" showHeader="true" standardStylesheets="false">

<head>

<script type="text/javascript">


function SelectFile( fileUrl )

{

// window.opener.SetUrl( url, width, height, alt);

parent.SetUrl( fileUrl ) ;

}

</script>

</head>

<apex:messages />

<apex:form >

<apex:inputFile value="{!document.body}" filename="{!document.name}"/>

<br />

<apex:commandButton value="save" action="{!doUpload}" />

</apex:form>

<apex:pageBlock rendered="{!hasImage}" >

<img src="{!url}" width="200" height="160" />

<script>

this.onload = function() {

SelectFile('{!url}');

}

</script>

</apex:pageBlock>

</apex:page>




FileUploadController: Apex Class


 public class FileUploadController{

public Document document {get; set;}

public String url {get; set;}

public boolean hasImage {get; set;}



public FileUpload() {

hasImage = false;

document = new document();

}


 public PageReference doUpload() {

if (document.body != null) {

System.debug('@@@@@@@@ document:' + document.name);

 if (document.name != null) {

System.debug('@@@@@@@@ doSave');

 Document d = document;

System.debug(document);

System.debug('@@@@@@@@ document name: '+d.name);

System.debug(d);



d.folderid = UserInfo.getUserId(); //store in Personal Documents


 /*
d.folderid
 = 'any other id you want here'; // Fetch Id dynamically by using [Select Id from Folder where Name='My Images'].*/

System.debug('@@@@@@@@ document folder id: '+d.folderid);

d.IsPublic = true;

 try {

insert d;

url = DocumentUtil.getInstance().getURL(d);

hasImage = true;

} catch (Exception e) {

ApexPages.addMessages(e);

url = '';

}

 d.body = null;

 System.debug('@@@@@@@@ document object id: '+d.id);

String url = DocumentUtil.getInstance(d).getURL();

System.debug('######## document content type: '+d.type);

}

 }

 PageReference page = new PageReference('/apex/FileUpload');

//page.setRedirect(true);

return page;

}

 static testmethod void testFileUpload() {

FileUpload fu = new FileUpload();

fu.doUpload();

 fu.document.Name = 'test1';

fu.document.Body = Blob.valueOf('test1');

 fu.doUpload();

 }

 }

How to Pass ID in Visualforce Pages

Apex Controller:-

public class Teamlist {
  
    
    public ApexPages.StandardSetController setTeam {
        get {
            if(setTeam == null) {
                setTeam = new ApexPages.StandardSetController(Database.getQueryLocator(
                      [select id, name from Team__c]));
            }
            return setTeam;
        }
        set;
    }
    
     public List<Team__c> getTeams() {
         return (List<Team__c>) setTeam.getRecords();
       }  
         
    public PageReference Go() {
      Id id = System.currentPageReference().getParameters().get('id');
      PageReference nextpage = new PageReference('/apex/CustomTeam?id='+id);
                return nextpage;
    }
  }

VisualForce Page:-

<apex:page controller="Teamlist" showHeader="false" title="false"> 
  <apex:form >
   <apex:tabPanel switchType="client" selectedTab="TabDetails" tabClass="activetab" inactiveTabClass="inactivetab">
        <apex:tab label="TEAM">
            <apex:pageBlock title="TEAMLIST">
                <apex:pageBlockTable value="{!teams}" var="t">
                    <apex:column headerValue="TEAM NAME">
                       <apex:outputPanel >
                            <apex:commandLink action="{!Go}">
                               {!t.name}<apex:param name="id" value="{!t.id}"/>
                            </apex:commandLink>
                       </apex:outputPanel>
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlock>
        </apex:tab>
   </apex:tabPanel>
  </apex:form>
</apex:page>



Here is a visualforce page containing a list of teams. What we want is after clicking a particular team name, it will go to a page where the details are displayed of that corresponding team. Here we are retrieving the team id using <apex:param name="id" value="{!t.id}"/> within commandLink where we defined the action.
Then we can observe that we defined that function in the apex controller for getting that id by System.currentPageReference().getParameters().get('id'); After that it is referenced in a different page with that id. It may be simple,but as a beginner I think it is an important thing to know.

How to use Inline Edit in a custom Visualforce UI Page?

Inline Edit
 We all know that we can edit the value of a field by going to the Edit Page,edit it and Save it using the Save button. But Salesforce     besides that provides an efficient of editing a value of a field from the detail page of a record OR from List View of records which is       very efficient for users and less time consuming. Just by double clicking on the Field Value a popup will open where we can edit the       value and save it. But Salesforce provides that inBuilt only in their Standard Pages. To create that in our Custom Visualforce Pages we   have to write code for that. Here is a small example of using INLINE EDIT in Visualforce Pages..


Visualforce Page 
   <!-- VisualForce Page Responsible for Entry of Customer Records -->
  <apex:page controller="CustomerEntryPageController">
    <apex:form>
      <apex:pageBlock title="Customer Information" >
         <apex:pageMessages />
         <!-- Display Save and Cancel Button -->
         <apex:pageBlockButtons >
            <apex:commandButton value="Save" id="saveButton" action="{!savingCustomerRecord}"/>
         </apex:pageBlockButtons>
         <!-- A PageBlockSection for Entry and Display Customer Values -->
         <apex:pageBlockSection title="Information" columns="2">
            <apex:outputField value="{!customerObj.Name}"/>
            <apex:outputField value="{!customerObj.Address__c}">
               <apex:inlineEditSupport showOnEdit="saveButton" event="ondblclick"/>  
            </apex:outputField>
         </apex:pageBlockSection>
      </apex:pageBlock>
   </apex:form>


Apex Class
/**
*@purpose : Apex Controller responsible for Entry of Customer Records
*@author :  Souvik
**/
public with sharing  class CustomerEntryPageController {
    public Customer__c customerObj{get;set;}
    String customerId{get;set;}
    public String message{get;set;}

    /**
    *@purpose : Constructor to fetch current Customer Record and its Action
    **/
   public CustomerEntryPageController () {
      message = '';
      // Fetching the Current Customer Id
      customerId = System.currentPageReference().getParameters().get('Id');
       if(cutomerId != NULL){
         customerObj = [SELECT Id,Name,Address__c FROM Customer__c WHERE id=:customerId];
      }
   }

   /**
    *@purpose : Method for Saving the Customer Object Record
    *@param : None
    *@return : PageReference to Standard Salesforce Record Detail Page
    **/
   public PageReference savingCustomerRecord(){
      try{
         upsert customerObj;
         PageReference nextpage= new PageReference('/'+customerObj.id);
           return nextpage;
      }
      catch(Exception e){
            message='Data Base error during saving...';
            ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR, message));
            return null;
        }
   }
}


Explanation
The Visualforce Page here is a Detail Page of a Customer Record means here field values are displayed in a noneditable state. Now if one wants to edit some specific field values(here for e.g Address__c) then he instead of going to the Edit Page he can edit that field value here only just by double clicking on that.

Record Types In Apex According To The Current User's Profile Availability

Record types allow you to offer different business processes, picklist values, and page layouts to different users.After creating record types for any
object you need to set the availability of that record type into the user profile.

Suppose you creates three record type of Account as 'Borrower','Investor' and 'Dealer'. And set the availability according to the profile:

Profile Name  Available Record Type
 Profile 1         Borrower,Investor,Dealer /** Profile1 can see the all record types.**/
 Profile 2         Borrower,Investor   /** Profile2 can only see the two record types.**/

Now you need to display record type name in VF page.For this we need to find out the name of recordTypes according to the current user's profile availability.
You can achieve it by  getRecordTypeInfos() method of Schema.DescribeSObjectResult given below:

List<String> recordTypeNameList = new List<String>();
/** Need to create list to collect record type name.**/
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
/** You need to change the object name according to your requirement.**/
List<Schema.RecordTypeInfo> RT = R.getRecordTypeInfos();
for( Schema.RecordTypeInfo recordType : RT )
{
if(recordType.isAvailable())
 { 
 /** Check if the recordtype is visible for the current user or not. **/
if(recordType.Name!='Master') {
recordTypeNameSet.add(recordType.Name);
 /** Collect the record type name in list. **/
    }
  }
}

Sending Mass Email Through Apex Controllers

This tip demonstrates how to send mass emails along with attachments(pdf/resources/assets etc) through Apex Controllers.
Apex Controllers

/**
*@purpose : Method for Creating an Attachment
*@param : None
*@return : PageReference to convertpdf Page
**/
public PageReference attachpdf() {

   //Parameters getting from the URL
    Id quoteId = ApexPages.currentPage().getParameters().get('quoteId');
    Id cId = ApexPages.currentPage().getParameters().get('cId');
    Quote quoteObj = [select id,name from Quote where id =:quoteId];

   //Referring from the Pdf page(The page which is rendered as PDF)
    PageReference pdfPage = Page.pdfPage;
    pdfPage.getParameters().put('id',quoteid);
    Blob pdfBlob = pdfPage.getContent();
 
   //Creating a Attachment
    Attachment attachmentObj = new Attachment(parentId = quoteObj.id, name=quoteObj.name + '.pdf', body = pdfBlob);
    INSERT attachmentObj;
    PageReference nextPage = new PageReference('/apex/convertpdf?cId='+cId+'qId='+quoteId);
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'PDF Attached Successfully'));
    return nextPage;
}


/**
*@purpose : Method for Sending Mass mail along with the Attachment
*@param : None
*@return : PageReference to convertpdf Page
**/
public PageReference sendEmail(){  

   //Parameters getting from the URL
   Id quoteId = ApexPages.currentPage().getParameters().get('quoteId');
   Id emailTemplate = ApexPages.currentPage().getParameters().get('emailTemplate');
   Id cId = ApexPages.currentPage().getParameters().get('cId');
   Id aId = ApexPages.currentPage().getParameters().get('aId');
  List<Contact> contactNames = [SELECT id, name FROM Contact WHERE AccountId =: aId];
   for (String obj : contactNames){
      contact = [SELECT Id,name,email FROM Contact WHERE name =:obj];
      for(Integer i=0; i < contact.size(); i++){

       //Initializing for Sending Mails(Written Single because of in a loop)
         Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

       //Initializing the Email Attachment
         List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

       //Attaching them to the mail by setting the parameters
         for (Attachment attachmentObj : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :quoteId]){
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
            efa.setFileName(attachmentObj.Name);
            efa.setBody(attachmentObj.Body);
            fileAttachments.add(efa);
         }

       //Setting the Template and Target Ids
         email.setFileAttachments(fileAttachments);
         email.setTargetObjectId(contact[i].Id);
         email.setTemplateId(emailTemplate.id);

       //Sending the Mail
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
      }
   }
   PageReference nextPage = new PageReference('/apex/convertpdf?quoteId='+quoteId+'&cId='+cId);
   ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Email Sent Successfully'));
   return nextPage;
}

IMPORTANT POINTS
1) setFileAttachments = Attaching the files to the Mail
2) setTargetObjectId = Setting the Target Ids(Contacts to whom the mail is to be send)
3) setTemplateId = Format of the Mail by setting the Template Format
4) Messaging.sendEmail = Sending the Mail

#Note: It is good to use "Messaging.SingleEmailMessage"  within a loop rather than "Messaging.MassEmailMessages".

Salesforce 2 Salesforce Data Migration

Salesforce to Salesforce Data Migration

There are several Data Migration tools in Salesforce which helps to migrate data swiftly from one salesforce org to another.
There is another mode of data transfer between two organisations is by S2S. This is a feature which is present within salesforce.com. In this tip we will discuss about S2S data migration.
It has some advantages as well as some disdvantages.

Advantages:
a) It helps to transfer data very quickly around 1000 data/3-4 secs.
b) The data which is shared between two organisations are automatically updated in the target organisation if there is some modification in the source organisation.

Disdavantages:
a) We know that we can set the value of audit fields of most of the standard objects and all custom objects only during first insert by enabling the feature from Salesforce.com support. But S2S feature doesn't expose the audit fields even after enabling it. This is a big fault in S2S.
b) We cannot migrate data of all standard objects through S2S connection. There are some specific standard objects whose data we can transfer.
c) S2S connection cannot be created between Production and Sandbox organisation or between Developer and Sandbox organisation.

Things to Set up for S2S migration:

a) First of all we need to enable Salesforce to Salesforce connection in both the source and target organisations.
b) Then we need to enable the Connection tab.
c) In the connections tab we need to create a new connection by selecting an account and contact from the lookup in the source organisation.
d) After that a link will be sent to the contact's email by clicking which, we open the target organisation and create the connection between the source and target.
e) Now that all the connections are ready we can start sharing the objects and fields the datas of which we need to transfer.
f) First we need to Publish the objects in the source organisation by checking them in the list.
g) In the target organisation we need to go the Subscribe/Unsubscribe section and need to accept the objects which are shared by the source organisation and we can check the auto-accept checkbox which implies that data will be auto-accepted after those will be shared by the source organisation.
h) Then in the source organisation we need to check the fields of the objects which we want to share so that those can be visible in the target.
i) Then we can map the fields shared by source organisation with those in the target organisation.

Data Transfer with Lookups:

We can transfer data between two organisations in two modes:

a) Manually - We can see a button in the list view of all objects "Forward to Connections". We can click this button by checking the datas we need to transfer from the list and then select the connection name to which the data needs to be transferred. We can observe that there are checkboxes present below regarding transfer of the related datas. If we select those the related lookup object datas will be transferred as well. In this way we can transfer related datas as well.
For e.g When transferring accounts, there will be a checkbox below mentioning "Send Related Contacts". By checking that the related contacts will also be transferred along with the accounts.

#Note: Manual S2S data transfer is best when the data amount is not huge.

b) Apex Script - When there is large amount of data, then data transfer through script will be the best option. What we can do is to create a batch Apex and transfer the data mentioning the batch size and by selecting the connection name through query. We can set the lookups through script as well.
For e.g When transferring accounts we can mention in script to transfer the related datas as well i.e contact, case etc by
acc.relatedList(Contact,Case);
We can also make lookp up through script.
Suppose account is already transferred to target organisation. Now while transferring contacts we can make lookup with parent account by
String accountId = con.AccountId;
con.parentRecordId(accountId);
But remember this parent record lookup assignment are helpful when there is only one lookup present. But when an object has many lookups then we have to send the oldprimarykey and oldparentid through formula field to the target organisation and then in target organisation we have to write script to assign them.

How to Get Current Page URL in Apex

Sometime we need to get current page URL in apex ,Then we need to use Apexpages.currentPage() methods provided by salesforce.
There is following step which you need to follow:
Step 1:
First call 'getHeaders()' method which return a map of the request headers,where the key string contains the name of the header, and the value string contains the value of the header.
After that get the 'Host' key value from that map.
String hostVal  = ApexPages.currentPage().getHeaders().get('Host');
It gives like 'c.ap1.visual.force.com',etc.



Step 2:
Second,you need to call 'getUrl()' method which returns the relative URL associated with the PageReference,including any query string parameters and anchors.
String urlVal = Apexpages.currentPage().getUrl();
It returns as '/apex/pagename','/apex/pageName?check=false' etc.
Step 3: After that add these two values return in step1 and step2 with 'https://'
The whole method is given below:
public void getPageURL() {
    String hostVal  = ApexPages.currentPage().getHeaders().get('Host');
    String urlVal = Apexpages.currentPage().getUrl();
    String URLL = 'https://' + hostVal+ urlVal;
}

Scheduler Class in Apex

In this Tip, "http://xml.utrace.de/?query=" is used as external web service , which takes global IP as its request parameter (e.g http://xml.utrace.de/?query=111.93.167.67). Then it returns XML data as its response .
The format of XML response for above example is as follows
<?xml version="1.0" encoding="iso-8859-1" ?>
<results>
<result>
  <ip>111.93.167.67</ip>
  <host />
  <isp>Tata Teleservices ISP</isp>
  <org>Tata Teleservices ISP</org>
  <region>Calcutta</region>
  <countrycode>IN</countrycode>
  <latitude>22.569700241089</latitude>
  <longitude>88.369697570801</longitude>
  <queries>2</queries>
  </result>
  </results>

Apex Class

public class OrgInfo_XmlStreamReader {

public String org{get;set;}
public List<String> XMLData{get;set;}

public OrgInfo_XmlStreamReader(){
XMLData=new List<String>();

}

public List<String> getOrganisationInfo(String ip){ 
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://xml.utrace.de/?query='+ip);
req.setMethod('GET');
HttpResponse res = http.send(req);

// Log the XML content
String xmlContent=res.getBody();
System.debug(res.getBody());
System.debug('#####XmlStreamReader ##11##');
// Generate the HTTP response as an XML stream

XmlStreamReader reader = res.getXmlStreamReader();
System.debug('##########XML DATA##########'+res.getXmlStreamReader());

XMLData=XMLParser(res.getBody());
return XMLData;
}

public List<String> XMLParser(String strXml){
System.debug('####Inside XMLParser Method########'+strXml);
List<String> orgInfo=new List<String>();
Dom.Document doc = new Dom.Document();
doc.load(strXml);
//Retrieve the root element for this document.
Dom.XMLNode Envelope = doc.getRootElement();
Dom.XMLNode Body= Envelope.getChildElements()[0];
string user_createResult = '';

for(Dom.XMLNode child : Body.getChildElements()) {
orgInfo.add(child .getText());
}
return orgInfo;
}

}

 Call the method getOrganisationInfo(String ip) from the Class , where you need the parsed data.
This method will return a String List containingIP,HOST,ISP,ORGANISATION NAME,REGION,COUNTRY CODE,LATITUDE,LONGITUDE, and NUMBER OF QUERIES from YOU . This information is in sequential manner inside the List(index 0,1,....n).

Note: Before Calling a external/remote site, please registered that site under
SetUP-->Security Control--> Remote Site Setting

References:- http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_xml_XmlStream_reader.htm

Monday 30 March 2015

Calling external WebService & parsing its XML Response using Salesforce's Apex

In this Tip, "http://xml.utrace.de/?query=" is used as external web service , which takes global IP as its request parameter (e.g http://xml.utrace.de/?query=111.93.167.67). Then it returns XML data as its response .
The format of XML response for above example is as follows
<?xml version="1.0" encoding="iso-8859-1" ?>
<results>
<result>
  <ip>111.93.167.67</ip>
  <host />
  <isp>Tata Teleservices ISP</isp>
  <org>Tata Teleservices ISP</org>
  <region>Calcutta</region>
  <countrycode>IN</countrycode>
  <latitude>22.569700241089</latitude>
  <longitude>88.369697570801</longitude>
  <queries>2</queries>
  </result>
  </results>

Apex Class

public class OrgInfo_XmlStreamReader {

public String org{get;set;}
public List<String> XMLData{get;set;}

public OrgInfo_XmlStreamReader(){
XMLData=new List<String>();

}

public List<String> getOrganisationInfo(String ip){ 
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://xml.utrace.de/?query='+ip);
req.setMethod('GET');
HttpResponse res = http.send(req);

// Log the XML content
String xmlContent=res.getBody();
System.debug(res.getBody());
System.debug('#####XmlStreamReader ##11##');
// Generate the HTTP response as an XML stream

XmlStreamReader reader = res.getXmlStreamReader();
System.debug('##########XML DATA##########'+res.getXmlStreamReader());

XMLData=XMLParser(res.getBody());
return XMLData;
}

public List<String> XMLParser(String strXml){
System.debug('####Inside XMLParser Method########'+strXml);
List<String> orgInfo=new List<String>();
Dom.Document doc = new Dom.Document();
doc.load(strXml);
//Retrieve the root element for this document.
Dom.XMLNode Envelope = doc.getRootElement();
Dom.XMLNode Body= Envelope.getChildElements()[0];
string user_createResult = '';

for(Dom.XMLNode child : Body.getChildElements()) {
orgInfo.add(child .getText());
}
return orgInfo;
}

}

 Call the method getOrganisationInfo(String ip) from the Class , where you need the parsed data.
This method will return a String List containingIP,HOST,ISP,ORGANISATION NAME,REGION,COUNTRY CODE,LATITUDE,LONGITUDE, and NUMBER OF QUERIES from YOU . This information is in sequential manner inside the List(index 0,1,....n).

Note: Before Calling a external/remote site, please registered that site under
SetUP-->Security Control--> Remote Site Setting

References:- http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_xml_XmlStream_reader.htm