Friday, May 19, 2017

Java PayPal API integration through proxy server

Java PayPal API integration through proxy server

Getting the below exception while integrating PayPal API with Java, based on the analysis the direct communication to the API is not enabled from the server and the communication should be directed via Proxy server.

09:10:50.525 [main] ERROR com.paypal.base.HttpConnection -  Retry  No : 1...
09:11:54.577 [main] ERROR com.paypal.base.HttpConnection - Caught exception while handling error response java.net.ConnectException: Connection timed out
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.7.0_67]

Setting the proxy server in the API:

 HashMap<String,String> config=new HashMap<String,String>();
config.put("http.UseProxy", "true");
config.put("http.ProxyPort", "80");
config.put("http.ProxyHost", "proxy.server.com");
config.put("http.ProxyUserName", null);
config.put("http.ProxyPassword", null);

APIContext context = new APIContext(clientId, clientSecret, "sandbox",config);

Change the values of  ProxyHost,  ProxyPort, ProxyUserName and ProxyPassword accordingly.

The communication will be success after this.


Tuesday, September 29, 2015

org.apache.sling.commons.json.JSONException: Misplaced array - JSONWriter

org.apache.sling.commons.json.JSONException: Misplaced array - JSONWriter

The Misplaced array exception is thrown,While we are trying to create the JSON Array of objects from the servlet using - org.apache.sling.commons.json.io.JSONWriter.

Code:-

JSONWriter writer=new JSONWriter(response.getWriter());
try {
writer.object();
writer.key("authorName").value("test");
writer.key("biography").value("test");
writer.key("image").value("test");
writer.array();
writer.object();
writer.key("authorName").value("test");
writer.key("biography").value("test");
writer.endObject();
writer.endArray();
writer.endObject();
} catch (JSONException e) {

}

The root cause of the exception is not providing the key for initialized array(there will be different scenarios we will receive this exception)

To fix the issue as shown below in the code, add the key before starting the array.

JSONWriter writer=new JSONWriter(response.getWriter());
try {
writer.object();
writer.key("authorName").value("test");
writer.key("biography").value("test");
writer.key("image").value("test");
writer.key("list");
writer.array();
writer.object();
writer.key("authorName").value("test");
writer.key("biography").value("test");
writer.endObject();
writer.endArray();
writer.endObject();
} catch (JSONException e) {

}  

O/P

{"authorName":"test","biography":"test","image":"test","list":[{"authorName":"test","biography":"test"}]}       



Thursday, September 17, 2015

a:ActionNotSupported: The message with Action '"' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher.

a:ActionNotSupported: The message with Action '"' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher.

Getting the below error while invoking the SOAP service via WebServiceTemplate.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">a:ActionNotSupported</faultcode>
<faultstring xml:lang="en-US">The message with Action '"' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).</faultstring>
</s:Fault>
</s:Body>
</s:Envelope>

The root cause of the issue is the SOAPAction is not set in the request header while invoking the service.

To fix the issue set the SOAPAction specified in the WSDL binding while invoking the service.

  <binding name="binding" type="service">
    <binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="process">
      <operation soapAction="process" style="document"/>
      <input>
        <body namespace="request" use="literal"/>
      </input>
      <output>
        <body namespace="response" use="literal"/>
      </output>
    </operation>
  </binding>

webServiceTemplate.marshalSendAndReceive(url,request, new WebServiceMessageCallback() {

    public void doWithMessage(WebServiceMessage message) {
        ((SoapMessage)message).setSoapAction("process");
    }
});


Sunday, May 31, 2015

org.springframework.a op.framework.AopConfigException: Could not generate CGLIB subclass of class [class net.sf.ehcache.CacheManager]

org.springframework.a op.framework.AopConfigException: Could not generate CGLIB subclass of class [class net.sf.ehcache.CacheManager]

While using Ehcache with spring, spring context initialization fails with the below exception

Caused by: org.springframework.beans.factory.BeanCreationException: Error creati
ng bean with name 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceI
mpl#0': Cannot resolve reference to bean 'ehcacheManager' while setting bean pro
perty 'cacheManager'; nested exception is org.springframework.beans.factory.Bean
CreationException: Error creating bean with name 'ehcacheManager': Post-processi
ng of the FactoryBean's object failed; nested exception is org.springframework.a
op.framework.AopConfigException: Could not generate CGLIB subclass of class [cla
ss net.sf.ehcache.CacheManager]: Common causes of this problem include using a f
inal class or a non-visible class; nested exception is org.springframework.cglib
.core.CodeGenerationException: net.sf.ehcache.CacheException-->Another unnamed C
acheManager already exists in the same VM. Please provide unique names for each
CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same Cac
heManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: InputStreamConfigurationSource [stre
am=java.io.BufferedInputStream@128647a]

Configuration Details:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
     xsi:schemaLocation="
     http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

<ehcache:annotation-driven cache-manager="cacheManager"/>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  <property name="configLocation" value="classpath:config/ehcache/ehcache.xml" />
  <property name="shared" value="true" />
</bean>
</beans>



Friday, May 8, 2015

Removing the Cookie is not working in IE10 and IE11

Removing the Cookie is not working in IE10 and IE11

While trying to remove the cookies in IE10 and IE11 through Java, the cookies are not getting removed in the browser.

The code snippet used to remove the cookie:


Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String cookieName = "SampleCookieName";
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
cookie.setPath("/");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}

The root cause of  the issue is IE10 and IE11 expecting the value for the attribute Expires as 0 not for Max-Age.

Fix for the issue - Use the below code to remove the cookies

Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String cookieName = "SampleCookie";
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
StringBuilder cookieString = new StringBuilder(cookieHeaderName + "=" + "" + "; ");

cookieString.append("Expires=0" + "; ");
cookieString.append("Version=0; ");
cookieString.append("Path=/; ");
cookieString.append("Max-Age=0" + "; ");
//cookieString.append("HttpOnly");

response.addHeader("Set-Cookie", cookieString.toString());
}
}
}

Refer the following blog to set cookies in IE10 and IE11 - cookie-values-are-not-setting-in-ie10-and-ie11


Thursday, March 12, 2015

Browser cookie values are not setting in IE10 and IE11

Browser cookie values are not setting in IE10 and IE11

While trying to set the cookies in IE10 and IE11 through Java, the values are not stetting in the browser.

The code snippet used to set the cookie is

cookie = new javax.servlet.http.Cookie(cookieHeaderName,"Sample Cookie");
cookie.setPath("/");
ookie.setMaxAge(365*24*60*60);
cookie.setSecure(false);
cookie.setVersion(0);
response.addCookie(cookie);

After long struggle we found the issue might be with the value of Expires is not set, IE10 and IE11 expecting the value for Expires and it is not considering the value set in Max-Age.

Fix for the issue - Use the below code to set the cookie value

int expiration = 365*24*60*60;
StringBuilder cookieString = new StringBuilder("TestCookie=Test; ");

DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, expiration);
cookieString.append("Expires=" + df.format(cal.getTime()) + "; ");
//cookieString.append("Domain="+request.getServerName()+"; ");
cookieString.append("Version=0; ");
cookieString.append("Path=/; ");
cookieString.append("Max-Age=" + expiration + "; ");
cookieString.append("HttpOnly");
response.addHeader("Set-Cookie", cookieString.toString());



Tuesday, March 3, 2015

How to find the Email Group Id in Eloqua?

 How to find the Email Group Id in Eloqua? 

This post will explain  how to find the Email Group Id in Eloqua

There will be different approach to find the Email Group id. Here. This post explains the approach used by me.
Use any of the REST client(here i am using Advance Rest Client)

Provide the below URL - https://secure.p03.eloqua.com/API/REST/1.0/assets/email/groups

Select the Http Method as GET

Provide the Authorization header

Authorization: Basic xxxxxxxxxxx

Replace xxxxxxxxxxx with base64 encoded string of companyName\userName:password

Send the request

The response will have all the Email Group id details - id and name of the Emial group can be found in the response.

{
  elements: [2]
  0:  {
         type: "ContactEmailSubscription"
         contactId: "1"
         emailGroup: {
             type: "EmailGroup"
             id: "1"
            depth: "minimal"
            description: ""
            name: "Sample1"
            permissions: "fullControl"
            updatedAt: "1423758721"
           updatedBy: "1"
        }
       isSubscribed: "true"
       updatedAt: "1423219686"
   }
  1:  {
         type: "ContactEmailSubscription"
         contactId: "1"
         emailGroup: {
             type: "EmailGroup"
             id: "2"
            depth: "minimal"
            description: ""
            name: "Sample2"
            permissions: "fullControl"
            updatedAt: "1423758721"
           updatedBy: "1"
        }
       isSubscribed: "true"
       updatedAt: "1423219686"
   }
  page: 1
 pageSize: 1000
 total: 2
}



Sunday, March 1, 2015

How to send the email through Java API in Eloqua

How to send the email through Java API in Eloqua

This post explains how to send the email through Eloqua API.

Create the required model classes:

public class EmailTestDeployment 

    public String contactId ;
    public String sendFromUserId ;
    public Email email;
    public String name;
    public String type;       

}

public class Email 
{
public int emailGroupId;
public RawHtmlContent htmlContent; 
public int id; 
public boolean isPlainTextEditable; 
public String name; 
public String plainText; 
public boolean sendPlainTextOnly; 
public String subject; 

}

public class RawHtmlContent 
{
    public String type;
    public String html;

}

RestClient class to connect to Eloqua:


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{
    private String authToken;
    private String baseUrl;       
    public RestClient(String user, String password, String url)
    {
       baseUrl = url;             
       String authString = user + ":" + password;
      authToken = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());           
    }             
                          
    public String execute(String uri, String method, String body)  throws Exception
    {
       String response ="";
       try
       {           
          URL url = new URL(baseUrl + uri);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();                         
          conn.setInstanceFollowRedirects(false);
          conn.setRequestMethod(method.toString());
          conn.setRequestProperty("Content-Type", "application/json");
          conn.setRequestProperty("Accept", "application/json");
          System.out.println(authToken);
          conn.setRequestProperty("Authorization", authToken);         
                  
          if (method == "POST" || method == "PUT")
          {
              if(null != body){
                  conn.setDoOutput(true);
                  final OutputStream os = conn.getOutputStream();
                  os.write(body.getBytes());
                  os.flush();
                  os.close();
               }
           }
                      
           InputStream is = conn.getInputStream();
           BufferedReader rd = new BufferedReader(new InputStreamReader( is));
           String line; 
           while ((line = rd.readLine()) != null)
           {
               response += line;
           }           
           rd.close();
           conn.disconnect();
         }
         catch (Exception e)
         {
            throw e;
         }
       return response;
      }

}



How to find the id of the existing contact in Eloqua

How to find the id of the existing contact in Eloqua

This post will explain How to find the id of the existing contact in Eloqua

Login to Eloqua
Click on Contacts in main page
Search by entering *, this will return all the contacts.
Open the particular contact.
Select Field Details tab and select All Contact Fields in the drop down.


In the Eloqua Contact ID field ignore CTHOM and all the zeros, consider the last digits as contact id(e.g 109)


Saturday, February 28, 2015

How to subscribe the Contact to a EmailGroup through Java API in Eloqua

How to subscribe the Contact to a EmailGroup through Java API in Eloqua

This post explains how to create the contact in Eloqua through java.

Create the required model classes:

public class EmailGroup
{
public String type;
public String id;
public String depth;
public String description;
public String name;
public String updatedAt;
public String updatedBy;
}

public class Subscription
{
public EmailGroup emailGroup;
public String isSubscribed;
public String contactId;
public String  type;
}

RestClient class to connect to Eloqua:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{
    private String authToken;
    private String baseUrl;    
    public RestClient(String user, String password, String url)
    {
       baseUrl = url;          
       String authString = user + ":" + password;
      authToken = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());        
    }          
                       
    public String execute(String uri, String method, String body)  throws Exception
    {
       String response ="";
       try
       {        
          URL url = new URL(baseUrl + uri);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();                      
          conn.setInstanceFollowRedirects(false);
          conn.setRequestMethod(method.toString());
          conn.setRequestProperty("Content-Type", "application/json");
          conn.setRequestProperty("Accept", "application/json");
          System.out.println(authToken);
          conn.setRequestProperty("Authorization", authToken);      
               
          if (method == "POST" || method == "PUT")
          {
              if(null != body){
                  conn.setDoOutput(true);
                  final OutputStream os = conn.getOutputStream();
                  os.write(body.getBytes());
                  os.flush();
                  os.close();
               }
           }
                   
           InputStream is = conn.getInputStream();
           BufferedReader rd = new BufferedReader(new InputStreamReader( is));
           String line;
           while ((line = rd.readLine()) != null)
           {
               response += line;
           }        
           rd.close();
           conn.disconnect();
         }
         catch (Exception e)
         {
            throw e;
         }
       return response;
      }
}



How to get the Subscriptions of a Contact through through Java API in Eloqua

How to get the Subscriptions of a Contact through through Java API in Eloqua

This post explains how to create the contact in Eloqua through java.

Create the required  model classes:

public class SubscriptionResponse
{
public List<Subscription> elements;
}

public class Subscription
{
public EmailGroup emailGroup;
public String isSubscribed;
}

public class EmailGroup
{
public String type;
public String id;
public String depth;
public String description;
public String name;
public String updatedAt;
public String updatedBy;
}

RestClient class to connect to Eloqua:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{
    private String authToken;
    private String baseUrl;    
    public RestClient(String user, String password, String url)
    {
       baseUrl = url;          
       String authString = user + ":" + password;
      authToken = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());        
    }          
                       
    public String execute(String uri, String method, String body)  throws Exception
    {
       String response ="";
       try
       {        
          URL url = new URL(baseUrl + uri);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();                      
          conn.setInstanceFollowRedirects(false);
          conn.setRequestMethod(method.toString());
          conn.setRequestProperty("Content-Type", "application/json");
          conn.setRequestProperty("Accept", "application/json");
          System.out.println(authToken);
          conn.setRequestProperty("Authorization", authToken);      
               
          if (method == "POST" || method == "PUT")
          {
              if(null != body){
                  conn.setDoOutput(true);
                  final OutputStream os = conn.getOutputStream();
                  os.write(body.getBytes());
                  os.flush();
                  os.close();
               }
           }
                   
           InputStream is = conn.getInputStream();
           BufferedReader rd = new BufferedReader(new InputStreamReader( is));
           String line;
           while ((line = rd.readLine()) != null)
           {
               response += line;
           }        
           rd.close();
           conn.disconnect();
         }
         catch (Exception e)
         {
            throw e;
         }
       return response;
      }
}



Saturday, February 14, 2015

How to create the contact in Eloqua through java

How to create the contact in Eloqua through java

This post explains how to create the contact in Eloqua through java.

Create the model class for Contact:

public class Contact
{
 public String accountName;
 public String address1;
 public String address2;
 public String address3;
 public String businessPhone;
 public String city;
 public String country;
 public String firstName;
 public String emailAddress;
 public String id;
 public boolean isBounceback;
 public boolean isSubscribed;
 public String lastName;
 public String salesPerson;
 public String title;
 public String type;
 public String name;

}

RestClient class to connect to Eloqua:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{
 private String authToken;
 private String baseUrl;

 public RestClient(String user, String password, String url)
 {
  baseUrl = url;
  String authString = user + ":" + password;
  authToken = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());        }

 public String execute(String uri, String method, String body)  throws Exception
 {
  String response ="";
  try
  {
   URL url = new URL(baseUrl + uri);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();

   conn.setInstanceFollowRedirects(false);
   conn.setRequestMethod(method.toString());
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setRequestProperty("Accept", "application/json");
         conn.setRequestProperty("Authorization", authToken);    
       
         if (method == "POST" || method == "PUT")
         {
          if(null != body){
    conn.setDoOutput(true);
          final OutputStream os = conn.getOutputStream();
                os.write(body.getBytes());
                os.flush();
                os.close();
          }
         }
       
         InputStream is = conn.getInputStream();
         BufferedReader rd = new BufferedReader(new InputStreamReader( is));

          String line;
         while ((line = rd.readLine()) != null)
         {
             response += line;
         }      
         rd.close();
         conn.disconnect();
  }
  catch (Exception e)
  {
   throw e;
  }
        return response;
 }
}




Saturday, February 7, 2015

How to activate the Campaign in Eloqua through java

How to activate the Campaign in Eloqua through java

This post explains how to activate the Eloqua campaign through java.

RestClient class to connect to Eloqua:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{
    private String authToken;
    private String baseUrl;       
    public RestClient(String user, String password, String url)
    {
       baseUrl = url;             
       String authString = user + ":" + password;
      authToken = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());           
    }             
                          
    public String execute(String uri, String method, String body)  throws Exception
    {
       String response ="";
       try
       {           
          URL url = new URL(baseUrl + uri);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();                         
          conn.setInstanceFollowRedirects(false);
          conn.setRequestMethod(method.toString());
          conn.setRequestProperty("Content-Type", "application/json");
          conn.setRequestProperty("Accept", "application/json");
          conn.setRequestProperty("Authorization", authToken);         
                  
          if (method == "POST" || method == "PUT")
          {
              if(null != body){
                  conn.setDoOutput(true);
                  final OutputStream os = conn.getOutputStream();
                  os.write(body.getBytes());
                  os.flush();
                  os.close();
               }
           }
                      
           InputStream is = conn.getInputStream();
           BufferedReader rd = new BufferedReader(new InputStreamReader( is));
           String line; 
           while ((line = rd.readLine()) != null)
           {
               response += line;
           }           
           rd.close();
           conn.disconnect();
         }
         catch (Exception e)
         {
            throw e;
         }
       return response;
      }
}



Friday, February 6, 2015

How to update the html content of Email template in Eloqua through java

How to update the html content of Email template in Eloqua through java

This post explains how to update the html content of the Eloqua email through java.

Create the model class for Email:

public class Email
{            
public int emailGroupId;
public RawHtmlContent htmlContent;
public Integer id;
public boolean isPlainTextEditable;
public String name;
public String plainText;
public boolean sendPlainTextOnly;
public String subject;
}
public class RawHtmlContent
{
 public String type;
 public String html;
}

Create the html template with place holder for dynamic content and place the template in the same location of the below java classes.

sample-template.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <body>
      ${content}
   </body>
</html>

RestClient class to connect to Eloqua

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{
    private String authToken;
    private String baseUrl;      
    public RestClient(String user, String password, String url)
    {
       baseUrl = url;            
       String authString = user + ":" + password;
      authToken = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());          
    }            
                         
    public String execute(String uri, String method, String body)  throws Exception
    {
       String response ="";
       try
       {          
          URL url = new URL(baseUrl + uri);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();                        
          conn.setInstanceFollowRedirects(false);
          conn.setRequestMethod(method.toString());
          conn.setRequestProperty("Content-Type", "application/json");
          conn.setRequestProperty("Accept", "application/json");
          conn.setRequestProperty("Authorization", authToken);        
                 
          if (method == "POST" || method == "PUT")
          {
              if(null != body){
                  conn.setDoOutput(true);
                  final OutputStream os = conn.getOutputStream();
                  os.write(body.getBytes());
                  os.flush();
                  os.close();
               }
           }
                     
           InputStream is = conn.getInputStream();
           BufferedReader rd = new BufferedReader(new InputStreamReader( is));
           String line;
           while ((line = rd.readLine()) != null)
           {
               response += line;
           }          
           rd.close();
           conn.disconnect();
         }
         catch (Exception e)
         {
            throw e;
         }
       return response;
      }
}



Wednesday, January 14, 2015

Invoking NTLM authentication enabled service through Java

Invoking NTLM authentication enabled service through Java

Java API

The below program help us to invoke NTLM authentication enabled services.

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.HttpStatus;

public class NTLMAuthentication {

public String invokeService(String url, String soapMessage) {
String responseString = null;
try {

HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestEntity(new StringRequestEntity(soapMessage,"text/xml","utf-8"));
postMethod.setRequestHeader("SOAPAction", "http://www.service.com/GetEmployeeData");
postMethod.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
NTCredentials credentials = new NTCredentials("username","password", "hostName", "domain");
client.getState().setCredentials(new AuthScope(null, -1, null), credentials);
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK)
{
responseString = postMethod.getResponseBodyAsString();
}
} catch (Exception e) {

}
return responseString;

}

}



Saturday, July 5, 2014

Invoking Salesforce REST based web service from Java

Invoking Salesforce REST based web service from Java

This post will explain the approach to call the Salesfore REST based webservice through java.
I have exposed a Apex class as REST service from salesforce to fetch the account details.

@RestResource(urlMapping='/AccountDetails/*')
global with sharing class AccountDetails {

    @HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        System.debug('Account Id:'+accountId);
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
        return result;
    }
}

The communication is of two steps
  •  getting the access_token 
  •  invoking the service endpoint by attaching the access_token to the request.
To obtain an access token, we will send an HTTP POST request to the authentication endpoint exposed by Salesforce - https://login.salesforce.com/services/oauth2/token  with the details client_id, client_secret, username and password.This values can be get from the configured Connected Apps from salesforce.





Friday, July 4, 2014

Ignoring the Host Name verification while invoking the HTTPS service through HttpsURLConnection

Ignoring the Host Name verification while invoking the HTTPS service through HttpsURLConnection

Sometimes you may receive the Host Name mismatch exception while invoking the HTTPS service from the Java client even though the valid certificate is installed to the key store.

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching <Host Name> found

The root cause of the exception is the CN name of the certificate is not matching with the host name used to connect the service.

In real scenario while the certificate is signed with third party certificate authority , the CN name will be specified as the host name of the server where the service is hosted or wildcard name will be specified e.g *.example.com to represent all sub domains in a domain. So there will not be any issue while connecting to the service.

This mismatch exception will happen most of the time communicating with self signed certificate, the certificate is signed with CN name that is not matching with the host name.

How to Fix the issue

To resolve the issue, the certificate should be signed with proper CN name or we can create a custom host name verifier to customize the host name verification functionality.

We have to return true from the custom host name verifier for the host name for which the CN name is mismatching.This will connect to the service irrespective of the host name used .

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;

public class HTTPCaller {
static {
   javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
   new javax.net.ssl.HostnameVerifier(){
       public boolean verify(String hostname,
               javax.net.ssl.SSLSession sslSession) {
           if (hostname.equals("localhost")) {
               return true;
           }
           return false;
       }
   });
}

    public static String execute() {
        String targetURL="https://localhost/test"
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(targetURL);
            url = new URL(url.toString());              

            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestProperty("accept", "application/xml"); //for GET service to return xml payload

            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            System.out.println("\n Received response" + System.currentTimeMillis());

            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return (e.getClass().getName()+":"+e.getMessage().toString());
        }
        finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }



Wednesday, July 2, 2014

Encrypting XML Payload through XSLT in Spring WS

Encrypting XML Payload through XSLT in Spring WS

The below document explain the approach to This document will explain the approach to encrypt the critical elements of XML payload while invoking the services in Spring WS or storing the data to a database table through XSLT.



Encrypting_XML_Payload.pdf


Tuesday, July 1, 2014

Unit Testing the Velocity Templates in spring

Unit Testing the Velocity Templates in spring

It is painful to test the Velocity Template  by deploying to the server while doing frequent changes.
The unit testing  will help as to overcome this and do proper testing without deploying the project to the server.
This post will explain the approach to unit test the Velocity Templates through eclipse.

Spring velocity configurations

Create a Velocity-test.xml configuration file to configure the velocity bean - instead of creating separate configuration file we can also use the project configuration file that has the velocity bean configuration (e.g. application-context.xml)


Change the vm template path accordingly.

Create a test java class (VelocityTest.java)

import java.io.*;
import java.util.ArrayList;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.thomson.ecom.core.velocity.VelocityContextBuilder;
public class VelocityTest
{
public static void main(String[] args) throws Exception
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:velocity-test.xml");
ArrayList<Employee> employeeList=new ArrayList<Employee>();

Employee emp1=new Employee();
emp1.setContactNo("111111");
emp1.setDept("CSC");
emp1.setEmail("[email protected]");
emp1.setEmpName("Albin");
emp1.setEmpNo("1");
emp1.setLocation("Bangalore");
employeeList.add(emp1);

Employee emp2=new Employee();
emp2.setContactNo("22222");
emp2.setDept("IT");
emp2.setEmail("[email protected]");
emp2.setEmpName("Albin1");
emp2.setEmpNo("2");
emp2.setLocation("Bangalore");
employeeList.add(emp2);

Employee emp3=new Employee();
emp3.setContactNo("33333");
emp3.setDept("IT");
emp3.setEmail("[email protected]");
emp3.setEmpName("Albin2");
emp3.setEmpNo("3");
emp3.setLocation("Bangalore");
employeeList.add(emp3);

VelocityEngine engine = ctx.getBean("velocityEngine", VelocityEngine.class);
Context velocityCtx = VelocityContextBuilder.getInstance().buildContext();
velocityCtx.put("empList", employeeList);

Writer w = new FileWriter(new File("D:\\Albin\\velocity.html"));
engine.mergeTemplate("EmployeeEmailTemplate.vm", velocityCtx, w);
w.close();

System.exit(0);
}
}

Change the velocity.html file path and the vm template name accordingly.
Pass the required inputs to the velocityCtx map.
Execute the VelocityTest.java; this will generate the velocity.html file in the specified location.