Sunday, 9 September 2018

JAXB Object to XML conversion using java (Marshalling)

convert person object into an XML. 


public class ObjectToXML {

public static void main(String args[]) {
Person person = new Person();
person.setFirtName("Aneesh");
person.setLastName("T.G");
person.setAge(25);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// print output to console
jaxbMarshaller.marshal(person, System.out);

} catch (JAXBException e) {
e.printStackTrace();
}
}
}

use the annotation @XmlRootElement to the class you want to convert into XML.
use the annotation @XmlType propOrder for ordering the tags in the XML.

@XmlRootElement
@XmlType(propOrder={"firtName","lastName","age"})
public class Person {

private String firtName;
private String lastName;
private int age;
public String getFirtName() {
return firtName;
}
public void setFirtName(String firtName) {
this.firtName = firtName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Output
---------

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <firtName>Aneesh</firtName>
    <lastName>T.G</lastName>
    <age>25</age>
</person>

Sunday, 26 February 2017

Unlock bootloader in Moto G3

How to Unlock Bootloader in Moto G 3rd generation in few simple steps which is completely Official and 100% safe.

Before that you guys need to know what is bootloader....???

Bootloader is code that is executed before any Operating System starts to run. Bootloader is usually locked on an Android device. If you need to flash a custom ROM on your android phone then you must unlock your bootloader first.

Note: Unlocking your phone’s bootloader voids its warranty. Do it at your own risk and I'm not responsible for any loss. It also completely wipes your Android phone’s internal memory. So before you start backup every data you want.

1. Install motorola usb driver and minimal ADB & Fastboot in your Pc.

2. Turn off your device. then turn on the device by holding volume down button and power key for 5 sec. This will launch the bootloader screen

3. Connect your phone to Pc using a data cable.

4. Open the folder where ADB was installed then hold the shift key and right click you’ll see an option “Open Command window here”. Click on it.

5. Then type fastboot oem get_unlock_data

6. Above code will return something like this
(bootloader) 0A40040192024205#4C4D3556313230
(bootloader) 30373731363031303332323239#BD00
(bootloader) 8A672BA4746C2CE02328A2AC0C39F95
(bootloader) 1A3E5#1F53280002000000000000000
(bootloader) 0000000
Paste together 5 lines of output into one continuous string without (bootloader) or white spaces.Your string looks like this.
0A40040192024205#4C4D355631323030373731363031303332323239#BD008A672BA4746C2CE02328A2AC0C39F951A3E5#1F532800020000000000000000000000
7. Now, Goto Motorola’s Boot loader unlock site & login with google. Paste the entire code in the input box & clicking can my device be unlocked.
8. After that, Check I agree and click Request Unlock Key. You’ll receive the unlock key in your Gmail.
9. Copy the key from your mail and paste in a notepad file, Open Command prompt and type 
fastboot oem unlock "KEY" (Replace KEY with the key you received).
That's it you have successfully unlocked the Bootloader. :)

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>