java server throws java.lang.IllegalStateException: Cannot call sendError() after the response has been committed - illegalstateexception

please help me
java server throws : java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
I rechecked many times and googled alot but i cant find what's the problem
here's my code
DataOutputStream stream = null;
BufferedInputStream buf = null;
try {
response = ServletActionContext.getResponse();
response.setHeader(Constants.AU_TRST_X_RESULT_CD, "0"); // x-resultCd = 0 is OK
// add RSP_KEY_CODE to header
response.setHeader(Constants.RSP_KEY_CODE, Constants.RSP_SUCCCESS + "");
response.setContentType("application/csv");
//------------ write csv file to body ----------
// get response's outputStream
stream = new DataOutputStream(response.getOutputStream());
// fix file csv
File csvFixFile = new File("E:\\a.xls");
// buffer to read csv File
File csvResponse = new File(csvFixFile.getPath());
// file Input to read csv File
FileInputStream inputStream = new FileInputStream(csvResponse);
buf = new BufferedInputStream(inputStream);
int readBytes = 0;
while ((readBytes = buf.read()) != -1) {
stream.write(readBytes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != buf)
try {buf.close();} catch (Exception e2) {e2.printStackTrace();}
if (null != stream)
try {stream.close();} catch (Exception e2) {e2.printStackTrace();}
}
.It looks okay but it didnt work properly and perhaps the problem is in the while loop
please point it out for me.....

You can use IOUtils from apache commons-io to copy input stream into output stream (it also uses buffer, so you don't need to):
ServletOutputStream outStream = response.getOutputStream();
IOUtils.copy(inputStream, outStream);
IOUtils javadoc

Related

spring mvc export excel failed sometimes and data displays garblend on the page

There is a data report as the following in my project, I want to export it as excel:
But the wierd thing is that sometimes it exports successfully and sometimes failed. I have tried many times and it turns out that when the excel sheet is over 17 lines, it will lead to this:
the page redirects to a new page with garblend data.
the post request has been changed to get request.
It's sure that the excel is successfully created even if it exports failed, because I have written it to disk and checked the file. The following is the controller, what goes wrong with me?
#RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response, ReportCondition condition){
try {
List<HashMap<String, String>> mapList = reportFormService.find(condition);
if(mapList == null || mapList.size() == 0){
logger.info("No reports...");
}
Map<String, Date> dateMap = DateConditionUtil.getStartEndDate1(condition.getStartDate(), condition.getEndDate());
String startDate = DateFormatUtils.format(dateMap.get("startDate"), "yyyyMMdd");
String endDate = DateFormatUtils.format(dateMap.get("endDate"), "yyyyMMdd");
String[] titleArr = new String[]{"序号","日期","应用系统","短信服务商","请求发送总数","请求成功数量","实际短信条数","实际成功条数","费用","失败数量","成功率"};
String[] fieldArr = new String[]{"ID","RECORDDATE","APPNAME","PROVIDERNAME","SENDCOUNT","SUCCESSCOUNT","SENDSUM","SUCCESSSUM","TOTALFEE","FAILURECOUNT","SUCCESSRATE"};
ByteArrayOutputStream os = new ByteArrayOutputStream();
WorkBookUtil.createExcel(titleArr, fieldArr, mapList, os);
try(BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(os.toByteArray()));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())){
byte[] buff = new byte[1024];
int bytes;
while (-1 != (bytes = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytes);
}
bos.flush();
}catch (Exception e){
logger.error(e);
}
response.setCharacterEncoding("utf-8");
response.setHeader("content-disposition", "attachment;filename=" + String.format("%s-%s.xls", startDate, endDate));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
} catch (IOException e){
logger.error("Export failed", e);
}
}
You should set the response headers first before you create the .xls file. So try this:
response.setCharacterEncoding("utf-8");
response.setHeader("content-disposition", "attachment;filename=" + String.format("%s-%s.xls", startDate, endDate));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
ByteArrayOutputStream os = new ByteArrayOutputStream();
WorkBookUtil.createExcel(titleArr, fieldArr, mapList, os);
// ...
Try adding your response headers before writing the bytes out to the user. It would help to add a content-length header as well. You can get that after your call to createExcel with os.toByteArray().length. In addition close() your bos after you flush() it.

FileInputStream issue - App has stopped working

I am having trouble with FileInputStream in Android Studio. My application has stopped working when I use it to read file .txt in the internal memory (I have writen data to this file successfully). I have try many solutions but they didn't work. Can anyone give the solution for this problem? Here is my code. Thanks very much. (I have added users-permission "WRITE_EXTERNAL_STORAGE" and "READ_EXTERNAL_STORAGE").
String fileName = "infoProfile.txt";
private int readData() {
try {
String path = MainActivity.this.getFilesDir().getAbsolutePath() + "/" + fileName;
FileInputStream in = openFileInput(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
ArrayList<String> str = new ArrayList<>();
String data = "";
while ((data = reader.readLine()) != null) {
str.add(data);
}
in.close();
if (str.isEmpty())
return 0;
etName.setText(str.get(0));
etEmail.setText(str.get(1));
etPhone.setText(str.get(2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}

Nifi: how to remove session based on atribute value in nifi

I want to remove session in case i get certain data from file i have code like this,but i got errors "flowfile has already marked for removal", what should i change to get rid of extra errors?
In case of session rollback flowfile will dissapear in queues also?
2.should i use rollback instead of remove()?
NodeList childNodes = nodeGettingChanged.getChildNodes();
for (int i = 0; i != childNodes.getLength(); ++i) {
Node child = childNodes.item(i);
if (!(child instanceof Element))
continue;
if (child.getNodeName().equals("runAs")) {
if(child.getFirstChild().getTextContent()=="false"){
session.remove(flowFile1);
File deleteExtraFile =new File("C://Users//s.tkhilaishvili//Desktop//try2//nifi-1.3.0//1//conf.xml");
boolean delete=deleteExtraFile.delete();
}
else {
child.getFirstChild().setNodeValue("false");
}
}
}
Document finalXmlDocument = xmlDocument;
session.write(flowFile1, new StreamCallback() {
public void process(InputStream inputStream, OutputStream outputStream) throws IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource source = new DOMSource(finalXmlDocument);
ffStream.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bos);
try {
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
byte[] array = bos.toByteArray();
outputStream.write(array);
}
});
session.remove(flowFile);
session.transfer(flowFile1, REL_SUCCESS);
}
If you are executing session.remove(flowFile1) then later trying to transfer it to REL_SUCCESS, you will get that error. It looks like you already have an if-clause checking the firstChild for "false", perhaps you could put the transfer in an else-clause, such that it will only be transferred if it wasn't removed.

Best way to cancel creating a outputsteam that was to create a new pdf file?

I have SSJS in a button that opens a pdf file, writes to some fields on it (Acroform) and then downloads the file to the user. All works great (using pdfbox) but I wanted to be a good programmer and if the original pdf file was not available then cancel the operation. Otherwise, the user still gets prompted to open the file but Adobe Reader reports the file is corrupted (obviously it will be). I do my pdf operations in a Java class that I call and pass in the outputStream of the response object. Below is my SSJS. If I test the ret value from newVal.outputPdf and put all the other code in the if statement then my XPage is just blank. I assume because the response and outputStream was already opened?
Howard
importPackage(com.tlcc);
var newVal = new PdfBoxTest();
importPackage(java.net);
importPackage(java.lang);
var con = facesContext.getExternalContext();
var response:com.ibm.xsp.webapp.XspHttpServletResponse = con.getResponse();
try {
var writer:javax.servlet.ServletOutputStream = response.getOutputStream();
//get the stream
var ret = newVal.outputPdf(writer, "http://localhost/pdfexportcc.nsf/certificate.pdf");
// setting response headers for browser
print("Good output");
response.setContentType("application/pdf");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", -1);
response.setHeader( "Content-Disposition", "attachment; filename=\"mypdf.pdf\"" );
writer.flush();
writer.close();
print("in close");
facesContext.responseComplete();
} catch (e) {
var errorMessage = "An error has occured: " + e.toString();
_dump(errorMessage);
writer.close();
response.sendError(500, errorMessage);
}
Tried again with all the work being done in Java. I called this method from a button. Works fine with a valid url but when the url is bad it throws an error. Exception Can't get a Writer while an OutputStream is already in use.
public boolean outputAllInJavaPdf() {
try {
FacesContext context = FacesContext.getCurrentInstance();
XspHttpServletResponse response = (XspHttpServletResponse) context.getExternalContext().getResponse();
ServletOutputStream writer = response.getOutputStream();
InputStream docUrl = new URL("http://localhost/pdfexportcc.nsf/certifxxicate.pdf").openStream();
pdfDoc = PDDocument.load(docUrl);
System.out.println("Number of pages is " + pdfDoc.getNumberOfPages());
setField("Student", "James Namce");
setField("CourseName", "XPages Development 2 for Notes and Domino 9");
setField("Instructor", "John Smith");
System.out.println("After set field");
pdfDoc.save(writer);
pdfDoc.close();
response.setContentType("application/pdf");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", -1);
response.setHeader("Content-Disposition", "attachment; filename=\"mypdf.pdf\"");
writer.flush();
writer.close();
context.responseComplete();
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
}
All depends on what you tell the browser.
You use content type of PDF file. Browser opens (downloads) PDF file. Anything you put inside, for example error page, is treated as content of PDF file.
So in case PDF generation fails, do not set that content type and redirect browser to error page, or back to original XPage with explanation.
public boolean outputAllInJavaPdf() {
try {
FacesContext context = FacesContext.getCurrentInstance();
XspHttpServletResponse response = (XspHttpServletResponse) context.getExternalContext().getResponse();
ServletOutputStream writer = response.getOutputStream();
boolean servePdf = true;
try {
InputStream docUrl = new URL("http://localhost/pdfexportcc.nsf/certifxxicate.pdf").openStream();
pdfDoc = PDDocument.load(docUrl);
// do something to validate PDF
} catch (Exception e) {
//no PDF
servePdf = false;
}
if (servePdf) {
System.out.println("Number of pages is " + pdfDoc.getNumberOfPages());
setField("Student", "James Namce");
setField("CourseName", "XPages Development 2 for Notes and Domino 9");
setField("Instructor", "John Smith");
System.out.println("After set field");
pdfDoc.save(writer);
pdfDoc.close();
response.setContentType("application/pdf");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", -1);
response.setHeader("Content-Disposition", "attachment; filename=\"mypdf.pdf\"");
} else {
// take care of no PDF response - redirect?
}
writer.flush();
writer.close();
context.responseComplete();
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
}
It is probably trying to render your Xpage, but you want to control the response yourself. To prevent rendering of the Xpage and take control of the writer, add rendered="false"to your Xpage.

Download Images in loop java me

In my application we have to download around 10 Images from server and display it in mobile. How can I do this? Can I use same HttpConnection for full download? Is any other way for download?
You can do with this simple loop (Supposing imageList is a List with the url of the images).
HttpConnection = null;
Image image = null;
for (int i = 0; i < imageList.getSize(); i++) {
try{
String urlImage = imageList.get(i);
hc = (HttpConnection) Connector.open(urlImage);
image = Image.createImage(hc.openInputStream()));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
hc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can try following method in a loop for downloading images from server.
private void downloadImage ( String URL )
{
try
{
System.out.println("URL FOR POST_DATA : "+URL);
// Open up a http connection with the Web server for both send and receive operations
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
if(eventName==null || eventName.equals(""))
eventName="default";
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
// all the headers are sending now and connection chanel is establising
dis = httpConnection.openDataInputStream();
int ch = 0;
ByteArrayOutputStream bytearray = new ByteArrayOutputStream(250000);
while((ch = dis.read()) != -1)
bytearray.write(ch);
// fileByte contains whole file in bytes
byte fileByte[] = bytearray.toByteArray();
fileSize = fileByte.length;
System.out.println("Got file size : "+fileSize);
if(bytearray!=null) bytearray.close();
midlet.getLastPostedImageResponse(fileByte);
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("IOException occured during getting last image data : "+ioe.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Eeception occurred during getting last image data : "+e.getMessage());
}
finally
{
System.out.println("Calling close from Last image posted Action");
close();
}

Resources