How to get URL location from server path for properties file

I need to pass the properties file URI to the following method (third-party jar)

defaultConfiguration = Factory.createDefaultConfiguration(propertiesUrl.toURI()); PayClient client = Factory.createClient(defaultConfiguration); 

When I deploy my code to the server, I get this path, that is, the Url.toURI () properties, like abc://localhost/server/test/payment/ConfigLookup.properties

The third-party application rejects this value and does not create the configuration that is used to create the connection client.

The sample code in which the properties file is located in my local bin folder works fine during transfer.

The path is obtained as propertiesUrl.toURI()

 file:/D:/Code/bin/ConfigLookup.properties 

The above creates a successful connection.

Preach to me what is missing between them. How to make server code work the same way local code works.

+6
source share
2 answers

Obviously, a third-party JAR expects a local URI based on the file system on disk. This is actually a mistake on their side. It is possible to retrieve content via uri.toURL().openStream() without worrying about the context the URI is sitting on. The rejection of the cost suggests that for this the third-party uses new FileInputStream(new File(uri)) . First of all, this should be reported on their side so that they can correctly fix it.

At the same time, it is best to convert it to a local URI based on the local file system instead of a virtual file system or web URI. This can be done by creating a temporary file using File#createTempFile() in a temporary folder managed by the container, entering the contents into it, and finally providing the temporary file as a URI.

The example below assumes that you are inside the servlet and thus have getServletContext() on hand. Otherwise, the Java EE environment you are using should be able to give / enter you a ServletContext .

 String tempDir = (String) getServletContext().getAttribute(ServletContext.TEMPDIR); File tempFile = File.createTempFile("temp-", ".properties", new File(tempDir)); Files.copy(propertiesUrl.openStream(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); // ... defaultConfiguration = Factory.createDefaultConfiguration(tempFile.toURI()); 

However, are you absolutely sure that this properties file should not be placed in the /WEB-INF folder? Right now, it is publicly available to anyone in the world with a web browser. See Also ao Where to place and how to read configuration resource files in a servlet application?

+1
source

You can get the resource through the classloader and then for the URI file, see here for details.

0
source

All Articles