Baran Topal

Baran Topal


September 2018
M T W T F S S
« Feb    
 12
3456789
10111213141516
17181920212223
24252627282930

Categories


CryptoServices in Java: HibernatePro

baranbaran

This is the Java Realm implementation for cryptoserverices by using hibernate. Note there are 4 other parts to fulfill this cryptoservices completely. Check the above link’s requirements, yet, this is also a standalone module.

Historically, Hibernate emerged from the need of object mapping to the database entities. In design, programmer wanted to differentiate the data access controller objects from the actual representation of the presentation. This is fairly straightforward, more modularity. So, HQL was introduced which is fairly easier than SQL (Note that I sometimes prefer MDX and sometimes NoSQL when it comes to extremely complicated queries).

Speaking of queries; please be sure that you already run the following sql:



/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

CREATE DATABASE /*!32312 IF NOT EXISTS*/`desedm` /*!40100 DEFAULT CHARACTER SET latin1 */;

USE `desedm`;

/*Table structure for table `descontent` */

DROP TABLE IF EXISTS `descontent`;

CREATE TABLE `descontent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`input_file_name` varchar(200) DEFAULT NULL,
`input_file_path` varchar(200) DEFAULT NULL,
`output_file_name` varchar(200) DEFAULT NULL,
`output_file_path` varchar(200) DEFAULT NULL,
`hash_input` varchar(50) DEFAULT NULL,
`hash_output` varchar(50) DEFAULT NULL,
`trivia` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

/*Data for the table `descontent` */

insert into `descontent`(`id`,`input_file_name`,`input_file_path`,`output_file_name`,`output_file_path`,`hash_input`,`hash_output`,`trivia`) values (7,'loremipsum_inp.txt','C:\\Users\\Baran\\Desktop\\Crypto\\JAX-WSRPCPro\\loremipsum_inp.txt','loremipsum_inp_139821104934900222447065033885224517803.enc','C:\\Users\\Baran\\Desktop\\Crypto\\JAX-WSRPCPro\\loremipsum_inp_139821104934900222447065033885224517803.enc','3470074571','3717763143','1234-4567-8910-2345'),(6,'loremipsum_inp.txt','C:\\Users\\Baran\\Desktop\\Crypto\\JAX-WSRPCEx\\loremipsum_inp.txt','loremipsum_inp_233791748694139990319682670690557272739.enc','C:\\Users\\Baran\\Desktop\\Crypto\\JAX-WSRPCEx\\loremipsum_inp_233791748694139990319682670690557272739.enc','3470074571','3717763143','1234-4567-8910-2345'),(8,'loremipsum_inp.txt','C:\\Users\\Baran\\Desktop\\Crypto\\JAX-WSRPCPro\\loremipsum_inp.txt','loremipsum_inp_68324782374304057550113228240832301009.enc','C:\\Users\\Baran\\Desktop\\Crypto\\JAX-WSRPCPro\\loremipsum_inp_68324782374304057550113228240832301009.enc','3470074571','3717763143','1234-4567-8910-2345');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

Now, for hibernate formation, what you need is actually a mapping configuration file and it’s naturally XML 🙂

The following code requires only one table in one database, so there is no cardinality idea as you can see.

You will also need the following jars for this hibernate project. Note that if you are using Ant or Maven, those are cool but I wrote the name of the jars here. Also, please note that if you check this code a year later, the jars may be updated in time. In this case, be extremely cautious.

Following is the POJO class. POJO reflect Plain Object definition. To put it simply, a POJO is a Java object that doesn’t implement any special interfaces. This class is required for ORM’s ‘O’.

The following are the jars utilized:
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.10.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
mysql-connector-java-5.0.7-bin.jar



/* 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 * Company: -								 							 *            
 * Assignment: Cyclic Redundancy Check + DES + Hibernate + JAX-WSRPC	 *
 * Deadline: -                           	 							 *
 * Programmer: Baran Topal                   							 *
 * WorkspaceName: Crypto					 							 *
 * Project Name: HibernatePro          									 *
 * Package name: com.baran.hibernate									 *
 * File name: FileRealm.java               							  	 *
 *                                          							 *      
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *	                                                                                         *
 *  LICENSE: This source file is subject to have the protection of GNU General               *
 *	Public License. You can distribute the code freely but storing this license information. *
 *	Contact Baran Topal if you have any questions. barantopal@barantopal.com                 *
 *	                                                                                         *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */

package com.baran.hibernate;

// POJO class
public class FileRealm {
	private int id;
	private String inputFileName;
	private String inputFilePath;
	private String outputFileName;
	private String outputFilePath;
	private String hashInput;
	private String hashOutput;
	private String trivia;	

	public FileRealm(){}
	public FileRealm(String inputFileName, String inputFilePath, String outputFileName, String outputFilePath, String hashInput, String hashOutput, String trivia)
	{
		this.inputFileName = inputFileName;
		this.inputFilePath = inputFilePath;
		this.outputFileName = outputFileName;
		this.outputFilePath = outputFilePath;
		this.hashInput  = hashInput;
		this.hashOutput = hashOutput;
		this.trivia = trivia;
	}

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getInputFileName() {
		return inputFileName;
	}
	public void setInputFileName(String inputFileName) {
		this.inputFileName = inputFileName;
	}
	public String getInputFilePath() {
		return inputFilePath;
	}
	public void setInputFilePath(String inputFilePath) {
		this.inputFilePath = inputFilePath;
	}
	public String getOutputFileName() {
		return outputFileName;
	}
	public void setOutputFileName(String outputFileName) {
		this.outputFileName = outputFileName;
	}
	public String getOutputFilePath() {
		return outputFilePath;
	}
	public void setOutputFilePath(String outputFilePath) {
		this.outputFilePath = outputFilePath;
	}
	public String getHashInput() {
		return hashInput;
	}
	public void setHashInput(String hashInput) {
		this.hashInput = hashInput;
	}
	public String getHashOutput() {
		return hashOutput;
	}
	public void setHashOutput(String hashOutput) {
		this.hashOutput = hashOutput;
	}
	public String getTrivia() {
		return trivia;
	}
	public void setTrivia(String trivia) {
		this.trivia = trivia;
	}
}

As you can see, it’s totally plain 🙂 Actually, you may not need all accessors and mutators according to your need.

Now, following is the hbm.xml file for this POJO.






	
	
		
			This class contains FileRealm details.
		
		
			
		
		
		
		
		
		
		
		
	
 

This class contains FileRealm details.

Be extremely careful. This class configuration is your base for your ORM. If there is a single typo, you may end up in error as SAX parser will fail to parse.

Careful that, I gave the qualified name of the POJO class. Since it’s in a package, the class name is: com.baran.hibernate.FileRealm

table property reflects the table in your database.

Now, let’s check the hibernate.cfg.xml

This is the mediator xml configuration for your actual program and database server. Here, I went for MySQL:

Above desedm is the database instance (name of the database) I think you are able to grap the rest. The mapping resource must match as we have given FileRealm.hbm.xml above.

Now, what we need is the actual implementation. We will need a SessionFactory and session that establish a session and transaction object to fulfill HQL needs. If the transaction fails, there will be rollover, if not, the operation will be commited. If you have a PL/SQL background, the idea is similar.

Note that you have to map, hibernate.cfg.xml file in the code to have the mapping.






	
		
		com.mysql.jdbc.Driver
		jdbc:mysql://localhost/desedm
		root
		root

		1
		org.hibernate.dialect.MySQLDialect
		thread
		org.hibernate.cache.NoCacheProvider
		true
		validate
		
	


/* 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 * Company: -								 *            
 * Assignment: Cyclic Redundancy Check + DES + Hibernate + JAX-WSRPC	 *
 * Deadline: -                           	 			 *
 * Programmer: Baran Topal                  				 *
 * WorkspaceName: Crypto						 *
 * Project Name: HibernatePro          					 *
 * Package name: com.baran.hibernate					 *
 * File name: HibernateOp.java             				 *
 *                                          				 *      
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *	                                                                                         *
 *  LICENSE: This source file is subject to have the protection of GNU General                   *
 *	Public License. You can distribute the code freely but storing this license information. *
 *	Contact Baran Topal if you have any questions. barantopal@barantopal.com                 *
 *	                                                                                         *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */

package com.baran.hibernate;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateOp {

	public static void main(String [] args)
	{		
		// mock values:
		String inputFileName = "test1.txt";
		String inputFilePath = "C:\\test1";
		String outputFileName = "test2.txt";
		String outputFilePath = "C:\\test2";
		String hashInput = "hashin";
		String hashOutput = "hashout";
		String trivia = "trivia";		

		HibernateOp.addFileRealm(inputFileName, inputFilePath, outputFileName, outputFilePath, hashInput, hashOutput, trivia);		
	}

	public static Session prepare()
	{
		Configuration configuration = new Configuration();
		configuration.configure("hibernate.cfg.xml");
		ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder().applySettings(configuration
				.getProperties());
		SessionFactory sessionFactory = configuration
				.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
		Session session = sessionFactory.openSession();

		return session;        
	}

	public static Integer addFileRealm(String inputFileName, String inputFilePath, String outputFileName, String outputFilePath, String hashInput, String hashOutput, String trivia)
	{
		// create factory, deprecated
		// SessionFactory factory = new Configuration().configure().buildSessionFactory();
		// Session session = factory.openSession();
		Session session= prepare();

		Transaction tx = null;
		Integer id =null;

		try
		{			
			// session starts
			tx = session.beginTransaction();

			// ORM
			FileRealm fr = new FileRealm(inputFileName, inputFilePath, outputFileName, outputFilePath, hashInput, hashOutput, trivia);
			id = (Integer)session.save(fr);
			tx.commit();

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

		return id;		
	}

	public static void listFiles()
	{
		Session session= prepare();

		Transaction tx = null;
		try
		{
			tx = session.beginTransaction();
			List files = session.createQuery("FROM FileRealm").list();
			for(Iterator iterator = files.iterator(); iterator.hasNext();)
			{
				FileRealm fileRealm = (FileRealm)iterator.next();
				System.out.println("Input File Name: " + fileRealm.getInputFileName());
				System.out.println("Input File Path: " + fileRealm.getInputFilePath());
				System.out.println("Output File Name: " +  fileRealm.getOutputFileName());
				System.out.println("Output File Path: " + fileRealm.getOutputFilePath());
				System.out.println("Hash Input: " + fileRealm.getHashInput());
				System.out.println("Hash Output: " + fileRealm.getHashOutput());
			}
			tx.commit();			
		}catch(Exception ex)
		{
			if(tx != null)
				tx.rollback();
			ex.printStackTrace();
		}finally{
			session.close();
		}
	}
}

Comments 0
There are currently no comments.