String str;
java.util.Date currentDate = new java.util.Date(); //gets the current date
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
str = sdf.format(currentDate);
String nameOfTextFile =getServletContext().getRealPath("imp.txt");
try
{
PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
pw.println(str);
//clean up
pw.close();
}
catch(IOException e)
{
out.println(e.getMessage());
}
Monday, April 4, 2011
Friday, March 11, 2011
Copy file permissions from one file to another
I need to copy the file permission of FirstFile.jar to SecondFile.jar.
You may know how to change file permissions using chmod but, if you already have a file with the permissions you want to assign to some other files, you can use --reference option in chmod
chmod --reference
As an example, if you have this:
-rwxrwxrwx 1 root root 0 Dec 20 15:35 FirstFile.jar
-rwx------ 1 root root 0 Dec 20 15:35 SecondFile.jar
And you run:
chmod --reference FirstFile.jar SecondFile.jar
You should then have this:
-rwxrwxrwx 1 root root 0 Dec 20 15:35 FirstFile.jar
-rwxrwxrwx 1 root root 0 Dec 20 15:35 SecondFile.jar
Just be sure, you are the owner of the files, you that you have permission to change them.
You may know how to change file permissions using chmod but, if you already have a file with the permissions you want to assign to some other files, you can use --reference option in chmod
chmod --reference
As an example, if you have this:
-rwxrwxrwx 1 root root 0 Dec 20 15:35 FirstFile.jar
-rwx------ 1 root root 0 Dec 20 15:35 SecondFile.jar
And you run:
chmod --reference FirstFile.jar SecondFile.jar
You should then have this:
-rwxrwxrwx 1 root root 0 Dec 20 15:35 FirstFile.jar
-rwxrwxrwx 1 root root 0 Dec 20 15:35 SecondFile.jar
Just be sure, you are the owner of the files, you that you have permission to change them.
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);
      }
    }
  }
}
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;
        }
      }
    }
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.
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);
}
}
}
//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
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
Subscribe to:
Posts (Atom)