Lambda Expression without Formal Paramaters

Java Lambda Expression with No Formal Parameters

Interface

package com.codereq.corejava;

public interface Print {
    String show();
}

Implementation Class :

package com.codereq.corejava;

public class LambdaExpression {

    public static void main(String[] args) {
        LambdaExpression le = new LambdaExpression();
        le.printSummary("County : ", ()->{return "India";});
    }

    public void printSummary(String name, Print p) {
        System.out.println(name+p.show());
    }

}

Note the use ()-> for lambda expression without formal parameters.

Share and Enjoy

  • Facebook
  • Twitter
  • LinkedIn
  • Add to favorites
  • Email

Hibernate Collection Mapping – Mapping a Set

Overview

This post describes how Hibernate Collection mapping to a table can be achieved for a class having Set of attributes. The domain object is a Product which has various features modeled as Set . Our objective is to map this domain object to tables in relational database.

Hibernate Collection Mapping – Define domain object

Our domain object , Product, has prod_feature which is modeled as Set .

Product.java

package com.codereq.hibernatelab.setMapping;

import java.util.HashSet;
import java.util.Set;

public class Product {

    private String productId;
    private String productName;
    private String productType;

    private Set<String> prod_feature = new HashSet<String>();

    public String getProductId() {
	return productId;
    }

    public void setProductId(String productId) {
 	this.productId = productId;
    }

    public String getProductName() {
	return productName;
    }

    public void setProductName(String productName) {
	this.productName = productName;
    }

    public String getProductType() {
	return productType;
    } 

    public void setProductType(String productType) {
	this.productType = productType;
    }

    public Set<String> getProd_feature() {
	return prod_feature;
    }

    public void setProd_feature(Set<String> prod_feature) {
	this.prod_feature = prod_feature;
    }

}

Hibernate Collection Mapping : Mapping Product to table

To map Product class to a table in database we will configure a product.hbm.xml file. This configuration file will have all the information needed by hibernate to map Product to Product table in database.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.codereq.hibernatelab.setMapping.Product" table="product">
        <id column="productid" name="productId" type="java.lang.String">
 	    <generator class="assigned"/>
 	</id>

	<property column="productname" name="productName" not-null="true" type="java.lang.String"/>
	<property column="producttype" name="productType" not-null="true" type="java.lang.String"/>

	<set name="prod_feature" table="prod_feature">
	    <key column="productid"></key>
	    <element type="string" column="featurename" not-null="true" />
	</set>

    </class>
</hibernate-mapping>

 


hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
	<property name="show_sql">true</property>
	<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:db01</property>
        <property name="hibernate.connection.username">dblab</property>
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>

	<mapping resource="product.hbm.xml"/>

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


ProductService.java

package com.codereq.hibernatelab.setMapping;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class ProductService {

    public void init() {

        Configuration configuration = new Configuration();

	//Build ServiceRegistry using configuration
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

	//Get the SessionFactory.
	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

	//Create Session
	Session session = sessionFactory.openSession();
	Transaction tx = session.beginTransaction();

	String feature_1 = "voice";
	String feature_2 = "surf";
	Set<String> featureSet = new HashSet<String>();
	featureSet.add(feature_1);
	featureSet.add(feature_2);

	Product prod = new Product();
	prod.setProductId("123");
	prod.setProductName("mobile_1");
	prod.setProductType("mobile");
	prod.setProd_feature(featureSet);

	session.save(prod);
	//commit the transaction
	tx.commit();
	session.close();
	sessionFactory.close();
    }

}

Share and Enjoy

spring-xml

Marshalling and Unmarshalling XML using Spring

Introduction – Marshalling and Unmarshalling XML using Spring

This article illustrates Spring’s support for Object/XML mapping. Mapping XML to Object is called unmarshalling and mapping an object to XML is called Marshalling. Marshalling and Unmarshalling XML using Spring is supported by Spring’s OXM module. Spring provides an extensible , easy and simple way to use various O/X framework. By using Spring provided interfaces, one can switch between different O/X framework by a simple change in configuration.

 
Continue reading

Share and Enjoy

  • Facebook
  • Twitter
  • LinkedIn
  • Add to favorites
  • Email

Command Design Pattern in Java

Command Design Pattern

In this article we will see the application of command design pattern and problem domain it tries to solve.

Definition :

Command design pattern is a behavioral design pattern which encapsulates a request as an object. In command design pattern all the information required to invoke a method is encapsulated.

Continue reading

Share and Enjoy

  • Facebook
  • Twitter
  • LinkedIn
  • Add to favorites
  • Email
unix faqs

Unix FAQs

UNIX FAQs

The following faqs has list some commonly asked questions related to unix operating system. These also highlight some important concepts related to unix and which can come handy in day to day task of a software engineer. Continue reading

Share and Enjoy

  • Facebook
  • Twitter
  • LinkedIn
  • Add to favorites
  • Email

Unmarshalling and Marshalling XML – Using JAXB

Unmarshalling and Marshalling XML

In this article we will see how JAXB APIs and tools can be used for unmarshalling and marshalling XML document. Unmarshalling means converting an XML document to a Java object or set of java objects. Marshalling on the other hand means converting a java object to XML representation.
Continue reading

Share and Enjoy

  • Facebook
  • Twitter
  • LinkedIn
  • Add to favorites
  • Email

Proxy Design Pattern

Proxy Design Pattern :

This article explains the usage, purpose and implementation details of a very popular design pattern, the Proxy Design Pattern.

In general term, a Proxy means any thing which represents something and is similar. In Java as well, the meaning is no different.

 A proxy object represents some object , is similar and more importantly from client perspective it is not different. The client still feels that it is invoking same object. However, in actual it is using a proxy to actual object.

Proxy Design Pattern : Implementation:

Let’s see how a proxy design pattern is implemented  :

We have an interface IProcess, with a method process().

package com.codereq.designpattern.proxy;

public interface IProcess {

    public String process() throws Exception;

}

There is a class , ActualObject, which implements interface IProcess. This is our actual class which does some heavy operation like loading a large size file.

package com.codereq.designpattern.proxy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class ActualObject implements IProcess {

    @Override
    public String process() throws Exception {
        String line = null;
	File file = new File("NamesFile.txt");
	FileReader fileReader = new FileReader(file);

        BufferedReader bufferedReader = new BufferedReader(fileReader);
        line = new String();
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        bufferedReader.close();
        fileReader.close();
		return line;
    }

}

Because the client may not need the file immediately , we want to postpone the creation of this class as late as possible. However, the client still needs reference to ActualObejct.

The solution is to create a proxy class which would act as a representation of ActualObject.

The first requirement for creating a proxy class, is that it should implement the same interface which the class it proxies implements. So , our proxy class, ProxyObject , will implement the same interface, the IProcess.

package com.codereq.designpattern.proxy;

import java.util.Date;

public class ProxyObject implements IProcess {

    private ActualObject realClass = new ActualObject();
    private long lastAccessTime = 0l;
    String data = null;

    @Override
    public String process() throws Exception {
	long currentTime = new Date().getTime();
	if(currentTime - lastAccessTime > 100000) {
	    data = realClass.process();
	    lastAccessTime = currentTime;
	} 
	return data;
    }
}

Our proxy class has a reference to actual class. The proxy class calls the actual object only if the time difference between two successive call is 100 seconds otherwise it returns the stored data. This is just a hypothetical use case but should give enough understanding on how the proxy design pattern can be used.

Proxy Design Pattern – Client Code

The client code is :

package com.codereq.designpattern.proxy;

public class ProxyService {

    public static void main(String args[]) {

        IProcess pc = new ProxyObject();
        try {
            pc.process();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }	
}

Note that the client code has no reference to ActualObject. It only uses interface and ProxyObject.

The Proxy Design pattern can also be used for implementing caching, provide support for security and as a wrapper to a complex object.

Here is the UML representation of Proxy Design Pattern:

Proxy Design pattern

Share and Enjoy

  • Facebook
  • Twitter
  • LinkedIn
  • Add to favorites
  • Email

Ethernet Technology – IEEE 802.3

Ethernet – IEEE 802.3

Ethernet and IEEE 802.3 is a family of computer networking technologies for Local Area Networks (LAN) and was invented by Robert Metcalfe.

Initially Xerox Systems had built 2.94 Mbps network system to connect over 100 PCs on a 1 mile cable. This was called Ethernet. After its success, DEC and Intel drew a standard for 10Mbps Ethernet which ultimately formed the basis for 802.3

The most common installed Ethernet systems are 10BaseT which provides transmission speeds up to 10Mbps

Another high speed Ethernet which provides speed up to 100Mbps is FastEthernet or 100Base-T. These are typically used as backbone systems supporting workstations with 10Base-T cards.

Gigabit Ethernet provides even higher speed of up to 1000 Mbps and provides stronger support for backbone systems. 10-Gigabit Ethernet provides data transmission speed of 10 billion bits per second.

In Ethernet, the devices are connected to a common cable and compete for access using Carrier Sense Multiple Access and Collision Detection (CSMA/CD) protocol. In this protocol, when a station has to transmit it listens to the channel. If the channel is busy , it waits else it begins transmission immediately. Now, if two or more stations begin transmission immediately then there will be a collision and all the colliding stations stop immediately. They again wait for random duration and the repeat the process again.

The cable length in Ethernet setup is typically 100 meters and by using network bridge devices can be extended to more distances.

In Ethernet, data travels  inside protocol unit called frames. These frames begins with preamble and start frame delimiter, followed by ethernet header which has source and destination MAC address. The middle section of the frame has payload and headers for other protocols. The end of the frame has 32-bit CRC or Cyclic redundancy check which is used to detect data corruption.

Share and Enjoy

  • Facebook
  • Twitter
  • LinkedIn
  • Add to favorites
  • Email