Thursday, November 11, 2010

Getting started JDBC in Ubuntu with MySQL

Installation of MySQL

Install mysql client, server and the jdbc connector, either via synaptic or by using the following.

sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysql-java

Set up MySQL default password 

Set up the password for the root user as 'root' or whatever you want. The last entry is the password.

mysqladmin -u <root> password <root>

Use MySQL client with Terminal


Go to Applications --> Accessories --> Terminal

Now type: sudo mysql --user=<user> --password=<password>

Create a database 


create database <leann>; //Here "leann" is the database name. Don't forget semi-colon.

User Creation and privileges


Create a user with access to that table. Replace the items in square brackets by the database name, and the chosen user and password. Don't type in the square brackets !

grant all privileges on <database>. * to <user>@localhost identified by <password>;
flush privileges;

Setting up the user to use JDBC in ubuntu

CLASSPATH=$CLASSPATH:/usr/share/java/mysql.jar
export CLASSPATH

Alternatively, you can set it for all users, by editing /etc/environment.

CLASSPATH=".:/usr/share/java/mysql.jar"

Testing in Java

import java.sql.*;
import java.util.Properties;
/**
 * https://help.ubuntu.com
 **/
public class DBDemo
{
  // The JDBC Connector Class.
  private static final String dbClassName = "com.mysql.jdbc.Driver";

  // Connection string. emotherearth is the database the program
  // is connecting to. You can include user and password after this
  // by adding (say) ?user=paulr&password=paulr. Not recommended!

  private static final String CONNECTION =
                          "jdbc:mysql://127.0.0.1/emotherearth";

  public static void main(String[] args) throws
                             ClassNotFoundException,SQLException
  {
    System.out.println(dbClassName);
    // Class.forName(xxx) loads the jdbc classes and
    // creates a drivermanager class factory
    Class.forName(dbClassName);

    // Properties for user and password. Here the user and password are both 'paulr'
    Properties p = new Properties();
    p.put("user","paulr");
    p.put("password","paulr");

    // Now try to connect
    Connection c = DriverManager.getConnection(CONNECTION,p);

    System.out.println("It works !");
    c.close();
    }
}

Thursday, November 4, 2010

Copy Image From Clipboard

package isuru;

/**
 *
 * @author Isuru
 */
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Main {

    public static void main(String[] args) {
        //Create clipboard object
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        try{
            //Get data from clipboard and assign it to an image
            //clipboard.getData() returns an object, so we need to cast it to a BufferedImage
            BufferedImage image = (BufferedImage)clipboard.getData(DataFlavor.imageFlavor);

            //file that we'll save to disk
            File file = new File("image.jpg");

            /**
             * class to write image to disk. You specify the image
             * to be saved, its type, and then the file in which to write the image data.
             */

            ImageIO.write(image, "jpg", file);

        }catch(UnsupportedFlavorException ufe){
            ufe.printStackTrace();
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
    }  

}
 
Found from a online forum and tested in my system.  

Monday, August 23, 2010

Java Robot Class in Java

This is a quick snap of using Robot class of Java. You can find full article on keyboard and mouse events here.
package test;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Main{
    public static void main(String args[]) throws AWTException
    {
        Robot robot = new Robot();

       int keyEvent[] = {
            KeyEvent.VK_H,
            KeyEvent.VK_E,
            KeyEvent.VK_L,
            KeyEvent.VK_L,
            KeyEvent.VK_O,
            
        };
       for(int i = 0; i < keyEvent.length; i++)
       {
          robot.keyPress(keyEvent[i]);
          robot.delay(1000);
       }

    }
}

Tuesday, August 17, 2010

Yahoo mail is down without noticing users.

Yahoo mail is down without noticing users about any scheduled maintenance. When I try to access yahoo mail, I get different kinds of error massages including LaunchFFC-1. These are the screenshots.







And is this an attack? or are they updating yahoo mail?

Friday, August 13, 2010

How to make a Socket Connection?

This program creates a socket connection to the server of atomic clock in Boulder, Colorado.

import java.io.*;
import java.net.*;
import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        try
        {
            Socket time = new Socket("time-A.timefreq.bldrdoc.gov", 13);
            try
            {
                InputStream inStream = time.getInputStream();
                Scanner in = new Scanner(inStream);

                while(in.hasNext())
                {
                    String line = in.nextLine();
                    System.out.println(line);
                }
            }
            finally
            {
                time.close();
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Thursday, August 12, 2010

Java - Files and Streams Summary Part 2

1.6 File Streams


The classes FileInputStream and FileOutputStream define byte input and output streams that are connected to files.

FileInputStream(File file) - Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

FileInputStream(String name) - Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

FileInputStream(FileDescriptor fdObj) - Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.


FileOutputStream(File file) - Creates a file output stream to write to the file represented by the specified File object.


FileOutputStream(File file, boolean append) - Creates a file output stream to write to the file represented by the specified File object.


FileOutputStream(FileDescriptor fdObj) - Creates an output file stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.


FileOutputStream(String name) - Creates an output file stream to write to the file with the specified name.


FileOutputStream(String name, boolean append) - Creates an output file stream to write to the file with the specified name.








Java - Files and Streams Summary Part 1

1.1  Introduction.
Java.io package provides an extensive library of classes to deal with input and output. Java provides streams as a general mechanism for dealing with data  I/O.

There are three kinds of streams.

  1. Byte Streams 
  2. Character Streams
  3. Buffered Streams
An input stream - an object that an application use to read sequence of data, acts as a source of data.
An output stream - an object that an application use to write a sequence of data, acts as a destination of data.

Entities work as output or input streams.

  1. An array of character or bytes.
  2. A file
  3. A pipe 
  4. A network connection
1.2 File Class

File(String pathname)
          Creates a new File instance by converting the given pathname string into an abstract pathname.

Methods

  1. String getName() - Returns the name of the file, excluding directory file resides.
  2. String getPath() - Returns the (absolute or relative) pathname of the file.
  3. String getAbsolutePath() - Returns the absolute pathname string of this abstract pathname.
  4. Stirng getCononicalPath() - Platform-dependent. Returns the canonical form of this abstract pathname.
  5. String getParent() -  The parent part of the pathname of this File object is returned if one exists, otherwise the null value is returned.
  6. boolean isAbsolute() - Whether a File object represents an absolute pathname can be determined using this method.
  7. long lastModified() - Returns the time that the file denoted by this abstract pathname was last modified.
  8. long length() - Returns the size (in bytes) of the file represented by the File object.
  9. boolean equals(Object obj) - This method only compares the pathnames of the File objects, and returns true if they are identical.
  10. boolean exists() - Return true if specified file or directory is existed.
  11. boolean isFile() - Return true if the object is a file.
  12. boolean isDirectory() - Returns true if the object is a directory.
  13. boolean canRead() - Returns true if the object has read access.
  14. boolean canWrite() - Returns true if the object has writing access.
  15. String[] list() - Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
  16. String[] list(FileNameFilter filter) -  Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
1.3 Creating New Files and Directories
  1. boolean  createNewFile() throws IOException  - Creates  a new, empty file named by the abstract pathname if,and only if, a file with this name does not already exist. Return value is true if the file is created, else false means file is already exists.
  2. boolean mkdir() - Creates the directory named by this abstract pathname.
  3. boolean mkdirs() - Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.
1.4 Rename Files and Directories
  1. boolean renameTo(File dest) - Renames the file denoted by this abstract pathname.
1.5 Deleting Files and Directories
  1.  boolean delete() -  Deletes the file or directory denoted by this abstract pathname.