Pda project using java

1 Overview

As for a fresh man learning java language, the best practice of learning a specific programming language is to develop an application using it. The Pda is a statictical model about energy comsumption. industry revenue and carbon dioxide emission. This model was developed by Python language. There are some pros and cons of Python completaton.

  • Python can build prototype immediatly.
  • Python is armed with countless packages which are sovle every possible situations.


  • Python is dynamic and weak type language, that brings out difficulties of refactoring.
  • As its relaying on packages, it takes time to share this application with others, especially when he or she hasn't installed Python environments.

Java is the best substitution of python. The open source code can be refered here.

2 Maven

Maven is a widely used java build tool with features like compile, test, package, denpendencies management and so on.

2.1 Maven Jdk setting

Maven chooses jdk 1.6 as default, and it doesn't meet our requirements. So we add some configurations in pom.xml file.


2.2 Denpendency

Maven set free us from manual management of application libraray jar file. If some jars also have other denpendencies, it sounds extradinary terriable. We just add dependencies in pom.xml.


Maven can download the dependencies and those dependencies from local repostitory, central repository and remote repository.

2.3 Add jar to repository

If your need a specific dependency which does not upload to central repository, you can add it to local repository as follows:

mvn install:install-file

Where: <path-to-file>  the path to the file to load
   <group-id>      the group that the file should be registered under
   <artifact-id>   the artifact name for the file
   <version>       the version of the file
   <packaging>     the packaging of the file e.g. jar

3 Hibernate

Hibernate is very popular ORM framework. To fetch data effectively, we take approach of getting data from database but not excel file.

3.1 Mysql database

./mysql -u root -p
create database industry;
use industry;
create table production(
    id int(4) not null primary key auto_increment,
    province varchar(10) not null,
    year char(4) not null,
    prod double(20,8) default 0.00
)default charset=utf8;

3.2 Hibernate class

class ProductionDb implements Serializable {
    private int id;
    private String province;
    private String year;
    private double prod;
    public ProductionDb(){}
    public ProductionDb(int id,String province, String year, double prod){
        this.id = id;this.province = province;
        this.year = year;this.prod = prod;}
    public int getId(){return id;}
    public String getProvince(){return province;}
    public String getYear(){return year;}
    public double getProd(){return prod;}
    public void setId(int id){this.id=id;}
    public void setProvince(String province){this.province=province;}
    public void setYear(String year){this.year = year;}
    public void setProd(double prod){this.prod=prod;}

3.3 Hibernate Configuration

Mapping configuration

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    <class name="org.iecas.pda.io.db.ProductionDb" table="production">
        <id name="id" type="int" column="id">
            <generator class="native"/>
        <property name="year" type="string">
            <column name="year"/>
        <property name="province" type="string">
            <column name="province"/>
        <property name="prod" type="double">
            <column name="prod"/>

Hibernate Configruation

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    <session-factory name="">
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">admin</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/industry?</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping resource="IndustryDb.hhm.xml" />

Java Usage

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    public static void shutdown() {
public class ProductionDbReader implements ProductionReader {
    public List<Production> read(String year) throws Exception{
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<ProductionDb> produtions = session.createQuery("From ProductionDb where year=:year ORDER BY id ASC")
        return produtions.stream().map(db->new Production(db.getProvince(),db.getProd())).collect(Collectors.toList());

4 Linear Programming

Joptimizer is choice of linear programming.
$ min \quad C^Tx $
subject to $Gx \le h,Ax=b$

protected double optimize(double[] energies, double[] co2s, double[] productions, double energy,double co2, double production){
        LPOptimizationRequest or = new LPOptimizationRequest();
        double[] c = energies;
        double[][] G = new double[1][];
        double[] h =new double[]{production};
        double[][] A = new double[1][];
        double[] b = new double[]{co2};
        double[] lb = new double[energies.length];
        LPPrimalDualMethod opt = new LPPrimalDualMethod();
            double[] sol = opt.getOptimizationResponse().getSolution();
            return IntStream.range(0, energies.length).mapToDouble(i->sol[i]*energies[i]).sum()/energy;
        }catch (Exception e){
            return -1.0;

5 Log4j

Log4j is a unseparate component of a java program. There two basic steps of using log4j.
In maven projcet, create a log4j.properties file in src/main/resourecs folder.

# Root logger option
log4j.rootLogger=ERROR, stdout, file

# Redirect log messages to console
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Redirect log messages to a log file, support file rolling.
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Get logger

Logger log = Logger.getLogger(MyClass.name);
Write a Comment