/* * Java program to retrieve a file from the Remedy ESDDB Database * * The program takes a file ID, retrieves the file from the database and saves it to the current directory. * Some of the code is based on the LongRawSample example application on the Oracle Website. * * Author: Chris Thomson * Email: Chris.Thomson@vodafone.com / Chris.Thomson@uk.fujitsu.com * Date: 09/10/2007 */ //java utility classes import java.util.Enumeration; import java.util.ResourceBundle; import java.util.Properties; import java.util.zip.GZIPInputStream; // java IO classed import java.io.IOException; import java.io.InputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.SequenceInputStream; import java.io.ByteArrayInputStream; // java SQL classes import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; import java.sql.PreparedStatement; import oracle.jdbc.pool.OracleDataSource; public class RemedyFile { class RemedyInputStream extends GZIPInputStream { /** * Creates a new input stream with a default buffer size. * @param in the input stream * @exception IOException if an I/O error has occurred */ public RemedyInputStream(InputStream in) throws IOException { super(in); } /* * Reads GZIP member trailer. */ private void readTrailer() throws IOException { System.out.println("THIS CODE NEVER EXECUTES"); InputStream in = this.in; int n = inf.getRemaining(); if (n > 0) { in = new SequenceInputStream( new ByteArrayInputStream(buf, len - n, n), in); } long v = crc.getValue(); //if (readUInt(in) != v || readUInt(in) != inf.getTotalOut()) { // throw new IOException("Corrupt GZIP trailer"); //} } } /** Database Connection Object */ private Connection connection = null; /* Main method takes file IDs as arguments and passes them to getFile. */ public static void main(String[] args) { RemedyFile remedyFile = new RemedyFile(); Properties prop = remedyFile.dbConnection(); //Get the connection to the database remedyFile.getFile(args[0], prop); remedyFile.createGZIP(); remedyFile.unGZIP(); } /* Uncompress the GZIP file. */ private void unGZIP() { try { // Open the compressed file String inFilename = "outfile.gz"; RemedyInputStream in = new RemedyInputStream(new FileInputStream(inFilename)); // Open the output file String outFilename = "pic.jpg"; FileOutputStream out = new FileOutputStream(outFilename); // Transfer bytes from the compressed file to the output file byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Close the file and stream in.close(); out.close(); } catch (IOException ex) { System.out.println(ex.toString()); } } /*Convert the outputfile to a GZIP file. */ private void createGZIP() { String filename = "testfile"; //byte b = 0xf1; byte gzHeader[] = {(byte)0x1f, (byte)0x8b, (byte)0x08, (byte)0x08, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03}; try { //Open the file read from the DB and get its size File rawFile = new File ("outputfile"); int fileSize = (int)rawFile.length(); System.out.println("File Size: "+fileSize); //Create an Input Stream and skip the first 7 byte of the raw file as we don't care about them FileInputStream inputStream = new FileInputStream(rawFile); inputStream.skip(7); // Create a new file which will be a proper GZip file FileOutputStream outfile= new FileOutputStream("outfile.gz"); outfile.write(gzHeader); //Write the header outfile.write(filename.getBytes()); //Write the filename which is stored in the file //Write out the raw file int chunk=0; while( (chunk = inputStream.read()) != -1) { outfile.write(chunk); } outfile.write(intToByteArray(fileSize)); //Append the filesize of the original file } catch( Exception ex ) { //Trap IO Errors System.out.println(ex.toString()); } } //Convert filesze to byte[] to write to file private byte[] intToByteArray (final int integer) { int byteNum = (40 - Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer)) / 8; byte[] byteArray = new byte[4]; for (int n = 0; n < byteNum; n++) byteArray[3 - n] = (byte) (integer >>> (n * 8)); return (byteArray); } /*Get the file and save it to the current directory.*/ private void getFile(String fileID, Properties prop) { System.out.println("Getting file for "+fileID+"."); String name = null; InputStream readData = null; String userHome = null; String fullName = null; try{ // Query the logo of the selected airline - (String)prop.get("DataColumn") String query = "SELECT "+(String)prop.get("DataColumn")+" FROM "+(String)prop.get("FileTable")+" WHERE "+(String)prop.get("EntryID")+"='"+fileID+"'"; System.out.println("Executing Query:"); System.out.println(query); // Create a PreparedStatement object for executing the query PreparedStatement pst = connection.prepareStatement(query); // bind the parameter with code value //pst.setString(1,fileID); // Obtain the result-set for the selected airline record ResultSet result = pst.executeQuery(); if( result.next() ) { // Fetch column values fullName = "outputfile"; readData = result.getBinaryStream(1); if (result.wasNull()) { System.out.println("Result set was Null!!!"); } System.out.println("Left to read: "+readData.available()); // create new file File outFile = new File(fullName); // Write the byte array into a local file FileOutputStream file= new FileOutputStream(outFile); int chunk=0; System.out.println("1"); // write to the local file until image (LONGRAW) data is found while( (chunk = readData.read()) != -1) { file.write(chunk); } System.out.println("1"); // flush the data file.flush(); file.close(); // close the file pst.close(); //closing the statement object System.out.println("File Written"); } } catch( Exception ex ) { //Trap IO Errors System.out.println(ex.toString()); } } /** * This method reads a properties file which is passed as * the parameter to it and load it into a java Properties * object and returns it. */ private Properties loadParams(String file) throws IOException { // Loads a ResourceBundle and creates Properties from it Properties prop = new Properties(); ResourceBundle bundle = ResourceBundle.getBundle(file); Enumeration keys = bundle.getKeys(); String key = null; while(keys.hasMoreElements()) { key = (String)keys.nextElement(); prop.put(key, bundle.getObject(key)); } return prop; } /** * Creates a database connection object using DataSource object. Please * substitute the database connection parameters with appropriate values in * Connection.properties file */ private Properties dbConnection() { Properties prop = null; try { System.out.println("Trying to connect to the Database"); // Load the properties file to get the connection information prop = this.loadParams("Connection"); // Create a OracleDataSource instance OracleDataSource ods = new OracleDataSource(); // Sets the driver type ods.setDriverType("thin"); // Sets the database server name ods.setServerName((String)prop.get("HostName")); // Sets the database name ods.setDatabaseName((String)prop.get("SID")); // Sets the port number ods.setPortNumber(new Integer((String)prop.get("Port")).intValue()); // Sets the user name ods.setUser((String)prop.get("UserName")); // Sets the password ods.setPassword((String)prop.get("Password")); connection=ods.getConnection(); System.out.println(" Connected to " + prop.get("SID") + " Database as " + prop.get("UserName")); } catch(SQLException ex) { // Trap SQL errors System.out.println( "Error in Connecting to the Database "+'\n'+ex.toString()); } catch(IOException ex) { // Trap IO errors System.out.println( "Error in reading the properties file "+'\n'+ex.toString()); } return prop; } }