Monday, 3 March 2014

Read an XML File usin Java

ReadXMLFile .java

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

    File fXmlFile = new File("Staff.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    //optional, but recommended
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("staff");

    System.out.println("----------------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            System.out.println("Staff id : " + eElement.getAttribute("id"));
            System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
            System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
            System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
            System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

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

}



Staff.xml

<?xml version="1.0"?>
<company>
    <staff id="1001">
        <firstname>yong</firstname>
        <lastname>mook kim</lastname>
        <nickname>mkyong</nickname>
        <salary>100000</salary>
    </staff>
    <staff id="2001">
        <firstname>low</firstname>
        <lastname>yin fong</lastname>
        <nickname>fong fong</nickname>
        <salary>200000</salary>
    </staff>
</company>

Friday, 28 February 2014

Fetching a Web page in WEB-HARVEST(PART:2)




<?xml version="1.0" encoding="UTF-8"?>

<config>
    <var-def name="datestring">
          <file action="read" path="date.txt"></file>
    </var-def>
   
    <var-def name="webpage">
         <html-to-xml>
          <http url="http://scores.espn.go.com/ncb/scoreboard?date=20121124"/>
     </html-to-xml>
    </var-def>
    <var-def name="duke">
    <xpath expression="(//div[@class='team visitor'])[1]//a[@title]/text()">
        <var name="webpage"></var>
   </xpath>
   </var-def>
</config>


Today I'll show how to pull information out of the webpage and save it -- specifically, we'll pull the teams and scores out of the page and save them off for later use.

Find the Information

The first step is to figure out where the information we want is in the web page.  This is easier said than done on modern web pages, which tend to be impenetrable morasses of Javascript, HTML and CSS.  One way to get started is to use the "View Source" option on your web browser (or save the web page onto your computer and view it with your favorite text editor) and then search for text you can see from the web page.  For example, if we go the ESPN Scoreboard page for 11/24/2012, we can see that the first listed game is Duke versus Louisville.  If we do "View Source" and search for "Duke", we find this as the first reference:
    <a title="Duke" href="http://espn.go.com/mens-college-basketball/team/_/id/150/duke-blue-devils">Duke</a>
And, this in fact, is the HTML code that creates the "Duke" text in the Duke vs. Louisville scoreboard.  With some more digging, re-formating and so on, we can eventually see that the information about Duke is in an HTML structure that looks like this:
    <div class="team visitor">
      <div class="team-capsule">
          <span id="323290097-aTeamName">
        <a title="Duke">
          Duke</a>
          </span>
      </div>
      <ul id="323290097-aScores" class="score" style="display:block">
        <li class="final" id="323290097-awayHeaderScore">
          76</li>
      </ul>
    </div>
The information about Louisville is in a structure that is identical except that it starts with "team home" instead of "team visitor."

So now that we know where the information is, we need to pluck it out and put it to use.

The Power of XPath

Web-Harvest uses Xpath extensively to dig information out of webpages.  Xpath is a notation for specifying where to find something in an XML file.  It's a "path" from the top-level of the XML down to some particular piece (or pieces) of the XML.  It's very useful and very powerful, but like regular expressions can be confusing and difficult to use.  If you don't know anything about XPath, you might want to go off and read a tutorial about it to familiarize yourself with how it works.  It's also very useful to have an XPath tester for working out the correct paths for the information you're trying to get.

In fact, Web-Harvest itself provides a very handy XPath tester.  To see it's use, run the above script to fetch the ESPN page, and then use the left-hand pane to see the value of the "webpage" variable (also as shown above).  Now click on the magnifier icon to the right of the "[Value]" box and you'll get a pop-up window showing the text of the webpage:


Notice the "View as:" option in the top left of the pop-up.  Click here and select XML.  This will show the webpage in XML format:


This view has a couple of handy features.  First, you can use the "Pretty-Print" button at the top to reorganize and cleanup the XML for easier viewing.  Second, you'llsee a box at the bottom labeled "XPath expression."  If you type an Xpath into this box, Web-Harvest will run that XPath against the displayed XML and show the result.  For example, try typing the Xpath //div[@class="team visitor"] into the box.  This expression finds all div elements in the page that have the class "team visitor":


This matches a total of 15 div elements on this page, the first of which is the Duke entry we found above.

When an Xpath returns a list of items, we can pick items out of the list in various ways, including using an index. To pick out the first element of this list, we use (//div[@class="team visitor"])[1]. That gives us the entire block HTML for Duke that I showed earlier. If you look up there, you'll see the team name is within a <a @title="Duke"> tag. We can pull that out by extending our Xpath to say (//div[@class="team visitor"])[1]//a[@title] which essentially says "Give me all the <a> elements with a title attribute that are within the first div element with a class of team visitor". Try that out:


We've now narrowed the Xpath down to just the <a> element containing the team name. We can extract the actual name by appending the function text()to the end of our Xpath. This function returns whatever text it finds inside the element selected by the Xpath:



Here's how we'd use that same Xpath within Web-Harvest to pull out the name and save it in a variable:



You can experiment with creating the Xpaths to pull out the home team's name and the final scores of the game.

Looping


The Xpath example above works on the first element in the list of visitor team names, but what we really want to do is capture the team names and scores for all the games on the page. To do that, we will loop over each of the game sections in turn. Web-Harvest provides a processor for this called <loop>, which works about as you would imagine. It takes a list of elements and loops over them one at a time, and returns a list of the results. Here's the skeleton for looping over each of the games in turn:



The <loop> processor has two parts. The first part is a <list> of items to loop over. The second party is a <body> that will be executed for each element of the list. Each time the <body> is executed, a variable called currGame (which is specified as "item" in the <loop> tag) will be set to the current element of the list. In this case, each <body> execution just returns the current item, so the result of the loop is just the list.

Notice that the <list> of items is given by the Xpath "(//div[contains(@class,'final-state')])". That Xpath returns a list of div elements. There's one div element for each game on the page, and the div has the team names and scores inside of it. (The visiting team name we pulled out earlier is inside this div.)

So now, each time through the loop we need pull out the team names and scores for currGame. currGame contains a chunk of XML, so we can once again use Xpath to do this. Then we'll store each item in its own variable:



<?xml version="1.0" encoding="UTF-8"?>

<config>
  <var-def name="datestring">
    <file action="read" path="date.txt"></file>
  </var-def>
  <var-def name="webpage">
      <html-to-xml> 
        <http url="http://scores.espn.go.com/ncb/scoreboard?date=20121124"/>
      </html-to-xml>
    </var-def> 
  <loop item="currGame">
      <list>
        <xpath expression="(//div[contains(@class,'final-state')])">
            <var name="webpage"/>
        </xpath>
      </list>
      <body>
          <var-def name="visitor">
              <xpath expression="(//div[@class='team visitor'])[1]//a[@title]/text()">
                  <var name="currGame"/>
              </xpath>
          </var-def>
          <var-def name="visitorScore">
              <xpath expression="(//li[@class='final'])[2]//text()">
                  <var name="currGame"/>
              </xpath>
          </var-def>
          <var-def name="home">
              <xpath expression="(//div[@class='team home'])[1]//a[@title]/text()">
                  <var name="currGame"/>
              </xpath>
          </var-def>
          <var-def name="homeScore">
              <xpath expression="(//li[@class='final'])[3]//text()">
                  <var name="currGame"/>
              </xpath>
          </var-def>
        <file action="append" type="text" path="scores.txt">
           <template>
               ${visitor} ${visitorScore} ${home} ${homeScore} ${sys.cr}${sys.lf}
           </template>
        </file>
      </body>
  </loop>
</config>

Each var-def in the body of the loop uses an Xpath expression to pull out a particular piece of the data. You might want to experiment with the Xpaths to see how each of them finds the right piece of information.

If you run this and look at the value of the loop after it is complete you'll see this:



The value of the loop is a list of all the values of the body as it is executed, and the value of each body is just the list of the values of the processors in the body (four var-def processors in this case). It all gets mashed together and you end up with a long list of team names and scores.

 

Format and Output


To make this more useful, let's clean up the format of the game data and write it out to a file. We can format using the <template> process that we saw last time, and to output we use the same <file> processor we used to read a file. Every time through the loop we'll add a line to the file for the game we just processed:



The ${sys.cr} and ${sys.lf} are Javascript values that put a carriage-return/line-feed at the end of every line. The output file looks like this:




Conclusion


This tutorial should give a general idea of how Web-Harvest works and some of the basic tools it offers for scraping information out of web pages. More help can be found online at the Web-Harvest documentation as well as the Web-Harvest forums.

Here is the completed Web-Harvest script, for cut & paste purposes:

<?xml version="1.0" encoding="UTF-8"?>

<config>
  <var-def name="datestring">
    <file action="read" path="date.txt"></file>
  </var-def>
  <var-def name="webpage">
      <html-to-xml>  
        <http url="http://scores.espn.go.com/ncb/scoreboard?date=20121124"/>
      </html-to-xml>
    </var-def>  
  <loop item="currGame">
      <list>
        <xpath expression="(//div[contains(@class,'final-state')])">
            <var name="webpage"/>
        </xpath>
      </list>
      <body>
          <var-def name="visitor">
              <xpath expression="(//div[@class='team visitor'])[1]//a[@title]/text()">
                  <var name="currGame"/>
              </xpath>
          </var-def>
          <var-def name="visitorScore">
              <xpath expression="(//li[@class='final'])[2]//text()">
                  <var name="currGame"/>
              </xpath>
          </var-def>
          <var-def name="home">
              <xpath expression="(//div[@class='team home'])[1]//a[@title]/text()">
                  <var name="currGame"/>
              </xpath>
          </var-def>
          <var-def name="homeScore">
              <xpath expression="(//li[@class='final'])[3]//text()">
                  <var name="currGame"/>
              </xpath>
          </var-def>
        <file action="append" type="text" path="scores.txt">
           <template>
               ${visitor} ${visitorScore} ${home} ${homeScore} ${sys.cr}${sys.lf}
           </template>
        </file>
      </body>
  </loop>
</config>

Wednesday, 26 February 2014

Fetching a Webpage in WEB-HARVEST(PART:1)

Now we'll be to fetching webpages.  Look at the following script:

<?xml version="1.0" encoding="UTF-8"?>

<config>
    <var-def name="datestring">
          <file action="read" path="date.txt"></file>
    </var-def>
   
    <var-def name="webpage">
         <html-to-xml>
          <http url="http://scores.espn.go.com/ncb/scoreboard?date=$(datestring)"/>
     </html-to-xml>
    </var-def>
   
</config>




As before, we read in the datestring from a file.  And as in Part 1, we use the http processor to fetch a web page.  But notice the url:

url="http://scores.espn.go.com/ncb/scoreboard?date=${datestring}"
The end of the URL is "${datestring}".  In processor attributes, just as in the template processor, anything enclosed in ${ } is evaluated in Javascript.  In this case, "${datestring}" is replaced with the value of the datestring variable -- which is the "20121110" we read from the date.txt file.  So the resulting URL is "http://scores.espn.go.com/ncb/scoreboard?date=20121110".  This leads (as you might have guessed) to the college basketball results from 11/10/2012.

Conclusion

We now have some basic tools for fetching and manipulating data.  Next time we'll get to the real work of pulling information out of a web page.

CONTINUE WITH PART : 2 

Reading a file in Web-Harvest

 Reading a File

To begin with, let's look at how we can read information from a file into Web-Harvest.  In this example, I'm going to assume we have a file in our working directory called "date.txt" and that file contains a single line with a date in the format YYYYMMDD, e.g., 20121110.  Go to your working directory and create that file.  Then open up Web-Harvest, start a new configuration file, and type in this script:
<?xml version="1.0" encoding="UTF-8"?>

<config>
    <var-def name="datestring">
          <file action="read" path="date.txt"></file>
    </var-def>
   
    <var-def name="USdate">
          <regexp>
              <regexp-pattern>
                  ^(/d/d/d/d)(/d/d)(/d/d)
             </regexp-pattern>
             <regexp-source>
                  <var name="datestring"></var>
             </regexp-source>
            
             <regexp-result>
                  <template>${_2}/${_3}/${_1}</template>
             </regexp-result>
           </regexp>
    </var-def>
   
</config>


The file processor reads the contents of the "date.txt" file and provides that as a result to the outer processor.  In this case, that's the var-def processor that is creating the "datestring" variable.  The result is that the datestring variable will be created and its value will be the contents of the date.txt file.  To see this, hit the green "Run" arrow, and then examine the datestring variable:



Regular Expressions

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.  (Jamie Zawinski)
Jamie Zawinski's famous and generally sound advice notwithstanding, regular expressions are a significant element in the Web-Harvest toolbox.  This makes sense -- much of what we do in screen scraping is manipulating text, and regular expressions are very good at that task.  It's beyond my interest (and probably, ability) to teach you regular expressions.  You'll have to find other resources for that.  But I recommend using a regular expression tester like this to help you debug your regular expressions.  (Remember that Web-Harvest is implemented in Java, so it uses the Java regular expression syntax.)

For a simple example, we'll use a regular expression to pull the year out of the date we've read from the date.txt file.   The year is the first four digits of the date, and digits in regular expressions are represented as \d.  Here's the script to use a regular expression to pull the year out of the datestring variable and store it in a new variable called year:


This example introduces a couple of new processors.  The first is the regexp processor, which has three parts: the regexp-pattern, the regexp-source, and the regexp-result.  The regexp-pattern portion holds the regular expression we're trying to match.  In this case, it is the expression "^(\d\d\d\d)" which means "a group of four digits at the beginning of a line".  The regexp-source provides the string against which we'll try to match the pattern.  In this case, it is the value of the datestring variable, which is the contents of the date.txt file from the previous step of the configuration file.  Finally, the regexp-result portion determines what the result of the regular expression will be -- that is, what value it will feed back up to the next processor.

As you can see, inside of regexp-result we have another processor -- template.  Template basically returns whatever is inside of it.  So if you wrote <template>Test</template> the result would simply be the string "Test".  However -- and this is the useful part -- anything enclosed inside ${ } will be evaluated in Javascript and the result of the Javascript will be injected into the template.  So if you wrote <template>Today is the ${sys.datetime("dd")}th</template> you'd get back "Today is the 13th" (or whatever the current day is).

Web-Harvest defines a number of useful variables inside Javascript.  One of these is _1, which is the value of the first matched group in a regular expression.  Because the _1 in our template is enclosed in ${ } it is evaluated in Javascript and is replaced with the first matched group in the regular expression.  So in this case, our template returns "2012".

Finally, the regexp processor returns the value of the regexp-result part, and the year variable gets set to "2012".  (As you can see in the above screenshot.)

Here's a slightly more complicated example that uses a regular expression to reformat the date in US format.  See if you can figure it out:

Installing Web-Harvest

Installing Web-Harvest is trivial. Download the latest "Single self-executable JAR file" from the website here .
This contains a single Jar file.  Put that somewhere on your computer and then double-click on the Jar file.  Presuming you have Java correctly installed, after a few moments the Web-Harvest GUI will pop up:



Notice that you can download and open some examples.  Under the Help menu (or with F1) you'll find the Web-Harvest manual.  You can also read this online here.

A Useful Note:  Version 2.0 of Web-Harvest has a memory leak bug.  This can cause the tool to use up all available memory and hang when downloading and processing a large number of web pages.  (Say, a whole season's worth of basketball games :-)  You can somewhat minimize this problem by starting Java with a larger memory allocation, using the "-Xms" and "-Xmx" options.  How to do this will vary slightly depending upon your operating system and whether things are installed.  On my Windows machine, I use a command line that looks something like this:
C:\WINDOWS\system32\javaw.exe -Xms1024m -Xmx1024m -jar "webharvest_all_2.jar"
On Windows you can create a shortcut and set the "Target" to be the proper command line.  However, even with this workaround, Web-Harvest will eventually hang.  The only choice then is to quit and restart.

Initial Set-Up

After you've downloaded and installed Web-Harvest, there are one or two things you should set before continuing.  Open the Web-Harvest GUI as above, and on the Execution menu, select Preferences.  This should open a form like this:


First of all, use this form to set an "Output Path".  This is the folder (directory) where Web-Harvest will look for input files and write output files.  (You can use absolute path names as well, but if you don't, this is where Web-Harvest will try to find things.)  There's no way to change this within your Web-Harvest script, so if you need to change this for different scripts, you'll have to remember to do it here first before running your script.

Second, if you need to use a proxy, this is where you can fill in that information.

Using WEB HARVEST for Content Scraping

"Web scraping" is the process of crawling over a web site, downloading web pages intended for human consumption, extracting information, and saving it in a machine-readable format.  With the advent of the Web 2.0 and services-based architectures, web scraping has largely fallen into disuse, but it is still required/handy in situations such as this.

There are a number of web scraping tools available, with various functionality and state of repair.  Many are frameworks or libraries intended to be embedded in languages like Python.  Others are commercial.  For my purposes, I wanted a stand-alone, open-source tool with fairly powerful features and a GUI interface.  I ended up settling on Web-Harvest. Web-Harvest is written in Java, so it can be run on nearly any platform, and can also be embedded into Java programs.


<?xml version="1.0" encoding="UTF-8"?>

<config>
    <var-def name="google">
     <html-to-xml>
          <http url="http://www.google.com"/>
     </html-to-xml>
    </var-def>
</config>


There are three commands (what Web-Harvest calls "processors") in this configuration file: var-def, html-to-xml, and http.  Reading these from the inside outwards, this is what they do:

  1. The innermost processor, http, fetches the web page given in the url attribute -- in this case, the Google home page.
  2. The next processor, html-to-xml, takes the web page, cleans it up a bit and converts it to XML.
  3. The last processor, var-def, defines a new Web-Harvest variable named google and gives it the value of the XML returned by the html-to-xml processor.
To see this in action, click the green "Run" arrow near the top of the GUI.  Web-Harvest will whir through the script and give you a message that "Configuration 'Config 1' has finished execution."  Click OK

This is just the HTML for the Google home page -- it's what the http processor fetched from the Web.  Try clicking on the "html-to-xml [1]" processor and see how the same web page looks encoded as XML.  (Pretty much the same in this case.)


Conclusion

So far I've shown how to get Web-Harvest installed and to create a simple script to download a web page.  Next time I'll go into some more detail about how to use the various Web-Harvest features to extract and save information from a web page.

Wednesday, 5 February 2014

Motorola G....Launches in India





BUY ON FLIPKART NOW..!!


 Apart from Flipkart, Snapdeal is also retailing Moto G. As of now, the pre-order booking has been closed due non-availability of stocks. It recorded 1000 orders within 2 hours of listing the Moto G on 4 February, reported BGR.
Feature-rich Moto G flaunts a 4.5-inch HD (1270x720p) LCD screen protected by Corning Gorilla Glass 3 shield and houses dual-SIM slots. It run on the Android v4.3 Jelly Bean (guaranteed to get KitKat update) powered by a Qualcomm Snapdragon 400 series quad-core processor backed by 1GB RAM and comes in 8GG and 16GB variants.
With the launch, Motorola Moto G is expected to give a stiff challenge to low-cost Indian smartphones like Micromax Canvas Turbo Mini A200, Lava Iris Pro 30, Karbonn Titanium S5 plus and others.
Key specifications of Motorola Moto G:

BUY ON FLIPKART NOW..!!


Model Motorola Moto G (Dual-SIM model confirmed for India)
Display 4.5-inch HD (1270x720p) LCD screen with 329 ppi (pixels per inch), comes protected with Corning Gorilla Glass 3 shield.
OS  Android v4.3 KitKat(Upgrade Guranteed)
Processor Qualcomm Snapdragon 400 series quad-core processor with 1.2GHz CPU speed
RAM 1GB
Storage capacity 8GB/16 GB variants ( no microSD card slot)
Camera Main: 5.0-megapixel camera with LED flash
Front: 1.3-megapixel camera
Network 3G
Battery 2,070 mAh
Add-ons Wi-Fi (802.11 b/g/n),Bluetooth v4.0, USB, NFC, GPS
Dimensions 129.9 x 65.9 x 11.6 mm
Weight 143 g
Price 8GB: ₹12,999) & 16GB: ₹14,499
BUY ON FLIPKART NOW..!!

Sunday, 19 January 2014

Android Local SQLite Database Example

Android platform includes the SQLite embedded database and provides out of the box support to use it via Android APIs. In this tutorial we shall see how to get started with SQLitedatabase in Android. SQLiteis nothing but a relational database and our SQLskills will help.

How to Use SQLite with Android?

To use SQLite in Android, a java class should be created as a sub class of SQLiteOpenHelper. This class will act as a database controller which will have the methods to perform the CRUD operations. This custom java class should override the methods named onCreate()and .onUpgrade()

onCreate() method will be called for the first time when the Android application is run. First the database instance should be created using the method like getReadableDatabase() or getWritableDatabase() based on the type of access required. Android supports this method by providing in-built methods. For that, SQLiteQueryBuilder class should be imported.

Lets have three Android Activity for List, Add and Edit operations and ensure that these are declared in manifest file. And then we need to create subclass of SQLiteHelper to manage SQLite database.
Database & Table Structure :
+------------+------------+------------------------------+---+--------+--+
| Field Name |  Field Type                   | Sample                    |
+------------+------------+------------------------------+---+--------+--+
| ID         |  PRIMARY KEY [Auto Generated] |  1                        |
| Name       |  TEXT                         | Chintan Khetiya           |
| Number     |  TEXT                         | 787-806-0124              |
| Email      |  TEXT                         | khetiya.chintan@gmail.com |
+------------+------------+------------------------------+---+--------+--+
Create or Setup Database
DatabaseHandler.java is going to be our custom java class that will manage the SQLite database. We should extend SQLiteOpenHelper and override the essential methods. The constructor is the hook that will be used to setup the database. While running the Android application, the database will be created for the first time.
public DatabaseHandler(Context applicationcontext) {
super(applicationcontext, "androidsqlite.db", null, 1);
Log.d(LOGCAT,"Created");
}

Table Creation and Upgrade

SQLiteOpenHelper provides callback methods and we should override it to get our job done. Those callback methods that we can override are onCreate(), onUpgrade(), onOpen() and onDowngrade(). And onCreate() and onUpgrade() are abstract methods and must be overridden.

onCreate(SQLiteDatabase database) – is the method which is called first time when the database is created and we need to use this method to create the tables and populate it as per the need.

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT," + KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) – is the method called when upgrade is done. We can drop the database and reset if required.

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again
onCreate(db);
}

 

 
How it looks after all task ?

New
Add New user

Update
Update Record
Delete
Delete Record

View
View All

Note: The Contact details are fake or random

Do some Task : Insert, Read, Update and Delete
We shall have other user defined methods to handle the sql aobve operations. The <code>Contact table </code> will be created when the onCreate() method is invoked while installing the application. For performing operations like insert, update, the SQLiteDatabase instance should be created using the methods like getReadableDatabase() or getWritableDatabase(). ContentValues() are used to pass values to the query.

Insert Records :
// Adding new contact
public void Add_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
values.put(KEY_EMAIL, contact.getEmail()); // Contact Email
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
Read Records  :
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO, KEY_EMAIL }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
cursor.close();
db.close();

return contact;
}
 
Update Records :
// Updating single contact
public int Update_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
values.put(KEY_EMAIL, contact.getEmail());

// updating row

return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });

}
 
Delete Records :
// Deleting single contact
public void Delete_Contact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
db.close();
}
 
 
Read All records
// Getting All Contacts
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();

// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contact.setEmail(cursor.getString(3));
// Adding contact to list
contact_list.add(contact);
} while (cursor.moveToNext());
}

// return contact list
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}

return contact_list;
} 

DOWNLOAD SOURCE CODE

Simple SQLiteHelper example in android

DOWNLOAD : SQLiteHelper.jar


This jar has the following functions.

1. public SQLiteHelper(Context context, String dbname, CursorFactory factory, int version)
This constructor is used to initialize SQLiteOpenHelper class.

2. public void createTable(String table_name, String[] fields, String[] types)
This method is used to create table with fields. Total number of fields and types must be equal.

3. public ArrayList<HashMap<String, Object>> getFields(String table_name)
This method will return all fields with their types as ArrayList.

4. public String insertData(String table_name, String[] fields, String[] data)
This method used to insert record in our table. This will return a String as
Transaction successfully completed
if the transaction completed. Otherwise it will return exception.

5. public ArrayList<HashMap<String, Object>> getAllData(String table_name)
This method used to get all record from our table as arraylist.

6. public ArrayList<HashMap<String, Object>> getSelectedData(String table_name, String fields[], String[] WhereClolmn, String[] WhereClolmnType, String[] data)
This method will return selected data as ArrayList

7. public String UpdateData(String table_name, String[] fields, String[] data, String WHereClassField, String WhereClassFieldData)
This method used to update record in our table. This will return a String as
Transaction Successfully Updated
if the transaction completed. Otherwise it will return exception.

8. public String deleteRecords(String table_name, String field_name, String[] data)
This method used to delete record in our table. This will return a String as
Number of rows deleted


9. public void addFields(String table_name, String field_name, String type, String defaultValue)
This method used to add new field in our table

10. public String executeQuery(String query)
This method used to execute the dynamic query

Sample program using this jar

                                                         MainActivity.java

package com.example.myproject;

import com.example.dbhelper.SQLiteHelper;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MainActivity extends Activity {

 SQLiteHelper helper;
 Context context;
 String DBName;
 CursorFactory factory = null;
 int version = 1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  context = this;
  DBName = "MyDBname";
  helper = new SQLiteHelper(context, DBName, factory, version);
  helper.createTable("MyFirstTable", new String[] { "id", "name" },
    new String[] { "INTEGER PRIMARY KEY AUTOINCREMENT", "TEXT" });
  System.out.println(helper.getFields("MyFirstTable"));
  System.out.println(helper.insertData("MyFirstTable",
    new String[] { "name" }, new String[] { "Gunaseelan" }));
  System.out.println(helper.getAllData("MyFirstTable"));
  System.out.println(helper.UpdateData("MyFirstTable",
    new String[] { "name" }, new String[] { "Guna" }, "name",
    "Gunaseelan"));
  System.out.println(helper.getAllData("MyFirstTable"));
  System.out.println(helper.deleteRecords("MyFirstTable", "name",
    new String[] { "Guna" }));
  System.out.println(helper.getAllData("MyFirstTable"));
 
  helper.addFields("MyFirstTable", "mark", "NUMBER", "");
 
  System.out.println(helper.insertData("MyFirstTable", new String[] {
    "name", "mark" }, new String[] { "Gunaseelan", "98" }));
  System.out.println(helper.getSelectedData("MyFirstTable", new String[] {
    "name", "mark" }, new String[] { "name", "mark" },
    new String[] { "Text", "Number" }, new String[] { "Gunaseelan",
      "98" }));
  System.out.println(helper.executeQuery("Select * from MyFirstTable"));
 }
}
 


                                                              Logcat output

[{Type=INTEGER, Filed=id}, {Type=TEXT, Filed=name}, {Type=NUMBER, Filed=mark}]
Transaction successfully completed
[{id=4, mark=, name=Gunaseelan}]
Transaction Successfully Updated
[{id=4, mark=, name=Guna}]
Number of rows deleted 1
Transaction successfully completed
[{mark=98, name=Gunaseelan}]


Update Samsung Galaxy Y GT-S5360 to Android 4.4 KitKat



Hello readers as you know that Google  has recently released Android 4.4 KitKat and many of the devices already started receiving the update.Today we have Samsung Galaxy y GT-S5360 in the list.
We are going to show you How to Update Samsung Galaxy Y GT-S5360 to Android 4.4 KitKat.

Samsung Galaxy Y is one of the most popular device among the masses. I still remind those days in which talking tom was played in the Samsung Galaxy Y in the TVC. The specifications of the device are good enough to run most of the apps in the playstore and its still selling like hotcakes in the market. Lets see How to Update Samsung Galaxy Y GT-S5360 to Android 4.4 KitKat.
 
The update we are going to write about is not official update its makes your device look alike the latest Google Android 4.4 Kitkat. By installing this Rom you will lose your warranty. Follow the steps carefully this procedure is only meant to update Samsung Galaxy Y GT-S5360 to Android 4.4 KitKat and may not work on any other device. Don’t try to do on other devices this will make the devices not work causing them a hard brick which is hard to recover. Proceed with caution.

Prerequisites to Update Samsung Galaxy Y GT-S5360 to Android 4.4 KitKat

  1. Make sure your device Model is GT-S5360.
  2. Charge the device upto 80%.
  3. Make sure you have rooted the Device and Installed a custom recovery like ClockWorkMod on it. If your device is not rooted, have a look at How to Root Samsung Galaxy Y gt-s5360.
  4. Enable USB Debugging on your device. During the process you will loss all the data present in your device. Kindly back up your device.
  5. Download CWM RECOVERY, CM Kernel & Android 4.4 Kitkat rom.
Now you are good to go to start updating your Samsung Galaxy Y GT-S5360 follow the below steps carefully.

Procedure to Update Samsung Galaxy Y GT-S5360 to Android 4.4 KitKat

  1. Copy all the files you have downloaded from above links to your SD Card.
  2. Now Turn off your mobile and switch it on using Volume up+power+Home button.
  3. The above combination takes you to a recovery screen.
  4. Now select update from SD Card and select CWM.
  5. Now you are in CWM recovery screen. Select Install from SD card.
  6. Select CyanogenMod.zip from the list after installing select reboot recovery.
  7. Now its time to format system, Cache & Dalvik Cache.
  8. After that select Install from sd card and Select Android 4.4 Kitkat rom.
  9. After installing the Rom do a factory reset from the recovery menu itself.

JDBC Connection for Postgres


STEPS :
1.Download the postgre JDBC driver
2.While executing the program first  GRANT ALL PRIVILEGES ON TABLE ttt TO aaa;
3.set the class path for the .jar driver
 export CLASSPATH=/home/exam/Desktop/postgresql.jar:.
4.execute the program



import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.Statement;
import java.util.*;
 
/**
 * @author www.javaworkspace.com
 * 
 */ 


public class ConnectPostgre { 
    public static void main(String[] args) { 
        Connection connection = null; 
        ResultSet resultSet = null; 
        Statement statement = null; 
 
        try { 
            Class.forName("org.postgresql.Driver"); 
            connection = DriverManager.getConnection( 
                    "jdbc:postgresql://localhost:5432/jobportal", "postgres","kiran"); 
            statement = connection.createStatement();
             
             Scanner sc=new Scanner(System.in);
             System.out.println("enter data for new company:cid;name;branch;email;website;address;username;password");
             cid=sc.nextInt();
             name=sc.next();
             branch=sc.next();
             email=sc.next();
             website=sc.next();
             address=sc.next();
             username=sc.next();
             password=sc.next();
             
             //String sql = "INSERT INTO patient " +
               //    "VALUES (4, 'Zara', 'Ali','nama','2013-06-10' ,'1993-6-5')";
             String sql = "INSERT INTO company " +
                   "VALUES ("+cid+", '"+name+"', '"+branch+"','"+email+"','"+website+"' ,'"+address+"' ,'"+username+"' ,'"+password+"')";
             statement.executeUpdate(sql);


 
            resultSet = statement.executeQuery("SELECT * FROM company"); 
            while (resultSet.next())
          { 
               System.out.print("Company NAME:" 
                        + resultSet.getString("name"));
               System.out.print("    Company Branch:" 
                        + resultSet.getString("branch"));
               System.out.print("    Company Email:" 
                        + resultSet.getString("email"));
               System.out.print("    Companyt Website:" 
                        + resultSet.getString("website"));
               System.out.println("    Company Address:" 
                        + resultSet.getString("address"));
           System.out.println("    Company Username:" 
                        + resultSet.getString("username")); 
               System.out.println("    Company Password:" 
                        + resultSet.getString("password"));
 

            }
           //System.out.println("enter data for new patient:id;fname;mname;lname;apptime;dob")
           //int id ;String fname,mname,lname;
          
           
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                resultSet.close(); 
                statement.close(); 
                connection.close(); 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
}                                                           

                                                               OLD OUTPUT
exam@exam-OptiPlex-390:~/Desktop$ export CLASSPATH=/home/exam/Desktop/postgresql.jar:.
exam@exam-OptiPlex-390:~/Desktop$ javac ConnectPostgre.java
exam@exam-OptiPlex-390:~/Desktop$ java ConnectPostgre

patient FNAME:ramu
patient MNAME:papu
patient LNAME:lal
patient time:2013-10-10   
patient DOB:1993-10-10

patient FNAME:asd 
patient MNAME:ssss
patient LNAME:2er 
patient time:null   
patient DOB:1993-06-12

patient FNAME:qqqq 
patient MNAME:cu  
patient LNAME:okedemes 
patient time:2013-01-04   
patient DOB:2013-06-08

exam@exam-OptiPlex-390:~/Desktop$



                                                              NEW OUTPUT


exam@exam-OptiPlex-390:~/Desktop$ export CLASSPATH=/home/exam/Desktop/postgresql.jar:.
exam@exam-OptiPlex-390:~/Desktop$ javac ConnectPostgre.java exam@exam-OptiPlex-390:~/Desktop$ java ConnectPostgreenter data for new patient:id;fname;mname;lname;apptime;
dob
6
new
tttt
yyyy
2013-2-5
1995-2-1

patient FNAME:ramu 
patient MNAME:papu
 patient LNAME:lal 
patient time:2013-10-10   
patient DOB:1993-10-10

patient FNAME:asd
 patient MNAME:ssss
 patient LNAME:2er 
patient time:null 
 patient DOB:1993-06-12

patient FNAME:qqqq
 patient MNAME:cu  
patient LNAME:okedemes
 patient time:2013-01-04 
 patient DOB:2013-06-08

patient FNAME:Zara 
patient MNAME:Ali
patient LNAME:nama
patient time:2013-06-10 
 patient DOB:1993-06-05

patient FNAME:w 
patient MNAME:aa 
patient LNAME:aaa
 patient time:2013-05-09 
 patient DOB:1993-05-04

patient FNAME:new 
patient MNAME:tttt 
patient LNAME:yyyy
patient time:2013-02-05   
patient DOB:1995-02-01

exam@exam-OptiPlex-390:~/Desktop$


*/
                                       

Installing Wireshark on Ubuntu 12.04 LTS

Installing wireshark on Ubuntu 12.04 LTD and limiting packet capture to one group, in this case the group wireshark. I’m sure you can use these instructions for other debian based distributions.
Although you’ll have to take it as read that I’ve only tested it on Ubuntu, feel free to let me know if it doesn’t and I’ll amend the instructions to suit.
First, we install Wireshark from the terminal.

Installing Wireshark

sudoapt-get install wireshark
No interface can be used for capturing in this system with the current configuration

If you run wireshark as a non root user at this stage (see image above), you will get the message “No interface can be used for capturing in this system with the current configuration.”. The following steps will rectify this.

Create the wireshark group.
sudo groupadd wireshark
Add your username to the wireshark group
sudo usermod -a -G wireshark YOUR_USER_NAME
Change the group  ownership of file dumpcap to wireshark
sudo chgrp wireshark/usr/bin/dumpcap
Change the mode of the file dumpcap to allow execution by the group wireshark
sudo chmod/usr/bin/dumpcap
Grant capabilities with setcap
sudo setcap cap_net_raw,cap_net_admin=eip /usr/bin/dumpcap
Verify the change
sudo getcap /usr/bin/dumpcap
At this point, you will need to log out, then back into Unity (Thanks for Jorge for pointing this out).
You should now be able to run Wireshark as a non-root user, just as long as that user is part on the wireshark group, everything should just work.

Wednesday, 15 January 2014

Zoom Image Demo In Android, Zoom Image Example with code in Android , MotionEvent, Matrix example in Android

1- Screen


 





https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi5O9IO8M6qO2dgKMmRru-VvzFyWgjmN80R-GIXXrGQ4BymcPfY8oH4LnPqYus2obrCA1O739-SoYULn-R57duAvDYdhmDUjtKrx_RHaay27t00YlnKwPKk6PJJjHV7EQWreyrG_hInEOI/s1600/Screenshot_2013-05-22-11-31-56.png

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTeD4DZL6J8OX7S5YAD_6woMhWcOsX56V0tTVCIHwQI-o3DQSsLC4WNmpMUzzwlxaF7RQ0UwfZkjIBC5sostAP4MP2AbQZ_9fdA4OsH0Fh9oEH6GUJe0q3nL1FlxC6zE66QAFFR3eE3_A/s1600/Screenshot_2013-05-22-11-32-13.png



2-MainActivity

package com.kiran.zoomimage;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends Activity {
 ImageView imageDetail;
 Matrix matrix = new Matrix();
 Matrix savedMatrix = new Matrix();
 PointF startPoint = new PointF();
 PointF midPoint = new PointF();
 float oldDist = 1f;
 static final int NONE = 0;
 static final int DRAG = 1;
 static final int ZOOM = 2;
 int mode = NONE;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  imageDetail = (ImageView) findViewById(R.id.imageView1);
  /**
   * set on touch listner on image
   */
  imageDetail.setOnTouchListener(new View.OnTouchListener() {

   @Override
   public boolean onTouch(View v, MotionEvent event) {

    ImageView view = (ImageView) v;
    System.out.println("matrix=" + savedMatrix.toString());
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:

     savedMatrix.set(matrix);
     startPoint.set(event.getX(), event.getY());
     mode = DRAG;
     break;

    case MotionEvent.ACTION_POINTER_DOWN:

     oldDist = spacing(event);

     if (oldDist > 10f) {
      savedMatrix.set(matrix);
      midPoint(midPoint, event);
      mode = ZOOM;
     }
     break;

    case MotionEvent.ACTION_UP:

    case MotionEvent.ACTION_POINTER_UP:
     mode = NONE;

     break;

    case MotionEvent.ACTION_MOVE:
     if (mode == DRAG) {
      matrix.set(savedMatrix);
      matrix.postTranslate(event.getX() - startPoint.x,
        event.getY() - startPoint.y);
     } else if (mode == ZOOM) {
      float newDist = spacing(event);
      if (newDist > 10f) {
       matrix.set(savedMatrix);
       float scale = newDist / oldDist;
       matrix.postScale(scale, scale, midPoint.x, midPoint.y);
      }
     }
     break;

    }
    view.setImageMatrix(matrix);

    return true;
   }

   @SuppressLint("FloatMath")
   private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return FloatMath.sqrt(x * x + y * y);
   }

   private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
   }
  });

 }

}

3-activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="matrix"
        android:src="@drawable/images" />

</RelativeLayout>

Total Pageviews

DjKiRu Initative. Powered by Blogger.