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 //         System.out.println(sqlStat.toString());
00329          Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00330          ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00331          int recordCount=0;
00332          for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00333             String sn = resultSet.getString(1);
00334             String testno = resultSet.getString(2);
00335             String locn = resultSet.getString(3);
00336             String runno = resultSet.getString(4);
00337             boolean isUKUpload = (locn.equals("Cambridge") || locn.equals("RAL") || locn.equals("Birmingham"));
00338             if(!isUKUpload && !signoffType.equals(runno)) continue;   // non-UK uploads both SIGNOFF and FINALSIGNOFF
00339             if(isUKUpload && runno.equals("SIGNOFF")) continue; // UK uploads FINALSIGNOFF only
00340             if(latestOnly && snHash.contains(sn)) continue;
00341             snList.addElement(testno);
00342             snHash.add(sn);
00343             recordCount++;
00344             if(recordCount%100==0) System.out.println("Retrieved "+recordCount+" tests so far...");
00345             }
00346       System.out.println("Retrieved "+recordCount+" tests in total, now downloading and extracting raw data");
00347       statement.close();
00348       return snList;
00349       }
00350 //*************************************************
00351     public static String getUploaderInfo(String testno) throws Exception {
00352          StringBuffer sqlStat = new StringBuffer("SELECT locn_name,test_date,initls FROM tests");
00353          sqlStat.append(" WHERE test_no="+testno);
00354          Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00355          ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00356          String returnString=null;
00357          for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00358             String location = resultSet.getString(1);
00359             String testdate = guiUtilities.DaveUtils.extractDate(resultSet.getString(2));
00360             String initials = resultSet.getString(3);
00361             returnString = "Uploaded by "+initials+" from "+location+" on "+testdate;
00362             }
00363       statement.close();
00364       return returnString;
00365       }
00366 //**********************************************************
00367   public static Hashtable testComments(String testno_subQuery) throws Exception {
00368      return testComments(testno_subQuery,false);
00369      }
00370    public static Hashtable testComments(String testno_subQuery, boolean isHTML) throws Exception {
00371       String nl = isHTML ? "<br>" : " ";
00372       Hashtable commentHash = new Hashtable();
00373       StringBuffer sqlStat = new StringBuffer("SELECT test_no,cmnt_text FROM test_cmnts WHERE test_no IN (SELECT tests.test_no FROM tests ");
00374       sqlStat.append(testno_subQuery+")");
00375 //      System.out.println(sqlStat.toString());
00376      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00377      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00378      int ncomments=0;
00379      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00380           ncomments++;
00381           if(ncomments%100 ==0) System.out.println("Retrieved "+ncomments+" comments so far...");
00382           String testno = resultSet.getString(1);
00383           String comment = resultSet.getString(2);
00384           // beware of more than one comment in a given testno !
00385           String newComment = (commentHash.containsKey(testno)) ? (String)commentHash.get(testno)+nl+comment : comment;
00386           commentHash.put(resultSet.getString(1),newComment);
00387             }
00388       statement.close();
00389       return commentHash;
00390       }
00391 
00392 
00393 
00394 
00395    public static Hashtable testImages(String testno_subQuery) throws Exception {
00396 // has contains a vector, and the vector contains title, then url, then title, then url etc
00397       Hashtable testImageHash = new Hashtable();
00398 //      System.out.println("Checking for test images...");
00399       StringBuffer sqlStat = new StringBuffer("SELECT test_no,title,name FROM test_images WHERE test_no IN (SELECT tests.test_no FROM tests ");      
00400       sqlStat.append(testno_subQuery+")");
00401 
00402      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00403      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00404      int ncomments=0;
00405      Vector imageList;
00406      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00407           ncomments++;
00408           if(ncomments%100 ==0) System.out.println("Retrieved "+ncomments+" test images so far...");
00409           String testno = resultSet.getString(1);
00410           String title = resultSet.getString(2);
00411           String name = resultSet.getString(3);
00412           // beware of more than one image in a given testno !
00413           if(testImageHash.containsKey(testno)) imageList = (Vector)testImageHash.get(testno);
00414           else imageList = new Vector();
00415           imageList.addElement(title);
00416           imageList.addElement(name);
00417           testImageHash.put(testno,imageList);
00418             }
00419 //      System.out.println("Retrieved "+ncomments+" test images in total.");
00420       statement.close();
00421       return testImageHash;
00422       }
00423 
00424 //***********************************************************************************************
00425    public static void saveImage(String testno, String fileName, File theFile) throws Exception {
00426       InputStream in;   
00427       FileOutputStream fos = new FileOutputStream(theFile);               
00428       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00429 
00430      String sqlQuery = "SELECT data FROM test_images WHERE test_no="+testno+" AND name='"+fileName+"'";
00431      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00432      ResultSet resultSet = statement.executeQuery(sqlQuery);
00433 
00434 // execute query here
00435       System.out.println("Retrieving "+fileName+" ...");
00436      int nByteCount=0;
00437 
00438      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00439          in  = resultSet.getBinaryStream(1);           // open the data stream
00440 
00441 // read the data - will stop when reach end of stream or error, hopefully!
00442          for(int nbytes=in.read(buffer); nbytes>0; nbytes=in.read(buffer)){
00443 
00444             // System.out.print("Nbytes read : " + nbytes+". ");
00445             nByteCount += nbytes;
00446             fos.write(buffer,0,nbytes);  // write the data to the file output
00447             }
00448          fos.close();  // close the file output
00449          System.out.println("Saved image "+fileName+" with size "+nByteCount+" bytes...");
00450          guiUtilities.HTMLViewer.getInstance().addImageFile(theFile.getAbsolutePath());
00451 
00452          }
00453      statement.close();
00454      return;
00455 }
00456 // *****************************************************************************************************************
00457     public static Vector getItemVector(String serialNo) throws Exception {
00458       Vector itemList = new Vector();
00459       StringBuffer sqlStat = new StringBuffer("SELECT ");
00460       sqlStat.append("mfr,mfr_ser_no,ctype,locn_name,assembled,trashed FROM items WHERE ser_no="+serialNo);
00461       sqlStat.append(" ORDER BY ser_no");
00462 
00463      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00464 //      System.out.println("Interrogating items table ...");
00465       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00466       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00467           itemList.addElement(resultSet.getString(1));   // mfr name
00468           itemList.addElement(resultSet.getString(2));   // mfr serial no
00469           itemList.addElement(resultSet.getString(3));   // type
00470           itemList.addElement(resultSet.getString(4));   // location name
00471           itemList.addElement(resultSet.getString(5));   // assembled flag
00472           itemList.addElement(resultSet.getString(6));   // trashed flag
00473             }
00474       statement.close();
00475       return itemList;
00476       }
00477 
00478 // ******************************************************************************************************
00479     public static Vector getVisualTestList(String ser_no1, String ser_no2, String location, String currLocn,String orderString) throws Exception {
00480      StringBuffer sqlStat = new StringBuffer("SELECT ");
00481      sqlStat.append("tests.test_no,tests.ser_no,tests.test_date,tests.locn_name,tests.problem,tests.pass");
00482      sqlStat.append(" FROM tests");
00483      sqlStat.append(" WHERE tests.ser_no >= "+ser_no1+" AND tests.ser_no <= "+ser_no2);
00484      if(!location.equals("Anywhere")) sqlStat.append(" AND tests.locn_name='"+location+"'");
00485      if(!currLocn.equals("Anywhere")) sqlStat.append(" AND tests.ser_no IN (SELECT items.ser_no FROM items WHERE items.locn_name='"+currLocn+"')");
00486      sqlStat.append(" AND tests.test_name='Visual_Inspection'");
00487      sqlStat.append(" ORDER BY "+orderString);
00488      return createVisualTestTable(sqlStat.toString());
00489      }
00490 // ******************************************************************************************************
00491     public static Vector getVisualTestList(String ser_no1, String ser_no2, String location, String currLocn) throws Exception {
00492       return getVisualTestList(ser_no1,ser_no2,location,currLocn,"tests.ser_no,tests.test_date,tests.test_no");
00493      }
00494 //***************************************************************8
00495     public static Vector createVisualTestTable(String theQuery) throws Exception {
00496       Hashtable testnoHash = new Hashtable();
00497       Vector testnoList = new Vector();
00498       Vector itemList = new Vector();
00499       Vector theLine = new Vector();
00500       String snKey="SNKEY";
00501       String dateKey="DATEKEY";
00502       String locationKey="LOCATIONKEY";
00503       String flagKey="FLAGKEY";
00504 
00505      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00506 
00507      System.out.println("Interrogating tests and tstdetivs tables ...");
00508      ResultSet resultSet = statement.executeQuery(theQuery);
00509      int recordCount=0;
00510      testNumberList = new Vector();
00511      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00512           Hashtable thisHash = new Hashtable();
00513           recordCount++;
00514           if(recordCount%100 == 0) System.out.println("Retrieved "+recordCount+" records so far...");
00515           String testno = resultSet.getString(1);
00516           thisHash.put(snKey,resultSet.getString(2));
00517           String date = resultSet.getString(3);
00518           thisHash.put(dateKey,guiUtilities.DaveUtils.extractDate(date));
00519           thisHash.put(locationKey,resultSet.getString(4));
00520           String problemFlag = resultSet.getString(5);
00521           String passFlag = resultSet.getString(6);
00522           String statusFlag; 
00523           if(passFlag.equals("YES")) {
00524              statusFlag = (problemFlag.equals("YES")) ? "PROBLEM" : "Ok";
00525              }
00526           else statusFlag = "FAIL";
00527           thisHash.put(flagKey,statusFlag);
00528           testnoHash.put(testno,thisHash);   
00529           testnoList.addElement(testno);  
00530 
00531             }
00532       System.out.println("Retrieved "+recordCount+" records in total.");
00533       statement.close();
00534       if(recordCount==0) return itemList;
00535 
00536 // now get the comments, if any
00537       String subQuery = theQuery;
00538       subQuery = subQuery.substring(subQuery.indexOf("WHERE"),subQuery.indexOf("ORDER")-1);
00539       Hashtable commentsHash = testComments(subQuery);
00540       Hashtable testImagesHash = testImages(subQuery);
00541 
00542       theLine.addElement("Serial Number");
00543       theLine.addElement("Date");
00544       theLine.addElement("Location");
00545       theLine.addElement("Status");
00546       theLine.addElement("Remarks");
00547       theLine.addElement("Pictures");
00548       itemList.addElement(theLine);
00549 
00550       for(int i=0;i<testnoList.size();i++) {
00551             theLine = new Vector();
00552             String testno = (String)testnoList.elementAt(i); // this contains the testno's, ordered by serial no
00553             Hashtable tempHash = (Hashtable)testnoHash.get(testno);
00554             theLine.addElement(tempHash.get(snKey));                                      // first column is serial number
00555 
00556             theLine.addElement(tempHash.get(dateKey));                                    // 2nd column is the date
00557             theLine.addElement(tempHash.get(locationKey));              
00558             theLine.addElement(tempHash.get(flagKey));
00559             if(commentsHash.containsKey(testno)) theLine.addElement(commentsHash.get(testno));
00560             else theLine.addElement("");
00561             if(testImagesHash.containsKey(testno)) {
00562                Vector imageList = (Vector)testImagesHash.get(testno);
00563 
00564                for(int j=0;j<imageList.size()/2; j++) {
00565                    if(j==0) {
00566 
00567                               theLine.addElement((String)imageList.elementAt(0));
00568                               testNumberList.addElement(testno);
00569                               itemList.addElement(theLine);
00570                               }
00571                    else {
00572 
00573                               theLine = new Vector();
00574                               theLine.addElement(tempHash.get(snKey));
00575                               theLine.addElement("  ''");
00576                               theLine.addElement("  ''");
00577                               theLine.addElement("  ''");
00578                               theLine.addElement("  ''");
00579                               theLine.addElement((String)imageList.elementAt(2*j));  
00580                               testNumberList.addElement(testno);
00581                               itemList.addElement(theLine);                     
00582                           }
00583 
00584                       }
00585             }
00586             else {theLine.addElement(""); testNumberList.addElement(testno);itemList.addElement(theLine);}
00587             }
00588       return itemList;
00589 
00590 
00591       }
00592 //
00593 //***********************************************************************************************
00594    public static Vector getImages(String testno,String headerTitle) throws Exception {
00595       InputStream in;   
00596  //     FileOutputStream fos;               
00597       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00598 
00599      Vector imageList = new Vector();
00600 
00601      String sqlQuery = "SELECT data,title,name FROM test_images WHERE test_no="+testno;
00602      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00603      ResultSet resultSet = statement.executeQuery(sqlQuery);
00604 
00605 // execute query here
00606       System.out.println("Interrogating test_images table for images ...");
00607      int nByteCount=0;
00608      int noImages=0;
00609 
00610      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00611          noImages++;
00612          in  = resultSet.getBinaryStream(1);           // open the data stream
00613 
00614 // read the data - will stop when reach end of stream or error, hopefully!
00615          for(int nbytes=in.read(buffer); nbytes>0; nbytes=in.read(buffer)){
00616             nByteCount += nbytes;
00617             }
00618          javax.swing.ImageIcon thisImage;
00619          try {
00620            thisImage = new javax.swing.ImageIcon(buffer);
00621          } catch (Exception e) {thisImage=null;} // just in case 
00622          String title = resultSet.getString(2);
00623          String name = resultSet.getString(3);
00624          System.out.println("Retrieved image "+name+" with size "+nByteCount+" bytes...");
00625          imageList.addElement(new guiUtilities.Photo(thisImage,title,name,headerTitle,testno));
00626          }
00627      System.out.println("Retrieved "+noImages+" images in total for test number "+testno);
00628      statement.close();
00629 //     storedImages.put(testno,imageList); // store the image list vector, in case we want to look again
00630      return imageList;
00631 }
00632 
00633 //***************************************************************************************************
00634  public static Map getRawDataLists(String sn1, String sn2, String location, int testType, int temperature, String runNo, int testRequest) throws Exception {
00635       Map m = new HashMap();
00636       StringBuffer sqlStat = new StringBuffer("SELECT tests.test_no,tests.ser_no,tests.test_date,tests.locn_name,");
00637       if(testType>=0) sqlStat.append("test_rawdata.filename,");
00638       sqlStat.append("SCT_TSTDCSINFO.T0 FROM tests,");
00639       if(testType>=0) sqlStat.append("test_rawdata,");
00640       sqlStat.append("sct_tstdaqinfo,SCT_TSTDCSINFO ");
00641 
00642       if(testRequest>=0) sqlStat.append("WHERE tests.test_name='"+sctdaqDBTestNames[testRequest]+"'");
00643       else {
00644         switch(testType) {
00645          case SCTDBInfo.SCTDB_TEST_TIMEWALK: 
00646 // xml data
00647       sqlStat.append(" WHERE ( (tests.test_name = 'HybTWalk' AND tests.locn_name !='Oxford') OR (tests.test_name = 'HybNoise' AND tests.locn_name = 'Oxford'))");
00648           break;
00649          default:
00650           sqlStat.append("WHERE tests.test_name='"+sctdaqDBTestNames[testType]+"'");
00651           }
00652        }
00653      sqlStat.append(" AND tests.ser_no >= "+sn1+" AND tests.ser_no <= "+sn2);
00654      if(runNo!=null) sqlStat.append(" AND tests.run_no LIKE '"+runNo+"'");
00655      if(testType>=0)sqlStat.append(" AND tests.test_no=test_rawdata.test_no");
00656      sqlStat.append(" AND SCT_TSTDCSINFO.test_no=tests.test_no");
00657      if(!location.equals("Anywhere")) sqlStat.append(" AND tests.locn_name='"+location+"'");
00658      sqlStat.append(" AND sct_tstdaqinfo.version NOT LIKE 'SctRodDaq%' AND sct_tstdaqinfo.test_no=tests.test_no"); // REQUIRE sctdaq data only, not SctRodDaq
00659      switch(temperature) {
00660        case 1:
00661          sqlStat.append(" AND SCT_TSTDCSINFO.T0<=10");
00662          break;
00663        case 2:
00664          sqlStat.append(" AND SCT_TSTDCSINFO.T0>10");
00665          break;
00666        default:
00667        }
00668      sqlStat.append(" ORDER BY tests.ser_no,tests.test_date,tests.test_no");
00669 
00670 //     System.out.println(sqlStat.toString());
00671      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00672      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00673 
00674      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00675 
00676            SCTDBTestInfoHolder testInfo = new SCTDBTestInfoHolder();
00677            testInfo.put(SCTDBTestInfoHolder.TESTNUMBER,resultSet.getString(1));
00678            Long sn = new Long(resultSet.getLong(2));
00679            testInfo.put(SCTDBTestInfoHolder.SN,sn.toString());
00680            testInfo.put(SCTDBTestInfoHolder.DATE,guiUtilities.DaveUtils.extractDate(resultSet.getString(3)));
00681            testInfo.put(SCTDBTestInfoHolder.LOCATION,resultSet.getString(4));
00682            int lastIndex = (testType>=0) ? 6 : 5;
00683            testInfo.put(SCTDBTestInfoHolder.TEMPERATURE,resultSet.getString(lastIndex));
00684            m.put(sn,testInfo);
00685        }
00686      statement.close();
00687      return m;
00688      }
00689    public static Vector getRawData(String testno) throws Exception {
00690      return getRawData(testno,PreferencesInterface.getInstance().getPreference(PreferencesInterface.SCRATCH_DIR));
00691      }
00692 
00693 // ****************************************************************************************************************
00694    public static Vector getRawData(String testno, String saveDir) throws Exception {
00695 // get the raw data - if its a zip file, save it to disk with same filename
00696 // otherwise just download as a string
00697       Vector returnData = new Vector();
00698 
00699       // first get filename of the raw data file of this testno
00700 
00701      String sqlQuery = "SELECT filename from test_rawdata WHERE test_no="+testno;
00702      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00703      ResultSet resultSet = statement.executeQuery(sqlQuery);
00704      String thisFname = null;
00705      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00706           thisFname = resultSet.getString(1);
00707           }
00708      statement.close();
00709      if(thisFname==null) {
00710           return returnData;
00711           }
00712 // now download that file
00713      File savedFile = new File(saveDir,thisFname);
00714      if(downloadFile(testno,savedFile)==0) return returnData;
00715 // now read in the downloaded file - firat assume it is zipped...
00716      try {
00717        returnData = unZipFile(savedFile);
00718        }
00719      catch(Exception ee) {
00720 // not zipped, so assume its just text
00721        returnData = getFileContent(savedFile);
00722        File tempFile = new File(thisFname); // get just the last part, not a pathname
00723        returnData.insertElementAt((String)tempFile.getName(),0);
00724        }
00725      boolean deleted = savedFile.delete(); // delete the downloaded file
00726 // check if its an .xml file, if so, assume it is an sctdaq xml config file
00727 // in which case, we want to lookup and susbtitute the calibrate correction factors
00728      returnData = insertCalFactors(returnData);
00729 // index0 : filename
00730 // index1 : content as a String
00731 // ..etc for index2 and 3 etc
00732      return returnData;
00733      }
00734 //***********************************************************************8
00735 public static Vector getFileContent(File theFile) throws Exception {
00736     // get file content as a String
00737     Vector returnData = new Vector();
00738     BufferedReader in = new BufferedReader(new FileReader(theFile));
00739     String line;
00740     StringBuffer stringBuffer = new StringBuffer();
00741     boolean firstLine=true;
00742     while((line=in.readLine())!=null) {
00743       if(!firstLine) stringBuffer.append("\n");
00744       stringBuffer.append(line);
00745       firstLine=false;
00746       }
00747     in.close();
00748     returnData.addElement(stringBuffer.toString());
00749     return returnData;
00750     }
00751 
00752 //********************************************
00753 public static int downloadFile(String testno, File savedFile) throws Exception {
00754 
00755       InputStream in;         
00756       String theData = "";      
00757       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00758     FileOutputStream fos;
00759 // execute query here
00760      String sqlQuery = "SELECT raw_data FROM test_rawdata WHERE test_no="+testno; 
00761      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00762      ResultSet resultSet = statement.executeQuery(sqlQuery);
00763 
00764      int nByteCount=0;
00765      fos = new FileOutputStream(savedFile);       // open the file output stream
00766      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00767          in  = resultSet.getBinaryStream(1);           // open the data stream
00768 
00769 // read the data - will stop when reach end of stream or error, hopefully!
00770          for(int nbytes=in.read(buffer); nbytes>0; nbytes=in.read(buffer)){
00771            nByteCount += nbytes;
00772            fos.write(buffer,0,nbytes);
00773             }
00774          }
00775      fos.close();
00776      statement.close();
00777      if(nByteCount==0) System.out.println("No raw data available for test "+testno);
00778 //     else System.out.println("Downloaded "+savedFile.getName()+", size "+nByteCount+" bytes.");
00779      return nByteCount;
00780 }
00781 //*************************************************************************
00782 public static Vector unZipFile(File savedFile) throws Exception{
00783       Vector returnData = new Vector();
00784       byte[] buffer = new byte[128000]; // max size is 128kByte per image (I think!)
00785 
00786 // now extract the zip file...
00787      final int BUFFER=2048;
00788      ZipFile zFile = new ZipFile(savedFile);
00789      FileInputStream fis = new FileInputStream(savedFile);
00790      ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
00791      ZipEntry entry;
00792      while((entry = zis.getNextEntry()) != null) {
00793          returnData.addElement((String)entry.getName());   // first the data filename
00794          int count;
00795          byte[] data = new byte[BUFFER];
00796          StringBuffer thisData = new StringBuffer();
00797          while((count=zis.read(data,0,BUFFER)) != -1) {
00798             thisData.append(new String(data,0,count)); 
00799             }
00800          returnData.addElement((String)thisData.toString());    // then the filename content as a string
00801         }
00802      zis.close();
00803      return returnData;
00804 }
00805 public static Vector insertCalFactors(Vector rawdata) throws Exception {
00806     String lineTerminator = "\\s*\\n";
00807     Pattern modulePattern = Pattern.compile("<module>");
00808     Pattern locationPattern = Pattern.compile(".*<location>(.*)</location>.*");
00809     Pattern snPattern = Pattern.compile("\\s*<sn>.*(\\d{14}).*</sn>");
00810     Pattern chipIDPattern = Pattern.compile("\\s*<chip id=\"(\\d{2})\".*");
00811     Pattern cFactorPattern = Pattern.compile("(\\s*)<c_factor>.*</c_factor>");
00812     Pattern runNoPattern = Pattern.compile(".*<run>(\\d+)</run><scan>(\\d+)</scan>.*");
00813     Pattern rcFitPattern = Pattern.compile("(.*)<rc_function.*</rc_function>");
00814     String moduleSerialNo = null;
00815     String location=null;
00816     String thisChipPosition=null;
00817     Hashtable chipPositionHash = new Hashtable();
00818     Hashtable rcFitHash = null;
00819 
00820     boolean xmlfile=false;
00821     for(int i=0;i<rawdata.size();i++) {
00822 
00823         if(i%2==0) {
00824             if (((String)rawdata.elementAt(i)).indexOf(".xml")!=-1) xmlfile=true;
00825             else xmlfile=false;
00826             continue;
00827             }
00828 
00829         if(!xmlfile) continue;
00830         String[] lines = ((String)rawdata.elementAt(i)).split(lineTerminator);
00831 
00832         Matcher matcher = modulePattern.matcher(lines[0]);
00833         if(!matcher.matches()) return rawdata;     // first line of xml file is expected to be <module>
00834 
00835         StringBuffer newString = new StringBuffer("<module>");
00836         for(int line=1;line<lines.length;line++) {
00837             String thisLine = lines[line];
00838 //            System.out.println("Checking line "+line+": "+thisLine);
00839             matcher = snPattern.matcher(thisLine);
00840             if(matcher.matches()) {
00841                  moduleSerialNo = thisLine.substring(matcher.start(1),matcher.end(1));
00842                  chipPositionHash = getChipPositionHash(moduleSerialNo);               
00843                  }
00844             matcher = locationPattern.matcher(thisLine);
00845             if(matcher.matches()) location = thisLine.substring(matcher.start(1),matcher.end(1));
00846 
00847             matcher = runNoPattern.matcher(thisLine);
00848             if(matcher.matches()) {
00849                    rcFitHash = getRCFits(moduleSerialNo,location,thisLine.substring(matcher.start(1),matcher.end(1)),thisLine.substring(matcher.start(2),matcher.end(2)));
00850                    if(rcFitHash.size()!=12) System.err.println("Failed to extract RC fit parameters for module config file");
00851                    }
00852 
00853             matcher = rcFitPattern.matcher(thisLine);
00854             if(matcher.matches() && thisChipPosition!=null && rcFitHash!=null) {
00855               String padding = thisLine.substring(matcher.start(1),matcher.end(1));
00856               if(rcFitHash.containsKey(thisChipPosition)) {
00857                  lines[line] = padding+(String)rcFitHash.get(thisChipPosition);
00858                  }
00859               }
00860 
00861             matcher = chipIDPattern.matcher(thisLine);
00862             if(matcher.matches()) {
00863                  thisChipPosition = thisLine.substring(matcher.start(1),matcher.end(1));
00864 //                 System.out.println("Found chip position "+thisChipPosition);
00865                  }
00866             matcher = cFactorPattern.matcher(thisLine);
00867             if(matcher.matches() && thisChipPosition!=null) {
00868                  String spaces = thisLine.substring(matcher.start(1),matcher.end(1));
00869                  if(chipPositionHash.containsKey(thisChipPosition)) lines[line] = spaces+"<c_factor>"+(String)chipPositionHash.get(thisChipPosition)+"</c_factor>";
00870                  else System.err.println("Cal Correction factors are not available for "+moduleSerialNo);
00871                 }
00872             newString.append("\n"+lines[line]);
00873 
00874             }
00875          rawdata.setElementAt((String)newString.toString(),i);
00876 
00877         }
00878 
00879    return rawdata;
00880 }
00881 public static Hashtable getChipPositionHash(String moduleSN) throws Exception {
00882    Pattern lotNoPattern = Pattern.compile("(Z\\d+-W\\d+).*"); // miss out the non-LOT info, eg Z39993-W12 X1 Y2
00883    Hashtable thisHash = new Hashtable();
00884    String sn=null;
00885 // first get the hybrid serial no
00886      StringBuffer sqlStat = new StringBuffer("SELECT ");
00887      sqlStat.append("ser_no from ASSM_ITEMS WHERE assm_ser_no="+moduleSN);
00888      sqlStat.append(" AND (ctype LIKE '%Hybrid%' OR ctype LIKE 'bmHASIC')");
00889 //     System.out.println("get hybrid serial no ...");
00890 //     System.out.println(sqlStat.toString());
00891      Statement statement;
00892      statement = SCTDBInterface.getInstance().connection.createStatement();
00893 
00894      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00895 
00896      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00897           sn = resultSet.getString(1);
00898           }
00899      statement.close();
00900      if(sn==null) return thisHash;  // no entry in assembly table - return empty hash
00901 //     else System.out.println("Hybrid is "+sn);
00902 
00903 // now get the chips in the assembly table
00904 // construct the hash with position as Key and LotNumber as value
00905      sqlStat = new StringBuffer("SELECT ");
00906      sqlStat.append("ASSM_ITEMS.posn,items.mfr_ser_no from ASSM_ITEMS,items WHERE assm_ser_no="+sn);
00907      sqlStat.append(" AND items.ser_no=assm_items.ser_no AND assm_items.ctype = 'chABCD3T'");
00908 
00909 //     System.out.println("now get chips ...");
00910 //     System.out.println(sqlStat.toString());
00911      statement = SCTDBInterface.getInstance().connection.createStatement();
00912      resultSet = statement.executeQuery(sqlStat.toString());
00913 
00914      int chipno=0;
00915      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
00916           String posn = resultSet.getString(1);
00917           String mfr_sn = resultSet.getString(2);
00918           Matcher matcher = lotNoPattern.matcher(mfr_sn);
00919           int thePosition = Integer.parseInt(posn);
00920           thePosition--;
00921           posn = Integer.toString(thePosition);
00922 //          System.out.println("chipno="+chipno+", posn="+posn+", mfr_sn="+mfr_sn);
00923           if(matcher.matches()) {
00924             mfr_sn = mfr_sn.substring(matcher.start(1),matcher.end(1));
00925             if(posn.length()<2) posn="0"+posn;
00926             thisHash.put(posn,mfr_sn);
00927 //            System.out.println("chipno="+chipno+", posn="+posn+", mfr_sn="+mfr_sn);
00928             }
00929           chipno++;
00930           }
00931       statement.close();
00932      if(thisHash.size()!=12) {
00933         System.out.println("No asic assembly data for hybrid "+sn);
00934         return new Hashtable();
00935         }
00936 // ok, now go through the chips to get the cal correction factors
00937      Hashtable correctionHash = new Hashtable();
00938      int ifactors=0;
00939      for (Enumeration e = thisHash.keys() ; e.hasMoreElements() ;) {
00940          String thisPosn = (String)e.nextElement();
00941          String thisLotNo = (String)thisHash.get(thisPosn);
00942          if(!correctionHash.containsKey(thisLotNo)) {
00943               String factor = WaferUtilities.getCalCorrFactor(thisLotNo); 
00944               if(!factor.equals("")) correctionHash.put(thisLotNo,factor);
00945               else {
00946                   System.out.println("WARNING: CalCorr factors not available for wafer "+thisLotNo);
00947                   correctionHash.put(thisLotNo,"1.0");
00948                   }
00949               }
00950          if(correctionHash.containsKey(thisLotNo)) {
00951               String thisFactor = (String)correctionHash.get(thisLotNo);
00952               thisHash.put(thisPosn,thisFactor);
00953 //              System.out.println("Putting "+thisFactor+" into chip position "+thisPosn);
00954               ifactors++;
00955               }
00956          }
00957       ifactors = 12 - ifactors;
00958       if(ifactors>0) System.out.println("WARNING: CalCorr factors not found for "+ifactors+" chips");
00959     
00960       return thisHash;    
00961 
00962 }
00963    public static Hashtable getRCFits(String sn, String location, String runNo, String scanNo) throws Exception {
00964 
00965       Hashtable rcFitHash = new Hashtable();
00966       if(sn==null) {
00967          System.err.println("Null serialno in getRCFits");
00968          return rcFitHash;
00969          }
00970       if(location==null) {
00971          System.err.println("Null location in getRCFits");
00972          return rcFitHash;
00973          }
00974 
00975       int scanNumber= Integer.parseInt(scanNo);
00976 // the run-scan of the ResponseCurve is either 10 or 12 scans before the run-scan in the module config file
00977 // depending on whether it was uploaded with the TimeWalk or Noise test
00978       String rsString1 = runNo+"-"+Integer.toString(scanNumber-10);
00979       String rsString2 = runNo+"-"+Integer.toString(scanNumber-21);
00980 
00981 // first get the hybrid serial no
00982      StringBuffer sqlStat = new StringBuffer("SELECT tests.test_no,tests.run_no");
00983 
00984      for(int i=0;i<12;i++) {
00985         for (int y=9;y<=12;y++) sqlStat.append(","+chipDBnames[i]+DBChipParameterNames[SCTDB_TEST_NPTGAIN][y]);
00986         }
00987      sqlStat.append(" FROM SCT_TSTHYBRC,tests WHERE SCT_TSTHYBRC.test_no=tests.test_no");
00988      sqlStat.append(" AND (tests.run_no='"+rsString1+"' OR tests.run_no='"+rsString2+"')");
00989      sqlStat.append(" AND tests.ser_no="+sn+" AND tests.locn_name='"+location+"'");
00990 
00991 //     System.out.println(sqlStat.toString());
00992 
00993      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
00994      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
00995 
00996      int oKey=0;
00997      java.util.regex.Pattern rPattern = java.util.regex.Pattern.compile("(\\d+)-(\\d+)");
00998      java.util.regex.Matcher matcher;
00999      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01000           int arg=1;
01001           String testno = resultSet.getString(arg++);
01002 //        System.out.println("testno="+testno);
01003 
01004           // want the most recent run and scan only, if by chance nboth 3PtGain and NPtGain are found
01005           String runno = resultSet.getString(arg++);
01006           matcher = rPattern.matcher(runno);
01007           if(matcher.matches()) {
01008              int run = Integer.valueOf(runno.substring(matcher.start(1),matcher.end(1))).intValue();
01009              int scan = Integer.valueOf(runno.substring(matcher.start(2),matcher.end(2))).intValue();
01010              int thisKey = run*100000 + scan;
01011              if(oKey>0) System.out.println("found more than one 3PtGain/NPtGain for "+sn+" from "+location+". Using latest run/scan only....");
01012              if(thisKey<oKey) continue;
01013              oKey=thisKey;
01014              }
01015           for(int chipno=0;chipno<12;chipno++) {
01016               String line = "<rc_function type=\""+resultSet.getString(arg++)+"\">p0 "+resultSet.getString(arg++)+" p1 "+resultSet.getString(arg++)+" p2 "+resultSet.getString(arg++)+"</rc_function>";
01017               String posn = Integer.toString(chipno);
01018               if(posn.length()<2) posn="0"+posn;
01019               rcFitHash.put(posn,line);
01020               }
01021           }
01022       statement.close();
01023       return rcFitHash;
01024       }
01025 
01026 
01027 
01028      
01029 
01030 
01031 // ******************************************************************************************************************
01032     public static boolean confirmLocation(String location) throws Exception {
01033      boolean foundit=false;
01034      String sqlStat = new String("SELECT locn_name FROM locns WHERE locn_name='"+location+"'");
01035      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01036      ResultSet resultSet = statement.executeQuery(sqlStat);
01037      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01038            return true;
01039             }
01040       statement.close();
01041       return foundit;
01042      }
01043 //**************************************************************
01044      public static String getTestString(int testIndex,String testno) {
01045          Hashtable snHash = new Hashtable();
01046          Hashtable testnoHash = new Hashtable();
01047 
01048          StringBuffer result = new StringBuffer();
01049 
01050          StringBuffer sqlStat = new StringBuffer();
01051             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");
01052             sqlStat.append(",SCT_TSTDAQINFO.VERSION,SCT_TSTDAQINFO.TEST_TIME");
01053             switch(testIndex) {
01054                     case SCTDB_TEST_RESET:
01055                     case SCTDB_TEST_REDUNDANCY:
01056                     case SCTDB_TEST_LONGTERM:
01057                     case SCTDB_TEST_IV:
01058                         break;
01059                     default:
01060                         for(int y=0;y<chipDBnames.length;y++) {
01061                            for(int paramIndex=0;paramIndex<DBChipParameterNames[testIndex].length;paramIndex++) {
01062                                   sqlStat.append(","+chipDBnames[y]+DBChipParameterNames[testIndex][paramIndex]);
01063                                   }
01064                           }
01065 
01066                      }
01067          sqlStat.append(" FROM "+sctdaqDBTableNames[testIndex]+",tests,SCT_TSTDCSINFO,SCT_TSTDAQINFO");
01068          sqlStat.append(" WHERE tests.test_no = "+testno);
01069          sqlStat.append(" AND tests.TEST_no = "+sctdaqDBTableNames[testIndex]+".TEST_no");
01070          sqlStat.append(" AND tests.TEST_no = SCT_TSTDCSINFO.TEST_no");
01071          sqlStat.append(" AND tests.TEST_no = SCT_TSTDAQINFO.TEST_no");
01072          sqlStat.append(" ORDER BY tests.TEST_date DESC,tests.TEST_no DESC");
01073 
01074          try {
01075 
01076          Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01077 //         System.out.println(sqlStat.toString());
01078          ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01079          for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01080             int rc=1;
01081 
01082             String sn = resultSet.getString(rc++);
01083             result.append("SERIALNO="+sn+"\n");
01084             if(snHash.containsKey(sn)) continue;
01085             int status = (resultSet.getString(rc++).equals("YES")) ? 0 : 2;
01086             if(resultSet.getString(rc++).equals("YES") && status==0) status = 1;
01087 
01088 
01089 
01090             result.append(sctdaqNormalTestNames[testIndex]+"\n");
01091             switch(status) {
01092               case 0:
01093                  result.append("PASS\n");
01094                  break;
01095               case 1:
01096                  result.append("PROBLEM\n");
01097                  break;
01098               default:
01099                  result.append("FAIL\n");
01100                  }
01101             result.append("TESTNO="+resultSet.getString(rc++)+"\n");  // testno
01102             result.append("LOCATION="+resultSet.getString(rc++)+"\n");  //date
01103             result.append("DATE="+guiUtilities.DaveUtils.extractDate(resultSet.getString(rc++))+"\n");
01104             result.append("RUN/SCAN="+resultSet.getString(rc++)+"\n");
01105             result.append("TESTNAME="+resultSet.getString(rc++)+"\n");
01106             result.append("TEMPERATURE="+resultSet.getString(rc++)+"\n");
01107            result.append("SCTDAQ_VERSION="+resultSet.getString(rc++)+"\n");
01108            result.append("TIME="+resultSet.getString(rc++)+"\n");
01109 
01110             result.append("Chip\t");
01111             for(int i=0;i<DBChipParameterNames[testIndex].length;i++) result.append(DBChipParameterNames[testIndex][i]+"\t");
01112             result.append("\n");
01113 
01114             for(int chip=0;chip<12;chip++) {
01115               result.append(chipDBnames[chip].substring(0,2)+"\t");
01116               for(int r=0;r<DBChipParameterNames[testIndex].length;r++) {
01117                  if(r>0) result.append("\t");
01118                  result.append(resultSet.getString(rc++));
01119                  }
01120               result.append("\n");
01121               }
01122 
01123             }
01124         statement.close();
01125 
01126         sqlStat = new StringBuffer();
01127         sqlStat.append("SELECT defects.defect_name,defects.chan_1st,defects.chan_last");
01128         sqlStat.append(" FROM defects");
01129         sqlStat.append(" WHERE defects.TEST_no = "+testno);
01130 
01131 
01132         statement = SCTDBInterface.getInstance().connection.createStatement();
01133 //         System.out.println(sqlStat.toString());
01134         resultSet = statement.executeQuery(sqlStat.toString());
01135         int ndefects=0;
01136         result.append("Defects:\n");
01137         for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){ 
01138             ndefects++;
01139             String defectName = resultSet.getString(1);
01140             String chan1 = resultSet.getString(2);
01141             String chanLast = resultSet.getString(3);
01142             result.append(chan1+"-"+chanLast+" : "+defectName+"\n");
01143             }
01144         statement.close();
01145         result.append("defectCount="+Integer.toString(ndefects)+"\n");
01146 
01147         }catch(Exception e) {System.out.println("Failed to publish SCTDB Data: "+e.toString());}
01148 
01149         return result.toString();
01150 }
01151 
01152 //****************************************************************************************8
01153      public static void removePreviousUploads(String testname, String runno, String locn, Map itemList) throws Exception {
01154 
01155      StringBuffer sqlStat = new StringBuffer("SELECT tests.ser_no,test_name,run_no,test_date,sct_tstdaqinfo.test_time FROM tests,sct_tstdaqinfo");
01156      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");
01157      sqlStat.append(" AND sct_tstdaqinfo.version LIKE 'SctRodDaq%'");
01158      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01159 //     System.out.println(sqlStat.toString());
01160      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01161      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01162           StringBuffer thisSig = new StringBuffer(resultSet.getString(1));
01163           thisSig.append("_");
01164           thisSig.append(resultSet.getString(2));   // testname
01165           thisSig.append("_");
01166           thisSig.append(resultSet.getString(3));   // run_no
01167           thisSig.append("_");
01168           thisSig.append(guiUtilities.DaveUtils.extractSCTDAQDate(resultSet.getString(4)));   // date
01169           thisSig.append("_");
01170           thisSig.append(resultSet.getString(5));   // time
01171           String signature = thisSig.toString();
01172           if(itemList.containsKey(signature)) {
01173               System.out.println("Data for "+signature.substring(0,14)+" is already uploaded!");
01174               itemList.remove(signature);
01175               }
01176             }
01177       statement.close();
01178      }
01179 
01180 //*************************************************************
01181      public static String getUserName(String locn) throws Exception {
01182      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01183 //     System.out.println(sqlStat.toString());
01184      ResultSet resultSet = statement.executeQuery("SELECT username FROM locns WHERE locn_name='"+locn+"'");
01185      String username = null;
01186      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01187           username = resultSet.getString(1);
01188           }
01189      statement.close();
01190      return username;
01191      }
01192 //*************************************************************
01193      public static String getSerialNo(String testno) throws Exception {
01194      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01195 //     System.out.println(sqlStat.toString());
01196      ResultSet resultSet = statement.executeQuery("SELECT ser_no FROM tests WHERE test_no='"+testno+"'");
01197      String sn = null;
01198      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01199           sn = resultSet.getString(1);
01200           }
01201      statement.close();
01202      return sn;
01203      }
01204 //*************************************************************
01205      public static String getCType(String serno) throws Exception {
01206      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01207 //     System.out.println(sqlStat.toString());
01208      ResultSet resultSet = statement.executeQuery("SELECT ctype FROM items WHERE ser_no='"+serno+"'");
01209      String ctype = null;
01210      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01211           ctype = resultSet.getString(1);
01212           }
01213      statement.close();
01214      return ctype;
01215      }
01216 //**********************************************************
01217     public static List getTestList(int testIndex,String locn, String testMenuName) throws Exception {
01218      java.util.regex.Pattern runPattern = java.util.regex.Pattern.compile("(\\d+)-(\\d+)");
01219      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01220      StringBuffer sqlStat = new StringBuffer("SELECT DISTINCT test_date,locn_name,run_no,tests.test_no FROM tests,sct_tstdaqinfo WHERE locn_name='"+locn+"' AND test_name='"+sctdaqDBTestNames[testIndex]+"'");
01221      sqlStat.append(" AND tests.test_no=sct_tstdaqinfo.test_no AND sct_tstdaqinfo.version LIKE 'SctRodDaq%'");
01222      sqlStat.append(" ORDER BY tests.test_date");
01223 //     System.out.println(sqlStat.toString());
01224      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01225      List itemList = new ArrayList();
01226      SortedMap runMap = new TreeMap();
01227      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01228           List row = new ArrayList();
01229           row.add(guiUtilities.DaveUtils.extractDate(resultSet.getString(1)));
01230           row.add(testMenuName);
01231           row.add(resultSet.getString(2));
01232           String runno = resultSet.getString(3);
01233           java.util.regex.Matcher matcher = runPattern.matcher(runno);
01234           if(!matcher.matches()) {
01235             System.err.println("Unrecognised runno "+runno);
01236             continue;
01237              }
01238           String run = runno.substring(matcher.start(1),matcher.end(1));
01239           String scan = runno.substring(matcher.start(2),matcher.end(2));
01240           int key = Integer.valueOf(run).intValue()*1000000 + Integer.valueOf(scan).intValue();
01241           row.add(runno.substring(matcher.start(1),matcher.end(1)));
01242           row.add(runno.substring(matcher.start(2),matcher.end(2)));
01243           runMap.put(new Integer(key),row);
01244 
01245           }
01246      statement.close();
01247 //     for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01248 //          List row = new ArrayList();
01249 //          row.add(guiUtilities.DaveUtils.extractDate(resultSet.getString(1)));
01250 //          row.add(testMenuName);
01251 //        row.add(resultSet.getString(2));
01252 //          String runno = resultSet.getString(3);
01253 //          java.util.regex.Matcher matcher = runPattern.matcher(runno);
01254 //          if(!matcher.matches()) {
01255 //            System.err.println("Unrecognised runno "+runno);
01256 //            continue;
01257 //             }
01258 //
01259 //          row.add(runno.substring(matcher.start(1),matcher.end(1)));
01260 //          row.add(runno.substring(matcher.start(2),matcher.end(2)));
01261 //          itemList.add(row);
01262 //
01263 //          }
01264      return new ArrayList(runMap.values());
01265      }
01266 
01267 //******************************************************
01268    public static SCTDBTestInfoHolder getTestInfo(String test_no) throws Exception {
01269 
01270       SCTDBTestInfoHolder testInfo= new SCTDBTestInfoHolder();
01271 
01272       StringBuffer genTable = new StringBuffer();
01273       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);
01274       sqlStat.append(" AND items.ser_no=tests.ser_no");
01275 
01276 // submit query
01277      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01278      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01279    
01280      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01281           testInfo.put(SCTDBTestInfoHolder.TEST_NAME,resultSet.getString(1));
01282           testInfo.put(SCTDBTestInfoHolder.SN,resultSet.getString(2));
01283           testInfo.put(SCTDBTestInfoHolder.DATE,guiUtilities.DaveUtils.extractDate(resultSet.getString(3)));
01284           testInfo.put(SCTDBTestInfoHolder.LOCATION,resultSet.getString(4));
01285           testInfo.put(SCTDBTestInfoHolder.CTYPE,resultSet.getString(5));
01286           }
01287      testInfo.put(SCTDBTestInfoHolder.TESTNUMBER,test_no);
01288      statement.close();
01289      if(testInfo.isValid()) return testInfo;
01290      return null;
01291      }
01292 
01293 // **********************************************************************************************
01294     public static Vector getTestHistory(String serialNo) throws Exception {
01295      StringBuffer sqlStat = new StringBuffer("SELECT ");
01296      sqlStat.append("tests.ser_no,tests.locn_name,tests.test_date,tests.test_name,tests.problem,tests.pass");
01297      sqlStat.append(" FROM tests");
01298      sqlStat.append(" WHERE tests.ser_no = "+serialNo);
01299      sqlStat.append(" ORDER BY tests.test_date,tests.test_no");
01300      
01301 
01302       Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01303       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01304       Hashtable serNoHash = new Hashtable();
01305       Hashtable thisHash;
01306       Vector serNoList = new Vector();
01307       Vector theLine = new Vector();
01308       Vector itemList = new Vector();
01309       int recordCount=0;
01310       theLine.addElement("Serial Number");
01311       theLine.addElement("Test Location");
01312       theLine.addElement("Date");
01313       theLine.addElement("Test Name");
01314       theLine.addElement("Test Status");
01315       itemList.addElement(theLine);
01316       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01317           theLine = new Vector();
01318           theLine.addElement(resultSet.getString(1));
01319           theLine.addElement(resultSet.getString(2));
01320           theLine.addElement(guiUtilities.DaveUtils.extractDate(resultSet.getString(3)));
01321           theLine.addElement(resultSet.getString(4));
01322 
01323           String problemFlag = resultSet.getString(5);
01324           String passFlag = resultSet.getString(6);
01325           String statusFlag; 
01326           if(passFlag.equals("YES")) {
01327              statusFlag = (problemFlag.equals("YES")) ? "Problem" : "Pass";
01328              }
01329           else statusFlag="FAIL";
01330           theLine.addElement(statusFlag);
01331           itemList.addElement(theLine);
01332           recordCount++;
01333           if(recordCount%100 ==0) System.out.println("Retrieved "+recordCount+" records ...");
01334             }
01335        System.out.println("Retrieved "+recordCount+" records in total.");
01336 
01337        statement.close();
01338        return itemList;
01339 
01340      }
01341 
01342    public static Vector getShipmentHistory(String serialNo) throws Exception {
01343       Vector theLine = new Vector();
01344       Vector itemList = new Vector();
01345       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 ");
01346       sqlStat.append("WHERE ship_items.ser_no="+serialNo+" AND ship_items.ship_no=ship.ship_no ");
01347       sqlStat.append("ORDER BY ship.ship_date,ship.ship_no"); 
01348  
01349       theLine.addElement("Serial Number");
01350       theLine.addElement("Shipment No");
01351       theLine.addElement("Sent from");
01352       theLine.addElement("Received By");
01353       theLine.addElement("Send Date");
01354       theLine.addElement("Received?");
01355       itemList.addElement(theLine);
01356       Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01357       ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01358       
01359       int recordCount=0;
01360       for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01361           theLine = new Vector();
01362           theLine.addElement(resultSet.getString(1));
01363           theLine.addElement(resultSet.getString(2));
01364           theLine.addElement(resultSet.getString(3));
01365           theLine.addElement(resultSet.getString(4));
01366           theLine.addElement(guiUtilities.DaveUtils.extractDate(resultSet.getString(5)));
01367           theLine.addElement(new Boolean(resultSet.getString(6).equals("YES")));
01368           itemList.addElement(theLine);
01369 
01370           recordCount++;
01371           if(recordCount%100 ==0) System.out.println("Retrieved "+recordCount+" shipment records ...");
01372             }
01373        System.out.println("Retrieved "+recordCount+" shipment records in total.");
01374        statement.close();
01375        return itemList;
01376        }
01377 
01378 
01379     public static List getRodList(String sn) throws Exception {
01380 
01381       StringBuffer sqlStat = new StringBuffer("SELECT ");
01382       sqlStat.append(" tests.test_no,tests.ser_no,tests.locn_name,tests.test_date,sct_tstdcsinfo.t0 FROM tests,test_rawdata,sct_tstdcsinfo");
01383       sqlStat.append(" WHERE tests.ser_no="+sn);
01384       sqlStat.append(" AND ( (tests.test_name = 'HybTWalk' AND tests.locn_name !='Oxford') OR (tests.test_name = 'HybNoise' AND tests.locn_name = 'Oxford'))");
01385 
01386       sqlStat.append(" AND tests.test_no = sct_tstdcsinfo.test_no AND tests.test_no=test_rawdata.test_no");
01387       sqlStat.append(" ORDER BY tests.ser_no,tests.test_date,tests.test_no");
01388 
01389      List itemList = new ArrayList();
01390 
01391      Statement statement = SCTDBInterface.getInstance().connection.createStatement();
01392      ResultSet resultSet = statement.executeQuery(sqlStat.toString());
01393      testNumberList = new Vector();
01394      for(boolean n = resultSet.next() ; n==true ; n=resultSet.next() ){
01395           testNumberList.addElement(resultSet.getString(1));
01396           List thisLine = new ArrayList();
01397           thisLine.add(resultSet.getString(2));  //sn
01398           thisLine.add(resultSet.getString(3)); // location
01399           thisLine.add(guiUtilities.DaveUtils.extractDate(resultSet.getString(4)));
01400           thisLine.add(resultSet.getString(5));
01401           itemList.add(thisLine);
01402          }
01403 
01404       statement.close();
01405 
01406       return itemList;
01407 
01408       }
01409 
01410         
01411      
01412 
01413 
01414 }

Generated on Mon Feb 6 14:12:11 2006 for SCT DAQ/DCS Software - Java by  doxygen 1.4.6