Utilización del proyecto de muestra de integración
Cada instalación de tiempo de ejecución de Interact incluye un proyecto de muestra que describe el proceso de la integración Digital Recommendations - Interact. El proyecto de muestra describe cómo crear una página web que llama a una oferta que contiene un ID de categoría, el cual se pasa a Digital Recommendations para recuperar una lista de productos recomendados para su presentación en los puntos de interacción de la página.
Descripción general
Puede utilizar el proyecto de muestra tal como se proporciona si desea probar el proceso de integración, o puede utilizar el proyecto como punto de partida para desarrollar sus propias páginas personalizadas. El proyecto de muestra se encuentra en el archivo siguiente:
directorio_inicio_Interact/samples/IntelligentOfferIntegration/MySampleStore.jsp
Este archivo, además de contener un ejemplo completo funcional del proceso de integración, también contiene comentarios extensos que describen qué debe configurar en Interact, qué debe personalizar en el archivo .jsp , y cómo desplegar la página correctamente para ejecutarla con la instalación.
MySampleStore.jsp
Para su comodidad, el archivo MySampleStore.jsp se muestra aquí. Esposible que esta muestra se actualice en releases subsiguientes de Interact; utilice pues el archivo que se incluye con la instalación como punto de partida para cualquier ejemplo que necesite.
<!--
# *******************************************************************************
# Licensed Materials - Property of IBM
# IBM Interact
# (c) Copyright IBM Corporation 2001, 2011.
# US Government Users Restricted Rights - Use, duplication or disclosure
# restricted by GSA ADP Schedule Contract with IBM Corp.
# *******************************************************************************

-->


<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ page import="java.net.URL,
java.net.URLConnection,
java.io.InputStreamReader,
java.io.BufferedReader,
com.unicacorp.interact.api.*,
com.unicacorp.interact.api.jsoverhttp.*,
org.apache.commons.json.JSONObject,
org.apache.commons.json.JSONArray" %>

<%

/*********************************************************************************
* This sample jsp program demonstrates integration of Interact and
Digital Recommendations.
*
* When the URL for this jsp is accessed via a browser. the logic will call Interact
* to fetch an Offer. Based on the categoryID associated to the offer, the logic
* will call Digital Recommendations to fetch recommended products. The offer and products
* will be displayed.
* To toggle the customerId in order to demonstrate different offers, one can simply
* append cid=<id> to the URL of this JSP.
*
* Prerequisites to understand this demo:
* 1) familiarity of Interact and its java API
* 2) familiarity of IntelligentOffer and its RestAPI
* 3) some basic web background ( html, css, javascript) to mark up a web page
* 4) Technology used to generate a web page (for this demo, we use JSP executed on the server side)
*
*
* Steps to get this demo to work:
* 1) set up an Interact runtime environment that can serve up offers with the following
* offer attributes:
* ImageURL : url that links to the image of the offer
* ClickThruURL : url that links to the landing page of the offer
* CategoryID : Digital Recommendations category id associated to the offer
* NOTE: alternate names for the attributes may be used as long as the references to those
* attributes in this jsp are modified to match.
* 2) Obtain a valid REST API URL to the Intelligent Offer environment
* 3) Embed this JSP within a Java web application
* 4) Make sure interact_client.jar is in the WEB-INF/lib directory (communication with Interact)
* 5) Make sure JSON4J_Apache.jar (from interact install) is in the
* WEB-INF/lib directory (communication with IO)
* 6) set the environment specific properties in the next two sections
**********************************************************************************/

/*********************************************************************************
* *****************CHANGE THESE SETTINGS TO REFLECT YOUR ENV********************
* Set your Interact environment specific properties here...
**********************************************************************************/

final String sessionId="123";
final String interactiveChannel = "SampleIO";
final String audienceLevel = "Customer";
final String audienceColumnName="CustomerID";
final String ip="ip1";
int customerId=1;
final String interactURL="http://localhost:7011/interact/servlet/InteractJSService";
final boolean debug=true;
final boolean relyOnExistingSession=true;

/*********************************************************************************
*****************CHANGE THESE SETTINGS TO REFLECT YOUR ENV********************
* Set your Digital Recommendations environment specific properties here...
**********************************************************************************/

final String ioURL="http://recs.coremetrics.com/iorequest/restapi";
final String zoneID="ProdRZ1";
final String cID="90007517";



/*********************************************************************************
********************************************************************************/

StringBuilder interactErrorMsg = new StringBuilder();
StringBuilder intelligentOfferErrorMsg = new StringBuilder();

// get the customerID if passed in as a parameter
String cid = request.getParameter("cid");
if(cid != null)
{
customerId = Integer.parseInt(cid);
}

// call Interact to get offer
Offer offer=getInteractOffer(interactURL,sessionId,interactiveChannel,audienceLevel,
audienceColumnName,ip,customerId,debug,relyOnExistingSession,interactErrorMsg);

// get specific attributes from the offer (img url, clickthru url, & category id)
String offerImgURL=null;
String offerClickThru=null;
String categoryId="";

if(offer != null)
{
for(NameValuePair offerAttribute : offer.getAdditionalAttributes())
{
if(offerAttribute.getName().equalsIgnoreCase("ImageURL"))
{
offerImgURL=offerAttribute.getValueAsString();
}
else if(offerAttribute.getName().equalsIgnoreCase("ClickThruURL"))
{
offerClickThru=offerAttribute.getValueAsString();
}
else if(offerAttribute.getName().equalsIgnoreCase("CategoryID"))
{
categoryId=offerAttribute.getValueAsString();
}
}
}

// call Digital Recommendations to get products
JSONObject products=getProductsFromIntelligentOffer(ioURL, cID, zoneID, categoryId,
intelligentOfferErrorMsg);

%>

<html>
<head>
<title>My Favorite Store</title>

<script language="javascript" type="text/javascript">
var unicacarousel=(function(){var g=false;var h;var j=0;var k=0;var l=0;var m=40;
var n=new Array(0,2,6,20,40,60,80,88,94,97,99,100);var o=function(a){var b=a.parentNode;
h=b.getElementsByTagName("UL")[0];var c=h.getElementsByTagName("LI");j=c[0].offsetWidth;
k=c.length;l=Math.round((b.offsetWidth/j));unicacarousel.recenter()};var p=function(a)
{var b=parseFloat(h.style.left);if(isNaN(b))b=0;for(var i=0;i<n.length;i++)
{setTimeout("unicacarousel.updateposition("+(b+(a*(n[i]/100)))+");",((i*m)+50))}
setTimeout("unicacarousel.recenter();",((i*m)+50))};return{gotonext:function(a,b)
{if(!g){o(a);g=true;p((-1*b*j))}},gotoprev:function(a,b){if(!g){o(a);g=true;p((b*j))}},
updateposition:function(a){h.style.left=a+"px"},recenter:function(){var a=parseFloat(h.style.left);
if(isNaN(a))a=0;var b=j*Math.round(((l-k)/2));var c=Math.abs(Math.round((b-a)/j));
if(a<b){var d=h.getElementsByTagName("LI");var e=new Array();
for(var i=0;i<c;i++){e[e.length]=d[i]}for(var i=0;i<e.length;i++)
{h.insertBefore(e[i],null)}unicacarousel.updateposition(b)}else
if(a>b){var d=h.getElementsByTagName("LI");var e=new Array();
for(var i=0;i<c;i++){e[e.length]=d[d.length-c+i]}var f=d[0];
for(var i=0;i<e.length;i++){h.insertBefore(e[i],f)}unicacarousel.updateposition(b)}g=false}}})();
</script>

<style type="text/css">
.unicaofferblock_container {width:250px; position:relative; display:block;
text-decoration:none; color:#000000; cursor: pointer;}
.unicaofferblock_container .unicateaserimage {margin:0px 0.5em 0.25em 0px; float:left;}
.unicaofferblock_container .unicabackgroundimage {position:absolute; top:0px; left:0px;}
.unicaofferblock_container .unicabackgroundimagecontent {width:360px; height:108px;
padding:58px 4px 4px 20px; position:relative; top:0px;}
.unicaofferblock_container h4 {margin:0px; padding:0px; font-size:14px;}

.unicacarousel {width:588px; position:relative; top:0px;}
.unicacarousel_sizer {width:522px; height:349px; margin:0px 33px; padding:0;
overflow:hidden; position:relative;}
.unicacarousel_rotater {height:348px; width:1000px; margin:0 !important;
padding:0; list-style:none; position:absolute; top:0px;
left:0px;}
.unicacarousel li {width:167px; height:349px; float:left; padding:0 4px;
margin:0px !important; list-style:none !important;
text-indent:0px !important;}
.unicacarousel_gotoprev, .unicacarousel_gotonext {width:18px; height:61px;
top:43px; background:url(../img/carouselarrows.png) no-repeat;
position:absolute; z-index:2; text-align:center; cursor:pointer;
display:block; overflow:hidden; text-indent:-9999px;
font-size:0px; margin:0px !important;}
.unicacarousel_gotoprev {background-position:0px 0; left:0;}
.unicacarousel_gotonext {background-position:-18px 0; right:0;}

</style>


</head>

<body>

<b>Welcome To My Store</b> Mr/Mrs. <%=customerId %>
<br><br>
<% if(offer != null) { %>
<!-- Interact Offer HTML -->

<div onclick="location.href='<%=offerClickThru %>'" class="unicaofferblock_container">
<div class="unicabackgroundimage">
<a href="<%=offerClickThru %>"><img src="<%=offerImgURL %>" height="170"
width="695" border="0"></a>
</div>
</div>


<% } else { %>
No offer available.. <br> <br>
<%=interactErrorMsg.toString() %>
<% } %>

<% if(products != null) { %>
<!-- IntelligentOffer Products HTML -->
<br><br><br> <br><br><br> <br><br><br> <br><br><br> <br>
<div class="unicacarousel">
<div class="unicacarousel_sizer">
<ul class="unicacarousel_rotater">


<% JSONArray recs = products.getJSONObject("io").getJSONArray("recs");
if(recs != null)
{
for(int x=0;x< recs.length();x++)
{
JSONObject rec = recs.getJSONObject(x);
if(rec.getString("Product Page") != null &&
rec.getString("Product Page").trim().length()>0) {
%>

<li>
<a href="<%=rec.getString("Product Page") %>" title="<%=rec.getString("Product Name") %>">
<img src="<%=rec.getString("Image") %>" width="166" height="148" border="0" />
<%=rec.getString("Product Name") %>
</a>
</li>

<% }
}
}
%>
</ul>
</div>
<p class="unicacarousel_gotoprev" onclick="unicacarousel.gotoprev(this,1);"></p>
<p class="unicacarousel_gotonext" onclick="unicacarousel.gotonext(this,1);"></p>
</div>
<% } else { %>
<div>
<br><br> <br><br><br> <br><br><br> <br><br><br> <br>
No products available...<br> <br>
<%=intelligentOfferErrorMsg.toString() %>
</div>
<% } %>

</body>
</html>



<%!
/*********************************************************************************
* The following are convenience functions that will fetch from Interact and
* Digital Recommendations
**********************************************************************************/

/*********************************************************************************
* Call Digital Recommendations to retrieve recommended products
**********************************************************************************/
private JSONObject getProductsFromIntelligentOffer(String ioURL, String cID,
String zoneID, String categoryID, StringBuilder intelligentOfferErrorMsg)
{

try
{

ioURL += "?cm_cid="+cID+"&cm_zoneid="+zoneID+"&cm_targetid="+categoryID;
System.out.println("CoreMetrics URL:"+ioURL);
URL url = new java.net.URL(ioURL);

URLConnection conn = url.openConnection();

InputStreamReader inReader = new InputStreamReader(conn.getInputStream());
BufferedReader in = new BufferedReader(inReader);

StringBuilder response = new StringBuilder();

while(in.ready())
{
response.append(in.readLine());
}

in.close();

intelligentOfferErrorMsg.append(response.toString());

System.out.println("CoreMetrics:"+response.toString());

if(response.length()==0)
return null;

return new JSONObject(response.toString());
}
catch(Exception e)
{
intelligentOfferErrorMsg.append(e.getMessage());
e.printStackTrace();
}

return null;

}

/*********************************************************************************
* Call Interact to retrieve offer
**********************************************************************************/
private Offer getInteractOffer(String interactURL,String sessionId,String interactiveChannel,
String audienceLevel,
String audienceColumnName,String ip, int customerId,boolean debug,
boolean relyOnExistingSession, StringBuilder interactErrorMsg)
{
try
{
InteractAPI api = InteractAPI.getInstance(interactURL);
NameValuePairImpl custId = new NameValuePairImpl();
custId.setName(audienceColumnName);
custId.setValueAsNumeric(Double.valueOf(customerId));
custId.setValueDataType(NameValuePair.DATA_TYPE_NUMERIC);
NameValuePairImpl[] audienceId = { custId };

// call startSession
Response response = api.startSession(sessionId, relyOnExistingSession,
debug, interactiveChannel, audienceId, audienceLevel, null);

if(response.getStatusCode() == Response.STATUS_ERROR)
{
printDetailMessageOfWarningOrError("startSession",response, interactErrorMsg);
}

// call getOffers
response = api.getOffers(sessionId, ip, 1);
if(response == null || response.getStatusCode() == Response.STATUS_ERROR)
{
printDetailMessageOfWarningOrError("getOffers",response, interactErrorMsg);
}

OfferList offerList=response.getOfferList();

if(offerList != null && offerList.getRecommendedOffers() != null)
{
return offerList.getRecommendedOffers()[0];
}
}
catch(Exception e)
{
interactErrorMsg.append(e.getMessage());
e.printStackTrace();
}
return null;
}

private void printDetailMessageOfWarningOrError(String command, Response response,
StringBuilder interactErrorMsg)
{
StringBuilder sb = new StringBuilder();
sb.append("Calling "+command).append("<br>");
AdvisoryMessage[] messages = response.getAdvisoryMessages();

for(AdvisoryMessage msg : messages)
{
sb.append(msg.getMessage()).append(":");
sb.append(msg.getDetailMessage());
sb.append("<br>");
}
interactErrorMsg.append(sb.toString());
}
%>