How to open pdf file in browser - java

I'm trying to open a pdf file in which has been exported from a repository. Here is the code that I'm using:
ConnectionManager con = new ConnectionManager();
String id = request.getParameter("uname");
String objname = request.getParameter("pass");
Properties prop = new Properties();
//ResourceBundle resource = ResourceBundle.getBundle("query");
//prop.load(getClass().getResourceAsStream("query.properties"));
String uname = "DmAdmin";
String pass = "<pass>";
String docbase = "QDocs";
String ext = new String();
IDfSession ssn = con.getSession(uname, pass, docbase);
sysObj = (IDfSysObject)ssn.getObject((IDfId)new DfId(id));
//ByteArrayInputStream buf = sysObj.getContent();
//sysObj.getFile("C:\\Users\\rsaha04\\Downloads\\"+objname+".pdf");
String path = "C:\\Users\\rsaha04\\Downloads\\";
String filename = path + sysObj.getObjectName().toString();
IDfCollection coll = sysObj.getRenditions(null);
if (coll != null)
{
while (coll.next())
{
String format = coll.getString("full_format");
{
if (format.equalsIgnoreCase("pdf"))
{
ext = "pdf";
System.out.println("extension set: "+ext);
}
}
}
filename = filename+"."+ext;
sysObj.getFileEx(filename, ext, 0, false);
}
con.closeConnection(ssn);
//Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+filename);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename='"+filename+"'");
I'm able to open the pdf file in adobe acrobat reader but it is failing for browser with this error.
Please help me understand where I'm going wrong here.

You need your server to respond with a pdf file. You set the response headers, but your code never writes the pdf data into the response.
Do that using
response.write(bytesFromPdfFile)

Related

File downloads but while extracting it gives "invalid zip file"

I am working on a jsp zip file download ,I am able to download the file but while extracing I get Invalid zip file error. In the java controller I have added
#RequestMapping("/upload")
public void getDownload(ModelView mv,HttpServletResponse response)
{
String fileName = "";
String fullZipFileName = zipDir+ zipFileName;
FileManager fm = FileManager.getInstance();
zipOS = fm.getZipOutputStream(fullZipFileName);
try {​​​​​
for(int i = 0; i < numOfFiles; i++) {​​​​​
fileName = (String) selectedFiles.get(i);
File file = new File(directory, fileName);
bIS = fm.getBufferedInputStream(file.getAbsolutePath());
ZipEntry entry = new ZipEntry(file.getName());
zipOS.putNextEntry(entry);
while((count = bIS.read(fileToAddToZip, 0, buffer)) != -1) {​​​​​
zipOS.write(fileToAddToZip, 0, count);
}​​​​​
bIS.close();
}​​​​​
zipOS.close();
FileManager fm = FileManager.getInstance();
bIS = fm.getBufferedInputStream(zipFileName);
byte[] byteArray = new byte[bIS.available()];
bIS.read(byteArray);
bIS.close();
response.setContentType("application/octate-stream");
response.setHeader("Content-Disposition", "attachment;filename" + zippedFilename);
response.getOutputStream().write(byteArray);
}
In the jsp side I have added
$.ajax({​​​​​​​​​​​
type: 'POST',
url: "${​​​​​​​​​​​pageContext.request.contextPath}​​​​​​​​​​​/download",
contentType: "application/json",
data: JSON.stringify(payload),
success: function (res, textStatus, response) {​​​​​​​​​​​
var fileName = response.getResponseHeader("content-disposition").replace("attachment;filename=", "");
var fileName = response.getResponseHeader("Content-Disposition").replace("attachment;filename=", "");
var bytes = new Uint8Array(res.length);
for(var i=0;i< res.length;i++)
{
var as=res.charCodeAt(i);
bytes[i]=as;
}
var blob = new Blob([bytes], {​​​​​​​​​​​ type: "application/octetstream" }​​​​​​​​​​​);
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {​​​​​​​​​​​
window.navigator.msSaveBlob(blob, fileName);
}​​​​​​​​​​​ else {​​​​​​​​​​​
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", fileName);
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}​​​​​​​​​​​
}​​​​​​​​​​​,
error: function (e) {​​​​​​​​​​​
}​​​​​​​​​​​
}​​​​​​​​​​​);
I am able to download the file but when I try to extract the zip file ,I get Invalid zip file. Can someone tell me how can I fix this issue

file.getName() returns nothing

I need to get the name of a CSV file selected for the user, but the getName() method does not return any value.
This is the code
private void readCSV(Uri uri) {
InputStream is;
File file = null;
try {
if (uri.getScheme().equals("file")) {
file = new File(uri.toString());
Log.i("File selected: ", file.getName()); //file.getName() doesn't work
is = new FileInputStream(file);
Why does this not return the name of the file?
Edit 1
private void readCSV(Uri uri) {
InputStream is;
File file;
try {
/*This conditional is false*/
if (uri.getScheme().equals("file")) {
file = new File(uri.toString());
Log.i("File selected: ", file.getName()); //file.getName() doesn't
is = new FileInputStream(file);
} else {
/* this part is the one that runs */
is = this.getContentResolver().openInputStream(uri);
Log.i("File selected: ", uri.getLastPathSegment()); //i tried this, it returns me 5049 but it is not the name of the selected file
}
uri.toString() will return the object reference but not the file path.
You should call uri.getPath()
Use
new File(uri.getPath());
instead of
new File(uri.toString());
NOTE: uri.toString() returns a String in the format: "file:///mnt/sdcard/image.jpg", whereas uri.getPath() returns a String in the format: "/mnt/sdcard/image.jpg".
try this
fileName = uri.getLastPathSegment();
Getting file names through the apachecommons io lib https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html
String name = FileNameUtils.getName(uri.getPath());

How to get file extension from google drive direct download link?

I have given a URI which is from google drive direct download link of a image, and I want to find the file extension of the file that is returned, what do I have to do in Java.
For example Link will be like:https://drive.google.com/uc?export=download&id=0BwtDpsO0CtJZbm9iNUNMTXNTX0k
`
public static String saveImage(String imageUrl, String playlist) throws
IOException {
URL url = new URL(imageUrl);
String fileName = url.getFile();
System.out.println(fileName);
String destName
="./figures"+fileName.substring(fileName.lastIndexOf("/"));
String destName = "../imgUpload/"+playlist;System.out.println(destName);
InputStream is = url.openStream();System.out.println("is-
1"+is);OutputStream os = new FileOutputStream(destName);
System.out.println("is"+is);
byte[] b = new byte[2048];int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
return destName;
}
`
O/P:-
fileName--/uc?export=download&id=0BwtDpsO0CtJZbm9iNUNMTXNTX0k
fileName-extrect from link-/uc?export=download&id=0BwtDpsO0CtJZbm9iNUNMTXNTX0k
For your example URL there is a redirect to a different URL, but a request to that URL returns a response with the header content-type. For your example it is image/jpeg.

Download attachments with same name without overwriting in Java

As per my requirement,i need to download a file from mail inbox into a specified directory,later after some time if same comes in , i need to save the same file into the same directory but with different name,here previous file should not be overridden means files must be saved in the same directory with same names(here i have one assumption,that , for example if my file is abc.txt, after modifications if i download the modified file it can be saved as abc(1).txt ). how can i resolve my issue? can anybody assist me to come out from this issue in JAVA. Below is my code but it is overwriting same file.
if (contentType.contains("multipart")) {
// this message may contain attachment
Multipart multiPart = (Multipart) message.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// save an attachment from a MimeBodyPart to a file
String destFilePath = "F:/unprocessed/"+part.getFileName();
InputStream input = part.getInputStream();
BufferedInputStream in = null;
in = new BufferedInputStream(input);
FileOutputStream output = new FileOutputStream(destFilePath);
byte[] buffer = new byte[4096];
int byteRead;
while ((byteRead = input.read(buffer)) != -1) {
output.write(buffer, 0, byteRead);
}
System.out.println("FileOutPutStream is Being Closed");
output.close();
}
}
}
As said before, you need to check the existing files. Here's one way of doing that:
public String getUniqueFileName(String input) {
String base = "F:/unprocessed/";
String filename = base+input;
File file = new File(filename);
int version = 0;
while (file.exists()) {
version++;
String filenamebase = filename.substring(0, filename.lastIndexOf('.'));
String extension = filename.substring(filename.lastIndexOf('.'));
file = new File(filenamebase+"("+ version+")"+extension);
}
return file.getAbsolutePath();
}
Then change the assignment of destFilePath to a call this method:
String destFilePath = getUniqueFileName(part.getFileName());

How to extract Lotus Notes database icon?

I have tried to extract Lotus Notes database icon by using DXL Exporter but it is not success. Result file is corrupt and can not be opened by image viewer.
How can I extract Lotus Notes database icon by using java?
private String extractDatabaseIcon() {
String tag = "";
String idfile = "";
String password = "";
String dbfile = "";
NotesThread.sinitThread();
Session s = NotesFactory.createSessionWithFullAccess();
s.createRegistration().switchToID(idfile, password);
Database d = s.getDatabase("", dbfile);
NoteCollection nc = d.createNoteCollection(false);
nc.setSelectIcon(true);
nc.buildCollection();
String noteId = nc.getFirstNoteID();
int counter = 0;
while (noteId != null) {
counter++;
try {
Document doc = d.getDocumentByID(noteId);
DxlExporter dxl = s.createDxlExporter();
String xml = dxl.exportDxl(doc);
xml = xml.substring(xml.indexOf("<note "));
org.jsoup.nodes.Document jdoc = Jsoup.parse(xml);
Element ele = jdoc.select("rawitemdata").first();
String raw = ele.text().trim();
String temp = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + "\\";
File file = new File(temp);
file.mkdir();
String filename = temp + UUID.randomUUID().toString().replaceAll("-", "") + ".gif";
byte[] buffer = decode(raw.getBytes());
FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer);
fos.close();
tag = filename;
} catch (Exception e) {
logger.error("", e);
}
if (counter >= nc.getCount()) {
noteId = null;
} else {
noteId = nc.getNextNoteID(noteId);
}
}
return tag;
}
private byte[] decode(byte[] b) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
InputStream b64is = MimeUtility.decode(bais, "base64");
byte[] tmp = new byte[b.length];
int n = b64is.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return res;
}
It is not even a bitmap, it is an icon. The format you can find here:
http://www.daubnet.com/formats/ICO.html
I managed to do this, a long time ago, in LotusScript. My code was based on an earlier version of this page:
http://www2.tcl.tk/11202
For the icon itself, you only have to open one document:
NotesDocument doc = db.getDocumentByID("FFFF8010")
exporter = session.createDXLExporter
exporter.setConvertNotesBitmapsToGIF(false)
outputXML = exporter.export(doc)
and then parse the XML to find the rawitemdata from the IconBitmap item, as you did in your original code.
I'm not sure what the format is. As far as I know' it's a 16 color bitmap, but not in standard BMP file format. And it's definitely not GIF format, but you can tell the DXLExporter to convert it. The default is to leave it native, so you need to add this to your code before you export:
dxl.setConvertNotesBitmapsToGIF(true);

Categories