I have a Spring Boot application that provides Open API specification by /api/open-api/v3 path. The idea is that I request the Open API JSON during test running and then write its content to the file in build folder. So, I could parse it later and generate documentation. I tried to do it like this:
Files.writeString(Path.of("src", "test", "resources", "open-api.json"), res.getBody());
It did write the the file to the src/test/resources folder but in the source code module itself. Not the result build folder. Is it possible to overcome this issue?
#Test
#DisplayName("Create a file on the build diretory")
void createFileOnBuildDir() throws IOException {
final URL buildRoot = getClass().getResource("/");
final Path jsonFile = Path.of(buildRoot.getPath(), "open-api.json");
Files.writeString(jsonFile, "{\"value\": 123}");
System.out.println(jsonFile);
}
result
/home/myuser/projects/testproject/build/classes/java/test/open-api.json
$ cat /home/myuser/projects/testproject/build/classes/java/test/open-api.json
{"value": 123}
But, I guess the best answer for your need is https://github.com/Swagger2Markup/spring-swagger2markup-demo project's https://github.com/Swagger2Markup/spring-swagger2markup-demo/blob/master/src/test/java/io/github/robwin/swagger2markup/petstore/Swagger2MarkupTest.java
Related
I have a spring application, and i'm trying to access a json file with the following code :
try (FileReader reader = new FileReader("parameters.json")) {
Object obj = jsonParser.parse(reader);
parameterList = (JSONArray) obj;
}
I have put the parameter.json file in the project folder and I'm accesing the file data from an angular app through a rest api, and that works fine when I run the application on local machine, but when I deploy the war file on tomcat, my application can't load the file, should I put parameter.json file somewhere else on tomcat or what is the best solution for it.
Your question states you are attempting to access a file called parameter.json, while your code excerpt shows parameters.json. Perhaps that discrepancy indicates a typo in your source code?
If not, there are various ways to access a file from the classpath in Spring, with the first step for each being to ensure the file is in the project's src/main/resources directory.
You can then use one of the Spring utility classes ClassPathResource, ResourceLoader or ResourceUtils to get to the file. The easiest approach, though, may be to put your properties in a .properties file (default file name application.properties) and access the values using Spring's #Value annotation:
#Value("${some.value.in.the.file}")
private String myValue;
You can use other file names as well by utilizing #PropertySource:
#Configuration
#PropertySource(value = {"classpath:application.properties",
"classpath:other.properties"})
public class MyClass {
#Value("${some.value.in.the.file}")
private String myValue;
...
}
Make sure your parameters.josn filename is exactly same in the code.
Move you parameters.json file in the resources folder and then use the classpath with the filename.
try (FileReader reader = new FileReader("classpath:parameters.json")) {
Object obj = jsonParser.parse(reader);
parameterList = (JSONArray) obj;
}
Try to put the file under resources folder in your spring project. You should be able to access the file from that location.
FileReader is looking for a full-fledged file system like the one on your computer, but when your WAR is deployed, there just isn't one, so you have to use a different approach. You can grab your file directly from your src/main/resources folder like this
InputStream inputStream = getClass().getResourceAsStream("/parameters.json");
I have a Java-only module in my Android project. In that project I want to have a unit test that reads the contents from a local json file that is stored in the resources folder. Android Studio changes the icon of the resources folder, so I'd think it recognises it as the resources folder.
How I'm reading:
String json = Files.lines(Paths.get("file.json"))
.parallel()
.collect(Collectors.joining());
folder structure:
+project
+app (android)
+module (java only)
+src
+main
+java
+package
-the java file
+resources
-file.json
My question is how can I read the file?
updated below
URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");
All these are null.
I've copied the json file to resources/same.package.structure too, but to no success.
Don't need to do all this complicated stuff with ClassLoaders. You have access to test/resources directory from you /test/* classes.
UPD
This is how to deserialize file using its path using SimpleXML. So here source method param is your path to resource file
you should using Paths.get(URI) instead, for example:
ClassLoader loader = ClassLoader.getSystemClassLoader();
String json = Files.lines(Paths.get(loader.getResource("file.json").toURI()))
.parallel()
.collect(Collectors.joining());
this is because you run your tests in android platform, and the resoruces were packaged in a jar, please using BufferedReader.lines instead, for example:
ClassLoader loader = activity.getClassLoader();
BufferedReader in = new BufferedReader(new InputStreamReader(
loader.getResourceAsStream("file.json"),"UTF-8"
));
String json = in.lines()
.parallel()
.collect(Collectors.joining());
Apparently it was a bug, should be fixed now:
https://issuetracker.google.com/issues/63612779
Thank you all for your help
I need to run a web-app on Tomcat, but it cannot read the txt files(from a relative paths as below) on Tomcat. However, it does work if I use a full path.
So I am wondering where can I put these txt files so that when Tomcat started, the app can successfully read the txt files from a relative path.
Currently, the project structure is as follows, the txt files is located on the same directory as src file in Project Explorer in Eclipse.
Project_Name
src
java files
EDGES.txt
NODES.txt
The code is as follows, I am appreciated if someone can give me an answer in details, since I am quite new to Java.
The code is as follows:
public class RouteingDao {
NodeJSONReader nodeInput = new NodeJSONReader("NODES.txt");
EdgeJSONReader edgeInput = new EdgeJSONReader("EDGES.txt");
...
}
The NodeJSONReader/EdgeJSONReader class is as follows:
public class EdgeJSONReader {
private EdgeEntity[] edgeEntity;
// constructor
public EdgeJSONReader(String JSON_FILE) {
edgeEntity = readEntityFromFile(JSON_FILE);
}
// load the JSON data from local file
public EdgeEntity[] readEntityFromFile(String JSON_FILE) {
try {
Reader reader = new FileReader(JSON_FILE);
Gson gson = new Gson();
edgeEntity = gson.fromJson(reader, EdgeEntity[].class);
}
...
}
}
If you are using a servlet, then access the servlet context and the getRealPath method.
this.getServletContext().getRealPath("WEB-INF/nodes.txt")
The relative path sent to getRealPath will be expanded to the location of the files for your web app. You can add any path you like, even to a hidden file in WEB-INF.
From a JSP you can use
${pageContext.servletContext.getRealPath("WEB-INF/nodes.txt")}
Be careful, this will be in the build directory, so any changes to nodes.txt will not be saved to the original file.
Play 2.2.3. Windows 7.
public static Result menu() throws IOException {
String path = Play.application().resource("resources/menu.json").toString();
String content = Files.toString(new File(path), Charsets.UTF_8);
return ok(content).as("JSON");
}
Got an error:
... scala-2.10\classes\resources\menu.json The filename, directory
name, or volume label syntax is incorrect
Checking that path in file-system, I'm able to find my file there:
..\target\scala-2.10\classes\resources\menu.json
I'm able to find it there. Why play can't?
--
UPDATE:
I've just figured out I can not create files on C:\ root folder on my machine. That maybe the issue. But on other hand I'm not accessing root folder, and ad trying to get read only access. And I do have write access to that file on that path anyway.
As actually you want to use your menu.json file as a static asset you can put it i.e. into public/resources/menu.json file and then read it with simple:
<script>
$.get('#routes.Assets.at("resources/menu.json")');
</script>
or just directly by request:
http://localhost:9000/assets/resources/menu.json
To do what you want via controller you need to read the InputStream by classpath (remember that finally it will be archived into jar file!) but it need to be placed in conf folder i.e.: conf/resources/menu.json then from controller:
public static Result menuViaControllerJson() {
InputStream is = Play.application().classloader().getResourceAsStream("resources/menu.json");
return (is != null)
? ok(is)
: notFound();
}
Anyway you will get exactly the same result as for common Assets.at, so consider if it's worth of effort.
Edit: If you want to use this file as custom config just use HOCON syntax file i.e.: conf/ses.conf:
foo = "bar"
and in controller:
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
....
Config cfg = ConfigFactory.parseResources(Play.application().classloader(), "ses.conf");
debug("My 'foo' is configured as: " + cfg.getString("foo"));
my project struture looks like
project/
src/main/
java/ ...
resources/
definitions.txt
test/
CurrentTest.java
resources/ ...
In my test I need to open the definitions.txt
I do
#Test
public void testReadDesiredDefinitions() throws PersistenceException, IOException {
final Properties definitions = new Properties();
definitions.load(new ResourceService("/").getStream("desiredDefinitions"));
System.out.println(definitions);
}
When I run this, I get
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
How can I read this text file?
Thanks
The "current directory" of unit tests is usually the project directory, so use this:
File file = new File("src/main/resources/definitions.txt");
and load the properties from the file:
definitions.load(new FileInputStream(file));
If this doesn't work, or you want to check what the current directory is, just print out the path and it will be obvious what the current directory is:
System.out.println(file.getAbsolutePath());
You can make use of Class#getResourceAsStream to easily create a stream to a resource file.
definitions.load(getClass().getResourceAsStream("/main/java/resources/definitions.txt"));
The location parameter should be the relative file path with regards to your project base (my guess was main).
If your resources directory is a source folder, you can use /resources/definitions.txt as a correct path.
I don't know about ResourceService but this should work:
final Properties definitions = new Properties();
definitions.load(getClass().getResourceAsStream("/resources/definitions.txt"))
File file = new File("../src/main/resources/definitions.txt");