示例#1
0
文件: GestionBDD.java 项目: nd4pa/tp
 public void listerArticles() {
   Connection con = null;
   Statement st = null;
   ResultSet rs = null;
   try {
     Class.forName(driver).newInstance();
     con = DriverManager.getConnection(url, usr, passwd);
     st = con.createStatement();
     rs = st.executeQuery("SELECT id, nom, quantite FROM articles");
     // remise à 0 de la liste - utile pour les mises à jour
     list.clear();
     // Stocker les enregistrements dans la liste
     while (rs.next()) {
       int id = rs.getInt(1);
       String nom = new String(rs.getString(2));
       int quantite = rs.getInt(3);
       list.add(new ElementBDD(nom, quantite)); // ajout
       System.out.println(nom + "          " + quantite);
     }
   } catch (Exception e) {
     System.err.println("Exception: " + e.getMessage());
   } finally {
     try {
       if (rs != null) rs.close();
       if (st != null) st.close();
       if (con != null) con.close();
     } catch (SQLException e) {
     }
   }
 }
 public void close() throws SQLException {
   Iterator<Connection> it = pool.iterator();
   while (it.hasNext()) {
     Connection conn = it.next();
     conn.close();
   }
   pool.clear();
 }
  public void doDDLOp(Connection dConn, Connection gConn) {
    boolean success = false;
    int maxNumOfTries = 1;
    ArrayList<SQLException> exList = new ArrayList<SQLException>();
    String tableName = tableNames[SQLTest.random.nextInt(tableNames.length)];
    String routineName = (hasRoutine) ? getRoutineNames(dConn, gConn) : null;
    StringBuffer aStr = new StringBuffer();

    // grant or revoke
    String act = action[SQLTest.random.nextInt(action.length)];
    aStr.append(act);

    // rest of the authorization stmt
    if (routineName == null) aStr.append(getAuthForTables(tableName, act));
    else
      aStr.append(
          SQLTest.random.nextBoolean()
              ? getAuthForTables(tableName, act)
              : getAuthForRoutines(routineName, act));

    if (dConn != null) {
      try {
        success = applySecurityToDerby(dConn, aStr.toString(), exList); // insert to derby table
        int count = 0;
        while (!success) {
          if (count >= maxNumOfTries) {
            Log.getLogWriter()
                .info("Could not get the lock to finish grant/revoke stmt, abort this operation");
            return;
          }
          exList.clear();
          success =
              applySecurityToDerby(
                  dConn, aStr.toString(), exList); // retry insert to derby table
          count++;
        }

        applySecurityToGFE(gConn, aStr.toString(), exList); // insert to gfe table
        SQLHelper.handleMissedSQLException(exList);
        gConn.commit();
        dConn.commit();
      } catch (SQLException se) {
        SQLHelper.printSQLException(se);
        throw new TestException("execute security statement fails " + TestHelper.getStackTrace(se));
      } // for verification
    } else {
      try {
        applySecurityToGFE(gConn, aStr.toString()); // insert to gfe table
        gConn.commit();
      } catch (SQLException se) {
        SQLHelper.printSQLException(se);
        throw new TestException("execute security statement fails " + TestHelper.getStackTrace(se));
      }
    } // no verification
  }
  public void assignSelectToMe(Connection dConn, Connection gConn, int tid) {
    boolean success = false;
    int maxNumOfTries = 1;
    ArrayList<SQLException> exList = new ArrayList<SQLException>();

    // for load test
    String sql = "grant select on trade.buyorders to thr_" + tid;

    if (dConn != null) {
      try {
        success = applySecurityToDerby(dConn, sql, exList); // insert to derby table
        int count = 0;
        while (!success) {
          if (count >= maxNumOfTries) {
            Log.getLogWriter()
                .info("Could not get the lock to finish grant/revoke stmt, abort this operation");
            return;
          }
          exList.clear();
          success = applySecurityToDerby(dConn, sql, exList); // retry insert to derby table
          count++;
        }

        applySecurityToGFE(gConn, sql, exList); // insert to gfe table
        SQLHelper.handleMissedSQLException(exList);
        gConn.commit();
        dConn.commit();
      } catch (SQLException se) {
        SQLHelper.printSQLException(se);
        throw new TestException("execute security statement fails " + TestHelper.getStackTrace(se));
      } // for verification
    } else {
      try {
        applySecurityToGFE(gConn, sql); // insert to gfe table
        gConn.commit();
      } catch (SQLException se) {
        SQLHelper.printSQLException(se);
        throw new TestException("execute security statement fails " + TestHelper.getStackTrace(se));
      }
    } // no verification
  }
 /**
  * Parses the files passed into the <CODE>setTemplateFiles</CODE> method. The data extracted from
  * the template files is returned.
  */
 public void parse() {
   setMessage("Parsing Files");
   templates.clear();
   importedFieldCount = 0;
   importedMacroCount = 0;
   File[] templateFiles = getTemplateFiles();
   resetParseCanceled();
   int totalFileSize = 0;
   for (int i = 0; i < templateFiles.length; i++)
     if (templateFiles[i].exists()) totalFileSize += (int) templateFiles[i].length();
   setProgressMaximum(totalFileSize);
   int progress = 0;
   setProgressValue(0);
   setProgressIndeterminate(false);
   for (int i = 0; i < templateFiles.length; i++) {
     String currentFilePath = templateFiles[i].getAbsolutePath();
     Timestamp modifiedDate = new Timestamp(templateFiles[i].lastModified());
     Template currentTemplate = new Template(currentFilePath, modifiedDate);
     String[] nameParts = templateFiles[i].getName().split("\\.");
     if (nameParts != null && nameParts.length > 0) currentTemplate.setID(nameParts[0]);
     templates.add(currentTemplate);
     try {
       BufferedReader iStream = new BufferedReader(new FileReader(templateFiles[i]));
       try {
         String currentLine = iStream.readLine();
         Signal currentSignal = null, archiveTag = null;
         ArchiveRequest request = null;
         ArchiveGroup group = null;
         HashMap archiveSignals = new HashMap();
         int lineNumber = 0;
         int braceCount = 0;
         while (currentLine != null) // null indicates EOF
         {
           lineNumber++;
           if (currentLine.trim().startsWith("#")) // Comments start with #
           {
             // Comments start with #. Archive information is embedded in comments.
             ArchiveGroup newGroup = parseArchiveGroupTag(currentLine, currentTemplate);
             if (newGroup != null) group = newGroup;
             else {
               ArchiveRequest newRequest =
                   parseArchiveRequestTag(currentLine, group, currentTemplate);
               if (newRequest != null) request = newRequest;
               else {
                 Signal newArchiveTag = parseArchiveTag(currentLine);
                 if (newArchiveTag != null) {
                   if (archiveTag != null) // Tag was not used in request. Use for defaults.
                   archiveSignals.put(archiveTag.getID(), archiveTag);
                   archiveTag = newArchiveTag;
                 }
               }
             }
           } else {
             Matcher macroMatcher = macroPattern.matcher(currentLine);
             if (macroMatcher.find()) {
               String macro = macroMatcher.group(1);
               if (!currentTemplate.containsMacro(macro)) {
                 importedMacroCount++;
                 currentTemplate.addMacro(macro);
               }
             }
             int linePosition = 0;
             int lineLength = currentLine.length();
             while (linePosition < lineLength) {
               int openBracePosition = currentLine.indexOf('{', linePosition);
               int closeBracePosition = currentLine.indexOf('}', linePosition);
               if (currentSignal == null || braceCount == 0) {
                 // Got no signal or the brace was never opened...
                 Matcher recordMatcher = recordPattern.matcher(currentLine);
                 if (recordMatcher.find(linePosition))
                   if (openBracePosition < 0 || recordMatcher.start() < openBracePosition) {
                     linePosition = recordMatcher.end();
                     SignalType currentSignalType = new SignalType();
                     String recordType = recordMatcher.group(1);
                     currentSignalType.setRecordType(new EpicsRecordType(recordType));
                     String signalID = recordMatcher.group(2);
                     currentSignal = new Signal(signalID);
                     currentSignal.setType(currentSignalType);
                     if (archiveTag != null)
                       archiveSignals.put(archiveTag.getID(), archiveTag); // Use as defaults.
                     archiveTag = (Signal) archiveSignals.get(signalID);
                     if (archiveTag != null) {
                       currentSignal.setArchiveIndicator("Y");
                       currentSignal.setArchiveType(archiveTag.getArchiveType());
                       currentSignal.setArchiveFrequency(archiveTag.getArchiveFrequency());
                       // Must use a new instance of signal since each request has different
                       // values for type, frequency, etc.
                       if (request != null && request.getSignal(signalID) == null)
                         request.addSignal(new Signal(signalID));
                       currentSignal.setArchiveIndicator("Y");
                       currentSignal.setArchiveType(archiveTag.getArchiveType());
                       currentSignal.setArchiveFrequency(archiveTag.getArchiveFrequency());
                     }
                     currentTemplate.addSignal(currentSignal);
                     archiveTag = null; // Reset so is not used twice.
                     continue; // Go back and check the line position against length.
                   }
               }
               if (braceCount == 0 && currentSignal != null && openBracePosition >= linePosition) {
                 // Got the signal, need the open brace.
                 linePosition = openBracePosition + 1;
                 braceCount++;
                 continue; // Go back and check the line position against length.
               }
               if (braceCount > 0) {
                 // Looking for fields or the close brace.
                 Matcher fieldMatcher = fieldPattern.matcher(currentLine);
                 if (fieldMatcher.find(linePosition))
                   if (closeBracePosition < 0 || fieldMatcher.start() < closeBracePosition) {
                     // Found a field...
                     linePosition = fieldMatcher.end();
                     SignalField currentField = new SignalField();
                     String currentFieldID = fieldMatcher.group(1);
                     currentField.setType(new SignalFieldType(currentFieldID));
                     currentField.setValue(fieldMatcher.group(2));
                     currentSignal.addField(currentField);
                     importedFieldCount++;
                     continue;
                   }
                 if (closeBracePosition >= 0) {
                   // Found end of current signal.
                   braceCount--;
                   linePosition = closeBracePosition + 1;
                   currentSignal = null;
                   continue;
                 }
               }
               linePosition = lineLength;
               if (isParseCanceled()) break;
             }
           }
           progress += currentLine.length() + 1;
           setProgressValue(progress);
           currentLine = iStream.readLine();
           if (isParseCanceled()) break;
         }
       } finally {
         iStream.close();
       }
     } catch (java.io.FileNotFoundException ex) {
       StringBuffer errorMessage = new StringBuffer("<HTML><FONT COLOR=RED>Unable to open file '");
       errorMessage.append(templateFiles[i].getAbsoluteFile());
       errorMessage.append("'.</FONT></HTML>");
       addMessage(errorMessage.toString());
     } catch (java.io.IOException ex) {
       ex.printStackTrace();
       StringBuffer errorMessage = new StringBuffer("<HTML><FONT COLOR=RED>IO Error: ");
       errorMessage.append(ex.getMessage());
       errorMessage.append("</FONT></HTML>");
       addMessage(errorMessage.toString());
     }
     if (isParseCanceled()) break;
   }
 }
 public void clearBatch() throws SQLException {
   if (batch != null) {
     batch.clear();
     batch = null;
   }
 }