Sunday, 18 September 2016

Java API to detect virus in a file using ClamAv

Many of the programmers were stucks in file scanning for virus ,me also stucked in that about 2 weeks.
Actually it's not in the code we stuck...The installation of antivirus and running the service in the pc were we stuck and the lack of proper documentation of installation and running the service.

ClamAv is the only antivirus engine available as an open source till now...

On this post, i will help you guys to install clamAv in windows and use clamAv service for scanning files for virus using java

1) Download ClamAv from https://www.clamav.net/downloads
download proper .msi file for your windows version. current version for windows 64 bit (clamav-0.99.2-x64.msi)Double click and install clamAv.

2) Download ClamAv virus database from the same page
or download main.cvd from the direct link http://database.clamav.net/main.cvd
and daily.cvd from the direct link http://database.clamav.net/daily.cvd
put these two files where you install clamAv (default location will be c drive--> program files--> clamAv)

3) They will provide sample files for clamd.conf and freshclam.conf
studying these files and creating config file will be the next challenge for you..So i will give you the config files just put these file in the clamAv root directory(where clamAv is installed)

a) clamd.conf ( https://drive.google.com/file/d/0B1n0939T4he7Z2xnME0tZFdMazg/view?usp=sharing )
b) freshclam.conf ( https://drive.google.com/file/d/0B1n0939T4he7c3YtWEZ2a3FaOWM/view?usp=sharing )
Edit the clamd.config file

DatabaseDirectory-->path of virus database files(main.cvd and daily.cvd)

TCPAddr-->your currenct ip address

4) Now run cmd as administrator
Change cmd to clamAv directory
 then run command--> clamd.exe install
That's it!!!!!!!!!This will start service of clamAv in your system

5) Now scan the file using java

Download these third party jars
a) org.apache.commons.logging-1.1.1.jar
b) commons-io-2.0.jar
c) libclamav-1.0.jar ( https://drive.google.com/file/d/0B1n0939T4he7d1JyYnE2RlB1OGc/view?usp=sharing )
1)
ClamAVFileScan.java 

import java.io.FileInputStream;
import java.io.InputStream;

import net.taldius.clamav.ClamAVScanner;
import net.taldius.clamav.ClamAVScannerFactory;

/**
 * Class to scan files using ClamAV antivirus APIs.
 *
 * @author Aneesh T.G
 *
 */
public class ClamAVFileScan {
private ClamAVScanner scanner;
public static void main(String args[]){
boolean scanResult=false;
ClamAVFileScan clamAVFileScan=new ClamAVFileScan();
try {
clamAVFileScan.initScanner();
scanResult=clamAVFileScan.fileScanner("C:\\Users\\Aneesh.T.G\\Desktop\\eicar.zip");

if(scanResult){
System.out.println("No virus found");
}
else{
System.out.println("Warning!!!! Virus found");
}
} catch (Exception e) {
e.printStackTrace();
}

}

       /**
        * Method to initialize clamAV scanner
        */
       public void initScanner(){
           
              ClamAVScannerFactory.setClamdHost("192.168.0.7"); // Host ip where 'clamd' process is running
              ClamAVScannerFactory.setClamdPort(3310); // Port on which 'clamd' process is listening
              ClamAVScannerFactory.setConnectionTimeout(20);// Connection time out to connect 'clamd' process
             
              this.scanner = ClamAVScannerFactory.getScanner();
       }

        /**
        * Method to scans files to check whether file is virus infected
        *
        * @param fileInputStream
        * @return
        * @throws Exception
        */
       public boolean fileScanner(String fileInputStream) throws Exception {

              boolean resScan = false;
              if (fileInputStream != null) {
              InputStream file=new FileInputStream(fileInputStream);
                     resScan = scanner.performScan(file);
                   
              } else {

                     throw new Exception();
              }
              return resScan;
       }

}

6) Create a test virus file or download eicar.zip and check...Happy coding!!!! :)

Friday, 16 September 2016

How to create log using java

Jar files required

1)datedFileAppender-1.0.2 (https://drive.google.com/file/d/0B1n0939T4he7ZGpBeW5NdzNXUEk/view?usp=sharing)
2)log4j-1.2.17 (https://drive.google.com/file/d/0B1n0939T4he7b2d0RFJxUXFxMzQ/view?usp=sharing)

Create a property file named log4j.properties within the project folder (outside the src)..copy paste the below content in that file..

log4j.properties file

# Root logger option


log4j.rootLogger=INFO, file, stdout
#log4j.logger.org.quartz=DEBUG
#comment

# Direct log messages to a log file
log4j.appender.file=biz.minaret.log4j.DatedFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.Prefix=logfile.
#log4j.appender.T.MaxFileSize=100MB
#log4j.appender.T.MaxBackupIndex=7
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Direct log messages to stdout(to show in the console)
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


LogFile.java

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author Aneesh.T.G
 */

public class LogFile {

 static Logger logger = Logger.getLogger(LogFile.class.getName());
 public static void main(String args[]) {
     PropertyConfigurator.configure("./log4j.properties");
  logger.info("This is my first log statement");
  logger.error("Sorry, something wrong");

 }
}

This will create a 'logs' folder in project directory inside that a dated log file will create

Wednesday, 8 June 2016

Google pie chart with dynamic values from json response and click listener

<html >
  <head>
    <meta charset="UTF-8">
    <title>Google Pie Chart</title>
  </head>
  <script src='http://www.gstatic.com/charts/loader.js'></script>
  <script>
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {

    var Json = [
    {"Name":"Vignesh ","Mark":"40","class":"s4","id":"1",},
    {"Name":"Sreeragh","Mark":"50.5","class":"s5","id":"2"},
    {"Name":"Indu","Mark":"43.5","class":"s6","id":"3"},
    {"Name":"Mathew","Mark":"26.5","class":"s7","id":"4"}
];
        var data =new google.visualization.DataTable();
        data.addColumn('string','Name');        //specifying the column header and type
        data.addColumn('number','Mark');
        data.addColumn('string','class');
        data.addColumn('number','id');
    
    for(i=0;i<Json.length;i++){
         data.addRow([Json[i].Name,parseFloat(Json[i].Mark),Json[i].class,parseInt(Json[i].id)]);    //adding data to the datatable from json
    }

    var options = {
          title: 'Google pie chart with dynamic value (json)',
        is3D: true,
        pieStartAngle: 0,
        };
    var chart=new google.visualization.PieChart(document.getElementById('piechart'));
        
    
    function selectHandler() {                //selection method

   var selectedItem = chart.getSelection()[0];
          if (selectedItem) {
            var id = data.getValue(selectedItem.row,3);        //3 is column index of the datatable to which the data to be alerted
            alert('The user selected has Id '+ id);
          }

  }

  google.visualization.events.addListener(chart, 'select', selectHandler);
    chart.draw(data, options);
        

      }
    </script>
 <body>

    <div id="piechart" style="width: 900px; height: 500px;"></div>
     
</body>
</html>

Thursday, 26 May 2016

How to update an XML tag's attribute using java


XML file before update:-

xmlfile.config

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<configuration>
  <appSettings>
    <add key="Aneesh" value="aneesh.aneesh83@gmail.com"/>
    <add key="Akshay" value="vishnu.akshayprabhu@gmail.com"/>
    </appSettings>
</configuration>


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

class UpdateXMLAttribute {
    public static  void main(String args[]){
      
        try{
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse("E:\\Aneesh\\xmlfolder\\xmlfile.config"); //xml file path  
            StreamResult result = new StreamResult("E:\\Aneesh\\xmlfolder\\xmlfile.config");    
                
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("//configuration/appSettings/add[@key]");//specifying the nodes
            NodeList nodelist = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
         
              for (int c = 0; c < nodelist.getLength(); c++)
                {
                Node currentItem = nodelist.item(c);
                  
                String key = currentItem.getAttributes().getNamedItem("key").getNodeValue();
               if(key.equals("Akshay")){
                 
                   currentItem.getAttributes().getNamedItem("value").setTextContent("Aneesh");//updating the attribute
               
                  }
               Transformer transformer = TransformerFactory.newInstance().newTransformer();
               transformer.setOutputProperty(OutputKeys.INDENT, "yes");
               DOMSource source = new DOMSource(document);
               transformer.transform(source, result);
                }
          
          }
          catch(Exception e){
              e.printStackTrace();
              
          }
    }

    }

XML file after update:-

xmlfile.config

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<configuration>
  <appSettings>
    <add key="Aneesh" value="aneesh.aneesh83@gmail.com"/>
    <add key="Akshay" value="Aneesh"/>
    </appSettings>
</configuration>

How to read XML node's attributes of a configuration file using java

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReading {
   
    public static void main(String args[]) {

        try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse("E:\\Aneesh\\xmlfolder\\xmlfile.config");
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xPath = xPathfactory.newXPath();
            XPathExpression expr = xPath.compile("//configuration/appSettings/add[@key]");
            NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int c = 0; c < nodeList.getLength(); c++) {
                Node currentItem = nodeList.item(c);
                String key = currentItem.getAttributes().getNamedItem("key").getNodeValue();
                String value = currentItem.getAttributes().getNamedItem("value").getNodeValue();
                System.out.println("Key:"+key+" Value:"+value);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}


Sample XML file

xmlfile.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Aneesh" value="aneesh.aneesh83@gmail.com"/>
    <add key="Akshay" value="vishnu.akshayprabhu@gmail.com"/>
    </appSettings>
</configuration>

Saturday, 16 April 2016

How to include Social network Like and follow button in website

 Index.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Social Network</title>

<!----------google script-------------->  
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
/*----------facebook script-------------*/
(function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.6";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));


/*----------twitter script-------------*/
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];
if(!d.getElementById(id)){js=d.createElement(s);js.id=id;
js.async=true;
js.src="//platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);
}}(document,"script","twitter-wjs");
</script>
</head>
<body>
  
    <!-----facebook------>
        <div class="fb-like"
            data-href="https://www.facebook.com/Govt-Model-Boys-HSSThycaud-146378908747315/"
            data-layout="standard" data-action="like" data-show-faces="true"
            data-share="true"></div>
  
    <!-------twitter------->
        <a class="twitter-follow-button"
            href="https://twitter.com/intent/follow?screen_name=NASA&original_referer=https://dev.twitter.com/web/follow-button"></a>
  
    <!-----google plus----->  
        <div class="g-follow" data-href="https://plus.google.com/+chelseafc"
            data-rel="{relationshipType}"></div>
  
</body>
</html>

Thursday, 24 March 2016

Get Started with Android

Android

Android is an open source linux based operating system for mobile such as smart phones and tablet.Android was developed by google.

Android phones typically come with several built-in applications and also support third-party programs. Developers can create programs for Android using the free Android SDK (Software Developer Kit). Android programs are written in Java and run through Google's "Davlik" virtual machine, which is optimized for mobile devices.

Android Architecture

Android operating system is a stack of software components which is roughly divided into five sections and four main layers

1)Linux kernel

At the bottom of the layers is Linux. This provides a level of abstraction between the device hardware and it contains all the essential hardware drivers like camera, keypad, display etc.

2)Libraries

On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well known library libc, SQLite database which is a useful repository for storage and sharing of application data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc.

3)Android Runtime

This section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android application developers to write Android applications using standard Java programming language.

4)Application Framework

The Application Framework layer provides many higher-level services to applications in the form of Java classes.


5)Application

You will find all the Android application at the top layer like Contacts Books, Browser, Games etc.

Application Components

Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact.
There are four main components

1)Activities

An activity represents a single screen with a user interface,in-short Activity performs actions on the screen. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched.

2)Services

A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.

3)Broadcast Receiver

Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.

4)Content Provider

A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolverclass. The data may be stored in the file system, the database or somewhere else entirely.

Additional Components

1)Fragments
Represents a portion of user interface in an activity.

2)Views
UI elements that are drawn on-screen including buttons, lists forms etc.

3)Layouts
View hierarchies that control screen format and appearance of the views.

4)Intents
Messages wiring components together.

5)Resources
External elements, such as strings, constants and drawable pictures.

6)Manifest
Configuration file for the application.

Sunday, 13 March 2016

Star rating using jquery


Requirements

1)Jquery
2)star rating plugin

 Download it from here
https://www.dropbox.com/sh/1mguiv1l4w6afdx/AAClxTcd0FWPFJuBWeVl5oABa?dl=0

Project Structure




Index.jsp

<html>
<head>
<link rel="stylesheet" href="resources/rating/jquery.rateyo.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Rating</title>
</head>
<body>
    <div id="id-showStar"></div>
    <span class="counter" id="counter"></span>   
    <button id="id-showReading" name="name-showReading" onclick="showRating()">Show Rating</button>
    <div id="id-showRating"></div>
</body>
<script src="resources/jquery/jquery-2.1.4.min.js"></script>
<script src="resources/rating/jquery.rateyo.js"></script>
<script src="resources/customjs.js"></script>
</html>


customjs.js


$(document).ready(function() {
   
    $("#id-showStar").rateYo({
        onChange : function(rating, rateYoInstance) {
            $(this).next().text(rating);
        }
    });

});

function showRating() {   
   
    var getRating = document.getElementById("counter").innerHTML;
    $("#id-showRating").rateYo({
        rating : getRating
    });
   
}
 

Saturday, 6 February 2016

Java program to send mail using Gmail smtp with attachments

Requirements

1)javax mail jar file (javamail-1.4.5)

Gmail smtp need authentication so you must provide username and password

package emailblog;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



    public class EmailSender {

    private static String SMTP_HOST_NAME = "smtp.gmail.com";
    private static String SMTP_PORT= "465";
    private static String SSL_FACTORY="javax.net.ssl.SSLSocketFactory";
    private static String emailContent = "success";
    private static String emailSubject = "subject email";
    private static String emailFromAddress="your email address";
    private static String emailPassword="your email password";
    private static final String[] attachment = {                              
            "attachmnt's file path",
            "attachmnt's file path" };                                 //attachmnt file address

    private static final String[] sendTo = { "to address" };               //to address
    private static final String[] sendCC = {"cc address"};                //cc address
    private static final String[] sendBCC = {"bcc address"};           //Bcc address
   
   

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

        EmailSender emailSender = new EmailSender();
       
        emailSender.sendMail(sendTo, sendCC, sendBCC, emailSubject,           
                emailContent, emailFromAddress, attachment);
    }                                                           //calling sendMail method for send mail

    private void sendMail(String[] toAddress, String[] ccAddress,
            String[] bccAddress, String subject, String message, String from,
            String[] attach) throws MessagingException {

        boolean debug = true;
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailFromAddress,
                                emailPassword);
                    }

                });
        session.setDebug(debug);
        Message msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();  //creating object for multipart
     
       MimeBodyPart messageBodyPart = new MimeBodyPart();       //creating first obj for bodypart to send msg

        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[toAddress.length];
        for (int i = 0; i < toAddress.length; ++i) {
            addressTo[i] = new InternetAddress(toAddress[i]);
        }
        InternetAddress[] addressCC = new InternetAddress[ccAddress.length];   
        for (int i = 0; i < ccAddress.length; ++i) {
            addressCC[i] = new InternetAddress(ccAddress[i]);
        }
        InternetAddress[] addressBCC = new InternetAddress[bccAddress.length];
        for (int i = 0; i < bccAddress.length; ++i) {
            addressBCC[i] = new InternetAddress(bccAddress[i]);
        }                                                                     //setting address to,cc,bcc
     
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        msg.setRecipients(Message.RecipientType.CC, addressCC);
        msg.setRecipients(Message.RecipientType.BCC, addressBCC);
       
       
        msg.setSubject(subject);                                                 //setting subject
        messageBodyPart.setContent(message, "text/plain");    //setting body

        multipart.addBodyPart(messageBodyPart);         //adding body part to the multipart(msg)

     
        if (attach != null && attach.length > 0) {                            //attachmnt
            for (String filePath : attach) {

                MimeBodyPart attachPart = new MimeBodyPart();        //create second obj for bodypart to send attchmnt
           
                try {
                    attachPart.attachFile(filePath);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

                multipart.addBodyPart(attachPart);            //adding body part to the multipart(attachmnt)
            }
        }

        msg.setContent(multipart);
        Transport.send(msg);                                             //sending mail
    }

}

How to install mysql in ubuntu 14.04

First of all update your system if you need

1) sudo apt-get update
2) sudo apt-get upgrade


Install MySQL

1)sudo apt-get install mysql-server
 
During the installation process, you will be prompted to set a password for the MySQL root user.
Choose a strong password and keep it in a safe place for future reference.
 
 
MySQL Server

1)sudo mysql_secure_installation
You will be given the choice to change the MySQL root password, remove anonymous user accounts, disable root logins outside of localhost, and remove test databases. It is recommended that you answer yes to these options.

 

Root Login

To log in to MySQL as the root user:
 
1) mysql -u root -p

When prompted, enter the root password you assigned when the 
mysql_secure_installation.
 
You’ll then be presented with the MySQL monitor prompt:

1
2
3
4
5
6
7
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.45 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>