<%--
  Copyright 2003 Sun Microsystems, Inc. All rights reserved 
  Use is subject to license terms.
 --%>
<%-- @(#)processRating.jsp --%>

<%@page language="java" import="com.sun.portal.search.demo.Search, 
				com.sun.portal.search.soif.*, 
				com.sun.portal.search.soif.SOIFOutputStream, 
				com.sun.portal.search.soif.SOIFInputStream, 
				java.net.*,
				java.lang.*, 
				java.util.*" %> 

<%@page errorPage="error.jsp" %>

<%@ taglib uri="/tld/jx.tld" prefix="jx" %>
<%@ taglib uri="/tld/desktop.tld" prefix="dt" %>
<%@ taglib uri="/tld/desktopProviderContext.tld" prefix="dtpc" %>

<% 
String ratingDatabase = request.getParameter("rating_database");
String ratingURL = request.getParameter("rating_url");
int newRating = Integer.parseInt(request.getParameter("new_rating"));
int numRating = Integer.parseInt(request.getParameter("num_rating"));
int sumRating = Integer.parseInt(request.getParameter("sum_rating"));
int peakRating = Integer.parseInt(request.getParameter("peak_rating"));

numRating = numRating + 1; 
sumRating = sumRating + newRating; 
float tmp = (((float)sumRating) / (numRating + 1)); 
newRating = (int)Math.round(tmp); 

if (newRating > peakRating) {
    peakRating = newRating; 
}

%>

<dt:obtainChannel channel="$JSPProvider">
<dtpc:providerContext>
    <dtpc:getSessionID id="accessToken"/>
    <jx:declare id="accessToken" type="java.lang.String"/>

<%
    SOIF rd = new SOIF("DOCUMENT", ratingURL);
    rd.replace("rd-rating", newRating + ""); 
    rd.replace("rd-num-rating", numRating + ""); 
    rd.replace("rd-sum-rating", sumRating + ""); 
    rd.replace("rd-peak-rating", peakRating + ""); 

    String searchServer = (String)pageContext.findAttribute("searchServer");
    try {
	URLConnection pc = new URL(searchServer).openConnection();
	pc.setAllowUserInteraction(true);
	pc.setUseCaches(false);
	pc.setDoOutput(true);
	pc.setDoInput(true);
	SOIFOutputStream sos = new SOIFOutputStream(pc.getOutputStream()); 
	pc.connect();

	SOIF hdr = new SOIF("RDMHEADER", "-");
	hdr.insert("rdm-type", "rd-submit-request");
	hdr.insert("rdm-access-token", accessToken);
	hdr.insert("submit-database", ratingDatabase);
	sos.write(hdr); 

	SOIF req = new SOIF("Request", "-");
	req.insert("submit-type", "persistent"); 
	req.insert("submit-operation", "update"); 
	req.insert("submit-view", "url,rd-rating,rd-num-rating,rd-sum-rating,rd-peak-rating");
	sos.write(req);
	sos.write(rd);
	sos.close();

        SOIFInputStream sis = new SOIFInputStream(pc.getInputStream());
	SOIF s;
        while ((s = sis.readSOIF()) != null) {}
    } catch (Exception e) {
	throw new Exception("Discussions: Cannot submit comments. Failed to connect to " + searchServer);
    }
%>
</dtpc:providerContext>
</dt:obtainChannel>
