简体   繁体   中英

How to get an URL location from a server path for a property file

I need to pass the property file's URI to the following method (3rd party jar)

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

When I deploy my code on server, I get this path ie propertiesUrl.toURI() as abc://localhost/server/test/payment/ConfigLookup.properties

The 3rd party application refuses this value and doesn't create the configuration which is used to create a connection client.

A sample code where the property file is in my local bin folder works fine when passed on.

Path received as propertiesUrl.toURI()

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

The above creates a successful connection.

Kindly guide me on what's missing between them. How to make the server code work in similar fashion as the local code works.

Apparently that 3rd party JAR expects a local disk file system based URI. This is actually a mistake on their side. It's possible to obtain the contents via uri.toURL().openStream() without worrying about the context the URI is actually sitting in. The refusal of the value suggests that the 3rd party is using new FileInputStream(new File(uri)) for that. First and foremost, this should be reported on their side so they can properly fix it.

In the meanwhile, your best bet is to convert it to a local disk file system based URI instead offering a virtual file system or web based URI. You can do that by creating a temporary file with help of File#createTempFile() in container managed temporary folder, writing the contents to it and finally provide the temp file as URI.

Below example assumes that you're inside a servlet and thus have getServletContext() already at hands. Otherwise, the Java EE based framework you're using must have facility to give/inject you the 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());

That said, are you absolutely sure that this properties file shouldn't rather be placed in /WEB-INF folder? Right now it's publicly accessible to anyone in the world having a webbrowser. See also ao Where to place and how to read configuration resource files in servlet based application?

您可以通过类加载器获取资源,然后为文件获取URI,请参阅此处了解详细信息。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM