I have a method that has a few static classes as well as java.nio.Files,ResourceUtils, etc I am not sure how to write test cases for it as I keep getting NPE Paths.get(filePath);
Below is the method:
#Value("${file.path}")
private String filePath;
private List<MyJsonObj> readJSONFiles() throws IOException {
List<MyJsonObj> myJsonObjList = new ArrayList<>();
Gson gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
Path folder = Paths.get(filePath);
try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder)) {
for (Path entry : stream) {
String file = folder + "\\" + entry.getFileName().toString();
MyJsonObj jsonObj = gson.fromJson(new FileReader(ResourceUtils.getFile(file)), MyJsonObj.class);
myJsonObjList.add(jsonObj);
}
return myJsonObjList;
}catch (IOException e) {
logger.error(Arrays.asList(e.getStackTrace()).toString());
}
}
In my Eclipse project I have a "src" folder that's linked from a one drive folder.
I have some other text files in the linked folder that I want to load with a FileReader.
How would I get this location, optimally in a way that's agnostic to whether the folder is linked or actually in the project folder. I've tried using
MyClass.class.getResource("");
But it returns me a path to the "bin" folder. I'm probably not using it right. The file I want to get is "src/de/lauch/engine/shaders/primitiveTestShader/vertexShader.vsh"
Thanks in advance!
You can create resources folder like that 'src\main\resources' and put the file after that you can run your same code . hopefully it will work.
I solved my particular issue for now but im still open to better solutions :)
public class LinkedResourceLocator {
private static Dictionary<String,String> locations;
public static String getPath(String path) {
if(locations==null) {
File projectLocal = new File(LinkedResourceLocator.class.getClassLoader().getResource("").getPath().replaceAll("%20", " ")).getParentFile();
File dotProject = new File(projectLocal.getAbsolutePath()+"\\.project");
locations = new Hashtable<String,String>();
File[] files = projectLocal.listFiles(new FileFilter(){
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (int i = 0; i < files.length; i++) {
locations.put(files[i].getName(), files[i].getAbsolutePath());
}
try {
BufferedReader br = new BufferedReader(new FileReader(dotProject));
StringBuilder fileContentBuilder = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
fileContentBuilder.append(line.trim());
}
String fileContents = fileContentBuilder.toString();
Pattern p = Pattern.compile("<link><name>(\\w*)</name><type>\\d*</type><location>([\\w/:]*)</location></link>");
Matcher m = p.matcher(fileContents);
while(m.find()) {
locations.put(m.group(1),m.group(2));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("Can't locate .project file");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Can't read .project file");
}
}
String locator = path.contains("/")?path.substring(0, path.indexOf("/")):path;
String restPath = path.substring(locator.length());
return locations.get(locator)+restPath;
}
}
This class gets the linked resource locations from the eclipse .project file and then converts project local paths like "src/de/lauch/engine/shaders/primitiveTestShader/vertexShader.vsh" to these linked locations.
I'm wondering how I can create a new file with an existing emf resource. At the moment I've the following code in my org.eclipse.ui.menus DefaultHandler, which get me the existing emf resource and create a new (empty) file:
if (element instanceof IResource) {
IResource pldFile = (IResource) element;
String path = pldFile.getLocation().toString();
URI uri = URI.createFileURI(path);
// Obtain a new resource set
ResourceSet resSet = new ResourceSetImpl();
// Get the existing resource
Resource emfResource = resSet.getResource(uri, true);
IProject project = pldFile.getProject();
String fileName = pldFile.getName().replace(pldFile.getFileExtension(), "plc");
IFile plcFile = project.getFile(new Path(fileName));
byte[] bytes = "".getBytes();
try {
InputStream source = new ByteArrayInputStream(bytes);
if (plcFile.exists()) {
int i = 1;
String tmp = "";
do {
tmp = fileName;
int index = tmp.indexOf(".plc");
tmp = tmp.substring(0, index) + i + tmp.substring(index, tmp.length());
plcFile = project.getFile(new Path(tmp));
i++;
} while (plcFile.exists());
plcFile.create(source, IResource.NONE, null);
} else {
plcFile.create(source, IResource.NONE, null);
}
PlcEditorInput input = new PlcEditorInput(emfResource);
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IDE.openEditor(page, plcFile);
} catch (CoreException e) {
e.printStackTrace();
}
How can I assign now the existing emf resource to my newly created file?
Cheers,
Phil
I'm not sure but try to import the resource as new file. I mean define a new file or project and then import the resource.
To be honestly I try a similary way but it didn't work with my resource(--> it's a 10-years-old-code).
I need to read class names(just the simple name) from a jar file(OSGified). I've placed the jar file in the lib folder and it's added to class path. Here is the code I've written:
public void loadClassName() throws IOException {
JarFile jf = new JarFile("/lib/xxxx-1.0.0.jar");
List<String> list = new ArrayList<String>();
for (JarEntry entry : Collections.list(jf.entries())) {
if (entry.getName().endsWith(".class")) {
String className = entry.getName().replace("/", ".").replace(".class", "");
list.add(className);
}
}
}
Somehow, I"m getting Filenotfound exception while constructing the jarfile object. Can somebody let me know how we should give the jar path to the JarFile constructor ?
try this:
JarFile jf = new JarFile("lib/xxxx-1.0.0.jar");
Thanks to the user #Perception. His answer has worked flawlessly.
This is the working code:
final InputStream jarStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lib/xxxxx-1.0.0.jar");
JarInputStream jfs = new JarInputStream(jarStream);
List<String> list = new ArrayList<String>();
JarEntry je = null;
while (true) {
je = jfs.getNextJarEntry();
if (je == null) {
break;
}
if (je.getName().endsWith(".class")) {
String className = je.getName().replace("/", ".").replace(".class", "");
list.add(className);
}
}
I have a file called mybundle.txt in c:/temp -
c:/temp/mybundle.txt
How do I load this file into a java.util.ResourceBundle? The file is a valid resource bundle.
This does not seem to work:
java.net.URL resourceURL = null;
String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);
try {
resourceURL = fl.toURI().toURL();
} catch (MalformedURLException e) {
}
URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle( path ,
java.util.Locale.getDefault(), urlLoader );
As long as you name your resource bundle files correctly (with a .properties extension), then this works:
File file = new File("C:\\temp");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("myResource", Locale.getDefault(), loader);
where "c:\temp" is the external folder (NOT on the classpath) holding the property files, and "myResource" relates to myResource.properties, myResource_fr_FR.properties, etc.
Credit to http://www.coderanch.com/t/432762/java/java/absolute-path-bundle-file
When you say it's "a valid resource bundle" - is it a property resource bundle? If so, the simplest way of loading it probably:
try (FileInputStream fis = new FileInputStream("c:/temp/mybundle.txt")) {
return new PropertyResourceBundle(fis);
}
1) Change the extension to properties (ex. mybundle.properties.)
2) Put your file into a jar and add it to your classpath.
3) Access the properties using this code:
ResourceBundle rb = ResourceBundle.getBundle("mybundle");
String propertyValue = rb.getString("key");
From the JavaDocs for ResourceBundle.getBundle(String baseName):
baseName - the base name of the
resource bundle, a fully qualified
class name
What this means in plain English is that the resource bundle must be on the classpath and that baseName should be the package containing the bundle plus the bundle name, mybundle in your case.
Leave off the extension and any locale that forms part of the bundle name, the JVM will sort that for you according to default locale - see the docs on java.util.ResourceBundle for more info.
For JSF Application
To get resource bundle prop files from a given file path to use them in a JSF app.
Set the bundle with URLClassLoader for a class that extends
ResourceBundle to load the bundle from the file path.
Specify the class at basename property of loadBundle tag.
<f:loadBundle basename="Message" var="msg" />
For basic implementation of extended RB please see the sample at Sample Customized Resource Bundle
/* Create this class to make it base class for Loading Bundle for JSF apps */
public class Message extends ResourceBundle {
public Messages (){
File file = new File("D:\\properties\\i18n");
ClassLoader loader=null;
try {
URL[] urls = {file.toURI().toURL()};
loader = new URLClassLoader(urls);
ResourceBundle bundle = getBundle("message", FacesContext.getCurrentInstance().getViewRoot().getLocale(), loader);
setParent(bundle);
} catch (MalformedURLException ex) { }
}
.
.
.
}
Otherwise, get the bundle from getBundle method but locale from others source like Locale.getDefault(), the new (RB)class may not require in this case.
If, like me, you actually wanted to load .properties files from your filesystem instead of the classpath, but otherwise keep all the smarts related to lookup, then do the following:
Create a subclass of java.util.ResourceBundle.Control
Override the newBundle() method
In this silly example, I assume you have a folder at C:\temp which contains a flat list of ".properties" files:
public class MyControl extends Control {
#Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
if (!format.equals("java.properties")) {
return null;
}
String bundleName = toBundleName(baseName, locale);
ResourceBundle bundle = null;
// A simple loading approach which ditches the package
// NOTE! This will require all your resource bundles to be uniquely named!
int lastPeriod = bundleName.lastIndexOf('.');
if (lastPeriod != -1) {
bundleName = bundleName.substring(lastPeriod + 1);
}
InputStreamReader reader = null;
FileInputStream fis = null;
try {
File file = new File("C:\\temp\\mybundles", bundleName);
if (file.isFile()) { // Also checks for existance
fis = new FileInputStream(file);
reader = new InputStreamReader(fis, Charset.forName("UTF-8"));
bundle = new PropertyResourceBundle(reader);
}
} finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(fis);
}
return bundle;
}
}
Note also that this supports UTF-8, which I believe isn't supported by default otherwise.
This worked for me very well. And it doesn't reload the bundle everytime. I tried to take some stats to load and reload the bundle from external file location.
File file = new File("C:\\temp");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("myResource", Locale.getDefault(), loader);
where "c:\temp" is the external folder (NOT on the classpath) holding the property files, and "myResource" relates to myResource.properties, myResource_fr_FR.properties, etc.
Note: If you have the same bundle name on your classpath then it will be picked up by default using this constructor of URLClassLoader.
Credit to http://www.coderanch.com/t/432762/java/java/absolute-path-bundle-file
Find some of the stats below, all time in ms.
I am not worried about the initial load time as that could be something with my workspace or code that I am trying to figure out but what I am trying to show is the reload took way lesser telling me its coming from memory.
Here some of the stats:
Initial Locale_1 load took 3486
Reload Locale_1 took 24
Reload Locale_1 took 23
Reload Locale_1 took 22
Reload Locale_1 took 15
Initial Locale_2 load took 870
Reload Locale_2 took 22
Reload Locale_2 took 18
Initial Locale_3 load took 2298
Reload Locale_3 took 8
Reload Locale_3 took 4
I would prefer to use the resourceboundle class to load the properties - just to get it done in one line instead of 5 lines code through stream, Properties class and load().
FYI ....
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
try {
/*** Type1 */
Properties props = new Properties();
String fileName = getServletContext().getRealPath("WEB-INF/classes/com/test/my.properties");
// stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
// stream = ClassLoader.getSystemResourceAsStream("WEB-INF/class/com/test/my.properties");
InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/classes/com/test/my.properties");
// props.load(new FileInputStream(fileName));
props.load(stream);
stream.close();
Iterator keyIterator = props.keySet().iterator();
while(keyIterator.hasNext()) {
String key = (String) keyIterator.next();
String value = (String) props.getProperty(key);
System.out.println("key:" + key + " value: " + value);
}
/*** Type2: */
// Just get it done in one line by rb instead of 5 lines to load the properties
// WEB-INF/classes/com/test/my.properties file
// ResourceBundle rb = ResourceBundle.getBundle("com.test.my", Locale.ENGLISH, getClass().getClassLoader());
ResourceBundle rb = ResourceBundle.getBundle("com.ibm.multitool.customerlogs.ui.nl.redirect");
Enumeration<String> keys = rb.getKeys();
while(keys.hasMoreElements()) {
String key = keys.nextElement();
System.out.println(key + " - " + rb.getObject(key));
}
} catch (IOException e) {
e.printStackTrace();
throw new ServletException("Error loading config.", e);
} catch (Exception e) {
e.printStackTrace();
throw new ServletException("Error loading config.", e);
}
}
I think that you want the file's parent to be on the classpath, not the actual file itself.
Try this (may need some tweaking):
String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);
try {
resourceURL = fl.getParentFile().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("mybundle.txt",
java.util.Locale.getDefault(), urlLoader );
The file name should have .properties extension and the base directory should be in classpath. Otherwise it can also be in a jar which is in classpath
Relative to the directory in classpath the resource bundle can be specified with / or . separator. "." is preferred.
If you wanted to load message files for different languages, just use the
shared.loader=
of catalina.properties...
for more info, visit http://theswarmintelligence.blogspot.com/2012/08/use-resource-bundle-messages-files-out.html
This works for me:
File f = new File("some.properties");
Properties props = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
props.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
fis = null;
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
public class One {
private static One one = null;
Map<String, String> configParameter = Collections.synchronizedMap(new HashMap<String, String>());
private One() {
ResourceBundle rb = ResourceBundle.getBundle("System", Locale.getDefault());
Enumeration en = rb.getKeys();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = rb.getString(key);
configParameter.put(key, value);
}
}
public static One getInstance() {
if (one == null) {
one= new One();
}
return one;
}
public Map<String, String> getParameter() {
return configParameter;
}
public static void main(String[] args) {
String string = One.getInstance().getParameter().get("subin");
System.out.println(string);
}
}
ResourceBundle rb = ResourceBundle.getBundle("service"); //service.properties
System.out.println(rb.getString("server.dns")); //server.dns=http://....