Java application can't read file from Resources
My actions before raising this issue
- [x] Followed the troubleshooting guide
- [x] Read/searched the docs
- [x] Searched past issues
Expected Behaviour
I am currently experimenting with Openfaas and Java. I made a simple function to check the body of an HTTP call against a JSON schema.This JSON schema is read from the resources folder.
Current Behaviour
Once deployed on the openfaas environment in my kubernetes cluster it fails to read the file I get an error of the following type:
2019/07/05 12:40:13 stdout: 2019-07-05 12:40:13 ERROR Utils - Exception:
webhook-xxxxxxxxx-xxxxx:webhook java.io.FileNotFoundException: file:/home/app/entrypoint-1.0/lib/function-1.0.jar!/InputSchema.json (No such file or directory)
Context
The flow of my program:
- Openfaas receives an HTTP call with JSON body
- Load Input schema from Resources
- Check the body against the schema
- Returns status code 200 if correct or 400 if wrong
Your Environment
-
FaaS-CLI version: 0.8.19
-
Docker version: 18.09.6
-
Are you using Docker Swarm or Kubernetes (FaaS-netes)? Kubernetes
-
Operating System and version (e.g. Linux, Windows, MacOS): Linux
-
Code example or link to GitHub repo or gist to reproduce problem:
public static String readResource(String fileName) {
StringBuilder result = new StringBuilder();
//Get file from resources folder
ClassLoader classLoader = Utils.class.getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
System.out.println(result);
scanner.close();
} catch (IOException ex) {
log.error("Exception: ", ex);
}
return result.toString();
}
I'm moving this issue to the templates repo where the Java code exists.
See also: #86 by @ivanayov
@BTony95 : can you check if the resource is in the jar file ? kubectl exec into the container, unzip and check the file.
Also this might help: https://www.baeldung.com/java-classpath-resource-cannot-be-opened .
try (InputStream inputStream = getClass().getResourceAsStream("/input.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String contents = reader.lines()
.collect(Collectors.joining(System.lineSeparator()));
}
@BTony95 : can you check if the resource is in the jar file ? kubectl exec into the container, unzip and check the file.
Also this might help: https://www.baeldung.com/java-classpath-resource-cannot-be-opened .
try (InputStream inputStream = getClass().getResourceAsStream("/input.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String contents = reader.lines() .collect(Collectors.joining(System.lineSeparator())); }
best solution I come across, after struggling for many hours to make it work.