I am using this example to read from configuration file (data such as host name, password, etc) . But they did not include the Configurations class itself.
So I am not really sure how that should be implemented.
Here is how I am trying to read the properties from Main class:
Configurations configs = new Configurations(); // Error: cannot find symbol symbol: class Configurations location: class Main
try {
Configuration config = configs.properties(new File("database.properties"));
String dbHost = config.getString("database.host");
int dbPort = config.getInt("database.port");
String dbUser = config.getString("database.user");
String dbPassword = config.getString("database.password", "secret"); // provide a default
long dbTimeout = config.getLong("database.timeout");
} catch (ConfigurationException cex) {
cex.printStackTrace();
}
And this is how my database.properties file looks:
database.host = "dbname";
datatabase.port = 5005;
datatabase.user = "root";
datatabase.password = "";
database.timeout = 60000
P.S. Sorry for my stupidity, I am very new to Java.
You can use the properties class in java, which has a load method that specifies an inputstream.
Then, you can read your properties file via FileInputStream.
example:
public class Test {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
InputStream inputStream =
new FileInputStream("D:\\work_space\\java_workspace\\test-mq\\src\\main\\resources\\database.properties");
properties.load(inputStream);
String host = properties.getProperty("database.host");
// get more properties......
System.out.println(host);
}
}
Related
How do I go about configuring the classpath when using the scripts package with atom/java?
I know my classpath is:
usr/local/algs4/algs4.jar
Here is the code I am testing with:
import edu.princeton.cs.algs4.*;
public class Wget {
public static void main(String[] args) {
// read in data from URL
String url = args[0];
In in = new In(url);
String data = in.readAll();
// write data to a file
String filename = url.substring(url.lastIndexOf('/') + 1);
Out out = new Out(filename);
out.println(data);
out.close();
}
}
Since you're using algs4, Use Princeton's site and search for classpath.
http://algs4.cs.princeton.edu/code/
Trying to use java.util.logging and failing.
In an attempt to make use of https://stackoverflow.com/a/8249319/3322533 :
handlers = mypackage.logging.RequestFileHandler, mypackage.logging.MainFileHandler
config =
mainLogger.handlers = mypackage.logging.MainFileHandler
requestLogger.handlers = mypackage.logging.RequestFileHandler
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.filter =
java.util.logging.ConsoleHandler.formatter = mypackage.logging.VerySimpleFormatter
java.util.logging.ConsoleHandler.encoding =
mypackage.RequestFileHandler.level = SEVERE
mypackage.RequestFileHandler.filter =
mypackage.RequestFileHandler.formatter = mypackage.logging.VerySimpleFormatter
mypackage.RequestFileHandler.encoding =
mypackage.RequestFileHandler.limit =
mypackage.RequestFileHandler.count =
mypackage.RequestFileHandler.append = false
mypackage.RequestFileHandler.pattern = REQUESTS.%u.%g.log
mypackage.MainFileHandler.level = INFO
mypackage.MainFileHandler.filter =
mypackage.MainFileHandler.formatter = mypackage.logging.VerySimpleFormatter
mypackage.MainFileHandler.encoding =
mypackage.MainFileHandler.limit =
mypackage.MainFileHandler.count =
mypackage.MainFileHandler.append = false
mypackage.MainFileHandler.pattern = MAIN.%u.%g.log
where
public class MainFileHandler extends FileHandler {
public MainFileHandler() throws IOException, SecurityException {
super();
}
}
and
public class RequestFileHandler extends FileHandler {
public RequestFileHandler() throws IOException, SecurityException {
super();
}
}
Intention: provide two loggers accessible through
Logger.getLogger("mainLogger");
or
Logger.getLogger("requestLogger");
respectively, one that will write (exclusively) to MAIN[...].log and the other to REQUESTS[...].log
(No limits on the amount of messages that can be logged to either file and if necessary, use logging level to filter out unwanted msgs to either.)
However, neither file is created when I (for example)
public static final Logger log = Logger.getLogger("mainLogger");
and then
public void configureLogger(){
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream config = classLoader.getResourceAsStream("logging.properties");
LogManager.getLogManager().readConfiguration(config);
}catch(Exception ex){
throw new RuntimeException("logging properties failed");
}
}
before I
log.info("Hello World!")
I know the properties are loaded because when I include java.util.logging.ConsoleHandler in the handlers = ... list and use the global logger, instead, the formatter is applied for the console output.
So ... I guess my attempt at setting up the file loggers is faulty. How do I get this working?
EDIT
So I removed the [...].pattern = [...] lines and instead hardcoded the file names:
public class MainFileHandler extends FileHandler implements FileHandlerProperties {
public MainFileHandler() throws IOException, SecurityException {
super("MAIN_" + new SimpleDateFormat(TIME_PATTERN).format(new Date()) + ".log");
}
}
and
public class RequestFileHandler extends FileHandler implements FileHandlerProperties {
public RequestFileHandler() throws IOException, SecurityException {
super("REQUESTS_" + new SimpleDateFormat(TIME_PATTERN).format(new Date()) + ".log");
}
}
where
public interface FileHandlerProperties {
static final String TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
}
Both files now get created BUT they both contain exactly the same (despite their different level settings and loggers) AND what they contain is in xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2016-10-10T18:49:23</date>
<millis>1476118163654</millis>
<sequence>0</sequence>
<logger>mainLogger</logger>
<level>INFO</level>
<class>mypackage.main.Main</class>
<method><init></method>
<thread>1</thread>
<message>Hello World</message>
</record>
</log>
Please help ...
The problem is that the first call to Logger.getLogger during class loading reads the log configuration and your configureLogger method fails due to JDK-8033661: readConfiguration does not cleanly reinitialize the logging system.
To workaround this you have to ensure that configureLogger runs before the first call to Logger.getLogger.
public class BootMain {
static {
configureLogger();
mainLogger = Logger.getLogger("mainLogger");
requestLogger = Logger.getLogger("requestLogger");
}
private static final Logger mainLogger;
private static final Logger requestLogger;
public static void main(String[] args) throws IOException {
mainLogger.log(Level.SEVERE, "Test from main.");
requestLogger.log(Level.SEVERE, "Test from request.");
System.out.println(new File(".").getCanonicalPath());
}
private static void configureLogger() {
try {
InputStream config = config();
LogManager.getLogManager().readConfiguration(config);
} catch (Exception ex) {
throw new RuntimeException("logging properties failed");
}
}
private static String prefix() {
return "mypackage.logging";
}
private static InputStream config() throws IOException {
String p = prefix();
Properties props = new Properties();
props.put("mainLogger.handlers", p + ".MainFileHandler");
props.put("requestLogger.handlers", p + ".RequestFileHandler");
props.put(p + ".RequestFileHandler.level", "SEVERE");
props.put(p + ".MainFileHandler.level", "INFO");
props.put(p + ".RequestFileHandler.pattern", "REQUESTS.%u.%g.log");
props.put(p + ".MainFileHandler.pattern", "MAIN.%u.%g.log");
ByteArrayOutputStream out = new ByteArrayOutputStream();
props.store(out, "");
return new ByteArrayInputStream(out.toByteArray());
}
}
Also make sure you are not using a really old version of JDK or you can run into JDK-5089480: java.util.logging.FileHandler uses hardcoded classname when reading properties.
Otherwise you can use the LogManager config option to manually setup your configuration.
I have a static array list in my code. Now I want that should be moved to the properties file so that if there is any change or modification in future I have simply change the values in properties file and it will be reflected everywhere where it is used.
As of now static code is like this:
ArrayList dataList = new ArrayList();
dataList.add("A");
dataList.add("B");
dataList.add("E");
dataList.add("G");
dataList.add("H");
dataList.add("P");
dataList.add("W");
ArrayList TypeList = new ArrayList();
TypeList.add(new Brand("A", "Test1"));
TypeList.add(new Brand("B", "Test2"));
TypeList.add(new Brand("E", "Test3"));
TypeList.add(new Brand("G", "Test4"));
I have tried this but this is not working:
Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
I want both of them to be dynamic and the values should be picked from properties file. How can I do this?
You can try below code:
private static Properties props = null;
public static void load(String configFilePath) {
InputStream is = ClassLoader.getSystemResourceAsStream(configFilePath);
props = new Properties();
props.load(is);
is.close();
}
public static String getValueByKey(String key) {
String propertyValue=null;
if(props.containsKey(key)) {
propertyValue = props.getProperty(key);
}
return propertyValue;
}
Call this function during start of your program. You need to restart your program in case of properties file update
You can use in this way :-
Properties prop = new Properties();
prop.load(new FileInputStream("Test.properties"));
String name = prop.getProperty("name");
String city = prop.getProperty("city");
Test.properties
name=xyz
city=AAA
I tried best couldn't find a complete instructions on how to config a properties file with Maven,Testng.
Here are what I did and the exception I got:
from TestNG for suite, added
content of the config file:
user=testuser
password=pswd
pom.xml
src/test/resources
true
in code:
#BeforeTest #Parameters(value = { "config-file" })
public void initFramework(String configfile) throws Exception
{
InputStream stream = Config.class.getResourceAsStream("/config.properties");
Properties properties = new Properties();
try {
properties.load(stream);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
System.out.println("\nGot User FirstName+LastName shows as:"+ user +"\n" + password + "===========");
} catch (IOException e) {
e.printStackTrace();
// You will have to take some action here...
}
}
Here is what I got when compile:
org.testng.TestNGException:
Parameter 'config-file' is required by #Configuration on method initFramework but has not been marked #Optional or defined
Question:
I think I got all options mixed but really wanted a working way to read the parameter for Java/Selenium/TestNG/Maven.
Properties CONFIG= new Properties();
FileInputStream ip = new FileInputStream("C://config.properties");
CONFIG.load(ip);
//Now simply read through property file:-
String user = CONFIG.getProperty("user");
String password = CONFIG.getProperty("password");
//To write property file:-
CONFIG.setProperty("user","newbie1");
CONFIG.setProperty("password","secret123");
I am trying to output a changelog xml file through java.
I am not sure as to what I need to pass as parameters to the following method.
liquibase.generateChangeLog("chris", changeLogWriter, outputStream, snapshotTypes);
Chris is the schema name in Oracle 11g XE.
I don't want to generate on command line. I want to use application I am building to generate it.
public class Test {
public static void main(String[] args) {
String driverName = "oracle.jdbc.driver.OracleDriver";
String dbURL = "jdbc:oracle:thin:#localhost:1521:xe";
String userName = "chris";
String userPwd = "Liberty123";
try {
Class.forName(driverName);
Connection c = DriverManager.getConnection(dbURL, userName, userPwd);
System.out.println("success");
Liquibase liquibase = null;
try {
Database liqui_oracle = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c));
liquibase = new Liquibase("", new FileSystemResourceAccessor(), liqui_oracle);
liquibase.generateChangeLog("chris", changeLogWriter, outputStream, snapshotTypes);