Cannot upload the Image to server java.lang.IndexOutOfBoundsException: - java

I'm trying to upload some Image file to my database. When I run my code It produces the error java.lang.IndexOutOfBoundsException:. But the same code works well in another form.
My code is :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String uname = (String) request.getSession().getAttribute("uname");
//set content type
response.setContentType("text/html");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
if (! ServletFileUpload.isMultipartContent(request)) {
System.out.println("sorry. No file uploaded");
return;
}
// parse request
List<?> items = uploadHandler.parseRequest(request); //getting error
System.out.println(items.size());
// get uploaded file
FileItem file = (FileItem) items.get(0);
Connection con=prepareConnection();
con.setAutoCommit(false);
//Part photo=request.getPart("photo");
BufferedImage originalImage=ImageIO.read(file.getInputStream());
int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(resizeImageJpg, "png", baos);
baos.flush();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
StringBuilder sb=new StringBuilder(1024);
sb.append("insert into ").append(uname).append("PROFILEPICTURE values(?,?)");
String query = sb.toString();
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, 1);
ps.setBinaryStream(2, is);
int i=ps.executeUpdate();
con.commit();
con.close();
if(i==1)
{
RequestDispatcher dispatcher = request.getRequestDispatcher("/sp/profile");
if(dispatcher != null) {
dispatcher.forward(request, response);
}
}
else
{
out.println("Error ocuured");
}
out.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
console output :
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at skypark.AddProfilePict.doPost(AddProfilePict.java:79)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
And my form is:
<form id="form" method="post" action="AddProfilePict" enctype="multipart/form-data">
<input type="file" accept="image/*" style="width: 450px; border:0px; background:none; margin-top:5px; width:245px;" value="">
<input class="upld" type="submit" value="Upload">
</form>
Can anyone help me figure out what is causing the error?

items should indeed be empty. You should first check it's length and then try to fetch the items using
if(! items.isEmpty()) {
FileItem file = (FileItem) items.get(0);
}
or
if(items.size() > 0) {
FileItem file = (FileItem) items.get(0);
}

Related

Exception when submitting a page containing <s:select>

I am working on a project using Struts2. In that, there is a dynamic dropdown. Whenever I select values and submit the page I'm getting below exception. I tried a few alternatives but nothing worked for me. Below is the exception stack trace.
SEVERE: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'locname': The requested list key 'requestListLocationInfo' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:260)
at org.apache.struts2.components.Component.findValue(Component.java:356)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:84)
at org.apache.struts2.components.Select.evaluateExtraParams(Select.java:104)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:886)
at org.apache.struts2.components.UIBean.end(UIBean.java:535)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.AddReader_jsp._jspx_meth_s_005fselect_005f0(AddReader_jsp.java:592)
at org.apache.jsp.AddReader_jsp._jspx_meth_s_005fform_005f0(AddReader_jsp.java:426)
at org.apache.jsp.AddReader_jsp._jspService(AddReader_jsp.java:332)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:720)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.struts2.result.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:173)
at org.apache.struts2.result.StrutsResultSupport.execute(StrutsResultSupport.java:208)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:373)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:277)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:52)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:199)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:157)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:123)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:201)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:53)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:577)
at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
JSP Code
<s:if test="hasActionMessages()">
<div class="welcome">
<s:actionmessage />
</div>
</s:if>
<s:elseif test="hasActionErrors()">
<div class="errors">
<s:actionerror />
</div>
</s:elseif>
<div id="myDIV" style="margin-top: 8%; margin-left: 25%;">
<label>Reader IP:</label>&nbsp <input type="text" name="readerIp" id="readerIp" required>&nbsp &nbsp &nbsp <br>
<label>Antenna ID:</label>&nbsp <input type="text" name="antennaId" id="antennaId" required>&nbsp
&nbsp &nbsp <br> <label>Select Gate:</label>&nbsp
<s:select id="locname" name="locname" list = "requestListLocationInfo" listKey = "locId" listValue = "locname" headerKey = "-1" headerValue = "Select Gate" />
<br>
<button class="btn" id="newBtn"
style="margin-top: 2%; margin-left: 17%; width: 17%; text-decoration: none;"
onclick="clickedMe(this.id)">Add</button>
</div>
</s:form>
Method in Action class:
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String addReaderConfig() {
HttpServletRequest req = ServletActionContext.getRequest();
try {
String locName = req.getParameter("newButton");
int locationid = Integer.parseInt(locName);
String readerIp = req.getParameter("readerIp");
String antenaID = req.getParameter("antennaId");
int antennaId = Integer.parseInt(antenaID);
String created_by = req.getParameter("created_by");
String company_id = (String) ActionContext.getContext().getSession().get("company_id");
int companyId = Integer.parseInt(company_id);
int i = ChartDAO.addReader(readerIp, antennaId, locationid, companyId, created_by);
if (i > 0) {
msg = Constants.READER_ADDED_SUCCESSFULLY;
addActionMessage(msg);
} else {
msg = Constants.READER_ADDING_FAILED;
addActionError(msg);
return Constants.ERROR;
}
} catch (Exception e) {
e.printStackTrace();
return Constants.ERROR;
}
return Constants.SUCCESS;
}
POJO
private int locId;
private String locname;
private List < ChartPOJO > requestListLocationInfo = null;
public String getLocname() {
return locname;
}
public void setLocname(String locname) {
this.locname = locname;
}
public int getLocId() {
return locId;
}
public void setLocId(int locId) {
this.locId = locId;
}
public List < ChartPOJO > getRequestListLocationInfo() {
return requestListLocationInfo;
}
public void setRequestListLocationInfo(List < ChartPOJO > requestListLocationInfo) {
this.requestListLocationInfo = requestListLocationInfo;
}
Method in DAO class
public static int addReader(String readerIp, int antennaId, int locId, int company_id, String created_by) {
int status = 0;
String driverClass = Constants.DB_Driver;
Class.forName(driverClass);
String url = Constants.DB_Address;
String username = Constants.DB_Username;
String password = Constants.DB_Password;
try (Connection conn = DriverManager.getConnection(url, username, password);) {
try (PreparedStatement ps1 = conn.prepareStatement("select locationid,loc_name from locations where locationid=?");) {
ps1.setInt(1, locId);
try (ResultSet rs2 = ps1.executeQuery();) {
if (!rs2.next()) {
String query = "INSERT INTO reader(ipaddress,antenaid,companyid,locationid,status,created_by,created_date) values(?,?,?,?,?,?,?)";
try(PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, readerIp);
ps.setInt(2, antennaId);
ps.setInt(3, company_id);
ps.setInt(4, locId);
ps.setInt(5, 1);
ps.setString(6, created_by);
LocalDateTime now = LocalDateTime.now();
System.out.println("Before : " + now);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = now.format(formatter);
System.out.println("After : " + formatDateTime);
ps.setString(7, formatDateTime);
status = ps.executeUpdate();
System.out.println("after adding reader successfully");
}
} else {
System.out.println("location already exists");
}
}
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
return status;
}
return status;
}
May I know the reason for this exception and how to fix it. Thanks in advance.
You have to remove listKey or resolve it in select field somewhere in you project.
Your logs complain about requestListLocationInfo list probably without properly listKey value or with null value

Executing Unix command from jsp

So I need a unix command to be executed by clicking a button in a jsp.
Here's the jsp:
<body>
<div align="center">
<h2>Welcome to ETL Automation Testing Tool</h2>
<h3>Please select Graph:</h3>
<table border="1">
<th>Graph</th>
<tr>
<td>Graph 1</td>
<td><INPUT TYPE="radio" NAME="graph" VALUE="radio1"></td>
</tr>
</table>
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</body>
All pretty straightforward there.
Here's the servlet:
#WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UnixPrompt unixprompt = new UnixPrompt();
unixprompt.connect();
}
}
Here's the code to connect to ssh and execute a command:
import com.jcraft.jsch.*;
import java.io.*;
public class UnixPrompt{
public static void connect(){
try{
JSch jsch=new JSch();
String host=null;
String user="******";
host="*******";
String config =
"Port 22\n"+
"\n"+
"Host foo\n"+
" User "+user+"\n"+
" Hostname "+host+"\n"+
"Host *\n"+
" ConnectTime 30000\n"+
" PreferredAuthentications keyboard-interactive,password,publickey\n"+
" #ForwardAgent yes\n"+
" #StrictHostKeyChecking no\n"+
" #IdentityFile ~/.ssh/id_rsa\n"+
" #UserKnownHostsFile ~/.ssh/known_hosts";
ConfigRepository configRepository =
com.jcraft.jsch.OpenSSHConfig.parse(config);
jsch.setConfigRepository(configRepository);
Session session=jsch.getSession("foo");
String passwd ="*****";
session.setPassword(passwd);
UserInfo ui = new MyUserInfo(){
public boolean promptYesNo(String message){
int foo = 0;
return foo==0;
}
};
session.setUserInfo(ui);
session.connect();
String command="pwd";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String arg[]){
connect();
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return null; }
public boolean promptYesNo(String str){ return false; }
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return false; }
public boolean promptPassword(String message){ return false; }
public void showMessage(String message){ }
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
return null;
}
}
}
I am able to connect to the SSH and execute commands through the standalone UnixPrompt class but am not able to do so through the jsp.
This is the error I am getting:
SEVERE: Servlet.service() for servlet [unix.MyServlet] in context with
path [/Scratchpad] threw exception [Servlet execution threw an
exception] with root cause java.lang.ClassNotFoundException:
com.jcraft.jsch.ConfigRepository at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1858)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1709)
at unix.MyServlet.doPost(MyServlet.java:17) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
The class the error refers to is present in the newer JSch jar having version 0.1.54 which I have included in the build path so I'm not sure what the problem is.
Any help would be appreciated

Java exception in openConnection method (fetching data from html)

I have a problem getting the input stream using 'getInputStream' method for few URLs (most of the URLs works fine) although the URL seems to work via web browser.
I am using the following code:
public static String getContents(String uri, String encoding) {
StringBuffer sb = new StringBuffer();
URL url;
try {
url = new URL(uri);
URLConnection con = url.openConnection();
con.setReadTimeout(90000);
System.out.println("--------2.1:");//////////////////////////////////////////////////////////////
InputStream is = con.getInputStream();
System.out.println("--------2.2:"+is);/////////////////////////////////////////////////////////
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// read lines from HTML
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
System.out.println("--------2.6:");//////////////////////////////////////////////////////
return null;
}
return sb.toString();
}
output:
--------2.1:http://infoscience.epfl.ch/oai2d?verb=ListIdentifiers&metadataPrefix=oai_dc
--------2.6:
Exception:
java.io.IOException: Server returned HTTP response code: 503 for URL: http://infoscience.epfl.ch/oai2d?verb=ListIdentifiers&metadataPrefix=oai_dc
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.irWizard.common.util.FileUtils.getContents(FileUtils.java:29)
at com.irWizard.web.controller.WizardController.getActualTotalOfRecords(WizardController.java:500)
at com.irWizard.web.controller.WizardController.validateSets(WizardController.java:419)
at com.irWizard.web.controller.WizardController.onSubmit(WizardController.java:242)
at com.irWizard.web.controller.BaseController.onSubmit(BaseController.java:127)
at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:258)
at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:652)
at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:257)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:45)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:728)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:350)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
It seems that it's code 503.
Does anyone know how it can be solved? (it works fine via browser).
Mike

Spring MVC - Get non-mulitpart form/data in Multipart HTTP Post

Form my client application (AngularJS), I am uploading a file and some other data as FormData.
var formData=new FormData();
formData.append("file",file.files[0]); //files
formData.append("docData", angular.toJson($scope.docdata)); //invoice
Value of angular.toJson($scope.docdata) is like {"configuration":20,"title":"invoicedata"}
This is my HTTP post
$http({
method: 'POST',
url: uploadurl,
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
})
.success(function(data, status) {
alert("Error");
})
.error(function(data, status) {
alert("Error");
});
The request is getting in my Spring MVC controller and I am able to process with the file. But the other data (docData), I am not able to get.
Here is my UploadController.java
#Controller
public class UploadController {
#RequestMapping(value="/newDocument", method = RequestMethod.POST)
public void UploadFile(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
Iterator<String> itr=mRequest.getFileNames();
while(itr.hasNext()){
MultipartFile file=mRequest.getFile(itr.next());
String fileName=file.getOriginalFilename();
try {
File newFile = new File("/home/myHome/file-uploaded/"+fileName);
// if the directory does not exist, create it
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileCopyUtils.copy(file.getBytes(), newFile);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
Enumeration<String> parametrs = request.getParameterNames();
while(parametrs.hasMoreElements()) {
String param=parametrs.nextElement();
System.out.println("Param : " + param);
Object object=request.getAttribute(param);
System.out.println("Param Instance" + object.getClass().getName());
}
}
}
The first part is working perfectly. (Copying file to the directory). But the second part giving me an exception. First it prints the value of param which is docData the one I send form client app in FormData. Then it throws the exception
java.lang.NullPointerException
at com.serverapp.demoapp.web.UploadController.UploadFile(UploadController.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Line 63 refers to System.out.println("Param Instance" + object.getClass().getName());
which means the object is null
How to get the values?
When you use multipart then your form fields are included in request Stream. So you have to check whether they are form fields or not.
This is what I use in a servlet, you can make appropriate changes in it to work in Spring-MVC.
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
String name = item.getFieldName();
String value = item.getString();
System.out.println(name+value);
}
if (!item.isFormField())
{
//your code for getting multipart
}
}
}

Unable to connect to database based on property file

Hi I'm new in java/jsp developing.
I'm trying to connect to database depending on parameter that jsp file receives from previous page.
My program works if i connect to single DB like
try {
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/db.properties");
properties.load(in);
connString = properties.getProperty("db_conn").toString();
connUser = properties.getProperty("db_user").toString();
connPass = properties.getProperty("db_pass").toString();
bPath = properties.getProperty("exec_path").toString();
in.close();
} catch (IOException ex) {
System.out.println(ex);
}
and db.properties file contains
db_conn=jdbc:oracle:thin:#33.333.3.33:3333:DKSE1
db_user=guest
db_pass=guestpw
My attempt:
String userinfo = request.getParameter("userinfo");
try {
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/db.properties");
properties.load(in);
db_conn = userinfo + "_conn";
db_user = userinfo + "_user";
db_pass = userinfo + "_pass";
connString = properties.getProperty(db_conn).toString();
connUser = properties.getProperty(db_user).toString();
connPass = properties.getProperty(db_pass).toString();
bPath = properties.getProperty("exec_path").toString();
in.close();
} catch (IOException ex) {
System.out.println(ex);
}
try {
// --- Required database stuff ---
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn = DriverManager.getConnection(connString, connUser, connPass);
Statement stmt = conn.createStatement();
More codes....
}
db.properties
guest_conn=jdbc:oracle:thin:#33.333.3.33:3333:DKSE1
guest_user=guest
guest_pass=guestpw
user_conn=jdbc:oracle:thin#11.222.3.33:4444:ESMZ1
user_user=user
user_pass=upw1
user1_conn=jdbc:oracle:thin#11.11.1.11:1111:GEPD1
user1_user=user1
user1_pass=upw1
batch_exec_path = ${SERVER_DIR}
Stacktrace
Nov 30, 2012 9:03:55 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/dashboard] threw exception [An exception occurred processing JSP page /alpharunBatch.jsp at line 106
103: db_conn = userinfo + "_conn";
104: db_user = userinfo + "_user";
105: db_pass = userinfo + "_pass";
106: connString = properties.getProperty(db_conn).toString();
107: connUser = properties.getProperty(db_user).toString();
108: connPass = properties.getProperty(db_pass).toString();
109: bPath = properties.getProperty("exec_path").toString();
Stacktrace:] with root cause
java.lang.NullPointerException
at org.apache.jsp.alpharunBatch_jsp._jspService(alpharun_jsp.java:192)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Am i doing something fundamentally wrong?
Thanks for your help!
try following for test:
change that
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/db.properties");
to
InputStream in = getServletContext().getResourceAsStream("db.properties");
and put your properties in the classpath folder(src)
Furthermore change
properties.getProperty("exec_path").toString();
to
properties.getProperty("batch_exec_path").toString();

Categories