Creating a class to wrap Properties - java

I want to create a class that wraps Properties and specifically hides the file I/O operations. I have come up with the abridged code below. This is intended to read the properties from a file at a fixed location outside of the class path. It also has a method to write the properties to the same file.
//
/* Defines key properties of the iFlag application.
* Methods read and write properties.
*/
public class ClientProperties {
private Properties props;
private static String xPanelSizeStg = "32";
private static int xPanelSize = 32;
private static String configFilename = "/home/myname/config/client_config.properties";
public ClientProperties() {
props = new Properties();
}
/**
* Reads properties from file
* Reads the current properties object from file.
* The file is stored in /home/mimibox/config/flag_config.properties
*/
public Properties readPropertiesFromFile( ){
// create and load default properties
InputStream input = null;
logger.trace("Read flag config properties.");
try {
input = new FileInputStream( configFilename );
//load a properties file from class path, inside static method
props.load(input);
//get the property values and save
xPanelSizeStg = props.getProperty("xPanelsize","32");
yPanelSizeStg = props.getProperty("yPanelsize", "32");
}
catch (IOException ex) {
logger.error("Could not open config file" + configFilename,ex );
}
finally{
if(input!=null){
try {
input.close();
}
catch (IOException e) {
logger.error( "Could not close config file" + configFilename,e );
}
}
}
return props;
}
/**
* Writes properties to file
* Writes the current properties object to file.
* The file is stored in /home/mimibox/config/flag_config.properties
*/
public void writePropertiesToFile() {
//saves the current properties to file. Overwrites the existing properties.
Properties props = new Properties(); //a list of properties
OutputStream outStrm = null;
logger.info("Writing default flag config properties.");
System.out.println("Panel size x = " + xPanelSizeStg );
try {
outStrm = new FileOutputStream( configFilename );
// set the properties values
props.setProperty("xPanelsize", xPanelSizeStg);
props.setProperty("yPanelsize", yPanelSizeStg);
// save properties to file, include a header comment
props.store(outStrm, "This is the Server configuration file");
} catch (IOException io) {
logger.error( "The file :{0} could not be opened", configFilename,io);
} finally {
if (outStrm!= null) {
try {
outStrm.close();
} catch (IOException e) {
logger.error("The file :{0} could not be closed", configFilename, e);
}
}
}
}
}
The read and write methods work. What doesn't work is trying to change the value of a property, and then save it. The demo code below successfully reads the properties file and displays the correct value for XPanelsize.
I then change that value and attempt to write the properties to a file. The new value 64 for xPanelsize is not written to the file.
public static void main(String[] args) {
Properties props;
ClientProperties p = new ClientProperties();
props = p.readPropertiesFromFile();
String txt = props.getProperty("xPanelsize");
System.out.println("Panel size x = " + txt );
p.setProperty("xPanelsize","64"); //method not found error
p.writePropertiesToFile();
So I would like to be able to use the Property.setProperty() method to set the value of a property. When I do that, the changed property is not written to the file. I can see that is because I have more than 1 Property instance and one is not visible to the other. I think I need to extend the built-in Properties class to achieve what I want to do, but I am not sure how to make it all work.
I have found plenty of examples of using Properties on the internet. What I haven't found are any examples that hide the related file I/O in a class. How would I do that??

OK so thanks to the comments and answers above, I have made a number of changes. For the benefit of those that stumble upon this post, I have posted the working code in this answer. The main change is to extend Properties. This allows me to use the Properties methods directly.
package com.test;
import java.util.Properties;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
public class ClientProperties extends Properties {
//initiate logger
private final static Logger logger = LogManager.getLogger();
private static String xPanelSizeStg = "32";
private static String yPanelSizeStg = "32";
private final configFilename = "/home/myname/myConfig.properties";
public ClientProperties() {
}
public Properties readPropertiesFromFile( ){
// create and load default properties
InputStream input = null;
logger.trace("Read flag config properties.");
try {
input = new FileInputStream( configFilename );
//load a properties file from class path, inside static method
this.load(input);
//get the property values and save
xPanelSizeStg = this.getProperty("xPanelsize","32");
yPanelSizeStg = this.getProperty("yPanelsize", "32");
}
catch (IOException ex) {
logger.error("Could not open config file" + configFilename,ex );
}
finally{
if(input!=null){
try {
input.close();
}
catch (IOException e) {
logger.error( "Could not close config file" + configFilename,e );
}
}
}
return this;
}
public void writePropertiesToFile() {
//saves the current properties to file. Overwrites the existing properties.
//Properties props = new Properties(); //a list of properties
OutputStream outStrm = null;
logger.info("Writing default flag config properties.");
System.out.println("Panel size x = " + xPanelSizeStg );
try {
outStrm = new FileOutputStream( configFilename );
// save properties to file, include a header comment
this.store(outStrm, "This is the Server configuration file");
} catch (IOException io) {
logger.error( "The file :{0} could not be opened", configFilename,io);
} finally {
if (outStrm!= null) {
try {
outStrm.close();
} catch (IOException e) {
logger.error("The file :{0} could not be closed", configFilename, e);
}
}
}
}
}
I have relied on the Properties parent to initiate Properties which I have accessed with "this". So now main looks like:
public static void main(String[] args) {
ClientProperties p = new ClientProperties();
p.readPropertiesFromFile();
String txt = p.getProperty("xPanelsize");
System.out.println("Panel size x = " + txt );
p.setProperty("xPanelsize","64");
p.writePropertiesToFile();
}
The class now hides all the admin around reading, writing and files. Crucially it avoids writing a setter/getter for each property (and I have a lot more properties than the two shown here). That is what I had in my first version.
Thanks for your help. It would have taken me a long time to figure all this out by myself.

You should probably need to create a getter for your 'props' object.
public Properties getProps()
{
return props;
}
And you will be able to invoke it like this:
p.getProps().setProperty("key", "value");
Or, if you are planning to make your ClientProperties class a children of Properties class, then you will need to use 'extends' and you would be able to invoke it by using
p.setProperty("key", "value");
And in this case you wouldn't need any Properties object in your class' fields.

This is my suggestion for your example.
First, you don't need to be edit again the properties in your writePropertiesToFile method like this:
public void writePropertiesToFile() {
// saves the current properties to file. Overwrites the existing properties.
// Properties props = new Properties(); // a list of properties
OutputStream outStrm = null;
logger.info("Writing default flag config properties.");
logger.debug("Panel size x = " + xPanelSizeStg);
try {
outStrm = new FileOutputStream(configFilename);
// set the properties values
//props.setProperty("xPanelsize", xPanelSizeStg);
//props.setProperty("yPanelsize", yPanelSizeStg);
// save properties to file, include a header comment
props.store(outStrm, "This is the Server configuration file");
} catch (IOException io) {
logger.error("The file :{0} could not be opened", configFilename, io);
} finally {
if (outStrm != null) {
try {
outStrm.close();
} catch (IOException e) {
logger.error("The file :{0} could not be closed", configFilename, e);
}
}
}
}
Then, you just create a setProperty method using the global variable -props- in the class.
private void setProperty(String key, String value) {
this.props.setProperty(key, value);
}
If your property file looks like image below:
The value of xPanelsize should be changed after running application.
public static void main(String[] args) {
Properties props = null;
ClientProperties p = new ClientProperties();
props = p.readPropertiesFromFile();
String xPanelsize = props.getProperty("xPanelsize");
System.out.println("Panel size x = " + xPanelsize);
p.setProperty("xPanelsize", "64"); // method not found error
p.writePropertiesToFile();
props = p.readPropertiesFromFile();
xPanelsize = props.getProperty("xPanelsize");
System.out.println("So, now the Panel size x = " + xPanelsize);
}
The debug message is,
The property file contents will be:
Here is full source:
package stackoverflow;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/* Defines key properties of the iFlag application.
* Methods read and write properties.
*/
public class ClientProperties {
Logger logger = LoggerFactory.getLogger(ClientProperties.class.getSimpleName());
private Properties props;
private String xPanelSizeStg;
private String yPanelSizeStg;
private int xPanelSize;
private int yPanelSize;
// private static String configFilename =
// "/home/myname/config/client_config.properties";
private static String configFilename = "resource/client_config.properties";
public ClientProperties() {
props = new Properties();
xPanelSizeStg = "32";
yPanelSizeStg = "32";
xPanelSize = 32;
yPanelSize = 32;
}
/**
* Reads properties from file Reads the current properties object from file. The
* file is stored in /home/mimibox/config/flag_config.properties
*/
public Properties readPropertiesFromFile() {
// create and load default properties
InputStream input = null;
logger.trace("Read flag config properties.");
try {
input = new FileInputStream(configFilename);
// load a properties file from class path, inside static method
props.load(input);
// get the property values and save
xPanelSizeStg = props.getProperty("xPanelsize", "32");
yPanelSizeStg = props.getProperty("yPanelsize", "32");
} catch (IOException ex) {
logger.error("Could not open config file" + configFilename, ex);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
logger.error("Could not close config file" + configFilename, e);
}
}
}
return props;
}
/**
* Writes properties to file Writes the current properties object to file. The
* file is stored in /home/mimibox/config/flag_config.properties
*/
public void writePropertiesToFile() {
// saves the current properties to file. Overwrites the existing properties.
// Properties props = new Properties(); // a list of properties
OutputStream outStrm = null;
logger.info("Writing default flag config properties.");
logger.debug("Panel size x = " + xPanelSizeStg);
try {
outStrm = new FileOutputStream(configFilename);
// set the properties values
//props.setProperty("xPanelsize", xPanelSizeStg);
//props.setProperty("yPanelsize", yPanelSizeStg);
// save properties to file, include a header comment
props.store(outStrm, "This is the Server configuration file");
} catch (IOException io) {
logger.error("The file :{0} could not be opened", configFilename, io);
} finally {
if (outStrm != null) {
try {
outStrm.close();
} catch (IOException e) {
logger.error("The file :{0} could not be closed", configFilename, e);
}
}
}
}
private void setProperty(String key, String value) {
this.props.setProperty(key, value);
}
public int getxPanelSize() {
return this.xPanelSize;
}
public void setxPanelSize(int xPanelSize) {
this.xPanelSize = xPanelSize;
}
public int getyPanelSize() {
return yPanelSize;
}
public void setyPanelSize(int yPanelSize) {
this.yPanelSize = yPanelSize;
}
public static void main(String[] args) {
Properties props = null;
ClientProperties p = new ClientProperties();
props = p.readPropertiesFromFile();
String xPanelsize = props.getProperty("xPanelsize");
System.out.println("Panel size x = " + xPanelsize);
p.setProperty("xPanelsize", "64"); // method not found error
p.writePropertiesToFile();
props = p.readPropertiesFromFile();
xPanelsize = props.getProperty("xPanelsize");
System.out.println("So, now the Panel size x = " + xPanelsize);
}
}

Related

Cheking uniqueness of key values in java properties files

I want to load a certain number of properties files into the same java.util.Properties object. I achieve this correctly with the following code:
public class GloalPropReader {
public static final Properties DISPATCHER = new Properties();
public static final Properties GLOBAL_PROP = new Properties();
public GloalPropReader() {
try (InputStream input = GloalPropReader.class.getClassLoader().getResourceAsStream("dispatcher.properties")) {
DISPATCHER.load(input);
} catch (IOException ex) {
throw new RuntimeException("Can't access dispatcher information");
}
for (Object nth : DISPATCHER.keySet()) {
String nthKey = (String) nth;
String nthPathToOtherProps = (String) DISPATCHER.get(nthKey);
Path p = Paths.get(nthPathToOtherProps);
try (InputStream input = new FileInputStream(p.toFile())) {
GLOBAL_PROP.load(input);
} catch (IOException ex) {
throw new RuntimeException("Can't access " + nthPathToOtherProps + " information");
}
}
}
}
And having this properties files:
dispatcher.properties
path_to_prop_1=C:/Users/U/Desktop/k.properties
path_to_prop_2=C:/Users/U/Desktop/y.properties
k.properties
prop1=BLABLA
y.properties
prop2=BLEBLE
But what i would like to achieve is to throw a RuntimeException if 2 properties file have the same key inside. For instance, i would like this class to throw an exception if k.properties and y.properties were so:
k.properties
prop1=BLABLA
y.properties
prop1=BLEBLE
EDIT
It's the same as this post Loading multiple properties files but i don't want the overriding logic when 2 keys are equal
public static class GloalPropReader {
private final Properties K_PROPERTIES = new Properties();
private final Properties Y_PROPERTIES = new Properties();
public GloalPropReader() {
loadProperties("k.properties", K_PROPERTIES);
loadProperties("y.properties", Y_PROPERTIES);
Set intersection = new HashSet(K_PROPERTIES.keySet());
intersection.retainAll(Y_PROPERTIES.keySet());
if (!intersection.isEmpty()) {
throw new IllegalStateException("Property intersection detected " + intersection);
}
}
private void loadProperties(String name, Properties y_properties) {
try (InputStream input = GloalPropReader.class.getClassLoader().getResourceAsStream(name)) {
y_properties.load(input);
} catch (IOException ex) {
throw new RuntimeException("Can't access dispatcher information");
}
}
}

Creating multiple files after receiving a queue message

I have a project that reads from mongodb and sends that information to the queue. my listener picks up the queue message from cloud. I am able to create a .txt file that inputs all the information inside from the queue. My problem that I have been searching for is: How can I sort through a specific field inside the POJO (IBusiness1,IBusiness2,IBusiness3)and create the file for each? The following code allows me to create only 1 txt file and it does not sort the field:
public static void main(String[] args) {
SpringApplication.run(PaymentPortalBatchListenerApplication.class, args);
}
private class MessageHandler implements IMessageHandler {
private final Logger logger = LoggerFactory.getLogger(MessageHandler.class);
public CompletableFuture<Void> onMessageAsync(IMessage message) {
System.out.println("received "+message.getBody());
ObjectMapper om = new ObjectMapper();
PortalList auditList = null;
try {
auditList = om.readValue( message.getBody(), PortalList.class );
System.out.println( "**Audit Message " + auditList );
logger.info( "Creating file");
String exportFilePath = "C:\\filewriter\\IBusiness1 " +
LocalDateTime.now().format(formatter) + ".txt";
File file = new File(exportFilePath);
FileWriter writeToFile = new FileWriter(file);
String exportFileHeader = "CREATE_DTTM|FNAME|LNAME|IBusiness";
StringHeaderWriter headerWriter = new
StringHeaderWriter(exportFileHeader);
writeToFile.write(exportFileHeader);
writeToFile.write( String.valueOf( headerWriter));
writeToFile.write( String.valueOf(auditList));
writeToFile.flush();
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(auditList);
return CompletableFuture.completedFuture(null);
}
Here is what I did:
PaymentPortalBean = POJO
auditlist =on-prem copy of PPB
PortalList =
import lombok.Data;
import java.util.List;
#Data
public class PortalList{
private List<PaymentPortalBean> portalList;
}
answer to creating files:
for(PaymentPortalBean bean: auditList.getPortalList()) {
if(bean.RxBusiness().contains( "IBusiness")){
File file = new File( exportFilePath );
FileWriter writeToFile = new FileWriter( file );
String exportFileHeader = CREATE_DTTM|FNAME|LNAME|IBusiness";
writeToFile.write( exportFileHeader );
writeToFile.write( String.valueOf(bean));
writeToFile.flush();
}
that worked to to find IBusiness, I created two more conditional statements for the types I needed. runs fine.
Mongo db was able to separate the fields I needed.

Open office sdk create xls, doc,ppt files in Java

How to create a xls file using open office sdk? Please give Java example source code. Also needed to create word and power point files. I’m not able to get any examples
Below is the code I tried. It tries to open in Open office App, that I don't want. I want to generate the .ods file in the WebSphere App Server under AIX environment, using Java. I'm using it to generate a report and download it to front end (web app).
import ooo.connector.BootstrapSocketConnector;
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.container.XIndexAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.XCell;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
XComponentContext xContext = null;
// get the remote office component context
try {
String folder = "C:\\Program Files (x86)\\OpenOffice 4\\program";
xContext = BootstrapSocketConnector.bootstrap(folder);
} catch (BootstrapException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XSpreadsheetDocument myDoc = null;
System.out.println("Opening an empty Calc document");
myDoc = openCalc(xContext);
XSpreadsheet xSheet = null;
try {
System.out.println("Getting spreadsheet");
XSpreadsheets xSheets = myDoc.getSheets();
XIndexAccess oIndexSheets = (XIndexAccess) UnoRuntime
.queryInterface(XIndexAccess.class, xSheets);
xSheet = (XSpreadsheet) UnoRuntime.queryInterface(
XSpreadsheet.class, oIndexSheets.getByIndex(0));
} catch (Exception e) {
System.out.println("Couldn't get Sheet " + e);
e.printStackTrace(System.err);
}
System.out.println("Creating the Header") ;
insertIntoCell(1,0,"JAN",xSheet,"");
insertIntoCell(2,0,"FEB",xSheet,"");
insertIntoCell(3,0,"MAR",xSheet,"");
insertIntoCell(4,0,"APR",xSheet,"");
insertIntoCell(5,0,"MAI",xSheet,"");
insertIntoCell(6,0,"JUN",xSheet,"");
insertIntoCell(7,0,"JUL",xSheet,"");
insertIntoCell(8,0,"AUG",xSheet,"");
insertIntoCell(9,0,"SEP",xSheet,"");
insertIntoCell(10,0,"OCT",xSheet,"");
insertIntoCell(11,0,"NOV",xSheet,"");
insertIntoCell(12,0,"DEC",xSheet,"");
insertIntoCell(13,0,"SUM",xSheet,"");
System.out.println("Fill the lines");
insertIntoCell(0,1,"Smith",xSheet,"");
insertIntoCell(1,1,"42",xSheet,"V");
insertIntoCell(2,1,"58.9",xSheet,"V");
insertIntoCell(3,1,"-66.5",xSheet,"V");
insertIntoCell(4,1,"43.4",xSheet,"V");
insertIntoCell(5,1,"44.5",xSheet,"V");
insertIntoCell(6,1,"45.3",xSheet,"V");
insertIntoCell(7,1,"-67.3",xSheet,"V");
insertIntoCell(8,1,"30.5",xSheet,"V");
insertIntoCell(9,1,"23.2",xSheet,"V");
insertIntoCell(10,1,"-97.3",xSheet,"V");
insertIntoCell(11,1,"22.4",xSheet,"V");
insertIntoCell(12,1,"23.5",xSheet,"V");
insertIntoCell(13,1,"=SUM(B2:M2)",xSheet,"");
insertIntoCell(0,2,"Jones",xSheet,"");
insertIntoCell(1,2,"21",xSheet,"V");
insertIntoCell(2,2,"40.9",xSheet,"V");
insertIntoCell(3,2,"-57.5",xSheet,"V");
insertIntoCell(4,2,"-23.4",xSheet,"V");
insertIntoCell(5,2,"34.5",xSheet,"V");
insertIntoCell(6,2,"59.3",xSheet,"V");
insertIntoCell(7,2,"27.3",xSheet,"V");
insertIntoCell(8,2,"-38.5",xSheet,"V");
insertIntoCell(9,2,"43.2",xSheet,"V");
insertIntoCell(10,2,"57.3",xSheet,"V");
insertIntoCell(11,2,"25.4",xSheet,"V");
insertIntoCell(12,2,"28.5",xSheet,"V");
insertIntoCell(13,2,"=SUM(B3:M3)",xSheet,"");
insertIntoCell(0,3,"Brown",xSheet,"");
insertIntoCell(1,3,"31.45",xSheet,"V");
insertIntoCell(2,3,"-20.9",xSheet,"V");
insertIntoCell(3,3,"-117.5",xSheet,"V");
insertIntoCell(4,3,"23.4",xSheet,"V");
insertIntoCell(5,3,"-114.5",xSheet,"V");
insertIntoCell(6,3,"115.3",xSheet,"V");
insertIntoCell(7,3,"-171.3",xSheet,"V");
insertIntoCell(8,3,"89.5",xSheet,"V");
insertIntoCell(9,3,"41.2",xSheet,"V");
insertIntoCell(10,3,"71.3",xSheet,"V");
insertIntoCell(11,3,"25.4",xSheet,"V");
insertIntoCell(12,3,"38.5",xSheet,"V");
insertIntoCell(13,3,"=SUM(A4:L4)",xSheet,"");
}
public static void insertIntoCell(int CellX, int CellY, String theValue,
XSpreadsheet TT1, String flag) {
XCell xCell = null;
try {
xCell = TT1.getCellByPosition(CellX, CellY);
} catch (com.sun.star.lang.IndexOutOfBoundsException ex) {
System.err.println("Could not get Cell");
ex.printStackTrace(System.err);
}
if (flag.equals("V")) {
xCell.setValue((new Float(theValue)).floatValue());
} else {
xCell.setFormula(theValue);
}
}
public static XSpreadsheetDocument openCalc(XComponentContext xContext) {
// define variables
XMultiComponentFactory xMCF = null;
XComponentLoader xCLoader;
XSpreadsheetDocument xSpreadSheetDoc = null;
XComponent xComp = null;
try {
// get the servie manager rom the office
xMCF = xContext.getServiceManager();
// create a new instance of the the desktop
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
// query the desktop object for the XComponentLoader
xCLoader = (XComponentLoader) UnoRuntime.queryInterface(
XComponentLoader.class, oDesktop);
PropertyValue[] szEmptyArgs = new PropertyValue[0];
String strDoc = "private:factory/scalc";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0,
szEmptyArgs);
xSpreadSheetDoc = (XSpreadsheetDocument) UnoRuntime.queryInterface(
XSpreadsheetDocument.class, xComp);
} catch (Exception e) {
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xSpreadSheetDoc;
}
}

RestFul web service which reads properties file

I have got couple of Jersey REST Web services say SendPassword and ResetPassword whose purpose is to send email .
For sending email , i have configured a properties file under tomcat and all this works fine
The code of the SendPassword.java is somewhat this way
#Path("/sendpassword")
public class SendPassword {
#GET
#Produces("application/json")
public String sendPasswordToEmail(#QueryParam("empid") String empid)
throws JSONException
{
try {
SendEmailUtility.sendmail("weqw","2312");
}
catch(Exception e)
{
}
}
SendEmailUtility.java
public class SendEmailUtility
{
public static String sendmail(String sendemalto,String generatedpwd) throws IOException {
String result = "fail";
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "email.properties");
InputStream stream = new FileInputStream(configFile);
Properties props_load = new Properties();
props_load.load(stream);
final String username = props_load.getProperty("username");
final String password = props_load.getProperty("password");
Properties props_send = new Properties();
props_send.put("mail.smtp.auth","true");
props_send.put("mail.smtp.starttls.enable","true");
Transport.send(message);
// Some code to send email
result = "success";
} catch (MessagingException e) {
result = "fail";
e.printStackTrace();
}
return result;
}
}
As you can see i am reading the properties file for every call of the websercice
(As reading operation is somewhat costly) , Is there any way to resolve this ??
Could you please let me know whats the best approach to handle this.
Thanks in advance .
There are few ways to do this the one way of doing it is to make the props_load a private static member of the class and call it like this
public class SendEmailUtility
{
private static Properties props;
private static Properties getProperties() {
if (props == null) {
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "email.properties");
InputStream stream = new FileInputStream(configFile);
props = new Properties();
props.load(stream);
}
return props;
}
public static String sendmail(String sendemalto,String generatedpwd) throws IOException {
String result = "fail";
Properties props_load = getProperties();
final String username = props_load.getProperty("username");
final String password = props_load.getProperty("password");
Properties props_send = new Properties();
props_send.put("mail.smtp.auth","true");
props_send.put("mail.smtp.starttls.enable","true");
Transport.send(message);
// Some code to send email
result = "success";
} catch (MessagingException e) {
result = "fail";
e.printStackTrace();
}
return result;
}
}
The other design I would suggest is to make an email service class like EmailSender or EmailService and then inject it into SendPassword class
#Path("/sendpassword")
public class SendPassword {
#Autowired
EmailService emailService;
#GET
#Produces("application/json")
public String sendPasswordToEmail(#QueryParam("empid") String empid)
throws JSONException
{
I would recommend using resource bundle, which does not need InputStream
create a properties file and put directly inside your packages along with your java code
example folder structure
com
- preethi
-SendPassword.java
-email.properties
Then you can code like
ResourceBundle props_load = ResourceBundle.getBundle("com.preethi.email");
final String username = props_load.getString("username");
This way you don't have to worry about opening and closing the stream or file path
You could use a lazy-getter to fetch and cache the Properties object.
private static Properties props;
private static Properties getProperties() {
if (props == null) {
File configDir = new File(System.getProperty("catalina.base"), "conf");
File configFile = new File(configDir, "email.properties");
InputStream stream = new FileInputStream(configFile);
props = new Properties();
props.load(stream);
}
return props;
}
Each time you want to use the Properties, call getProperties(). It will cache it the first time it's called. Each subsequent call will just return the cached object.
Note: This example does not catch any exceptions.

Why it is not storing all the key values rather it is storing the last updated value?

Using the below code I am able to store in the properties file, but the problem is it is storing the last stored value. I mean if a am stoing values val1, val2, val3...val5 it is storing only var5 value not others...Is there any way to do it?
prop = new Properties();
try {
/* //set the properties value
prop.setProperty(Key, value);
System.out.println("Updating the value for:"+Key);
//save properties to project testdata.properties file
prop.store(new FileOutputStream(System.getProperty("user.dir")
+ "xyz.properties"), null); */
file = new File(System.getProperty("user.dir")
+ "\\src\\test\\java\\config\\testdata123.properties");
Properties table = new Properties();
table.setProperty(Key, value);
System.out.println("Properties has been set in HashTable:" + table);
System.out.println("The Key values are :" + value);
//saving the properties in file
saveProperties(table);
System.out.println("After the change in HashTable:" + table);
//saving the properties in file
} catch (IOException ex) {
ex.printStackTrace();
return "Fail" + "While updating the testdata.properties file";
}
return "Pass";
}
public static void saveProperties(Properties p) throws IOException {
FileOutputStream fr = new FileOutputStream(file);
p.store(fr, "Properties");
System.out.println("After saving properties:" + p);
}
static void loadProperties(Properties p) throws IOException {
FileInputStream fi = new FileInputStream(file);
p.load(fi);
fi.close();
System.out.println("After Loading properties:" + p);
}
The Full code:
public static String setPropertiesValue(String Key, String value) {
try {
file = new File(System.getProperty("user.dir")
+ "\\src\\test\\java\\config\\xyz.properties");
Properties table = new Properties();
table.load(new FileInputStream(file));
table.setProperty(Key, value);
System.out.println("Properties has been set in HashTable:" + table);
System.out.println("The Key values are :" + value);
//saving the properties in file
saveProperties(table);
System.out.println("After the change in HashTable:" + table);
//saving the properties in file
} catch (IOException ex) {
ex.printStackTrace();
return "Fail" + "While updating the testdata.properties file";
}
return "Pass";
}
public static void saveProperties(Properties p) throws IOException {
FileOutputStream fr = new FileOutputStream(file);
p.store(fr, "Properties");
System.out.println("After saving properties:" + p);
}
static void loadProperties(Properties p) throws IOException {
FileInputStream fi = new FileInputStream(file);
p.load(fi);
fi.close();
System.out.println("After Loading properties:" + p);
}
enter code here
Thanks
you are creating a new Properties called 'table' and overwriting your File every time you save the Properties into a File. Instead load the Properties from an existing file and set the new key,value and save it.
Hope this should work!
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Test {
static File file = null;
/**
* #param args
*/
public static void main(String[] args) {
setPropertiesValue("name1", "value1");
setPropertiesValue("name2", "value2");
setPropertiesValue("name3", "value3");
setPropertiesValue("name4", "value4");
setPropertiesValue("name5", "value5");
}
public static String setPropertiesValue(String Key, String value) {
try {
file = new File(System.getProperty("user.dir") + "\\src\\test\\java\\config\\xyz.properties");
Properties table = new Properties();
table.load(new FileInputStream(file));
table.setProperty(Key, value);
System.out.println("Properties has been set in HashTable:" + table);
System.out.println("The Key values are :" + value);
// saving the properties in file
saveProperties(table);
System.out.println("After the change in HashTable:" + table);
// saving the properties in file
} catch (IOException ex) {
ex.printStackTrace();
return "Fail" + "While updating the testdata.properties file";
}
return "Pass";
}
public static void saveProperties(Properties p) throws IOException {
FileOutputStream fr = new FileOutputStream(file);
p.store(fr, "Properties");
System.out.println("After saving properties:" + p);
}
static void loadProperties(Properties p) throws IOException {
FileInputStream fi = new FileInputStream(file);
p.load(fi);
fi.close();
System.out.println("After Loading properties:" + p);
}
}
The result (value) of the properties file is as follows
Properties
Thu Mar 13 12:18:25 GMT 2014
name5=value5
name4=value4
name3=value3
name2=value2
name1=value1
Is this what you are trying to get as the result? or Am I missing something?

Categories