Java: mock multipartfile in unit test - java

I am trying to mock a MultipartFile and I want to create the mock with a stream that I create in the test
I've tries with a file without much luck either. Here is what I have tried so far
FileInputStream stream = new
FileInputStream("MOCK_file.xlsm");
MultipartFile f1 = new MockMultipartFile("file1",stream);
MultipartFile[] files = {f1};
return files;
I get a fileNotFoundException. Where should I put my file in my Maven project so the unit tests can find the file?
-- OR --
How do I just create a stream in code without the use of a file?

Even better you can mock only the MultipartFile and you will not be needing the InputStream at all.
To do so you only need to do mock(MultiPartFile.class) and then define what each function will do
For example if you use the name
final MultipartFile mockFile = mock(MultipartFile.class);
when(mockFile.getOriginalFilename()).thenReturn("CoolName");
This way you wont have to bother with actual files neither unexpected responses as you will be defining them

How do I just create a stream in code without the use of a file?
You could use a ByteArrayInputStream to inject mock data. It's pretty straightforward for a small amount of data:
byte[] data = new byte[] {1, 2, 3, 4};
InputStream stream = new ByteArrayInputStream(data);
Otherwise, you need to figure out what directory is your code running from, which is something that depends on how it's being run. To help with that you could print the user.dir system property, which tells you the current directory:
System.out.println(System.getProperty("user.dir"));
Alternatively, you can use a full path, rather than a relative one to find the file.

Put the file in
src/test/resources/MOCK_file.xlsm
Read from JUnit class with:
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("MOCK_file.xlsm");

Related

How to convert MultipartFile properly to match for Microsoft AudioConfig?

In my Spring Boot application, I accept an audiofile as MultipartFile with #RequestParam. I know, I can convert the file into some InputStream. I am also able to convert it into some byte array:
#PostMapping("/microsoft")
void transcribe(#RequestParam("file") MultipartFile file) {
InputStream inputStream = new BufferedInputStream(file.getInputStream());
byte[] byteArr = file.getBytes();
AudioConfig audioConfig = AudioConfig.???; //here the correct method with my file needs to be called
}
For transcription using Microsoft API, I need to create some Audioconfig object. This is the link to the class.
I used in the past fromWavFileInput(...) when I loaded a local audio file. But now, I need to be able to use the MultipartFile. I have no idea which method of the AudioConfig class I can use and how to convert the file correctly.
The idea is, to create a temp file and transfer the MultipartFile into it:
File tempFile = File.createTempFile("prefix-", "-suffix");
file.transferTo(tempFile);
The use fromWavFileOutput with the path of the temporary file:
AudioConfig audioConfig = AudioConfig.fromWavFileOutput(tempFile.getPath());
For me, the temp file exceeds its maximum permitted size. To get this solved, make sure to add spring.servlet.multipart.max-file-size=-1 in your application.properties file to set limit to infinity.

Strange NoSuchFileException when trying to read a file

File privateKeyFile = new File(this.getClass().getClassLoader().getResource("privateKey").getFile());
successfully gives me a keyFile. If I now list the path with:
privateKeyFile.toPath()
debug successfully shows me a path to the file:
file:/Users/me/.m2/repository/com/xx/xyz/abc/encryption/1.0/encryption-1.0.jar!/privateKey
--
However, as soon as I try and read that file with
Files.readAllBytes(privateKeyFile.toPath())
I get
Method threw 'java.nio.file.NoSuchFileException' exception.
This is really confusing, and I've tried changing the getResource() to various things like getResource("/privateKey"); - yet that errors a lot sooner, actually a NPE right when trying to create a new File(), so the file MUST exist as I've shown above??
Thanks to replies, I now use this code successfully
//working
InputStream publicKeyStream = this.getClass().getClassLoader().getResourceAsStream("publicKey");
toByteArray(privateKeyStream));
I initally tried the other method that was given, but that resulted in a BadPaddingException, likely due to not fully reading the file
//The incorrect code:
byte[] array = new byte[in.available()];
in.read(array);
The constructor of File does not care if the path string actually points to an existing file, so do not rely on that to check whether the file is there or not. Use privateKeyFile.exists() instead (it returns true if the file exists). From what I see, the file really isn't there or the path you give isn't correct, so exists() should return false.
Since the file is inside of your Jar, it is not recognized by Java as an actual "file". Because of this, you have to read it a little differently. According to this post, you might read it something like this:
InputStream in = getClass().getResourceAsStream("privatekey");
byte[] array = new byte[in.available()];
in.read(array);
Or of you're in Java 9+, it could look like this:
InputStream in = getClass().getResourceAsStream("privatekey");
byte[] array = in.readAllBytes();
Edit:
Since some people wanted an example with the entire source code of the read function, here you go:
InputStream in = getClass().getResourceAsStream("privatekey");
List<Byte> bytes = new ArrayList<Byte>();
while(in.available() > 0) {
byte[] b = new byte[in.available()];
in.read(b);
bytes.addAll(b);
}
byte[] array = (byte[]) bytes.toArray();

NoSuchFileException in Files.newInputStream with StandardOpenOption.CREATE

I am trying to open a file for reading or create the file if it was not there.
I use this code:
String location = "/test1/test2/test3/";
new File(location).mkdirs();
location += "fileName.properties";
Path confDir = Paths.get(location);
InputStream in = Files.newInputStream(confDir, StandardOpenOption.CREATE);
in.close();
And I get java.nio.file.NoSuchFileException
Considering that I am using StandardOpenOption.CREATE option, the file should be created if it is not there.
Any idea why I am getting this exception?
It seems that you want one of two quite separate things to happen:
If the file exists, read it; or
If the file does not exist, create it.
The two things are mutually exclusive but you seem to have confusingly merged them. If the file did not exist and you've just created it, there's no point in reading it. So keep the two things separate:
Path confDir = Paths.get("/test1/test2/test3");
Files.createDirectories(confDir);
Path confFile = confDir.resolve("filename.properties");
if (Files.exists(confFile))
try (InputStream in = Files.newInputStream(confFile)) {
// Use the InputStream...
}
else
Files.createFile(confFile);
Notice also that it's better to use "try-with-resources" instead of manually closing the InputStream.
Accordingly to the JavaDocs you should have used newOutputStream() method instead, and then you will create the file:
OutputStream out = Files.newOutputStream(confDir, StandardOpenOption.CREATE);
out.close();
JavaDocs:
// Opens a file, returning an input stream to read from the file.
static InputStream newInputStream(Path path, OpenOption... options)
// Opens or creates a file, returning an output stream that
// may be used to write bytes to the file.
static OutputStream newOutputStream(Path path, OpenOption... options)
The explanation is that OpenOption constants usage relies on wether you are going to use it within a write(output) stream or a read(input) stream. This explains why OpenOption.CREATE only works deliberatery with the OutputStream but not with InputStream.
NOTE: I agree with #EJP, you should take a look to Oracle's tutorials to create files properly.
I think you intended to create an OutputStream (for writing to) instead of an InputStream (which is for reading)
Another handy way of creating an empty file is using apache-commons FileUtils like this
FileUtils.touch(new File("/test1/test2/test3/fileName.properties"));

how to access image folder in spring application

I like to access an image from the web/images directory. I like to access this image in the spring controller, so I can convert this image to byte[]. I am creating a chart and this image is part of the chart display. So, I am using this byte[] to construct Graphic2d object. Closest I have got to it is using this:
FileSystemResource resource = new FileSystemResource("images/"+imageName);
Currently, I have stored this image in the package structure. I like to do better than this. I like to read directly from web/images directory. Please give me some advice, Thanks.
The more elegant way is let your controller implement ServletContextAware so as your controller can injecte ServletContext instance, then you should use:
InputStream stream = servletContext.getResourceAsStream("/images/image.jpg");
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
//process image data, i.e. write to sompe place,etc.
}
//close the stream
stream.close();
BTW, as for servletContext.getRealPath, different servlet container might have different implementation, and it might not work after project packaged to a war file. so, it's recommended to use getResourceAsStream.
Well you can use servlet context to get the path to web/images. Use following code:
File file=new File(request.getSession().getServletContext().getRealPath("images/file.jpg"));
Note: Here I am utilizing request i.e. HttpServletRequest.

How to create a java.io.File from a ByteArrayOutputStream?

I'm reading a bunch of files from an FTP. Then I need to unzip those files and write them to a fileshare.
I don't want to write the files first and then read them back and unzip them. I want to do it all in one go. Is that possible?
This is my code
FTPClient fileclient = new FTPClient();
..
ByteArrayOutputStream out = new ByteArrayOutputStream();
fileclient.retrieveFile(filename, out);
??????? //How do I get my out-stream into a File-object?
File file = new File(?);
ZipFile zipFile = new ZipFile(file,ZipFile.OPEN_READ);
Any ideas?
You should use a ZipInputStream wrapped around the InputStream returned from FTPClient's retrieveFileStream(String remote).
You don't need to create the File object.
If you want to save the file you should pipe the stream directly into a ZipOutputStream
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
// do whatever with your zip file
If, instead, you want to open the just retrieved file work with the ZipInputStream:
new ZipInputStream(fileClient.retrieveFileStream(String remote));
Just read the doc here and here
I think you want:
ZipInputStream zis = new ZipInputStream( new ByteArrayInputStream( out.toByteArray() ) );
Then read your data from the ZipInputStream.
As others have pointed out, for what you are trying to do, you don't need to write the downloaded ZIP "file" to the file system at all.
Having said that, I'd like to point out a misconception in your question, that is also reflected in some of the answers.
In Java, a File object does no really represent a file at all. Rather, it represents a file name or *path". While this name or path often corresponds to an actual file, this doesn't need to be the case.
This may sound a bit like hair-splitting, but consider this scenario:
File dir = new File("/tmp/foo");
boolean isDirectory = dir.isDirectory();
if (isDirectory) {
// spend a long time computing some result
...
// create an output file in 'dir' containing the result
}
Now if instances of the File class represented objects in the file system, then you'd expect the code that creates the output file to succeed (modulo permissions). But in fact, the create could fail because, something deleted the "/tmp/foo", or replaced it with a regular file.
It must be said that some of the methods on the File class do seem to assume that the File object does correspond to a real filesystem entity. Examples are the methods for getting a file's size or timestamps, or for listing the names in a directory. However, in each case, the method is specified to throw an exception if the actual file does not exist or has the wrong type for the operation requested.
Well, you could just create a FileOutputStream and then write the data from that:
FileOutputStream fos = new FileOutputStream(filename);
try {
out.writeTo(fos);
} finally {
fos.close();
}
Then just create the File object:
File file = new File(filename);
You need to understand that a File object doesn't represent any real data on disk - it's just a filename, effectively. The file doesn't even have to exist. If you want to actually write data, that's what FileOutputStream is for.
EDIT: I've just spotted that you didn't want to write the data out first - but that's what you've got to do, if you're going to pass the file to something that expects a genuine file with data in.
If you don't want to do that, you'll have to use a different API which doesn't expect a file to exist... as per Qwerky's answer.
Just change the ByteArrayOutputStream to a FileOutputStream.

Categories

Resources