I am trying to use Properties file to parameterize connection to Mongodb.
I have added this function:
public static Properties load(String filename) throws IOException, FileNotFoundException{
Properties properties = new Properties();
FileInputStream input = new FileInputStream(filename);
try{
properties.load(input);
return properties;
}
finally{
input.close();
}
}
and use this code:
String path = System.getProperty("user.dir") + "/config.properties";
Properties prop = load(path);
//System.out.println("key: "+ prop.getProperty("MONGO_HOST"));
try {
//m = new Mongo(config.MONGO_HOST, config.MONGO_PORT);
m = new Mongo(prop.getProperty("MONGO_HOST"), config.MONGO_PORT);
this.db = m.getDB("cloud_datasource");
db.authenticate(config.MONGO_USER, config.MONGO_PASS.toCharArray());
} catch (Exception e) {
System.out.println("Can't connect to MongoDB");
e.printStackTrace();
}
In my config.properties: MONGO_HOST="192.168.10.84"
Problem: with this code, I have an error java.net.UnknownHostException: "192.168.10.84"
but if I am using the code:
m = new Mongo("192.168.10.84", config.MONGO_PORT);
it works.
Try this (without quotes):
MONGO_HOST=192.168.10.84
make sure what Tomasz said (no double quotes in prop file). then if it still doesn't work then maybe cast the prop.getProperty() to a String like this:
m = new Mongo((String)prop.getProperty("MONGO_HOST"), config.MONGO_PORT);
Related
I have sourcehandler.java class which has the code
public class SourceHandler {
String PrpPath = null;
Properties prop = null;
public Properties loadConfigProperties() {
try {
System.out.println("Propertiess " +PrpPath );
InputStream in =new FileInputStream(new File(PrpPath ));
prop.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}
and main method in a different class,
public static void main(String[] args) throws ParserConfigurationException,
Exception {
try {
SourceHandler conf = new SourceHandler();
conf.setProperties("C:/config.properties");
Properties p = conf.loadConfigProperties();
System.out.println("Done");
} catch (DOMException dome) {
// TODO: Add catch code
dome.printStackTrace();
}
Now, if i run the code , it shows null pointer exception at line , prop.load(in);
stack trace:
java.lang.NullPointerException
at DecryptEncryptSource.SourceHandler.loadConfigProperties(SourceHandler.java:98)
at DecryptEncryptSource.SourceHandler.updateCofigDestn(SourceHandler.java:151)
at DecryptEncryptSource.MainClass.main(MainClass.java:27)
First of all,
InputStream in =new FileInputStream(new File(Properties));
should better read
InputStream in =new FileInputStream(new File(propertyFileName));
to avoid any ambiguity; and then:
Are you sure that there is really a file named C:\config.properties
Probably you need either escaping: C:\\config.properties; or you try C:/config.properties
Regarding the update; you have this line:
Properties prop = null;
and further down:
prop.load(in);
And you are surprised that you get a NPE? Really? Hint: look into your code and create that Property object using the file path; instead of just calling a method on a null object.
And the real answer is read this here over and over again.
(and for those who wonder why I didn't close out as duplicate ... I can't any more, because I already close-requested on another reason )
I am using following java code in my application:
protected String encryptContact(Long contactId) {
if (contactId != null) {
EncryptionFactoryBean enbe = new EncryptionFactoryBean(String.valueOf(contactId), "/etc/test/encrypt.properties");
try {
enbe.SetProperties();
return (String) enbe.getObject();
} catch (Exception e) {
return null;
}
}
return null;
}
In EncryptionFactoryBean.java
public void setProperties()
throws Exception {
Assert.notNull(textToEncrypt, "encryption text cannot be null");
encryptionProperties = loadFile(encryptionFile);
super.setProperties();
}
protected Properties loadFile(String filename)
throws IOException {
Properties properties = null;
if (StringUtils.hasText(filename)) {
File file = new File(filename);
if (file.exists()) {
FileInputStream fi = new FileInputStream(file);
properties = new Properties();
properties.load(fi);
fi.close();
}
}
return properties;
}
On running the application, I am getting following error -
javax.servlet.ServletException: java.io.FileNotFoundException:
/etc/test/encrypt.properties (Too many open files)
It is not possible to increase the file limit in the application. Is there any way to fix this issue? Is it possible to close the file handler through finally ?
Console log error :
[org.apache.tomcat.util.net.JIoEndpoint] Socket accept failed java.net.SocketException: Too many open files
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:404)
at java.net.ServerSocket.implAccept(ServerSocket.java:545)
at java.net.ServerSocket.accept(ServerSocket.java:513)
at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:61)
at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:352)
at java.lang.Thread.run(Thread.java:745)
Most probably during the process of new EncryptionFactoryBean(String, String) you have something similar to
Properties props = new Properties();
Reader inStream = new FileReader("/etc/test/encrypt.properties");
props.load(inStream);
As the Javdoc of Properties.load(Reader) / Properties.load(InputStream) mention
The specified stream remains open after this method returns.
You need to close the stream yourself. For example like:
Properties props = new Properties();
try (Reader inStream = new FileReader("/etc/test/encrypt.properties")) {
props.load(inStream);
}
I have config.properties file that contains names.
Say it looks as such:
#Client1 properties
1Client=Client1
1someproperty=someproperty
#Client2 properties
2Client=Client1
2someproperty=someproperty
What I am trying to achieve is only getting the client names in a DefaultListModel so I can add them to a list. I have tried the following:
public static DefaultListModel SetVM() {
int clientCode = 1;
DefaultListModel vm_list = new DefaultListModel();
Properties props = new Properties();
FileInputStream fis = null;
try {
props.load(fis);
fis = new FileInputStream("config.properties");
//if (statement to see if props contains clientCode) {
String vmClient = props.getProperty(DatabaseCode + "CLIENT");
vm_list.addElement(vmClient);
//}
} catch (Exception e) {
}
return vm_list;
}
I was thinking along the line of for(Object obj : fis), but that is not possible. The other option was using an iterator as discribed here.
Though I cannot grasp how to get a certain property.
Try this. Using Properties entrySet which gives you the key and value for each property.
#Test
public void testClient () throws IOException {
DefaultListModel<String> vm_list = new DefaultListModel<String>();
Properties props = new Properties();
FileInputStream fis = null;
fis = new FileInputStream("config.properties");
props.load(fis);
for (Entry<Object, Object> entry : props.entrySet()) {
System.out.println("Entry key:" + entry.getKey() + " value:" + entry.getValue());
String key = (String)entry.getKey();
if (key.endsWith("Client")) {
vm_list.addElement(key); // maybe want to add entry.getValue() instead
}
}
// return vm_list;
}
Try something like this. Just used the regex to identify the client property.
Hope this helps.
Properties properties = new Properties();
try
{
properties.load(new FileInputStream("config.properties"));
for(String key : properties.stringPropertyNames()){
if(key.matches("(\\d+)Client")){
//add to arrayList
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Try this:-
Manage with a domain class
public class Client {
private String client;
private String someproperty;
// default constructor
// parameterized constructor
// get set methods
}
public static List<Client> SetVM() {
List<Client> vm_list = new ArrayList<Client>();
// client codes example
Integer clientCodes[] = { 1, 2 };
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property values
for (Integer code : clientCodes) {
vm_list.add(new Client(prop.getProperty(code + "Client"), prop.getProperty(code + "someproperty")));
}
return vm_list;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
I have tried in multiple ways to load the property file from the resource folder.
Every time, I'm getting a file not found exception. My code is as follows:
Properties prop = new Properties();
FileInputStream inputStream = new FileInputStream("/resource/excelfilepath.properties");
prop.load(inputStream);
String path = prop.getProperty("excelPath");
System.out.println("Excel File Path "+ path);
My project structure looks as follows,
What is the needed structure of the file path literal?
I don't think that you really want to read a ....properties file from web resources. That way the content is visible to all users that access your server - as long as you don't hide it explicitly in web.xml.
It's much more common to put it into the classpath next to your accessing class. That way you can access it with the classloader and it is not visible to the webusers anymore:
Properties prop = new Properties();
prop.load(CreateUser.class.getResourceAsStream("excelfilepath.properties"));
But as you are using Liferay, you should use its configuration as well. Just add the property UserCreationPortlet.excelPath to your portal-ext.properties and use:
String path = PrefsPropsUtil.getString("UserCreationPortlet.excelPath", defaultPath);
You need to tell to the server where your root folders are :
With Tomcat : in the catalina.properties
append the properties shared.loader with yours.
With Jboss : Edit jboss-service.xml in your conf folder
<classpath codebase="${jboss.home.url}/server/default/lib//proprietes/rootFolder" archives="*"/>
I would advice to create a classe to load your properties :
Like :
public static Properties charger(Class<?> pClass, String pFilename) {
Properties aProperties = null;
try {
InputStream aIs = null;
File aFile = new File(pFilename);
if (!aFile.isAbsolute()) {
aIs = pClass.getClassLoader().getResourceAsStream(pFilename);
if (aIs == null) {
return null;
}
} else if (!aFile.exists()) {
return null;
}
if (aIs == null)
aIs = new FileInputStream(aFile);
InputStreamReader reader = new InputStreamReader(aIs, "UTF-8");
aProperties = new Properties();
aProperties.clear();
aProperties.load(reader);
reader.close();
aIs.close();
} catch (FileNotFoundException e) {
LOG.error("Catch FileNotFoundException : ", e);
} catch (IOException e) {
LOG.error("Catch IOException : ", e);
}
return aProperties;
}
Then call your new class with the property that you wish :
protected static final Properties property = ChargeurProprietes.charger( .class,"PATH");
property.getProperty(NAME OF YOUR PROPERTY);
I'm having the following problem. I'm using Java properties to read some info of a file, but when I call prop.getProperty("var") it returns null. I ran out of ideas. Here is the code I have.
static final Properties prop = new Properties();
public JConnection(){
try{
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
logger.info("file not found.");
e.printStackTrace();
}
}
I never get the error message "file not found".
public static Connection getConnection(String conType) {
Connection conn;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
if(model == "client"){
conn = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("usr"),prop.getProperty("pass"));
}else{
conn = DriverManager.getConnection(prop.getProperty("url1"),prop.getProperty("usr1"),prop.getProperty("pass1"));
}
} catch (Exception ex) {
ex.printStackTrace();
conn = null;
}
When it tries to connect to the DB, getProperty is returning null as it is not found. Any ideas of what it could be or what I'm doing wrong?
Another wild guess: I noticed that both your prop variable and the method that's reading from it are static, so maybe you are using this as some sort of static utilities class without ever creating an instance of the class? In this case, you are never calling the constructor and never actually loading the properties file. Instead, you might try this:
static final Properties prop = new Properties();
static {
try{
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
logger.info("file not found.");
e.printStackTrace();
}
}
You have a static field (prop), but you initialize it in a constructor. This means if you consult your prop object before you construct any object of JConnection, prop will not be initialized.
You can try something like this:
public class JConecction {
static final Properties prop = new Properties();
static {
try {
prop.load(new FileInputStream("db.properties"));
} catch(Exception e) {
logger.info("file not found.");
e.printStackTrace();
}
}
}