Utilisation de l'exemple de projet d'intégration
Chaque installation de l'exécution Interact est fournie avec un exemple de projet qui explique le processus d'intégration de Digital Recommendations - Interact. L'exemple de projet fournit une démonstration complète et de bout en bout. Il explique comment créer une page Web qui appelle une offre contenant un ID de catégorie, qui est ensuite transmis à Digital Recommendations en vue de récupérer une liste de produits recommandés à présenter dans les points d'interaction de la page.
Présentation
Vous pouvez utiliser l'exemple de projet tel quel, si vous souhaitez tester le processus d'intégration, ou l'utiliser comme point de départ pour développer vos propres pages personnalisées. L'exemple de projet se trouve dans le fichier suivant :
Interact_home/samples/IntelligentOfferIntegration/MySampleStore.jsp
Ce fichier contient un exemple fonctionnel complet du processus d'intégration. Il inclut également des commentaires détaillés expliquant ce que vous devez configurer dans Interact, ce que vous devez personnaliser dans le fichier .jsp, et comment déployer correctement la page à exécuter avec votre installation.
MySampleStore.jsp
Pour plus de commodité, le fichier MySampleStore.jsp est représenté ici. Cet exemple peut être mis à jour dans les éditions suivantes de Interact. Utilisez par conséquent le fichier fourni avec votre installation comme point de départ pour les exemples dont vous avez besoin.
<!--
# *******************************************************************************
# 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" %>

<%

/*********************************************************************************
* Cet échantillon de programme jsp explique l'intégration d'Interact et
Digital Recommendations.
*
* Lorsque vous accédez à l'URL de ce jsp via un navigateur, la logique appelle Interact
* pour extraire une Offre. En fonction de l'ID de catégorie associé à l'offre, la logique
* appelle Digital Recommendations pour extraire des produits recommandés. L'offre et les produits
* s'affichent.
* Pour basculer l'ID client pour voir différentes offres, vous pouvez simplement
* ajouter cid=<id> à l'URL de ce JSP.
*
* Prérequis pour comprendre cette démo :
* 1) Connaissance d'Interact et de son API java
* 2) Connaissance d'IntelligentOffer et de son API REST
* 3) Connaissances Web de base (html, css, javascript) pour le marquage de page
* 4) Technologie utilisée pour générer une page Web (pour cette démo, nous utilisons JSP exécuté côté serveur)
*
*
* Marche à suivre pour faire fonctionner cette démo :
* 1) Configurez un environnement d'exécution Interact pouvant proposer des offres
* ayant les attributs suivants :
* ImageURL : URL de lien à l'image de l'offre
* ClickThruURL : URL de lien à la page d'arrivée de l'offre
* CategoryID : ID de catégorie Digital Recommendations associé à l'offre
* REMARQUE : d'autres noms peuvent être utilisés pour les attributs, à condition que les références à ces
* attributs dans ce jsp soient modifiées en conséquence.
* 2) Obtenez une URL d'API REST valide pour l'environnement Intelligent Offer
* 3) Intégrez ce JSP dans une application Web Java
* 4) Vérifiez que interact_client.jar se trouve dans le répertoire WEB-INF/lib (communication avec Interact)
* 5) Vérifiez que JSON4J_Apache.jar (provenant de l'installation d'interact) se trouve dans le
* répertoire WEB-INF/lib (communication avec IO)
* 6) Définissez les propriétés de l'environnement dans les deux sections suivantes
**********************************************************************************/

/*********************************************************************************
* *****************MODIFIEZ CES PARAMETRES EN FONCTION DE VOTRE ENVIRONNEMENT********************
* Définissez ici les propriétés de votre environnement Interact...
**********************************************************************************/

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;

/*********************************************************************************
*****************MODIFIEZ CES PARAMETRES EN FONCTION DE VOTRE ENVIRONNEMENT*********************
* Définissez ici les propriétés propres à votre environnement Digital Recommendations...
**********************************************************************************/

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>Ma boutique préférée</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>Bienvenue dans ma boutique</b> M./Mme <%=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("Page produit") != null &&
rec.getString("Page produit").trim().length()>0) {
%>

<li>
<a href="<%=rec.getString("Page produit") %>" title="<%=rec.getString("Nom produit") %>">
<img src="<%=rec.getString("Image") %>" width="166" height="148" border="0" />
<%=rec.getString("Nom produit") %>
</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>



<%!
/*********************************************************************************
* Les fonctionnalités suivantes sont des fonctions libre-service qui font des extractions dans Interact et
* Digital Recommendations
**********************************************************************************/

/*********************************************************************************
* Appelez Digital Recommendations pour extraire les produits recommandés
**********************************************************************************/
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;

}

/*********************************************************************************
* Appeler Interact pour extraire l'offre
**********************************************************************************/
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());
}
%>