loading image to jsp (struts2) from database - database

I have problem with loading image from database to jsp view. It looks like action are execute but stop in middle.
I log when execute() method start and when its end. In log file i can see start this method but there are no end.
I have action:
public class ShowImageAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(ShowImageAction.class);
private int id;
public String execute() {
LOG.info("Enter execute()");
MessageBean messageBean = (MessageBean) sessionParameters
.get(SessionParameters.BANNER_EDIT);
IFiles filesEJB = EJBLocator.getFiles();
if (messageBean != null) {
id = messageBean.getBannerId();
}
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
bytes = FileUtils.readFileToByteArray(file.getImage());
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
LOG.info("Exit execute()");
return NONE;
}
jsp:
<div class="OneFilteringRow">
Podgląd<br />
<img src="/ebok-bm/ShowImageAction" alt="Podgląd banera" />
</div>
struts.xml
<action name="ShowImageAction"
class="pl.bm.action.content.ShowImageAction">
</action>

Problem was in:
FileBean file = filesEJB.file(id);
I get bytes from database and try to save it to tmpFile. Now I get bytes and writes them to a temporary file and immediately transmit it to the action and everything is ok.
Now I have:
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
**bytes = file.getImage();**
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
}

Switch to your own result implements Result class and write output here.Other in struts.xmlaction result type specified own with approx mate parameters.
refer:generate own image as action result

Related

Encode InputStream response as UTF-8

I'm trying to make a connection to a URL which displays some data in plain text on a webpage (it's a block of text in between <pre> tags). Whenever a character with a character with a special character is passed through (for example é or ì) it displays a question mark instead of the character a �
is displayed. I've tried using this but that didn't change much. I can't read the page per line so I'm pretty much stuck here.
Here is my code:
try
{
// Open the connection
NetworkManager networkManager = NetworkManager.getInstance();
networkManager.addErrorListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
NetworkEvent n = (NetworkEvent) evt;
n.getError().printStackTrace();
success = false;
}
});
ConnectionRequest request = new ConnectionRequest()
{
{
setTimeout(40000);
}
#Override
protected void readResponse(InputStream input) throws IOException
{
InputStreamReader inputStreamReader = new InputStreamReader(input, "UTF-8");
int chr;
buffer = new StringBuilder();
//reading the answer
while ((chr = inputStreamReader.read()) != -1)
{
System.out.println("Append the character " + (char) chr);
buffer.append((char) chr);
}
response = buffer.toString();
response = response.trim();
data = new byte[buffer.length()];
int tmpCounter = buffer.length();
counter = 0;
while (counter != buffer.length())
{
for (int i = 0; i < tmpCounter; i++)
{
data[counter + i] = (byte) buffer.charAt(i);
}
counter += tmpCounter;
}
process(data);
dataEvent.setDataAvailable();
}
#Override
protected void handleException(Exception err)
{
success = false;
dataEvent.setDataAvailable();
}
};
request.setUrl(url);
request.setPost(false);
networkManager.addToQueue(request);
}
catch (Exception x)
{
x.printStackTrace();
}
Turns out the actual response didn't respond using UTF-8 the characters were just readable in my browser. I fixed it by specifying the response characters should be UTF-8

Extracting text inside body of mail using javamail API stopping after first iteration

I've searched for hours and tried everything to fix this code. I've been working with the example below and after updating appropriate variables this works fine through till the end of processing the first email. It seems to pause indefinitely. I had to alter code at (//check if the content is an inline image) as variables appear to need declaration before they were used but have not changed anything apart from that. Any help before I loose my mind will be much appreciated.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Original code at https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
My code below... (output below that)
package com.mail.coder;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
public class FetchingEmail2 {
public static void fetch(String pop3Host, String storeType, String user,
String password) {
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3.host", pop3Host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
// emailSession.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect("mail.DOMAIN.com", "USERNAME#DOMAIN.com", "PASS");
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
writePart(message);
String line = reader.readLine();
if ("YES".equals(line)) {
message.writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username =
"abc#gmail.com";// change accordingly
String password = "*****";// change accordingly
//Call method fetch
fetch(host, mailStoreType, username, password);
}
/*
* This method checks for content-type
* based on which, it processes and
* fetches the content of the message
*/
public static void writePart(Part p) throws Exception {
if (p instanceof Message)
//Call method writeEnvelope
writeEnvelope((Message) p);
System.out.println("----------------------------");
System.out.println("CONTENT-TYPE: " + p.getContentType());
//check if the content is plain text
if (p.isMimeType("text/plain")) {
System.out.println("This is plain text");
System.out.println("---------------------------");
System.out.println((String) p.getContent());
}
//check if the content has attachment
else if (p.isMimeType("multipart/*")) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
writePart(mp.getBodyPart(i));
}
//check if the content is a nested message
else if (p.isMimeType("message/rfc822")) {
System.out.println("This is a Nested Message");
System.out.println("---------------------------");
writePart((Part) p.getContent());
}
//check if the content is an inline image
else if (p.isMimeType("image/jpeg")) {
System.out.println("--------> image/jpeg");
Object o = p.getContent();
InputStream x = (InputStream) o;
// Construct the required byte array
System.out.println("x.length = " + x.available());
**int i;
byte[] bArray = new byte[x.available()];**
while ((i = (int) ((InputStream) x).available()) > 0) {
int result = (int) (((InputStream) x).read(bArray));
if (result == -1)
i = 0;
break;
}
FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
f2.write(bArray);
}
else if (p.getContentType().contains("image/")) {
System.out.println("content type" + p.getContentType());
File f = new File("image" + new Date().getTime() + ".jpg");
DataOutputStream output = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
com.sun.mail.util.BASE64DecoderStream test =
(com.sun.mail.util.BASE64DecoderStream) p
.getContent();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = test.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
else {
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a string");
System.out.println("---------------------------");
System.out.println((String) o);
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
System.out.println("---------------------------");
InputStream is = (InputStream) o;
is = (InputStream) o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
}
else {
System.out.println("This is an unknown type");
System.out.println("---------------------------");
System.out.println(o.toString());
}
}
}
/*
* This method would print FROM,TO and SUBJECT of the message
*/
public static void writeEnvelope(Message m) throws Exception {
System.out.println("This is the message envelope");
System.out.println("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("FROM: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("TO: " + a[j].toString());
}
// SUBJECT
if (m.getSubject() != null)
System.out.println("SUBJECT: " + m.getSubject());
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output
messages.length---5
---------------------------------
This is the message envelope
---------------------------
FROM: Jack Frost <sender#gmail.com>
TO: recipient#domain.com
SUBJECT: another email
----------------------------
CONTENT-TYPE: multipart/alternative; boundary="000000000000096c73056991868c"
This is a Multipart
---------------------------
----------------------------
CONTENT-TYPE: text/plain; charset="UTF-8"
This is plain text
---------------------------
testing
----------------------------
CONTENT-TYPE: text/html; charset="UTF-8"
This is a string
---------------------------
<div dir="ltr">testing</div>

Multipart image upload issue in Codename One

I am using this code to upload an image. It works on emulator but always fail on Android device (OS 6.0)
My code is
`private void uploadImage3(final String imagePath, String id){
final Hashtable htArg = new Hashtable();
htArg.put("pk1value", id);
htArg.put("pk2value", "");
htArg.put("pk3value", "");
htArg.put("datatype", "6");
htArg.put("module", "");
htArg.put("action", "");
try {
htArg.put("thefile", FileSystemStorage.getInstance().openInputStream(imagePath));
} catch (IOException ex) {
Log.p("imgRequest.Error = " + ex.toString());
}
htArg.put("submit", "Submit");
final String boundary = "-----------------------------0123456789012";
MultipartRequest request = new MultipartRequest(){
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
Writer writer = null;
writer = new OutputStreamWriter(os, "UTF-8");
String CRLF = "\r\n";
boolean canFlushStream = true;
Enumeration e = htArg.keys();
while(e.hasMoreElements()) {
if (shouldStop()) {
break;
}
String key = (String)e.nextElement();
Object value = htArg.get(key);
writer.write("--");
writer.write(boundary);
writer.write(CRLF);
if(value instanceof String) {
writer.write("Content-Disposition: form-data; name=\""+key+"\"");
writer.write(CRLF);
writer.write(CRLF);
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
writer.write(Util.encodeBody((String)value));
if(canFlushStream){
writer.flush();
}
}else {
writer.write("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + key +"\"");
writer.write(CRLF);
writer.write("Content-Type: ");
writer.write("image/jpeg");
writer.write(CRLF);
writer.write("Content-Transfer-Encoding: binary");
writer.write(CRLF);
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
InputStream i;
if (value instanceof InputStream) {
i = (InputStream)value;
byte[] buffer = new byte[8192];
int s = i.read(buffer);
while(s > -1) {
os.write(buffer, 0, s);
if(canFlushStream){
writer.flush();
}
s = i.read(buffer);
}
// (when passed by stream, leave for caller to clean up).
if (!(value instanceof InputStream)) {
Util.cleanup(i);
}
} else {
os.write((byte[])value);
}
value = null;
if(canFlushStream){
writer.flush();
}
}
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
}
writer.write("--" + boundary + "--");
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
writer.close();
}
#Override
protected void readResponse(InputStream input) {
try {
Result result = Result.fromContent(input, Result.XML);
Log.p("imgRequest response: " + result.toString());
} catch (Exception ex) {
Log.p("imgRequest.Error = " + ex.toString());
ex.printStackTrace();
}
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Log.p("handleErrorResponseCode = "+code + ":" + message);
}
#Override
protected void handleException(Exception err) {
Log.p("handleException = "+err.toString());
err.printStackTrace();
}
};
String theURL = Application.getCurrentConnection().get("URL").toString() + "/W1Servlet";
request.setUrl(theURL+"/uploadfiledebug");
request.setBoundary(boundary);
request.setPost(true);
try {
//need to keep this code as it will calculate file size internally
// and also have to add thefile separately in myArgHashTable
request.addData("thefile", imagePath, "image/jpeg");
request.setFilename("thefile", "img.jpeg");
} catch (Exception ex) {
}
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
request.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(request);
}`
The traced error on real device is,
`java.net.ProtocolException: exceeded content-length limit of 11076 bytes
at com.android.okhttp.internal.http.RetryableSink.write(RetryableSink.java:58)
at com.android.okhttp.okio.RealBufferedSink.close(RealBufferedSink.java:234)
at com.android.okhttp.okio.RealBufferedSink$1.close(RealBufferedSink.java:209)
at com.codename1.impl.CodenameOneImplementation.cleanup(CodenameOneImplementation.java:4385)
at com.codename1.impl.android.AndroidImplementation.cleanup(AndroidImplementation.java:4579)
at com.codename1.io.Util.cleanup(Util.java:149)
at com.codename1.io.BufferedOutputStream.close(BufferedOutputStream.java:287)
at com.codename1.impl.CodenameOneImplementation.cleanup(CodenameOneImplementation.java:4385)
at com.codename1.impl.android.AndroidImplementation.cleanup(AndroidImplementation.java:4579)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:804)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread$1.run(CodenameOneThread.java:60)
at java.lang.Thread.run(Thread.java:818)`
I am not sure what I am missing.
Please someone can help me.
Thanks
Updated Code
`private void uploadImage4(final String imagePath, String id){
MultipartRequest request = new MultipartRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
try {
Result result = Result.fromContent(input, Result.XML);
if(isDebugOn){
Application.writeInDebugFile(debugFileName,
"result.toString(): "+ result.toString());
}
Log.p("imgRequest response: " + result.toString());
} catch (Exception ex) {
Log.p("imgRequest.Error = " + ex.toString());
ex.printStackTrace();
if(isDebugOn){
Application.writeInDebugFile(debugFileName,
"readResponse.Exception: "+ex.toString());
}
}
}
};
String theURL = Application.getCurrentConnection().get("URL").toString() + "/W1Servlet";
request.setUrl(theURL+"/uploadfiledebug");
request.addArgument("entityname", "RCV_HEADERS");
request.addArgument("category", "37");
request.addArgument("description", "Uploaded by More4Apps Mobile App");
request.addArgument("pk1value", id);//this is used as a primary key
request.addArgument("pk2value", "");
request.addArgument("pk3value", "");
request.addArgument("datatype", "6");
request.addArgument("module", "");
request.addArgument("action", "");
request.addArgument("submit", "Submit");
try {
//add the data image
request.addData("thefile", imagePath, "image/jpeg");
request.setFilename("thefile", "img.jpeg");
} catch (IOException ex) {
Log.p("Error:"+ ex.toString());
}
request.setPriority(ConnectionRequest.PRIORITY_CRITICAL);
NetworkManager.getInstance().addToQueue(request);
}`
And new error is:
`<ERROR_MESSAGE>IO Error:com.more4apps.mobile.ActionUploadFileoracle.ord.im.OrdHttpUploadException: IMW-00106: the end-of-headers delimiter (CR-LF) was not present
IMW-00112: additional error information: Content-Type: text/plain; charset=UTF-8IMW-00106: the end-of-headers delimiter (CR-LF) was not present
IMW-00112: additional error information: Content-Type: text/plain; charset=UTF-8
oracle.ord.im.OrdMultipartParser.doParse(OrdMultipartParser.java:312)
oracle.ord.im.OrdMultipartParser.parseFormData(OrdMultipartParser.java:150)
oracle.ord.im.OrdHttpUploadFormData.parseFormData(OrdHttpUploadFormData.java:532)
com.more4apps.mobile.ActionUploadFile.performAction(ActionUploadFile.java:39)
com.more4apps.mobile.W1Servlet.processAction(W1Servlet.java:449)
com.more4apps.mobile.W1Servlet.doPost(W1Servlet.java:248)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:64)
oracle.apps.jtf.base.session.ReleaseResFilter.doFilter(ReleaseResFilter.java:26)
com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:15)
oracle.apps.fnd.security.AppsServletFilter.doFilter(AppsServletFilter.java:318)
com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:642)
com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:391)
com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:908)
com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:458)
com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:313)
com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:199)
oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
java.lang.Thread.run(Thread.java:682)</ERROR_MESSAGE>`
If you override buildRequestBody in a multipart request you effectively disable its functionality...
All of that code is incorrect and shouldn't be there. Multipart will work for large files by default.

Get IMSI from the SIM using codename1

I need to get the IMSI (International
Mobile Subsriber Identity) stored in the SIM card using codename1. Also in the case of dual or tri SIM phones, i need to get the IMSI for each SIM. Please, How do i get it?
Display.getMsisdn() will work for some devices but most don't allow accessing that information. For more information you can just use a native interface if you can access it that way.
Another way to get IMSI for dual Sim device:
Try this .. its working for me. Idea is to call service for iphonesubinfo function#3. you will get output as parcel value thats why I use getNumberFromParcel to extract number.
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by Apipas on 6/4/15.
*/
public class SimUtil {
public static String getIMSI_1() {
String imsiParcel = runCommand("service call iphonesubinfo 3");
String imsi = getNumberFromParcel(imsiParcel);
Log.d("apipas", "IMSI_1:" + imsi);
return imsi;
}
public static String getIMSI_2() {
String imsiParcel = runCommand("service call iphonesubinfo2 3");
String imsi = getNumberFromParcel(imsiParcel);
Log.d("apipas", "IMSI_2:" + imsi);
return imsi;
}
public static String runCommand(String src) {
try {
Process process = Runtime.getRuntime().exec(src);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[2048];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
Log.e("apipas", "IOException:" + e.getMessage());
return null;
} catch (InterruptedException e) {
Log.e("apipas", "InterruptedException:" + e.getMessage());
return null;
}
}
public static String getNumberFromParcel(String str) {
String res = "";
if (str != null && str.length() > 0) {
String lines[] = str.split("\n");
for (String line : lines) {
if (line == null || line.length() == 0)
continue;
String content[] = line.split("'");
if (content.length > 1) {
res += content[1].replace(".", "");
}
}
} else return "NA";
return res;
}
}
Then call these static methods like:
String imsi1 = SimUtil.getIMSI_1();
String imsi2 = SimUtil.getIMSI_2();
You'd need to set this permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

getting an empty file when downloading : jsf

I want to download a file stored in system directory but when downloading the file in jsf page I get it empty.
This is my xhtml page :
<h:form>
<h:commandButton value="Download" action="#{helloBean.downloadFile}" />
</h:form>
and my managed bean :
#ManagedBean
#SessionScoped
public class HelloBean {
public void downloadFile() {
File file = new File("C:\\data\\contacts.doc");
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=contacts.doc");
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
so How to solve it? Thanks in advance.
I think this code solve your problem.
public void download() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context
.getExternalContext().getResponse();
File file = new File(filePath);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment;filename=\""
+ file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
input.close();
output.close();
}
context.responseComplete();
}

Resources