Obviously ResourceBundle requires a property file like syntax in the files it finds.
We have a situation where we want to use entire files (in our case HTML-files) as "values". This means that we don't have keys as such. Well, maybe the filename would work as the key.
Here's a directory tree:
src/
main/
resources/
html/
content.html
content_de.html
content_fr.html
content_es.html
order.html
order_de.html
order_fr.html
order_es.html
Now we need logic to find the correct file based on the current locale. If the current locale is German and I'm looking for html/content.html file, it should find html/content_de.html. It doesn't necessarily need to load it right away. Is there some existing mechanism in Java? Do we need to do this manually?
Due to some restrictions, we are currently planning to not use any third-party libraries. So if there is something available in Java 6 SE, it would be our best choice; however, if you know of a third-party library, feel free to name it.
EDIT #1:
An obvious solution would be to have a key in messages.properties to name that HTML-file. While that would work it may become a pain in the butt on the long run (and besides that I don't think this would solve all our issues with this).
EDIT #2: I forgot to say that this is a desktop application.
To make this more ideal, if your naming convention for your files remains consistent (i.e. for each locale, you use the two-letter prefix of the language - meaning 'en' for English, 'fr' for French, and 'es' for Spanish), then this process is extremely straightforward.
We will make use of the Properties class to read the properties in, then use MessageFormat to format the appropriate locale we want from the resultant property.
First, we make a change to the property file - we parameterize it such that we are able to pass in whatever we like.
content=content_{0}.html
order=order_{0}.html
The {0} represents the first parameter to the property.
Now, we only need to load the property in, and pass in the appropriate parameter.
Properties prop = new Properties();
try {
MessageFormat messageFormat = new MessageFormat("");
String property;
// change to suit the locale you wish to serve
String[] param = {"en"};
prop.load(new FileReader(new File("/full/path/to/property/file.properties")));
property = prop.getProperty("content");
messageFormat.applyPattern(property);
System.out.println(messageFormat.format(param));
} catch(IOException ioex) {
System.out.println("no property file here");
}
This prints out:
content_en.html
Ensure that the HTML file you want to access exists before making this call, or turn this into a function which returns String, and ensure that the file exists before it's returned.
To show that I wasn't doing nothing, here are two attempts using an "on our own"-approach:
The first attempt with locale-postfix build up and straight forward loading of resources:
public void attempt1(String baseName, String extension) {
List<String> locales = buildLocaleStrings(Locale.getDefault());
String resourceFound = null;
for (String locale : locales) {
String resourceName = baseName + locale + "." + extension;
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
resourceFound = resourceName;
break;
}
}
System.out.println("found #1: " + resourceFound);
}
private List<String> buildLocaleStrings(Locale localeBase) {
String locale = "_" + localeBase;
List<String> locales = new ArrayList<String>();
while (locale.length() > 0) {
locales.add(locale);
locale = locale.replaceFirst("_[^_]*?$", "");
}
locales.add("");
return locales;
}
The second attempt "abusing" ResourceBundle and its toString():
public void attempt2(String baseName, final String extension) {
ResourceBundle.Control control = new ResourceBundle.Control() {
private String resourceFound = null;
#Override
public List<String> getFormats(String baseName) {
return Arrays.asList(extension);
}
#Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, format);
if (loader.getResource(resourceName) != null) {
resourceFound = resourceName;
return new ResourceBundle() {
#Override
public Enumeration<String> getKeys() {
return null;
}
#Override
protected Object handleGetObject(String key) {
return null;
}
};
}
return null;
}
#Override
public String toString() {
return resourceFound;
}
};
ResourceBundle.getBundle(baseName, control);
System.out.println("found #2: " + control.toString());
}
Sample calls:
public void proof() {
attempt1("html/content", "html");
attempt2("html/content", "html");
}
Both find the same file.
To be honest, I don't like neither.
I know this is an old question but I just came across the exact same problem and I found a more elegant solution. What you need is to delegate locale to file mapping to the standard Java API the same way the API solves translations for keys. So in your example, if the current locale is fr_FR you want to load the files called "content_fr.html" and "order_fr.html", right?
Then simply have a set of resource bundle files and designate a variable to translate the current locale to the closest existing locale:
File translation.properties:
localeCode =
File translation_fr.properties:
localeCode = fr
File translation_en.properties:
localeCode = en
Then you just need to read the value of "localeCode" and concatenate it with "content" and ".html" or "order" and ".html".
Related
I've made a class which takes in any string of one format (eg. UNIX) and coverts into whatever OS the java is running on.
enum OperatingSystem {
WINDOWS,
LINUX;
static OperatingSystem initOS() {
String osName = System.getProperty("os.name");
switch (osName) {
case "Windows 8.1":
return WINDOWS;
case "Linux":
return LINUX;
default:
return LINUX;
}
}
}
public class OSSP {
public static final OperatingSystem USEROS = OperatingSystem.initOS();
// Auxilarry methods to return OSAppropriateString
private static String makeLinuxCompatible(String[] path) {
return String.join("/", path);
}
private static String makeWindowsCompatible(String[] path) {
return String.join("\\", path);
}
public static String getOSSpecificPath(String path) {
String[] splittedPath = {""}, subpath = {""};
String finalPath = "";
if(path.contains("\\")) {
splittedPath = path.split("\\\\",-1);
}
else if (path.contains("/")) {
splittedPath = path.split("/",-1);
}
if (USEROS == OperatingSystem.LINUX) {
finalPath = makeLinuxCompatible(splittedPath);
}
else if (USEROS == OperatingSystem.WINDOWS) {
finalPath = makeWindowsCompatible(splittedPath);
}
return finalPath;
}
}
This is fine if you're working on small code and you'd have to do it often.
But, I have a huge GUI code where I'd have to insert this function wherever there is path specified in the program. Is there a way to make path like strings automatically OS specific?
Otherwise a setting where any OS function which takes a path automatically changes accordingly under the hood.
Use Path with Files.
Path path = Paths.get(".../...");
Path path = Paths.get("...", "...");
// path.resolve, relativize, normalize, getFileSystem
This class is a generalisation of File which is only for pure file system files.
A path might point in a subdirectory of a .zip using a zip file system and so on.
For established File using APIs one can use Path.toFile() and File.toPath().
Paths.get is very versatile, also due to the Posix compatibility of Windows (accepting / besides \). You can get a canonical normalized path anyway.
path.toRealPath()
The old File you can use:
String separator = File.separator;
For a path which can point to different file systems:
String separator = path.getFileSystem().getSeparator();
In general Path is a nifty class storing the name parts, the file system.
It covers many aspects like "..".
The best way to deal with this kind of situation is to not try to detect the OS since that can be rather hit-or-miss. Instead the Java API does provide a way to tell you what character to use as a path separator. Look at this API documentation on File: https://docs.oracle.com/javase/8/docs/api/java/io/File.html and look for the specific static field separator. I would highly suggest you parse the path using the File class then if you need the path as an string simply call toURI().toString() to get it into a format that the OS can recognize.
I have built a program, which takes in a provided ".class" file and parses it using the BCEL, I've learnt how to calculate the LCOM4 value now. Now I would like to know how to calculate the CBO(Coupling between object) value of the class file. I've scoured the whole web, trying to find a proper tutorial about it, but I've been unable so far (I've read the whole javadoc regarding the BCEL as well and there was a similar question on stackoverflow but it has been removed). So I would like some help with this issue, as in some detailed tutorials or code snippets that would help me understand on how to do it.
OK, here you must compute the CBO of the classes within a whole set of classes. The set can be the content of a directory, of a jar file, or all the classes in a classpath.
I would fill a Map<String,Set<String>> with the class name as the key, and the classes it refers to:
private void addClassReferees(File file, Map<String, Set<String>> refMap)
throws IOException {
try (InputStream in = new FileInputStream(file)) {
ClassParser parser = new ClassParser(in, file.getName());
JavaClass clazz = parser.parse();
String className = clazz.getClassName();
Set<String> referees = new HashSet<>();
ConstantPoolGen cp = new ConstantPoolGen(clazz.getConstantPool());
for (Method method: clazz.getMethods()) {
Code code = method.getCode();
InstructionList instrs = new InstructionList(code.getCode());
for (InstructionHandle ih: instrs) {
Instruction instr = ih.getInstruction();
if (instr instanceof FieldOrMethod) {
FieldOrMethod ref = (FieldInstruction)instr;
String cn = ref.getClassName(cp);
if (!cn.equals(className)) {
referees.add(cn);
}
}
}
}
refMap.put(className, referees);
}
}
When you've added all the classes in the map, you need to filter the referees of each class to limit them to the set of classes considered, and add the backward links:
Set<String> classes = new TreeSet<>(refMap.keySet());
for (String className: classes) {
Set<String> others = refMap.get(className);
others.retainAll(classes);
for (String other: others) {
refMap.get(other).add(className);
}
}
i have multiple xml files named media01.xml, media02.xml and so on.
I have written one java code which parses this xml file and fetches its table name and renames xml file. eg: media01--> Records.xml, media02 --> Info.xml and so on.
Part of that code is as follows:
File inputFile = new File(path+File.separator+"media0"+xmlval+".xml");
if(inputFile.exists())
{
try{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
aaaa a= new aaaa();
saxParser.parse(inputFile, a);
String abc = aaaa.nsList();
File dest = new File(path+File.separator+abc+".xml");
inputFile.renameTo(dest);
xmlval++;
}
catch(Exception e)
{
System.err.println(""+e);
}
}
and the function which i am calling is:
class aaaa extends DefaultHandler {
boolean bFirstName = false;
boolean bLastName = false;
boolean loc = false;
String name = null;
static String ans;
#Override
public void startElement(String uri,String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("table")) {
name = attributes.getValue("name");
}
if(qName.equalsIgnoreCase("row")){
}
ans=name;
}
public static String nsList(){
return ans;
}
}
i deployed my project on server and when i run the project from ubuntu OS then the xml file names are getting changed but the same when i am running from windows then its not renaming the files. what might be the issue?
Pls help me out. Thanks in advance.
i don't thin it is a Parser problem since there is no problem and SAXParser is used by so many projects that depend on SAX to parse their configuration file such as Spring , jsf i think and so many others so it is unlikely to be a saxproblem so the problem can be i your call to
File dest = new File(path+File.separator+abc+".xml");
inputFile.renameTo(dest);
which is platform dependent instruction you better check if the renaming was done successfully by doing like this
File dest = new File(path+File.separator+abc+".xml");
boolean renameSuccess=inputFile.renameTo(dest);
System.out.println("renaming "+renameSuccess?"succeeded":"failed");
One of the problems I could encounter when deploying an application tested on a system to another system is that path and file names are case sensitive on Unix-like system. It is possible that your file already existed on your target system but with a different case. Anyway, as achabahe mentioned it, you should check your return value when you rename a file.
Another remark, path separators are system dependent but generally Java doesn't make any problem. You can for example use '/' in a Windows path. I just would suggest you to instantiate File objects this way:
File myFile = new File(myPath, myFileName);
This is so easier to read and system-independent.
I also suggest you to trace if you actually open the source file. By the way can't you run it in debug mode?
I have a resource file (.properties file) which is having thai characters.
When I read that file using the below code it is showing junk characters like "?"
package RD1.Common;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
public class LabelManagerRD {
public static String[] getLabel(String ParamString1)
{
String NextEle = "";
String str2 = ParamString1;
int i = 1;
String Final[] = new String[1000];
ResourceBundle bundle =
ResourceBundle.getBundle("rd", Locale.US);
Enumeration<String> enumeration = bundle.getKeys();
while (enumeration.hasMoreElements())
{
NextEle = enumeration.nextElement();
if (NextEle.toLowerCase().contains(str2.toLowerCase()))
{
Final[i] = NextEle+"="+bundle.getString(NextEle);
i++;
}
}
return Final;
}
public static void main(String[] args)
{
try
{
String TestValue[] = getLabel("RD.RDRAPCEX");
for(int i=1;i<=TestValue.length;i++)
{
if (!(TestValue[i].length()==0))
{
System.out.println(i+" - "+TestValue[i]);
}
}
}
catch (Exception e)
{
}
}
}
And properties file (rd_en_US.properties) is like below
BL_BLNG_GROUP.BL_BLNG_GRP.BLNG_GRP_ID.IP=รสสรืเ เพนีย รก~^PAGE_1~^Y~^N
BL_BLNG_GROUP.BL_BLNG_GRP.LONG_DESC.IP=Long Desc~^PAGE_1~^Y~^N
BL_BLNG_GROUP.BL_BLNG_GRP.SHORT_DESC.IP=Short Desc~^PAGE_1~^Y~^N
BL_BLNG_GROUP.BL_BLNG_GRP.DETAIL_DESC.IP=Explanatory Note~^PAGE_1~^Y~^N
Please suggest how to proceed with this.
Thanks in advance,
Sandy
If encoding of your file is corrent then you must note that System.out will not be able to print the UTF-8 characters with default console settings. Make sure the console you use to display the output is also encoded in UTF-8.
In Eclipse for example, you need to go to Run Configuration > Common to do this.
Property files are typically interpreted in ISO 8859-1 encoding. If you need other characters not included in this set use unicode escapes like \uxxxx. There are also tools available to convert property files with different encoding to this one (see native2ascii).
Does any one know of any Java libraries I could use to generate canonical paths (basically remove back-references).
I need something that will do the following:
Raw Path -> Canonical Path
/../foo/ -> /foo
/foo/ -> /foo
/../../../ -> /
/./foo/./ -> /foo
//foo//bar -> /foo/bar
//foo/../bar -> /bar
etc...
At the moment I lazily rely on using:
new File("/", path).getCanonicalPath();
But this resolves the path against the actual file system, and is synchronised.
java.lang.Thread.State: BLOCKED (on object monitor)
at java.io.ExpiringCache.get(ExpiringCache.java:55)
- waiting to lock <0x93a0d180> (a java.io.ExpiringCache)
at java.io.UnixFileSystem.canonicalize(UnixFileSystem.java:137)
at java.io.File.getCanonicalPath(File.java:559)
The paths that I am canonicalising do not exist on my file system, so just the logic of the method will do me fine, thus not requiring any synchronisation. I'm hoping for a well tested library rather than having to write my own.
I think you can use the URI class to do this; e.g. if the path contains no characters that need escaping in a URI path component, you can do this.
String normalized = new URI(path).normalize().getPath();
If the path contains (or might contain) characters that need escaping, the multi-argument constructors will escape the path argument, and you can provide null for the other arguments.
Notes:
The above normalizes a file path by treating it as a relative URI. If you want to normalize an entire URI ... including the (optional) scheme, authority, and other components, don't call getPath()!
URI normalization does not involve looking at the file system as File canonicalization does. But the flip side is that normalization behaves differently to canonicalization when there are symbolic links in the path.
Using Apache Commons IO (a well-known and well-tested library)
public static String normalize(String filename)
will do exactly what you're looking for.
Example:
String result = FilenameUtils.normalize(myFile.getAbsolutePath());
If you don't need path canonization but only normalization, in Java 7 you can use java.nio.file.Path.normalize method.
According to http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html:
This method does not access the file system; the path may not locate a file that exists.
If you work with File object you can use something like this:
file.toPath().normalize().toFile()
You could try an algorithm like this:
String collapsePath(String path) {
/* Split into directory parts */
String[] directories = path.split("/");
String[] newDirectories = new String[directories.length];
int i, j = 0;
for (i=0; i<directories.length; i++) {
/* Ignore the previous directory if it is a double dot */
if (directories[i].equals("..") && j > 0)
newDirectories[j--] = "";
/* Completely ignore single dots */
else if (! directories[i].equals("."))
newDirectories[j++] = directories[i];
}
/* Ah, what I would give for String.join() */
String newPath = new String();
for (i=0; i < j; i++)
newPath = newPath + "/" + newDirectories[i];
return newPath;
}
It isn't perfect; it's linear over the number of directories but does make a copy in memory.
Which kind of path is qualified as a Canonical Path is OS dependent.
That's why Java need to check it on the filesystem.
So there's no simple logic to test the path without knowing the OS.
So, while normalizing can do the trick, here is a procedure that exposes a little more of the Java API than would simply calling Paths.normalize()
Say I want to find a file that is not in my current directory on the file system.
My working code file is
myproject/src/JavaCode.java
Located in myproject/src/. My file is in
../../data/myfile.txt
I'm testing my program running my code from JavaCode.java
public static void main(String[] args) {
findFile("../../data","myfile.txt");
System.out.println("Found it.");
}
public static File findFile(String inputPath, String inputFile) {
File dataDir = new File("").getAbsoluteFile(); // points dataDir to working directory
String delimiters = "" + '\\' + '/'; // dealing with different system separators
StringTokenizer st = new StringTokenizer(inputPath, delimiters);
while(st.hasMoreTokens()) {
String s = st.nextToken();
if(s.trim().isEmpty() || s.equals("."))
continue;
else if(s.equals(".."))
dataDir = dataDir.getParentFile();
else {
dataDir = new File(dataDir, s);
if(!dataDir.exists())
throw new RuntimeException("Data folder does not exist.");
}
}
return new File(dataDir, inputFile);
}
Having placed a file at the specified location, this should print "Found it."
I'm assuming you have strings and you want strings, and you have Java 7 available now, and your default file system uses '/' as a path separator, so try:
String output = FileSystems.getDefault().getPath(input).normalize().toString();
You can try this out with:
/**
* Input Output
* /../foo/ -> /foo
* /foo/ -> /foo
* /../../../ -> /
* /./foo/./ -> /foo
* //foo//bar -> /foo/bar
* //foo/../bar -> /bar
*/
#Test
public void testNormalizedPath() throws URISyntaxException, IOException {
String[] in = new String[]{"/../foo/", "/foo/", "/../../../", "/./foo/./",
"//foo/bar", "//foo/../bar", "/", "/foo"};
String[] ex = new String[]{"/foo", "/foo", "/", "/foo", "/foo/bar", "/bar", "/", "/foo"};
FileSystem fs = FileSystems.getDefault();
for (int i = 0; i < in.length; i++) {
assertEquals(ex[i], fs.getPath(in[i]).normalize().toString());
}
}