I have a GWT project running in dev and production mode as well as on web and mobile.
I have different web.xml files for each mode.
I also need different constants for each version. Currently I use this:
class Params {
public static final String SOME_CONSTANT = "value";
...
}
The value of SOME_CONSTANT may change across modes (versions of the app).
How can I have different constants for each mode (dev, prod, web, mobile)?
Move these constants into properties file one for each environment.
create a folder like this (It must be outside of your final generated war file, somewhere on server)
resources
|__dev
|__prod
|__web
|__mobile
Each folder contains properties file having values based on environment.
Pass the value of environment at start up of server as system property or environment variable. Load all the properties at the application context initialization and use it anywhere in your application.
Use ServletContextListener to read all the properties at server start up.
How to load properties file based on system properties or environment variable?
Use
System.getProperty()
or
System.getenv()
to read the location of properties file.
and load the properties file
Properties properties = new Properties()
properties.load(new FileInputStream(new File(absolutePath)));
You can store properties as Application context attribute that can be read from anywhere including JSP as well.
--EDIT--
Load properties file at server start-up:
web.xml
<listener>
<listener-class>com.x.y.z.server.AppServletContextListener</listener-class>
</listener>
AppServletContextListener.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class AppServletContextListener implements ServletContextListener {
private static Properties properties = new Properties();
static {
// load properties file
String absolutePath = null;
if (System.getenv("properties_absolute_path") == null) {
absolutePath = System.getProperty("properties_absolute_path");
} else {
absolutePath = System.getenv("properties_absolute_path");
}
try {
File file = new File(absolutePath);
properties.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
#Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext().setAttribute("properties", properties);
}
public static Properties getProperties() {
return properties;
}
}
Related
Java creating logfile java0.log and lock file in /root folder
This behavior can be disabled using LogManager.reset() function, but I want to call this function based on some configuration parameter.
Can anyone suggest which config file I can use to do this and how to achieve this ?
Use the java.util.logging.config.file system property and point it to the NUL device.
On Windows:
-Djava.util.logging.config.file=NUL
On Linux:
-Djava.util.logging.config.file=/dev/null
On any platform you can simply create an empty file and point to it.
What this does is on startup the LogManager.readConfiguration() is called with the given file path (stream). Per the contract this method will:
Reinitialize the logging properties and reread the logging configuration
When it reads the logging configuration there is no new data to read. Therefore, this behaves as if it was just calling LogManager.reset() on startup.
If you want more selective behavior on the root logger then you write a custom class and use the java.util.logging.config.class property:
package foo.bar;
import java.io.FileInputStream;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public final class LogConfig {
public LogConfig() throws Throwable {
//Load the default config file.
String file = System.getProperty("java.util.logging.config.file");
if (file != null) {
LogManager.getLogManager().readConfiguration(new FileInputStream(file));
}
//Modify the logger tree if property is set.
String key = "some.config.property";
String v = System.getProperty(key);
if (v == null) {
throw new NullPointerException("System property '"
+ key + "' was not defined");
}
if (Boolean.parseBoolean(v)) {
Logger root = Logger.getLogger("");
for (Handler h : root.getHandlers()) {
if (h instanceof FileHandler) {
root.removeHandler(h);
h.close();
}
}
}
}
}
The to use this class you set the following command line properties:
-Djava.util.logging.config.file=/path/to/file -Djava.util.logging.config.class=foo.bar.LogConfig -Dsome.config.property=true
I'm trying to load a file from resources/ path using
getClassLoader().getResourceAsStream("file.LIB")
but the method always returns null, unless I rename the file into another extension, say ".dll".
I've looked into the official Java documentation, but to no avail.
Why does the method acts strange on that file type?
Note: I'm using JDK 1.8.0_111 x86 (due to constraints on that lib file, which only works well with a 32-bit JVM)
It does works for me, you need to be sure what exactly you are doing with lib file.
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class FileHelper {
public String getFilePathToSave() {
Properties prop = new Properties();
String filePath = "";
try {
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("abc.lib");
prop.load(inputStream);
filePath = prop.getProperty("json.filepath");
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
public static void main(String args[]) {
FileHelper fh = new FileHelper();
System.out.println(fh.getFilePathToSave());
}
}
I am trying to run pig scripts remotely from my java machine, for that i have written below code
code:
import java.io.IOException;
import java.util.Properties;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.backend.executionengine.ExecException;
public class Javapig{
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("fs.default.name", "hdfs://hdfs://192.168.x.xxx:8022");
props.setProperty("mapred.job.tracker", "192.168.x.xxx:8021");
PigServer pigServer = new PigServer(ExecType.MAPREDUCE, props);
runIdQuery(pigServer, "fact");
}
catch(Exception e) {
System.out.println(e);
}
}
public static void runIdQuery(PigServer pigServer, String inputFile) throws IOException {
pigServer.registerQuery("A = load '" + inputFile + "' using org.apache.hive.hcatalog.pig.HCatLoader();");
pigServer.registerQuery("B = FILTER A by category == 'Aller';");
pigServer.registerQuery("DUMP B;");
System.out.println("Done");
}
}
but while executing i am getting below error.
Error
ERROR 4010: Cannot find hadoop configurations in classpath (neither hadoop-site.xml nor core-site.xml was found in the classpath).
I don't know what am i doing wrong.
Well, self describing error...
neither hadoop-site.xml nor core-site.xml was found in the classpath
You need both of those files in the classpath of your application.
You ideally would get those from your $HADOOP_CONF_DIR folder, and you would copy them into your Java's src/main/resources, assuming you have a Maven structure
Also, with those files, you should rather use a Configuration object for Hadoop
PigServer(ExecType execType, org.apache.hadoop.conf.Configuration conf)
I want to put all my config files in a /config subfolder of my application directory. Log4j is expecting the log4j.properties file in the root folder of my application. Is there a way to tell log4j where to look for the properties file?
Yes, define log4j.configuration property
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
Note, that property value must be a URL.
For more read section 'Default Initialization Procedure' in Log4j manual.
You can use PropertyConfigurator to load your log4j.properties wherever it is located in the disk.
Example:
Logger logger = Logger.getLogger(this.getClass());
String log4JPropertyFile = "C:/this/is/my/config/path/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
logger.info("Wow! I'm configured!");
} catch (IOException e) {
//DAMN! I'm not....
}
If you have an XML Log4J configuration, use DOMConfigurator instead.
Use the PropertyConfigurator: PropertyConfigurator.configure(configFileUrl);
Refer to this example taken from -
http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
static final String path = "src/resources/log4j.properties";
public static void main(String[] args) {
PropertyConfigurator.configure(path);
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
To change the logger levels - Logger.getRootLogger().setLevel(Level.INFO);
In Eclipse you can set a VM argument to:
-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}
This is my class : Path is fine and properties is loaded.
package com.fiserv.dl.idp.logging;
import java.io.File;
import java.io.FileInputStream;
import java.util.MissingResourceException;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LoggingCapsule {
private static Logger logger = Logger.getLogger(LoggingCapsule.class);
public static void info(String message) {
try {
String configDir = System.getProperty("config.path");
if (configDir == null) {
throw new MissingResourceException("System property: config.path not set", "", "");
}
Properties properties = new Properties();
properties.load(new FileInputStream(configDir + File.separator + "log4j" + ".properties"));
PropertyConfigurator.configure(properties);
} catch (Exception e) {
e.printStackTrace();
}
logger.info(message);
}
public static void error(String message){
System.out.println(message);
}
}
You must use log4j.configuration property like this:
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
If the file is under the class-path (inside ./src/main/resources/ folder), you can omit the file:// protocol:
java -Dlog4j.configuration=path/to/log4j.properties myApp
I want to put all my config files in a /config subfolder of my application directory. Log4j is expecting the log4j.properties file in the root folder of my application. Is there a way to tell log4j where to look for the properties file?
Yes, define log4j.configuration property
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
Note, that property value must be a URL.
For more read section 'Default Initialization Procedure' in Log4j manual.
You can use PropertyConfigurator to load your log4j.properties wherever it is located in the disk.
Example:
Logger logger = Logger.getLogger(this.getClass());
String log4JPropertyFile = "C:/this/is/my/config/path/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
logger.info("Wow! I'm configured!");
} catch (IOException e) {
//DAMN! I'm not....
}
If you have an XML Log4J configuration, use DOMConfigurator instead.
Use the PropertyConfigurator: PropertyConfigurator.configure(configFileUrl);
Refer to this example taken from -
http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
static final String path = "src/resources/log4j.properties";
public static void main(String[] args) {
PropertyConfigurator.configure(path);
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
To change the logger levels - Logger.getRootLogger().setLevel(Level.INFO);
In Eclipse you can set a VM argument to:
-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}
This is my class : Path is fine and properties is loaded.
package com.fiserv.dl.idp.logging;
import java.io.File;
import java.io.FileInputStream;
import java.util.MissingResourceException;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LoggingCapsule {
private static Logger logger = Logger.getLogger(LoggingCapsule.class);
public static void info(String message) {
try {
String configDir = System.getProperty("config.path");
if (configDir == null) {
throw new MissingResourceException("System property: config.path not set", "", "");
}
Properties properties = new Properties();
properties.load(new FileInputStream(configDir + File.separator + "log4j" + ".properties"));
PropertyConfigurator.configure(properties);
} catch (Exception e) {
e.printStackTrace();
}
logger.info(message);
}
public static void error(String message){
System.out.println(message);
}
}
You must use log4j.configuration property like this:
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
If the file is under the class-path (inside ./src/main/resources/ folder), you can omit the file:// protocol:
java -Dlog4j.configuration=path/to/log4j.properties myApp