Monday, July 22, 2013

Store a file to a bytea column in postgres and retrieve it from postgres and show

I have explained below an example of how to store a file in bytea column in postgres and how to retrieve it and show.

Lets assume i have a postgres table sample with fields id,File,filename

Upload a file to bytea column in postgres
    sampleEntityTable tbl = new sampleEntityTable ();
    File file = new File(path);
      byte[] b = new byte[(int) file.length()];
            try {
                  FileInputStream fileInputStream = new FileInputStream(file);
                  fileInputStream.read(b);
             } catch (FileNotFoundException e) {
                         System.out.println("File Not Found.");
                         e.printStackTrace();
             }
             catch (IOException e1) {
                      System.out.println("Error Reading The File.");
                       e1.printStackTrace();
             }
           
            tbl.setFile(b);

Download a bytea column from postgres to file

    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException{
     response.setContentType("application/pdf");
     response.setHeader("Content-Disposition","attachment; filename="+fileName);
     sampleEntityTableImpl = (sampleEntityTableImpl) applicationContext.getBean("sampleEntityTableImpl");
     long id=8054L;
     sampleEntityTable tbl = sampleEntityTableImpl.getSampleEntityTable(id);
       byte[] b = new byte[(int) tbl.getFile().length];
             try {
                   FileInputStream fileInputStream = new FileInputStream(file);
                   fileInputStream.read(b);
          }
              } catch (FileNotFoundException e) {
                          System.out.println("File Not Found.");
                          e.printStackTrace();
              }
              catch (IOException e1) {
                       System.out.println("Error Reading The File.");
                        e1.printStackTrace();
              }
             ServletOutputStream output = response.getOutputStream();
              output.write(b);
     }

  Another Method

package org.in.my.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConnection {
    public void connect() {
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection connection = null;

        try {
            connection = DriverManager.getConnection(
                    "jdbc:postgresql://localhost:5432/testing", "postgres",
                    "postgres");
            
            File file = new File("d:\\samnew.pdf");
            FileInputStream fis = new FileInputStream(file);
            fis.close();
             
            
            InputStream is = null;
            StringBuffer out = null;
            ResultSet rs = connection.createStatement().executeQuery(
                            "SELECT filedata FROM documents where id=1");
            byte[] imgBytes = null;
            if (rs != null) {
                while (rs.next()) {
                    imgBytes = rs.getBytes(1);
                }

                FileOutputStream os = new FileOutputStream("d:\\samoutput.pdf");
                os.write(imgBytes);
                os.flush();
                os.close();
            }

            rs.close();
            connection.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

If you have tried the example and it is not working. If the file size is double the original size, Then execute the below command in postgres database and then try again

ALTER DATABASE testing SET bytea_output = 'escape';

Monday, July 08, 2013

Digital Signature Example Using Java PdfSignatureAppearance

We are going to digitally sign the document using
For the below example you will need itext-1.3.1.jar

                PdfStamper pefstamp= PdfStamper.createSignature(....

                PdfSignatureAppearance pdfSign = stp.getSignatureAppearance();
               
                pdfSign .setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
                pdfSign .setReason("Testing");
                pdfSign .setLocation("Chennai");
               
                com.lowagie.text.Font font = new com.lowagie.text.Font();
                font.setSize(10);
               
                pdfSign .setLayer2Font(font);
                pdfSign .setVisibleSignature(new com.lowagie.text.Rectangle(30, 830, 190, 750), 1, "Footer");
                pefstamp.close();

Friday, July 05, 2013

How to read a file MIME Type in Java

There is an extension in a file name which says it is an .xls extension. But you can rename an .txt file also to .xls file. So just by reading extension if you want to find the file type, then below are the methods

Method 1
String g = URLConnection.guessContentTypeFromName(filename);
         if( g == null)
         {
             g = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filename);
         }


Method 2
FileNameMap fileNameMap = URLConnection.getFileNameMap();
       String type = fileNameMap.getContentTypeFor("file://" + filename);
       System.out.println(filename + "-"+type);


Method 3
 This is available in Jre 7
try
   {
    Path p = Paths.get(filename);
    s = Files.probeContentType(p);
    System.out.println("Mime type" + s);
   }
   catch(IOException e)
   {

   }


Method 4
File obFile = new File(filename);
String mimeType= URLConnection.guessContentTypeFromName(obFile.getName());
System.out.println(filename + "-"+mimeType);

If you want to read the file and then find the MIME Type

Method 5
  This is using Apache Tikia  which identifies the filetype using magic byte patterns and globbing hints (the file extension) to detect the MIME type.

 File file = new File(filename);
         AutoDetectParser parser = new AutoDetectParser();
         parser.setParsers(new HashMap<MediaType, Parser>());

         Metadata metadata = new Metadata();
         metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());

         InputStream stream;
   try
   {
    stream = new FileInputStream(file);
    parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
       stream.close();
   }
   catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (TikaException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
    String mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
       System.out.println(mimeType);

Tuesday, May 07, 2013

Concatenate 2 CLOB in oracle

SQL
====
Select  CONCAT(clob1, clob2) from table

PL/SQL
====
declare
  clob1 clob;
  clob2 clob;
begin
  clob1 := 'Clob1 ';
  clob2 := '+ Clob2';
  dbms_output.put_line(CONCAT(clob1, clob2));
end;

Wednesday, April 10, 2013

Unable to See Responsibilities after End Date Is Removed

Problem: I am Unable to See Responsibilities after End Date Is Removed

Solution: Go to System Administrator Responsibility

Run the below Concurrent Programs
1. Run the request ‘Sync responsibility role data into the WF table’.
2. Run the request “Synchronize WF LOCAL tables”.
3. Run the request “Workflow Directory Services User/Role Validation” (with parameters 10000, yes,
yes, yes).