Posts Tagged ‘java’

Rails-like configuration of different environments in JAVA – YAML instead of properties file

April 21st, 2010 | By Christoph in Software-Development | No Comments »

This article shows a simple code example how you can replace a standard JAVA properties file (.ini) with a more flexible .yml (YAML) file using the JYAML library.
I used this to store configuration parameters for an application for different environments (e.g. development vs. production) in one central file. This is how the RubyOnRails guys are doing this e.g. in the database.yml.

1. See how the usual standard config files look like.

# config.ini file
# Database
dbconnectionurl=jdbc:mysql://localhost:3306/mydb
dbuser=dbuser
dbpass=dbpasswd

As you see it just has key/value pairs. There is also no notion of an “environement” which means I could use a separate file to store information for different environments. But I want everything centralized.

And here the new yaml file:

# config.yml
development:
    # Database
    dbconnectionurl: jdbc:mysql://localhost:3306/mydevelopmentdb
    dbuser: dbuserdevelopment
    dbpass: dbpasswddevelopment

production:
    # Database
    dbconnectionurl: jdbc:mysql://localhost:3306/myproductiondb
    dbuser: dbuserproduction
    dbpass: dbpasswdproduction

As you can see the config.yml contains two sections. The first section is the configuration for the development environment, which is the default per my convention. The second section contains the configuration for the production environment.

2. Now here is the JAVA code which first loads the config.ini file using the standard approach and second loads the config.yml using the JYAML library and puts them into properties as well. Using that approach we almost don’t have to change any application code, because our application still uses a Java Properties object.

public static void main(String[] args) {
 
		/***
		 * 1. Load Properties using traditional approach
		 * from config.ini
		 */
		try {
			Properties props = new Properties();
			props.load(new FileReader(new File("config.ini")));
			System.out.println(props.toString());
 
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
 
		/***
		 * 2. Try to do the same based on
		 */
		try {
			Properties props = new Properties();
 
			HashMap yamlConfig = (HashMap) Yaml.load(new File("config.yml"));
 
			// now check which environment to load (production or development)
			// development is default
			String environment = System.getProperty("MYENVIRONMENT","development");
			HashMap propertiesFromYamlForEnvironment = yamlConfig.get(environment);
			props.putAll(propertiesFromYamlForEnvironment);
			System.out.println(props.toString());
 
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
	}

As you can see the line
String environment = System.getProperty("MYENVIRONMENT","development");
is responsible to read the environment from a system property. you can set this by setting the usual -DMYENVIRONMENT=”production” when you start you java program.

That’s it. Pretty simple but powerful.
You can read more about JYAML in their tutorial.

Initializing Hibernate without XML

April 13th, 2010 | By Christoph in Software-Development | No Comments »

This article just shows a code snippet I have used for initializing Hibernate in pure JAVA code without the hibernate.xml which you would normally use.

public void start(BundleContext context) throws Exception {
      initHibernate(context);
}
 
private void initHibernate(BundleContext context) {
	try {
		final AnnotationConfiguration cfg = new AnnotationConfiguration();
		cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    cfg.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    cfg.setProperty("hibernate.connection.url", applicationRegistry.getAppProperties().getDbConnectionUrl()); // e.g. "jdbc:mysql://localhost:3306/mydatabase"
    cfg.setProperty("hibernate.connection.username", applicationRegistry.getAppProperties().getDbUser());
    cfg.setProperty("hibernate.connection.password", applicationRegistry.getAppProperties().getDbPassword());
    cfg.setProperty("hibernate.connection.pool_size", "5");
    cfg.setProperty("hibernate.connection.autocommit", "false");
    cfg.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider");
    //cfg.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    cfg.setProperty("hibernate.show_sql", "true");
    cfg.setProperty("hibernate.format_sql","true");
    cfg.setProperty("hibernate.use_sql_comments","true");
    cfg.setProperty("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
    cfg.setProperty("hibernate.current_session_context_class", "thread");
    cfg.setProperty("org.hibernate.flushMode", "COMMIT");
    cfg.setProperty("hibernate.generate_statistics", "true");
 
    // Hibernate entities
    cfg.addAnnotatedClass(com.myproject.model.entities.Project.class);
    cfg.addAnnotatedClass(com.myproject.model.entities.Customer.class);
		// ... and so on...
 
		sessionFactory = cfg.buildSessionFactory();
 
		org.springframework.orm.hibernate3.HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
		applicationRegistry.setTransactionHelper(new TransactionHelper(transactionManager));
 
	} catch (Exception e) {
		LOGGER.error("Error", e.getMessage(), e);
	}
}

That’s it. I am using this code with Hibernate 3 using Annotations and so far it does what I want and it is not more ugly than the hibernate.xml (although that is in the eye of the observer ;) )

Cassandra Distributed Database – a link list for beginners

April 12th, 2010 | By Christoph in Software-Development | 3 Comments »

I am currently playing around with Apache Cassandra (distributed database) and this article is to store all the links I have used before I close my browser with trillions of open tabs :)

http://wiki.apache.org/cassandra/GettingStarted
http://wiki.apache.org/cassandra/ClientOptions
http://prettyprint.me/2010/02/23/hector-a-java-cassandra-client/

http://wiki.apache.org/cassandra/DataModel

Installing and using Apache Cassandra With Java Part 5 Parts (very good article series!!!)
http://www.sodeso.nl/?p=80
http://www.sodeso.nl/?p=108
http://www.sodeso.nl/?p=207
http://www.sodeso.nl/?p=251
http://www.sodeso.nl/?p=354
Update 2010/04/13: Ronald Mathies commented that he has two new articles. Thanks!
About importing / exporting data from a Cassandra Database: http://www.sodeso.nl/?p=448
Creating custom sorting types for Cassandra: http://www.sodeso.nl/?p=421

WTF is a SuperColumn? An Intro to the Cassandra Data Model

http://stackoverflow.com/questions/1502735/whats-the-best-practice-in-designing-a-cassandra-data-model

https://www.cloudkick.com/blog/2010/mar/02/4_months_with_cassandra/

Building a small Cassandra Cluster for Development and Testing

Cassandra: RandomPartitioner vs OrderPreservingPartitioner

http://about.digg.com/blog/looking-future-cassandra

http://blog.evanweaver.com/articles/2009/07/06/up-and-running-with-cassandra/

http://emmanuelpozo.com/post/317479418/cassandra-messaging-1

Time Series-Data Model

If somebody has some more links on examples and best practices forCassandra data models, then please comment. Thanks.

Java Code Snippet: Redirect System.out into a string

Januar 19th, 2010 | By Christoph in Software-Development | No Comments »

For a simple test application / prototype I just wanted to just dump everything from System.out into a String, which I can output somewhere e.g. in a JSP file so that I see what’s going on. And yes, I didn’t want to setup a Logging framework for this…I want a String. Here it is:


OutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
System.out.println(“Test”);
String sysout_content = out.toString();
System.out.println();
}

public static void main(String[] args) {

OutputStream out = new ByteArrayOutputStream();

System.setOut(new PrintStream(out));

System.out.println(“Test”);

String sysout_content = out.toString();

System.out.println();

}