Tuesday, March 26, 2019

Out of the Box Thinking When Comes to Programming

 

What Does “Think Outside of the Box” Mean ?

 

 In the IT Industry one of the most well-worn phrase is a "Thinking Outside of the Box". It's all about creativity and doing the things in Best+ way. Think a situation like below


Question -: In a MCQ questionnaire num of choices for a question can be change, but only one answer can be selected. Think you have all the answers array from MCQ questionnaire.
Calculate how many times one answer choice selected.

Example -: Choice 1 - 3 Times Selected
                    Choice 2 - 5 Times Selected
                    Choice 3 - 6 Times Selected
                    Choice 4 - 8 Times Selected
          

Think a best way to do this. You can use any no of Arrays and any other but avoid using if conditions and ternary operations

Answer -:  

public static void main(String[] args){
       
        int[] d = new int[]{4,2,3,3,4,4,6,2};
        int choises[] = new int[d.length];
        for(int i = 0; i<d.length; i++){
            choises[d[i]]++;
        }

        for(int val : choises){
                System.out.println(Integer.valueOf(val));
        }
}

Get more from  : http://techprogramme.com/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Monday, April 3, 2017

Wednesday, February 1, 2017

Spring + Hibernate + MySql

In this article i'm discussing about how to use Spring and Hibernate with MySql

First create MySql Database using below script

springtutorial Database has two tables dmo_t_customer and dmo_t_item which has 1 to Many relationship.

CREATE DATABASE springtutorial;

USE `springtutorial`;

/*Table structure for table `dmo_t_customer` */

CREATE TABLE `dmo_t_customer` (
  `CUS_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `CUS_NAME` VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`CUS_ID`)
) ENGINE=INNODB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


/*Table structure for table `dmo_t_item` */

CREATE TABLE `dmo_t_item` (
  `ITM_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_I192NCREMENT,
  `ITM_ITEM` VARCHAR(60) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ITM_COST` DOUBLE DEFAULT '0',
  `ITM_Unit` DOUBLE DEFAULT NULL,
  `ITM_QTY` INT(11) DEFAULT NULL,
  `CUS_ID` BIGINT(20) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`ITM_ID`),
  KEY `cus_fk` (`CUS_ID`),
  CONSTRAINT `cus_fk` FOREIGN KEY (`CUS_ID`) REFERENCES `dmo_t_customer` (`CUS_ID`)
) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


Create a new Spring MVC project in Intellij

Go to File ---> New Project ---> Select Spring MVC and Fill details as follows and click finish




After click on Finish you will get a layout like below


Now lets add required dependencies to the Maven pom.xml file. Add below lines inside of <dependencies> tag in the pom.xml

   <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
  </dependency>

  <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier>
 </dependency>

        <!--Hibernate dependencies-->
  <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.3.2.ga</version>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
  </dependency>
        <!--END Hibernate dependencies-->
     
 <!--Jackson is use to serialize or map Java objects to JSON and vice versa-->
   <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-jaxrs</artifactId>
            <version>1.6.3</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.6.3</version>
            <type>jar</type>
            <scope>compile</scope>
  </dependency>

After that Go to src --> main --> webapp --> Open mvc-dispatcher-servlet.xml and change it as below.

highlighted lines are the lines which added newly to declare explicit support for annotation-driven MVC

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context              http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.customer.controller"/>

    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

Now lets configure Hibernate Framework to our project. to do that right click on the project name and select Add Framwork Support. 

From that select Hibernate and put a tick on Create default hibernate configuration and main class check box and make sure to put a tick on Set up library later because we already added hibernate dependency to the pom.xml file


Click ok. now you will be able to see the generated hibernate.cfg.xml file and Main.java file in "src/main/java/" location. Delete Main.java file and create a new folder called resources in "src/main/" and move hibernate.cfg.xml file to resources folder.

Now we need to create domain classes for Database Tables. Create a new package name com.customer.domains in the location "src/main/java/" and create below classes in side of that

DmoTCustomerEntity

package com.customer.domains;

import org.codehaus.jackson.annotate.JsonManagedReference;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "dmo_t_customer", schema = "", catalog = "springtutorial")
public class DmoTCustomerEntity {
    private long cusId;
    private String cusName;
    private List<DmoTItemEntity> dmoTItemEntityList;

    @Id
    @Column(name = "CUS_ID")
    @GeneratedValue(strategy= GenerationType.AUTO)
    public long getCusId() {
        return cusId;
    }

    public void setCusId(long cusId) {
        this.cusId = cusId;
    }

    @Basic
    @Column(name = "CUS_NAME")
    public String getCusName() {
        return cusName;
    }

    public void setCusName(String cusName) {
        this.cusName = cusName;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "dmoTCustomerEntity")
    @JsonManagedReference
    public List<DmoTItemEntity> getDmoTItemEntityList() {
        return dmoTItemEntityList;
    }

    public void setDmoTItemEntityList(List<DmoTItemEntity> dmoTItemEntityList) {
        this.dmoTItemEntityList = dmoTItemEntityList;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DmoTCustomerEntity that = (DmoTCustomerEntity) o;

        if (cusId != that.cusId) return false;
        if (cusName != null ? !cusName.equals(that.cusName) : that.cusName != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = (int) (cusId ^ (cusId >>> 32));
        result = 31 * result + (cusName != null ? cusName.hashCode() : 0);
        return result;
    }
}


DmoTItemEntity


package com.customer.domains;

import org.codehaus.jackson.annotate.JsonBackReference;

import javax.persistence.*;

@Entity
@Table(name = "dmo_t_item", schema = "", catalog = "springtutorial")
public class DmoTItemEntity {
    private long itmId;
    private String itmItem;
    private Double itmCost;
    private Double itmUnit;
    private Integer itmQty;
    private DmoTCustomerEntity dmoTCustomerEntity;

    @Id
    @Column(name = "ITM_ID")
    @GeneratedValue(strategy= GenerationType.AUTO)
    public long getItmId() {
        return itmId;
    }

    public void setItmId(long itmId) {
        this.itmId = itmId;
    }

    @Basic
    @Column(name = "ITM_ITEM")
    public String getItmItem() {
        return itmItem;
    }

    public void setItmItem(String itmItem) {
        this.itmItem = itmItem;
    }

    @Basic
    @Column(name = "ITM_COST")
    public Double getItmCost() {
        return itmCost;
    }

    public void setItmCost(Double itmCost) {
        this.itmCost = itmCost;
    }

    @Basic
    @Column(name = "ITM_Unit")
    public Double getItmUnit() {
        return itmUnit;
    }

    public void setItmUnit(Double itmUnit) {
        this.itmUnit = itmUnit;
    }

    @Basic
    @Column(name = "ITM_QTY")
    public Integer getItmQty() {
        return itmQty;
    }

    public void setItmQty(Integer itmQty) {
        this.itmQty = itmQty;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CUS_ID", nullable = false)
    @JsonBackReference
    public DmoTCustomerEntity getDmoTCustomerEntity() {
        return dmoTCustomerEntity;
    }

    public void setDmoTCustomerEntity(DmoTCustomerEntity dmoTCustomerEntity) {
        this.dmoTCustomerEntity = dmoTCustomerEntity;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DmoTItemEntity that = (DmoTItemEntity) o;

        if (itmId != that.itmId) return false;
        if (itmCost != null ? !itmCost.equals(that.itmCost) : that.itmCost != null) return false;
        if (itmItem != null ? !itmItem.equals(that.itmItem) : that.itmItem != null) return false;
        if (itmQty != null ? !itmQty.equals(that.itmQty) : that.itmQty != null) return false;
        if (itmUnit != null ? !itmUnit.equals(that.itmUnit) : that.itmUnit != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = (int) (itmId ^ (itmId >>> 32));
        result = 31 * result + (itmItem != null ? itmItem.hashCode() : 0);
        result = 31 * result + (itmCost != null ? itmCost.hashCode() : 0);
        result = 31 * result + (itmUnit != null ? itmUnit.hashCode() : 0);
        result = 31 * result + (itmQty != null ? itmQty.hashCode() : 0);
        return result;
    }
}

Now open hibernate.cfg.xml file and change it as below. change hibernate.connection.url,
hibernate.connection.username, hibernate.connection.password based on your database information. 

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver
        </property>

        <!-- Assume students is the database name -->
        <property name="hibernate.connection.url">
            jdbc:mysql://192.168.8.86:3306/springtutorial
        </property>
        <property name="hibernate.connection.username">
            allroot
        </property>
        <property name="hibernate.connection.password">
            123
        </property>
        <property name="show_sql">true</property>

        <mapping class="com.customer.domains.DmoTCustomerEntity"/>
        <mapping class="com.customer.domains.DmoTItemEntity"/>

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

Create another two class in the com.customer.controller package as HibernateUtil and JsonResponse

HibernateUtil.java

package com.customer.controller;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Created by janithag on 1/16/17.
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().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() {
        // Close caches and connection pools
        getSessionFactory().close();
    }


}


JsonResponse.java

package com.customer.controller;

import java.util.List;


public class JsonResponse  {

    private List<?> dataCollection;
    private String serverMessage;

    public String getServerMessage() {
        return serverMessage;
    }

    public void setServerMessage(String serverMessage) {
        this.serverMessage = serverMessage;
    }

    public List<?> getDataCollection() {
        return dataCollection;
    }

    public void setDataCollection(List<?> dataCollection) {
        this.dataCollection = dataCollection;
    }

}


Now delete both HelloController.java(src/main/java/com.customer.controller/HelloController.java) and hello.jsp(src/main/webapp/WEB-INF/pages/hello.jsp) files from the project.

Right click on the pages folder in the webapp and go to new and click on Create JSP and name it as customerPage.

Change customerPage.jsp as below

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>

        function saveDetails()
        {
            $.post('saveDetails.do?cusName='+$("#cusName").val()+'&itemName='+$("#itemName").val()+'&itemCost='+$("#itemCost").val()+'&itemUnit='+$("#itemUnit").val()+'&itemQty='+$("#itemQty").val(), function(response) {

                alert(response.serverMessage);
            });
        }

        function showDetails()
        {
            $.getJSON("showDetails",function(data) {

                var detailsList = "";
                var itemList = "";
                var dataCollection=[];
                dataCollection = data.dataCollection
                for(var i=0;i<dataCollection.length;i++)
                {
                    var details = dataCollection[i];
                    var cusID = details['cusId'];
                    var cusName = details['cusName'];

                    var itemDetails = details['dmoTItemEntityList'];
                    for(var x = 0; x<itemDetails.length; x++)
                    {
                        var items = itemDetails[x];
                        var itmCost = items['itmCost'];
                        var itmItem = items['itmItem'];
                        var itmQty = items['itmQty'];
                        var itmUnit = items['itmUnit'];

                        itemList += "itmCost: "+itmCost+" || itmItem: "+itmItem+" || itmQty: "+itmQty+" || itmUnit: "+itmUnit +"\n";
                    }

                    detailsList += "cusID: "+cusID+" || cusName: "+cusName+"\n Items -: \n"+itemList +"\n";
                    itemList = "";
                }

                alert(detailsList);

            });
        }

    </script>

    <title>Customer Page</title>
</head>
<body>

<label for="cusName">Customer Name :</label><br>
<input type="text" name="cusName" id="cusName"><br><br>
<label for="itemName">Item Name :</label><br>
<input type="text" name="itemName" id="itemName"><br><br>
<label for="itemCost">Item Cost :</label><br>
<input type="text" name="itemCost" id="itemCost"><br><br>
<label for="itemUnit">Item Unit :</label><br>
<input type="text" name="itemUnit" id="itemUnit"><br><br>
<label for="itemQty">Item Quantity :</label><br>
<input type="text" name="itemQty" id="itemQty"><br><br>

<button type="button" onclick="saveDetails()">Save</button><br><br>
<button type="button" onclick="showDetails()">Show Details</button>

</body>
</html>

Now right click on the package com.customer.controller and create a new java class as CustomerController. change it as below

CustomerController.java

package com.customer.controller;

import com.customer.domains.DmoTCustomerEntity;
import com.customer.domains.DmoTItemEntity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class CustomerController {

    @RequestMapping(value = "/customerPage",method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        return "customerPage";
    }

    @RequestMapping(value = "/saveDetails", method = RequestMethod.POST)
    public @ResponseBody
    JsonResponse saveDetails(@RequestParam("cusName") String cusName,@RequestParam("itemName") String itemName,@RequestParam("itemCost") String itemCost,@RequestParam("itemUnit") String itemUnit,@RequestParam("itemQty") String itemQty,HttpServletRequest request) {

        JsonResponse jsonResponse = new JsonResponse();

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        DmoTCustomerEntity dmoTCustomerEntity = new DmoTCustomerEntity();
        dmoTCustomerEntity.setCusName(cusName);
        session.save(dmoTCustomerEntity);

        DmoTItemEntity dmoTItemEntity = new DmoTItemEntity();
        dmoTItemEntity.setItmItem(itemName);
        dmoTItemEntity.setItmCost(Double.parseDouble(itemCost));
        dmoTItemEntity.setItmQty(Integer.parseInt(itemQty));
        dmoTItemEntity.setItmUnit(Double.parseDouble(itemUnit));
        dmoTItemEntity.setDmoTCustomerEntity(dmoTCustomerEntity);
        session.save(dmoTItemEntity);

        DmoTItemEntity dmoTItemEntitySecond = new DmoTItemEntity();
        dmoTItemEntitySecond.setItmItem("Item Second");
        dmoTItemEntitySecond.setItmCost(Double.parseDouble(itemCost));
        dmoTItemEntitySecond.setItmQty(Integer.parseInt(itemQty));
        dmoTItemEntitySecond.setItmUnit(Double.parseDouble(itemUnit));
        dmoTItemEntitySecond.setDmoTCustomerEntity(dmoTCustomerEntity);
        session.save(dmoTItemEntitySecond);

        session.getTransaction().commit();

        jsonResponse.setServerMessage("Successfully Saved");

        return jsonResponse;
    }

    @RequestMapping(value = "/showDetails", method = RequestMethod.GET)
    public @ResponseBody
    JsonResponse showDetails(HttpServletRequest request) {
        JsonResponse jsonResponse = new JsonResponse();

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Criteria criteria = session.createCriteria(DmoTCustomerEntity.class);
        List<DmoTCustomerEntity> dmoTCustomerEntity = criteria.list();

        jsonResponse.setDataCollection(dmoTCustomerEntity);

        return jsonResponse;
    }

}

Now project hierarchy should be like below 



To run this project first we need to configure Maven and JBoss in the intellij idea. To do that follow below instructions.

Click on the marked drop down arrow and select Edit Configurations.


 In the left side of panel click on the + sign and add Maven. Change the maven properties as below
 

Click apply.

Again click on the + sign and select JBoss Server and click on Local. For Application Sever give your JBoss home location and change other options as below


Click on the Deployment tab of JBoss module and click on + sign and add war file as a artifact



Now first build system from Maven and Run it from JBoss. You will get final result as below



Download Source Code from here

Wednesday, September 14, 2016

Show alertdialog from a service in Android




Use this code segment in your service

AlertDialog alertDialog;     
  AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getBaseContext());

    alertBuilder.setTitle("New Approvals Alert")
                       .setMessage("You have " + jObj.length() + " new transactions for your approvals")
                       .setCancelable(false)
                       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                });
                        

alertDialog = alertBuilder.create();
                                      alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();

Add this permission to your AndroidManifest.xml

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

 

Get more from  : http://techprogramme.com/

Monday, June 20, 2016

RESTful Web Services(JAX-RS) in JavaEE with IntelliJ IDEA

What Are RESTful Web Services?

RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.

Create a new JavaEE Web Module 

File - New Project - Select JavaEE Web Module 




In the IntelliJ IDEA, the RESTful Web Services development is based on the Java EE: RESTful Web Services (JAX-RS) plugin. Usually this plugin is bundled with IntelliJ IDEA and enabled by default.
To check whether plugin is enable or not go to Setting Dialog (Ctrl+Alt+S), from the left hand side select Plugins, After that type restful in the search box and check whether Java EE: RESTful Web Services (JAX-RS) is selected. if it's not make sure to enable that.

To add JAX-RS to the project right click on the project and click on Add Framework Support and put a tick to Restful Web Service element and make sure to select Download option to download the required libraries, and press OK



After that again right click on the project and click Open Module Settings - Go to libraries and click on the Change Version button and select jax-rs-jersey-1.12 and click OK. In the latest Jersey library HttpServerFactory class is not included but in this example we are using that class to create the server therefor we need to change the version in to jax-rs-jersey-1.12.



Now lets create the Restful Server

First Create a Class called CompanyDetails and modify it as below, This class we are using as a Data Model to return a details object.

/**
 * Created by easywayforcoadings on 6/20/16.
 */
public class CompanyDetails {

    private String welcomeMessage;
    private String companyName;
    private String companyAddress;
    private Integer companyPhone;

    public String getWelcomeMessage() {
        return welcomeMessage;
    }

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getCompanyAddress() {
        return companyAddress;
    }

    public void setCompanyAddress(String companyAddress) {
        this.companyAddress = companyAddress;
    }

    public int getCompanyPhone() {
        return companyPhone;
    }

    public void setCompanyPhone(int companyPhone) {
        this.companyPhone = companyPhone;
    }
}


Create a new Class Called RestServer and change it as below Code Segment. This is the class we are going to use as the Server.

/**
 * Created by easywayforcoadings on 6/20/16.
 */

import com.sun.net.httpserver.HttpServer;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;

@Path("/company_service/{username}")
public class RestServer {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public CompanyDetails getCompanyDetails(@PathParam("username") String userName) {

        CompanyDetails companyDetails = new CompanyDetails();
        companyDetails.setWelcomeMessage("Hello "+userName);
        companyDetails.setCompanyName("MY COMPANY PVT");
        companyDetails.setCompanyAddress("No. 111/1, MY ADDRESS");
        companyDetails.setCompanyPhone(123456789);
        return companyDetails;
    }

    public static void main(String[] args) throws IOException {

        HttpServer server = HttpServerFactory.create("http://localhost:9998/");
        server.start();

        System.out.println("Server running");
        System.out.println("Visit: http://localhost:9998/company_service/[userName]'");
        System.out.println("Hit return to stop...");
        System.in.read();
        System.out.println("Stopping server");
        server.stop(0);
        System.out.println("Server stopped");
    }
}

After that Save All, right click on the RestServer Class and click on Run 'RestServer.Main()' to start the server

Open the browser and check whether service is working or not via this address 

http://localhost:9998/company_service/easywayforcoadings123


Stop the server and lets create a Client to access our Restful Service

In the same project create a new Class called RestClient and change it as below 

/**
 * Created by easywayforcoadings on 6/20/16.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RestClient {

    public static void main(String[] argv) {

        try {

            URL url = new URL("http://localhost:9998/company_service/easywayforcoadings123");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Json Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }


    }
}

Save All and Right click on the RestServer to start the server first by clicking on Run 'RestServer.Main()' and finally right click on the RestClient and click on Run 'RestClient .Main()'


Output Result -:



Get more from  : http://techprogramme.com/



Wednesday, May 25, 2016

Factory Pattern With Reflection



An important aspect of software design is the manner in which objects are created, although far more time is often spent considering the object model and object interaction. But if this simple design (of object creation) aspect is ignored, it will adversely impact the entire system. Thus, it is not only important what an object does or what it models, but also in what manner it was created. 
Factory pattern is one of the most widely used pattern for these kind of situations. In this article lets see how to use Factory pattern with Reflection.  

What is Reflection ? 

Reflection provides objects (of type Type) that describe assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. 

Example -: 

int
 i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

Output -: System.Int32


Factory pattern without Reflection

------------------- IFruit Interface (IFruit.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    interface IFruit
    {
        string Name { get; }

        void eatMe();

        void donEatMe();
    }
}

------------------- Apple Class(Apple.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Apple: IFruit
    {

        public string Name
        {
            get { return "I am an Apple"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Apple -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Apple -: Don't eat me, I'm not a good fruit");
        }
    }
}


------------------- Orange Class(Orange.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Orange : IFruit
    {
        public string Name
        {
            get { return "I am an Orange"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Orange -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Orange -: Don't eat me, I'm not a good fruit");
        }
    }
}

------------------- Kiwi Class(Kiwi.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Kiwi : IFruit
    {
        public string Name
        {
            get { return "I am a Kiwi"; }
        }

        public void eatMe()
        {
            Console.WriteLine("Kiwi -: Eat me, I'm very delicious");
        }

        public void donEatMe()
        {
            Console.WriteLine("Kiwi -: Don't eat me, I'm not a good fruit");
        }
    }
}


------------------- NoFruit Class(NoFruit.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class NoFruit:IFruit
    {
        public string Name
        {
            get { return "I am not a Fruit"; }
        }

        public void eatMe()
        {
            Console.WriteLine("You can't eat me");
        }

        public void donEatMe()
        {
            Console.WriteLine("You can't eat me");
        }
    }
}



------------------- FruitFactory Class(FruitFactory.cs) ---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class FruitFactory
    {
        public static IFruit getFruit(string fruitName)
        {
            switch (fruitName)
            {
                case "Orange":
                    return new Orange();
                 
                case "Apple":
                    return new Apple();
               
                case "Kiwi":
                    return new Kiwi();
             
                default:
                    return new NoFruit();
                 
            }

        }
    }
}


------------------- Program Class(Program.cs) ---------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            IFruit myFruit = FruitFactory.getFruit("Orange");
            Console.WriteLine(myFruit.Name);
            myFruit.eatMe();          

            Console.ReadLine();
        }
    }
}


Factory pattern with Reflection

Change FruitFactory.cs and Program.cs Classes as below


------------------- FruitFactory Class(FruitFactory.cs) ---------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class FruitFactory
    {
         Dictionary<string, Type> cars;

         public FruitFactory()
        {
            TypesToReturn();
        }

        public IFruit CreateInstance(string carName)
        {
            Type t = TypeToCreate(carName);

            if (t == null)
            {
                return new NoFruit();
            }
            else
            {
                return Activator.CreateInstance(t) as IFruit;
            }
        }

        public Type TypeToCreate(string carName)
        {
            foreach (var car in cars)
            {
                if (car.Key.Contains(carName.ToUpper()))
                {
                    return cars[car.Key];
                }
            }
            return null;
        }

        public void TypesToReturn()
        {
            cars = new Dictionary<string, Type>();

            Type[] typesInCurrentAssembly = Assembly.GetExecutingAssembly().GetTypes();

            foreach (Type type in typesInCurrentAssembly)
            {
                if(type.GetInterface(typeof(IFruit).ToString()) != null)
                {
                    cars.Add(type.Name.ToUpper(), type);
                }
            }
        }
    }
}


------------------- Program Class(Program.cs) ---------------------

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryWithReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            FruitFactory fruitFactory = new FruitFactory();

            IFruit myfruit = fruitFactory.CreateInstance("Orange");

            Console.WriteLine(myfruit.Name);
            myfruit.eatMe();
            //myfruit.donEatMe();

            Console.ReadLine();

        }
    }
}