Tomcat: WebService response as zip archive instead of file - java

I want web service to make response as a zip file.
Generally there is nothing hard to do. But there is one thing I want to know:
Can I zip file without saving it to the hard disk, even if it's very large (100Mb - 500Mb)?
Now I'm using this nice hack. And i want to extend it with ziping functionality without creating new files on the file system.
public class TempFileInputStream extends FileInputStream {
private File file;
public TempFileInputStream(File file) throws FileNotFoundException {
super(file); // TO WANT: to pass here already zipped stream
this.file = file;
}
#Override
public void close() throws IOException {
super.close();
if (!file.delete()) {
// baad
} else {
// good
}
}
}
If I can, then what is the better/optimal way to do it ?
Thanks for any help !

take a look at this:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/zip/ZipOutputStream.html
hope that helps...

Related

Java unit testing Java NIO Files library?

Let's say I have a method like:
public void copyAndMoveFiles() throws IOException {
Path source = Paths.get(path1);
Path target = Paths.get(path2);
if (Files.notExists(target) && target != null) {
Files.createDirectories(Paths.get(target.toString()));
}
for (String fileInDirectory: Files.readAllLines(source.resolve(fileToRead))) {
Files.copy(source.resolve(fileInDirectory), target.resolve(fileInDirectory), StandardCopyOption.REPLACE_EXISTING);
}
}
How would I do a unit test on this? I have tried looking at mockito but it doesn't return anything or have anything I can assert. I read about JimFs, but for some reason, I can't grasp my head around that.
I don't think mocking is the right way to go here. Since you're code reads and writes files, you need a file system, and you need to assert its state at the end of the test.
I'd create temporary directories for source and target (e.g., using JUnit's TempDir). Then, you can set up various test cases in the source directory (e.g., it's empty, one file, nested directories, etc) and at the end of the test used java.io functionality to assert the files were copied correctly.
EDIT:
stub-by example of the concept:
class MyFileUtilsTest {
#TempDir
File src;
#TempDir
File dest;
MyFileUtils utils;
#BeforeEach
void setUp() {
utils = new MyFileUtils();
}
#Test
void copyAndMoveFiles() throws IOException {
// Create a file under src, initialize the utils with src and dest
File srcFile = File.createTempFile("myprefix", "mysuffix", src);
utils.copyAndMoveFiles();
File destFile = new File(dest, srcFile.getName());
assertTrue(destFile.exists());
}
}

Filter all files in any depth by file prefix inside a directory

I'm using Apache Commons VFS2.0 to access files both in a local file system and a remote file system. I'm trying to find a way to filter all the descendent files in any depth with FileType=File and has a given filePrefix with the file name. I was able to do it for the same case except for file prefix, but for file extension, as follows.
FileSelector fileSelector = new FileExtensionSelector("extensions...");
directory.findFiles(fileSelector);
In this way, I was able to fetch all the files(no folders) in any depth with the given extension. I have tried the below approach but it only works for matching files with depth=1.
FileFilterSelector prefixFileSelector = new FileFilterSelector(new PrefixFileFilter("Prefix"));
directory.findFiles(prefixFileSelector);
Appreciate if anyone can give a suggestion.
new FileFilterSelector(fileFilter) {
#Override
public boolean traverseDescendents(FileSelectInfo fileInfo) {
return true;
}
#Override
public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
return accept(fileInfo);
}
}

How do I create those methods correctly for a html file?

Completely new to programming and studying it right now at a university. This might seem easy but they literally showed us nothing on how to program so this task is hard for me to do. So maybe someone here can help me understand how I can do this:
The task:
Create a method called "open(String fileName)" that creates and opens a text file with the name fileName
Create a method called "pageStart()" that writes "html" into the file
There are a lot more methods I have to create but all of them should be easy if I understand how the "pageStart()" one works.
package exporter;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class HTMLCreator {
public static void main(String[] args) {
open("Hello.txt");
}
public static void open(String fileName) {
File file = new File(fileName);
try {
// Creates new file
if (file.createNewFile()) {
}
// Opens file
Desktop desktop = Desktop.getDesktop();
if (file.exists())
desktop.open(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Ok so that does create a .txt file and opens it. So far so good.
Now the problem. I have to create a method that WRITES into that .txt file and I have NO clue how to do that.
What I tried until now:
public static void startPage() {
FileWriter fw = new FileWriter(file)/*<-- obviously won't work but I don't know how it would work...*/;
fw.write("<html>");
fw.close();
}
I know that this obviously won't work since the file that I want is not in that method. How do I do that?
How do I make it so my startPage() method writes into the Hello.txt file I created earlier?
I would appreciate help a lot!!!
My question is not about how to create and write into a textfile! My question is more how you combine two methods to do this! It would help immensely if someone could write two methods for me, one that creates and opens a textfile and another method that writes into the textfile that the first method created and opened. That would most likely solve my problem!

Changing the properties file while the application is running

I have a attribute in properties file. say 'x'.
In my Java class, I use this x in a loop. So the first time loop is executed, it loads from properties file and from the second time, it takes value from memory without loading the props file every time. Now if I want to change the value of x in the properties file, can i load that value without restarting the application? If yes, how?
Also is there any Java equivalent for Session_OnStart in .net? I heard Session_OnStart in .net serves this purpose
You can load and parse the properties each time a variable is requested.
class RefreshingProperties extends Properties {
private final File file;
public RefreshingProperties (File file) throws IOException {
this.file = file;
refresh ();
}
private void refresh () throws IOException {
load (new FileInputStream (file));
}
#Override
public String getProperty (String name) {
try { refresh (); }
catch (IOException e) {}
return super.get (name);
}
}
You can tweak this to reload only whenever a certain time period expires

How to get files from a directory on specific condition one file must come after another

Hi I am trying to load data into table using data files. I am using JDBC batch upload. After I load data from test.data into table, I want to validate it using expected-table.data. So in the following method first when test.data comes I want to do batch upload and then it should validate data using expected file but the following code does not work as expeted-data files comes in first iteration and test.data in second iteration. Please help I am new to file programming. Thanks in advance.
public static void loadFromFilesNValidateTable(Schema schema, final File folder)
{
for (final File fileEntry : folder.listFiles())
{
if (fileEntry.isDirectory())
{
loadFromFilesNValidateTable(schema,fileEntry);
}
else
{
if(fileEntry.getName().equals("test.data"))
{
BatchUpload.batchUpload(schema,fileEntry.getAbsolutePath());
}
if(fileEntry.getName().equals("expected-table.data"))
{
validateData(schema,fileEntry.getAbsolutePath());
}
}
}
}
Use a FileFilter
public static void loadFromFilesNValidateTable(TableDef schema, final File folder) {
// Process folders recursively
for(final File subFolder : folder.listFiles(new DirectoryFilter())){
loadFromFilesNValidateTable(schema, subFolder);
}
// Process data files
for (final File dataFileEntry : folder.listFiles(new FileNameFilter("test.data"))) {
BatchUpload.batchUpload(schema,dataFileEntry.getAbsolutePath());
}
// Process expected files
for (final File expectedFileEntry : folder.listFiles(new FileNameFilter("expected-table.data"))) {
validateData(schema,expectedFileEntry.getAbsolutePath());
}
}
public class FileNameFilter implements FileFilter {
private String name;
public FileNameFilter(String name){
this.name = name;
}
public boolean accept(File pathname){
return pathname.getName().equals(name)
}
}
public class DirectoryFilter implements FileFilter {
public boolean accept(File pathname){
return pathname.isDirectory();
}
}
Note: Apache commons-io provides a lot of FileFilters ready to use http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/filefilter/package-summary.html
I have 2 things to suggest you:
1. Change equals method with matches method. Matches method is the best method to compare
Strings.
2. Try to separate the moment in which you do batchUpload from that in which you do
validateData. Maybe you jump some files. For example the algorithm finds first the
"expected-table.data" file and then the "test.data" file. In this case it doesn't validate
the file. I hope my answer is usefull and I hope I have understood your problem : )
You should change the algorithm to something like this:
for (each directory in current directory) {
loadFromFilesNValidateTable(schema, directory);
}
if (current directory contains file "test.data") {
batchUpload();
if (current directory contains file "expected-table.data") {
validateData();
}
}

Categories