Web Service to Display a PDF, deleting the file once displayed - java

I am attempting to display PDFs to the user in their browser using a web service. Once they pass in the URL containing the variables needed. My program first downloads the PDF to local storage then proceeds to copy it to the stream and displays it. Once the viewer is able to view the PDF we wish to delete the file locally so that we do not wind up storing every file searched for. I have managed to accomplish most of this task however I am having issues deleting the file once it is displayed to the user.
Even when I attempt to manually delete the file I receive the "Currently in use in the Java SE Binary" message
Code below:
File testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".pdf");
try
{
ServletOutputStream os = res.raw().getOutputStream();
FileInputStream inputStr = new FileInputStream(testFile);
IOUtils.copy(inputStr, os);
os.close();
inputStr.close();
//finished settings
res.status(200);
testFile.delete();
} catch (IOException e)
{
System.out.println(e.getMessage());
}

If you don't write to the file, you'r code should work.
If you call inputStr.close(); the file is no longer used by java and it can be deleted.
Pleace check, if your file is not used by any other programm. It's the best if you reboot your PC.
If it still not works, it would be interessting to know, what res is and if your file get's sendet.
I've read this part of the documentation and i think this should solve your problem.
It reads the file into a String and change the header for png images. As the http Body it uses the String of the file.
Make sure, if you change the response type, you have to change the line res.type("image/png"); to the new one.
Here you find the most common ones
File testFile = null;
try {
testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".png");
FileInputStream fin = new FileInputStream(testFile);
int charAsInt = 0;
String httpBody = "";
while((charAsInt = fin.read()) != -1){
httpBody +=(char)charAsInt;
}
fin.close();
res.body(httpBody);
res.type("image/png");
res.status(200);
testFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

ThumbnailUtils.createVideoThumbnail

Can someone please tell me if what I'm doing is correct?
File directoryToStore;
directoryToStore = getBaseContext().getExternalFilesDir("MyFiles");
Bitmap b = ThumbnailUtils.createVideoThumbnail(directoryToStore + "/" + SavedVideoName, 3);
File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg"));
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
b.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm trying create a thumbnail from a video, but for some the FileOutputStream returns null.
I have checked the path of File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg")); and it returns the correct path.
The video exists at the location I have given and I have permissions. I can't understand why it is gives me a null pointer?
According to this post, new FileOutputStream() will try to create a new file if it doesn't exist already. From the docs:
If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
When you are debugging (at least in Android Studio), if you add a breakpoint and hover over newFile, it shows the file path. However, it doesn't show any details about the file, because the file doesn't (shouldn't) exist yet. You could try newFile.createNewFile() as suggested in the linked post, to confirm you are able to write the file first.

Java: open text file as html file with browser using File.renameTo()

I want to convert a text file to a html file and then open it with a browser. I try to use file.renameTo() to rename the text file's extension to .html but the rename attempt always fails and file.renameTo() always returns false. Therefore, when I try to open the file in the below method, the file is opened in notepad.
file declaration:
private File file;
file declaration in constructor:
file = new File("D:/dc1000/Project/webPage.txt");
file.getParentFile().mkdirs();
method that doesn't work:
public void compileWebpage(){
File file2 = new File("D:/dc1000/Project/CompiledWebpage.html");
file2.getParentFile().mkdirs();
addFileTags("end"); //add ending tags like </body>
boolean success = true;
try{
success = file.renameTo(file2);
}catch (Exception e){
System.out.println(e);
}
if(!success){
System.out.println("webPage compilation failed.");
}
Desktop desktop = Desktop.getDesktop();
try{
desktop.browse(file.toURI());
}catch (IOException e){
e.printStackTrace();
}
}
No exceptions are thrown, "Webpage compilation failed" is printed to the console and then notepad opens the file. The file looks like this when opened in notepad:
<html>
<head>
</head>
<body>
<p>hi</p>
</body>
</html>
Why does File.renameTo() always fail? How can I open this text file in a browser as a html file?
Well, off hand it's rather hard to tell without truly knowing what the addFileTag() method is doing. The only reason I can think of is that the webPage.txt file is still open for either read or write operations.
Your code has accessed the file but never closed it again. You can't rename a file that is open. I would have to assume this is in fact done somewhere within the addFileTag() method.
Because your call to the File.renameTo() method was unsuccessful the "webPage.txt" text file was never renamed to "CompiledWebpage.html" so in essence the "CompiledWebpage.html" file simply does not exist within the system. This however is not the reason why the Windows NotePad application is opening your file instead of the expected default Web Browser:
To begin with the File object variable so conveniently named 'file' was declared and initialized to be related to the "D:/dc1000/Project/webPage.txt" text file and it always will be since it's Class global unless of course that relationship is changed somewhere within your code. To be blunt... it's not and I guess it's a good thing for now because IF your File Rename was successful you would have simply gotten an FileNotFound Exception because the text file related to the 'file' variable would no longer exist due to the simple fact that it was renamed.
What you really want to pass to the DeskTop.browse() method is the File object 'file2' variable which is related to the "D:/dc1000/Project/CompiledWebpage.html" text file. Mind you, you'll still get an FileNotFound Exception because the File.renameTo() method had failed. So you definitely want to make sure you have success here.
Whatever...Why did the Windows NotePad application open instead of the Web Browser?
Here's why:
The Operating System File Associations is what determines which application will open the file when using the DeskTop.browse() method. In the Windows Operating System, by default, a file with the file name extension of ".txt" is automatically opened and displayed within NotePad, a file with the file name extension of ".docx" is automatically opened and displayed in MS Office WORD, a file with the file name extension of ".html" is opened and displayed within the default Web Browser. I think you get the idea here.
Because the 'file' variable is still related to the file "D:/dc1000/Project/webPage.txt" and because the File.renameTo() method failed, Windows simply seen the .txt file extension and displayed the file (as stipulated within the 'file' variable) to NotePad.
So...How do I get all this to actually Work!?
Well, if I may be so bold, do this instead:
Place this somewhere in your code, a button action event or whatever:
String sourceFile = "D:/dc1000/Project/webPage.txt";
String destinationFile = "D:/dc1000/Project/CompiledWebpage.html";
boolean success = CompileToWebPage(sourceFile, destinationFile, "This is My Head Text");
if (success) {
System.out.println("Text File Successfully Compiled!");
}
else {
System.out.println("Text File Compilation FAILED!");
}
//Display our new file in the web Browser...
try {
File htmlFile = new File(destinationFile);
Desktop.getDesktop().browse(htmlFile.toURI());
} catch (IOException ex) {}
Here is a new CompileToWebPage() method:
private static boolean CompileToWebPage(final String sourcefilePath,
final String destinationFilePath, String... headText) {
// headText is OPTIONAL.
String headTxt = "";
if (headText.length != 0) { headTxt = headText[0]; }
//Read sourcefilePath file data into a String ArrayList...
BufferedReader input;
try {
input = new BufferedReader(new FileReader(sourcefilePath));
if (!input.ready()) { throw new IOException(); }
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\nThe supplied "
+ "file path was not found!\n\n" + sourcefilePath, "File NotFound",
JOptionPane.ERROR_MESSAGE);
return false;
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\nThe supplied "
+ "file is not ready to be read!\n\n" + ex.getMessage(), "File Not Ready",
JOptionPane.ERROR_MESSAGE);
return false;
}
// Place required HTML Tags into String ArrayList
ArrayList<String> txt = new ArrayList<>();
txt.add("<html>");
txt.add("<head>");
txt.add(headTxt);
txt.add("</head>");
txt.add("<body>");
// Read each line of the source text File and add
// them to our String ArrayList...
try {
String str;
while((str = input.readLine()) != null){
txt.add("<p>" + str + "</p>");
}
input.close();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\n"
+ "There was a problem reading the source Text from file!\n\n"
+ ex.getMessage(), "File Read Error", JOptionPane.ERROR_MESSAGE);
return false;
}
// Place our HTML finishing Tags into our String ArrayList...
txt.add("</body>");
txt.add("</html>");
// Write the String ArrayList to our supplied Destination
// File Path...
try {
FileWriter fw = new FileWriter(destinationFilePath);
Writer output = new BufferedWriter(fw);
for (int i = 0; i < txt.size(); i++) {
// Some Windows applications (such as NotePad require
// the \r tag for a new line to actually be accomplished
// within a text file.
output.write(txt.get(i) + "\r\n");
}
output.close();
return true;
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"CompileToWebPage() Method Error!\n\n"
+ "There was a problem writing the Compiled Web Text to file!\n"
+ "Ensure that permissions are properly set.\n\n" + ex.getMessage(),
"File Write Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
Well, I hope this has helped you somewhat or at the very least been entertaining.

PDF File does not open in JAR

I am trying to open a PDF file when a button is clicked. However I can't seem to get this working when I run my program as a JAR.
Initially, I was using this code:
if(Desktop.isDesktopSupported())
{
try
{
File myFile = new File("src/1. Handel - And the Glory of the Lord.pdf");
Desktop.getDesktop().open(myFile);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
That worked on Netbeans, however it didn't work on the JAR. After research, I found out its because I need to open it using a stream. Meaning I had to make a copy of it as a stream, and open that copy as a File. After looking around on stack overflow, I am now using this code:
try {
String inputPdf = "src/1. Handel - And the Glory of the Lord.pdf";
InputStream manualAsStream = getClass().getClassLoader().getResourceAsStream(inputPdf);
Path tempOutput = Files.createTempFile("1. Handel - And the Glory of the Lord", ".pdf");
tempOutput.toFile().deleteOnExit();
Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
File file = new File (tempOutput.toFile().getPath());
if (file.exists())
{
Desktop.getDesktop().open(file);
}
} catch (IOException ex) {
Logger.getLogger(HandelNotes.class.getName()).log(Level.SEVERE, null, ex);
}
This does not even work on Netbeans, whilst on another thread on Stack Exchange, the user said it worked for them.
I am getting a java.lang.NullPointerException error, on this line:
Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
Does anyone know what's going wrong, and could someone please tell me how to correct my code?
Thanks,
Rohan

download the files from Gdrive to local system by using java

Drive Quickstart: Run a Drive App in Java example works for uploading files fine. I want to download the files from Gdrive to local system by using java.
For download they are given a method
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
The above method,how can i give inputs? and from where i give the inputs? Can anyone give a complete code for download like Quickstart upload class.
any help will be appreciated.
you can use google drive api and send Http get request, you can see this tutorial
https://developers.google.com/drive/manage-downloads
Thanks Hanan it works fine.By using the retrieveAllFiles() i can list all the documents.And i have stored the retrieved documents in my local by using this below code.Is it a correct way to download.
for(File f:result){
i++;
System.out.println("File Name==>"+f.getTitle());
System.out.println("File Id==>"+f.getId());
System.out.println("File ext==>"+f.getFileExtension());
System.out.println("File size==>"+f.getFileSize());
InputStream in = downloadFile(service,f);
byte b[] = new byte[in.available()];
in.read(b);
java.io.File ff = new java.io.File("/home/test/Desktop/gdocs/"+f.getTitle());
FileOutputStream fout = new FileOutputStream(ff);
fout.write(b);
fout.close();
}
It stores all the documents in local. The text (.txt) files are open properly in my local, but the image files or pdf files are not open properly.It gives some error messages like file corrupted. There is no content in the image or pdf documents how can i get content and store it. Any suggestions

Java: Error when save file in Resource after Deployment

My program has a function that read/write file from resource. This function I have tested smoothly.
For example, I write something to file, restart and loading again, I can read that data again.
But after I export to jar file, I faced problems when write file. Here is my code to write file:
URL resourceUrl = getClass().getResource("/resource/data.sav");
File file = new File(resourceUrl.toURI());
FileOutputStream output = new FileOutputStream(file);
ObjectOutputStream writer = new ObjectOutputStream( output);
When this code run, I has notice error in Command Prompt:
So, My data cannot saved. (I know it because after I restarted app, nothing changed !!!)
Please help me solve this problem.
Thanks :)
You simply can't write files into a jar file this way. The URI you get from getResource() isn't a file:/// URI, and it can't be passed to java.io.File's constructor. The only way to write a zip file is by using the classes in java.util.zip that are designed for this purpose, and those classes are designed to let you write entire jar files, not stream data to a single file inside of one. In a real installation, the user may not even have permission to write to the jar file, anyway.
You're going to need to save your data into a real file on the file system, or possibly, if it's small enough, by using the preferences API.
You need to read/write file as an input stream to read from jar file.
public static String getValue(String key)
{
String _value = null;
try
{
InputStream loadedFile = ConfigReader.class.getClassLoader().getResourceAsStream(configFileName);
if(loadedFile == null) throw new Exception("Error: Could not load the file as a stream!");
props.load(loadedFile);
}
catch(Exception ex){
try {
System.out.println(ex.getMessage());
props.load(new FileInputStream(configFileName));
} catch (FileNotFoundException e) {
ExceptionWriter.LogException(e);
} catch (IOException e) {
ExceptionWriter.LogException(e);
}
}
_value = props.getProperty(key);
if(_value == null || _value.equals("")) System.out.println("Null value supplied for key: "+key);
return _value;
}

Categories