Unable to upload the file in java - java

I am using richface and JSF .
I want to upload the image file with specific path .
But it give me error My jsf page is as follows
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich">
<ui:define name="header-title">
<h:panelGroup id="headerPanelGroup">
<span>Create New User</span>
</h:panelGroup>
</ui:define>
<ui:define name="content">
<h:form id="newUserForm" prependId="false">
<div id="mainDiv">
<div>
<rich:panel id="userPanel">
<h:panelGroup>
<h:panelGrid columns="2">
<span>Upload Photo</span>
<rich:fileUpload fileUploadListener="#{newUserBean.photoListener}" id="uploadPhoto"
style="height: 120px !important;" maxFilesQuantity="5">
<a4j:ajax event="uploadcomplete" execute="#none" render="info" />
</rich:fileUpload>
</h:panelGrid>
</h:panelGroup>
</rich:panel>
</div>
</div>
<div>
<a4j:commandButton id="saveBtn" value="Submit" action="#{newUserBean.insertEmployeeData}" />
</div>
</h:form>
</ui:define>
</ui:composition>
My Bean
public void photoListener(FileUploadEvent event) throws Exception {
UploadedFile item = event.getUploadedFile();
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
String destPath = session.getServletContext().getRealPath("/");
// String destPath = str.substring(0, str.substring(0, str.lastIndexOf(File.separator))
// .lastIndexOf(File.separator) + 1);
String filePath = "D:\\uploadImage";
File destFilePath = new File(filePath);
if (!destFilePath.exists()) {
new File(filePath).mkdirs();
}
try {
// InputStream inputstrem = new FileInputStream(new File(filePath));
// getNewUserVO().setInputstrem(inputstrem);
InputStream stream = item.getInputStream();
long fSize = item.getSize();
int lastIndex = item.getName().lastIndexOf(".");
String fileExtension = item.getName().substring(lastIndex);
System.out.println("--destPath--" + filePath + "--" + fSize + "--" + fileExtension + "----"
+ fileExtension.equalsIgnoreCase("jpg"));
if (!fileExtension.equalsIgnoreCase(".jpg")) {
FacesContext.getCurrentInstance().addMessage(
"",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_001"),
null));
} else if (fSize > 102400) {
FacesContext.getCurrentInstance().addMessage(
"",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_002"),
null));
} else {
FileOutputStream fos = new FileOutputStream(destFilePath);
byte[] buffer = new byte[(int) fSize];
stream.read(buffer, 0, (int) fSize);
stream.close();
fos.write(buffer);
fos.close();
}
} catch (FileNotFoundException e) {
FacesContext.getCurrentInstance().addMessage("",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_003"), null));
e.printStackTrace();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage("",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_004"), null));
e.printStackTrace();
}
}
Error comes like this
--destPath--D:\uploadImage--5416--.jpg----false
java.io.FileNotFoundException: D:\uploadImage (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at com.fractal.fms.modules.newUser.NewUserBean.photoListener(NewUserBean.java:167)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at org.richfaces.event.MethodExpressionEventListener.processEvent(MethodExpressionEventListener.java:125)
at org.richfaces.view.facelets.FileUploadHandler$FileUploadListenerImpl.processFileUpload(FileUploadHandler.java:55)
at org.richfaces.event.FileUploadEvent.processListener(FileUploadEvent.java:48)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:771)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:751)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:927)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:145)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:137)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
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:936)
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:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Jul 18, 2014 3:06:59 PM org.richfaces.request.MultipartRequest25 release
SEVERE: File delete failed
java.io.IOException: File delete failed
at org.richfaces.request.FileUploadDiscResource.delete(FileUploadDiscResource.java:74)
at org.richfaces.request.UploadedFile25.delete(UploadedFile25.java:54)
at org.richfaces.request.MultipartRequest25.release(MultipartRequest25.java:163)
at org.richfaces.context.FileUploadFacesContextFactory$FileUploadFacesContext.release(FileUploadFacesContextFactory.java:70)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:612)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:145)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:137)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
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:936)
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:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
What is wrong? I am not getting the problem where I am going to wrong .Thanks for the help in advanced.

I think the issue is in the
String filePath = "D:\\uploadImage";
File destFilePath = new File(filePath);
you are declaring a direction as a file, but you need a filename to write to a specific file.
for example try:
String filePath = "D:\\uploadImage";
File destFilePath = new File(filePath+"\\uploadimage.jpg");

The error
java.io.FileNotFoundException: D:\uploadImage (Access is denied)
is quite clear: the file is not found.
To quote from your code:
File destFilePath = new File(filePath);
if (!destFilePath.exists()) {
new File(filePath).mkdirs();
}
FileOutputStream fos = new FileOutputStream(destFilePath);
fos.write(buffer);
In your particular case you are initially creating a directory by calling File#mkdirs() and later trying write to the directory referenced by that File object. This is not legal.
You need to create a file and write to the file instead. For instance, you could use Java SE 7 Files#copy(...). See also How to save uploaded file in JSF.

Thanks brother , I got the answer. at line 1 and line 2 where I am going to wrong. I was not specify the image name (file name)
public void photoListener(FileUploadEvent event) throws Exception {
UploadedFile item = event.getUploadedFile();
String fileName = "";
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
String destPath = session.getServletContext().getRealPath("/");
// String destPath = str.substring(0, str.substring(0, str.lastIndexOf(File.separator))
// .lastIndexOf(File.separator) + 1);
String filePath = destPath + "/UserInfo/" + getNewUserVO().getName();
File destFilePath = new File(filePath);
if (!destFilePath.exists()) {
new File(filePath).mkdirs();
}
try {
InputStream stream = item.getInputStream();
long fSize = item.getSize();
int lastIndex = item.getName().lastIndexOf(".");
String fileExtension = item.getName().substring(lastIndex);
if (!fileExtension.equalsIgnoreCase(".jpg")) {
FacesContext.getCurrentInstance().addMessage(
"",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_001"),
null));
} else if (fSize > 102400) {
FacesContext.getCurrentInstance().addMessage(
"",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_002"),
null));
} else {
System.out.println("user name--" + getNewUserVO().getName());
fileName = getNewUserVO().getName() + fileExtension;
filePath = destFilePath + File.separator + fileName; // line 1
FileOutputStream fos = new FileOutputStream(filePath); // line 2
byte[] buffer = new byte[(int) fSize];
stream.read(buffer, 0, (int) fSize);
stream.close();
fos.write(buffer);
fos.close();
getNewUserVO().setPhotoPath(filePath);
}
} catch (FileNotFoundException e) {
FacesContext.getCurrentInstance().addMessage("",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_003"), null));
log.info(e.getMessage());
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage("",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_004"), null));
log.info(e.getMessage());
}
}

package com.journaldev.servlet;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
#WebListener
public class FileLocationContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
String rootPath = System.getProperty("catalina.home");
ServletContext ctx = servletContextEvent.getServletContext();
String relativePath = ctx.getInitParameter("tempfile.dir");
File file = new File(rootPath + File.separator + relativePath);
if(!file.exists())
file.mkdirs();
System.out.println("File Directory created to be used for storing files");
ctx.setAttribute("FILES_DIR_FILE", file);
ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//do cleanup if needed
}
}

Related

Lucene 5.3 Highlighter getBestFragments() not working

I am using the following code to take out the snippet of the retrieved results. The error shown below is coming at the line where the getBestFragment() function is used. I am using Apache Tomcat 7.0. Please help.
public JSONArray search(String indexDir,String scoring,boolean stemming) throws IOException, ParseException{
searcher = new Searcher(indexDir,scoring,stemming);
long startTime = System.currentTimeMillis();
TopDocs hits = searcher.search(query);
long endTime = System.currentTimeMillis();
JSONArray searchResultArray = new JSONArray();
StandardAnalyzer analyzer = new StandardAnalyzer();
int maxNumFragmentsRequired = 1;
QueryParser queryParser=new QueryParser(LuceneConstants.CONTENTS,analyzer);
QueryScorer scorer = new QueryScorer(queryParser.parse(query));
org.apache.lucene.search.highlight.Highlighter highlighter = new org.apache.lucene.search.highlight.Highlighter(scorer);
for(ScoreDoc scoreDoc : hits.scoreDocs) {
JSONObject searchResultObject = new JSONObject();
Document doc = searcher.getDocument(scoreDoc);
StandardAnalyzer analyzer2 = new StandardAnalyzer();
String text = doc.get(LuceneConstants.CONTENTS);
System.out.println("dfsdfsdfsdferer "+ text);
TokenStream tokenStream = analyzer2.tokenStream(LuceneConstants.CONTENTS,new StringReader(text));
highlighter.setTextFragmenter(new SimpleFragmenter(40));
String result = "";
try {
//result = highlighter.getBestFragments(tokenStream, text, maxNumFragmentsRequired,"...");
result = highlighter.getBestFragment(analyzer2, LuceneConstants.CONTENTS, text);
}
catch(Exception e)
{
e.printStackTrace();
result = "Oh Snap!!";
}
}
The error is
Sep 03, 2015 8:53:55 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.eniac.searchEngine.Search] in context with path [/Assignment1] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: org.apache.lucene.index.memory.MemoryIndex
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.getLeafContext(WeightedSpanTermExtractor.java:391)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.extractWeightedTerms(WeightedSpanTermExtractor.java:355)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.extract(WeightedSpanTermExtractor.java:150)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.getWeightedSpanTerms(WeightedSpanTermExtractor.java:518)
at org.apache.lucene.search.highlight.QueryScorer.initExtractor(QueryScorer.java:219)
at org.apache.lucene.search.highlight.QueryScorer.init(QueryScorer.java:187)
at org.apache.lucene.search.highlight.Highlighter.getBestTextFragments(Highlighter.java:196)
at org.apache.lucene.search.highlight.Highlighter.getBestFragments(Highlighter.java:156)
at org.apache.lucene.search.highlight.Highlighter.getBestFragment(Highlighter.java:102)
at org.apache.lucene.search.highlight.Highlighter.getBestFragment(Highlighter.java:80)
at com.eniac.sen.LuceneTester.search(LuceneTester.java:139)
at com.eniac.searchEngine.Search.doGet(Search.java:103)
at com.eniac.searchEngine.Search.doPost(Search.java:125)
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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
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:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
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:745)

write object to file from servlet

I'm trying to write to file from a servlet and i'm not really sure if the path i gave in the xml file is wrong or something else
private List<User> getUsersList() throws IOException, ClassNotFoundException{
List<User> users=new ArrayList<User>();
FileInputStream fis=new FileInputStream(f);
ObjectInputStream ois=new ObjectInputStream(fis);
User u;
while(true){
if((u=(User) ois.readObject())==null)
break;
else{
users.add(u);
}
}
ois.close();
return users;
}
that's the method i use to read from file where
private final String usersfile;
private ArrayList<User> users;
private File f;
public UsersService(String filename) throws ClassNotFoundException, IOException {
super();
usersfile=filename;
f=new File(this.usersfile);
if(!f.exists()){
f.createNewFile();
}
users= (ArrayList<User>) this.getUsersList();
}
and the xml param
<context-param>
<param-name>userslist</param-name>
<param-value>/users.txt</param-value>
</context-param>
and that's the exception
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at service.UsersService.getUsersList(UsersService.java:48)
at service.UsersService.<init>(UsersService.java:29)
at controller.LogServlet.doPost(LogServlet.java:43)
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 controller.LogFilter.doFilter(LogFilter.java:60)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
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:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Here we say that if there aren't any more bytes to read then we should break out of the while loop before trying to read the object, etc.
while (true) {
if (ois.readObject() == -1) break;
//...rest of the code
}

How to download a zip file in a struts2 application

I am facing a problem while enabling zip file download in struts2 application.
here is my jsp page
<%# taglib prefix="s" uri="/struts-tags"%>
<s:url id="fileDownload" namespace="/" action="Download" ></s:url>
<h4>Download file - <s:a href="%{fileDownload}">MyFile.zip</s:a>
</h4>
and here is my action class
public class DownloadAction implements Action
{
List<String> fileList = new ArrayList<String>();
private String OUTPUT_ZIP_FILE = "C:\\Users\\Ankush\\Desktop\\MyFile.zip";
private String SOURCE_FOLDER ;
private FileOutputStream fos;
private InputStream fileInputStream;
public FileOutputStream getFos() {
return fos;
}
public void setFos(FileOutputStream fos) {
this.fos = fos;
}
private ZipOutputStream zos;
public String execute()
{
Map<String, Object> session = ActionContext.getContext().getSession();
System.out.println("DOWNLOAD ACTION path="+(session.get("BASIC_PATH").toString()+session.get("username").toString()+"\\"+session.get("course_Name").toString()));
this.setSOURCE_FOLDER(session.get("BASIC_PATH").toString()+session.get("username").toString()+"\\"+session.get("course_Name").toString());
System.out.println("ORIGINOL PATH="+"E:\\Z800\\WebAuthoringData\\EMMRC\\Ankush\\Raag_Durga");
this.generateFileList(new File(this.getSOURCE_FOLDER()));
this.zipIt(OUTPUT_ZIP_FILE);
return SUCCESS;
}
public InputStream getFileInputStream() {
return fileInputStream;
}
public ZipOutputStream getZos() {
return zos;
}
public void setZos(ZipOutputStream zos) {
this.zos = zos;
}
/**
* Zip it
* #param zipFile output ZIP file location
*/
public void zipIt(String zipFile){
byte[] buffer = new byte[1024];
try{
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
for(String file : this.fileList){
System.out.println("File Added : " + file);
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
fileInputStream =
new FileInputStream(SOURCE_FOLDER + File.separator + file);
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
fileInputStream.close();
fos.flush();
zos.flush();
zos.closeEntry();
//remember close it
zos.close();
fos.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}
and my struts.xml for this
<action name="Download" class="com.cdac.action.DownloadAction">
<result name="error">/WEB-INF/jsps/error.jsp</result>
<result name="success" type="stream">
<param name="contentType">application/zip</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="MyFile.zip"</param>
<param name="bufferSize">2048</param>
</result>
</action>
and error log
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:626)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:215)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:105)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:182)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:123)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80)
at org.apache.jsp.WEB_002dINF.jsps.error_jsp._jspService(error_jsp.java:82)
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:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
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:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:593)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:530)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:166)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Nov 18, 2014 3:54:05 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger error
SEVERE: Exception occurred during processing request: java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:534)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:452)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
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:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:593)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:530)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:166)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:626)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:215)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:105)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:182)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:123)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80)
at org.apache.jsp.WEB_002dINF.jsps.error_jsp._jspService(error_jsp.java:82)
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:419)
... 32 more
Nov 18, 2014 3:54:05 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/web-authoring-tool] threw exception
java.lang.IllegalStateException
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:443)
at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:914)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:574)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please anybody help me as i don't know how to fix this issue and probably i may be doing some silly mistake but i can't figure it out. Please help me . i will be very thankful to you!
You can't write in the client File System like that; in your case, your server is in your machine, but don't get fooled, it's a server path, not a client one. You need to write on the response.
You can't use both Struts2 result and writing in the OutputStream together: when manually forging the response, you must bypass the framework convention, and return the result by yourself. The correct result for this case is is Action.NONE:
<action name="Download" class="com.cdac.action.DownloadAction" />
public String execute(){
/*
do your stuff
*/
return NONE;
}
You're lucky, here is a kick off example I've written long time ago, explaining the whole thing (including the need to deal with duplicate filenames in the same ZIP).
Also try using Content-Length properly (to let the browser draw a realistic progress-bar).

Getting "Error loading object from InputStream" exception during call JasperRunManager.runReportToPdfStream

I'm trying to generate pdf via button but my problem is this method
JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, new HashMap<Object, Object>(), resultSetDataSource);
it is not supporting Hashmap it gives following error
The method runReportToPdfStream(InputStream, OutputStream, Map<String,Object>, Connection) in the type JasperRunManager is
not applicable for the arguments (InputStream, ServletOutputStream, HashMap<Object,Object>, JRResultSetDataSource)
it Supports String parameter like Hashmap<String,Object> while generating pdf it gives following error
net.sf.jasperreports.engine.JRException: Error loading object from InputStream
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:219)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:632)
at net.sf.jasperreports.engine.JasperRunManager.runToPdfStream(JasperRunManager.java:428)
at net.sf.jasperreports.engine.JasperRunManager.runReportToPdfStream(JasperRunManager.java:849)
at com.p41.jasper.Jasper.doPost(Jasper.java:103)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:546)
at com.sun.faces.application.view.JspViewHandlingStrategy.executePageToBuildView(JspViewHandlingStrategy.java:364)
at com.sun.faces.application.view.JspViewHandlingStrategy.buildView(JspViewHandlingStrategy.java:154)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:100)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.p41.setting.FacesFilter.doFilter(FacesFilter.java:153)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
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:936)
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)
Caused by: java.io.StreamCorruptedException: invalid stream header: 3C3F786D
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at net.sf.jasperreports.engine.util.ContextClassLoaderObjectInputStream.<init>(ContextClassLoaderObjectInputStream.java:53)
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:214)
Servlet
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperRunManager;
public class Jasper extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection connection;
Statement statement;
ResultSet resultSet;
response.setContentType("text/html");
String si = request.getParameter("input");
ServletOutputStream servletOutputStream = response.getOutputStream();
byte[] bytes = null;
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("WEB-INF/HR/Jasp.jasper");
System.out.println("Print" + si);
try {
System.out.println("Second print" + si);
String query = "SELECT Where Empno = '" + si + "' ";
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/schemedb?user=root&password=root");
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(resultSet);
response.setContentType("application/pdf");
servletOutputStream.flush();
servletOutputStream.close();
System.out.println("print" + reportStream);
System.out.println("print" + servletOutputStream);
System.out.println("print" + resultSetDataSource);
JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, new HashMap<Object, Object>(), resultSetDataSource);
resultSet.close();
statement.close();
connection.close();
response.setContentType("application/pdf");
servletOutputStream.flush();
servletOutputStream.close();
} catch (Exception e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
response.setContentType("text/plain");
response.getOutputStream().print(stringWriter.toString());
}
}
}
Solution is I Removed Run Report pdf stream and used method as exportReport to pdf Stream
JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, new HashMap<Object, Object>(), resultSetDataSource);
Coding:-
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("WEB-INF/HR/Jasp.jrxml");
ByteArrayOutputStream baos =new ByteArrayOutputStream();
response.setContentType("application/pdf");
JasperDesign design = JRXmlLoader.load(reportStream);
JasperReport report = JasperCompileManager.compileReport(design);
JRResultSetDataSource jasperReports = new JRResultSetDataSource(rs);
JasperPrint print = JasperFillManager.fillReport(report, new HashMap(), jasperReports);
net.sf.jasperreports.engine.JasperExportManager.exportReportToPdfStream(print,baos);
response.setContentLength(baos.size());
ServletOutputStream out1 = response.getOutputStream();
baos.writeTo(out1);
out1.flush();
rs.close();
st.close();
conn.close();

Oracle JDBC connection issue

I'm trying to connect to Oracle dataBase in Java web project and this is the exception that I got :
java.sql.SQLException: Exception d'E/S: Got minus one from a read
call at
oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134) at
oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179) at
oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:333) at
oracle.jdbc.driver.OracleConnection.(OracleConnection.java:404) at
oracle.jdbc.driver.OracleDriver.getConnectionInstance(OracleDriver.java:468)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:314) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
mypack1.login.doPost(login.java:60) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:641) 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.ow2.jonas.web.tomcat7.CheckOpenResourcesValve.invoke(CheckOpenResourcesValve.java:69)
at
org.ow2.jonas.web.tomcat7.tx.TransactionValve.invoke(TransactionValve.java:89)
at
org.ow2.jonas.web.tomcat7.ResetAuthenticationValve.invoke(ResetAuthenticationValve.java:95)
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.ow2.jonas.web.tomcat7.versioning.VersioningValve.invoke(VersioningValve.java:105)
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:307)
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 this's my connection code:
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
out.println("<html><head><title>Hello World</title></head><body>");
out.println ("<h1>Where is your Oracle JDBC Driver?</h1>"+exceptionAsString+"</body></html>");
return;
}
out.println("<html><head><title>Hello World</title></head><body>");
out.println ("<h1>Oracle JDBC Driver Registered!</h1></body></html>");
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:3010/apex/:XE","JEE","admin");
} catch (SQLException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
out.println("<html><head><title>Hello World</title></head><body>");
out.println ("<h1>Connection Failed! Check output console</h1>"+exceptionAsString+"</body></html>");
e.printStackTrace();
return;
}
if (connection != null) {
out.println("<html><head><title>Hello World</title></head><body>");
out.println ("<h1>You made it, take control your database now!</h1></body></html>");
} else {
out.println("<html><head><title>Hello World</title></head><body>");
out.println ("<h1>Failed to make connection!</h1></body></html>");
}

Categories

Resources