Sunday, 11 October 2015

XML PARSING IN PYTHON USING MINIDOM

parsing an xml in python using minidom

xml file to be parsed

<?xml version="1.0"?>
<company>
    <employee id="1001">
        <firstname>yong</firstname>
        <lastname>mna</lastname>
        <nickname>mrreferenc</nickname>
        <salary>100000</salary>
    </employee>
    <employee id="2001">
        <firstname>dev</firstname>
        <lastname>journal</lastname>
        <nickname>general</nickname>
        <salary>200000</salary>
    </employee>
       <employee id="2002">
        <firstname>darth</firstname>
        <lastname>vader</lastname>
        <nickname>anakan</nickname>
        <salary>2000</salary>
    </employee>
<employee id="2003">
        <firstname>obi</firstname>
        <lastname>van kanobi</lastname>
        <nickname>ben kanobi</nickname>
        <salary>1500</salary>
    </employee>
<employee id="2009">
        <firstname>hello</firstname>
        <lastname>world</lastname>
        <nickname>wasteland</nickname>
        <salary>20</salary>
    </employee>
</company>

CODE:
   
__author__ = 'solomon'
from xml.dom import minidom

xmlfile= minidom.parse('/home/solomon/solo.xml')
employee = xmlfile.getElementsByTagName("employee")
for emp in employee:
    if(emp.hasAttribute('id')):
        print emp.getAttribute('id')
    firstname= emp.getElementsByTagName('firstname')[0]
    print "firtname" + firstname.childNodes[0].data
    lastname=emp.getElementsByTagName('lastname')[0]
    print 'lastname'+lastname.childNodes[0].data
    salry=emp.getElementsByTagName('salary')[0]
    print "salary"+salry.childNodes[0].data
 
 
OUTPUT:
 
/usr/bin/python2.7 /home/solomon/PycharmProjects/untitled/domparsing.py
1001
firtnameyong
lastnamemna
salary100000
2001
firtnamedev
lastnamejournal
salary200000
2002
firtnamedarth
lastnamevader
salary2000
2003
firtnameobi
lastnamevan kanobi
salary1500
2009
firtnamehello
lastnameworld
salary20

Process finished with exit code 0
 

Sunday, 4 October 2015

OBJECT SORTING IN JAVA COMPARATOR VS COMPARABLE

comparable and comparators are two interfaces provided by java to Sort custom Objects . Here i'm going to explain to you how to sort a person class using java


package sample;
import  com.solo.Adress;public class Person implements Comparable<Person> {

    private String name;    private String age;    private Adress adress;
    public String getName() {
        return name;    }

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


    public String getAge() {
        return age;    }

    public Adress getAdress() {
        return adress;    }

    public void setAdress(Adress adress) {
        this.adress = adress;    }

    public void setAge(String age) {
        this.age = age;    }


    public Person(String name, String age, Adress adress) {
        this.name = name;        this.age = age;        this.adress = adress;    }


    @Override

    public int compareTo(Person person) {
        return this.name.compareTo(person.getName());    }
}

THis is a simple example for comparable interface it is self explanatory .it has one method

very simple and used for normal sorting operations 


what if you want more than two sorting techniques i.e you want to sort by both age and salry 

that's where comparator kicks in
 
package sample;
import java.util.Comparator;
public class Agecomparator implements Comparator<Person> {
    @Override    public int compare(Person person, Person t1) {
        return person.getAge().compareTo(t1.getAge());    }
}

System.out.println("before Sorting");printperson(personList);
System.out.println("....................sorting........................");
Collections.sort(personList,new  Agecomparator());
System.out.println("....................... After sorting --------------------------");
printperson(personList);


before Sorting
solomon
anish
bob
zolton
farage
hercules
....................sorting........................
....................... After sorting --------------------------
farage
hercules
zolton
anish
solomon
bob




Friday, 4 September 2015

Removing elements from collections in java

in this tutorial lets discuss how to remove objects from collections list,Maps for the tutorial uses Array List

everybody knows how to iterate over a list or map my  .even though lots of way are there my favorite was for each. to iterate over a List of String

for(String iter:listname){

}
 so if we try to modify that is add or modify while iterating over it will throw concurrent modification exception So how to modify a collection while we iterate over it


ok  here we have a list

    

List<String> database = new ArrayList<String>();
        database.add("mysql");
        database.add("oracle");
        database.add("postgrade");
        database.add("mongodb");
        database.add("couchdb");
 there is two ways to remove a element while iterating over it 
1. iterating for loop backwards and removing them

for (int i = database.size() - 1; i >= 0; i--) {
            System.out.println("inside for loop" + database.get(i));
            if (database.get(i).equals("mongodb")) {
                System.out.println("sorry bitches you dont belong here you need to be kicked out");
                database.remove(i);
            }
        }
2nd way using the iterator

while (iterator.hasNext()) {
            String dbname = iterator.next();
            System.out.println("the iterator element is" + dbname);
            if (dbname.equals("couchdb")) {
                System.out.println("YOU too dont belong here you too will be kicked out");
                iterator.remove();
            }
        }

and the output








Sunday, 19 July 2015

JSON/XML PARSING IN JAVA

In this tutorial we are going to see how to parse xml and json files. first we will just parse a xml file and later we will parse xml elements to objects

1) for java we are using DOM parser

xml file to be parsed


<?xml version="1.0"?>
<company>
<employee id="1001">
<firstname>yong</firstname>
<lastname>mna</lastname>
<nickname>mrreferenc</nickname>
<salary>100000</salary>
</employee>
<employee id="2001">
<firstname>dev</firstname>
<lastname>journal</lastname>
<nickname>general</nickname>
<salary>200000</salary>
</employee>
       <employee id="2002">
<firstname>darth</firstname>
<lastname>vader</lastname>
<nickname>anakan</nickname>
<salary>2000</salary>
</employee>
<employee id="2003">
<firstname>obi</firstname>
<lastname>van kanobi</lastname>
<nickname>ben kanobi</nickname>
<salary>1500</salary>
</employee>
<employee id="2009">
<firstname>hello</firstname>
<lastname>world</lastname>
<nickname>wasteland</nickname>
<salary>20</salary>
</employee>
</company>


and the coe to parse the nodes and attributes were


package xmlparsing;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Domparsing {

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
File file= new File("/home/solomon/solo.xml");
System.out.println(file.exists());
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
       NodeList companylist= doc.getElementsByTagName("employee");
       for(int i=0;i<companylist.getLength();i++){
      Node companynoes=companylist.item(i);
      System.out.println(companynoes.getTextContent());
   if(companynoes.hasAttributes()){
  NamedNodeMap attributes = companynoes.getAttributes();
  for(int j=0;j<attributes.getLength();j++){
  System.out.println("attribut values"+attributes.getNamedItem("id").getNodeValue());
  }
   }
   
   
       }
}

}

and the output is

true

yong
mna
mrreferenc
100000

attribut values1001

dev
journal
general
200000

attribut values2001

darth
vader
anakan
2000

attribut values2002

obi
van kanobi
ben kanobi
1500

attribut values2003

hello
world
wasteland
20

attribut values2009


XPATH;
  now we use get the firstname of all employees whose salary is greater than 1500

1)create an xpath object
      XPath xpath= XPathFactory.newInstance().newXPath();

private static void getdata(Document doc, XPath path){
List<String>salarybyname= new ArrayList<>();
try {
XPathExpression expression = path.compile("/company/employee[salary>"+1500+"]/firstname/text()");
NodeList nodelist=(NodeList)expression.evaluate(doc, XPathConstants.NODESET);
System.out.println(nodelist.getLength());
for(int i=0;i<nodelist.getLength();i++){
System.out.println(nodelist.item(i).getTextContent());
}
System.out.println("Number of items added to the list"+salarybyname.size());
for(String employee:salarybyname){
System.out.println(employee);
}

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

}

and the o/p is

yong
dev
darth

SAVING IMAGES IN MONGODB USING JAVA/PYTHON


SAVING IMAGES IN MYSQL UING JAVA/PYTHON

hi in this tutorial we are going to store how to store binary data in java and python .image and pdf are stored as binary format


using java

package mysql;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BinaryPicture {
public static void main(String[] args) throws ClassNotFoundException, SQLException, FileNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/binarymanipulation", "root", "solomon");
PreparedStatement pstmt = con.prepareStatement("insert into images values(?,?,?)");
File file = new File("/home/solomon/Downloads/javapic.jpeg");
System.out.println(file.exists());
FileInputStream is = new FileInputStream(file);
int length= (int)file.length();
System.out.println(length);
 pstmt.setString(1, "javacomplete edition");
 pstmt.setInt(2,length );
 pstmt.setBlob(3, is);
int i=  pstmt.executeUpdate();
System.out.println(i);
 pstmt.close();
 con.close();


}

}

using python

import mysql.connector
import base64

conn = mysql.connector.Connect(user="root",passwd="solomon",host="localhost",db="binarymanipulation",port="3306")

cursor =conn.cursor();
with open('/home/solomon/Downloads/javapic.jpeg', 'rb') as image:
        imageraw = image.read()
s=(imageraw,)
sql = "INSERT INTO images(id,size,image) VALUES('PYTHON',245, %s)"
cursor.execute(sql,s)
conn.commit();
conn.close();


Saturday, 18 July 2015

Connecting to data base(MYSQL) using JAVA/PYTHON

In this tutorial im going  to discuss how to connect to database(MYSQL) usu= using JAVA and PYTHON

VERSIONS:
      JAVA 1.7
      MYSQL 5
      PYTHON 3.4

connecting to a database

1)JAVA

FIRST WE HAVE ADD MYQL CONNECTOR JAR TO THE PROJECT

RIGHT CLICK ON THE PROJECT -> SELECT PROPERTIES ->SELECT BUILDPATH ->ADD EXTERNAL LIBRARIES ->




Now we can start our coding
        now import mysql in to the class
import java.mysql.*;

make a connection with the database

Connection conn = DriverManager.getConnection("dbname","uername" , "password");

and using the connection create a statement

Statement  stmt = conn.createStatement();

now we can write a query 
for creating a  TABLE



now lets go to the database to see if  table is created


so we have successfully created  created database in java

now lets create a table in python

i have been in java for some years working full time as java devoleper but been smitten with python for some months

we can discuss briefly about python how it differs from java in future post in this post we will just see how to connect to a database using python

to connect python with MySQL we need mysqldriver
 in java to add third party libraries/JAR we simply download them and put it in the JAR folder  here in python we have to install it through pip or easy install now lets install mysql in python

in cm prompt go to the folder were python is installed


now install mysql using the following command


ok lets go to the  code

import mysql.connector
 
conn = mysql.connector.connect(user="root",passwd="",host="localhost",db="solomon",port="3306")
 
 
now we have established a connection with MySQL 



now we have created a table in python .lets see if it exists




 
 so database is created now Lets add some values in to this table




now lets view the result in db



Sunday, 31 May 2015

String to Hashmap in java

in this tutorial im going to explain how to split strings of  following type type so that we can use them as key value in hash map

so our string is in this format

String  authors  = "nikos Kazantzakis:Greece, nikos Kazantzakis:Greece, jersy kosinski:Poland,valmiki:india,shakessphere:England,jamcejoyce:ireland";

we have  continuous string contain authors and their corresponding countries what we have to do first is split the string using  .split();. it returnes an array string

String[] countries = authors.split(",");

the result would be an array of string 
 countries[0] =  nikos Kazantzakis:Greece;
 countries[1] =  jersy kosinski:Poland
again splitting that using delimer : and then add  the values in to map

below is the full code

package stringmanipulation;

import java.util.HashMap;
import java.util.Map;

public class Stringtomap {

    public static void main(String[] args) {
        String name = "nikos Kazantzakis:Greece, nikos Kazantzakis:Greece, jersy kosinski:Poland,valmiki:india,shakessphere:England,jamcejoyce:ireland";
        String[] name1 = name.split(",");
        System.out.println("printing the array");
        printArray(name1);
        for (String name2 : name1) {
            String[] name3 = name2.split(":");
            Map<String, String> countrylist = new HashMap<String, String>();
            countrylist.put(name3[0], name3[1]);
            System.out.println(countrylist);
        }
    }

    public static void printArray(String[] name1) {
        for (String print : name1) {
            System.out.println(print);
        }
    }
}


running the program will give the output





Saturday, 10 January 2015

Mongo DB+Java example

In  this tutorial im goiung to expalin how to connect MongoDb with java

1)installing MongoDb on windows
 download mongoDB
Extract it
then go to the comamnd prompt
click enter

then just type

--dbpath is the path where mongodb stores the data we have to create it .if it doesnt exist mongodb will give error

press enter






now mongoDB has been successfully started up


ok now lets connect it with java
1) add mongodb connection jar

rightclickon the project- -->select properties --> click java build path
then add the jar



MongoClient client = new MongoClient();
 connects with mongo db server
now we have created a connection sucessfully with mongoDB. now lets create a database

DB database = client.getDB("soloworld");

// here i have get the database  soloworld .if the database doesnt exist mongo db wil create one for you

create a table aka collection
 DBCollection table = database.getCollection("userprofile");
// if the collection doesnt exist mongodb will create one for you

  BasicDBObject columns = new BasicDBObject();
        columns.put("Name", mongopojo.getName());
        columns.put("Language", mongopojo.getLanguage());
        table.insert(columns);
//here we have inserted record in to the mongo db

below is the full code & output


and the pojo class