How to make pagination using sublist - java

hello there i got a problem with pagination with sublist..
right know i can load the first 50 data from data..but when i click "2" link to load other page its doesnt load anything i notice that my code is use from and to and it will load only from and to..but how to increment from and to???can anyone give me some example..
here is the example
int from= 0;
int to = 50;
List subList = logList.subList(from, to);
//pagination
if (logList.size()>50){
setTotalSessionRecord(logList.size());
int sessionCountPages = (logList.size()/subList.size());
if ((logList.size() % subList.size()) > 0) {
sessionCountPages++;
}
setTotalSessionPage(sessionCountPages);
if (getSessionPage() == 0) {
setSessionPage(1);
} else if (getSessionPage() > getTotalSessionPage()) {
setSessionPage(getTotalSessionPage());
}
int startPages = (getSessionPage() - 1) * logList.size();
startPages++;
arg = new ArgumentBuilder();
arg.addArg(getSessionLogId());
arg.addArg(startPages);
arg.addArg(logList.size());
arg.addArg(isAsCending());
//end of pagination
in my jsp
function toSessionPage(sessionPage, ascOrderSession , id,
folderId , numberOfSessions , selectedSessionPages) {
var tURL = '<%=request.getContextPath()%>/home/Folder.action?
listSessionLogEvents=&sessionLogId=' + id + '&folderID=' + folderId +
'&sessionPage=' + sessionPage + '&numberOfSessionPages='+ numberOfSessions
+ '&selectedSessionPages=' + selectedSessionPages
+ '&asCending=' + ascOrderSession ;
jQuery.ajax({
url: tURL,
dataType: 'html',
success: function(returnData) {
jQuery('#detailTR' + id).html(returnData);
}
});
}
function toSelectedSessionPages(sessionPage, selectedSessionPages,
ascOrderSession,id ,folderId) {
var tURL = '<%=request.getContextPath()%>/home/Folder.action?
listSessionLogEvents=&sessionLogId=' + id + '&folderID=' + "11"
+ '&sessionPage=' + sessionPage + '&selectedSessionPages='
+ selectedSessionPages +'&asCending=' + ascOrderSession ;
jQuery.ajax({
url: tURL,
dataType: 'html',
success: function(returnData) {
jQuery('#detailTR' + id).html(returnData);
}
});
}
in load jsp..
<td align="center" width = "60%" >
Page:
<%
int toSessionPage = 0;
if(fa.getTotalSessionPage() - fa.getNumberOfSessionPages() > 20){
toSessionPage = fa.getNumberOfSessionPages() + 19;
}else{
toSessionPage = fa.getTotalSessionPage();
}
int i = 0;
for ( i= fa.getSelectedSessionPages(); i <= toSessionPage; i++) {
if (fa.getSessionPage() == i) {%>
<font class="selectedPage"><%=i%></font>
<% } else { %>
<a href="javascript:toSelectedSessionPages(<%=i%>,${actionBean.selectedSessionPages},
'${actionBean.asCending}', '${actionBean.sessionLogId}')">
<font class="unselectedPage"><%=i%></font></a>
<% }
if(i != toSessionPage) { %><font class="unselectedPage">|</font><% }
} fa.setNumberOfSessionPages(i); %>
</td>

Related

Java Array index out of bounds error shows sometimes

I've been handed a task to update old code to use Google Custom Site Search. Code below.
The form seems to be working about 95%, But I'm running into an issue when a search is performed I'm getting an "java.lang.ArrayIndexOutOfBoundsException" error.
It seems that some search queries work and other do not.
For Example I run a search using "Hurricane" I'll get the above error. But let's say I search "Hurricane Matthew" it will return x amount of results.
I expect it has to do with line 29 (Notepadd++) of the code
int maxNumReturned = 1000;
along with this line 161
&start + (expectedResultCount - resultsPerPage)
When a serach is performed successfully I'm able to get all the print line to display (Spot 1, spot 1.2 exc to 3.1)
When a search fails it is breaking at Println 3 and not printing out 3.1
looking for some help to be pointed in the right direction, keep in mind that this is very old code
Error that is printed out:
spot 1 spot 1.1 spot 1.2 spot 2 spot 3 757 The page you are trying to view is unavailable. Please try again later
java.lang.ArrayIndexOutOfBoundsException
See code below:
<%
String searchURI = request.getQueryString();
String requestTemp = request.getParameter("num");
requestTemp = stripXSS(encodeHTML(requestTemp));
String query = request.getParameter("q");
query = encodeHTML(query);
String client = request.getParameter("client");
int ud = 1;
query = stripXSS(query);
// Get encoded query
int queryPos = searchURI.indexOf("&q=");
queryPos = queryPos + 3;
String subQuery = searchURI.substring(queryPos);
int j = subQuery.indexOf('&');
if ( j > -1) // Found
subQuery = subQuery.substring(0, j);
String site = request.getParameter("site");
site = encodeHTML(site);
String keyword = "null:" + query;
String resultCount="zero";
int resultsPerPage = 5;
try{
resultsPerPage = Integer.parseInt(request.getParameter("num"));
} catch(Exception e) {
}
int maxNumReturned = 1000;
int PageNo= 0;
int NextPage=0;
int PrevPage=0;
boolean sortByRelevance=true;
String previous = "";
String next = "";
String currentPage ="";
String resultsFrom="";
int total = 0;
int totalPages = 0;
int startResults = 0;
requestTemp = request.getParameter("start");
requestTemp = encodeHTML(requestTemp);
if (requestTemp == null) {
startResults = 0;
} else {
startResults = Integer.parseInt(requestTemp);
if (startResults == 1){
startResults = 0;
}
}
int fromRequest = searchURI.indexOf("?status=RMI1");
if (fromRequest >=0){
searchURI = searchURI.substring(0,fromRequest);
}
int fromRequestQuery = query.indexOf("?status=RMI1");
if (fromRequestQuery >=0) {
query = query.substring(0,fromRequestQuery);
}
if (site == null) {
site = "www.test.com";
}
PageNo = startResults;
String runSearch = request.getParameter("OPN");
%>
<form name="searchform" action="?" method="get" id="searchpg">
<input type="hidden" name="output" value="xml_no_dtd">
<input type="hidden" name="sort" value="date:D:L:d1">
<input type="hidden" name="client" value="google-csbe"> <!-- default_frontend -->
<input type="hidden" name="ud" value="1">
<input type="hidden" name="oe" value="UTF-8">
<input type="hidden" name="ie" value="UTF-8">
<input type="hidden" name="OPN" value="RT1">
<input type="hidden" name="num" value="<%=resultsPerPage%>">
<input type="hidden" name="start" value="0">
<input type="hidden" name="site" value="<%=site%>">
<input type="hidden" name="cx" value="&cx=00100000009622659069:xxxxxx_xxxx">
<span class="search_area">
<input type="text" id="q" name="q" class="txtbox" />
<input type="image" src="/siteImages//searchresults_submit.gif" alt="Submit" id="searchpg_submit" />
</span>
</form>
<%!
public String KWMatch(Node node) {
Node childNode = node.getFirstChild();
String docURI = "";
String GD = null;
String docTitle = null;
String docDesc = "";
while(childNode != null) {
//print link
String nodeName = childNode.getNodeName();
if (nodeName.equals("GL")){
docURI = childNode.getFirstChild().getNodeValue();
}else if (nodeName.equals("GD")){
GD = childNode.getFirstChild().getNodeValue();
if (GD.indexOf("|") > -1) {
docTitle = GD.substring(0, GD.indexOf("|"));
docDesc = GD.substring(GD.indexOf("|")+1, GD.length());
} else {
docTitle = GD;
}
}
childNode = childNode.getNextSibling();
}
//Begin 'search_res' div to hold one search result listing
return("<div class=\"search_res\">" + docTitle + "<p>" + docDesc + "</p></div>");
}
%>
<%
try {
if ("RT1".equals(runSearch)){
out.println("spot 1");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
URL url = new URL("http://xx.xxx.xxx.xx:5454/test/search?" + searchURI);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
Document searchDoc = docBuilder.parse(conn.getInputStream());
out.println("spot 1.1");
Element searchElements = searchDoc.getDocumentElement();
NodeList resultsList = searchElements.getElementsByTagName("R");
NodeList resultsCount = searchElements.getElementsByTagName("M");
NodeList keymatchCount = searchElements.getElementsByTagName("GM");
out.println("spot 1.2");
String preNext = "";
out.println("spot 2");
if(resultsCount.getLength() <= 0 && keymatchCount.getLength() > 0){
out.print("<h2 class=\"searchpage\">" + keymatchCount.getLength() + " results found for " + query + "</h2>");
for(int i=0; i<keymatchCount.getLength(); i++) {
Node node = keymatchCount.item(i);
out.print(KWMatch(node));
}
} else if(resultsCount.getLength() > 0){
Node totalNode = resultsCount.item(0);
int expectedResultCount = Integer.parseInt(totalNode.getFirstChild().getNodeValue()) + (int) keymatchCount.getLength();
if (expectedResultCount > maxNumReturned){
expectedResultCount = maxNumReturned;
}
// String encodedQuery = java.net.URLEncoder.encode(query);
String encodedQuery = subQuery;
String googleQuery = "q=" + encodedQuery + "&output=xml_no_dtd" + "&sort=" + "date:D:S:d1" + "&client=" + client + "&ud=" + ud + "&oe=UTF-8" + "&ie=UTF-8"
+ "&site=" + site + "&start=" + (expectedResultCount - resultsPerPage) + "&num=" + resultsPerPage + "&cx=00100000009622659069:xxxxxx_xxxx";
URL subUrl = new URL("http://xx.xxx.xxx.xx:5454/test/search?" + googleQuery);
URLConnection subConn = subUrl.openConnection();
subConn.setConnectTimeout(10000);
subConn.setReadTimeout(10000);
Document gSearchDoc = docBuilder.parse(subConn.getInputStream());
Element gSearchElements = gSearchDoc.getDocumentElement();
NodeList gResultsList = gSearchElements.getElementsByTagName("R");
out.println("spot 3");
Node lastResultNode = gResultsList.item(gResultsList.getLength() -1);
out.println("spot 3.1");
String lastResultNum = lastResultNode.getAttributes().getNamedItem("N").getNodeValue();
total = Integer.parseInt(lastResultNum) + keymatchCount.getLength();
keyword = query;
resultCount=String.valueOf(total);
Node firstNode =resultsList.item(0);
Node lastNode = resultsList.item(resultsList.getLength()-1);
String firstResultNum = firstNode.getAttributes().getNamedItem("N").getNodeValue();
lastResultNum= lastNode.getAttributes().getNamedItem("N").getNodeValue();
//Node totalNode = resultsCount.item(0);
//total = Integer.parseInt(totalNode.getFirstChild().getNodeValue());
totalPages = (total/resultsPerPage)+1;
startResults = startResults/resultsPerPage;
out.println("spot 4");
out.println(site);
out.print("<h2 class=\"searchpage\">" + total + " results found for \"" + query + "\"</h2>");
if(keymatchCount.getLength() > 0 && startResults == 0){
for(int i=0; i<keymatchCount.getLength(); i++) {
Node node = keymatchCount.item(i);
out.print(KWMatch(node));
}
}
if(startResults == 0 || total <= resultsPerPage){
NextPage=(PageNo/resultsPerPage) +1;
PrevPage = 0;
if (total <= resultsPerPage) {
next= "";
resultsFrom = "";
} else {
next= "<a href='javascript:NextValues()'><img src='/siteImages/page_right.gif' width='5' height='10' /></a>";
//resultsFrom = (1+ PageNo) + " - " + (PageNo + resultsPerPage) + " of " + total;
resultsFrom = firstResultNum + " - " + lastResultNum + " of " + total;
}
previous = "";
} else if(startResults==(totalPages -1)) {
NextPage=(PageNo/resultsPerPage) +1;
PrevPage =(PageNo/resultsPerPage)-1;
//resultsFrom = "1 - " + (PageNo + resultsPerPage) + " of " + total;
resultsFrom = firstResultNum + " - " + lastResultNum + " of " + total;
next = "";
previous= "<a href='javascript:PrevValues()'><img src='/siteImages/page_left.gif' width='5' height='10' /></a>";
} else {
NextPage=(PageNo/resultsPerPage) +1;
PrevPage =(PageNo/resultsPerPage)-1;
//resultsFrom = (1 + PageNo) + " - " + (PageNo + resultsPerPage) + " of " + total;
resultsFrom = firstResultNum + " - " + lastResultNum + " of " + total;
next= "<a href='javascript:NextValues()'><img src='/siteImages/page_right.gif' width='5' height='10' /></a>";
previous= "<a href='javascript:PrevValues()'><img src='/siteImages/page_left.gif' width='5' height='10' /></a>";
}
} else {
out.print("<h2 class=\"searchpage\">No Results Found results found for \"" + query + "\"</h2>");
}
try{
for(int i=0; i< resultsList.getLength(); i++) {
Node node = resultsList.item(i);
Node childNode = node.getFirstChild();
String docURI = "";
String docTitle = null;
String docDesc = "";
while(childNode != null) {
//print link
String nodeName = childNode.getNodeName();
if (nodeName.equals("U")) {
docURI = childNode.getFirstChild().getNodeValue();
} else if (nodeName.equals("T")) {
docTitle = childNode.getFirstChild().getNodeValue();
} else if (nodeName.equals("S")) {
try{
docDesc = childNode.getFirstChild().getNodeValue();
}catch(Exception e){}
} else { }
childNode = childNode.getNextSibling();
}
%>
<!-- Begin 'search_res' div to hold one search result listing -->
<div class="search_res"> <%=docTitle%>
<p><%=docDesc%></p>
</div>
<%
}
}catch(Exception e){
}
}
} catch (Exception e) {
out.println("The page you are trying to view is unavailable. Please try again later");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
out.println("" + sw.toString());
}
%>

xmlhttp.status returns 0

I have this java script code for ajax and I'm having trouble of get response.
xmlhttp.status always become 0. I have repeatCallHr Servlet and getting parameters from jsp page as follows.
function loadResults() {
var tt = document.getElementById("StartDate");
alert(tt);
if (xmlhttp) {
var query = "repeatCallHr?skill="
+ document.getElementById("ServiceCode").value
+"&startDate="+document.getElementById("StartDate").value
+"&startTime="+document.getElementById("StartTime").value
+"&endDate="+document.getElementById("EndDate").value
+"&endTime="+document.getElementById("EndTime").value;
xmlhttp.open("GET", query, true);
xmlhttp.onreadystatechange = loadStallsResponse;
xmlhttp.send(null);
} else {
alert("Browser not supported!");
}}
In following code I'm calling AJAX request and try to get response out of it.
function loadStallsResponse() {
alert("come here");
alert(xmlhttp.readyState);
if (xmlhttp.readyState == 4) {
alert("status is :"+xmlhttp.status);
if (xmlhttp.status == 200) {
resultList = [];
if (xmlhttp.responseText.indexOf("Error") == -1) {
alert("come to inside of status::")
console.log(xmlhttp.responseText);
stallList = $.parseJSON(xmlhttp.responseText);
populateStallData();
} else {
alert(xmlhttp.responseText);
}
} else {
alert("Error in loading salesman data");
}
}}
function populateStallData() {
var table = "<tr><th>Date</th><th>Time</th><th>Skill</th><th>Total Call</th><th>Unique Calls</th><th>Repeat Calls</th></tr>";
for (var i = 0; i < resultList.length; i++) {
table += "</td><td width='140'>"
+ resultList[i].date
+ "</td><td width='140'>"
+ resultList[i].time
+ "</td><td width='140'>"
+ resultList[i].skill
+ "</td><td width='140'><a style='color: -webkit-link; text-decoration: underline; cursor: auto;' href='http://"
+ resultList[i].totalCall
+ "</td><td width='140'>"
+ resultList[i].uniqueCall
+ "</td><td width='140'>"
+ resultList[i].repeatCall
+ "</td></tr>";
}
document.getElementById("ResultTable").innerHTML = table;}
But it gives xmlhttp.status as 0. Please help me to figure out what is the issue.

Want to filter products based on price of the products and print the filtered one

I am trying to filter the products by getting listOfProducts and ittirating over it..
public List<Products> filterByPrice(int min,int max){
List<Products> listofproducts = products.retrieveProducts();
System.out.println(listofproducts +" size: " +listofproducts.size());
for (Products productsVar : listofproducts) {
if(productsVar.getPrice()>= min && productsVar.getPrice()<= max){
return listofproducts; //here how do i print the reduced listOfProducts
}
}
return null;
}
May be its very easy one but not getting how to print out the reduced filtered products from the list
Thanks
You are printing and returning the whole list, try this:
List<Products> listofproducts = New List<Products>();
//System.out.println(listofproducts +" size: " +listofproducts.size());
for (Products productsVar : products.retrieveProducts()){
if(productsVar.getPrice()>= min && productsVar.getPrice()<= max){
listofproducts.add(productsVar);
}
return listofproducts; // may return blank list if no products fall between min and max price range
The best way for doing this is Java 8 Streams
List<Products> filteredListOfProducts = listofproducts.stream()
.filter(p -> p.getPrice >= min && p.getPrice() <= max)
.collect(Collectors.toList());
...
return filteredListOfProducts;
You can add here a lot of other type of your products processing. See java.util.stream.Stream javaDoc
This code is to add a price range and value filter for products
Please correct if wrong :)
Add this method to your sevlet
public int[] getMaxMinForConstraint() {
int[] array = new int[4]; //statement
String query = "SELECT min(price),max(price),min(owners),max(owners) from products";
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
if (rs != null) {
if(rs.next()) {
for(int i=1;i<=4;i++)
{
array[i-1]=rs.getInt(i);
}
Then add this code to your jsp or html to insert slider for price and input box for number of owners
<div class="slider">
<label>Custom Price</label>
<div id="price" data-min="0" data-max="
<%=getMaxMinForContraint[1]%>" data-min-name="min_price" data-max-name="min_price"
data-unit="USD" class="slider" aria-disabled="false"></div>
<div class="clearfix"></div>
</div>
<div class="form">
<div class="input">
<select id="owners" class="form">
<option value=""> </option>
<%for (int i = getMaxMinForConstraint[3]; i <= maxminValuesForSearch[4]; i++) {%>
<option value="<%=i%>"><%=i%></option>
<%}%>
</select>
<i class=""></i>
</div>
</div>
<button class="btn" onclick="myfun()">Find Product</button>
Then add this function to find the product
function myfun()
{
var $min_price = $("#price").slider("values", 0);
var $max_price = $("#price").slider("values", 1);
var $owners = $("#owners").val();
if ($min_price == null || $min_price == "" || $min_price < 0)
$min_price = -1;
if ($max_price == null || $max_price == "" || $max_price < 0)
$max_price = -1;
if ($owners == null || $owners == "" || $owners < 0)
$owners = -1;
var obj = {
"min_price": $min_price,
"max_price": $max_price,
"owners":
};
//alert(JSON.stringify(obj));
// console.log(JSON.stringify(obj));
var string = ""
$.ajax({
type: "post",
url: "SearchProduct",
//cache: false,
data: JSON.stringify(obj),
success: function (result) {
manageHtml(result);
},
error: function () {
alert("Request can not Proceed at this time");
}
});
}
function manageHtml($r)
{
var $str;
var $table = $("#example1").DataTable();
$("#arrnum").text($r.length);
$("#example1").empty();
//$("#tb1").html("");
for (var i = 0; i < $r.length; i++)
{
}
$str = "<tr><td><div class=\'col-lg-12 col-md-12\'><div class=\'product listing, product 1\'><div class=\'product\'><a href=\'SingleProduct.jsp?id=" + $r[i].id + "\'><img src=\'" + $r[i].pictures + "\' class=\'img-fluid \' alt=\'\'><\/a>" <h4 class=\'productname\'><a href=\'SingleProduct.jsp?id=" + $r[i].id + "\'>" + $r[i].name + "<\/a><\/h4><img src=\'\/img\/addProduct.png\' class=\'img-fluid'><\/a><\/div><\/div><div class=\'price\'><h4 class=\'price\'>$ " + ($r[i].price) + " <\/h4><\/div><div class=\'detail-btn\'><a href=\'SingleProduct.jsp?id=" + $r[i].id + "\' class=\'more-btn\'>More Info<\/a><\/div><\/div><\/div><\/div><\/div><\/td><\/tr>";
console.log($str);
$("#example1").append($str);
Finally add the following code to your search product servlet
String jsonString = "";
BufferedReader br
= new BufferedReader(new
InputStreamReader(request.getInputStream()));
String json = "";
if (br != null) {
jsonString = br.readLine();
System.out.println("recieve" + jsonString);
}
System.out.println(jsonString != null);
if (jsonString != null /*&& logged_in && role.compareToIgnoreCase("buyer")==0*/) {
int buyer_id = ((BuyerDAO) session.getAttribute("buyer")).getId();
JSONObject obj = new JSONObject(jsonString);
int min_price, max_price,
int owners;
min_price = obj.getInt("min_price");
max_price = obj.getInt("max_price");
owners = obj.getInt("owners");
String condition = "";
if (min_price != -1) {
condition += "price>=" + min_price + " And ";
}
if (max_price != -1) {
condition += "price<=" + max_price + " And ";
}
if (owners != -1) {
condition += "owners=" + owners + " And ";
}
condition += "1=1";
ProductDB db = new ProductDB();
//set buyer id from seesion
JSONArray arr = new JSONArray(db.getAllProducts(condition, buyer_id));
// System.out.println("recieve" + obj.toString());
out.println(arr.toString());
} else {
out.println("0");
}
} else {
out.println("0");
}

Pagination click on page index load only the first page always

I am trying to paginate rows of a table inside my servlet using hibernate.But once I click on the desire index of the page it always gives me only the first set of row of the table.
My servlet code:
int pageIndex = 0;
int totalNumberOfRecords = 0;
int numberOfRecordsPerPage = 5;
String sPageIndex = request.getParameter("pageIndex");
if (sPageIndex == null) {
pageIndex = 1;
} else {
pageIndex = Integer.parseInt(sPageIndex);
}
int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;
List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class)
.setFirstResult(s)
.setMaxResults(numberOfRecordsPerPage)
.list();
for (ProductHasSize pro : phs) {... some html content here...}
List<ProductHasSize> phs1 = ses.createCriteria(ProductHasSize.class)
.setProjection(Projections.rowCount()).list();
Iterator i = phs1.iterator();
if (i.hasNext()) {
Object o = i.next();
totalNumberOfRecords = Integer.parseInt(o.toString());
}
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
for (int j = 1; j <= noOfPages; j++) {
String myurl = "products.jsp?pageIndex=" + j;
String active = j == pageIndex ? "active" : "";
pagination = pagination + "<li class='" + active + "'>" + j + "</li>";
}
Thanks in advance.
Try to replace:
if (i.hasNext()) {
With:
while(i.hasNext()) {
And write the while loop like this:
while(i.hasNext()) {
Object o = i.next();
totalNumberOfRecords += Integer.parseInt(o.toString());
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
}

Why won't my compiled GWT project run in a browser?

I have a GWT project which is very very simple: it's one module with a single EntryPoint that just calls GWT.log in order to tell me that it has compiled and run successfully.
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
public class Tester implements EntryPoint {
public void onModuleLoad()
{
GWT.log("I have compiled and run successfully");
}
}
It does compile - it spits out a bunch of files in the WAR folder.
My understanding of what I need to do to run it (based on http://www.gwtproject.org/doc/latest/FAQ_DebuggingAndCompiling.html) is that I need to run the hosted.html file in a browser and it will do all of its magic. I've put the entire WAR folder on a HTTP server (so that it can get the other files without being blocked by file:// stuff like I've had issues with in web development before) and fetched it in Chrome. It does nothing. I looked at the network monitor in it and recorded while refreshing the page - the only file ever loaded is hosted.html:
There are no errors or messages in the JavaScript console...
The resulting hosted.html is as follows:
<html>
<head><script>
var $wnd = parent;
var $doc = $wnd.document;
var $moduleName, $moduleBase, $entry
,$stats = $wnd.__gwtStatsEvent ? function(a) {return $wnd.__gwtStatsEvent(a);} : null
,$sessionId = $wnd.__gwtStatsSessionId ? $wnd.__gwtStatsSessionId : null;
// Lightweight metrics
if ($stats) {
var moduleFuncName = location.search.substr(1);
var moduleFunc = $wnd[moduleFuncName];
var moduleName = moduleFunc ? moduleFunc.moduleName : "unknown";
$stats({moduleName:moduleName,sessionId:$sessionId,subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});
}
var $hostedHtmlVersion="2.1";
var gwtOnLoad;
var $hosted = "localhost:9997";
function loadIframe(url) {
var topDoc = window.top.document;
// create an iframe
var iframeDiv = topDoc.createElement("div");
iframeDiv.innerHTML = "<iframe scrolling=no frameborder=0 src='" + url + "'>";
var iframe = iframeDiv.firstChild;
// mess with the iframe style a little
var iframeStyle = iframe.style;
iframeStyle.position = "absolute";
iframeStyle.borderWidth = "0";
iframeStyle.left = "0";
iframeStyle.top = "0";
iframeStyle.width = "100%";
iframeStyle.backgroundColor = "#ffffff";
iframeStyle.zIndex = "1";
iframeStyle.height = "100%";
// update the top window's document's body's style
var hostBodyStyle = window.top.document.body.style;
hostBodyStyle.margin = "0";
hostBodyStyle.height = iframeStyle.height;
hostBodyStyle.overflow = "hidden";
// insert the iframe
topDoc.body.insertBefore(iframe, topDoc.body.firstChild);
}
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("gecko") != -1) {
// install eval wrapper on FF to avoid EvalError problem
var __eval = window.eval;
window.eval = function(s) {
return __eval(s);
}
}
if (ua.indexOf("chrome") != -1) {
// work around __gwt_ObjectId appearing in JS objects
var hop = Object.prototype.hasOwnProperty;
Object.prototype.hasOwnProperty = function(prop) {
return prop != "__gwt_ObjectId" && hop.call(this, prop);
};
// do the same in our parent as well -- see issue 4486
// NOTE: this will have to be changed when we support non-iframe-based DevMode
var hop2 = parent.Object.prototype.hasOwnProperty;
parent.Object.prototype.hasOwnProperty = function(prop) {
return prop != "__gwt_ObjectId" && hop2.call(this, prop);
};
}
// wrapper to call JS methods, which we need both to be able to supply a
// different this for method lookup and to get the exception back
function __gwt_jsInvoke(thisObj, methodName) {
try {
var args = Array.prototype.slice.call(arguments, 2);
return [0, window[methodName].apply(thisObj, args)];
} catch (e) {
return [1, e];
}
}
var __gwt_javaInvokes = [];
function __gwt_makeJavaInvoke(argCount) {
return __gwt_javaInvokes[argCount] || __gwt_doMakeJavaInvoke(argCount);
}
function __gwt_doMakeJavaInvoke(argCount) {
// IE6 won't eval() anonymous functions except as r-values
var argList = "";
for (var i = 0; i < argCount; i++) {
argList += ",p" + i;
}
var argListNoComma = argList.substring(1);
return eval(
"__gwt_javaInvokes[" + argCount + "] =\n" +
" function(thisObj, dispId" + argList + ") {\n" +
" var result = __static(dispId, thisObj" + argList + ");\n" +
" if (result[0]) {\n" +
" throw result[1];\n" +
" } else {\n" +
" return result[1];\n" +
" }\n" +
" }\n"
);
}
/*
* This is used to create tear-offs of Java methods. Each function corresponds
* to exactly one dispId, and also embeds the argument count. We get the "this"
* value from the context in which the function is being executed.
* Function-object identity is preserved by caching in a sparse array.
*/
var __gwt_tearOffs = [];
var __gwt_tearOffGenerators = [];
function __gwt_makeTearOff(proxy, dispId, argCount) {
return __gwt_tearOffs[dispId] || __gwt_doMakeTearOff(dispId, argCount);
}
function __gwt_doMakeTearOff(dispId, argCount) {
return __gwt_tearOffs[dispId] =
(__gwt_tearOffGenerators[argCount] || __gwt_doMakeTearOffGenerator(argCount))(dispId);
}
function __gwt_doMakeTearOffGenerator(argCount) {
// IE6 won't eval() anonymous functions except as r-values
var argList = "";
for (var i = 0; i < argCount; i++) {
argList += ",p" + i;
}
var argListNoComma = argList.substring(1);
return eval(
"__gwt_tearOffGenerators[" + argCount + "] =\n" +
" function(dispId) {\n" +
" return function(" + argListNoComma + ") {\n" +
" var result = __static(dispId, this" + argList + ");\n" +
" if (result[0]) {\n" +
" throw result[1];\n" +
" } else {\n" +
" return result[1];\n" +
" }\n" +
" }\n" +
" }\n"
);
}
function __gwt_makeResult(isException, result) {
return [isException, result];
}
function __gwt_disconnected() {
// Prevent double-invocation.
window.__gwt_disconnected = new Function();
// Do it in a timeout so we can be sure we have a clean stack.
window.setTimeout(__gwt_disconnected_impl, 1);
}
function __gwt_disconnected_impl() {
__gwt_displayGlassMessage('GWT Code Server Disconnected',
'Most likely, you closed GWT Development Mode. Or, you might have lost '
+ 'network connectivity. To fix this, try restarting GWT Development Mode and '
+ 'refresh this page.');
}
// Keep track of z-index to allow layering of multiple glass messages
var __gwt_glassMessageZIndex = 2147483647;
// Note this method is also used by ModuleSpace.java
function __gwt_displayGlassMessage(summary, details) {
var topWin = window.top;
var topDoc = topWin.document;
var outer = topDoc.createElement("div");
// Do not insert whitespace or outer.firstChild will get a text node.
outer.innerHTML =
'<div style="position:absolute;z-index:' + __gwt_glassMessageZIndex-- +
';left:50px;top:50px;width:600px;color:#FFF;font-family:verdana;text-align:left;">' +
'<div style="font-size:30px;font-weight:bold;">' + summary + '</div>' +
'<div style="font-size:15px;">' + details + '</div>' +
'</div>' +
'<div style="position:absolute;z-index:' + __gwt_glassMessageZIndex-- +
';left:0px;top:0px;right:0px;bottom:0px;filter:alpha(opacity=60);opacity:0.6;background-color:#000;"></div>'
;
topDoc.body.appendChild(outer);
var glass = outer.firstChild;
var glassStyle = glass.style;
// Scroll to the top and remove scrollbars.
topWin.scrollTo(0, 0);
if (topDoc.compatMode == "BackCompat") {
topDoc.body.style["overflow"] = "hidden";
} else {
topDoc.documentElement.style["overflow"] = "hidden";
}
// Steal focus.
glass.focus();
if ((navigator.userAgent.indexOf("MSIE") >= 0) && (topDoc.compatMode == "BackCompat")) {
// IE quirks mode doesn't support right/bottom, but does support this.
glassStyle.width = "125%";
glassStyle.height = "100%";
} else if (navigator.userAgent.indexOf("MSIE 6") >= 0) {
// IE6 doesn't have a real standards mode, so we have to use hacks.
glassStyle.width = "125%"; // Get past scroll bar area.
// Nasty CSS; onresize would be better but the outer window won't let us add a listener IE.
glassStyle.setExpression("height", "document.documentElement.clientHeight");
}
$doc.title = summary + " [" + $doc.title + "]";
}
function findPluginObject() {
try {
return document.getElementById('pluginObject');
} catch (e) {
return null;
}
}
function findPluginEmbed() {
try {
return document.getElementById('pluginEmbed')
} catch (e) {
return null;
}
}
function findPluginXPCOM() {
try {
return __gwt_HostedModePlugin;
} catch (e) {
return null;
}
}
gwtOnLoad = function(errFn, modName, modBase){
$moduleName = modName;
$moduleBase = modBase;
// Note that the order is important
var pluginFinders = [
findPluginXPCOM,
findPluginObject,
findPluginEmbed,
];
var topWin = window.top;
var url = topWin.location.href;
if (!topWin.__gwt_SessionID) {
var ASCII_EXCLAMATION = 33;
var ASCII_TILDE = 126;
var chars = [];
for (var i = 0; i < 16; ++i) {
chars.push(Math.floor(ASCII_EXCLAMATION
+ Math.random() * (ASCII_TILDE - ASCII_EXCLAMATION + 1)));
}
topWin.__gwt_SessionID = String.fromCharCode.apply(null, chars);
}
var plugin = null;
for (var i = 0; i < pluginFinders.length; ++i) {
try {
var maybePlugin = pluginFinders[i]();
if (maybePlugin != null && maybePlugin.init(window)) {
plugin = maybePlugin;
break;
}
} catch (e) {
}
}
if (!plugin) {
// try searching for a v1 plugin for backwards compatibility
var found = false;
for (var i = 0; i < pluginFinders.length; ++i) {
try {
plugin = pluginFinders[i]();
if (plugin != null && plugin.connect($hosted, $moduleName, window)) {
return;
}
} catch (e) {
}
}
loadIframe("http://www.gwtproject.org/missing-plugin/");
} else {
if (plugin.connect(url, topWin.__gwt_SessionID, $hosted, $moduleName,
$hostedHtmlVersion)) {
// take over the onunload function, wrapping any existing call if it exists
var oldUnload = window.onunload;
window.onunload = function() {
// run wrapped unload first in case it is running gwt code
!!oldUnload && oldUnload();
try {
// wrap in try/catch since plugins are not required to supply this
plugin.disconnect();
} catch (e) {
}
};
} else {
if (errFn) {
errFn(modName);
} else {
__gwt_displayGlassMessage(
"Plugin failed to connect to Development Mode server at " + simpleEscape($hosted),
"Follow the troubleshooting instructions at "
+ "<a href='http://code.google.com/p/google-web-toolkit/wiki/TroubleshootingOOPHM'>"
+ "http://code.google.com/p/google-web-toolkit/wiki/TroubleshootingOOPHM</a>");
}
}
}
}
function simpleEscape(originalString) {
return originalString.replace(/&/g,"&")
.replace(/</g,"<")
.replace(/>/g,">")
.replace(/\'/g, "'")
.replace(/\"/g,""");
}
// Lightweight metrics
window.fireOnModuleLoadStart = function(className) {
$stats && $stats({moduleName:$moduleName, sessionId:$sessionId, subSystem:'startup', evtGroup:'moduleStartup', millis:(new Date()).getTime(), type:'onModuleLoadStart', className:className});
};
window.__gwt_module_id = 0;
</script></head>
<body>
<font face='arial' size='-1'>This html file is for Development Mode support.</font>
<script><!--
// Lightweight metrics
$stats && $stats({moduleName:$moduleName, sessionId:$sessionId, subSystem:'startup', evtGroup:'moduleStartup', millis:(new Date()).getTime(), type:'moduleEvalEnd'});
// OOPHM currently only supports IFrameLinker
var query = parent.location.search;
if (!findPluginXPCOM()) {
document.write('<embed id="pluginEmbed" type="application/x-gwt-hosted-mode" width="10" height="10">');
document.write('</embed>');
document.write('<object id="pluginObject" CLASSID="CLSID:1D6156B6-002B-49E7-B5CA-C138FB843B4E">');
document.write('</object>');
}
// look for the old query parameter if we don't find the new one
var idx = query.indexOf("gwt.codesvr=");
if (idx >= 0) {
idx += 12; // "gwt.codesvr=".length() == 12
} else {
idx = query.indexOf("gwt.hosted=");
if (idx >= 0) {
idx += 11; // "gwt.hosted=".length() == 11
}
}
if (idx >= 0) {
var amp = query.indexOf("&", idx);
if (amp >= 0) {
$hosted = query.substring(idx, amp);
} else {
$hosted = query.substring(idx);
}
// According to RFC 3986, some of this component's characters (e.g., ':')
// are reserved and *may* be escaped.
$hosted = decodeURIComponent($hosted);
}
query = window.location.search.substring(1);
if (query && $wnd[query]) setTimeout($wnd[query].onScriptLoad, 1);
--></script></body></html>
What do I do?

Categories