Friday, January 28, 2011

Java program to insert image as byte array to postgres database

//Program to insert an image into postgres database as byte array

import java.sql.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class insertImage
{
  public static void main(String[] args)
  {
    PreparedStatement statement = null;
    {
      FileInputStream fin = null;
      try
      {
        System.out.println("Insert Image Example!");
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://x.x.x.x:5432/MYDB";
        Connection oConnection = DriverManager.getConnection(url, "username", "password");
        System.out.println("Sucessfully connected to Postgres Database");
        File imgfile = new File("myimage.jpg");
        fin = new FileInputStream(imgfile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        for (int readNum; (readNum = fin.read(buf)) != -1;)
        {
          bos.write(buf, 0, readNum);
          byte[] bytes = bos.toByteArray();
          String sql = "INSERT INTO my_table (byte_array) VALUES (?)";
          statement = oConnection.prepareStatement(sql);
          statement.setBytes(1, bytes);
          statement.executeUpdate();
          System.out.println("Image inserted into database!");

        }
        statement.close();
        oConnection.close();
      }
      catch (Exception ex)
      {
        System.out.println("Exception:- " + ex);
      }
      try
      {
        fin.close();
      }
      catch (IOException ex)
      {
        System.out.println(" IOException:- " + ex);
      }
    }
  }
}

Monday, January 10, 2011

Java program to send and read response from a serial to usb converter (without using modem)

//Program to send and read response from a serial to usb converter

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.*;
import java.util.*;

public class PortWriter implements Runnable,SerialPortEventListener
{
  static Enumeration ports;
  static CommPortIdentifier pID;
  static OutputStream outStream;
  static SerialPort serPort;
  static InputStream is;
  static PrintStream os;
  int i = 0;
  byte[] readBuffer = new byte[10];
  int numBytes = 0;

  public PortWriter() throws Exception
  {
    try
      {
        serPort = (SerialPort) pID.open("COM25", 2000);
        System.out.println("\ngetDataBits"+serPort.getDataBits());
        System.out.println("\ngetStopBits"+serPort.getStopBits());
        System.out.println("\ngetParity"+serPort.getParity());
        System.out.println("\ngetBaudRate"+serPort.getBaudRate());
        serPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        outStream = serPort.getOutputStream();
        serPort.addEventListener(this);
        serPort.notifyOnDataAvailable(true);
        is = serPort.getInputStream();
      }
      catch (Exception e)
      {
        System.out.println("PortInUseException : " + e);
      }
    }

    public static void main(String[] args) throws Exception
    {
      ports = CommPortIdentifier.getPortIdentifiers();
      while (ports.hasMoreElements())
      {
        pID = (CommPortIdentifier) ports.nextElement();
        if (pID.getPortType() == CommPortIdentifier.PORT_SERIAL)
        {
          if (pID.getName().equals("COM25"))
          {
            PortWriterThread pWriter = new PortWriterThread();
            System.out.println("USB found");
            try
            {
              String smsMessage = "TEST DATA";
              send(smsMessage);

              if (is != null)
              {
                is.close();
//System.out.println("Closing input stream..");
              }
              if (outStream != null)
              {
                outStream.close();
// System.out.println("Closing output stream..");
              }
              if (serPort != null)
                {
                serPort.close();
//System.out.println("Closing serial Port..");
              }
            }
            catch (Exception e)
            {
              System.out.println("could not write to outputstream:");
                System.out.println(e.toString());
              }
            }
          }
        }
      }

      public static void send(String cmd)
      {
        System.out.println("Sending...");
        try
        {
          outStream.write(cmd.getBytes());
          System.out.println(cmd+" send SUCCESS");
        }
        catch (Exception e)
        {
          System.out.println("Exception in send:- " + e);
        }
      }


/**
* Method declaration
*
*
* @see
*/
      public void run()
      {
        try
        {
          Thread.sleep(1000);
        }
        catch (Exception e)
        {
          System.out.println("Exception in run:-"+e);
        }
      }

/**
* Method declaration
*
*
* @param event
*
* @see
*/
      public void serialEvent(SerialPortEvent event)
      {
        switch (event.getEventType())
        {

          case SerialPortEvent.BI:

          case SerialPortEvent.OE:

          case SerialPortEvent.FE:

          case SerialPortEvent.PE:

          case SerialPortEvent.CD:

          case SerialPortEvent.CTS:

          case SerialPortEvent.DSR:

          case SerialPortEvent.RI:

          case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
          break;

          case SerialPortEvent.DATA_AVAILABLE:
          byte[] readBuffer = new byte[20];

          try
          {
            while (is.available() > 0)
            {
              int numBytes = is.read(readBuffer);
            }
            System.out.print("Reading Data>>>"+new String(readBuffer));
          }
          catch (Exception e)
          {
            System.out.println("Exception in reading from input stream:-" + e);
          }
          break;
        }
      }
    }

Tuesday, January 4, 2011

Command to find out the ports opened for an IP address

Enter the command in terminal
nmap -v x.x.x.x

This will display the ports opened for that IP address.

Thursday, December 23, 2010

Create case sensitive Database

My aim was to create a postgresql database through Java Program. The database name has consecutive Capital and small letters.

//Program to Create a Postgresql database
import java.io.*;
import java.sql.*;

public class CreateDatabase
{
public static void main(String[] args)
{
System.out.println("Database creation example!");
Connection oConnection = null;
try
{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://172.x.x.x:5432/postgres";
oConnection = DriverManager.getConnection(url, "postgres", "12345");
System.out.println("Sucessfully connected to Postgres Database");
try
{
Statement st = oConnection.createStatement();
st.executeUpdate("CREATE DATABASE \"TeStDb\" WITH
OWNER=postgres ENCODING='UTF8';);
}
catch (Exception s)
{
System.out.println("SQL statement is not executed:-" + s);
}
}
catch (Exception e)
{
System.out.println("Exception:- "+e);
}
}
}

Monday, December 13, 2010

Starting & Stopping services on Ubuntu bootup

my@my-desktop:~$ sudo su
Provide the command update-rc.d YOURSERVICENAME defaults in terminal.

root@my-desktop:/home/my# update-rc.d YOURSERVICENAME defaults

This will display the following:
Adding system startup for /etc/init.d/YOURSERVICENAME ...
/etc/rc0.d/K20YOURSERVICENAME -> ../init.d/YOURSERVICENAME
/etc/rc1.d/K20YOURSERVICENAME -> ../init.d/YOURSERVICENAME
/etc/rc6.d/K20YOURSERVICENAME -> ../init.d/YOURSERVICENAME
/etc/rc2.d/S20YOURSERVICENAME -> ../init.d/YOURSERVICENAME
/etc/rc3.d/S20YOURSERVICENAME -> ../init.d/YOURSERVICENAME
/etc/rc4.d/S20YOURSERVICENAME -> ../init.d/YOURSERVICENAME
/etc/rc5.d/S20YOURSERVICENAME -> ../init.d/YOURSERVICENAME

Restart the PC. The service YOURSERVICENAME will be started automatically on PC boot up.

To remove the service on PC boot

Provide the command,update-rc.d YOURSERVICENAME remove in terminal.
root@my-desktop:/home/my# update-rc.d YOURSERVICENAME remove

Tuesday, November 23, 2010

RMI on Ubuntu 9.04

I was having a problem with RMI running on Ubuntu PC (Ubuntu 9.04).

Whenever I tried to run my RMI program on Ubuntu PC, it showed the error,
java.rmi.ConnectException: Connection refused to host 127.0.1.1; nested exception is: java.net.ConnectException: Connection refused.
I have no idea why the host is here 127.0.1.1 ...

I tried out in many Ubuntu PC’s and everywhere it showed this error.

Found a solution to this problem:
I checked the /etc/hosts on Ubuntu machine and saw that 127.0.1.1 was mapped to ubuntu-PC name, so I've rewritten it to my correct LAN IP.

The /etc/hosts file in my PC looks like this
127.0.0.1 localhost
127.0.1.1 MYPCNAME

# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts


Using the command vi /etc/hosts, I changed the 2nd line to

127.0.0.1 localhost
172.16.1.1 MYPCNAME

# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts


After that it worked fine!

Tuesday, November 16, 2010

Useful Linux Commands

• List files, starting with 'V_20100810' and sort results by most recent
ls -lt V_20100810*

• File monitoring(tail displays the lines and then monitors the file)
tail -f V_20100810_DataAccq.log

• Linux version
cat /etc/*-release

• List files with permission details
ls –l

• Remove a folder with its contents
rm –r –f foldername

• Remove all files in a folder
rm -r -f *

• Shutdown PC
shutdown -h now

• Change the user and/or group ownership of each file-chown
chown newowner filename

chown root:root /backup
setup user and group ownership to root user only for /backup directory

chown root:ftp /home/data/file.txt
Set user user ownership to root user and allow any member of ftp group to access file.txt (provided that they have sufficient read/write rights).

• Change file access permissions such as read, write etc. - chmod
chmod [-r] permissions filenames
• r - Change the permission on files that are in the subdirectories of
the directory that you are currently in.
permission - Specifies the rights that are being granted. Below is the
different rights that you can grant in an alpha numeric format.
filenames - File or directory that you are associating the rights with
Permissions
• u - User who owns the file.
• g - Group that owns the file.
• o - Other.
• a - All.
• r - Read the file.
• w - Write or edit the file.
• x - Execute or run the file as a program.


Numeric Permissions:

CHMOD can also to attributed by using Numeric Permissions:

• 400 read by owner
• 040 read by group
• 004 read by anybody (other)
• 200 write by owner
• 020 write by group
• 002 write by anybody
• 100 execute by owner
• 010 execute by group
• 001 execute by anybody