Exception : Too many open files - java

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);
}

Related

How to read properties file from different location in JAVA

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 )

Issue with file path in Java/Liferay

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);

Unable to move a file using java while using apache tika

I am passing a file as input stream to parser.parse() method while using apache tika library to convert file to text.The method throws an exception (displayed below) but the input stream is closed in the finally block successfully. Then while renaming the file, the File.renameTo method from java.io returns false. I am not able to rename/move the file despite successfully closing the inputStream. I am afraid another instance of file is created, while parser.parse() method processess the file, which doesn't get closed till the time exception is throw. Is that possible? If so what should I do to rename the file.
The Exception thrown while checking the content type is
java.lang.NoClassDefFoundError: Could not initialize class com.adobe.xmp.impl.XMPMetaParser
at com.adobe.xmp.XMPMetaFactory.parseFromBuffer(XMPMetaFactory.java:160)
at com.adobe.xmp.XMPMetaFactory.parseFromBuffer(XMPMetaFactory.java:144)
at com.drew.metadata.xmp.XmpReader.extract(XmpReader.java:106)
at com.drew.imaging.jpeg.JpegMetadataReader.extractMetadataFromJpegSegmentReader(JpegMetadataReader.java:112)
at com.drew.imaging.jpeg.JpegMetadataReader.readMetadata(JpegMetadataReader.java:71)
at org.apache.tika.parser.image.ImageMetadataExtractor.parseJpeg(ImageMetadataExtractor.java:91)
at org.apache.tika.parser.jpeg.JpegParser.parse(JpegParser.java:56)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:244)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:244)
at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:121)
Please suggest any solution. Thanks in advance.
public static void main(String args[])
{
InputStream is = null;
StringWriter writer = new StringWriter();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();
File file = null;
File destination = null;
try
{
file = new File("E:\\New folder\\testFile.pdf");
boolean a = file.exists();
destination = new File("E:\\New folder\\test\\testOutput.pdf");
is = new FileInputStream(file);
parser.parse(is, new WriteOutContentHandler(writer), metadata, new ParseContext()); //EXCEPTION IS THROWN HERE.
String contentType = metadata.get(Metadata.CONTENT_TYPE);
System.out.println(contentType);
}
catch(Exception e1)
{
e1.printStackTrace();
}
catch(Throwable t)
{
t.printStackTrace();
}
finally
{
try
{
if(is!=null)
{
is.close(); //CLOSES THE INPUT STREAM
}
writer.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
boolean x = file.renameTo(destination); //RETURNS FALSE
System.out.println(x);
}
This might be due to other processes are still using the file, like anti-virus program and also it may be a case that any other processes in your application may possessing a lock.
please check that and deal with that, it may solve your problem.

Error while laoding properties file from jar file

I am trying to load a property file from within a jar file but not able do so.
Following is the code of class in which i am loading the file
public class PropertyClass {
private static Properties properties;
public String getProperty(String propertyName) {
try {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resources/test.properties");
System.out.println("Input Stream " + inputStream);
properties.load(inputStream);
inputStream.close();
if (properties == null) {
System.out.println("Properties null");
}
} catch (IOException e){
e.printStackTrace();
}
return properties.getProperty(propertyName);
}
}
The class file and the property file both are packed inside the jar. But when i am trying load the file from another method it gives following error :-
Input Stream - sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream#9304b1
Exception in thread "main" java.lang.NullPointerException
at PropertyClass.getProperty(PropertyClass.java:16)
It does not show input stream as null
Following bit is the line 16 in my code -
properties.load(inputStream);
Any help on this
You need to initalise your Properties object before you can call properties.load():
private static Properties properties = new Properties();

Use properties to parameterize connection to Mongodb

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);

Categories