使用集成样本项目
每个 Interact 运行时安装都包括一个用于描述 Digital Recommendations - Interact 集成过程的样本项目。该样本项目提供了有关创建 Web 页面的完整的端到端演示,该页面会调用包含类别标识的商品,然后该商品会传递到 Digital Recommendations 以检索页面交互点中呈示的建议产品列表。
概述
如果您想要测试集成过程,那么可以如所提供的一样使用所包含的样本项目,或者可以将其用作起始点来开发您自己的定制页面。样本项目位于以下文件中:
Interact_home/samples/IntelligentOfferIntegration/MySampleStore.jsp
此文件除了包含集成过程的完整的工作示例外,还包含用于描述在 Interact 中要设置的内容、在 .jsp 文件中要定制的内容以及如何正确部署页面以与您的安装一起运行的大量注释。
MySampleStore.jsp
为方便起见,此处显示了 MySampleStore.jsp 文件。由于此样本可以使用 Interact 的后续发行版来更新,因此可使用您的安装随附的文件作为起始点来进行所需的任何示例。
<!--
# *******************************************************************************
# 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)
{
System.out.println(msg.getMessage());
sb.append(msg.getDetailMessage());
sb.append("<br>");
}
interactErrorMsg.append(sb.toString());
}
%>