April 27, 2020
Estimated Post Reading Time ~

Integrating Adobe Experience Manager with REST services

Integrating CQ5 with REST services
Service integration is one of the important parts of Enterprise systems, the systems have to be integrated with different services to satisfy the business. SOAP/REST approaches can be used to integrate the systems with third party services.

This post will explain the approach to integrate CQ5 with REST-based services.
Create a service component class with the required HTTP methods. The service class is mapped to the url /services/RestInvocationServlet. This URL can be used to invoke the service class.

package com.test.servlet;
import java.io.*;
import javax.servlet.Servlet;
import org.apache.felix.scr.annotations.*; import org.apache.sling.api.*;
import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.*;
import com.test.core.config.ConfigService;
import com.test.service.RestUtilService;
import com.test.service.impl.RestUtileServiceImpl;
/**
* Gets OSGi configuration. */
@Service(value = Servlet.class) @Component(immediate = true, metatype = true) @Properties({
@Property(name = "sling.servlet.paths", value = "/services/RestInvocationServlet"),
@Property(name = "service.description", value = "RestInvocationServlet"),
@Property(name = "label", value = "RestInvocationServlet")
})
public class RestInvocationServlet extends SlingAllMethodsServlet implements Serializable {
private static final Logger LOG = LoggerFactory .getLogger(RestInvocationServlet.class);
/**
* Default serial version id. */
private static final long serialVersionUID = 1L;

/**
* {@inheritDoc} *
* @see
org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingH ttpServletRequest,
* org.apache.sling.api.SlingHttpServletResponse)
*/
protected final void doPost(final SlingHttpServletRequest request, final
SlingHttpServletResponse response)
throws IOException {
LOG.info("Entered servlet");
RestUtilService restUtilService = new RestUtileServiceImpl(); String
endPointURL=TRConfigService.getPropertyValue(TRConfigService.REST_INVOCATI ON_URL);
String result =restUtilService.execute(endPointURL, "GET"); LOG.info("URL is "+endPointURL);
System.out.println("value is"+restUtilService.execute(endPointURL,
LOG.info("Value is "+restUtilService.execute(endPointURL, "GET")); //response.setContentType("application/json"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(result);
}
/**
* {@inheritDoc} *
* @see
org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.Sling HttpServletRequest,
* org.apache.sling.api.SlingHttpServletResponse)
*/
protected final void doGet(final SlingHttpServletRequest request, final
SlingHttpServletResponse response)
throws IOException {
doPost(request, response); }

}

Create a service interface with the execute method
package com.test.service;
import java.io.IOException;
import org.apache.sling.api.*;
public interface RestUtilService {
String execute(String targetURL, String HttpMethod) throws IOException;
}

Create the implementation for the service interface – this class will use the HttpURLConnection to connect to the REST service and send the XML/JSON response back.

package com.test.service.impl; import java.io.*;
import java.net.*;
import org.slf4j.*;
import com.test.service.RestUtilService;
public class RestUtileServiceImpl implements RestUtilService{
static {
//for localhost testing only javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier( new javax.net.ssl.HostnameVerifier() {
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
if (hostname.equals("c111mdhdswapp")) {
return true;
}
return false;
}
});

}

private static final Logger LOG = LoggerFactory .getLogger(RestUtileServiceImpl.class);
public String execute(String targetURL, String HttpMethod) { URL url;
HttpURLConnection connection = null; try {
url = new URL(targetURL); if (HttpMethod == "GET") {
url = new URL(url.toString());
System.out.println("\n GET URL called " + url);
}
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("accept", "application/json"); //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();
LOG.info("Value response "+response.toString()); return response.toString();
} catch (Exception e) {
e.printStackTrace();
return (e.getClass().getName()+":"+e.getMessage().toString());
}
finally {
if (connection != null) {
connection.disconnect();

}
}
}

}

The value of the endpoint will be configured in the configuration service inside a bundle as shown

@Property(label = "Rest End point", value = "https://localhost:9002/webservices/v1/products/", description = "Enter the Service End point URL to consume")

public static final String REST_INVOCATION_URL = "restUrl";


The service can be invoked wherever REST-based integration.

<script type="text/javascript">
$('document').ready(function(){
$.ajax({
type : "POST",
async: false,
url : "/services/RestInvocationServlet", //dataType : "xml",
success : function(result) { alert(result);
},
error : function() {
}
});
}); </script>


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.