Main Page | Packages | Class Hierarchy | Alphabetical List | Class List | File List | Class Members | Related Pages

GeneralUtilities.java

00001 package ProdDatabase;
00002 import java.util.*;
00003 import java.sql.*;
00004 import java.util.zip.*;
00005 import java.util.regex.*;
00006 import java.io.*;
00007 import Preferences.*;
00008 
00009 public class GeneralUtilities implements SCTDBInfo {
00010     public static Hashtable generalHash;
00011     public static Vector testNumberList;
00012 
00013 // *****************************************************************************************************************
00014     public static void itemExists(String sn1,String sn2,boolean resetHash) throws Exception {
00015       if(resetHash || generalHash==null) generalHash = new Hashtable();
00016       Vector itemList = new Vector();
00017       StringBuffer sqlStat = new StringBuffer("SELECT ");
00018       sqlStat.append("ser_no,ctype,locn_name FROM items WHERE ser_no >="+sn1+" AND ser_no <="+sn2);
00019       sqlStat.append(" ORDER BY ser_no");
00020 //      System.out.println(sqlStat.toString());
00021 
00022       SCTDBInterface db = SCTDBInterface.getInstance();
00023 
00024       Statement statement = db.connection.createStatement();
00025       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00026       int recordCount=0;
00027       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00028          recordCount++;
00029          String serno = resultSet.getString(1);
00030           String ctype = resultSet.getString(2);
00031           String location = resultSet.getString(3);
00032           generalHash.put((String)serno,(String)ctype);
00033           System.out.println(serno+"("+ctype+") already exists, located at "+location);
00034           }
00035       statement.close();
00036       return;
00037       }
00038   public static boolean itemExists(String sn1) throws Exception {
00039        return itemExists(sn1,true);
00040        }
00041 //************************************************************
00042   public static boolean itemExists(String sn1, boolean showDialog) throws Exception {
00043      boolean itExists=false;
00044      String cType=null;
00045      StringBuffer sqlStat = new StringBuffer("SELECT ctype FROM items WHERE ser_no="+sn1);
00046       Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00047       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00048       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00049          cType=resultSet.getString(1);
00050          if(cType.indexOf("Module")!=-1) itExists=true;
00051          }
00052       statement.close();
00053       if(!itExists && showDialog) {
00054          if(cType==null) javax.swing.JOptionPane.showMessageDialog(null,sn1+" does not exist in the database!","No such device",javax.swing.JOptionPane.INFORMATION_MESSAGE);
00055          else  javax.swing.JOptionPane.showMessageDialog(null,sn1+" is a "+cType+" (not a module)","Not a module",javax.swing.JOptionPane.INFORMATION_MESSAGE);
00056          }
00057       return itExists;
00058       }
00059          
00060 
00061 // *****************************************************************************************************************
00062     public static String validateLocation(String theLocation) throws Exception {
00063 // get location name where argument = ulocation name OR institute username OR institute user number
00064       String validatedLocation="unknown";
00065       boolean isNumber = true;
00066       try {
00067          int locationNumber = Integer.parseInt(theLocation);
00068       }catch(Exception nException) {isNumber=false;}
00069 
00070       StringBuffer sqlStat = new StringBuffer("SELECT locn_name FROM LOCNS");
00071       if(isNumber) sqlStat.append(" WHERE locn="+theLocation);
00072       else sqlStat.append(" WHERE (locn_name='"+theLocation+"' OR username='"+theLocation+"')");
00073 
00074       SCTDBInterface db = SCTDBInterface.getInstance();
00075       Statement statement = db.connection.createStatement();
00076       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00077       int recordCount=0;
00078       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00079            validatedLocation = resultSet.getString(1);
00080             }
00081 //      System.out.println("Retrieved "+recordCount+" records in total.");
00082       statement.close();
00083       return validatedLocation;
00084       }
00085 // *****************************************************************************************************************
00086     public static String validatePersonInitial(String theUser) throws Exception {
00087 
00088       String person="unknown";
00089       StringBuffer sqlStat = new StringBuffer("SELECT initls FROM persons WHERE initls='"+theUser+"'");
00090 
00091       SCTDBInterface db = SCTDBInterface.getInstance();
00092       Statement statement = db.connection.createStatement();
00093       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00094       resultSet = statement.executeQuery(sqlStat.toString());
00095       int recordCount=0;
00096       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00097            person = resultSet.getString(1);
00098             }
00099 //      System.out.println("Retrieved "+recordCount+" records in total.");
00100       statement.close();
00101       return person;
00102       }
00103 
00104 // ******************************************************************************************************************
00105     public static Vector getNameList(String location) throws Exception {
00106      StringBuffer sqlStat = new StringBuffer("SELECT initls FROM persons");
00107      sqlStat.append(" WHERE persons.locn_name LIKE '"+location+"'");
00108 
00109       SCTDBInterface db = SCTDBInterface.getInstance();
00110       Statement statement = db.connection.createStatement();
00111       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00112 
00113      int recordCount=0;
00114      Vector itemList = new Vector();
00115      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00116           recordCount++;
00117           itemList.addElement(resultSet.getString(1));  
00118             }
00119 //      System.out.println("Retrieved "+recordCount+" names in total.");
00120 
00121       statement.close();
00122 
00123       if(itemList.size()>0) return itemList;
00124 // no users at this location? If so, return all users
00125 //      System.out.println("As there are no users defined at "+location+" I will return all users in the database.");
00126      sqlStat = new StringBuffer("SELECT initls FROM persons ORDER BY initls");
00127 
00128      statement = db.connection.createStatement();
00129      resultSet = statement.executeQuery(sqlStat.toString());
00130      recordCount=0;
00131      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00132           recordCount++;
00133           itemList.addElement(resultSet.getString(1));   // serial no
00134             }
00135       statement.close();
00136 //      System.out.println("Retrieved "+recordCount+" names in total.");
00137 
00138       return itemList;
00139      }
00140 
00141 
00142 //****************************************************************************
00143 public static double get500VData(String testno) throws Exception {
00144      java.util.regex.Pattern i500Pattern = java.util.regex.Pattern.compile(".*500[\\.\\d]*\\s*([\\.\\d]+).*");
00145      java.util.regex.Pattern lastCharPattern = java.util.regex.Pattern.compile("[0-9\\.]");
00146 
00147      Vector thisData = getRawData(testno);
00148      if(thisData.size()==0 || !isSctDaqData(testno)) return 0.;
00149      String[] theDataString = ((String)thisData.elementAt(1)).split("[\\r\\n]");
00150      for(int i=theDataString.length-1;i>=0;i--) {
00151          java.util.regex.Matcher matcher = i500Pattern.matcher(theDataString[i]);
00152          if(matcher.matches()) {
00153             String data500 = theDataString[i].substring(matcher.start(1),matcher.end(1));
00154             return Double.parseDouble(data500);
00155             }
00156          }
00157       return 0.;
00158 }
00159 //*********************************************************************
00160     public static boolean isSctDaqData(String testno) throws Exception {
00161      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00162      ResultSet resultSet = statement.executeQuery("SELECT version FROM SCT_TSTDAQINFO where test_no="+testno);
00163      String version=null;
00164      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00165           version = resultSet.getString(1);
00166             }
00167      statement.close();
00168      if(version==null) return false;
00169      return version.matches("\\d+\\.\\d+");
00170      }
00171 
00172 //**********************************************************************
00173     public static Vector getLocationList() throws Exception {
00174      System.out.println("Retrieving list of valid institute names from database ...");
00175      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00176      ResultSet resultSet = statement.executeQuery("SELECT locn_name FROM locns ORDER BY locn_name");
00177      Vector itemList = new Vector();
00178      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00179           itemList.addElement(resultSet.getString(1));   // serial no
00180             }
00181 //      System.out.println("Retrieved "+recordCount+" names in total.");
00182       statement.close();
00183       return itemList;
00184      }
00185 //*************************************************************************
00186       public static void downloadPSFile(javax.swing.JFrame parent, java.net.URL theURL) {
00187 
00188       File savedFile;
00189       String theFileName;
00190       String baseName=null;
00191       String tryAgainURL=null;
00192 
00193         theFileName = theURL.getFile();
00194         baseName = theURL.toString();
00195         System.out.println("Downloading "+baseName);
00196         baseName = baseName.substring(0,baseName.indexOf(theFileName));
00197 //        System.out.println("Downloading "+baseName);
00198 
00199         String theQuery = theURL.getQuery();
00200 //        if(theQuery!=null) System.out.println("theQuery: "+theQuery);
00201         theFileName = (theQuery!=null) ? theQuery : theURL.getFile();
00202         int lastEquals = theFileName.lastIndexOf("=");
00203         if(lastEquals!=-1) theFileName = theFileName.substring(lastEquals+1);
00204         int lastSlash = theFileName.lastIndexOf("/");
00205         if(lastSlash!=-1) theFileName = theFileName.substring(lastSlash+1);
00206 
00207         if(!theFileName.endsWith(".ps")) theFileName+=".ps";
00208         savedFile = new File(PreferencesInterface.getInstance().getPreference(PreferencesInterface.SCRATCH_DIR),theFileName);
00209 // execute query here
00210        try {
00211         downloadURL(savedFile,theURL,theFileName);
00212         }catch(Exception e1) {
00213             String eString = e1.toString();
00214             int nprot = eString.indexOf("no protocol: ");
00215             if(nprot==-1) {
00216                    System.out.println("Error downloading from URL: "+eString);
00217                    return;
00218                    }
00219             String theSubURL = eString.substring(nprot+13);
00220             tryAgainURL=baseName+theSubURL;
00221         }
00222      try {
00223      if(tryAgainURL!=null) {
00224         System.out.println("Invalid URL - maybe relative pathname - reconstructing new URL from relative pathname...");
00225         theURL = new java.net.URL(tryAgainURL);
00226         theFileName = theURL.getFile();
00227         lastSlash = theFileName.lastIndexOf("/");
00228         if(lastSlash!=-1) theFileName = theFileName.substring(lastSlash+1);
00229         int gzIndex = theFileName.indexOf(".gz");
00230         if(gzIndex!=-1) theFileName=theFileName.substring(0,gzIndex);
00231         savedFile = new File(PreferencesInterface.getInstance().getPreference(PreferencesInterface.SCRATCH_DIR),theFileName);
00232           
00233 
00234         downloadURL(savedFile,theURL,theFileName);
00235         }
00236       }catch(Exception e2) {
00237          System.out.println("Exception downloading from relative pathname in URL: "+e2.toString());
00238          return;
00239          }
00240 //     theFrame.psFileList.addElement(savedFile);   //save it for deletion when application closes
00241 
00242 
00243      String psExecutable = PreferencesInterface.getInstance().getPreference(PreferencesInterface.PSVIEWER);
00244      if(psExecutable.equals("Not defined")) {
00245                    Preference preference = new Preference(parent,PreferencesInterface.PSVIEWER);
00246                    psExecutable = PreferencesInterface.getInstance().getPreference(PreferencesInterface.PSVIEWER);
00247                    }
00248      if(psExecutable.equals("Not defined")) return; // fluffed the second chance!         
00249 
00250      try {
00251          File psExec = new File(psExecutable);
00252          if(!psExec.exists()) return;
00253          String command = psExecutable+" "+savedFile.getAbsolutePath();
00254          System.out.println(command);
00255          Process p = Runtime.getRuntime().exec( command );
00256      } catch(Exception e2) {System.out.println("Exception invoking ps viewer: "+e2.toString());}
00257    }
00258 //********************
00259       public static void downloadURL(File savedFile, java.net.URL theURL, String theFileName) throws Exception {
00260       InputStream in;              
00261       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00262       FileOutputStream fos;
00263       int nByteCount=0;
00264 
00265        fos = new FileOutputStream(savedFile);       // open the file output stream
00266        in  =  theURL.openStream();
00267 // read the data - will stop when reach end of stream or error, hopefully!
00268 //       System.out.println("Downloading postscript file "+theFileName+" Please be patient.");
00269        for(int nbytes=in.read(buffer); nbytes>0; nbytes=in.read(buffer)){
00270            nByteCount += nbytes;
00271            fos.write(buffer,0,nbytes);
00272             }
00273        fos.close();
00274        in.close();
00275        System.out.println("Wrote "+nByteCount+" bytes to "+savedFile.getAbsolutePath());
00276        guiUtilities.HTMLViewer.getInstance().addImageFile(savedFile.getAbsolutePath());
00277 } 
00278 //************************************************
00279        public static Hashtable getSignoffDataTestNo(String sn, String location, String signoffType) throws Exception {
00280          Hashtable thisHash = new Hashtable();
00281          StringBuffer sqlStat = new StringBuffer("SELECT test_no FROM tests");
00282          sqlStat.append(" WHERE ser_no="+sn+" AND run_no='"+signoffType+"' AND test_name='bmMOD_RData'");
00283          if(!location.equals("Any")) sqlStat.append(" AND locn_name='"+location+"'");
00284          sqlStat.append(" ORDER BY test_date DESC, test_no DESC");
00285          Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00286          ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00287          for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00288             if(thisHash.containsKey(location)) continue;
00289             thisHash.put(location,resultSet.getString(1));
00290             break;
00291             }
00292 //      System.out.println("Retrieved "+recordCount+" names in total.");
00293       statement.close();
00294       return thisHash;
00295       }
00296 //************************************************
00297        public static Hashtable getSignoffDataTestNo(String sn, String signoffType) throws Exception {
00298 // return vector of test numbers
00299          Hashtable locationHash = new Hashtable();
00300          StringBuffer sqlStat = new StringBuffer("SELECT locn_name,test_no FROM tests");
00301          sqlStat.append(" WHERE ser_no="+sn+" AND run_no='"+signoffType+"' AND test_name='bmMOD_RData'");
00302          sqlStat.append(" ORDER BY test_date DESC, test_no DESC");
00303          Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00304          ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00305          for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00306             String location = resultSet.getString(1);
00307             String testno = resultSet.getString(2);
00308             if(locationHash.containsKey(location)) continue;
00309             locationHash.put(location,testno);
00310             if(signoffType.equals("FINALSIGNOFF")) break;
00311             }
00312 //      System.out.println("Retrieved "+recordCount+" names in total.");
00313       statement.close();
00314       return locationHash;
00315       }
00316 //************************************************
00317        public static Vector getSignoffDataTestNos(String sn1, String sn2, String currLocn, String institute, String signoffType, boolean latestOnly) throws Exception {
00318 // return vector of test numbers
00319          Set snHash = new HashSet();
00320          Vector snList = new Vector();
00321          StringBuffer sqlStat = new StringBuffer("SELECT ser_no, test_no, locn_name, run_no FROM tests");
00322          if(!currLocn.equals("Anywhere")) sqlStat.append(",items");
00323          sqlStat.append(" WHERE ser_no>="+sn1+" AND ser_no<="+sn2+" AND (run_no='SIGNOFF' OR run_no='FINALSIGNOFF') AND test_name='bmMOD_RData'");
00324          if(!institute.equals("Anywhere")) sqlStat.append(" AND locn_name='"+institute+"'");
00325          if(!currLocn.equals("Anywhere")) sqlStat.append(" AND tests.ser_no IN (SELECT items.ser_no FROM items WHERE items.locn_name='"+currLocn+"')");
00326          String ordering = latestOnly ? "DESC" : "";
00327          sqlStat.append(" ORDER BY ser_no, test_date "+ordering+", test_no "+ordering);
00328          Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00329          ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00330          int recordCount=0;
00331          for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00332             String sn = resultSet.getString(1);
00333             String testno = resultSet.getString(2);
00334             String locn = resultSet.getString(3);
00335             String runno = resultSet.getString(4);
00336             boolean isUKUpload = (locn.equals("Cambridge") || locn.equals("RAL") || locn.equals("Birmingham"));
00337             if(!isUKUpload && !signoffType.equals(runno)) continue;   // non-UK uploads both SIGNOFF and FINALSIGNOFF
00338             if(isUKUpload && runno.equals("SIGNOFF")) continue; // UK uploads FINALSIGNOFF only
00339             if(latestOnly && snHash.contains(sn)) continue;
00340             snList.addElement(testno);
00341             snHash.add(sn);
00342             recordCount++;
00343             if(recordCount%100==0) System.out.println("Retrieved "+recordCount+" tests so far...");
00344             }
00345       System.out.println("Retrieved "+recordCount+" tests in total, now downloading and extracting raw data");
00346       statement.close();
00347       return snList;
00348       }
00349 //*************************************************
00350     public static String getUploaderInfo(String testno) throws Exception {
00351          StringBuffer sqlStat = new StringBuffer("SELECT locn_name,test_date,initls FROM tests");
00352          sqlStat.append(" WHERE test_no="+testno);
00353          Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00354          ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00355          String returnString=null;
00356          for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00357             String location = resultSet.getString(1);
00358             String testdate = guiUtilities.DaveUtils.extractDate(resultSet.getString(2));
00359             String initials = resultSet.getString(3);
00360             returnString = "Uploaded by "+initials+" from "+location+" on "+testdate;
00361             }
00362       statement.close();
00363       return returnString;
00364       }
00365 //**********************************************************
00366    public static Hashtable testComments(String testno_subQuery) throws Exception {
00367 
00368       Hashtable commentHash = new Hashtable();
00369       StringBuffer sqlStat = new StringBuffer("SELECT test_no,cmnt_text FROM test_cmnts WHERE test_no IN (SELECT tests.test_no FROM tests ");      
00370       sqlStat.append(testno_subQuery+")");
00371 //      System.out.println(sqlStat.toString());
00372      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00373      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00374      int ncomments=0;
00375      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00376           ncomments++;
00377           if(ncomments%100 ==0) System.out.println("Retrieved "+ncomments+" comments so far...");
00378           String testno = resultSet.getString(1);
00379           String comment = resultSet.getString(2);
00380           // beware of more than one comment in a given testno !
00381           String newComment = (commentHash.containsKey(testno)) ? (String)commentHash.get(testno)+" "+comment : comment;
00382           commentHash.put(resultSet.getString(1),newComment);
00383             }
00384       statement.close();
00385       return commentHash;
00386       }
00387 
00388 
00389 
00390 
00391    public static Hashtable testImages(String testno_subQuery) throws Exception {
00392 // has contains a vector, and the vector contains title, then url, then title, then url etc
00393       Hashtable testImageHash = new Hashtable();
00394 //      System.out.println("Checking for test images...");
00395       StringBuffer sqlStat = new StringBuffer("SELECT test_no,title,name FROM test_images WHERE test_no IN (SELECT tests.test_no FROM tests ");      
00396       sqlStat.append(testno_subQuery+")");
00397 
00398      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00399      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00400      int ncomments=0;
00401      Vector imageList;
00402      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00403           ncomments++;
00404           if(ncomments%100 ==0) System.out.println("Retrieved "+ncomments+" test images so far...");
00405           String testno = resultSet.getString(1);
00406           String title = resultSet.getString(2);
00407           String name = resultSet.getString(3);
00408           // beware of more than one image in a given testno !
00409           if(testImageHash.containsKey(testno)) imageList = (Vector)testImageHash.get(testno);
00410           else imageList = new Vector();
00411           imageList.addElement(title);
00412           imageList.addElement(name);
00413           testImageHash.put(testno,imageList);
00414             }
00415 //      System.out.println("Retrieved "+ncomments+" test images in total.");
00416       statement.close();
00417       return testImageHash;
00418       }
00419 
00420 //***********************************************************************************************
00421    public static void saveImage(String testno, String fileName, File theFile) throws Exception {
00422       InputStream in;   
00423       FileOutputStream fos = new FileOutputStream(theFile);               
00424       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00425 
00426      String sqlQuery = "SELECT data FROM test_images WHERE test_no="+testno+" AND name='"+fileName+"'";
00427      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00428      ResultSet resultSet = statement.executeQuery(sqlQuery);
00429 
00430 // execute query here
00431       System.out.println("Retrieving "+fileName+" ...");
00432      int nByteCount=0;
00433 
00434      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00435          in  = resultSet.getBinaryStream(1);           // open the data stream
00436 
00437 // read the data - will stop when reach end of stream or error, hopefully!
00438          for(int nbytes=in.read(buffer); nbytes>0; nbytes=in.read(buffer)){
00439 
00440             // System.out.print("Nbytes read : " + nbytes+". ");
00441             nByteCount += nbytes;
00442             fos.write(buffer,0,nbytes);  // write the data to the file output
00443             }
00444          fos.close();  // close the file output
00445          System.out.println("Saved image "+fileName+" with size "+nByteCount+" bytes...");
00446          guiUtilities.HTMLViewer.getInstance().addImageFile(theFile.getAbsolutePath());
00447 
00448          }
00449      statement.close();
00450      return;
00451 }
00452 // *****************************************************************************************************************
00453     public static Vector getItemVector(String serialNo) throws Exception {
00454       Vector itemList = new Vector();
00455       StringBuffer sqlStat = new StringBuffer("SELECT ");
00456       sqlStat.append("mfr,mfr_ser_no,ctype,locn_name,assembled,trashed FROM items WHERE ser_no="+serialNo);
00457       sqlStat.append(" ORDER BY ser_no");
00458 
00459      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00460 //      System.out.println("Interrogating items table ...");
00461       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00462       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00463           itemList.addElement(resultSet.getString(1));   // mfr name
00464           itemList.addElement(resultSet.getString(2));   // mfr serial no
00465           itemList.addElement(resultSet.getString(3));   // type
00466           itemList.addElement(resultSet.getString(4));   // location name
00467           itemList.addElement(resultSet.getString(5));   // assembled flag
00468           itemList.addElement(resultSet.getString(6));   // trashed flag
00469             }
00470       statement.close();
00471       return itemList;
00472       }
00473 
00474 // ******************************************************************************************************
00475     public static Vector getVisualTestList(String ser_no1, String ser_no2, String location, String currLocn,String orderString) throws Exception {
00476      StringBuffer sqlStat = new StringBuffer("SELECT ");
00477      sqlStat.append("tests.test_no,tests.ser_no,tests.test_date,tests.locn_name,tests.problem,tests.pass");
00478      sqlStat.append(" FROM tests");
00479      sqlStat.append(" WHERE tests.ser_no >= "+ser_no1+" AND tests.ser_no <= "+ser_no2);
00480      if(!location.equals("Anywhere")) sqlStat.append(" AND tests.locn_name='"+location+"'");
00481      if(!currLocn.equals("Anywhere")) sqlStat.append(" AND tests.ser_no IN (SELECT items.ser_no FROM items WHERE items.locn_name='"+currLocn+"')");
00482      sqlStat.append(" AND tests.test_name='Visual_Inspection'");
00483      sqlStat.append(" ORDER BY "+orderString);
00484      return createVisualTestTable(sqlStat.toString());
00485      }
00486 // ******************************************************************************************************
00487     public static Vector getVisualTestList(String ser_no1, String ser_no2, String location, String currLocn) throws Exception {
00488       return getVisualTestList(ser_no1,ser_no2,location,currLocn,"tests.ser_no,tests.test_date,tests.test_no");
00489      }
00490 //***************************************************************8
00491     public static Vector createVisualTestTable(String theQuery) throws Exception {
00492       Hashtable testnoHash = new Hashtable();
00493       Vector testnoList = new Vector();
00494       Vector itemList = new Vector();
00495       Vector theLine = new Vector();
00496       String snKey="SNKEY";
00497       String dateKey="DATEKEY";
00498       String locationKey="LOCATIONKEY";
00499       String flagKey="FLAGKEY";
00500 
00501      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00502 
00503      System.out.println("Interrogating tests and tstdetivs tables ...");
00504      ResultSet resultSet = statement.executeQuery(theQuery);
00505      int recordCount=0;
00506      testNumberList = new Vector();
00507      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00508           Hashtable thisHash = new Hashtable();
00509           recordCount++;
00510           if(recordCount%100 == 0) System.out.println("Retrieved "+recordCount+" records so far...");
00511           String testno = resultSet.getString(1);
00512           thisHash.put(snKey,resultSet.getString(2));
00513           String date = resultSet.getString(3);
00514           thisHash.put(dateKey,guiUtilities.DaveUtils.extractDate(date));
00515           thisHash.put(locationKey,resultSet.getString(4));
00516           String problemFlag = resultSet.getString(5);
00517           String passFlag = resultSet.getString(6);
00518           String statusFlag; 
00519           if(passFlag.equals("YES")) {
00520              statusFlag = (problemFlag.equals("YES")) ? "PROBLEM" : "Ok";
00521              }
00522           else statusFlag = "FAIL";
00523           thisHash.put(flagKey,statusFlag);
00524           testnoHash.put(testno,thisHash);   
00525           testnoList.addElement(testno);  
00526 
00527             }
00528       System.out.println("Retrieved "+recordCount+" records in total.");
00529       statement.close();
00530       if(recordCount==0) return itemList;
00531 
00532 // now get the comments, if any
00533       String subQuery = theQuery;
00534       subQuery = subQuery.substring(subQuery.indexOf("WHERE"),subQuery.indexOf("ORDER")-1);
00535       Hashtable commentsHash = testComments(subQuery);
00536       Hashtable testImagesHash = testImages(subQuery);
00537 
00538       theLine.addElement("Serial Number");
00539       theLine.addElement("Date");
00540       theLine.addElement("Location");
00541       theLine.addElement("Status");
00542       theLine.addElement("Remarks");
00543       theLine.addElement("Pictures");
00544       itemList.addElement(theLine);
00545 
00546       for(int i=0;i<testnoList.size();i++) {
00547             theLine = new Vector();
00548             String testno = (String)testnoList.elementAt(i); // this contains the testno's, ordered by serial no
00549             Hashtable tempHash = (Hashtable)testnoHash.get(testno);
00550             theLine.addElement(tempHash.get(snKey));                                      // first column is serial number
00551 
00552             theLine.addElement(tempHash.get(dateKey));                                    // 2nd column is the date
00553             theLine.addElement(tempHash.get(locationKey));              
00554             theLine.addElement(tempHash.get(flagKey));
00555             if(commentsHash.containsKey(testno)) theLine.addElement(commentsHash.get(testno));
00556             else theLine.addElement("");
00557             if(testImagesHash.containsKey(testno)) {
00558                Vector imageList = (Vector)testImagesHash.get(testno);
00559 
00560                for(int j=0;j<imageList.size()/2; j++) {
00561                    if(j==0) {
00562 
00563                               theLine.addElement((String)imageList.elementAt(0));
00564                               testNumberList.addElement(testno);
00565                               itemList.addElement(theLine);
00566                               }
00567                    else {
00568 
00569                               theLine = new Vector();
00570                               theLine.addElement(tempHash.get(snKey));
00571                               theLine.addElement("  ''");
00572                               theLine.addElement("  ''");
00573                               theLine.addElement("  ''");
00574                               theLine.addElement("  ''");
00575                               theLine.addElement((String)imageList.elementAt(2*j));  
00576                               testNumberList.addElement(testno);
00577                               itemList.addElement(theLine);                     
00578                           }
00579 
00580                       }
00581             }
00582             else {theLine.addElement(""); testNumberList.addElement(testno);itemList.addElement(theLine);}
00583             }
00584       return itemList;
00585 
00586 
00587       }
00588 //
00589 //***********************************************************************************************
00590    public static Vector getImages(String testno,String headerTitle) throws Exception {
00591       InputStream in;   
00592  //     FileOutputStream fos;               
00593       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00594 
00595      Vector imageList = new Vector();
00596 
00597      String sqlQuery = "SELECT data,title,name FROM test_images WHERE test_no="+testno;
00598      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00599      ResultSet resultSet = statement.executeQuery(sqlQuery);
00600 
00601 // execute query here
00602       System.out.println("Interrogating test_images table for images ...");
00603      int nByteCount=0;
00604      int noImages=0;
00605 
00606      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00607          noImages++;
00608          in  = resultSet.getBinaryStream(1);           // open the data stream
00609 
00610 // read the data - will stop when reach end of stream or error, hopefully!
00611          for(int nbytes=in.read(buffer); nbytes>0; nbytes=in.read(buffer)){
00612             nByteCount += nbytes;
00613             }
00614          javax.swing.ImageIcon thisImage;
00615          try {
00616            thisImage = new javax.swing.ImageIcon(buffer);
00617          } catch (Exception e) {thisImage=null;} // just in case 
00618          String title = resultSet.getString(2);
00619          String name = resultSet.getString(3);
00620          System.out.println("Retrieved image "+name+" with size "+nByteCount+" bytes...");
00621          imageList.addElement(new guiUtilities.Photo(thisImage,title,name,headerTitle,testno));
00622          }
00623      System.out.println("Retrieved "+noImages+" images in total for test number "+testno);
00624      statement.close();
00625 //     storedImages.put(testno,imageList); // store the image list vector, in case we want to look again
00626      return imageList;
00627 }
00628 
00629 //***************************************************************************************************
00630  public static Map getRawDataLists(String sn1, String sn2, String location, int testType, int temperature, String runNo, int testRequest) throws Exception {
00631       Map m = new HashMap();
00632       StringBuffer sqlStat = new StringBuffer("SELECT tests.test_no,tests.ser_no,tests.test_date,tests.locn_name,");
00633       if(testType>=0) sqlStat.append("test_rawdata.filename,");
00634       sqlStat.append("SCT_TSTDCSINFO.T0 FROM tests,");
00635       if(testType>=0) sqlStat.append("test_rawdata,");
00636       sqlStat.append("SCT_TSTDCSINFO ");
00637 
00638       if(testRequest>=0) sqlStat.append("WHERE tests.test_name='"+sctdaqDBTestNames[testRequest]+"'");
00639       else {
00640         switch(testType) {
00641          case SCTDBInfo.SCTDB_TEST_TIMEWALK: 
00642 // xml data
00643       sqlStat.append(" WHERE ( (tests.test_name = 'HybTWalk' AND tests.locn_name !='Oxford') OR (tests.test_name = 'HybNoise' AND tests.locn_name = 'Oxford'))");
00644           break;
00645          default:
00646           sqlStat.append("WHERE tests.test_name='"+sctdaqDBTestNames[testType]+"'");
00647           }
00648        }
00649      sqlStat.append(" AND tests.ser_no >= "+sn1+" AND tests.ser_no <= "+sn2);
00650      if(runNo!=null) sqlStat.append(" AND tests.run_no LIKE '"+runNo+"'");
00651      if(testType>=0)sqlStat.append(" AND tests.test_no=test_rawdata.test_no");
00652      sqlStat.append(" AND SCT_TSTDCSINFO.test_no=tests.test_no");
00653      if(!location.equals("Anywhere")) sqlStat.append(" AND tests.locn_name='"+location+"'");
00654      switch(temperature) {
00655        case 1:
00656          sqlStat.append(" AND SCT_TSTDCSINFO.T0<=10");
00657          break;
00658        case 2:
00659          sqlStat.append(" AND SCT_TSTDCSINFO.T0>10");
00660          break;
00661        default:
00662        }
00663      sqlStat.append(" ORDER BY tests.ser_no,tests.test_date,tests.test_no");
00664 
00665 //     System.out.println(sqlStat.toString());
00666      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00667      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00668 
00669      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00670 
00671            SCTDBTestInfoHolder testInfo = new SCTDBTestInfoHolder();
00672            testInfo.put(SCTDBTestInfoHolder.TESTNUMBER,resultSet.getString(1));
00673            Long sn = new Long(resultSet.getLong(2));
00674            testInfo.put(SCTDBTestInfoHolder.SN,sn.toString());
00675            testInfo.put(SCTDBTestInfoHolder.DATE,guiUtilities.DaveUtils.extractDate(resultSet.getString(3)));
00676            testInfo.put(SCTDBTestInfoHolder.LOCATION,resultSet.getString(4));
00677            int lastIndex = (testType>=0) ? 6 : 5;
00678            testInfo.put(SCTDBTestInfoHolder.TEMPERATURE,resultSet.getString(lastIndex));
00679            m.put(sn,testInfo);
00680        }
00681      statement.close();
00682      return m;
00683      }
00684    public static Vector getRawData(String testno) throws Exception {
00685      return getRawData(testno,PreferencesInterface.getInstance().getPreference(PreferencesInterface.SCRATCH_DIR));
00686      }
00687 
00688 // ****************************************************************************************************************
00689    public static Vector getRawData(String testno, String saveDir) throws Exception {
00690 // get the raw data - if its a zip file, save it to disk with same filename
00691 // otherwise just download as a string
00692       Vector returnData = new Vector();
00693 
00694       // first get filename of the raw data file of this testno
00695 
00696      String sqlQuery = "SELECT filename from test_rawdata WHERE test_no="+testno;
00697      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00698      ResultSet resultSet = statement.executeQuery(sqlQuery);
00699      String thisFname = null;
00700      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00701           thisFname = resultSet.getString(1);
00702           }
00703      if(thisFname==null) {
00704           return returnData;
00705           }
00706 // now download that file
00707      File savedFile = new File(saveDir,thisFname);
00708      if(downloadFile(testno,savedFile)==0) return returnData;
00709 // now read in the downloaded file - firat assume it is zipped...
00710      try {
00711        returnData = unZipFile(savedFile);
00712        }
00713      catch(Exception ee) {
00714 // not zipped, so assume its just text
00715        returnData = getFileContent(savedFile);
00716        File tempFile = new File(thisFname); // get just the last part, not a pathname
00717        returnData.insertElementAt((String)tempFile.getName(),0);
00718        }
00719      boolean deleted = savedFile.delete(); // delete the downloaded file
00720 // check if its an .xml file, if so, assume it is an sctdaq xml config file
00721 // in which case, we want to lookup and susbtitute the calibrate correction factors
00722      returnData = insertCalFactors(returnData);
00723 // index0 : filename
00724 // index1 : content as a String
00725 // ..etc for index2 and 3 etc
00726      return returnData;
00727      }
00728 //***********************************************************************8
00729 public static Vector getFileContent(File theFile) throws Exception {
00730     // get file content as a String
00731     Vector returnData = new Vector();
00732     BufferedReader in = new BufferedReader(new FileReader(theFile));
00733     String line;
00734     StringBuffer stringBuffer = new StringBuffer();
00735     boolean firstLine=true;
00736     while((line=in.readLine())!=null) {
00737       if(!firstLine) stringBuffer.append("\n");
00738       stringBuffer.append(line);
00739       firstLine=false;
00740       }
00741     in.close();
00742     returnData.addElement(stringBuffer.toString());
00743     return returnData;
00744     }
00745 
00746 //********************************************
00747 public static int downloadFile(String testno, File savedFile) throws Exception {
00748 
00749       InputStream in;         
00750       String theData = "";      
00751       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00752     FileOutputStream fos;
00753 // execute query here
00754      String sqlQuery = "SELECT raw_data FROM test_rawdata WHERE test_no="+testno; 
00755      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00756      ResultSet resultSet = statement.executeQuery(sqlQuery);
00757 
00758      int nByteCount=0;
00759      fos = new FileOutputStream(savedFile);       // open the file output stream
00760      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00761          in  = resultSet.getBinaryStream(1);           // open the data stream
00762 
00763 // read the data - will stop when reach end of stream or error, hopefully!
00764          for(int nbytes=in.read(buffer); nbytes>0; nbytes=in.read(buffer)){
00765            nByteCount += nbytes;
00766            fos.write(buffer,0,nbytes);
00767             }
00768          }
00769      fos.close();
00770      statement.close();
00771      if(nByteCount==0) System.out.println("No raw data available for test "+testno);
00772 //     else System.out.println("Downloaded "+savedFile.getName()+", size "+nByteCount+" bytes.");
00773      return nByteCount;
00774 }
00775 //*************************************************************************
00776 public static Vector unZipFile(File savedFile) throws Exception{
00777       Vector returnData = new Vector();
00778       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00779 
00780 // now extract the zip file...
00781      final int BUFFER=2048;
00782      ZipFile zFile = new ZipFile(savedFile);
00783      FileInputStream fis = new FileInputStream(savedFile);
00784      ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
00785      ZipEntry entry;
00786      while((entry = zis.getNextEntry()) != null) {
00787          returnData.addElement((String)entry.getName());   // first the data filename
00788          int count;
00789          byte[] data = new byte[BUFFER];
00790          StringBuffer thisData = new StringBuffer();
00791          while((count=zis.read(data,0,BUFFER)) != -1) {
00792             thisData.append(new String(data,0,count)); 
00793             }
00794          returnData.addElement((String)thisData.toString());    // then the filename content as a string
00795         }
00796      zis.close();
00797      return returnData;
00798 }
00799 public static Vector insertCalFactors(Vector rawdata) throws Exception {
00800     String lineTerminator = "\\s*\\n";
00801     Pattern modulePattern = Pattern.compile("<module>");
00802     Pattern locationPattern = Pattern.compile(".*<location>(.*)</location>.*");
00803     Pattern snPattern = Pattern.compile("\\s*<sn>(\\d{14})</sn>");
00804     Pattern chipIDPattern = Pattern.compile("\\s*<chip id=\"(\\d{2})\".*");
00805     Pattern cFactorPattern = Pattern.compile("(\\s*)<c_factor>.*</c_factor>");
00806     Pattern runNoPattern = Pattern.compile(".*<run>(\\d+)</run><scan>(\\d+)</scan>.*");
00807     Pattern rcFitPattern = Pattern.compile("(.*)<rc_function.*</rc_function>");
00808     String moduleSerialNo = null;
00809     String location=null;
00810     String thisChipPosition=null;
00811     Hashtable chipPositionHash = new Hashtable();
00812     Hashtable rcFitHash = null;
00813 
00814     boolean xmlfile=false;
00815     for(int i=0;i<rawdata.size();i++) {
00816 
00817         if(i%2==0) {
00818             if (((String)rawdata.elementAt(i)).indexOf(".xml")!=-1) xmlfile=true;
00819             else xmlfile=false;
00820             continue;
00821             }
00822 
00823         if(!xmlfile) continue;
00824         String[] lines = ((String)rawdata.elementAt(i)).split(lineTerminator);
00825 
00826         Matcher matcher = modulePattern.matcher(lines[0]);
00827         if(!matcher.matches()) return rawdata;     // first line of xml file is expected to be <module>
00828 
00829         StringBuffer newString = new StringBuffer("<module>");
00830         for(int line=1;line<lines.length;line++) {
00831             String thisLine = lines[line];
00832 //            System.out.println("Checking line "+line+": "+thisLine);
00833             matcher = snPattern.matcher(thisLine);
00834             if(matcher.matches()) {
00835                  moduleSerialNo = thisLine.substring(matcher.start(1),matcher.end(1));
00836                  chipPositionHash = getChipPositionHash(moduleSerialNo);               
00837                  }
00838             matcher = locationPattern.matcher(thisLine);
00839             if(matcher.matches()) location = thisLine.substring(matcher.start(1),matcher.end(1));
00840 
00841             matcher = runNoPattern.matcher(thisLine);
00842             if(matcher.matches()) {
00843                    rcFitHash = getRCFits(moduleSerialNo,location,thisLine.substring(matcher.start(1),matcher.end(1)),thisLine.substring(matcher.start(2),matcher.end(2)));
00844                    if(rcFitHash.size()!=12) System.err.println("Failed to extract RC fit parameters for module config file");
00845                    }
00846 
00847             matcher = rcFitPattern.matcher(thisLine);
00848             if(matcher.matches() && thisChipPosition!=null && rcFitHash!=null) {
00849               String padding = thisLine.substring(matcher.start(1),matcher.end(1));
00850               if(rcFitHash.containsKey(thisChipPosition)) {
00851                  lines[line] = padding+(String)rcFitHash.get(thisChipPosition);
00852                  }
00853               }
00854 
00855             matcher = chipIDPattern.matcher(thisLine);
00856             if(matcher.matches()) {
00857                  thisChipPosition = thisLine.substring(matcher.start(1),matcher.end(1));
00858 //                 System.out.println("Found chip position "+thisChipPosition);
00859                  }
00860             matcher = cFactorPattern.matcher(thisLine);
00861             if(matcher.matches() && thisChipPosition!=null) {
00862                  String spaces = thisLine.substring(matcher.start(1),matcher.end(1));
00863                  if(chipPositionHash.containsKey(thisChipPosition)) lines[line] = spaces+"<c_factor>"+(String)chipPositionHash.get(thisChipPosition)+"</c_factor>";
00864                  else System.err.println("Cal Correction factors are not available for "+moduleSerialNo);
00865                 }
00866             newString.append("\n"+lines[line]);
00867 
00868             }
00869          rawdata.setElementAt((String)newString.toString(),i);
00870 
00871         }
00872 
00873    return rawdata;
00874 }
00875 public static Hashtable getChipPositionHash(String moduleSN) throws Exception {
00876    Pattern lotNoPattern = Pattern.compile("(Z\\d+-W\\d+).*"); // miss out the non-LOT info, eg Z39993-W12 X1 Y2
00877    Hashtable thisHash = new Hashtable();
00878    String sn=null;
00879 // first get the hybrid serial no
00880      StringBuffer sqlStat = new StringBuffer("SELECT ");
00881      sqlStat.append("ser_no from ASSM_ITEMS WHERE assm_ser_no="+moduleSN);
00882      sqlStat.append(" AND (ctype LIKE '%Hybrid%' OR ctype LIKE 'bmHASIC')");
00883 //     System.out.println("get hybrid serial no ...");
00884 //     System.out.println(sqlStat.toString());
00885      Statement statement;
00886      statement = SCTDBInterface.getInstance().connection.createStatement();
00887 
00888      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00889 
00890      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00891           sn = resultSet.getString(1);
00892           }
00893      statement.close();
00894      if(sn==null) return thisHash;  // no entry in assembly table - return empty hash
00895 //     else System.out.println("Hybrid is "+sn);
00896 
00897 // now get the chips in the assembly table
00898 // construct the hash with position as Key and LotNumber as value
00899      sqlStat = new StringBuffer("SELECT ");
00900      sqlStat.append("ASSM_ITEMS.posn,items.mfr_ser_no from ASSM_ITEMS,items WHERE assm_ser_no="+sn);
00901      sqlStat.append(" AND items.ser_no=assm_items.ser_no AND assm_items.ctype = 'chABCD3T'");
00902 
00903 //     System.out.println("now get chips ...");
00904 //     System.out.println(sqlStat.toString());
00905      statement = SCTDBInterface.getInstance().connection.createStatement();
00906      resultSet = statement.executeQuery(sqlStat.toString());
00907 
00908      int chipno=0;
00909      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00910           String posn = resultSet.getString(1);
00911           String mfr_sn = resultSet.getString(2);
00912           Matcher matcher = lotNoPattern.matcher(mfr_sn);
00913           int thePosition = Integer.parseInt(posn);
00914           thePosition--;
00915           posn = Integer.toString(thePosition);
00916 //          System.out.println("chipno="+chipno+", posn="+posn+", mfr_sn="+mfr_sn);
00917           if(matcher.matches()) {
00918             mfr_sn = mfr_sn.substring(matcher.start(1),matcher.end(1));
00919             if(posn.length()<2) posn="0"+posn;
00920             thisHash.put(posn,mfr_sn);
00921 //            System.out.println("chipno="+chipno+", posn="+posn+", mfr_sn="+mfr_sn);
00922             }
00923           chipno++;
00924           }
00925       statement.close();
00926      if(thisHash.size()!=12) {
00927         System.out.println("No asic assembly data for hybrid "+sn);
00928         return new Hashtable();
00929         }
00930 // ok, now go through the chips to get the cal correction factors
00931      Hashtable correctionHash = new Hashtable();
00932      int ifactors=0;
00933      for (Enumeration e = thisHash.keys() ; e.hasMoreElements() ;) {
00934          String thisPosn = (String)e.nextElement();
00935          String thisLotNo = (String)thisHash.get(thisPosn);
00936          if(!correctionHash.containsKey(thisLotNo)) {
00937               String factor = WaferUtilities.getCalCorrFactor(thisLotNo); 
00938               if(!factor.equals("")) correctionHash.put(thisLotNo,factor);
00939               }
00940          if(correctionHash.containsKey(thisLotNo)) {
00941               String thisFactor = (String)correctionHash.get(thisLotNo);
00942               thisHash.put(thisPosn,thisFactor);
00943 //              System.out.println("Putting "+thisFactor+" into chip position "+thisPosn);
00944               ifactors++;
00945               }
00946          }
00947       ifactors = 12 - ifactors;
00948       if(ifactors>0) System.out.println("WARNING: CalCorr factors not found for "+ifactors+" chips");
00949     
00950       return thisHash;    
00951 
00952 }
00953    public static Hashtable getRCFits(String sn, String location, String runNo, String scanNo) throws Exception {
00954 
00955       Hashtable rcFitHash = new Hashtable();
00956       if(sn==null) {
00957          System.err.println("Null serialno in getRCFits");
00958          return rcFitHash;
00959          }
00960       if(location==null) {
00961          System.err.println("Null location in getRCFits");
00962          return rcFitHash;
00963          }
00964 
00965       int scanNumber= Integer.parseInt(scanNo);
00966 // the run-scan of the ResponseCurve is either 10 or 12 scans before the run-scan in the module config file
00967 // depending on whether it was uploaded with the TimeWalk or Noise test
00968       String rsString1 = runNo+"-"+Integer.toString(scanNumber-10);
00969       String rsString2 = runNo+"-"+Integer.toString(scanNumber-21);
00970 
00971 // first get the hybrid serial no
00972      StringBuffer sqlStat = new StringBuffer("SELECT tests.test_no");
00973 
00974      for(int i=0;i<12;i++) {
00975         for (int y=9;y<=12;y++) sqlStat.append(","+chipDBnames[i]+DBChipParameterNames[SCTDB_TEST_NPTGAIN][y]);
00976         }
00977      sqlStat.append(" FROM SCT_TSTHYBRC,tests WHERE SCT_TSTHYBRC.test_no=tests.test_no");
00978      sqlStat.append(" AND (tests.run_no='"+rsString1+"' OR tests.run_no='"+rsString2+"')");
00979      sqlStat.append(" AND tests.ser_no="+sn+" AND tests.locn_name='"+location+"'");
00980 
00981 //     System.out.println(sqlStat.toString());
00982 
00983      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00984      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00985 
00986      int arg=1;
00987      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00988           String testno = resultSet.getString(arg++);
00989           for(int chipno=0;chipno<12;chipno++) {
00990               String line = "<rc_function type=\""+resultSet.getString(arg++)+"\">p0 "+resultSet.getString(arg++)+" p1 "+resultSet.getString(arg++)+" p2 "+resultSet.getString(arg++)+"</rc_function>";
00991               String posn = Integer.toString(chipno);
00992               if(posn.length()<2) posn="0"+posn;
00993               rcFitHash.put(posn,line);
00994               }
00995           }
00996       statement.close();
00997       return rcFitHash;
00998       }
00999 
01000 
01001 
01002      
01003 
01004 
01005 // ******************************************************************************************************************
01006     public static boolean confirmLocation(String location) throws Exception {
01007      boolean foundit=false;
01008      String sqlStat = new String("SELECT locn_name FROM locns WHERE locn_name='"+location+"'");
01009      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01010      ResultSet resultSet = statement.executeQuery(sqlStat);
01011      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01012            return true;
01013             }
01014       statement.close();
01015       return foundit;
01016      }
01017 //**************************************************************
01018      public static String getTestString(int testIndex,String testno) {
01019          Hashtable snHash = new Hashtable();
01020          Hashtable testnoHash = new Hashtable();
01021 
01022          StringBuffer result = new StringBuffer();
01023 
01024          StringBuffer sqlStat = new StringBuffer();
01025             sqlStat = new StringBuffer("SELECT tests.ser_no,tests.pass,tests.problem,tests.TEST_no,tests.locn_name,tests.TEST_date,tests.run_no,tests.test_name,SCT_TSTDCSINFO.T0");
01026             sqlStat.append(",SCT_TSTDAQINFO.VERSION,SCT_TSTDAQINFO.TEST_TIME");
01027             switch(testIndex) {
01028                     case SCTDB_TEST_RESET:
01029                     case SCTDB_TEST_REDUNDANCY:
01030                     case SCTDB_TEST_LONGTERM:
01031                     case SCTDB_TEST_IV:
01032                         break;
01033                     default:
01034                         for(int y=0;y<chipDBnames.length;y++) {
01035                            for(int paramIndex=0;paramIndex<DBChipParameterNames[testIndex].length;paramIndex++) {
01036                                   sqlStat.append(","+chipDBnames[y]+DBChipParameterNames[testIndex][paramIndex]);
01037                                   }
01038                           }
01039 
01040                      }
01041          sqlStat.append(" FROM "+sctdaqDBTableNames[testIndex]+",tests,SCT_TSTDCSINFO,SCT_TSTDAQINFO");
01042          sqlStat.append(" WHERE tests.test_no = "+testno);
01043          sqlStat.append(" AND tests.TEST_no = "+sctdaqDBTableNames[testIndex]+".TEST_no");
01044          sqlStat.append(" AND tests.TEST_no = SCT_TSTDCSINFO.TEST_no");
01045          sqlStat.append(" AND tests.TEST_no = SCT_TSTDAQINFO.TEST_no");
01046          sqlStat.append(" ORDER BY tests.TEST_date DESC,tests.TEST_no DESC");
01047 
01048          try {
01049 
01050          Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01051 //         System.out.println(sqlStat.toString());
01052          ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01053          for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01054             int rc=1;
01055 
01056             String sn = resultSet.getString(rc++);
01057             result.append("SERIALNO="+sn+"\n");
01058             if(snHash.containsKey(sn)) continue;
01059             int status = (resultSet.getString(rc++).equals("YES")) ? 0 : 2;
01060             if(resultSet.getString(rc++).equals("YES") && status==0) status = 1;
01061 
01062 
01063 
01064             result.append(sctdaqNormalTestNames[testIndex]+"\n");
01065             switch(status) {
01066               case 0:
01067                  result.append("PASS\n");
01068                  break;
01069               case 1:
01070                  result.append("PROBLEM\n");
01071                  break;
01072               default:
01073                  result.append("FAIL\n");
01074                  }
01075             result.append("TESTNO="+resultSet.getString(rc++)+"\n");  // testno
01076             result.append("LOCATION="+resultSet.getString(rc++)+"\n");  //date
01077             result.append("DATE="+guiUtilities.DaveUtils.extractDate(resultSet.getString(rc++))+"\n");
01078             result.append("RUN/SCAN="+resultSet.getString(rc++)+"\n");
01079             result.append("TESTNAME="+resultSet.getString(rc++)+"\n");
01080             result.append("TEMPERATURE="+resultSet.getString(rc++)+"\n");
01081            result.append("SCTDAQ_VERSION="+resultSet.getString(rc++)+"\n");
01082            result.append("TIME="+resultSet.getString(rc++)+"\n");
01083 
01084             result.append("Chip\t");
01085             for(int i=0;i<DBChipParameterNames[testIndex].length;i++) result.append(DBChipParameterNames[testIndex][i]+"\t");
01086             result.append("\n");
01087 
01088             for(int chip=0;chip<12;chip++) {
01089               result.append(chipDBnames[chip].substring(0,2)+"\t");
01090               for(int r=0;r<DBChipParameterNames[testIndex].length;r++) {
01091                  if(r>0) result.append("\t");
01092                  result.append(resultSet.getString(rc++));
01093                  }
01094               result.append("\n");
01095               }
01096 
01097             }
01098         statement.close();
01099 
01100         sqlStat = new StringBuffer();
01101         sqlStat.append("SELECT defects.defect_name,defects.chan_1st,defects.chan_last");
01102         sqlStat.append(" FROM defects");
01103         sqlStat.append(" WHERE defects.TEST_no = "+testno);
01104 
01105 
01106         statement = SCTDBInterface.getInstance().connection.createStatement();
01107 //         System.out.println(sqlStat.toString());
01108         resultSet = statement.executeQuery(sqlStat.toString());
01109         int ndefects=0;
01110         result.append("Defects:\n");
01111         for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){ 
01112             ndefects++;
01113             String defectName = resultSet.getString(1);
01114             String chan1 = resultSet.getString(2);
01115             String chanLast = resultSet.getString(3);
01116             result.append(chan1+"-"+chanLast+" : "+defectName+"\n");
01117             }
01118         statement.close();
01119         result.append("defectCount="+Integer.toString(ndefects)+"\n");
01120 
01121         }catch(Exception e) {System.out.println("Failed to publish SCTDB Data: "+e.toString());}
01122 
01123         return result.toString();
01124 }
01125 
01126 //****************************************************************************************8
01127      public static void removePreviousUploads(String testname, String runno, String locn, Map itemList) throws Exception {
01128 
01129      StringBuffer sqlStat = new StringBuffer("SELECT tests.ser_no,test_name,run_no,test_date,sct_tstdaqinfo.test_time FROM tests,sct_tstdaqinfo");
01130      sqlStat.append(" WHERE tests.test_name='"+testname+"' AND tests.locn_name='"+locn+"' AND tests.run_no='"+runno+"' AND sct_tstdaqinfo.test_no=tests.test_no");
01131      sqlStat.append(" AND sct_tstdaqinfo.version LIKE 'SctRodDaq%'");
01132      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01133 //     System.out.println(sqlStat.toString());
01134      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01135      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01136           StringBuffer thisSig = new StringBuffer(resultSet.getString(1));
01137           thisSig.append("_");
01138           thisSig.append(resultSet.getString(2));   // testname
01139           thisSig.append("_");
01140           thisSig.append(resultSet.getString(3));   // run_no
01141           thisSig.append("_");
01142           thisSig.append(guiUtilities.DaveUtils.extractSCTDAQDate(resultSet.getString(4)));   // date
01143           thisSig.append("_");
01144           thisSig.append(resultSet.getString(5));   // time
01145           String signature = thisSig.toString();
01146           if(itemList.containsKey(signature)) {
01147               System.out.println("Data for "+signature.substring(0,14)+" is already uploaded!");
01148               itemList.remove(signature);
01149               }
01150             }
01151       statement.close();
01152      }
01153 
01154 //*************************************************************
01155      public static String getUserName(String locn) throws Exception {
01156      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01157 //     System.out.println(sqlStat.toString());
01158      ResultSet resultSet = statement.executeQuery("SELECT username FROM locns WHERE locn_name='"+locn+"'");
01159      String username = null;
01160      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01161           username = resultSet.getString(1);
01162           }
01163      statement.close();
01164      return username;
01165      }
01166 //*************************************************************
01167      public static String getSerialNo(String testno) throws Exception {
01168      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01169 //     System.out.println(sqlStat.toString());
01170      ResultSet resultSet = statement.executeQuery("SELECT ser_no FROM tests WHERE test_no='"+testno+"'");
01171      String sn = null;
01172      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01173           sn = resultSet.getString(1);
01174           }
01175      statement.close();
01176      return sn;
01177      }
01178 //*************************************************************
01179      public static String getCType(String serno) throws Exception {
01180      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01181 //     System.out.println(sqlStat.toString());
01182      ResultSet resultSet = statement.executeQuery("SELECT ctype FROM items WHERE ser_no='"+serno+"'");
01183      String ctype = null;
01184      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01185           ctype = resultSet.getString(1);
01186           }
01187      statement.close();
01188      return ctype;
01189      }
01190 //**********************************************************
01191     public static List getTestList(int testIndex,String locn, String testMenuName) throws Exception {
01192      java.util.regex.Pattern runPattern = java.util.regex.Pattern.compile("(\\d+)-(\\d+)");
01193      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01194      StringBuffer sqlStat = new StringBuffer("SELECT DISTINCT test_date,run_no FROM tests,sct_tstdaqinfo WHERE locn_name='"+locn+"' AND test_name='"+sctdaqDBTestNames[testIndex]+"'");
01195      sqlStat.append(" AND tests.test_no=sct_tstdaqinfo.test_no AND sct_tstdaqinfo.version LIKE 'SctRodDaq%'");
01196      sqlStat.append(" ORDER BY tests.test_date DESC");
01197 //     System.out.println(sqlStat.toString());
01198      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01199      List itemList = new ArrayList();
01200      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01201           List row = new ArrayList();
01202           row.add(guiUtilities.DaveUtils.extractDate(resultSet.getString(1)));
01203           row.add(testMenuName);
01204           String runno = resultSet.getString(2);
01205           java.util.regex.Matcher matcher = runPattern.matcher(runno);
01206           if(!matcher.matches()) {
01207             System.err.println("Unrecognised runno "+runno);
01208             continue;
01209              }
01210           
01211           row.add(runno.substring(matcher.start(1),matcher.end(1)));
01212           row.add(runno.substring(matcher.start(2),matcher.end(2)));
01213           itemList.add(row);
01214 
01215           }
01216      statement.close();
01217      return itemList;
01218      }
01219 
01220 //******************************************************
01221    public static SCTDBTestInfoHolder getTestInfo(String test_no) throws Exception {
01222 
01223       SCTDBTestInfoHolder testInfo= new SCTDBTestInfoHolder();
01224 
01225       StringBuffer genTable = new StringBuffer();
01226       StringBuffer sqlStat = new StringBuffer("SELECT tests.test_name,tests.ser_no,tests.test_date,tests.locn_name,items.ctype FROM tests,items WHERE tests.test_no="+test_no);
01227       sqlStat.append(" AND items.ser_no=tests.ser_no");
01228 
01229 // submit query
01230      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01231      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01232    
01233      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01234           testInfo.put(SCTDBTestInfoHolder.TEST_NAME,resultSet.getString(1));
01235           testInfo.put(SCTDBTestInfoHolder.SN,resultSet.getString(2));
01236           testInfo.put(SCTDBTestInfoHolder.DATE,guiUtilities.DaveUtils.extractDate(resultSet.getString(3)));
01237           testInfo.put(SCTDBTestInfoHolder.LOCATION,resultSet.getString(4));
01238           testInfo.put(SCTDBTestInfoHolder.CTYPE,resultSet.getString(5));
01239           }
01240      testInfo.put(SCTDBTestInfoHolder.TESTNUMBER,test_no);
01241      statement.close();
01242      if(testInfo.isValid()) return testInfo;
01243      return null;
01244      }
01245 
01246 // **********************************************************************************************
01247     public static Vector getTestHistory(String serialNo) throws Exception {
01248      StringBuffer sqlStat = new StringBuffer("SELECT ");
01249      sqlStat.append("tests.ser_no,tests.locn_name,tests.test_date,tests.test_name,tests.problem,tests.pass");
01250      sqlStat.append(" FROM tests");
01251      sqlStat.append(" WHERE tests.ser_no = "+serialNo);
01252      sqlStat.append(" ORDER BY tests.test_date,tests.test_no");
01253      
01254 
01255       Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01256       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01257       Hashtable serNoHash = new Hashtable();
01258       Hashtable thisHash;
01259       Vector serNoList = new Vector();
01260       Vector theLine = new Vector();
01261       Vector itemList = new Vector();
01262       int recordCount=0;
01263       theLine.addElement("Serial Number");
01264       theLine.addElement("Test Location");
01265       theLine.addElement("Date");
01266       theLine.addElement("Test Name");
01267       theLine.addElement("Test Status");
01268       itemList.addElement(theLine);
01269       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01270           theLine = new Vector();
01271           theLine.addElement(resultSet.getString(1));
01272           theLine.addElement(resultSet.getString(2));
01273           theLine.addElement(guiUtilities.DaveUtils.extractDate(resultSet.getString(3)));
01274           theLine.addElement(resultSet.getString(4));
01275 
01276           String problemFlag = resultSet.getString(5);
01277           String passFlag = resultSet.getString(6);
01278           String statusFlag; 
01279           if(passFlag.equals("YES")) {
01280              statusFlag = (problemFlag.equals("YES")) ? "Problem" : "Pass";
01281              }
01282           else statusFlag="FAIL";
01283           theLine.addElement(statusFlag);
01284           itemList.addElement(theLine);
01285           recordCount++;
01286           if(recordCount%100 ==0) System.out.println("Retrieved "+recordCount+" records ...");
01287             }
01288        System.out.println("Retrieved "+recordCount+" records in total.");
01289 
01290        statement.close();
01291        return itemList;
01292 
01293      }
01294 
01295    public static Vector getShipmentHistory(String serialNo) throws Exception {
01296       Vector theLine = new Vector();
01297       Vector itemList = new Vector();
01298       StringBuffer sqlStat = new StringBuffer("SELECT ship_items.ser_no,ship_items.ship_no,ship.locn_name,ship.dest_locn_name,ship.ship_date,ship_items.recvd FROM ship,ship_items ");
01299       sqlStat.append("WHERE ship_items.ser_no="+serialNo+" AND ship_items.ship_no=ship.ship_no ");
01300       sqlStat.append("ORDER BY ship.ship_date,ship.ship_no"); 
01301  
01302       theLine.addElement("Serial Number");
01303       theLine.addElement("Shipment No");
01304       theLine.addElement("Sent from");
01305       theLine.addElement("Received By");
01306       theLine.addElement("Send Date");
01307       theLine.addElement("Received?");
01308       itemList.addElement(theLine);
01309       Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01310       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01311       
01312       int recordCount=0;
01313       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01314           theLine = new Vector();
01315           theLine.addElement(resultSet.getString(1));
01316           theLine.addElement(resultSet.getString(2));
01317           theLine.addElement(resultSet.getString(3));
01318           theLine.addElement(resultSet.getString(4));
01319           theLine.addElement(guiUtilities.DaveUtils.extractDate(resultSet.getString(5)));
01320           theLine.addElement(new Boolean(resultSet.getString(6).equals("YES")));
01321           itemList.addElement(theLine);
01322 
01323           recordCount++;
01324           if(recordCount%100 ==0) System.out.println("Retrieved "+recordCount+" shipment records ...");
01325             }
01326        System.out.println("Retrieved "+recordCount+" shipment records in total.");
01327        statement.close();
01328        return itemList;
01329        }
01330 
01331 
01332     public static List getRodList(String sn) throws Exception {
01333 
01334       StringBuffer sqlStat = new StringBuffer("SELECT ");
01335       sqlStat.append(" tests.test_no,tests.ser_no,tests.locn_name,tests.test_date,sct_tstdcsinfo.t0 FROM tests,test_rawdata,sct_tstdcsinfo");
01336       sqlStat.append(" WHERE tests.ser_no="+sn);
01337       sqlStat.append(" AND ( (tests.test_name = 'HybTWalk' AND tests.locn_name !='Oxford') OR (tests.test_name = 'HybNoise' AND tests.locn_name = 'Oxford'))");
01338 
01339       sqlStat.append(" AND tests.test_no = sct_tstdcsinfo.test_no AND tests.test_no=test_rawdata.test_no");
01340       sqlStat.append(" ORDER BY tests.ser_no,tests.test_date,tests.test_no");
01341 
01342      List itemList = new ArrayList();
01343 
01344      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01345      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01346      testNumberList = new Vector();
01347      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01348           testNumberList.addElement(resultSet.getString(1));
01349           List thisLine = new ArrayList();
01350           thisLine.add(resultSet.getString(2));  //sn
01351           thisLine.add(resultSet.getString(3)); // location
01352           thisLine.add(guiUtilities.DaveUtils.extractDate(resultSet.getString(4)));
01353           thisLine.add(resultSet.getString(5));
01354           itemList.add(thisLine);
01355          }
01356 
01357       statement.close();
01358 
01359       return itemList;
01360 
01361       }
01362 
01363         
01364      
01365 
01366 
01367 }

Generated on Sat Jul 31 14:20:55 2004 for SCT DAQ/DCS Software - Java by doxygen 1.3.5