Dear staff,
I want to share this little piece of code.
Basically in this example, i just want to send
out a file.
To do this, i have follow 2 approach, the 1st (fileoutputbuffer) was
copied on grizzlyblog
the 2nd is a cut/paste of a staticresourceadapter more or less.
The 2nd work (the one that use bytechunk)
the 1st not (fileoutputbuffer)
Basically, i am just curious (i can use the 2nd without problem) but
i was wondering
a) what's the difference between the 2 options?
b) why the 1st one doesn't work? it's normal? (code copied from here
http://weblogs.java.net/blog/jfarcand/ Extending the Grizzly HTTP
Runtime part V: Programatically configuring Servlet and GrizzlyAdapter)
That's all :)
Have a nice weekend!
--------------
public static void main(String args[]) {
GrizzlyWebServer ws = new GrizzlyWebServer(8080);
GrizzlyAdapter adapter = new GrizzlyAdapter() {
@Override
public void service(GrizzlyRequest req, GrizzlyResponse
res) {
String uri = req.getRequestURI();
System.out.println(uri);
File file = new File("/Users/ramarama/html/test",uri);
long length = file.length();
if (file.exists()){
FileInputStream fis = null;
try{
fis = new FileInputStream(file);
long nWrite = 0;
FileOutputBuffer fob = (FileOutputBuffer)
res.getOutputBuffer();
while (nWrite < length) {
nWrite += fob.sendFile(fis.getChannel(),
nWrite, length - nWrite);
}
/* TWO
byte b[] = new byte[8192];
ByteChunk chunk = new ByteChunk();
int rd=0;
while ((rd=fis.read(b)) > 0) {
chunk.setBytes(b, 0, rd);
res.getResponse().doWrite(chunk);
}*/
} catch (IOException ex){
res.setStatus(404);
res.setDetailMessage("Not Found");
} finally {
try{
fis.close();
} catch (IOException ex){};
}
} else {
res.setStatus(404);
res.setDetailMessage("Not Found");
}
}
};
ws.addGrizzlyAdapter(adapter, new String[]{"/"});
try {
ws.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}