Tag Archives: gradle

Configure Hibernate With MySQL in Gradle and do CRUD

build.gradle

group 'ir.mhdr'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8
mainClassName="Main"

repositories {
    mavenCentral()
}

dependencies {

    // https://mvnrepository.com/artifact/org.hibernate/hibernate-core
    compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.10.Final'

    // https://mvnrepository.com/artifact/org.hibernate/hibernate-gradle-plugin
    compile group: 'org.hibernate', name: 'hibernate-gradle-plugin', version: '5.2.10.Final'

    // https://mvnrepository.com/artifact/mysql/mysql-connector-java
    compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'

    // https://mvnrepository.com/artifact/org.slf4j/slf4j-api
    compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'

    // https://mvnrepository.com/artifact/org.slf4j/slf4j-simple
    testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'

    testCompile group: 'junit', name: 'junit', version: '4.12'
}

Employee.java

import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "salary")
    private int salary;

    public Employee() {
    }

    public Employee(String fname, String lname, int salary) {
        this.firstName = fname;
        this.lastName = lname;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String first_name) {
        this.firstName = first_name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String last_name) {
        this.lastName = last_name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
}

resources/hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQL57Dialect
        </property>
        <property name="hibernate.connection.driver_class">
            com.mysql.cj.jdbc.Driver
        </property>

        <!-- Assume test is the database name -->
        <property name="hibernate.connection.url">
            jdbc:mysql://localhost/testdb?useUnicode=yes&amp;characterEncoding=UTF-8&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC
        </property>
        <property name="hibernate.connection.username">
            root
        </property>
        <property name="hibernate.connection.password">
            sampad622
        </property>

        <!-- List of XML mapping files -->
        <mapping class="Employee"/>

    </session-factory>
</hibernate-configuration>

ManageEmployee.java

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.util.Iterator;
import java.util.List;

public class ManageEmployee {

    private SessionFactory factory;

    public ManageEmployee() {
        factory = new Configuration().configure().buildSessionFactory();
    }

    /* Method to CREATE an employee in the database */
    public Integer addEmployee(String fname, String lname, int salary) {

        Session session = factory.openSession();
        Transaction tx = null;
        Integer employeeID = null;

        try {
            tx = session.beginTransaction();
            Employee employee = new Employee(fname, lname, salary);
            employeeID = (Integer) session.save(employee);
            tx.commit();
        } catch (HibernateException e) {

            if (tx != null) tx.rollback();
            e.printStackTrace();

        } finally {

            session.close();

        }

        return employeeID;
    }


    /* Method to  READ all the employees */
    public void listEmployees() {
        Session session = factory.openSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();
            List employees = session.createQuery("FROM Employee").list();
            for (Iterator iterator =
                 employees.iterator(); iterator.hasNext(); ) {
                Employee employee = (Employee) iterator.next();
                System.out.print("First Name: " + employee.getFirstName());
                System.out.print("  Last Name: " + employee.getLastName());
                System.out.println("  Salary: " + employee.getSalary());
            }
            tx.commit();
        } catch (HibernateException e) {

            if (tx != null) tx.rollback();
            e.printStackTrace();
        } finally {

            session.close();

        }
    }


    /* Method to UPDATE salary for an employee */
    public void updateEmployee(Integer EmployeeID, int salary) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Employee employee =
                    (Employee) session.get(Employee.class, EmployeeID);
            employee.setSalary(salary);
            session.update(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }


    /* Method to DELETE an employee from the records */
    public void deleteEmployee(Integer EmployeeID) {
        Session session = factory.openSession();
        Transaction tx = null;

        try {

            tx = session.beginTransaction();
            Employee employee =
                    (Employee) session.get(Employee.class, EmployeeID);
            session.delete(employee);
            tx.commit();

        } catch (HibernateException e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Main.java

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {

    public static void main(String[] args) {

        ManageEmployee ME = new ManageEmployee();

      /* Add few employee records in database */
        Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
        Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
        Integer empID3 = ME.addEmployee("John", "Paul", 10000);

      /* List down all the employees */
        ME.listEmployees();

      /* Update employee's records */
        ME.updateEmployee(empID1, 5000);

      /* Delete an employee from the database */
        ME.deleteEmployee(empID2);

      /* List down new list of the employees */
        ME.listEmployees();
    }
}

References
https://github.com/mhdr/HibernateSamples/tree/master/002_CRUD

Configure JSF with Gradle

build.gradle

group 'ir.iterator'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'war'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'

    // https://mvnrepository.com/artifact/com.sun.faces/jsf-api
    compile group: 'com.sun.faces', name: 'jsf-api', version: '2.2.14'

    // https://mvnrepository.com/artifact/com.sun.faces/jsf-impl
    compile group: 'com.sun.faces', name: 'jsf-impl', version: '2.2.14'

    // https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/javax.servlet.jsp.jstl-api
    compile group: 'javax.servlet.jsp.jstl', name: 'javax.servlet.jsp.jstl-api', version: '1.2.1'

    // https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
    compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
}

/src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
            xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
            id="WebApp_ID" version="2.5">  
      <!-- Change to "Production" when you are ready to deploy -->  
      <context-param>  
           <param-name>javax.faces.PROJECT_STAGE</param-name>  
           <param-value>Development</param-value>  
      </context-param>  
      <servlet>  
           <servlet-name>Faces Servlet</servlet-name>  
           <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
           <load-on-startup>1</load-on-startup>  
      </servlet>  
      <!-- Map these files with JSF -->  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>/faces/*</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.jsf</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.faces</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.xhtml</url-pattern>  
      </servlet-mapping>  
      <!-- Welcome page -->  
      <welcome-file-list>  
           <welcome-file>welcome.xhtml</welcome-file>  
      </welcome-file-list>  
 </web-app>  

References
http://b1102.blogspot.ru/2014/09/jsf-21-gralde-tomcat-hello-world.html

Embedding Crosswalk on Android

download Crosswalk .aar file
https://download.01.org/crosswalk/releases/crosswalk/android/maven2/

Then copy to libs folder

allprojects {
    repositories {
        jcenter()
        flatDir {
            dirs 'libs'
        }
    }
}
compile(name:'xwalk_core_library', ext:'aar')
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:id="@+id/container"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="iterator.ir.bmi.MainActivity"
             tools:ignore="MergeRootFrame">

    <org.xwalk.core.XWalkView
            android:id="@+id/xwalkview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</FrameLayout>
public class MainActivity extends XWalkActivity {

    XWalkView mXWalkView;

    @Override
    protected void onXWalkReady() {
// Do anyting with the embedding API
        mXWalkView.load("file:///android_asset/www/index.html", null);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mXWalkView = (XWalkView) findViewById(R.id.xwalkview);
    }
}

References
https://developer.chrome.com/multidevice/webview/gettingstarted
https://crosswalk-project.org/documentation/android/embedding_crosswalk_rvw.html
http://stackoverflow.com/questions/40256449/intellij-idea-how-to-import-aar
https://download.01.org/crosswalk/releases/crosswalk/android/maven2/

Gradle Task

task cleanAll {
    group = 'minify'
    doFirst {
        tasks.cleanCSS.execute()
        tasks.cleanJS.execute()
    }
}
task cleanCSS {
    group = 'minify'
    doLast {
        String basePath = 'src/main/resources/static/stylesheets/site';
        FileTree tree = project.fileTree(dir: basePath);
        tree.include "**/*.css"
        tree.exclude "**/*.scss"
        tree.exclude "**/*.css.map"

        tree.visit { FileVisitDetails element ->
            if (!element.isDirectory()) {
                element.file.delete()
            }
        }
    }
}
task cleanJS {
    group = 'minify'
    doLast {
        String basePath = 'src/main/resources/static/javascripts/site';
        FileTree tree = project.fileTree(dir: basePath);
        tree.include "**/*.min.js"
        tree.exclude "**/*.js.map"
        tree.exclude "**/*.ts"
        tree.exclude "**/*.d.ts"

        tree.visit { FileVisitDetails element ->
            if (!element.isDirectory()) {
                element.file.delete()
            }
        }
    }
}
task sass {
    group = 'minify'
    doLast {
        String basePath = 'src/main/resources/static/stylesheets/site';
        FileTree tree = project.fileTree(dir: basePath);
        tree.include "**/*.scss"
        tree.exclude "**/*.css"
        tree.exclude "**/*.css.map"

        tree.visit { FileVisitDetails element ->
            if (!element.isDirectory()) {
                String filePath = basePath + "/" + element.getPath();

                int pos = filePath.lastIndexOf(".");
                String newFilePath = "";

                if (pos > 0) {
                    newFilePath = filePath.substring(0, pos) + ".css";
                }

                if (project.file(newFilePath).exists()) {
                    project.file(newFilePath).delete();
                }


                String cmd = String.format("node-sass $filePath $newFilePath");
                java.lang.Runtime.getRuntime().exec(cmd);
            }
        }
    }
}
task csso {
    group = 'minify'
    doLast {
        String basePath = 'src/main/resources/static/stylesheets/site';
        FileTree tree = project.fileTree(dir: basePath);
        tree.include "**/*.css"
        tree.exclude "**/*.min.css"
        tree.exclude "**/*.css.map"
        tree.exclude "**/*.scss"

        tree.visit { FileVisitDetails element ->
            if (!element.isDirectory()) {
                String filePath = basePath + "/" + element.getPath();

                int pos = filePath.lastIndexOf(".");
                String newFilePath = "";

                if (pos > 0) {
                    newFilePath = filePath.substring(0, pos) + ".min.css";
                }

                String cmd = String.format("csso -i $filePath -o $newFilePath");
                java.lang.Runtime.getRuntime().exec(cmd);
            }
        }
    }
}
task uglify {
    group = 'minify'
    doLast {
        String basePath = 'src/main/resources/static/javascripts/site';
        FileTree tree = project.fileTree(dir: basePath);
        tree.include "**/*.js"
        tree.exclude "**/*.min.js"
        tree.exclude "**/*.js.map"
        tree.exclude "**/*.ts"
        tree.exclude "**/*.d.ts"

        tree.visit { FileVisitDetails element ->
            if (!element.isDirectory()) {
                String filePath = basePath + "/" + element.getPath();

                int pos = filePath.lastIndexOf(".");
                String newFilePath = "";

                if (pos > 0) {
                    newFilePath = filePath.substring(0, pos) + ".min.js";
                }

                String cmd = String.format("uglifyjs $filePath -o $newFilePath");
                java.lang.Runtime.getRuntime().exec(cmd);
            }
        }
    }
}
sass.mustRunAfter cleanCSS
csso.mustRunAfter sass
uglify.mustRunAfter cleanJS
task minify{
    group = 'minify'
    doFirst{
        tasks.cleanCSS.execute()
        tasks.cleanJS.execute()
    }
    doLast{
        tasks.sass.execute()
        tasks.csso.execute()
        tasks.uglify.execute()
    }
}

References
https://docs.gradle.org/current/userguide/working_with_files.html
https://docs.gradle.org/current/userguide/tutorial_using_tasks.html
https://docs.gradle.org/current/userguide/custom_tasks.html
https://docs.gradle.org/current/userguide/more_about_tasks.html