Sunday, 30 October 2016

Enumerations in Java


The Enumerated data type gives you an opportunity to invent your own data type and define what values the variable of this data type can take.As an Example, one could invent a data type called MaritalStatus which can have four possible values – Single , Married, Divorced or Widowed.

enum Season { WINTER, SPRING, SUMMER, FALL }  

class EnumExample1
{  
// public enum Season { WINTER, SPRING, SUMMER, FALL }  
  
public static void main(String[] args) 
{  
for (Season s : Season.values())  
System.out.println(s);  
 }}  


Another One Example:

enum Department
{
  Assemblly, Manufacturing,Accounts,Stores
}

class Employee
{
  private String name;
  private int age;
  private float salary;
  private Department dept;
  
  public Employee(String n, int a, float s, Department d)
  {
    name = n;
    age = a;
    salary = s;
    dept = d;
  }
  
  public void DisplayData()
  {
    System.out.println(name+ "   " +age+ "   " +salary + "  " +dept  );
    if(dept == Department.Accounts)
          System.out.println(name +" is an Acountant.");
    else
                System.out.println(name +" is not an Acountant.");
  }
}

public class main
{
  public static void main(String[] args)
  {
    Employee e = new Employee("Sagan",28,15555.75f,Department.Accounts);
    e.DisplayData();
  }
}

Tuesday, 25 October 2016

Understanding Big Data



Understanding Big Data      
      
        Over time, Hadoop has become the nucleus of the Big Data ecosystem, where many new technologies have emerged and become integrated with Hadoop. So it’s important that, first, we understand and appreciate the nucleus of modern Big Data architecture.

      The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers, using simple  programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage.

Components of the Hadoop Ecosystem
       Let's begin by looking at some of the components of the Hadoop ecosystem:

Hadoop Distributed File System (HDFS™):

       This is a distributed file system that provides high-throughput access to application data. Data in a Hadoop cluster is broken down into smaller pieces (called blocks) and distributed throughout the cluster. In this method, the map and reduce functions can be executed on smaller subsets of your larger data sets, and this provides the scalability needed for Big Data processing.

MapReduce  
       MapReduce is a programming model specifically implemented for processing large data sets on Hadoop cluster. This is the core component of the Hadoop framework, and it is the  only execution engine available for Hadoop 1.0.
The MapReduce framework consists of two parts:
        
          A function called ‘Map’, which allows different points in the distributed cluster to distribute their work.
        
           A function called ‘Reduce’, which is designed to reduce the final form of the clusters’ results into one output.
        
           The main advantage of the MapReduce framework is its fault tolerance, where periodic reports from each node in the cluster are expected as soon as the work is completed.

    The MapReduce framework is inspired by the ‘Map’ and ‘Reduce’ functions used in functional programming. The computational processing occurs on data stored in a file system or within a database, which takes a set of input key values and produces a set of output key values.

        Each day, numerous MapReduce programs and MapReduce jobs are executed on
Google's clusters. Programs are automatically parallelized and executed on a large
cluster of commodity machines.

Map Reduce is used in distributed grep, distributed sort, Web link-graph reversal, Web access log stats, document clustering, Machine Learning and statistical machine translation.

Pig

Pig is a data flow language that allows users to write complex MapReduce operations in simple scripting language. Then Pig then transforms those scripts into a MapReduce job.

 Hive 

          Apache Hive data warehouse software facilitates querying and managing large datasets residing in distributed storage. Hive provides a mechanism for querying the data using a SQL-like language called HiveQL. At the same time, this language also allows traditional map/reduce programmers to plug in their custom mappers and reducers when it is inconvenient or inefficient to express this logic in HiveQL.

Sqoop

Enterprises that use Hadoop often find it necessary to transfer some of their data from traditional relational database management systems (RDBMSs) to the Hadoop ecosystem.
          Sqoop, an integral part of Hadoop, can perform this transfer in an automated fashion. Moreover, the data imported into Hadoop can be transformed with MapReduce before exporting them back to the RDBMS. Sqoop can also generate Java classes for programmatically interacting with imported data.

          Sqoop uses a connector-based architecture that allows it to use plugins to connect with external databases.

Flume

Flume is a service for streaming logs into Hadoop. Apache Flume is a distributed, reliable, and available service for efficiently collecting, aggregating, and moving large amounts of streaming data into the Hadoop Distributed File System (HDFS).


Storm 

Storm is a distributed, real-time computation system for processing large volumes of high-velocity data. Storm is extremely fast and can process over a million records per second per node on a cluster of modest size. Enterprises harness this speed and combine it with other data-access applications in Hadoop to prevent undesirable events or to optimize positive outcomes.

Kafka

Apache Kafka supports a wide range of use cases such as a general-purpose messaging system for scenarios where high throughput, reliable delivery, and horizontal scalability are important. Apache Storm and Apache HBase both work very well in combination with Kafka.

Oozie

Oozie is a workflow scheduler system to manage Apache Hadoop jobs. The Oozie Workflow jobs are Directed Acyclical Graphs (DAGs) of actions, whereas the Oozie Coordinator jobs are recurrent Oozie Workflow jobs triggered by time (frequency) and data availability.

Oozie is integrated with the rest of the Hadoop stack and supports several types of Hadoop jobs out of the box (such as Java map-reduce, Streaming map-reduce, Pig, Hive, Sqoop and Distcp) as well as system-specific jobs (such as Java programs and shell scripts).

Oozie is a scalable, reliable and extensible system.

Spark 

Apache Spark is a fast, in-memory data processing engine for distributed computing clusters like Hadoop. It runs on top of existing Hadoop clusters and accesses the Hadoop data store (HDFS).

Spark can be integrated with Hadoop’s 2 YARN architecture, but cannot be used with Hadoop 1.0.

NoSQL

The NoSQL database, also called Not Only SQL, is an approach to data management and database design that's useful for very large sets of distributed data. This database system is non-relational, distributed, open-source and horizontally scalable. NoSQL seeks to solve the scalability and big-data performance issues that relational databases weren’t designed to address.

Apache Cassandra  

Apache Cassandra is an open-source distributed database system designed for storing and managing large amounts of data across commodity servers. Cassandra can serve as both a real-time operational data store for online transactional applications and a read-intensive database for large-scale business intelligence (BI) systems.

Google’s BigTable

Google’s BigTable is a distributed, column-oriented data store created by Google Inc. to handle very large amounts of structured data associated with the company's Internet search and Web services operations.

BigTable was designed to support applications requiring massive scalability; from its first iteration, the technology was intended to be used with petabytes of data. The database was designed to be deployed on clustered systems and uses a simple data model that Google has described as "a sparse, distributed, persistent multidimensional sorted map."

Data is assembled in order by row key, and indexing of the map is arranged according to row, column keys, and timestamps. Here, compression algorithms help achieve high capacity.

MongoDB 

MongoDB is a cross-platform, document-oriented database. Classified as a NoSQL database, MongoDB shuns the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.
MongoDB is developed by MongoDB Inc. and is published as free and open-source software under a combination of the GNU Affero General Public License and the Apache License. As of July 2015, MongoDB is the fourth most popular type of database management system, and the most popular for document stores.

CouchDB 

CouchDB is a database that completely embraces the web. It stores your data with JSON documents. It accesses your documents and queries your indexes with your web browser, via HTTP. It indexes, combines, and transforms your documents with JavaScript.

CouchDB works well with modern web and mobile apps. You can even serve web apps directly out of CouchDB. You can distribute your data, or your apps, efficiently using CouchDB’s incremental replication. CouchDB supports master-master setups with automatic conflict detection.

HBase

Apache HBase (Hadoop DataBase) is an open-source NoSQL database that runs on the top of the database and provides real-time read/write access to those large data sets.
HBase scales linearly to handle huge data sets with billions of rows and millions of columns, and it easily combines data sources that use a wide variety of different structures and schemas. HBase is natively integrated with Hadoop and works seamlessly alongside other data access engines through YARN.

Neo4j

Neo4j is a graph database management system developed by Neo Technology, Inc. Neo4j is described by its developers as an ACID-compliant transactional database with native graph storage and processing. According to db-engines.com, Neo4j is the most popular graph database.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
       <meta name="description" content="">
    <meta name="author" content="">
<!--- <link rel="icon" href="../../favicon.ico"> -->

    <title>Importing CSV File to MySQL using PHP with Bootstrap Templates</title>

    <!-- Bootstrap core CSS -->
    <link href="dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link href="assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="dist/css/sticky-footer-navbar.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="assets/js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>

    <!-- Fixed navbar -->
    <nav class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Sivasankar</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="http://sivasankarmsccs.blogspot.in/">Home</a></li>
            <li><a href="http://sivasankarmsccs.blogspot.in/">About</a></li>
            <li><a href="http://sivasankarmsccs.blogspot.in/">Contact</a></li>
     
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>

    <!-- Begin page content -->
    <div class="container">
      <div class="page-header">

<h1>
Importing CSV File to MySQL using PHP <br /> with Bootstrap Templates.
</h1>

<div style="width:75%;">

  <div class="panel panel-primary">
    <div class="panel-heading" role="tab" id="headingOne">
      <h4 class="panel-title">
        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Import User Account
        </a>
      </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<form action="import_query.php" method="post" name="upload_excel" enctype="multipart/form-data">
<div>
<div class="col-xs-6">
<label>Import CSV/Excel File:</label>
<input type="file" class="form-control" multiple name="filename" id="filename">
<br />
<button type="submit" id="submit" class="btn btn-primary" name="submit" data-loading-text="Loading...">Upload</button>
</div>
</div>
</form>
</div>
    </div>
  </div>

<table class="table table-striped">
<tr>
<th>User Name</th>

<th>First Name</th>
<th>Last Name</th>
</tr>
<?php
include ('database.php');
$result= mysql_query("select * from user1 order by user_id ASC") or die (mysql_error());
while ($row= mysql_fetch_array ($result) ){
$id=$row['user_id'];
?>
<tr>
<td><?php echo $row['user_name']; ?></td>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['last_name']; ?></td>
</tr>
<?php } ?>
</table>
</div>

</div>

      </div>
    </div>

    <footer class="footer">
      <div class="container">
        <p class="text-muted">Copyright &copy; 2016, <a href="http://sivasankarmsccs.blogspot.in/">For More Refer this blog. </a> </p>
      </div>
    </footer>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="dist/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="assets/js/ie10-viewport-bug-workaround.js"></script>
  </body>
</html>


import_query.php


<?php
if (isset($_POST['submit']))
{
include('database.php');

//Import uploaded file to Database
$file_CSV = fopen($_FILES['filename']['tmp_name'], "r");

while (($data = fgetcsv($file_CSV, 1000, ",")) !== FALSE) {
mysql_query("INSERT into user1 (user_name, first_name, last_name, date_added)
values('$data[0]', '$data[1]', '$data[2]', NOW())");

}

fclose($file_CSV);

//print "Import done";
echo "<script type='text/javascript'>alert('Successfully Imported a CSV File for User!');</script>";
echo "<script>document.location='index.php'</script>";
//view upload form
}

?>

database.php

<?php
mysql_select_db('upload',mysql_connect('localhost','root','sagan'))or die(mysql_error());

?>

Output:




Monday, 24 October 2016

Java Program to Convert Number to Word



import java.util.Scanner;

public class Num_word
{
    public static void main(String args[])
    {
        String[] one = {"","One", "Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"};
        String[] two = {"Twenty","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","eighteen","nineteen"};
        String[] three = {"","","Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"};
     
        Scanner in = new Scanner(System.in);
     
        System.out.println("Enter the number: ");
        int number = in.nextInt();
     
        if(number == 0)
            System.out.println("Zero");
     
        else if(number < 11)
            System.out.println(one[number]);
     
        else if(number > 10 && number < 21)
            System.out.println(two[number%10]);
     
        else if(number > 20 && number < 1000)
        {
            int temp = number;
            int count = 0;
     
            while(temp != 0)
            {
                count++;
                temp = temp / 10;
            }
           
            if(count == 2)
            {
                System.out.print(three[number/10]+" ");
                System.out.println(one[number%10]);
            }
            else if(count == 3)
            {
                System.out.print(one[number/100]+" hundred and");
                number = number - ((number/100)*100);
                System.out.print(three[number/10]+" ");
                System.out.println(one[number%10]);
               
            }
        }
    }
}

Output:

    Input: 105

    Output: One hundred and Five

Sunday, 23 October 2016

Form Validation using Java Script


index.html

<!DOCTYPE html>   // represents HTML5
<html lang = "en">
<head>
<title>Registration Form using JavaScript</title>
<script src="form.js"></script>

</head>
<body>
<h1>Registration Form using JavaScript</h1>
<body onload="firstfocus();">

<form name ="Registration" method = "post" action = "#" >

User Id : <input type = "text" name = "uid" size = "12" onblur = "uid_validation(5,12)"required><span id = "uid">  </span><br><br>
Password : <input type = "password" name = "pass" size = "12" onblur = "pass_validation(7,12)"required> <span id = "pass"> </span><br><br>
User Name : <input type = "text" name = "uname"  onblur = "alpha_only()" required> <br><br>
Address : <textarea rows = '5' cols = '20' name = "address" onblur="alphanumeric()"></textarea> <br><br>
Country : <select name = "country" onblur = "select_country()">
<option selected ="" value = "Default"> (Please Select a Country)</option>
<option value="IND"> India </option>
<option value ="US"> USA </option>
<option value ="UK"> UK </option>
</select>

ZIP Code : <input type = "text" name = "zip" onblur = "number_only()"></input><br><br>

Email : <input type = "text" name = "email" onblur = "email_validate()"></input><br><br>

Sex : <input type = "radio" name = "gender" value = "Male" checked> <span> Male </span>
<input type = "radio" name = "gender" value = "Female"> <span> Female </span><br><br>

Language : <input type = "checkbox" name = "en" value = "en" checked><span> English</span>
<input type = "checkbox" name = "non" value = "non" checked><span> Non English</span><br><br>

Description : <textarea name = "desc" rows = '10' cols = '10'></textarea><br><br>

<input type = "Button" name = "btn" value = "Click" onclick="alert('Form submitted successfully')">

</div>
</body>
</html>


form.js

// After form loads focus will go to User id field.
function firstfocus()
{
var uid = document.registration.userid.focus();
return true;
}

// This function will validate User id.
function userid_validation(mx,my)
{
var uid = document.registration.userid;
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
uid.focus();
return false;
}
// Focus goes to next field i.e. Password.
document.registration.passid.focus();
return true;
}

// This function will validate Password.
function passid_validation(mx,my)
{
var passid = document.registration.passid;
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+" to "+my);
passid.focus();
return false;
}
// Focus goes to next field i.e. Name.
document.registration.username.focus();
return true;
}

// This function will validate Name.
function allLetter()
var uname = document.registration.username;
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
// Focus goes to next field i.e. Address.
document.registration.address.focus();
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}

// This function will validate Address.
function alphanumeric()
var uadd = document.registration.address;
var letters = /^[0-9a-zA-Z]+$/;
if(uadd.value.match(letters))
{
// Focus goes to next field i.e. Country.
document.registration.country.focus();
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}

// This function will select country name.
function countryselect()
{
var ucountry = document.registration.country;
if(ucountry.value == "Default")
{
alert('Select your country from the list');
ucountry.focus();
return false;
}
else
{
// Focus goes to next field i.e. ZIP Code.
document.registration.zip.focus();
return true;
}
}

// This function will validate ZIP Code.
function allnumeric()
var uzip = document.registration.zip;
var numbers = /^[0-9]+$/;
if(uzip.value.match(numbers))
{
// Focus goes to next field i.e. email.
document.registration.email.focus();
return true;
}
else
{
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}

// This function will validate Email.
function ValidateEmail()
{
var x=document.myform.email.value;  
var atposition=x.indexOf("@");  
var dotposition=x.lastIndexOf(".");  
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){  
  alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);  
  return false;  
  }  



Encapsulation Program in Java




Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

  1. We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
  2. The Java Bean class is the example of fully encapsulated class.
  3. By providing only setter or getter method, you can make the class read-only or write-only.
  4. It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.



Example Program:

EncapsulationTest .java

import java.util.*;

public class EncapsulationTest
{
  public static void main(String[] args)
  {
    Scanner scan  = new Scanner(System.in);
    String name = scan.nextLine();
     String designation = scan.nextLine();
      String department = scan.nextLine();
      
    Student s = new Student();
    
    s.setName(name);
    s.setDesig(designation);
    s.setDepart(department);
    System.out.println(" The Name of the Student is : " + s.getName() + " The Desig of the Student is : " +s.getDesig()+" The department of the Student is : " + s.getDepart());
  }

}



Student.java (put these code in a separate file or put it in a EnhanceTest.java)

public class Student
{
private String name,desig,depart;


public String getName()
{
  return name;
}

public void setName(String name)
{
  this.name = name;
}

public String getDepart()
{
  return depart;
}

public void setDepart(String depart)
{
  this.depart = depart;
}
public String getDesig()
{
  return desig;
}

public void setDesig(String desig)
{
  this.desig = desig;
}
}



Abstract class Implementation in Java with best Example

Abstract class

If a class contain any abstract method then the class is declared as abstract class. An abstract class is never instantiated. It is used to provide abstraction. Although it does not provide 100% abstraction because it can also have concrete method.

1.)   Abstract class can have abstract and non-abstractmethods.
2.)  Abstract class can have final, non-final, static and non-static variables.
3.)  Abstract class can have static methods, main method and constructor.

(We can use this Program to this Operator / Super Keyword / Upcasting  )

Example Program :

public class AbstractConstructorTest 
  public static void main(String args[]) 
  { 
    Server server = new Tomcat("Apache Tomcat");     //  Upcasting
    server.start();
  }

abstract class Server
{
  protected final String name; // final variable
  
  protected double version  = 8.6;   // non-final variable 
  
  public Server(String name)   //  constructor inside a abstract  class
  { 
    this.name = name; 
  } 
  
  public String normalmethod()
  {
    
return  " started successfully";
    
  }
  
  public abstract boolean start();    //   abstract method
  
}

class Tomcat extends Server
  public Tomcat(String name)
  { 
  super(name); 
}
@Override 
public boolean start() 
  System.out.println( this.name +" - "+ version+ " " +normalmethod() ); 
  return true; 
}
}

Output:

Apache Tomcat - 8.6  started successfully