I've been trying to generate report files with Dynamic Reports, however it just doesn't seem to create files on Server. When I use the same method running locally it generates the file, however when I run it on server, there are not files created. I'm running Tomcat 7 in Eclipse. The file is supposed to be created using FileOutputStream.
Well here's the method that works locally, but not on Tomcat:
StyleBuilder plainStyle = stl.style().setFontName("FreeUniversal");
StyleBuilder boldStyle = stl.style(plainStyle).bold();
StyleBuilder italicStyle = stl.style(plainStyle).italic();
StyleBuilder boldItalicStyle = stl.style(plainStyle).boldItalic();
try {
report().title(
Templates.createTitleComponent("Fonts"),
cmp.text("FreeUniversal font - plain").setStyle(plainStyle),
cmp.text("FreeUniversal font - bold").setStyle(boldStyle),
cmp.text("FreeUniversal font - italic").setStyle(italicStyle),
cmp.text("FreeUniversal font - bolditalic").setStyle(boldItalicStyle))
.toDocx(createFile("docx"))
// .show()
;
} catch (DRException e) {
e.printStackTrace();
}
Oh and the CreateFile(...) method:
private FileOutputStream createFile(String extension) throws FileNotFoundException {
FileOutputStream file;
String filePath = reportsPath + "generated_report." + extension;
filePath = "generated_report." + extension;
System.out.println("FILENAME IS: " + filePath);
file = new FileOutputStream(new File(filePath));
return file;
}
I know the reportsPath here is not active.
So there are no exceptions. By the way, it might be possible that other files don't get created on this server too, because I'm also uploading a file via servlet and it get used, however it doesn't appear anywhere in the path and it doesn't seem to be saved, but I don't need to keep the uploaded files anyway, so it wasn't much of a concern, but now this? I need to be able to find those reports, so the files must get created.
And I'm sure it's not that I can't find the files, I've run the search everywhere, actually in all of my computer on which the server is running, there were no files created with that name...
So, any ideas? It must be a Tomcat configuration issue or something?
Any ideas? Thanks
The output was written to the file you supplied in the constructor. If that was a relative filename, it is relative to the current working directory when you executed the code.
Or else an IOException was thrown and the code didn't execute at all.
Related
I'm using the code from here:
https://developers.google.com/drive/api/v3/manage-downloads#downloading_a_file
The code snippet I'm using is the following and placed in the main method:
String fileId = "some file ID";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
I have found no sign of the code actually downloading the file, nor do I know where the file is IF it actually downloads.
I'm not sure if I am using the proper scope to gain permission to download files. I am able to upload, list, and delete files as long as I know the fileID, but downloading seems to not work.
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
Alternatively, I'm trying to create a method to enact the download protocol like so:
private static void downloadFile(Drive service, File file (or String fileID)){
}
but am not sure on how to do so. I've tried looking for samples online but most are from v1 or v2 apis and don't seem to work for me.
Also, I've read somewhere that it is not possible to download a Folder. Instead, I have to download each item in the folder one by one.
So do I have to make an Arraylist/list/array of the fileIDs and iterate through it after initializing a variable to represent fileID?
Edit: Some progress has been made, but I still have some problems I'm trying to thrash out.
List<File> files = result.getFiles();
File newFile;
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
String fileId = file.getId();
//System.out.println(fileId);
String fileName = file.getName();
//System.out.println(fileName);
OutputStream outputstream = new FileOutputStream();
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
outputstream.flush();
outputstream.close();
}
What I want:
The above code is in the main method. I don't know if this is the proper way to do it, but as the program fetches each file and executes the System.out.printf, I also want it to download that file (with the same mimeType, and pref the same name too) into the destination set in the OutputStream constructor (C://User//some name//Downloads).
What I've tried:
From what I've tested, it only downloads the first file exactly the way I want, but only because I specify the name and extension in OutputStream. I've initialized variables 'fileId' and 'fileName' so that they will change according to the info as the program fetches the metadata for the next file, but I don't know how to change or set multiple constructors into this code:
OutputStream outputstream = new FileOutputStream();
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
to download all the files.
My folder hierarchy in Google Drive is like this:
Logs
-- bin (folder)
---- bunch of .bin files
-- .xml file
-- .xml file
You are using a ByteArrayOutputStream object as the output of your download. If your program terminates without having saved the contents of this object somewhere, you will not be able to find this information in your computer's disk, as it is not written to it but rather saved in memory as a buffered byte-array (refer to the previous link for more information).
If you want to save the output of the download to the file, I suggest you use instead a FileOutputStream as the destination of your download. In order to do that, you have to modify your code as follows:
Add the appropriate import declaration:
import java.io.FileOutputStream;
Modify your outputStream variable assignment as follows:
OutputStream outputStream = new FileOutputStream('/tmp/downloadedfile');
Where the parameter passed to FileOutputStream should be the desired destination path of your download.
After writing any contents to your file, add the following lines of code:
outputStream.flush();
outputStream.close();
This will ensure that your file is being written to properly.
In regards to downloading a folder, you are completely right - you will first need to fetch the folder you want to download, and each of their children. In order to better understand how to do it, I suggest you check out the following answer: Download folder with Google Drive API
Edit - example downloading a folder
String destinationFolder = "/tmp/downloadedfiles/";
List<File> files = result.getFiles();
File newFile;
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
String fileId = file.getId();
String fileName = file.getName();
OutputStream outputstream = new FileOutputStream(destinationFolder + fileName);
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
outputstream.flush();
outputstream.close();
}
}
When trying to load the file in Eclipse the file loads just fine, however when I package the project into a .JAR file using jar-splice it seems that the application can no longer locate its resource files.
Here's the error thrown when the application is run
And here is the method that loads files:
public static File loadFile(String path) throws FileNotFoundException
{
InputStream stream;
stream = FileUtil.class.getClassLoader().getResourceAsStream(path);
System.out.println("Stream = " + stream); //Debug purposes
File file = new File(FileUtil.class.getClassLoader().getResource(path).getFile());
if (!file.exists())
{
System.err.println("Path: " + FileUtil.class.getClassLoader().getResource(path).getPath()); //Also debug purposes
throw new FileNotFoundException();
}
return file;
}
Using those two System.out.printlns it's clear that the application can't find the file based on that path, but if you look at the picture that path is exactly where the file it's looking for is located. I am so confused as this has never happened before, and the path it's saying it can't find the file at is exactly where it is. Any ideas anyone?
Here is the method that files
Here is the method that neither does nor can load resources as Files. It is impossible. Resources are not files and do not live in the file system. You must redesign it to return either a URL or an InputStream, and as you can get both directly from a Class or ClassLoader you don't actually need the method at all.
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
I had developed software in eclipse and platform was ubuntu (linux). I used gujarati fonts in program and completed it and it runs wery well in ubuntu but while running in windows 7 with JRE it doesnt work properly. Text won't show properly as it used in ubuntu. What shoud I do?
I have tried using java -Dfileencoding=utf-8 also but it wont worked properly. While I open java sorce file picked from Ubuntu in Windows the text works and shows properly.
So please tell me the way to do work this properly.
If you want to use a custom font in your application (that isn't available on all operating systems), you will need to include the font file (otf, ttf, etc.) in your .jar file, you can then use the font in your application via the method described here:
http://download.oracle.com/javase/6/docs/api/java/awt/Font.html#createFont%28int,%20java.io.File%29
Sample code from (Here thanks to commenter);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
If your unsure on how to extract your file from a .jar, here's a method I've shared on SO before;
/**
* This method is responsible for extracting resource files from within the .jar to the temporary directory.
* #param filePath The filepath relative to the 'Resources/' directory within the .jar from which to extract the file.
* #return A file object to the extracted file
**/
public File extract(String filePath)
{
try
{
File f = File.createTempFile(filePath, null);
FileOutputStream resourceOS = new FileOutputStream(f);
byte[] byteArray = new byte[1024];
int i;
InputStream classIS = getClass().getClassLoader().getResourceAsStream("Resources/"+filePath);
//While the input stream has bytes
while ((i = classIS.read(byteArray)) > 0)
{
//Write the bytes to the output stream
resourceOS.write(byteArray, 0, i);
}
//Close streams to prevent errors
classIS.close();
resourceOS.close();
return f;
}
catch (Exception e)
{
System.out.println("An error has occurred while extracting a resource. This may mean the program is missing functionality, please contact the developer.\nError Description:\n"+e.getMessage());
return null;
}
}
You'll need to install the font into Windows - or change the font on your application. You can do this by including it in your install process.
Fixed: Instead of calling isFile() I used exists() and it seems to be working fine. If possible could someone explain why this change worked?
I'm attempting to write out to an excel file but am having a problem when trying to create that file if the name already exists.
Basically I am taking a file that is uploaded to a server, reading it, and then outputting a report file in a new location with the same filename. I tried to do this by simply checking if the file already existed and then adding a number onto the filename. My code works if the file doesn't exist or if it exists without a number (e.g. filename.xls). If a file exists with the name "filename1.xls" the server just seems to hang when trying to write the file. What can do to fix this?
Here is my code:
String destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + ".xls";
int filenum = 1;
while (new File(destination).isFile()) {
destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + filenum + ".xls";
filenum++;
}
WritableWorkbook workbook = Workbook.createWorkbook(new File(destination));
That will happen if some process is still keeping the file open. E.g. you've created a FileInputStream on the file to read it, but are never calling close() on it after reading.
Unrelated to the problem, the expanded WAR folder is not the best place to use as a permanent storage. All those files in the expanded WAR folder will get lost whenever you redeploy the WAR. Also hardcoding a servletcontainer-specific path in the code makes it totally unportable.
If your actual intent is to return the Excel file on a per-request basis to the client using a servlet, then you should be using
WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
// ...
This way it writes to the response immediately without the need for an intermediate file.
Use the File.createTempFile(prefix, suffix, directory) API:
String localName = new File(fileName).getName();
String nameNoExt = localName.substring(0, fileName.lastIndexOf("."));
String extension = localName.substring(fileName.lastIndexOf(".")); // need to include the .
File directory = new File("c:/apache-tomcat-7.0.8/webapps/reports/");
File destFile = File.createTempFile(nameNoExt, extension, directory)