Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

MyJava file(JCreater) cannot connect to oracle database 10g express edition

843810Jan 20 2008
Hi all,i am facing difficulties in connecting my java source file to the oracle database 10g express edition. This is a free trial edition download from the web. Below is the file codes, if anybody know please reply to this posting. Thank you in advance. I would like to view all my rows in the table under the oracle database.


package com.ids;

//import com.sun.mail.util.BASE64DecoderStream;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.StringTokenizer;
import java.util.Iterator;
import java.util.Date;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.LinkedList;
import java.security.cert.Certificate;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.KeyPair;
import java.security.Key;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.InvalidKeyException;
import java.security.cert.CertificateException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.BadPaddingException;
//import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.zip.*;
import java.util.Enumeration;
import java.io.FileFilter;
//import com.ids.config.IDSConfig;
import java.util.logging.*;
//import javax.swing.*;
import java.sql.*;


/**
* @author John Lim
* Allows the creation and storage of file hashes in a database and
* to allow for checking of integrity by comparing hashes against
* the actual file in the file system. Also allows the identification of
* missing files in the file system.
*/

public class HashFile {

private String keyAlias;
private String keyPass;
private KeyStore keyStore;
private KeyPair keyPair;
private SecretKeySpec aesKSpec;
private BufferedReader bfstream;
private String hashFileName;

private Connection conn;
private HashSet<String> fileFilter;

private String logID;
private Logger log;
private String quarantinePath;

private Cipher aesCipher;
private Cipher aesEncryptCipher;
private byte[] raw;
//private IDSConfig config;
private boolean doEncrypt;
private boolean initialized;
private boolean debug;

public int RSA_SIZE = 2048;

public static final int FILE_HASH_MATCH = 0;
public static final int FILE_HASH_MISMATCH = 1;
public static final int FILE_HASH_NOT_EXIST = 2;
public static final int FILE_NOT_EXIST = 3;

public static final int PRIVATE_KEY = 1;
public static final int PUBLIC_KEY = 2;
// final private String driverName = "com.oracle.jdbc.Driver";
final private String driverName = "oracle:jdbc:Driver:OracleDriver";




/** Default constructor */
public HashFile() {
keyPair = null;
keyStore = null;
keyAlias = null;
keyPass = null;
aesKSpec = null;
quarantinePath = null;
aesEncryptCipher = null;
aesCipher = null;
//config = null;
doEncrypt = false;

logID = null;
log = null;
fileFilter = new HashSet<String>();
// try {
// Class.forName(driverName).newInstance();
// } catch (Exception e) {
// System.err.println("Cannot register jdbc driver : " + e);
// }
// try {
//config = IDSConfig;
// debug = config.isDebug();
// } catch(Exception e) {
// System.err.println("Error loading properties file");
// }

}

/**
* Constructor to open keystore, along with keystore password
* and hash file containing encrypted symmetric keys. If
* hash file does not exist, a new set of symmetric keys is
* created.
*/
public HashFile(String hashFile, String ks, String kp, String alias,
String keyPass) throws SQLException {
this();
String user = null;
hashFileName = hashFile;
//monitoredFiles = new HashMap();
doEncrypt = true;

// try {
int tries = 0;
boolean success = false;
while ((tries < 3) && !success) {
success = getDBConnection();
tries++;
}
if (!success) {
initialized = false;
return;
}
//String connStr = "") + "?user" + "=" + config.getDBUID() + "&password=" + config.getDBPass();
//conn = DriverManager.getConnection(connStr);
// conn = DriverManager.getConnection("jdbc:oracle://localhost/ids?user=hr&password=hr");
conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@localhost:1521/OracleServiceXE");
// conn = DriverManager.getConnection("jdbc:oracle://localhost:8080:xe","hr","hr");

//conn = DriverManager.getConnection("jdbc:oracle://localhost:8080:xe","hr","hr");
System.out.println("connected");
//FileInputStream is = new FileInputStream(ks);
//keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//keyStore.load(is, kp.toCharArray());
//getKeys(alias,keyPass);
// }
/*catch (KeyStoreException e) {
System.err.println("Key store exception - " + e);
} catch (CertificateException e) {
System.err.println("Key store exception - " + e);
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
*/
// catch (java.io.IOException e) {
// System.err.println("IO exception - " + e);
// return;
// }

try {
File hF = new File(hashFileName);
if (hF.exists() && hF.isFile() && (keyPair != null)) {

bfstream = new BufferedReader(new FileReader(hashFileName));

String encKey = bfstream.readLine();
//System.out.println("Length of encKey - " + encKey.length());

byte[] cKey = new BASE64Decoder().decodeBuffer(encKey);
//byte[] cKey = new Base64().decode(encKey.getBytes());
//System.out.println("read bfstream - " + cKey.length);

// decrypt AES key with RSA
Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
raw = cs.doFinal(cKey);
//System.out.println("after dectypting with RSA" + raw.length);

aesKSpec = new SecretKeySpec(raw, "AES");
//System.out.println("after sss");
aesCipher = Cipher.getInstance("AES");
//System.out.println("after getinstance");
aesCipher.init(Cipher.DECRYPT_MODE, aesKSpec);
//System.out.println("after init");
aesEncryptCipher = Cipher.getInstance("AES");
aesEncryptCipher.init(Cipher.ENCRYPT_MODE, aesKSpec);

bfstream.close();
} else if (!hF.exists() && (keyPair != null)) {
// Need to delete all entries in database as the entries
// are no longer usable.
flushDb();

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256);


// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
raw = skey.getEncoded();

aesKSpec = new SecretKeySpec(raw, "AES");
aesCipher = aesCipher.getInstance("AES");

BufferedWriter bfstream = new BufferedWriter(new FileWriter(hashFileName,false));

Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] eRaw = cs.doFinal(raw);
System.out.println("length encoded -" + eRaw.length);
//String sRaw = new String(new Base64().encode(eRaw));

// bfstream.write(sRaw);
bfstream.newLine();

bfstream.close();
//aesCipher.init(Cipher.DECRYPT_MODE, aesKSpec);
}
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return;
} catch (IOException e) {
System.err.println("IO error - " + e);
return;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return;
} finally {
try {
if (bfstream != null) {
bfstream.close();
}
} catch (IOException e) {}
}
initialized = true;
}

public HashFile(boolean encrypt) {
this();
doEncrypt = encrypt;

if (!doEncrypt) {
Object monitoredList = new ArrayList();
//List monitoredList = new ArrayList();

// List list = (List)o;

monitoredList = new HashMap();
// Object o = (List)monitoredList.getAdapter(java.util.List.class);

try {
//String connStr = config.getDBCon() + "?user" + "=" + config.getDBUID() + "&password=" + config.getDBPass();
conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@localhost:1521/OracleServiceXE");
// conn = DriverManager.getConnection(connStr);
} catch (SQLException ex) {
if (debug){
System.out.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}
}
}
}

private boolean getDBConnection() {
try {
//String connStr = config.getDBCon() + "?user" + "=" + config.getDBUID() + "&password=" + config.getDBPass();
conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@localhost:1521/OracleServiceXE");
// conn = DriverManager.getConnection(connStr);
return true;
} catch (SQLException e) {
try{
Thread.sleep(5000);
} catch (InterruptedException ex) {
System.err.println("Thread sleep exception: " + ex);
}
return false;
}
}

public void setQuarantinePath(String path){
quarantinePath = path;
}

/**
* Returns an array of filenames which are missing
*/
public String[] getMissingFiles() {
ResultSet rs = null;
Statement stmt = null;
File file = null;
ArrayList<String> fileList = new ArrayList<String>();
String[] fileArr = null;;

try {
conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@localhost:1521/OracleServiceXE");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT filepath FROM hash");

String filePath;
while (rs.next()) {
filePath = decrypt(rs.getString(1));
file = new File(filePath);
if (!file.exists()) {
fileList.add(filePath);
}
}
if (fileList.size() > 0) {
fileArr = new String[fileList.size()];
for (int i=0;i<fileList.size();i++)
fileArr[i] = fileList.get(i);
}

if (stmt != null) {
try {
rs.close();
stmt.close();
} catch (SQLException sqlEx) { // ignore
if (debug) {
stmt = null;
System.err.println("SQLException: " + sqlEx.getMessage());
}
}
}
return fileArr;

} catch (SQLException ex) {
if (debug) {
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}
return null;
} finally {
if (stmt != null) {
try {
rs.close();
stmt.close();
} catch (SQLException sqlEx) { // ignore
stmt = null;
}
}
}
}


public HashSet getHashList() {
ResultSet rs = null;
Statement stmt = null;
File file = null;

Object fileList = new ArrayList();
// monitoredList = new HashMap();

// return (HashSet) fileList;





try {
conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@localhost:1521/OracleServiceXE");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT filepath FROM hash");

String filePath;
/* while (rs.next()) {
filePath = decrypt(rs.getString(1));
fileList.add(filePath);
}*/

if (stmt != null) {
try {
rs.close();
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
System.err.println("SQLException: " + sqlEx.getMessage());
}
}
return (HashSet) fileList;
} catch (SQLException ex) {
if (debug) {
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}
return null;
} finally {
if (stmt != null) {
try {
rs.close();
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
}
}


public String[] getMissingFiles(ArrayList<String> dirFilter) {
String[] files = getMissingFiles();
if (files != null) {
LinkedList<String> fileList = new LinkedList<String>();
for (int i=0;i<files.length;i++)
fileList.add(files);
String[] filter = dirFilter.toArray(new String[0]);
for (int i=0;i<fileList.size();i++) {
for (int j=0;j<filter.length;j++) {
if (!fileList.get(i).startsWith(filter[j]))
fileList.remove(i);
}
}
return (String[])fileList.toArray();
} else
return null;
}


/**
* Returns 3 lists of files that have been changed, removed or updated
* list[0] - list of files that have been changed
* list[1] - list of files that have been removed
* list[2] - list of files that are added
**/

/* public ArrayList<String>[] getChanges() {
ResultSet rs = null;
Statement stmt = null;
File file = null;
ArrayList<String> changedList = new ArrayList<String>();
ArrayList<String> missingList = new ArrayList<String>();
ArrayList<String> newList = new ArrayList<String>();
ArrayList<String>[] result = new ArrayList[3];
//ArrayList<String>[] result = new ArrayList<String>[3];
//ArrayList<String>[] result = new ArrayList<String>[3];

MonitorList fileList = new MonitorList();
int i=0,compareResult;
while (config.getbackupLoc(i) != null) {
fileList.addDir(new File(config.getbackupLoc(i++)));
}

HashList dbList = getHashList();
String[] filter = fileFilter.toArray(new String[0]);
for (int c=0;c<filter.length;c++) {
fileList.addFileFilter(filter[c]);
dbList.removeExt(filter[c]);
}


dbList.remove(config.getIDSConfig());

String currEntry = fileList.getCurrent();
while (currEntry != null) {
file = new File(currEntry);
if (file.exists()) {
compareResult = this.compareFileHash(currEntry);
if (compareResult == this.FILE_HASH_MISMATCH) {
changedList.add(currEntry);
} else if (compareResult == this.FILE_HASH_NOT_EXIST) {
newList.add(currEntry);
}
dbList.remove(currEntry);
}
currEntry = fileList.getCurrent();
}
if (dbList.size()>0) { // New files
Iterator<String> iterator = dbList.getIterator();
while(iterator.hasNext()) {
currEntry = iterator.next();
missingList.add(currEntry);
//System.out.println("missing - " + currEntry);
}
}
result[0] = changedList;
result[1] = missingList;
result[2] = newList;
return result;
}

public ArrayList<String>[] getChanges(ArrayList<String> dirFilter) {
ArrayList<String>[] result = this.getChanges();
ArrayList<String> changedList, missingList, newList;

String[] filter = dirFilter.toArray(new String[0]);
boolean match = false;
for (int a=0;a<result.length;a++) {
for (int i=0;i<result[a].size();i++) {
match = false;
for (int j=0;j<filter.length;j++) {
if (result[a].get(i).startsWith(filter[j]))
match = true;
}
if (!match)
result[a].remove(i);
}
}
return result;
}

/**
* Returns the list of files that have been changed from the signature
* store.
**/
public String[] getChangedFiles() {
ResultSet rs = null;
Statement stmt = null;
File file = null;
ArrayList<String> fileList = new ArrayList<String>();
String[] fileArr = null;;

try {
conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@localhost:1521/OracleServiceXE");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT filepath FROM hash");

String filePath, fileHash;
int compareResult;

while (rs.next()) {
filePath = decrypt(rs.getString(1));

file = new File(filePath);
if (file.exists()) {
compareResult = this.compareFileHash(filePath);
if (compareResult == this.FILE_HASH_MISMATCH) {
fileList.add(filePath);
}
}
}
if (fileList.size() > 0) {
fileArr = new String[fileList.size()];
for (int i=0;i<fileList.size();i++)
fileArr[i] = fileList.get(i);
}
return fileArr;

} catch (SQLException ex) {
if (debug) {
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}
return null;
} finally {
if (stmt != null) {
try {
rs.close();
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
}
}

/**
* Gets the changed files that are in the folders indicated by
* dirFilter.
**/
public String[] getChangedFiles(ArrayList<String> dirFilter) {
String[] files = getChangedFiles();
LinkedList<String> fileList = new LinkedList<String>();
for (int i=0;i<files.length;i++)
fileList.add(files[i]);

String[] filter = dirFilter.toArray(new String[0]);
boolean match = false;
for (int i=0;i<fileList.size();i++) {
match = false;
for (int j=0;j<filter.length;j++) {
if (fileList.get(i).startsWith(filter[j]))
match = true;
}
if (!match)
fileList.remove(i);
}
return (String[])fileList.toArray();
}

/**
* Deletes ALL entries in the database
*/
public int flushDb() {
Statement stmt = null;
int rs;

try {
stmt = conn.createStatement();
rs = stmt.executeUpdate("DELETE FROM hash");
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
return rs;
} catch (SQLException ex) {
if (debug) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
return -1;
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}

}
}

/**
* Compares the specified file's hash against that stored in the
* database. Returns :
* FILE_HASH_MATCH if both hashes match
* FILE_HASH_MISMATCH if both hashes mismatch
* FILE_HASH_NOT_EXIST if file does not have corresponding hash in db
* FILE_NOT_EXIST if file does not exist in the file system
*/
public int compareFileHash(String filePath) {

ResultSet rs = null;
Statement stmt = null;

try {
File file = new File(filePath);
String fp;
if (this.doEncrypt)
fp = encrypt(file.getCanonicalPath());
else
fp = file.getCanonicalPath();

conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@localhost:1521/OracleServiceXE");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT filehash FROM hash WHERE filepath='"+fp+"'");

if (rs.next()) {
String fileHash;
if (doEncrypt)
fileHash = decrypt(rs.getString(1));
else
fileHash = rs.getString(1);
//System.out.println("obtained hash -" + fileHash);
String obtainedFileHash = null;//= HashUtil.hashFileEncoded(filePath);
//System.out.println("actual hash -" + obtainedFileHash);
if (obtainedFileHash == null)
return FILE_NOT_EXIST;
if (fileHash.equals(obtainedFileHash)) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt.close();
stmt = null;
}
}
return FILE_HASH_MATCH;
} else {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
} catch (SQLException sqlEx) { // ignore }
stmt.close();
stmt = null;
}

return FILE_HASH_MISMATCH;
}
} else if (!file.exists()) {
//System.err.println("File : " + filePath + " does not exist");
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt.close();
stmt = null;
}
}
return FILE_NOT_EXIST;
} else {
//System.err.println("File : " + filePath + " is not in the hash file");
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
} catch (SQLException sqlEx) { // ignore }
stmt.close();
stmt = null;
}
return FILE_HASH_NOT_EXIST;
}

} catch (IOException e) {
System.err.println("IO Exception - " + e);
} catch (SQLException ex) {
if (debug) {
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}
return -1;
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
return -1;
}

/**
* Adds directory into the hash store. Parameter recursive should be
* true if all subdirectories are to be added. False otherwise.
*
* @param dirPath path of directory to be hashed
* @param recursive switch to include subdirectories
*/
public boolean addDirs(String dirPath, boolean recursive) {
return addDir(dirPath, recursive);
}

public void addFileFilter(String aExt) {
if (!fileFilter.contains(aExt))
fileFilter.add(aExt);
}

public static void sortFileDir(File[] fileList) {
File temp;

for (int i=0;i<fileList.length;i++) {
for (int j=0;j<(fileList.length - i - 1);j++) {
if (fileList[j+1].isFile() && fileList[j].isDirectory()) {
temp = fileList[j];
fileList[j] = fileList[j+1];
fileList[j+1] = temp;
}
}
}
}

public static void sortFileDir(String path, String[] fileList) {
String temp;
File file1, file2;

for (int i=0;i<fileList.length;i++) {
for (int j=0;j<(fileList.length - i - 1);j++) {
file1 = new File(path+File.separatorChar+fileList[j]);
file2 = new File(path+File.separatorChar+fileList[j+1]);
if (file2.isFile() && file1.isDirectory()) {
temp = fileList[j];
fileList[j] = fileList[j+1];
fileList[j+1] = temp;
}
}
}
}

public void quarantine(String file) {
File fObj = new File(file);
String todayQPath = quarantinePath + File.separator; //+ IDSUtil.createDateString();
File qDir = new File(todayQPath);
if (!qDir.exists()) {
qDir.mkdirs();
}
File tgt = new File(todayQPath + File.separator +
file.substring(file.lastIndexOf(File.separatorChar)+1));
if (!tgt.exists()) {
fObj.renameTo(tgt);
} else { // filename already exists, append '[n]' to filename
int cnt = 0;
String newName = todayQPath + File.separator;
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 17 2008
Added on Jan 20 2008
0 comments
161 views