Accessing getProperty() outside of class - java

public static Properties defaultProps = new Properties();
static {
try {
FileInputStream in = new FileInputStream("config.properties");
defaultProps.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getProperty(String database) {
return defaultProps.getProperty(database);
}
public static void main(String[] args) {
System.out.println(...key database?);
// this is the part where I try to test if I can print the property 'database'
// I also try to make it available to other classes, tried using public statics,
}
This is my code in which I retrieve the properties from properties file config.properties. However, I want to be able to print property N (here: database) and be able to use property N in other classes.
Thanks for the help in advance.

so just call
System.out.println(getProperty("database"));

Related

How does sparkjava(java webframe) auto refresh page

I`m new developper of spark, And now I was block by a issue.
I was implements freemarker as web template.
Not like other framework when you modify a .ftl file, You no need to restart the server.
But now in my local it must restart the server if I wanto see the change.
Below is code.
public class SparkServer {
public static void main(String[] args){
get("/hello",(request,response) ->{
Map root = new HashMap();
root.put("user", "xiekakaban");
Map product = new HashMap();
product.put("name","Pringles");
product.put("price",13.2);
root.put("product",product);
return new ModelAndView(root,"test.ftl");
},FreeMarkerEngine.getInstance());
}
}
public class FreeMarkerEngine extends TemplateEngine{
private static FreeMarkerEngine freeMarkerEngine;
private Configuration freeConfig;
private FreeMarkerEngine() throws IOException{
freeConfig = new Configuration();
freeConfig.setDirectoryForTemplateLoading(StringUtil.getResourceFile("templates"));
freeConfig.setTemplateUpdateDelay(1);
}
public static FreeMarkerEngine getInstance(){
if(freeMarkerEngine == null){
try {
freeMarkerEngine = new FreeMarkerEngine();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
return freeMarkerEngine;
}
#Override
public String render(ModelAndView modelAndView) {
StringWriter stringWriter = new StringWriter();
try {
freeConfig.clearTemplateCache();
freeConfig.clearSharedVariables();
freeConfig.clearEncodingMap();
Template template = freeConfig.getTemplate(modelAndView.getViewName());
template.process(modelAndView.getModel(), stringWriter);
System.out.println(stringWriter.toString());
return stringWriter.toString();
} catch (IOException | TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Can not find the template:"+modelAndView.getViewName();
}
}
I don`t sure whether it is cache by spark or freemarker.But I have clear freemarker cache.
Anyone can help me.....
ok, I have figure out it.
Reloading the static files in Spark/Jetty-server
first I think you should make sure which page the freemarker load.
if you not setup, it will load ftl under "target" fold.
I think I put out a stupid question....

How to access java properties file

I have a properties file.
#My properties file
config1=first_config
config2=second_config
config3=third_config
config4=fourth_config
I have a class that loads the properties file in a small Java app. It works fine, specifically when I try to access each property within this class's method.
public class LoadProperties {
public void loadProperties() {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("resources/config.properties");
prop.load(input);
} catch (Exception e) {
System.out.println(e);
}
}
}
I am calling that class's method in another class, in a method.
public class MyClass {
public void myMethod() {
LoadProperties lp = new LoadProperties();
lp.loadProperties();
/*..More code...*/
}
}
How do I access the properties in the myMethod method in the MyClass class?
I tried typing prop.getProperty("[property_name]"), which does not work.
Any ideas? I'm assuming that this would be how I would access the properties. I can store them in variables in the loadProperties class and return the variables, but I thought that I would be able to access them how I stated above.
You can change the LoadProperties class to load the properties and add a method to return the loaded properties.
public class LoadProperties {
Properties prop = new Properties();
public LoadProperties() {
try (FileInputStream fileInputStream = new FileInputStream("config.properties")){
prop.load(fileInputStream);
} catch (Exception e) {
System.out.println(e);
}
}
public Properties getProperties() {
return prop;
}
}
Then use it like this
public class MyClass {
public void myMethod() {
LoadProperties loadProperties = new LoadProperties();
System.out.println(loadProperties.getProperties().getProperty("config1"));
}
}

Using variables from another method - problems understanding the object orientation

the following code is incomplete but the main focus of my question is on the method processConfig() anyway. It reads the properties out of a file and I want to handover these properties to the method replaceID(). It worked already when the content of processConfig was in the main()-method. But now I wanted to put this code into it´s own method. What is the best way of handing over the properties (which I saved in Strings like difFilePath). I´m not that familiar with OO-programming and want to understand the concept. Thanks for your help.
public class IDUpdater {
....
public static void main(String[] args) throws Exception {
//Here I want to call the variables from processConfig() to make them available for replaceID(...)
replaceID(difFilePath, outputDifPath, encoding);
}
public static void replaceID(String difFilePath, String outputDifPath, String encoding) throws Exception{
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
String difFilePath = prop.getProperty("dif_file_path");
String outputDifPath = prop.getProperty("output_dif_path");
String encoding = prop.getProperty("encoding");
}
}
You've to declare your variables globally. This way they can be accessed in each method. After you've declared them globally you first call your processConfig in your main method, which will set your variables to what they should be.
public class IDUpdater {
private String difFilePath;
private String outputDifPath;
private String encoding;
public void main(String[] args) throws Exception {
processConfig();
replaceID();
}
public void replaceID() throws Exception{
// You can use your variables here.
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
difFilePath = prop.getProperty("dif_file_path");
outputDifPath = prop.getProperty("output_dif_path");
encoding = prop.getProperty("encoding");
}
}
Note that I declared the variables privately. For more information about protecting your variables see https://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx.
You may want to read an article (or even better yet - a book) on topic of encapsulation and objects. This or this may be a good starting point for you. There is no point in anyone fixing your code, if you don't understand the concepts behind it.

Can Message Driven Bean read the queue names from a properties file

Case: Have and messaging appln will be deployed to JBOSS 6.1.1 server. Have different queue names for different environments. Is there any way to have the queue names and the details read from a config file instead of Queuenames
Hard coded in Annotation
Defined in ejb-jar.xml
Referring in jboss Standalone.xml
Regards,
Sucheta
You can put properties file in the root of your server. Access it within FileInputStream and set it in your MDB class.
make a singleton class and read the properties from this class:
public class EnvironmentProperties {
private static final EnvironmentProperties INSTANCE = new EnvironmentProperties();
private Properties props = null;
private Log log = LogFactory.getLog(EnvironmentProperties.class);
private EnvironmentProperties() {
loadProperties();
}
public static EnvironmentProperties getInstance() {
return INSTANCE;
}
public String getJmsName() {
return props.getProperty("jms.name");
}
public String getJmsQueue() {
return props.getProperty("jms.queue");
}
private Object readResolve() {
return INSTANCE;
}
private Properties loadProperties() {
props = new Properties();
try {
String filePath = new File("./config.properties").getCanonicalPath();
FileInputStream fis = new FileInputStream(filePath);
props.load(fis);
fis.close();
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return props;
}
}
get access to jms/queue name : EnvironmentProperties.getInstance().getJmsName();
Make sure the properties file existed on all your servers

"Could not find the main class, program will exit" while initializing class containing main()?

The class partially shown below contains a main method. When I run the code, I see a NullPointerException (NPE) and then an error message - "Could not find the main class, program will exit". My understanding is that if I get NPE, it means that the code is running, ie the JRE found a main method to begin execution, so why do I get the error message?
This is the console output
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at com.MyWorldDemo.getValue(MyWorldDemo.java:57)
at com.MyWorldDemo.<clinit>(MyWorldDemo.java:23)
Exception in thread "main"
In a nutshell:
username is stored in a properties file.
properties file is like this username=superman....etc
here is some code example
class MyClass {
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
// this method will assign a value to my final variable username.
public static String getData(String props) {
String property = prop.getProperty(props);// ERROR HERE !!!
return property;
}
}
Initializing of static variables depends on its position in code (variables are initialized from top to bottom). In your code
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
prop object will be initialized after username in static block, but since to initialize username prop is necessary and its not initialized yet you get NPE. Maybe change your code to something like:
private static Properties prop = new Properties();
private final static String username = getData("username");
static {
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
You have a static initialization at line 23 of MyWorldDemo that is calling the method getValue, which is then causing a NPE at line 57, therefore the class cannot be instantiated, therefore the main method cannot be called. It probably looks something like:
class MyWorldDemo {
private static String foo = getValue("username");
private static Properties prop;
// This happens too late, as getValue is called first
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch(IOException ex) {
ex.printStackTrace();
}
}
// This will happen before static initialization of prop
private static String getValue(String propertyValue) {
// prop is null
return prop.getProperty(propertyValue);
}
public static void main(String args[]) {
System.out.println("Hello!"); // Never gets here
}
}

Categories

Resources