I have wriiten a code to read an xlxs file using Apache poi. However, I keep getting the error :
No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
The servlet is supposed to read the contents of excel file and store the data accordingly to a mySQL database.
The code is given below:
This class uploads the file to server:
package finalApplication;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class uploader extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try {
ServletFileUpload sf=new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> multifiles = sf.parseRequest(request);
//String file="";
for(FileItem item : multifiles)
{
String filename =item.getName();
item.write(new File("C:\\Users\\khuha\\eclipse-workspace\\finalApplication"+"\\"+filename));
HttpSession session=request.getSession();
session.setAttribute("file",filename);
System.out.println(session.getAttribute("file"));
}
response.sendRedirect(request.getContextPath() +"/sheetsdetails.jsp");
}
catch (Exception ex) {
System.out.println(ex);
}
}
}
This file processes the uploaded file
package finalApplication;
import java.io.FileInputStream;
import java.sql.*;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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 org.apache.poi.xssf.usermodel.XSSFWorkbookType;
public class dataCollect extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//connection to mysql
String url="jdbc:mysql://localhost:3306/Aithent";
String uname="root";
String pass="mysql";
String dbUquery="use Aithent;";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(url,uname,pass);
Statement st=con.createStatement();
st.execute(dbUquery);
// database configured------------------
//getting session -------------
HttpSession session=request.getSession();
String filename=(String) session.getAttribute("file");
//Excel file processing-----------------------------
try(FileInputStream fis= new FileInputStream("C:\\Users\\khuha\\eclipse-workspace\\firstDemo\\"+filename);){
XSSFWorkbook wb=new XSSFWorkbook(fis);
int sheetnum=Integer.parseInt(request.getParameter("sheetnumber"));
XSSFSheet sheet=wb.getSheetAt(sheetnum-1);
Row firstRow=sheet.getRow(0);
Iterator<Row> itr=sheet.iterator();
// Keys stores column names--------------------------------
int colnum=firstRow.getPhysicalNumberOfCells();
String keys[]=new String[colnum-1];
Iterator<Cell> FirstrowIterator=sheet.getRow(0).cellIterator();{
int a=1;
while(FirstrowIterator.hasNext()){
Cell date_cell=firstRow.getCell(1);
String sdate=date_cell.getStringCellValue();
boolean isSingleDigit=Pattern.matches("[0-9]-[A-Z]*[a-z]+",sdate);
boolean isDoubleDigit=Pattern.matches("[0-9][0-9]-[A-Z]*[a-z]+",sdate);
String new_date;
String new_month;
if (isSingleDigit==true){
new_date="0"+sdate.substring(0);
new_month=sdate.substring(2-5);
keys[a]=appUtils.date_maker(new_date,new_month);
}
else if (isDoubleDigit=true){
new_date=sdate.substring(0,2);
new_month=sdate.substring(3,6);
keys[a]=appUtils.date_maker(new_date,new_month);
}
}
}
String tbquery="create table if not exists "+filename+"( Name varchar(100));";
st.execute(tbquery);
int i=0;
while (i<colnum){
String addQuery="Alter table "+filename+" add "+ keys[i]+" varchar(15);";
st.execute(addQuery);
i++;
}
while(itr.hasNext()) {
//Values stores tuple info------------------------------
String values[]=new String[colnum-1];
Row row=itr.next();
Cell name_cell=row.getCell(0);
String name=name_cell.getStringCellValue();
values[0]=name;
Iterator<Cell> cellIterator=row.cellIterator();
int k=1;
while(cellIterator.hasNext()) {
Cell cell=cellIterator.next();
String dbEntry;
if (cell.getRowIndex()!=0 && cell.getStringCellValue().equals("")&& cell.getColumnIndex()!=0){
dbEntry="Blank";
}
else if(cell.getRowIndex()!=0 && ( cell.getStringCellValue().equals("F")| cell.getStringCellValue().equals("f"))&& cell.getColumnIndex()!=0) {
dbEntry="Full Day";
}
else if(cell.getRowIndex()!=0 && ( cell.getStringCellValue().equals("H")| cell.getStringCellValue().equals("h"))&& cell.getColumnIndex()!=0) {
dbEntry="Half Day";
}
else if(cell.getRowIndex()!=0 &&( cell.getStringCellValue().equals("L")| cell.getStringCellValue().equals("l"))&& cell.getColumnIndex()!=0) {
dbEntry="Leave";
}
else {
dbEntry="Invalid Entry";
}
values[k]=dbEntry;
k++;
}
String insertQ="INSERT into "+filename+"Values (";
int l=0;
while (l<colnum) {
if (l!=colnum-2){
insertQ.concat(values[l]+",");
}
else {
insertQ.concat(values[l]+");");
}
}
st.execute(insertQ);
}
wb.close();
}
catch(Exception e){
e.printStackTrace();
}
}
catch(Exception e1) {
System.out.println(e1);
}
}
}
The excel file looks like this
The servlet is getting input from another servlet in form of session attribute file. and the sheetnum is obatined from a jsp.
This image shows the output:
!output]2
If you look at the file explorer you can see the null file.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SSEServlet
*/
#WebServlet("/SSE")
public class SSE extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
PrintWriter printwriter = response.getWriter();
File file= new File("/home/user/Documents/new.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
long length = randomAccessFile.length();
String temp;
int foundLine = 0;
while (length > 0 && foundLine < 10) {
randomAccessFile.seek(length--);
if (randomAccessFile.read() == 10) {
foundLine++;
}
}
while(true)
while((temp = randomAccessFile.readLine()) != null)
{
printwriter.println(temp);
response.flushBuffer();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
In my code I am trying to get the last 10 lines and also the one that is written to file dynamically after tht 10 lines but while running my pgm am only getting the last 10 lines and not the ones written after that....in short am not able to watch the file dynamically is there any solution for this
Kindly view code at for loop part where using replace method
I am Unable to replace stop words from data I have fetched from data base.
error shows ,array bound exception:1.
Kindly view code at for loop part where using replace method
I am Unable to replace stop words from data I have fetched from data base.
error shows ,array bound exception:1.
Kindly view code at for loop part where using replace method
I am Unable to replace stop words from data I have fetched from data base.
error shows ,array bound exception:1.
I amunable to resolve it ,give me some suggestion
package chatbot;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.IntStream;
public class keywords{
private static Scanner scan2;
private static final String driverName = "oracle.jdbc.driver.OracleDriver";
private static final String QUER = null;
//private static final String SCOR = null;
// private static final String SCORE =
private static final String ANSW = null;
public static void main(String[] args) throws IOException, SQLException {
Connection con = null;
Statement stmnt = null;
ResultSet result = null;
Set<String> list1= new HashSet<>();
try {
Class.forName(driverName);
con = DriverManager.getConnection("jdbc:oracle:thin:#10.144.97.144:1521:NQLDEV", "DEVNQL", "DEVNQL");
stmnt = con.createStatement();
System.out.println("Connection established");
List<String> rsl1 = new ArrayList<>();
List<String> rsl3 = new ArrayList<>();
String query = "SELECT * FROM DEVNQL.CHATKEY";
ResultSet rs = stmnt.executeQuery(query);
while (rs.next()) {
rsl1.add(rs.getString(1));
rsl3.add(rs.getString(3));
}
//System.out.println("result "+rsl1 + " "+rsl3);
File file = new File("M:\\Documents\\stop-word-list.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine()) != null){
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(st));
//List<String> ux = new ArrayList<>(Arrays.asList(st));
for(int i=0;i<rsl1.size()-1;i++){
for(String n:wordList)
if(rsl1.contains(n.getBytes()[i])){
rsl1.get(i).replace(n.charAt(i)+"\\rsl1+", "");
//note this will remove spaces at the end
}
}
System.out.println(rsl1);
}}
// for (int i=0;i<=rsl1.size()-1;i++){
/*
for (String removeword:wordList){
System.out.println("removeword "+removeword+ " "+rsl1.get(i)+
" "+rsl1.get(i).contains(removeword));
rsl1.get(i).replace("hi","abcd********");
if (rsl1.get(i).contains(removeword)) {
rsl1.get(i).replace("hi","abcd********");
} // end if
} // end for
*/ // } // end for
// System.out.println("result "+rsl1);
// }
// System.out.println("replace "+rsl1.get(0).replace("hi", "abcde"));
// }
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
fi`enter code here`nally {
if (stmnt != null) {
stmnt.close();
}
if (con != null) {
con.close();
}
}
}}
replace actually returns a new String as in Java Strings are immutatable
so
String newString = rsl1.get(i).replace(n.charAt(i)+"\\rsl1+", "");
I'm learning about servlets in java. Bellow is my code that is suppose to get the content of the url, store it in array list and, display it on the screen. for some reason I'm unable to get the string array content to displayed on the screen. When I load the page I get the "no luck" message. Any ideas why? thanks
//package fortune;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
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 static java.util.Arrays.*;
import java.util.Collections;
import java.util.List;
#WebServlet(name = "FortuneServlet", urlPatterns = {"/"})
public class FortuneServlet extends HttpServlet {
//private String [] cookies = null;
List<String> cookies = new ArrayList<>();
String line ;
public void geturl(String[] args) {
try
{
URL url = new URL(" http://fortunes.cat-v.org/openbsd/");
//URL url = new URL(" http://bbc.com");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while((line = in.readLine()) != null)
{
cookies.add(line);
//line = in.readLine();
}
in.close();
}
catch (java.net.MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
public void init() throws ServletException {
}
#Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
if (cookies != null)
{
//response.getWriter().println(
// cookies[new Random().nextInt(cookies.length)]
//);
for (String str: cookies)
{
Collections.shuffle(cookies);
response.getWriter().println(str);
}
}
else {
response.getWriter().println("No luck!");
}
}
}
cookies is always an empty list (unless you are not showing something to us), so you always shuffle it and try to display, but because you don't have anything there you see a blank page.
I would change check cookies != null to !cookies.isEmpty().
EDIT:
You are not adding anything to the cookies list, so it is empty (List<String> cookies = new ArrayList<>();).
Maybe you wanted to call geturl (which does some add on the cookies list) method somewhere in the doGet? Right now it is not used anywhere.
I am a beginner in java programming. I am trying to read response from url and insert into database. I ran my program which is posted below and it came back with this error:
Exception in thread "main" java.lang.NullPointerException
at javaapp.JavaApplication1.parseResponseString(JavaApplication1.java:41)
at javaapp.JavaApplication1.main(JavaApplication1.java:71)
I have been trying to solve this issue on my own through research, but I could not solve it. I was wondering if anyone can help me. If you do need any other information about my program, please just ask. Thanks in advance!
And here is the code i have written
enter code here package javaapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class JavaApplication1
{
Map<String,String> responseMap=new HashMap<String, String>();
static String input;
public void getResponseFromUrl() throws IOException
{
URL url = new URL("http://localhost:8084/home/Home");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())) ;
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.contains("<h1>"))
{
String input = inputLine;
input = input.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
}
}
}
public void parseResponseString(String input)
{
String params[]=input.split(",");
for(String param:params)
{
String key= param.substring(0,param.indexOf('='));
String value= param.substring(param.indexOf('=')+1,param.length());
responseMap.put(key, value);
System.out.println(param);
}
}
public void insertToDatabase() throws SQLException, ClassNotFoundException
{
Connection conn=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","jai","jaikiran");
String insertQuery = " INSERT INTO value_1 (username1,username2,username3,username4,username5) "+
" values (?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1,responseMap.get("username1"));
pstmt.setString(2,responseMap.get("username2"));
pstmt.setString(3,responseMap.get("username3"));
pstmt.setString(4,responseMap.get("username4"));
pstmt.setString(5,responseMap.get("username5"));
pstmt.executeUpdate();
}
public static void main(String[] args) throws MalformedURLException, IOException, SQLException, ClassNotFoundException
{
JavaApplication1 application =new JavaApplication1();
application.getResponseFromUrl();
application.parseResponseString(input);//shows exception here
try {
application.insertToDatabase();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in advance,please helpme..
The static String input; is null by default and you're passing it to the parseResponseString() method.
You need to assign a value to the input variable.
I believe you wanted the assignment to be done in the getResponseFromUrl() method, where you have created a new input variable. In order to have the static String input; assigned with a value, you need to refer it with the this keyword.
if (inputLine.contains("<h1>"))
{
String input = inputLine;
this.input = input.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
}
at the getResponseFromUrl method the String input is a new variable;
you must change the String input = inputLine; to String input2 = inputLine; and input = input2.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
your code become :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class JavaApplication1
{
Map<String,String> responseMap=new HashMap<String, String>();
static String input;
public void getResponseFromUrl() throws IOException
{
URL url = new URL("http://localhost:8084/home/Home");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())) ;
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.contains("<h1>"))
{
String input2 = inputLine;
input = input2.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
}
}
}
public void parseResponseString(String input)
{
String params[]=input.split(",");
for(String param:params)
{
String key= param.substring(0,param.indexOf('='));
String value= param.substring(param.indexOf('=')+1,param.length());
responseMap.put(key, value);
System.out.println(param);
}
}
public void insertToDatabase() throws SQLException, ClassNotFoundException
{
Connection conn=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","jai","jaikiran");
String insertQuery = " INSERT INTO value_1 (username1,username2,username3,username4,username5) "+
" values (?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1,responseMap.get("username1"));
pstmt.setString(2,responseMap.get("username2"));
pstmt.setString(3,responseMap.get("username3"));
pstmt.setString(4,responseMap.get("username4"));
pstmt.setString(5,responseMap.get("username5"));
pstmt.executeUpdate();
}
public static void main(String[] args) throws MalformedURLException, IOException, SQLException, ClassNotFoundException
{
JavaApplication1 application =new JavaApplication1();
application.getResponseFromUrl();
application.parseResponseString(input);//shows exception here
try {
application.insertToDatabase();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I think your problem is here:
String input = inputLine;
input = input.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
Declaring a new variable input in the first line prevents your code to assign the value to the private field input (which is what you are probably trying to do).
Besides, the first line is useless, just remove it and use directly inputLine in the second one:
input = inputLine.substring(inputLine.indexOf("<h1>") + 4, inputLine.indexOf("</h1>"));
I can be wrong... but you define a String input as a field of your class...
I believe that you want to use in public void getResponseFromUrl() the String input field and not the local input!!
Why I say that... obviously you try in the public void parseResponseString(String input) to take the data in the input field but you don't have anything in there... so you get NullPointerException.
So what you need to change is in:
public void getResponseFromUrl() throws IOException
{
.....
/*String input = inputLine; -> wrong, because you want to use a field and not a local var... */
input = inputLine; /* now you are using the class field input */
input = input.substring...
...
}