December 26, 2017

Consumerfed Triveni Kozhikode Region Budget creation software

Budget creating software developed for consumerfed kozhikode region price controlling officer





This is the way how we create budget for the next month using java software..



http://javabelazy.blogspot.in/

November 28, 2017

Permutation of String - Java code interview questions

package com.belazy.uber;
import java.util.HashSet;
import java.util.Set;

/**
 * Permutations for AAC are:
[AAC, ACA, CAA]
 * @author monica spear
 *
 */
public class PermutationString {
    public static Set<String> permutationFinder(String str) {
        Set<String> perm = new HashSet<String>();
        //Handling error scenarios
        if (str == null) {
            return null;
        } else if (str.length() == 0) {
            perm.add("");
            return perm;
        }
        char initial = str.charAt(0); // first character
        String rem = str.substring(1); // Full string without first character
        Set<String> words = permutationFinder(rem);
        for (String strNew : words) {
            for (int i = 0;i<=strNew.length();i++){
                perm.add(charInsert(strNew, initial, i));
            }
        }
        return perm;
    }

    public static String charInsert(String str, char c, int j) {
        String begin = str.substring(0, j);
        String end = str.substring(j);
        return begin + c + end;
    }

    public static void main(String[] args) {
        String s = "AAC";
        String s1 = "ABC";
        String s2 = "ABCD";
        System.out.println("\nPermutations for " + s + " are: \n" + permutationFinder(s));
       System.out.println("\nPermutations for " + s1 + " are: \n" + permutationFinder(s1));
       System.out.println("\nPermutations for " + s2 + " are: \n" + permutationFinder(s2));
    }
}

November 20, 2017

Rest call to Java Json sample program

Getting JSON Response from Rest Call in java

Description

This is a rest service call in java. The rest service which returns josn as response is saved to Java Object through Object Mapper API. The Object Mapper is very simple to use


/**
 *  Json to Java using Object Mapper
 */
package com.belazy.rest;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author itsection kozhikode
 *
 */
public class JsonMapper {

/**
* @param args
* @throws IOException
* @throws JsonMappingException
* @throws JsonGenerationException
*/
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
// TODO Auto-generated method stub

ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("bmw","blue");
File resultFile = new File("d://belazy.json");
objectMapper.writeValue(resultFile, car);

ComputerDetails comp = objectMapper.readValue(new URL("http://ip.jsontest.com"), ComputerDetails.class);
System.out.println(comp.getIp());

JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class);
System.out.println("jsonkey.getOne() : "+jsonkey.getOne());

}





}


computerdetails.class




/**
 *
 */
package com.belazy.rest;

/**
 * @author belazy
 *
 */
public class ComputerDetails {

String ip;

/**
* @return the ip
*/
public String getIp() {
return ip;
}

/**
* @param ip the ip to set
*/
public void setIp(String ip) {
this.ip = ip;
}


}

jsonkey.class


package com.belazy.rest;
public class JsonKey
{
    private String one;

    private String key;

    public String getOne ()
    {
        return one;
    }

    public void setOne (String one)
    {
        this.one = one;
    }

    public String getKey ()
    {
        return key;
    }

    public void setKey (String key)
    {
        this.key = key;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [one = "+one+", key = "+key+"]";
    }
}

java api needed



jackson annotation jar
jackson core
jackson databind



Output



86.99.219.5
jsonkey.getOne()two

November 19, 2017

How to deal with SSL Handshake exception

/**
 * Consuming a Rest application
 */
package com.belazy.rest;

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

/**
 * @author belazy
 *
 * This program I dedicate to my Tech Arc
 * she wish be a data scientist
 * Hope she will achieve it in the nearest days.
 *
 */
public class RestConsumer {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

String theUrl = "https://jsonplaceholder.typicode.com/posts";

try {
URL url = new URL(theUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

System.out.println(conn.getResponseCode());

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


/**
 * 
 */
package com.belazy.rest;

/**
 * @author belazy
 *
 */
public class Post {
private String userId;
private String id;
private String title;
private String body;

/**
* @return the userId
*/
public String getUserId() {
return userId;
}

/**
* @param userId the userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}

/**
* @return the id
*/
public String getId() {
return id;
}

/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}

/**
* @return the title
*/
public String getTitle() {
return title;
}

/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}

/**
* @return the body
*/
public String getBody() {
return body;
}

/**
* @param body the body to set
*/
public void setBody(String body) {
this.body = body;
}

}





Exception in thread "main" javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.recvAlert(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.belazy.rest.RestConsumer.main(RestConsumer.java:38)

November 08, 2017

Understanding garbage collection in java

Understanding garbage collection in java





https://stackify.com/memory-leaks-java/

http://javabelazy.blogspot.in/

November 04, 2017

Comparing Java Webservices JAX-WS with Spring WS

Conclusion

 Considering contract-first web services, my little experience has driven me to choose JAX-WS in favor of Spring WS: testing benefits do not balance the ease-of-use of the standard. I must admit I was a little surprised by these results since most Spring components are easier to use and configure than their standard counterparts, but results are here.
  Link
 http://javabelazy.blogspot.in/

October 30, 2017

Adding google map to Java Server Page to show the location of your business

Adding google map with markers in to website

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
        <title>Branch Details</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <link rel="stylesheet" type="text/css" href="../CSS/branchForm.css"/>
        <link href="CSS/jquery-ui.css" rel="stylesheet">
        <script type="text/javascript" src="JS/jquery.ui.datepicker.js"></script>
        <script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
        <link href="CSS/style.css" rel="stylesheet">
     
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>

    </head>
    <body> 
        <form action="" class="register">
        <!--
            <h1>Branch Registration</h1>
            <fieldset class="row1">
                <legend>Account Details
                </legend>
                <p>
                    <label>Category
                    </label>
                    <input type="text"/>
                    <label>Firm Code
                    </label>
                    <input type="text"/>
                </p>
                <p>
                    <label>Name
                    </label>
                    <input type="text"/>
                    <label>Constituency
                    </label>
                    <input type="text"/>
                    <label class="obinfo">* mandatory fields
                    </label>
                </p>
            </fieldset>
             -->
            <fieldset class="row2">
           
                <legend>Branch Details
                </legend>
             
                <p>
                    <label>Name
                    </label>
                    <input type="text"/>
                </p>
             
                <p>
                    <label>Firm Code
                    </label>
                    <input type="text"/>
                </p>
             
                <p>
                    <label>Category
                    </label>
                    <input type="text"/>
                </p>
           
             
                <p>
                    <label>Constituency
                    </label>
                    <input type="text"/>
               
                </p>
             
                <p>
                    <label>Address *
                    </label>
                    <input type="text" class="long"/>
                </p>
                <p>
                    <label>Location *
                    </label>
                    <input type="text" id="pac-Input" placeholder ="Enter your location"  />
                </p>

                <p>
                    <label>City *
                    </label>
                    <input type="text" class="long" id="cityTxt"/>
                </p>
                <!--
                <p>
                    <label>Country *
                    </label>
                    <select>
                        <option>
                        </option>
                        <option value="1">United States
                        </option>
                    </select>
                </p>
                -->
                <p>
                    <label>Inauguration Date *
                    </label>
                    <input type="text" maxlength="10" id="datepicker"/>
                </p>
                 <p>
                    <label>Lat *
                    </label>
                    <input type="text" maxlength="2" id="latBox" />
                    </p>
                    <p>
                    <label>Lon *
                    </label>
                    <input type="text" maxlength="2" id="lngBox" />
                </p>
             
                <p>
                    <label class="optional">Website
                    </label>
                    <input class="long" type="text" value="http://"/>

                </p>
            </fieldset>
            <fieldset class="row3">
                <legend>Branch Location
                </legend>
                <!--
                <p>
                    <label>Gender *</label>
                    <input type="radio" value="radio"/>
                    <label class="gender">Male</label>
                    <input type="radio" value="radio"/>
                    <label class="gender">Female</label>
                </p>
             
                -->
                  <!--
                <p>
                    <label>Inaugration date
                    </label>
                    <select class="date">
                        <option value="1">01
                        </option>
                        <option value="2">02
                        </option>
                        <option value="3">03
                        </option>
                        <option value="4">04
                        </option>
                        <option value="5">05
                        </option>
                        <option value="6">06
                        </option>
                        <option value="7">07
                        </option>
                        <option value="8">08
                        </option>
                        <option value="9">09
                        </option>
                        <option value="10">10
                        </option>
                        <option value="11">11
                        </option>
                        <option value="12">12
                        </option>
                        <option value="13">13
                        </option>
                        <option value="14">14
                        </option>
                        <option value="15">15
                        </option>
                        <option value="16">16
                        </option>
                        <option value="17">17
                        </option>
                        <option value="18">18
                        </option>
                        <option value="19">19
                        </option>
                        <option value="20">20
                        </option>
                        <option value="21">21
                        </option>
                        <option value="22">22
                        </option>
                        <option value="23">23
                        </option>
                        <option value="24">24
                        </option>
                        <option value="25">25
                        </option>
                        <option value="26">26
                        </option>
                        <option value="27">27
                        </option>
                        <option value="28">28
                        </option>
                        <option value="29">29
                        </option>
                        <option value="30">30
                        </option>
                        <option value="31">31
                        </option>
                    </select>
                    <select>
                        <option value="1">January
                        </option>
                        <option value="2">February
                        </option>
                        <option value="3">March
                        </option>
                        <option value="4">April
                        </option>
                        <option value="5">May
                        </option>
                        <option value="6">June
                        </option>
                        <option value="7">July
                        </option>
                        <option value="8">August
                        </option>
                        <option value="9">September
                        </option>
                        <option value="10">October
                        </option>
                        <option value="11">November
                        </option>
                        <option value="12">December
                        </option>
                    </select>
                 
                    <input class="year" type="text" size="4" maxlength="4"/>e.g 1976
                </p>
             
           
                <p>
                    <label>Nationality *
                    </label>
                    <select>
                        <option value="0">
                        </option>
                        <option value="1">United States
                        </option>
                    </select>
                </p>
               
                <p>
                    <label>Children *
                    </label>
                    <input type="checkbox" value="" />
                </p>
             
                <img src="../IMAGES/googleMap.jpg" style="width:398px;height:209px;">
                -->
                <div id="map"></div>
    <script>
      function initMap() {
        var mapDiv = document.getElementById('map');
       
        var map = new google.maps.Map(mapDiv, {
          center: {lat: 11.253069, lng: 75.78281},
          zoom: 12
        });
       
        var marker = new google.maps.Marker({
        position: {lat: 11.253069, lng: 75.78281},
        map: map,
        title: 'Triveni location',
        draggable: true
          });
       
        var locationInput = document.getElementById('pac-Input');
       
        google.maps.event.addListener(marker, 'dragend', function (event) {
        document.getElementById("latBox").value = this.getPosition().lat();
        document.getElementById("lngBox").value = this.getPosition().lng();
        //document.getElementById("cityTxt").value = locationInput;
        });
       
        var autocomplete = new google.maps.places.Autocomplete(locationInput);
        autocomplete.bindTo('bounds', map);
       
        var infowindow = new google.maps.InfoWindow();
       
          autocomplete.addListener('place_changed', function() {
          alert(" autocomplete add listener ");
         
            infowindow.close();
            //marker.setVisible(false);
            var place = autocomplete.getPlace();
            if (!place.geometry) {
              window.alert("Autocomplete's returned place contains no geometry");
              return;
            }
         
        var address = '';
            if (place.address_components) {
              address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
              ].join(' ');
            }

            infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
            infowindow.open(map, marker);
         
        });
       
       
          //});
        /*
        var input = document.getElementById('pacInput');
          var searchBox = new google.maps.places.SearchBox(input);
          map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
         
          searchBox.addListener('places_changed', function() {
            var places = searchBox.getPlaces();

            if (places.length == 0) {
              return;
            }
        */
       
      }
    </script>
   
                <!--
                <div class="infobox"><h4>Helpful Information</h4>
                    <p>Here comes some explaining text, sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
                </div>
                -->
            </fieldset>
            <fieldset class="row4">
                <legend> blah blah blah...
                </legend>
                <p class="agreement">
                    <input type="checkbox" value=""/>
                    <label>*  Is the <a href="#">unit currently working</a></label>
                </p>
                <!--
                <p class="agreement">
                    <input type="checkbox" value=""/>
                    <label>I want to receive personalized offers by your site</label>
                </p>
                <p class="agreement">
                    <input type="checkbox" value=""/>
                    <label>Allow partners to send me personalized offers and related services</label>
                </p>
                -->
            </fieldset>
            <div><button class="button">Register &raquo;</button></div>
        </form>
    </body>
</html>


How to enable database cache in my java application

https://stackoverflow.com/questions/47004240/how-to-enable-database-cache-in-my-java-application


October 26, 2017

Sample Mysql Trigger on product inventory


Sample Mysql Trigger on product inventory


DELIMITER $$

DROP TRIGGER /*!50032 IF EXISTS */ `db_inventory_datacom`.`UpdateInventoryOnSalesReturn`$$

CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `UpdateInventoryOnSalesReturn` AFTER INSERT ON `tbl_prdt_sales_returns`
    FOR EACH ROW begin
update tbl_inventories set prod_quantity=(prod_quantity + new.prdt_quantity),prod_reorder_date=curdate() where prod_id=new.prod_id;
    END;
$$

DELIMITER ;

The event triggers when ever a new row is inserted in  the table `tbl_prdt_sales_returns`.

The trigger will update the table  tbl_inventories  product quantity .

October 22, 2017

Real Time Currency Converter in java - Webservice

Currency Converter API (xe.com)


Description


some time instead of keeping currency rate converter static data in your local database is not at all feasible for your project. Yahoo is providing a free web sevices for currency rate converter similar to google xe.com. The below code will return the currency converting ratio

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 *
 */

/**
 * @author currency conversion
 *
 */
public class DCSCurrencyConvertor {



/**
* @param args
* @throws IOException
* @throws HttpException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub;

DCSCurrencyConvertor convertor = new DCSCurrencyConvertor();
try {
String rate = convertor.convert("USD","AED");
System.out.println("USD to AED :"+rate);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}





}

private String convert(String currencyFrom, String currencyTo) throws HttpException, IOException {
String currentRate = null;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://quote.yahoo.com/d/quotes.csv?s=" + currencyFrom + currencyTo + "=X&f=l1&e=.csv");
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    new DefaultHttpMethodRetryHandler(3, false));
int status = client.executeMethod(method);
System.out.println("status : "+status);

byte[] response = method.getResponseBody();
currentRate =new String(response);

return currentRate;
}

}

Jar files (Application Programming Interface)

commons-httpclient-3.1.jar
commons-codec-1.11.jar


Uri (Uniform Resource locator )


http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR%22,%20%22USDJPY%22,%20%22USDBGN%22,%20%22USDCZK%22,%20%22USDDKK%22,%20%22USDGBP%22,%20%22USDHUF%22,%20%22USDLTL%22,%20%22USDLVL%22,%20%22USDPLN%22,%20%22USDRON%22,%20%22USDSEK%22,%20%22USDCHF%22,%20%22USDNOK%22,%20%22USDHRK%22,%20%22USDRUB%22,%20%22USDTRY%22,%20%22USDAUD%22,%20%22USDBRL%22,%20%22USDCAD%22,%20%22USDCNY%22,%20%22USDHKD%22,%20%22USDIDR%22,%20%22USDILS%22,%20%22USDINR%22,%20%22USDKRW%22,%20%22USDMXN%22,%20%22USDMYR%22,%20%22USDNZD%22,%20%22USDPHP%22,%20%22USDSGD%22,%20%22USDTHB%22,%20%22USDZAR%22,%20%22USDISK%22)&env=store://datatables.org/alltableswithkeys


Thanks to steffi for her support

October 19, 2017

Java Real Time currency convertor

import java.io.IOException;



/**
 *
 */

/**
 * @author belazy
 *
 */
public class CurrencyConvertor {

   public float convert(String currencyFrom, String currencyTo) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://quote.yahoo.com/d/quotes.csv?s=" + currencyFrom + currencyTo + "=X&f=l1&e=.csv");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpGet, responseHandler);
        httpclient.getConnectionManager().shutdown();
        return Float.parseFloat(responseBody);
    }

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

CurrencyConvertor cc = new CurrencyConvertor();
try {
            float current = cc.convert("USD", "AED");
            System.out.println(current);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

}

}

October 17, 2017

Find Mean Mode and Median in Java : Introduction to Data Science

import java.util.Arrays;

/**
 * Introduction to Data science
 * Finding Mean Mode and Median
 */

/**
 * @author belazy
 * Consumerfed triveni supermarket kozhikode
 *
 */
public class DataScienceLessonOne {

Integer[] arraySample = {4,5,3,3,5,6,7,3,1,5};

/**
* @param args
*/
public static void main(String[] args) {

DataScienceLessonOne dataScience = new DataScienceLessonOne();
System.out.println(dataScience.findMean());
System.out.println(dataScience.findMedian());
System.out.println(dataScience.findMode());

}

private char[] findMode() {
// TODO Auto-generated method stub
return null;
}

private float findMedian() {
// TODO Auto-generated method stub
float median = 0;
Arrays.sort(arraySample);

median = (arraySample.length % 2) == 0 ? (arraySample[arraySample.length/2]+arraySample[(arraySample.length/2)-1])/2 :arraySample[arraySample.length/2];


return median;
}

private float findMean() {
int sum = 0;
float mean = 0;
for(int a:arraySample){
sum = sum +a;
mean = sum/arraySample.length;
}
return mean;
}

}

October 09, 2017

Bithesh Information Manager K S C C F Ltd Kozhikode regional office


Consumerfed Regional office kozhikode Region IT Section

à´¸ീസണൽ à´±ിà´ª്à´ªോർട്













à´¸ീസണൽ à´±ിà´ª്à´ªോർട്







Contact us @ 8281808025/9



October 03, 2017

Collection list to simple Array convert in java

/**
 * Sample java programs
 */
package com.belazy.misc;

import java.util.ArrayList;
import java.util.List;

/**
 * @author belazy
 *
 */
public class SampleArrays {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

List<Integer> sampleList = new ArrayList<Integer>();

for(int i=0;i<=10;i++){
sampleList.add(i);
}


/**
* Arrays
*/
Integer[] a= new Integer[sampleList.size()];
a= sampleList.toArray(a);
System.out.println("5 th element in the array "+a[5]);

}

}

A small description


Arrays are treated as object in JVM
Type of array - The elementType has to specified (say Integer)
The size of the array should be on the stack before the operation is performed
Example :-
Int[] javaArraySample = new int [12];

September 30, 2017

Most and longest running software developed for consumerfed

Dear readers,

It has been two and a half years since the application is launched at consumerfed kozhikode region and successfully running in the region at 40 trivenis including mobile , godown, neethi medicasl sections and liquor shop.
The whole credit for developing the software goes to the IT section regional office ( Management trainees) But now consumerfed is planning to reduce the size of Management trainees

A great that to I T Section kozhikode.


The project was launched on March 2015 and last updated on September 2017. Report to mobiles are also available now. Backup s are automated

E mail report
footer
Tracking the sales , subsidy monitoring, tracking hardware details are other key features of the application. Reports in html , pdf formats are available, video tutorials are available in youtube channel.


You can contact us on 0091-8218808029

Join us at linkedin  follow us  Hangout group


Mobile phone cover - Buy one Hurry !!! 


September 27, 2017

How to use same method for different objects in java

/**
 *  Main class
 */
package com.belazy.generics;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author belazy
 * @param <T>
 *
 */
public class GenericMethodClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericMethodClass g = new GenericMethodClass();

String type ="type";

Employee emp = new Employee();
Student stud = new Student();
g.returnText(emp, type);
g.returnText(stud, type);

}



public <T> String returnText(T element , String type){
String value = null;
try {
Class thisClass = element.getClass();

type = element.getClass().toString();
Method method = thisClass.getMethod("getName");
System.out.println("method with getName "+method.getName());
System.out.println(method.invoke(element));
if(method.invoke(element).toString().equalsIgnoreCase("type")){
System.out.println("inside if ");
Method method2 = thisClass.getMethod("getText");
System.out.println(method2.invoke(element));
value = method2.invoke(element).toString();
}


} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


System.out.println(type);
return value;


}

}

Student class

/**
 *
 */
package com.belazy.generics;

/**
 * @author belazy
 *
 */
public class Student {

String name = "type";
String text = "Student Type";
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}



}

Employee Class

/**
 * 
 */
package com.belazy.generics;

/**
 * @author belazy
 *
 */
public class Employee {
String name = "type";
String text = "employee Type";
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}

}


September 25, 2017

Difference between maps in java - Hash and Tree map

/**
 *
 */
package com.belazy.misc;

import java.util.HashMap;
import java.util.TreeMap;

/**
 * @author belazy
 *
 */
public class CollectionMaps {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CollectionMaps colMap = new CollectionMaps();
colMap.callHashMap();
colMap.callTreeMap();

}

private void callTreeMap() {
// TODO Auto-generated method stub
System.out.println("Inside Tree Map");
TreeMap<Integer, String> studentDetails = new TreeMap<Integer, String>();
studentDetails.put(10, "sachin");
studentDetails.put(7, "jadeja");
studentDetails.put(5, "dhoni");
studentDetails.put(1, "virat");
studentDetails.put(3, "saurav");
System.out.println("data in map "+studentDetails);
System.out.println("reverse order :"+studentDetails.descendingMap());
System.out.println("descending key sets : "+studentDetails.descendingKeySet());
System.out.println("first Entry "+studentDetails.firstEntry());
}

private void callHashMap() {
// TODO Auto-generated method stub
System.out.println("Inside Hash Map");
HashMap<Integer, String> studentDetails = new HashMap<Integer, String>();

studentDetails.put(10, "sachin");
studentDetails.put(7, "jadeja");
studentDetails.put(5, "dhoni");
studentDetails.put(1, "virat");
studentDetails.put(3, "saurav");

System.out.println(studentDetails);


}

}

Facebook comments