java.nio.file.NoSuchFileException: on android instrumented test [duplicate] - java

I've got this project which processes images. The library I use to do most of the actual image processing requires me to run these tests on a Android device or emulator. I'd like to provide a few test images which it should process, the thing is that I don't know how to include these files in the androidTest APK. I could supply the images through the context/resources but I'd rather not pollute my projects resources. Any suggestions as to how to supply and use files in instrumented unit tests?

You can read asset files that are in your src/androidTest/assets directory with the following code:
Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
InputStream testInput = testContext.getAssets().open("sometestfile.txt");
It is important to use the test's context as opposed to the instrumented application.
So to read an image file from the test asset directory you could do something like this:
public Bitmap getBitmapFromTestAssets(String fileName) {
Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
AssetManager assetManager = testContext.getAssets();
InputStream testInput = assetManager.open(fileName);
Bitmap bitmap = BitmapFactory.decodeStream(testInput);
return bitmap;
}

Related

Jar not finding image

I have a maven project with spring-boot. I have a png image in my-module/src/resources/images/image.png.
I make mvn clean package and a Jar is generated, ok, now I run the Jar as java -jar my_jar.jar but I get this error java.io.FileNotFoundException: /Users/jose/projects/my-project/classpath:images/image.png
In code I have:
private static final String IMAGE_PATH = "classpath:images/image.png";
and
Image image = PngImage.getImage(IMAGE_PATH);
Seems that it does not get :classpath keyword as it should, but as a literal.
When I unzip the Jar file the image is located in /BOOT-INF/classes/images/image.png
The idea is not to change the code if possible but the way of execute or generate the Jar.
All suggestions are welcome though.
Thank you
I'm not sure what PngImage class you are using. But if the getImage() method accepts an InputStream, you can use:
#Value("classpath:images/image.png")
private Resource resource;
And then:
InputStream inputStream = resource.getInputStream();
The following also should work:
ClassPathResource resource = new ClassPathResource("images/image.png");
InputStream inputStream = resource.getInputStream();

Executable JAR built with maven unable to find resources when loaded from static method

So I have a small resource loader for stuff that I need. The jar packages the resources but when I build the maven project, and all the dependencies work and resources folder is marked as resources, my images and scripts wont load.
Here is the code I am using:
...
public class ResourceLoader
{
public static ImageIcon getImageIconResource(String fileName) {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource("img/" + fileName).getFile());
return new ImageIcon(file.getPath());
}
public static File getScriptResource(String fileName) {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
return new File(classLoader.getResource("scripts/" + fileName).getFile());
}
}
The problem is not with maven itself. When you call
File.getPath
on File from the resource it points to a File, that is actually inside of your application archive. For most applications, this pose a problem because you cannot read file without extracting the archive. To correctly use resource file, you have to work with File, or you can call
ClassLoader.getResourcesAsStream
To adress ImageIcon
public static ImageIcon getImageIconResource(String fileName) {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
InputStream is = classLoader.getResourceAsStream("img/" + fileName);
Image image = ImageIO.read(is);
return new ImageIcon(image);
}
As for your getScriptResource method geting File object should work. But that depends, on how you will later use it. As I think you will need to read it anyway at some point I suggest using input stream as well.
public static InpoutStream getScriptResource(String fileName) {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
InputStream is = classLoader.getResourceAsStream("scripts/" + fileName);
return is;
}
Then, you can read the InputStream using many options that suits your need. For example, you can take a look at Apache Commons' IoUtils or handle it using ReaderApi
EDIT:
Because you have clarified how you will use your file I can see where is the problem with your scripts. You are starting another process outside of your application. In the first CLI param of python3, you are providing path to the file. As I wrote earlier - this is the problem, because python3 cannot read file inside of .jar file. First of all, I would have questioned your architecture. Do you really need to have script inside of .jar?
Anyway, one possible workaround may be storing contents of a script File in temporaryFile.
File tempFile = File.createTempFile("prefix-", "-suffix");
// e.g.: File tempFile = File.createTempFile("MyAppName-", ".tmp");
tempFile.deleteOnExit();
//get your script and prepare OutputStream to tempFile
// Try with resources, because you want to close your streams
try (InputStream is = ResourceLoader.getScriptResource(scriptName);
FileOutputStream out = new FileOutputStream(tempFile)) {
//NOTE: You can use any method to copy InputStream to OutputStream.
//Here I have used Apache IO Utils
IOUtils.copy(is, out);
}
boolean success = executePythonScriptWithArgs(tempFile, args);

NoSuchFileException uploading image into spring boot

I am wokring on spring boot, and i have created a folder web and images floders on this path : myApp/src/web/images
And when doing
private String saveFile(MultipartFile file, String fileName) throws IOException {
byte[] bytes = file.getBytes();
String imagePath = new String(this.servletContext.getRealPath(this.imagesPath) + "/" + fileName);
Path path = Paths.get(imagePath);
Files.write(path, bytes);
return imagePath;
}
i got this error :
java.nio.file.NoSuchFileException: /private/var/folders/4g/wd_lgz8970sfh64zm38lwfhw0000gn/T/tomcat-docbase.8255351399752894174.8098/images/IMG_2018-01-06 15:18:48.486.jpg
where i should put the images folder in order to upload files into it successfully.
Thanks for the help
You could save images into same /myapp/src/web/image/ directory using a fairly straightforward way.
the path in your application start in myapp directory you just need to chain the folow path /usr/web/images and using a FileOutputStream object to save there.
An example below.
private String saveFile(MultipartFile file,String filename) throws IOException{
final String imagePath = "src/web/images/"; //path
FileOutputStream output = new FileOutputStream(imagePath+filename);
output.write(file.getBytes());
return imagePath+filename;
}
Second Edit
if you want to get a image via GET request you can make a method that accept a Request Parameter with the name of the image and produces IMAGE CONTENT TYPE. something like that. (this sample work with a different types of images.)
#RequestMapping(value = "/show/",produces = MediaType.IMAGE_PNG_VALUE)
public #ResponseBody byte[] showImage(#RequestParam("image") String image) throws IOException{
final String imagePath = "src/web/images/";
FileInputStream input = new FileInputStream(imagePath+image);
return IOUtils.toByteArray(input);
}
I'm using apache common dependency to get byte array
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
i am working on spring boot, and i have created a folder web and
images folders on this path : myApp/src/web/images
and this exception :
java.nio.file.NoSuchFileException:
/private/var/folders/4g/wd_lgz8970sfh64zm38lwfhw0000gn/T/tomcat-docbase.8255351399752894174.8098/images/IMG_2018-01-06
15:18:48.486.jpg
At runtime the images folder created in the application source code will not be physically located in an images folder of the folder that hosts the application as this path : myApp/src/web/images is probably not considered by Spring Boot as the application is started.
In Spring Boot, you can access to static resources located in some specific folders such as static or public.
But I am not sure it will help you as you want to not only access to uploded files but also put content in the folder.
So I advise you to use another approach : put the images in a specific folder that is distinct of the application deployment folder.
Besides, generally, you want that the files be available after a shutdown/startup of the application.
So instead of using a relative path to the application to host the images :
myApp/src/web/images
use an absolute path (prefix with /) that is independently of the runtime folder of the application.

File location for unit testing

This is a very simple question which I cannot find a solution for. I have a quite complex Android app which uses the camera and does some manipulations to the images taken. I now want to write Unit tests for some of the functions but I cannot get a file loaded.
In an Android test project where should I paste the Image to test on and how can I load that image into a File object? I have a normal junit.framework.TestCase class that needs to send a File to an class to test on. Thanks in advance!
This may not be the best solution since it could bloat your project considerably. However, short of writing code to download an image in your test cases, I'm not sure what other approach there might be.
Simply, i have 'test' drawables in my resources and I load them as bitmaps, then store them somewhere on the disc to finally reference them in my tests. This is the code I use:
public File saveResourceImageToExternalStorage(Activity activity, String picFileName, int imageId)
{
Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), imageId);
File picFile = null;
OutputStream os = null;
try
{
picFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), picFileName);
picFile.createNewFile();
os = new FileOutputStream(picFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
}
catch (IOException e)
{
e.printStackTrace();
}
return file;
}
You'll probably want to make that method a little more robust.
Finally, you could just stash your test images in your assets folder for your project. Then you can get them from your assets folder using getAssets() in an Activity or using the path which should be something like file:///android_asset/your_file_name.jpg
EDIT
I think a better solution, after some research, would be to add your files to the assets of your test project and use InputStream input = this.getContext().getAssets().open("file.jpg");. You need to call this from a class that inherits from InstrumentationTestCase or, I suppose, ActivityInstrumentationTestCase2. You can then manipulate the input stream how you need

how to read image from project folder in java?

I am developing web method for webservice in java. In this web method I have to read image from my images folder which resides in my webservice project folder. I am using the code as follows.
#WebMethod(operationName = "getAddvertisementImage")
public Vector getAddvertisementImage()
{
Image image = null;
Vector imageList = new Vector();
try
{
File file = new File("E:/SBTS/SBTSWebservice/web/adv_btm.jpg");
image = ImageIO.read(file);
imageList.add(image);
}
catch (IOException e)
{
e.printStackTrace();
}
return imageList;
}
I am unable to read image from images folder.I am getting error image file "input file can't read" at image = ImageIO.read(file); how to resolve this issue ? Is there any mistake in my code or is there any other way to read image ? if there is any mistake in my code then can you proide me the code or link through which i can resolve the above issue.
Is the E:\ drive mapped on your web server? The Java compiler has no idea that you might access files outside of its scope and how it could tell your web server to map a network drive or a local hard disk which is attached to your development computer.
The solution is to put the image file into the same directory as the Java source file and then use
InputStream in = getClass().getResourceAsStream("adv_btm.jpg");
Check that your IDE (or whatever you use to build your application) does copy the image file in the same directory where it creates the .class file. Then it should work.

Categories

Resources