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());
}
%>
Related
So I have some issue on my for loop. It only work on the first row of jtable and printed the same result to the whole rows. here's my code:
try {
int row = tblHasil.getRowCount();
for (int i = 0; i < row; i++) {
String tempA = (String) tblHasil.getModel().getValueAt(i, 3);
String tempB = (String) tblHasil.getModel().getValueAt(i, 4);
String tempC = (String) tblHasil.getModel().getValueAt(i, 5);
double a = Double.parseDouble(tempA);
double b = Double.parseDouble(tempB);
double c = Double.parseDouble(tempC);
VNilaiRataRata.setNilaiRataRata(a);
VTanggungan.setTanggungan(b);
VPenghasilan.setPenghasilan(c);
Rules.hitung_u();
Rules.hitung_z();
DecimalFormat df = new DecimalFormat("#########.###");
double hasildef = Double.parseDouble(df.format(Rules.defuzzifikasi()));
VKeterangan.setKeterangan(hasildef);
double keterangan = VKeterangan.getKeterangan();
double tidakLolos = VKeterangan.tidaklolos();
double cadangan = VKeterangan.cadangan();
double lolos = VKeterangan.lolos();
String desc;
if (lolos > cadangan && lolos > tidakLolos) {
desc = "Lolos";
tblHasil.setValueAt(desc, i, 6);
} else if (cadangan > tidakLolos && cadangan > lolos) {
desc = "Cadangan";
tblHasil.setValueAt(desc, i, 6);
} else {
desc = "Tidak Lolos";
tblHasil.setValueAt(desc, i, 6);
}
System.out.println("Nama : " + tblHasil.getModel().getValueAt(i, 1));
System.out.println("Hasil Fuzzi : " + hasildef);
System.out.println("Keterangan Value : " + keterangan);
System.out.println("Keterangan Tidak Lolos : " + tidakLolos);
System.out.println("Keterangan Cadangan : " + cadangan);
System.out.println("Keterangan Lolos : " + lolos);
System.out.println("Nilai Rata2 : " + VNilaiRataRata.getNilaiRataRata());
System.out.println("Tangungan : " + VTanggungan.getTanggungan());
System.out.println("Penghasilan : " + VPenghasilan.getPenghasilan());
System.out.println("Keterangan : " + desc);
System.out.println("================================");
System.out.println();
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost/db_siswa", "root", "");
int nis = Integer.parseInt(tblHasil.getModel().getValueAt(i, 0).toString());
String sql = "UPDATE nilaisiswa SET hasil='" + desc + "' WHERE nis = '" + nis + "'";
cn.createStatement().executeUpdate(sql);
}
} catch (Exception e) {
e.printStackTrace();
java.util.logging.Logger.getLogger(Proses.class.getName()).log(Level.SEVERE, null, e);
}
And here's the result (marked with red circle) :
i don't know how to use this thing
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.
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");
}
I had tried to read excel file from jsp to servlet in apache tomcat.
The below code has been receive excel file from apache folder after write the file and get that file.I need to dont write in apache tomcat.How to directly read excel file values.
The following code is MyServletUpload.java .
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.mysql.jdbc.Statement;
import com.ppts.webwatcher.Validation.Urlvalidation;
import com.ppts.webwatcher.setting.DBConnector;
import com.ppts.webwatcher.webdownload.Webpagedownload;
#WebServlet("/MyservletUpload")
public class MyservletUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;
/**
* #see HttpServlet#HttpServlet()
*/
public MyservletUpload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
int count = 1;
DBConnector db2Connector = DBConnector.getInstance();
Connection con = db2Connector.getConnection(true);
Statement stmt = null;
String compName = null;
String url_Name = null;
String message = null;
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("/");
// + File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println("file path : " + filePath);
item.write(uploadedFile);
FileInputStream fis = new FileInputStream(uploadedFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
String h = "";
int i = 1;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
break;
case Cell.CELL_TYPE_STRING:
break;
}
if (i == 1) {
h = cell.getStringCellValue();
} else {
h = h + "~" + cell.getStringCellValue();
}
i++;
}
String[] a = h.split("~");
compName = a[0].trim();
url_Name = a[1].trim();
System.out.println("company name : " + compName);
System.out.println("ulr name : " + url_Name);
try {
long ft1 = 0;
long ft2 = 0;
int lk = 0;
BufferedReader in = null;
BufferedWriter be = null;
String filenam = "";
String patr = getServletContext().getRealPath("/");
filenam = patr + "webfolder";
// System.out.println("part : " + filenam);
File filchkr = new File(filenam);
if (filchkr.exists()) {
// System.out.println("fil exists");
} else {
// System.out.println("fil not exists");
}
try {
ft1 = System.currentTimeMillis();
String line1;
// String arrsp =
// "http://www.mmrf.org/research/research.html~helwel131";
int li = compName.length();
// System.out.println("Urlname " + url_Name);
// System.out.println("companyname " +
// compName);
System.out.println("####"
+ Urlvalidation.checkInsertValidation(
url_Name, compName));
if (Urlvalidation.checkInsertValidation(
url_Name, compName) != null) {
System.out
.println("error url name >>>>>>>>> "
+ url_Name);
System.out
.println("errror url link >>>>>>>>>>>"
+ compName);
} else {
String urlreplaceText = url_Name.replace(
" ", "%20");
// System.out.println("path : "+getServletContext().getRealPath("/"));
URL url1 = new URL(urlreplaceText);
// System.out.println(url1);
String filepath = filenam + "/" + compName;
File f1 = new File(filepath);
if (!f1.exists()) {
}
boolean result = false;
try {
f1.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
String fullpath = filepath
+ "/firstdownload.html";
Webpagedownload.webdown(fullpath, url1);
lk = 1;
ft2 = System.currentTimeMillis();
long ft = ft2 - ft1;
// System.out.println(ft + ": time ");
String selection = "full_content";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(
DATE_FORMAT);
String strDateNew = sdf.format(now);
stmt = (Statement) con.createStatement();
String sql = "INSERT INTO new_table (title,url,source_selection,content,inserttime,insertvalue) VALUES ('"
+ compName
+ "','"
+ url_Name
+ "','"
+ selection
+ "','','"
+ strDateNew + "','" + '0' + "')";
stmt.executeUpdate(sql);
HttpSession session = request.getSession();
String username = String.valueOf(session
.getAttribute("username"));
String userid = String.valueOf(session
.getAttribute("userid"));
stmt.executeUpdate("insert into usersession(userid,username,createtime,urlname,urllink) values('"
+ userid
+ "','"
+ username
+ "','"
+ strDateNew
+ "','"
+ compName
+ "','" + url_Name + "')");
}
} catch (Exception e) {
System.out.println("Error: \t" + e);
System.out
.println("exception Urlname>>>>>>>>> "
+ url_Name);
System.out
.println("exception companyname >>>>>>>>>>>"
+ compName);
}
} catch (Exception e) {
System.out.println(e);
}
count++;
}
message = "success";
File file = new File(filePath);
file.delete();
}
}
getServletContext().getRequestDispatcher("/Message.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
jsp
<form method="post" action="MyservletUpload"
enctype="multipart/form-data">
Choose File : <input type="file" name="photo" size="50" /> <input
type="submit" value="Upload" onclick="uppload()">
</form>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*,java.util.*,java.io.*"%>
<%# page import="com.ppts.webwatcher.setting.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}
}
</script>
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
<style>
.textbox {
background:
url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABClpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wUmlnaHRzPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvcmlnaHRzLyIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wUmlnaHRzOk1hcmtlZD0iVHJ1ZSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NzI3NTdDRTExNUFCMTFFMUE5NURCRkMwMEFDNjhEQUMiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NzI3NTdDRTIxNUFCMTFFMUE5NURCRkMwMEFDNjhEQUMiPiA8ZGM6cmlnaHRzPiA8cmRmOkFsdD4gPHJkZjpsaSB4bWw6bGFuZz0ieC1kZWZhdWx0Ij5DcmVhdGl2ZSBDb21tb25zIEF0dHJpYnV0aW9uIE5vbi1Db21tZXJjaWFsIE5vIERlcml2YXRpdmVzPC9yZGY6bGk+IDwvcmRmOkFsdD4gPC9kYzpyaWdodHM+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjcyNzU3Q0RGMTVBQjExRTFBOTVEQkZDMDBBQzY4REFDIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjcyNzU3Q0UwMTVBQjExRTFBOTVEQkZDMDBBQzY4REFDIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+SoKR9AAAAH5JREFUeNpi/P//PwMlgImBQsDS39/fAKTrydTfyESBZhCoR/bCAig9AYgZceAFaGpRwiARKlEAxPOx2AYSS4CqSYSHAZoimEQCGh+rZmwGYDOEAZdmXAZgMwSrZnwGMKBpSMSZDghEUyLtUyIS+z+5eaGRAgc0Mg54bgQIMAAD7RsCMDpK7QAAAABJRU5ErkJggg==)
no-repeat 10px 4px #FFF;
height: 25px;
width: 275px;
border: 1px solid #848484;
padding-left: 30px;
}
</style>
<title>UPDATE SCANNER-Updated Url</title>
</head>
<%# include file="header.jsp"%>
<body>
<SCRIPT language="JavaScript">
function OnSubmitForm()
{
if(document.pressed == 'Send Email')
{
document.myform.action ="emailaction.jsp";
}
else
if(document.pressed == 'View')
{
var slvals = [];
$('input:checkbox[name=case]:checked').each(function() {
slvals.push($(this).val());
});
var i;
for (i = 0; i < slvals.length; i++) {
var url="Multitabhelp.jsp?urlid="+slvals[i];
var win = window.open(url, '_blank');
win.focus();
}
return false;
}
return true;
}
</SCRIPT>
<center>
<b><h1>Updated URL</h1> </b>
<FORM name="myform" onSubmit="return OnSubmitForm();">
<%
int co = 1;
DBConnector db2Connector = DBConnector.getInstance();
Connection conn = db2Connector.getConnection(false);
Statement stmt = null;
Statement stmt1 = null;
String time;
String urld = request.getParameter("urlid");
System.out.println("hello " + urld);
try {
stmt = conn.createStatement();
stmt1 = conn.createStatement();
String son = "";
String b = "";
String sww = "select * from updatehistory where updatetime='"
+ urld + "' and updation='1'";
System.out.println(sww);
ResultSet rs = stmt
.executeQuery("select * from updatehistory where updatetime='"
+ urld + "' and updation='1'");
out.println("<div class='CSSTableGenerator'>");
out.println("<TABLE BORDER=1 id=\"tablepaging\" class=\"yui\" align=\"center\">");
out.println("<th>"
+ " S.No"
+ "</th>");
out.println("<th>"
+ " Date"
+ "</th>");
out.println("<th>"
+ " Source Name"
+ "</th>");
out.println("<th>"
+ " URL"
+ "</th>");
out.println("<th>"
+ " Updated Content"
+ "</th>");
%>
<th><input type="checkbox" id="selectall" /></th>
<%
out.println("<th>"
+ " <label class='col-md-3 control-label'> Action</label>"
+ "</th>");
while (rs.next()) {
time = rs.getString("date_time");
ResultSet rs11 = stmt1
.executeQuery("select * from new_table where urlid='"
+ rs.getString("urlid") + "' ");
if (rs11.next()) {
System.out.println(rs11.getInt(1));
out.println("<TR>");
out.println("<TD>" + co + "</TD>");
out.println("<TD>" + rs.getString("date_time")
+ "</TD>");
out.println("<TD>" + rs11.getString("title")
+ "</a></TD>");
out.println("<TD>" + rs11.getString("url")
+ "</a></TD>");
out.println("<TD>" + rs11.getString("updatecontent")
+ "</a></TD>");
%>
<td><input type="checkbox" class="case" name="case" id="chease"
value="<%=rs.getString("urlid")%>"></td>
<%
out.println("<TD><a href=\"Showupdate.jsp?urlid="
+ rs.getString("urlid") + "\" >VIEW </a></TD>");
}
%>
<%
out.println("</TD>");
out.println("</TR>");
co++;
}
out.println("</TABLE>");
if (co < 2) {
System.out.println("************" + co);
out.println("<center> NO UPDATES </center>");
}
out.print("</div");
} finally {
try {
conn.close();
} catch (SQLException se) {
}
}
%>
<br> Enter Email ID : <input type="text" class="textbox"
name="email"> <INPUT TYPE="SUBMIT" name="Operation"
onClick="document.pressed=this.value" VALUE="Send Email"> <br>
<br> <br> Click to View Selected Update Link... <INPUT
TYPE="SUBMIT" name="Operation" onClick="document.pressed=this.value"
VALUE="View">
</FORM>
<br> <br>
<div id="pageNavPosition" style="padding-top: 20px" align="center">
</div>
<br>
</center>
<script type="text/javascript"><!--
var pager = new Pager('tablepaging', 10);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
</script>
<%# include file="footer.jsp"%>
</body>
</html>
Better to use Apache POI and do one thing if you are not using maven download the below jars and keep it in your lib
dom4j-1.6.1.jar,
poi-3.9-20121203.jar,
poi-ooxml-3.9-20121203.jar,
poi-ooxml-schemas-3.9-20121203.jar,
xmlbeans-2.3.0.jar
and then using some classes you can read excel file even a row wise or cell wise
Try this I Hope this will you.....
Hope this helps`
public class ReadExcelfile {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Statement stmt = DriverManager.getConnection("jdbc:odbc:employee").createStatement();
ResultSet rs = stmt
.executeQuery("select lastname, firstname, id from [Sheet1$]");
while (rs.next()) {
String lname = rs.getString(1);
String fname = rs.getString(2);
int id = rs.getInt(3);
System.out.println(fname + " " + lname + " id : " + id);
}
rs.close();
stmt.close();
}
}
`
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>