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