Retrofitting java.util.Properties
Hi all,
why was java.util.Properties in JDK 1.5 not retrofitted to implement java.util.Map<String,String>?
This would have been the "natural" way to take advantage of typesafety.
I'm sure this has something to do with backwards compatibility, but what exactly woud it break?
Thanks
java.util.Properties extends java.util.Hashtable
java.util.Properties : private java.util.HashtableWhat does that actually buy you though?
I mean its really the difference between:
class Properties {
final Hashtable m_contents = new Hashtable();
public String getProperty(String key) {
return (String) m_contents.get(key);
}vs.
class Properties private extends Hashtable {
public String getProperty(String key) {
return (String) super.get(key);
}Which is nice and all, but it strikes me as syntactic sugar more than anything else.
I don't disagree: Properties should never have extended Hashtable, it should have encapsulated a Hashtable. Also Stack should not extend Vector, Booleans should not have a public constructor, it would even have been nicer if people actually used the Dictionary interface occassionally in 1.0/1.1.
Its easy to say these things now with the benefit of 20-20 hindsight.
Similar Messages
-
Finding the key according to string length in java.util.Properties
Finding the key according to string length in java.util.Properties.
I know only String length only.i need to retrieve the values from the java.util.properties.
we know that we need to give the key value in order to retrieve the datas.
but my problem is i will give the length of the key instead of giving the key value but i need to retrieve the datas according to the length of the key. -
Java.util.Properties methods load & store
Does java.util.Properties methods load & store produce & load platform independent code?
You mean that it is better to use loadFromXML(InputStream in) and storeToXML(OutputStream os, String comment) methods of this class in order to have platform independent code?
-
Error in Parser.fx file "incompatible types found : java.util.Properties"
Hi,
In parser file "Parser.fx",
public-read def PROPERTIES_PARSER = StreamParser {
override public function parse(input : java.io.InputStream) : RecordSet {
var props = javafx.util.Properties {};
props.load(input);
input.close();
MemoryRecordSet {
records: [
MapRecord {
fields: props
due to under line portion an error is appearing:
"incompatible types
found : javafx.util.Properties
required: java.util.Map
fields: props".
Please suggest some solution.
Thanks in advance.
regards,
Choudhary Nafees Ahmed
Edited by: ChoudharyNafees on Jul 5, 2010 3:48 AMParser.fx
package org.netbeans.javafx.datasrc;
import javafx.data.pull.PullParser;
import javafx.data.pull.Event;
import org.netbeans.javafx.datasrc.MemoryRecordSet;
public-read def PROPERTIES_PARSER = StreamParser {
override public function parse(input : java.io.InputStream) : RecordSet {
var props =java.util.Properties{};
props.load(input);
input.close();
MemoryRecordSet {
records: [
MapRecord {
fields: props
public-read def LINE_PARSER_FIELD_LINE = ".line";
public-read def LINE_PARSER = StreamParser {
override public function parse(input : java.io.Reader) : RecordSet {
var line : String;
var result : Record [] = [];
line = readLine(input);
// BEWARE ("" == null) is true
while (line != null or "".equals(line)) {
var map = new java.util.HashMap();
map.put(LINE_PARSER_FIELD_LINE, line);
var record = MapRecord {
fields: map
insert record into result;
line = readLine(input);
MemoryRecordSet {
records: result
function readLine(in : java.io.Reader) : String {
var str = new java.lang.StringBuilder;
while (true) {
var c = in.read();
if (c == -1) {
return if (str.length() == 0) then null else str.toString();
} else if (c == 0x0D) {
c = in.read();
if (c == 0x0A or c == -1) {
return str.toString();
str.append(0x0D);
} else if (c == 0x0A) {
return str.toString();
str.append(c as Character);
str.toString()
public-read def JSON_PARSER = StreamParser {
function toSequence(list : java.util.List) : Record [] {
var result : Record [] = [];
var ii = list.iterator();
while (ii.hasNext()) {
var r = ii.next() as Record;
insert r into result;
result
override public function parse(input : java.io.InputStream) : RecordSet {
var topLevel : Object;
def parser = PullParser {
documentType: PullParser.JSON
input: input
var mapStack = new java.util.Stack();
var currentMap : java.util.Map;
var recordsStack = new java.util.Stack();
var currentRecords : java.util.List;
var lastEvent: Event;
onEvent: function(event: Event) {
if (event.type == PullParser.TEXT) {
currentMap.put(event.name, event.text)
} else if (event.type == PullParser.INTEGER) {
currentMap.put(event.name, event.integerValue)
} else if (event.type == PullParser.NULL) {
currentMap.put(event.name, null)
} else if (event.type == PullParser.START_ELEMENT) {
if (lastEvent.type == PullParser.START_ARRAY_ELEMENT) return;
var oldMap = currentMap;
var temp = new java.util.HashMap();
temp.put(new Object(), null);
currentMap = temp;
currentMap.clear();
mapStack.push(currentMap);
if (topLevel == null) topLevel = currentMap;
if (oldMap != null) {
var mr = MapRecord {
fields: currentMap
if (event.name == "" and lastEvent.type == PullParser.START_VALUE) {
oldMap.put(lastEvent.name, mr)
} else {
oldMap.put(event.name, mr)
} else if (event.type == PullParser.START_ARRAY_ELEMENT) {
var temp = new java.util.HashMap();
temp.put(new Object(), null);
currentMap = temp;
currentMap.clear();
mapStack.push(currentMap);
var mr = MapRecord {
fields: currentMap
currentRecords.add(mr);
} else if (event.type == PullParser.END_ELEMENT) {
mapStack.pop();
if (not mapStack.empty()) {
currentMap = mapStack.peek() as java.util.HashMap;
} else {
currentMap = null;
} else if (event.type == PullParser.END_ARRAY_ELEMENT) {
if (lastEvent.type == PullParser.END_ELEMENT) return;
mapStack.pop();
if (not mapStack.empty()) {
currentMap = mapStack.peek() as java.util.HashMap;
} else {
currentMap = null;
} else if (event.type == PullParser.START_ARRAY) {
currentRecords = new java.util.ArrayList();
recordsStack.push(currentRecords);
if (topLevel == null) topLevel = currentRecords;
} else if (event.type == PullParser.END_ARRAY) {
var set = MemoryRecordSet {
records: toSequence(currentRecords)
currentMap.put(event.name, set);
recordsStack.pop();
if (not recordsStack.empty()) {
currentRecords = recordsStack.peek() as java.util.List;
} else {
currentRecords = null;
lastEvent = event;
parser.parse();
if (topLevel instanceof java.util.Map) {
var mr = MapRecord {
fields: topLevel as java.util.Map
MemoryRecordSet {
records: [mr]
} else {
// List
var rs = MemoryRecordSet {
records: toSequence(topLevel as java.util.List)
rs
parser.parse();
var mr = MapRecord {
fields: topLevel as java.util.Map
MemoryRecordSet {
records: [mr] -
Java.util.properties ? Using Config.getProperty
Hi all,
This one has been causing me a bit of a headache! I am using the Java.util.properties to create a file which looks like this:
#Tue Sep 13 19:15:06 GMT+02:00 2002
User=tristan
Password=bristol
Name=Tristan\ Webb
Rights=Tristan\ Webb
#Tue Sep 13 19:15:35 GMT+02:00 2002
User=adam
Password=newcastle
Name=Adam\ Jones
Rights=Adam\ Jones
The problem comes when I try to read the information back and put it in a Vector. Using the code below, it only ever puts the last users details (i.e. adam, Newcastle etc..) into the file and skips the first one. I have tried adding more users details, but it only ever reads the last entry. Is there anyway of forcing the config.getProperty to read the first entry in the file and then all the subsequesnt user details ?? I am thinking there must be a way of looping through the file, but im not sure where to start and am quite lost!
Many Thanks,
Properties config;
FileInputStream file;
file = new FileInputStream("password.cfg");
config = new Properties();
config.load(file);
User2 = config.getProperty("User");
Password = config.getProperty("Password");
name = config.getProperty("Name");
rights = config.getProperty("Rights");
UserDetails user = new UserDetails(User2, Password, name, rights);
userDetails.add(user);The java.util.Properties class works like a dictionary: it stores values, which you can access using the keys.
The keys must be unique. In your case, the keys are not unique. If you do: String s = config.getProperty("User"); then how do you expect to get two values back (tristan and adam)?
You must make the keys unique in some way. For example, write your properties file like this:
#Tue Sep 13 19:15:06 GMT+02:00 2002
User.1=tristan
Password=.1bristol
Name.1=Tristan\ Webb
Rights.1=Tristan\ Webb
#Tue Sep 13 19:15:35 GMT+02:00 2002
User.2=adam
Password.2=newcastle
Name.2=Adam\ Jones
Rights.2=Adam\ Jones
Now use for example: String s = config.getProperty("User.1"); to get the name of the first user, etc.
Jesper -
Applet using java.util.Properties.setPropterty()
Hi,
I'm trying to use the java.util.Properties class in an Applet. More specifically the setProperty(String, String) method. My applet compiles fine but it crashes when I run it with IE (ver. 6). It shows an "NoSuchMethodError: method setProperty(Ljava.lang.String,Ljava.lang.String)". When I compile with javac, it doesn't complain but I guess the IE VM doesn't see that method. But Properties is part of java.util.*, so shouldn't IE have access to that class?
Any help is much appreciated?
Thanks
HeatherThe API for that method includes this:
Since:
1.2
That means it's a Java 2 method. The JVM in Internet Explorer doesn't support Java 2 methods (unless you load a plugin that does). -
Invalid data returned when iterating a java.util.Properties
Hi all,
I'm having trouble iterating thru the values in a java.util.Properties object.
This problem only occurs when passing in a java.util.Properties object into the constructor of a java.util.Properties.
Here's some example code. (A picture is worth....)
<pre>
import java.util.Properties;
import java.util.Iterator;
public class PropertyTest {
public static void main(String[] args) {
Properties validProp = new Properties();
//add some data
validProp.put("key1", "key1Value");
validProp.put("key2", "key2Value");
validProp.put("key3", "key3Value");
System.out.println("This will iterate...");
dumpPropertyFile(validProp); //This will iterate correctly
Properties inValidProp = new Properties(validProp);
System.out.println("This doesn't iterate correctly");
dumpPropertyFile(inValidProp); //This will not iterate
public static void dumpPropertyFile(Properties prop) {
Iterator iter = prop.keySet().iterator();
while (iter.hasNext()) {
String key = (String)iter.next();
System.out.println(key + "=" + prop.getProperty(key));
</pre>
I have searched the bug database, but didn't find any open bugs related to this issue.
Could someone let me know if this is a existing bug or has this bug already been addressed.
My setup.
NT 4.0 / jdk1.3.1
Thanks,I found this works.
Iterator e = _props.keySet().iterator();
while(e.hasNext())
String str = (String)e.next();
System.out.println("key(" + str + ")=" + _props.getProperty(str));
but the display sequence is always in descending order ???
Anyone has a clue ?
Input :
catch#2 Prop catch#2
prop2 Properties.test.2
catch#6 Prop catch#6
catch#3 Prop catch#3
catch#5 Prop catch#5
catch#4 Prop catch#4
prop3 test Properties
prop4 test Properties4
prop1 Properties.test.1
catch#1 Prop catch#1
Output:
prop4=test Properties4<
prop3=test Properties<
prop2=Properties.test.2<
prop1=Properties.test.1<
catch#6=Prop catch#6<
catch#5=Prop catch#5<
catch#4=Prop catch#4<
catch#3=Prop catch#3<
catch#2=Prop catch#2<
catch#1=Prop catch#1< -
Unable to validate a java.util.Properties XML based File
I cannot for the life of me figure out what is wrong with this xml file, but it fails the validation of java.util.Properties and as such won't be parsed in. Help!
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties version="1.0">
<entry key="bottleneckServer.address"></entry>
<entry key="bottleneckServer.port">8206</entry>
<entry key="bottleneckServer.confirmDelay">10</entry>
<entry key="bottleneckServer.cleanupDelay">120</entry>
</properties>Thanks in advance!This xml file works perfectly.
Here is some test code:
Properties p = new Properties();
p.loadFromXML(getClass().getClassLoader().getResourceAsStream("someFilePath/someFileName.xml"));
assert "8206".equals(p.getProperty("bottleneckServer.port")) : "Property 'bottleneckServer.port' != 8206"; -
Java.util.Properties.load() not loading all properties
Hi,
I'm trying to load the following properties into my Properties class. However, Im only able to load SOME properties not ALL (11 to be precise)
This is my properties file :
~~~~~~~~~~~~~~~~~~~~~
gds.host=chissd235.bankofamerica.com
gds.datasource=gds.310.fob1
its.dataSource=gds.310.fob1
adv.dataSource=adv.310.fob1
gds.port=9650
gds.dataType=FpML
maxNumberOfConnectors=1000
itsConnectionMethod=ejb
advDB.driverToUse=jConnect2
advDB.userName=advDev1User
advDB.password=advDev1User
advDB.databaseName=advDev1
advDB.serverName=chisdd30.bankofamerica.com
advDB.port=2910
its.user=derivuser
This is my java code snippet:
~~~~~~~~~~~~~~~~~~~~~~~
private void loadProperties()
try
GDSConfigurationAdapter adapter = new GDSConfigurationAdapter();
String configurationResource = adapter.getConfigurationPropertiesResource();
load(loadStream(configurationResource));
String eventingPropsResource = adapter.getEventingPropertiesResource();
load(loadStream(eventingPropsResource));
} catch (IOException e)
throw new RuntimeException("Could not load GDS/Eventing properties");
private InputStream loadStream(String propFile) throws IOException
InputStream propStream = ResourceLocator.getResourceAsStream(propFile);
if (propStream == null)
logger.warning("could not find in JAR! Looking in classpath: " + propFile);
propStream = ResourceLocator.getResourceAsStream(propFile);
if (propStream == null)
IOException t = new IOException("Failed to load property file: " + propFile);
logger.throwing(getClass().getName(), "loadProperties", t);
throw t;
return propStream;
Any help will be appreciated.
Thanks
BjorkHi,
I'm trying to load the following properties into my Properties class. However, Im only able to load SOME properties not ALL (11 to be precise)
This is my properties file :
~~~~~~~~~~~~~~~~~~~~~
gds.host=chissd235.bankofamerica.com
gds.datasource=gds.310.fob1
its.dataSource=gds.310.fob1
adv.dataSource=adv.310.fob1
gds.port=9650
gds.dataType=FpML
maxNumberOfConnectors=1000
itsConnectionMethod=ejb
advDB.driverToUse=jConnect2
advDB.userName=advDev1User
advDB.password=advDev1User
advDB.databaseName=advDev1
advDB.serverName=chisdd30.bankofamerica.com
advDB.port=2910
its.user=derivuser
This is my java code snippet:
~~~~~~~~~~~~~~~~~~~~~~~
private void loadProperties()
try
GDSConfigurationAdapter adapter = new GDSConfigurationAdapter();
String configurationResource = adapter.getConfigurationPropertiesResource();
load(loadStream(configurationResource));
String eventingPropsResource = adapter.getEventingPropertiesResource();
load(loadStream(eventingPropsResource));
} catch (IOException e)
throw new RuntimeException("Could not load GDS/Eventing properties");
private InputStream loadStream(String propFile) throws IOException
InputStream propStream = ResourceLocator.getResourceAsStream(propFile);
if (propStream == null)
logger.warning("could not find in JAR! Looking in classpath: " + propFile);
propStream = ResourceLocator.getResourceAsStream(propFile);
if (propStream == null)
IOException t = new IOException("Failed to load property file: " + propFile);
logger.throwing(getClass().getName(), "loadProperties", t);
throw t;
return propStream;
Any help will be appreciated.
Thanks
Bjork -
Java.util.ResourceBundle VS java.util.Properties
I want to keep some key values pair outside program in a properties file and use that in my program. There is no requirement of localization. Should i use ResourceBundle or Properties class? Previously I have used Properties class for this purpose but in my current project ResourceBundle is being used. Is there any benefits in using ResourceBundle? will it be faster to read properties using ResourceBundle?
ResourceBundles support internationalization. If you know that don't need it and Properties suffice, okay then.
Forget about "fast", both will have to read from the disk (slow) and both will use hashmaps (fast look-up). And both will probably do it in the same way. -
Doubt in java.util.Properties
I have a configuration file which consists of name & value pairs. For editing this file i am using Properties class. The problem is , when it finds any property value which consists of character : (colon), its automatically inserting \ (backslash) before the colon(:). How can i get rid of this problem. Any help is highly appreciated. Thank you
Well, basically that's part of the formatdefinition
that Properties uses. If you don't do it, then you
aren't really using Properties format and you'llhave
to do your own IO.Thanks for the reply. Is there anyother api or class
that can be used to resolve my problem.What is the problem? A character is escaped, but you will get : when you read the value. You don't have a problem as long as all reading / writing is done through that class. -
Java.util.Properties
I execute this piece of code on application startup
public final Properties loadProperties() throws VmsBaseException {
Properties prop = new Properties();
prop.setProperty("ei.properties.file.import.path", "C:/projects/folders/input");
prop.setProperty("ei.properties.file.output.path", "C:/projects/folders/output");
prop.setProperty("ei.properties.file.name.pattern", "*.xml");
prop.setProperty("ei.properties.fixed.delay", "6000");
prop.setProperty("ei.properties.file.poller.interval", "100");
prop.setProperty("ei.properties.file.archive.path", "C:/projects/folders/archiveFolder/");
prop.setProperty("ei.properties.file.error.path", "C:/projects/folders/errorFolder/");
return prop;
Later on I would like my other beans to get hold of this properties and use the value inside it.
Any Idea how to achieve itManjit wrote:
Later on I would like my other beans to get hold of this properties and use the value inside it.
Any Idea how to achieve itYes, put the properties object somewhere where you can always reach it. Either that or let any piece of code that needs it call your loadProperties() method.
I'm sorry but your question is very open ended, so it is nearly impossible to be more specific. -
Java.util.Properties issue
I have an Integer array that i want to store using properties.
At the moment i have something like this
for(int i = 0; i < guitarNo.length; i++) {
p.setProperty("Identification", Integer.toString(guitarNo));
}But it doesn't store any of the ids it simpily stores as 1
Anyhelp would be fantasticbulger2503 wrote:
Ah well thats an inconvenience :)
Could you suggest another way?Maybe you could build a Properties file like the following given an e.g guitarNo like { 21, 54, 41 }
guitarNo = 3
Id0 = 21
Id1 = 54
Id2 = 41When you have to read the values back again, first read the key "guitarNo", create your array and read the keys "Id"+i for i in in [0,3)
kind regards,
Jos -
Hi,
I installed BI platform SBOP BI PLAT 4.1 and was able to log in to CMC and BI Launchpad. Post this, I installed SBOP DATA SERVICES 4.2 SP01 PATCH 3 WINDOWS 64B and am getting the above error while trying to open CMC and BI Launchpad.
Please helpThanks Jawahar, re deploying web apps helped.
-
Sort(java.util.LinkedList java.lang.Object ) doesn't work
Why doesn't this work?
LinkedList<Object> sysPropsKeys = new LinkedList<Object>(System.getProperties().keySet());
Collections.sort(sysPropsKeys);
cannot fnd symbol
symbol : method sort(java.util.LinkedList<java.lang.Object>)
location: class java.util.CollectionsI will admit to not having Java1.5 installed on my machine. Haven't yet had the chance to play with generics, but the above DOES work in 1.4, and SHOULD work in 1.5
Maybe I'm naive but, System.getProperties() returns a Properties object right?
According to the API: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html: Each key and its corresponding value in the property list is a string.
All the keys SHOULD be strings.
AFAIK string are comparable, and shouldn't throw class cast exceptions
Thus the keys returned from getProperties SHOULD be comparable, and compatible for comparision.
Ok, I can see your point in that some hackers abuse the Properties class by putting non string keys/values into the Properties Map. In that case the code would become more like your above. I'd probably still go with a TreeMap though, rather than a sorted list of keys. Most time you want the keys, you want the values as well. So if the intention is to print out a sorted list of system properties, and their values, keeping it in a map is best.
Just my 2 cents,
evnafets
Maybe you are looking for
-
Real time scenario for AXIS framework in SOAP adapter
Hello, Can anybody please suggest some real time scenario where AXIS framework can be used and what are the advanteges and disadvantages of using AXIS framework regards, Loveena
-
Can I use Fascinate as WiFi only?
I think I've read this question before, but here goes. After my contract runs out, can I dump my data plan and use the Fascinate as a WiFi only smartphone? Or maybe just dump my whole Verizon plan, go back to a "dumb" phone and use the Fascinate as
-
Lookup field in self registration form
I have added a user defined lookup field using Design View. I added the following attribute to FormMetaData.xml: <Attribute name="USR_UDF_LOCATION" label="global.udf.USR_UDF_LOCATION" displayComponentType="LookupField" map="USR_UDF_LOCATION" > <Valid
-
Why won't my final cut pro 7 open anymore?
The load screen starts up but after a certain piont it dissapears and says final cut quit unexpectedly. I already tried to reinstall it but it still happens. Please help.
-
URGENT: multiple currency one country grouping
I have a requirement whereby i have multiple currencies for one country grouping (international payroll). How do i handle thIs requirement? Since payroll driver RPCALCx0 only calls one currency. Treat as urgent. Cheers.