Reading Pdf from URL and Parsing with Android PDF Viewer - httpurlconnection

I have successfully displayed Pdf from Assets folder using Android Pdf Viewer library https://github.com/jblough/Android-Pdf-Viewer-Library. I am now trying to parse and display online pdf "http://www.gnostice.com/downloads/Gnostice_PathQuest.pdf" but it is giving the following error:
<code>
04-19 03:17:04.995: W/System.err(27806): java.io.IOException: This may not be a PDF File
04-19 03:17:04.995: W/System.err(27806): at com.sun.pdfview.PDFFile.parseFile(PDFFile.java:1395)
04-19 03:17:04.995: W/System.err(27806): at com.sun.pdfview.PDFFile.<init>(PDFFile.java:140)
04-19 03:17:04.995: W/System.err(27806): at com.sun.pdfview.PDFFile.<init>(PDFFile.java:116)
04-19 03:17:04.995: W/System.err(27806): at net.sf.andpdf.pdfviewer.PdfViewerActivity.openFile(PdfViewerActivity.java:909)
04-19 03:17:04.995: W/System.err(27806): at net.sf.andpdf.pdfviewer.PdfViewerActivity$8.run(PdfViewerActivity.java:863)
04-19 03:17:04.995: W/System.err(27806): at java.lang.Thread.run(Thread.java:1027)
</code>
I am opening URL Connection connection as :
<code>
fileUrl = new URL(filename);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
byte[] bytes = new byte[is.available()];
is.read(bytes);
System.out.println("Byte Lenght: " + bytes.length);
ByteBuffer bb = ByteBuffer.NEW(bytes);
is.close();
openFile(bb, password);
</code>
Please help what can be the issue?
Thanks

The way you read the stream is not correct. You can use these utility classes (taken from DavidWebb):
/**
* Read an <code>InputStream</code> into <code>byte[]</code> until EOF.
* <br/>
* Does not close the InputStream!
*
* #param is the stream to read the bytes from
* #return all read bytes as an array
* #throws IOException
*/
public static byte[] readBytes(InputStream is) throws IOException {
if (is == null) {
return null;
}
byte[] responseBody;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copyStream(is, baos);
baos.close();
responseBody = baos.toByteArray();
return responseBody;
}
/**
* Copy complete content of <code>InputStream</code> to <code>OutputStream</code> until EOF.
* <br/>
* Does not close the InputStream nor OutputStream!
*
* #param input the stream to read the bytes from
* #param output the stream to write the bytes to
* #throws IOException
*/
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int count;
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
}
}

Related

SocketException when reading file with BufferedInputStream

I'm writing a TCP Server and Client, in which the client will send the file and the server will save it. My send/save function is as following:
Server
public void saveFile2(Socket clientSocket) throws IOException
{
BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
String fileName = dis.readUTF();
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int byteCount;
byte[] buffer = new byte[4096];
while ((byteCount = bis.read(buffer, 0, buffer.length)) > 0)
{
System.out.println("Test byteCount = "+byteCount);
bos.write(buffer, 0, byteCount);
break;
}
System.out.println("Saved file"+file.getName());
bos.close();
dis.close();
}
Client
public void sendFile2(String xmlpath) throws IOException, InterruptedException
{
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
File file = new File(xmlpath);
System.out.println("Sending File : " + file.getName());
dos.writeUTF(file.getName());
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int bytesCount;
byte[] buffer = new byte[4096];
System.out.println("Sending file to server.");
while ((bytesCount = fis.read(buffer)) > 0 )
{
System.out.println(bytesCount);
bos.write(buffer, 0, bytesCount);
}
System.out.println("Finished sending.");
bis.close();
dos.flush();
}
Notice that I have added a break; command into the while loop of Server and the program work perfectly. But when I exclude it, I get this exception:
Test byteCount = 394
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at xml.xmlServer.saveFile2(xmlServer.java:72)
at xml.xmlServer.run(xmlServer.java:31)
This only occur when I include BufferedInputStream and BufferedOutputStream in my code. Can somebody help me explain what causes this exception ?
You're reading the filename but you aren't sending the filename. You're missing a writeUTF() call in the sender.
You also need to close the socket in the sender, or the DataOutputStream.
bos.write(buffer, 0, bytesCount);
Really this should be
dos.write(buffer, 0, bytesCount);

File upload to Weblogic server failed

I am trying to upload a file to WebLogic server using servlets. This is the doPost method:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
{
boolean isMultipart;
String filePath=null;
int maxFileSize = 2 * 1024 * 1024;
int maxMemSize = 1024 * 1024;
File file ;
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart )
{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(2 * 1024 * 1024);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
ServletContext context = getServletContext();
Connection conn = (Connection)context.getAttribute("DBCON");
PreparedStatement stmt=null;
try
{
stmt=conn.prepareStatement("INSERT INTO emp VALUES(?, ?, ?)");
out.println("Created the statement!");
}
catch (SQLException e)
{
out.println("Unable to create prepared statement because: "+e.getMessage());
}
WriteToDB ob=new WriteToDB();
out.println("CWriting to DB!");
ob.process("C:\\JDeveloper\\mywork\\App\\Project1\\data" + "\\" + fileName, stmt, out);
out.println("Wrote to DB!");
}
}
} catch (FileUploadException e) {
}
out.println("</body>");
out.println("</html>");
}
And this is, as I've read, the important part of web.xml:
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
C:\JDeveloper\mywork\App\Project1\data
</param-value>
I am using JDeveloper.
I have a standard upload HTML page with form data.
Everything is fine, except that the file is not to be found at the stored location, and it throws that exception.
Please help, thank you.

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}

Servlet call hanging when using S3 Java SDK

I have this servlet I call using GWT FileUpload (I don't thing it matters so much that it is GWT):
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
try {
User user = ServerUtil.validateUser(request);
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String saveFile = item.getName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10 * (1024 * 1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
// save file data
String fileName = user.getUsername() + "_" + new Date().getTime() + "_" + saveFile;
// store to S3
String imageUrl = S3PhotoUtil.storeThumbnailImage(out.toByteArray(), fileName, 100);
// return the url of the file
writer.println(imageUrl);
response.flushBuffer();
return;
}
} catch (RuntimeException e) {
writer.println(("error=" + e.getMessage()).getBytes());
} catch (FileUploadException e) {
writer.println(("error=Could not read file").getBytes());
} catch(IOException e) {
writer.println(("error=Image type not supported!").getBytes());
}
} catch (EIException e) {
e.printStackTrace();
writer.println(("error=Not logged in").getBytes());
}
}
When called the POST hangs, I check on firebug, it looks like it never gets a response. If I debug I see that all instructions are executed without any problem and the method is ran fine. The files are stored on my S3 bucket.
Now if I remove the call relating to the S3 storage it stops hanging, although obviously it doesn't do anything anymore... My conclusion is that there is something in this S3 storage that messes up with my servlet. The code itself is taken from the travel log example application # http://aws.amazon.com/code/1264287584622066
It does say needs tomcat and I'm using jetty... could that be a problem?
Thanks,
Thomas

save an uploaded file with GWT

I am using org.apache.commons.fileupload to upload.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
GWT.log("is multipart? " + Boolean.toString(isMultipart), null);
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream() ;
/**
* Save th uploaded file
*/
}
}
catch(Exception e){
e.printStackTrace();
}
}
How can I save the uploaded file?
This looks like server-side code, which (aside from GWT-RPC servlets) is not specific to GWT at all. That GWT.log() is unnecessary -- replace it with a regular logging call, and handle the upload as you normally would in non-GWT code, since that's what it is.
Here is a helpful example of using apache's fileupload to get you started.
I think this can help you.
if (!item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
File saveTo = new File("/file_uploads/" + fileName);
try {
item.write(saveTo);
...
}
catch (Exception e){
...
}
Keep in mind that uploaded file may already be automatically saved by org.apache.commons.fileupload
You can set size threshold for file to be saved on disk or loaded in memory using
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Everything you need to know about org.apache.commons.fileupload is here: Using FileUpload