protected void applySecurityToGFE(Connection gConn, String sql) {
   Log.getLogWriter().info("execute authorization statement in GFE");
   Log.getLogWriter().info("security statement is: " + sql);
   try {
     Statement stmt = gConn.createStatement();
     stmt.execute(sql); // execute authorization
   } catch (SQLException se) {
     if (se.getSQLState().equals("42506") && SQLTest.testSecurity)
       Log.getLogWriter()
           .info("Got the expected exception for authorization," + " continuing tests");
     else if (se.getSQLState().equals("42509") && SQLTest.testSecurity)
       Log.getLogWriter()
           .info(
               "Got the expected grant or revoke operation "
                   + "is not allowed exception for authorization,"
                   + " continuing tests");
     else if (se.getSQLState().equals("42Y03") && hasRoutine)
       Log.getLogWriter()
           .info(
               "Got the expected not recognized as "
                   + "a function or procedure exception for authorization,"
                   + " continuing tests");
     else SQLHelper.handleSQLException(se);
   }
 }
  private void putUpdateStoredBlock(StoredBlock storedBlock, boolean wasUndoable)
      throws SQLException {
    try {
      PreparedStatement s =
          conn.get()
              .prepareStatement(
                  "INSERT INTO headers(hash, chainWork, height, header, wasUndoable)"
                      + " VALUES(?, ?, ?, ?, ?)");
      // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
      byte[] hashBytes = new byte[28];
      System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
      s.setBytes(1, hashBytes);
      s.setBytes(2, storedBlock.getChainWork().toByteArray());
      s.setInt(3, storedBlock.getHeight());
      s.setBytes(4, storedBlock.getHeader().unsafeRimbitSerialize());
      s.setBoolean(5, wasUndoable);
      s.executeUpdate();
      s.close();
    } catch (SQLException e) {
      // It is possible we try to add a duplicate StoredBlock if we upgraded
      // In that case, we just update the entry to mark it wasUndoable
      if (!(e.getSQLState().equals(POSTGRES_DUPLICATE_KEY_ERROR_CODE)) || !wasUndoable) throw e;

      PreparedStatement s =
          conn.get().prepareStatement("UPDATE headers SET wasUndoable=? WHERE hash=?");
      s.setBoolean(1, true);
      // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
      byte[] hashBytes = new byte[28];
      System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
      s.setBytes(2, hashBytes);
      s.executeUpdate();
      s.close();
    }
  }
 private boolean AidedIn(SaoWorker w)
 {
   BatSQL bSQL = new BatSQL();
   boolean success = false;
   String id    = w.getUserID();
   String q = "select * from aidedin where USERID='" + id + "'";
   ResultSet rs = bSQL.query(q);
       
   try
   {
     boolean more = rs.next();
     if (more) { success = true; }
   } //end of try
   catch (SQLException ex)
   {
     System.out.println("!*******SQLException caught*******!");
     while (ex != null)
     {
       System.out.println ("SQLState: " + ex.getSQLState ());
       System.out.println ("Message:  " + ex.getMessage ());
       System.out.println ("Vendor:   " + ex.getErrorCode ());
       ex = ex.getNextException ();
       System.out.println ("");
     }
     System.exit(0);
   } //end catching SQLExceptions
   catch (java.lang.Exception ex)
   {
     System.out.println("!*******Exception caught*******!");
     System.exit(0);
   } //end catching other Exceptions
   bSQL.disconnect();
   return success;
 } //end of AidedIn?
  /** Method declaration Adjust this method for large strings...ie multi megabtypes. */
  void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    lTime = System.currentTimeMillis();

    try {
      sStatement.execute(sCmd);

      lTime = System.currentTimeMillis() - lTime;

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }
Exemple #5
0
 public void ramasserObjet() {
   boolean vide = true;
   try {
     ResultSet rset =
         stmt.executeQuery(
             "select idObjet from objet where positionX="
                 + positionX
                 + " and positionY="
                 + positionY);
     Hashtable<String, String> tabObj = new Hashtable<String, String>();
     while (rset.next()) {
       vide = false;
       String idObj = rset.getString("idObjet");
       System.out.println(idObj);
       tabObj.put(idObj, idObj);
     }
     rset.close();
     if (!vide) {
       System.out.println("Quel objet voulez vous ramasser ? : ");
       String obj = IO.lireChaine();
       if (tabObj.containsKey(obj)) {
         proc = conn.prepareCall("{call rammasser(?,?)}");
         proc.setInt(1, idTroll);
         proc.setString(2, obj);
         proc.executeUpdate();
         proc.close();
         rset = stmt.executeQuery("select typeObjet from objet where idObjet='" + obj + "'");
         rset.first();
         String type = rset.getString("typeObjet");
         if (type.equals("potion")) {
           menu.supprimerPopo(obj);
         } else {
           menu.supprimerObjet(obj);
         }
         rset = stmt.executeQuery("select paRestants from troll where idTroll=" + idTroll);
         int ancVal = 0;
         while (rset.next()) {
           ancVal = rset.getInt("paRestants");
         }
         stmt.executeUpdate(
             "update troll SET paRestants = " + (ancVal - 1) + " where idTroll=" + idTroll);
         paRestants = paRestants - 1;
       } else {
         System.out.println("Cet objet ne se trouve pas sur votre case !");
       }
     } else {
       System.out.println("Il n'y a aucun objet sur votre case");
     }
   } catch (SQLException E) {
     System.err.println("SQLException: " + E.getMessage());
     System.err.println("SQLState:     " + E.getSQLState());
   }
 }
Exemple #6
0
  public void tesObjets() {

    try {
      ResultSet rset =
          stmt.executeQuery(
              "select idObjet from equipement where idTroll=" + idTroll + " and estEquipe=false");
      while (rset.next()) {
        String idObj = rset.getString("idObjet");
        System.out.println(idObj);
      }
      rset.close();
      System.out.println();
    } catch (SQLException E) {
      System.err.println("SQLException: " + E.getMessage());
      System.err.println("SQLState:     " + E.getSQLState());
    }
  }
Exemple #7
0
  private static void shutdown() {
    // standard checking code when shutting down database.
    // code from http://db.apache.org/derby/
    if (framework.equals("embedded")) {
      try {
        // the shutdown=true attribute shuts down Derby
        DriverManager.getConnection("jdbc:derby:;shutdown=true");

      } catch (SQLException se) {
        if (((se.getErrorCode() == 50000) && ("XJ015".equals(se.getSQLState())))) {
          System.out.println("Derby shut down normally");
        } else {
          System.err.println("Derby did not shut down normally");
          se.printStackTrace();
        }
      }
    }
  }
Exemple #8
0
  public void utiliserPopo(objet potion) {
    int val = 0;
    int ancVal = 0;
    String carac = null;
    try {
      stmt.executeUpdate(
          "update equipement SET estEquipe = true where idObjet ='"
              + potion.idObjet()
              + "' and idTroll="
              + idTroll);
      ResultSet rset =
          stmt.executeQuery(
              "select caracteristique from carac where idObjet='" + potion.idObjet() + "'");
      while (rset.next()) {
        carac = rset.getString("caracteristique");
      }

      rset =
          conn.createStatement()
              .executeQuery("select valeur from carac where idObjet='" + potion.idObjet() + "'");
      while (rset.next()) {
        val = rset.getInt("valeur");
      }

      rset = stmt.executeQuery("select " + carac + " from troll where idTroll=" + idTroll);
      while (rset.next()) {
        ancVal = rset.getInt(carac);
      }
      stmt.executeUpdate(
          "update troll SET " + carac + " = " + (ancVal + val) + "where idTroll=" + idTroll);
      rset = stmt.executeQuery("select paRestants from troll where idTroll=" + idTroll);
      while (rset.next()) {
        ancVal = rset.getInt("paRestants");
      }
      stmt.executeUpdate(
          "update troll SET paRestants = " + (ancVal - 1) + " where idTroll=" + idTroll);
      tabPopoEnCours.put(potion.idObjet(), potion);
      paRestants = paRestants - 1;
    } catch (SQLException E) {
      System.err.println("SQLException: " + E.getMessage());
      System.err.println("SQLState:     " + E.getSQLState());
    }
  }
Exemple #9
0
 public void reinitialiserTroll() {
   String idObjet;
   try {
     ResultSet rset = stmt.executeQuery("select idObjet from equipement where idTroll=" + idTroll);
     while (rset.next()) {
       idObjet = rset.getString("idObjet");
       this.desequiperObjet(idObjet);
       // int res = stmt.executeUpdate("delete from equipement where idObjet=idObjet");
     }
   } catch (SQLException E) {
     System.err.println("SQLException: " + E.getMessage());
     System.err.println("SQLState:     " + E.getSQLState());
   }
   Enumeration enumPopo = tabPopoEnCours.elements();
   while (enumPopo.hasMoreElements()) {
     objet popo = (objet) enumPopo.nextElement();
     popo.supprimerTourPopo();
     this.verifTourPopo();
   }
 }
  public boolean openConnection() {
    try {

      Class.forName("com.mysql.jdbc.Driver").newInstance();
      // System.out.println(dbstring+"?"+ "user="******"&password="******"?" + "user="******"&password="******"SQLException: " + ex.getMessage());
      System.out.println("SQLState: " + ex.getSQLState());
      System.out.println("VendorError: " + ex.getErrorCode());
      return false;
    } catch (Exception ex) {
      ex.printStackTrace();
      return false;
    }
    return true;
  }
 /**
  *   Finds out if an aide is covering for another aide
  *   and makes an entry to the AIDELOG to note that
  *   coverage has ended.
  *
  *   @param The SaoWorker who might be covering
  */
 public void Covering(final SaoWorker w)
 {
   BatSQL bSQL = new BatSQL();
   String qc = "select * from AIDEDIN where USERID='" + w.getUserID() + "'";
   ResultSet rs = bSQL.query(qc);
   String cid = new String();
   
   try
   {
     rs.next();
     cid = rs.getString(2);
   }
   catch (SQLException ex)
   {
     System.out.println("!*******SQLException caught*******!");
     System.out.println("Covering");
     while (ex != null)
     {
       System.out.println ("SQLState: " + ex.getSQLState ());
       System.out.println ("Message:  " + ex.getMessage ());
       System.out.println ("Vendor:   " + ex.getErrorCode ());
       ex = ex.getNextException ();
       System.out.println ("");
     }
     System.exit(0);
   } //end catching SQLExceptions
   catch (java.lang.Exception ex)
   {
     System.out.println("!*******Exception caught*******!");
     System.out.println("Covering");      
     System.exit(0);
   } //end catching other Exceptions
   
   if (!cid.equals("No")) //then covering
   {
     String uc = "insert into AIDELOG values ('C', '" + cid + "', \"" + bd.getDate() + "\", " + bd.getStringHours() + bd.getStringMinutes() + ", 'O')"; 
     bSQL.update(uc);
   }
   bSQL.disconnect();
     
 } //end of Covering
Exemple #12
0
  public void supprimerPopo(objet popo) {

    String idPopo = popo.idObjet();
    int val = 0;
    int ancVal = 0;
    String carac = null;
    try {
      ResultSet rset =
          stmt.executeQuery("select caracteristique from carac where idObjet='" + idPopo + "'");
      while (rset.next()) {
        carac = rset.getString("caracteristique");
      }

      rset =
          conn.createStatement()
              .executeQuery("select valeur from carac where idObjet='" + idPopo + "'");
      while (rset.next()) {
        val = rset.getInt("valeur");
      }

      rset = stmt.executeQuery("select " + carac + " from troll where idTroll=" + idTroll);
      while (rset.next()) {
        ancVal = rset.getInt(carac);
      }
      stmt.executeUpdate(
          "update troll SET " + carac + " = " + (ancVal - val) + " where idTroll=" + idTroll);
      stmt.executeUpdate("delete from equipement where idObjet='" + idPopo + "'");
      stmt.executeUpdate("delete from carac where idObjet='" + idPopo + "'");
      stmt.executeUpdate("delete from objet where idObjet='" + idPopo + "'");
      tabPopoEnCours.remove(idPopo);
      // menu.supprimerPopo(idPopo);
    } catch (SQLException E) {
      System.err.println("SQLException: " + E.getMessage());
      System.err.println("SQLState:     " + E.getSQLState());
    }
  }
 private void delegateGrantOption(Connection gConn, String tableName) {
   int num = SQLTest.random.nextInt(SQLTest.numOfWorkers) + 1;
   String grantees = getGrantees(num);
   StringBuffer sql = new StringBuffer();
   int whichPriv = SQLTest.random.nextInt(tablePriv.length);
   sql.append(
       "grant " + tablePriv[whichPriv] + " on " + tableName + " to " + grantees + withGrantOption);
   Log.getLogWriter().info("security statement is " + sql.toString());
   try {
     Statement stmt = gConn.createStatement();
     stmt.execute(sql.toString()); // execute authorization
     gConn.commit();
     stmt.close();
   } catch (SQLException se) {
     if (se.getSQLState().equals("42X01")) {
       Log.getLogWriter()
           .info(
               "Got expected exception as WITH GRANT OPTION "
                   + "is not supported yet, continuing test");
     } else {
       SQLHelper.handleSQLException(se);
     }
   }
 }
  /** Method declaration */
  private void refreshTree() {

    tTree.removeAll();

    try {
      int color_table = Color.yellow.getRGB();
      int color_column = Color.orange.getRGB();
      int color_index = Color.red.getRGB();

      tTree.addRow("", dMeta.getURL(), "-", 0);

      String usertables[] = {"TABLE"};
      ResultSet result = dMeta.getTables(null, null, null, usertables);
      Vector tables = new Vector();

      // sqlbob@users Added remarks.
      Vector remarks = new Vector();

      while (result.next()) {
        tables.addElement(result.getString(3));
        remarks.addElement(result.getString(5));
      }

      result.close();

      for (int i = 0; i < tables.size(); i++) {
        String name = (String) tables.elementAt(i);
        String key = "tab-" + name + "-";

        tTree.addRow(key, name, "+", color_table);

        // sqlbob@users Added remarks.
        String remark = (String) remarks.elementAt(i);

        if ((remark != null) && !remark.trim().equals("")) {
          tTree.addRow(key + "r", " " + remark);
        }

        ResultSet col = dMeta.getColumns(null, null, name, null);

        while (col.next()) {
          String c = col.getString(4);
          String k1 = key + "col-" + c + "-";

          tTree.addRow(k1, c, "+", color_column);

          String type = col.getString(6);

          tTree.addRow(k1 + "t", "Type: " + type);

          boolean nullable = col.getInt(11) != DatabaseMetaData.columnNoNulls;

          tTree.addRow(k1 + "n", "Nullable: " + nullable);
        }

        col.close();
        tTree.addRow(key + "ind", "Indices", "+", 0);

        ResultSet ind = dMeta.getIndexInfo(null, null, name, false, false);
        String oldiname = null;

        while (ind.next()) {
          boolean nonunique = ind.getBoolean(4);
          String iname = ind.getString(6);
          String k2 = key + "ind-" + iname + "-";

          if ((oldiname == null || !oldiname.equals(iname))) {
            tTree.addRow(k2, iname, "+", color_index);
            tTree.addRow(k2 + "u", "Unique: " + !nonunique);

            oldiname = iname;
          }

          String c = ind.getString(9);

          tTree.addRow(k2 + "c-" + c + "-", c);
        }

        ind.close();
      }

      tTree.addRow("p", "Properties", "+", 0);
      tTree.addRow("pu", "User: "******"pr", "ReadOnly: " + cConn.isReadOnly());
      tTree.addRow("pa", "AutoCommit: " + cConn.getAutoCommit());
      tTree.addRow("pd", "Driver: " + dMeta.getDriverName());
      tTree.addRow("pp", "Product: " + dMeta.getDatabaseProductName());
      tTree.addRow("pv", "Version: " + dMeta.getDatabaseProductVersion());
    } catch (SQLException e) {
      tTree.addRow("", "Error getting metadata:", "-", 0);
      tTree.addRow("-", e.getMessage());
      tTree.addRow("-", e.getSQLState());
    }

    tTree.update();
  }
Exemple #15
0
  public static void main(
      String args[]) { // String args[] ist ein Feld von Stringreferenzen, die beim Programmaufruf
    // erhalten werden k�nnen (siehe auch:
    // http://www.gailer-net.de/tutorials/java/Notes/chap49B/ch49B_9.html)

    boolean fertig = false; // beendet switch-case Anweisung
    String name = "dbsys34"; // Variablen f�r Name und Passwort
    String passwd = "spion!";
    BufferedReader in =
        new BufferedReader(new InputStreamReader(System.in)); // zum Einlesen von Tastatur n�tig
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    String line = null; // Variable f�r Benutzereingabe
    int wahl = 0; // Variable f�r SwitchCase

    // AUSGABE auf die Konsole
    System.out.println(""); // Leerzeile ausgeben
    System.out.println("--- Dies ist Datenbank-Java-Aufgabe ---");
    System.out.println("");

    // --- DIALOG mit Benutzer ---
    /*		try {
        		System.out.print("Benutzername: ");
        		name = in.readLine();					// Einlesen der Eingabe "Benutzername"
    	System.out.print("Passwort: ");
    	passwd = in.readLine();					// Einlesen der Eingabe "Passwort"
    }
    // --- Abfangen des m�glichen Fehlers ---
    catch (IOException e) {
    	System.out.println("Fehler beim Lesen der Eingabe: " + e);
    	System.exit(-1);
      	}*/

    // --- Block f�r Verbindung mit Datenbank ---
    try {
      DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); // Treiber laden
      String url = "jdbc:oracle:thin:@rzdb01.fh-konstanz.de:1521:o9204"; // String f�r DB-Connection
      // (vgl.Skript)
      conn = DriverManager.getConnection(url, name, passwd); // Verbindung erstellen

      conn.setTransactionIsolation(
          conn.TRANSACTION_SERIALIZABLE); // Transaction Isolations-Level setzen: Serialisierbarkeit
      // als Korrektheitskriterium
      conn.setAutoCommit(false); // Kein automatisches Commit nach jedem SQL statement
      System.out.println("... zur Datenbank verbunden!"); // Ausgabe f�r den Benutzer
      conn.setAutoCommit(true); // Automatisches speichern aktivieren
      stmt = conn.createStatement(); // Statement-Objekt erzeugen

      while (!fertig) {
        System.out.println("\nHallo Benutzer! Was wollen Sie tun?");
        System.out.println("1: Kunde einfuegen");
        System.out.println("2: Kunde suchen");
        System.out.println("3: Ferienwohnung einfuegen");
        System.out.println("4: Ferienwohnung suchen");
        System.out.println("5: Ferienwohnung buchen");
        System.out.println("Zum Beenden bitte \"0\" druecken");

        // Einlesen der Benutzerwahl
        try {
          line = in.readLine();
        }
        // Fehler beim Einlesen
        catch (IOException ioe) {
          System.out.println("Fehler beim Lesen der Eingabe: " + ioe);
          fertig = true;
          continue;
        }
        // Konvertierung in int-Wert
        try {
          wahl = Integer.parseInt(line);
        } catch (NumberFormatException nfe) {
          System.out.println("Falsche Eingabe!");
          continue;
        }
        switch (wahl) {
          case 0:
            fertig = true;
            break;

            // {{{ Kunde einfuegen
          case 1:
            String vorname = null,
                nachname = null,
                plz = null,
                stadt = null,
                strasse = null,
                hsnr = null,
                blz = null,
                kontonr = null,
                landcode = null;

            try {
              System.out.println("Bitte Daten des Kunden eingeben.");
              System.out.print("Vorname: ");
              vorname = in.readLine();
              System.out.print("Nachname: ");
              nachname = in.readLine();
              System.out.print("PLZ (max. 5 Stellen): ");
              plz = in.readLine();
              System.out.print("Stadt: ");
              stadt = in.readLine();
              System.out.print("Strasse: ");
              strasse = in.readLine();
              System.out.print("Hausnr.: ");
              hsnr = in.readLine();
              System.out.print("BLZ: ");
              blz = in.readLine();
              System.out.print("Kontonr.: ");
              kontonr = in.readLine();
              System.out.print("Landkuerzel (de, fr, it, ch): ");
              landcode = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // Daten einfuegen
            stmt.executeUpdate(
                "INSERT INTO kunde "
                    + "VALUES ( (SELECT MAX(kdnr)+1 FROM kunde), '"
                    + vorname
                    + "', "
                    + "         '"
                    + nachname
                    + "', "
                    + "         "
                    + Integer.parseInt(plz)
                    + ", "
                    + "         '"
                    + stadt
                    + "', "
                    + "         '"
                    + strasse
                    + "', "
                    + "         '"
                    + hsnr
                    + "', "
                    + "         "
                    + Integer.parseInt(blz)
                    + ", "
                    + "         "
                    + Integer.parseInt(kontonr)
                    + ", "
                    + "         '"
                    + landcode
                    + "' )");

            System.out.println("Der Kunde wurde erfolgreich eingefuegt!");

            break;
            // }}}

            // {{{ Kunde suchen
          case 2:
            String suchVorname = null, suchNachname = null;

            try {
              System.out.println("Bitte Namen des zu suchenden Kunden eingeben.");
              System.out.print("Vorname: ");
              suchVorname = in.readLine();
              System.out.print("Nachname: ");
              suchNachname = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // ... und Abfrage senden
            String sSql =
                "SELECT * FROM kunde "
                    + "WHERE vorname LIKE '%"
                    + suchVorname
                    + "%' AND "
                    + "nachname LIKE '%"
                    + suchNachname
                    + "%'";
            rset = stmt.executeQuery(sSql);

            System.out.println("[DEBUG] " + sSql);
            System.out.println("Suchergebnisse: ");
            while (rset.next()) {
              System.out.println(
                  rset.getInt("kdnr")
                      + " "
                      + rset.getString("vorname")
                      + " "
                      + rset.getString("nachname")
                      + " "
                      + rset.getInt("zip")
                      + " "
                      + rset.getString("stadt")
                      + " "
                      + rset.getString("strasse")
                      + " "
                      + rset.getString("hsnr")
                      + " "
                      + rset.getInt("blz")
                      + " "
                      + rset.getInt("kontonr")
                      + " "
                      + rset.getString("landcode"));
              /*
                                          System.out.format("5%d 25%s 25%s 5%d 25%s 25%s 4%s 15%d 15%d 2%s",
                                                            rset.getInt("kdnr"),
                                                            rset.getString("vorname"),
                                                            rset.getString("nachname"),
                                                            rset.getInt("zip"),
                                                            rset.getString("stadt"),
                                                            rset.getString("strasse"),
                                                            rset.getString("hsnr"),
                                                            rset.getInt("blz"),
                                                            rset.getInt("kontonr"),
                                                            rset.getString("landcode"));
              */
            }
            break;
            // }}}

            // {{{ Wohnung einfuegen
          case 3:
            String zimmer = null, groesse = null, preis = null, sauna = null, schwbad = null;
            plz = null;
            landcode = null;

            try {
              System.out.println("Bitte Daten der Wohnung eingeben.");
              System.out.print("Anzahl Zimmer: ");
              zimmer = in.readLine();
              System.out.print("Groesse [qm]: ");
              groesse = in.readLine();
              System.out.print("Preis/Tag [EUR]: ");
              preis = in.readLine();
              System.out.print("Landkuerzel (de, fr, it, ch): ");
              landcode = in.readLine();
              System.out.print("Sauna? [0 = nein, 1 = ja]: ");
              sauna = in.readLine();
              System.out.print("Schwimmbad? [0 = nein, 1 = ja]: ");
              sauna = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // Daten einfuegen
            stmt.executeUpdate(
                "INSERT INTO ferienwohnung "
                    + "VALUES ( (SELECT MAX(fwnr)+1 FROM ferienwohnung), "
                    + "         "
                    + Integer.parseInt(zimmer)
                    + ", "
                    + "         "
                    + Integer.parseInt(groesse)
                    + ", "
                    + "         "
                    + Integer.parseInt(plz)
                    + ", "
                    + "         "
                    + Integer.parseInt(preis)
                    + ", "
                    + "         '"
                    + landcode
                    + "', "
                    + "         "
                    + Integer.parseInt(sauna)
                    + ", "
                    + "         "
                    + Integer.parseInt(schwbad)
                    + ")");

            System.out.println("Die Wohnung wurde erfolgreich eingefuegt!");
            break;
            // }}}

            // {{{ Wohnung suchen
          case 4:
            String datumAnreise = null, datumAbreise = null;
            zimmer = null;

            try {
              System.out.println("Bitte Daten der zu suchenden Wohnung eingeben.");
              System.out.print("Landkuerzel (de, fr, it, ch): ");
              landcode = in.readLine();
              System.out.print("Anzahl Zimmer: ");
              zimmer = in.readLine();
              System.out.print("Anreisedatum [YYYY-MM-DD]: ");
              datumAnreise = in.readLine();
              System.out.print("Abreisedatum [YYYY-MM-DD]: ");
              datumAbreise = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // Abfrage senden
            sSql =
                "SELECT f.* FROM ferienwohnung f "
                    + "LEFT OUTER JOIN buchung b "
                    + "ON ( b.fwnr = f.fwnr ) "
                    + "WHERE "
                    + "("
                    + " (     b.von < TO_DATE('"
                    + datumAnreise
                    + "', 'YYYY-MM-DD') "
                    + "   AND b.bis < TO_DATE('"
                    + datumAbreise
                    + "', 'YYYY-MM-DD') ) "
                    + " OR "
                    + " (     b.von > TO_DATE('"
                    + datumAnreise
                    + "', 'YYYY-MM-DD') "
                    + " AND b.bis > TO_DATE('"
                    + datumAbreise
                    + "', 'YYYY-MM-DD') ) "
                    + " OR "
                    + " ( b.bunr IS NULL ) "
                    + ")"
                    + "AND f.anz_zimmer = "
                    + Integer.parseInt(zimmer);
            rset = stmt.executeQuery(sSql);

            System.out.println("[DEBUG] " + sSql);
            System.out.println("Suchergebnisse: ");
            while (rset.next()) {
              System.out.println(
                  rset.getInt("fwnr")
                      + " "
                      + rset.getString("anz_zimmer")
                      + " "
                      + rset.getString("groesse")
                      + " "
                      + rset.getInt("preis")
                      + " "
                      + rset.getString("landcode")
                      + " "
                      + rset.getString("hat_sauna")
                      + " "
                      + rset.getString("hat_schwb"));
            }
            break;
            // }}}

            // {{{ Wohnung buchen
          case 5:
            String kdnr = null, fwnr = null;
            datumAnreise = null;
            datumAbreise = null;

            try {
              System.out.println("Bitte Daten der Buchung eingeben.");
              System.out.print("Kunden-Nr.: ");
              kdnr = in.readLine();
              System.out.print("Ferienwohnung-Nr.: ");
              fwnr = in.readLine();
              System.out.print("Anreisedatum [YYYY-MM-DD]: ");
              datumAnreise = in.readLine();
              System.out.print("Abreisedatum [YYYY-MM-DD]: ");
              datumAbreise = in.readLine();
            } catch (IOException e) {
              System.out.println("Fehler beim Lesen der Eingabe: " + e);
              System.exit(-1);
            }

            // Pruefen, ob Kunde/Fw existent?

            // Daten einfuegen
            stmt.executeUpdate(
                "INSERT INTO buchung "
                    + "VALUES ( (SELECT MAX(bunr)+1 FROM buchung), "
                    + "         SYSDATE, "
                    + "         TO_DATE('"
                    + datumAnreise
                    + "', 'YYYY-MM-DD'), "
                    + "         TO_DATE('"
                    + datumAbreise
                    + "', 'YYYY-MM-DD'), "
                    + "         "
                    + Integer.parseInt(kdnr)
                    + ", "
                    + "         "
                    + Integer.parseInt(fwnr)
                    + " )");

            System.out.println("Die Buchung wurde erfolgreich eingefuegt!");
            break;
            // }}}
        }
      }
      // Verbindung trennen
      stmt.close();
      conn.close();
    } catch (SQLException se) // Fehler abfangen
    {
      System.out.println("");
      System.out.println(
          "SQL Exception occurred while establishing connection to DBS: " + se.getMessage());
      System.out.println("- SQL state  : " + se.getSQLState());
      System.out.println("- Message    : " + se.getMessage());
      System.out.println("- Vendor code: " + se.getErrorCode());
      System.out.println("");
      System.out.println("EXITING WITH FAILURE ... !!!");
      System.out.println("");
      System.exit(-1);
    }
    System.out.println("");
    System.out.println("PROGRAM FINISHED!!!");
  }
  public void addUnspentTransactionOutput(StoredTransactionOutput out) throws BlockStoreException {
    maybeConnect();
    PreparedStatement s = null;

    // Calculate the toAddress (if any)
    String dbAddress = "";
    int type = 0;
    Script outputScript = null;
    try {
      outputScript = new Script(out.getScriptBytes());
    } catch (ScriptException e) {
      // Unparseable, but this isn't an error - it's an output not containing an address
      log.info("Could not parse script for output: " + out.getHash().toString());
    }
    if (outputScript != null
        && (outputScript.isSentToAddress()
            || outputScript.isSentToRawPubKey()
            || outputScript.isPayToScriptHash())) {
      if (outputScript.isSentToAddress()) {
        Address targetAddr = new Address(params, outputScript.getPubKeyHash());
        dbAddress = targetAddr.toString();
        type = 1;
      } else if (outputScript.isSentToRawPubKey()) {
        /*
         *   Note we use the deprecated getFromAddress here.  Coinbase outputs seem to have the target address
         *   in the pubkey of the script - perhaps we can rename this function?
         */

        dbAddress = outputScript.getFromAddress(params).toString();
        type = 2;
      } else if (outputScript.isPayToScriptHash()) {
        dbAddress = Address.fromP2SHHash(params, outputScript.getPubKeyHash()).toString();
        type = 3;
      }
    }

    try {
      s =
          conn.get()
              .prepareStatement(
                  "INSERT INTO openOutputs (hash, index, height, value, scriptBytes, toAddress, addressTargetable) "
                      + "VALUES (?, ?, ?, ?, ?, ?, ?)");
      s.setBytes(1, out.getHash().getBytes());
      // index is actually an unsigned int
      s.setInt(2, (int) out.getIndex());
      s.setInt(3, out.getHeight());
      s.setBytes(4, out.getValue().toByteArray());
      s.setBytes(5, out.getScriptBytes());
      s.setString(6, dbAddress);
      s.setInt(7, type);
      s.executeUpdate();
      s.close();
    } catch (SQLException e) {
      if (!(e.getSQLState().equals(POSTGRES_DUPLICATE_KEY_ERROR_CODE)))
        throw new BlockStoreException(e);
    } finally {
      if (s != null)
        try {
          s.close();
        } catch (SQLException e) {
          throw new BlockStoreException(e);
        }
    }
  }
  public void put(StoredBlock storedBlock, StoredUndoableBlock undoableBlock)
      throws BlockStoreException {
    maybeConnect();
    // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
    byte[] hashBytes = new byte[28];
    System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
    int height = storedBlock.getHeight();
    byte[] transactions = null;
    byte[] txOutChanges = null;
    try {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      if (undoableBlock.getTxOutChanges() != null) {
        undoableBlock.getTxOutChanges().serializeToStream(bos);
        txOutChanges = bos.toByteArray();
      } else {
        int numTxn = undoableBlock.getTransactions().size();
        bos.write((int) (0xFF & (numTxn >> 0)));
        bos.write((int) (0xFF & (numTxn >> 8)));
        bos.write((int) (0xFF & (numTxn >> 16)));
        bos.write((int) (0xFF & (numTxn >> 24)));
        for (Transaction tx : undoableBlock.getTransactions()) tx.rimbitSerialize(bos);
        transactions = bos.toByteArray();
      }
      bos.close();
    } catch (IOException e) {
      throw new BlockStoreException(e);
    }

    try {
      if (log.isDebugEnabled())
        log.debug("Looking for undoable block with hash: " + Utils.bytesToHexString(hashBytes));

      PreparedStatement findS =
          conn.get().prepareStatement("select 1 from undoableBlocks where hash = ?");
      findS.setBytes(1, hashBytes);

      ResultSet rs = findS.executeQuery();
      if (rs.next()) {
        // We already have this output, update it.
        findS.close();

        // Postgres insert-or-updates are very complex (and finnicky).  This level of transaction
        // isolation
        // seems to work for rimbitj
        PreparedStatement s =
            conn.get()
                .prepareStatement(
                    "UPDATE undoableBlocks SET txOutChanges=?, transactions=?" + " WHERE hash = ?");
        s.setBytes(3, hashBytes);

        if (log.isDebugEnabled())
          log.debug("Updating undoable block with hash: " + Utils.bytesToHexString(hashBytes));

        if (transactions == null) {
          s.setBytes(1, txOutChanges);
          s.setNull(2, Types.BINARY);
        } else {
          s.setNull(1, Types.BINARY);
          s.setBytes(2, transactions);
        }
        s.executeUpdate();
        s.close();

        return;
      }

      PreparedStatement s =
          conn.get()
              .prepareStatement(
                  "INSERT INTO undoableBlocks(hash, height, txOutChanges, transactions)"
                      + " VALUES(?, ?, ?, ?)");
      s.setBytes(1, hashBytes);
      s.setInt(2, height);

      if (log.isDebugEnabled())
        log.debug(
            "Inserting undoable block with hash: "
                + Utils.bytesToHexString(hashBytes)
                + " at height "
                + height);

      if (transactions == null) {
        s.setBytes(3, txOutChanges);
        s.setNull(4, Types.BINARY);
      } else {
        s.setNull(3, Types.BINARY);
        s.setBytes(4, transactions);
      }
      s.executeUpdate();
      s.close();
      try {
        putUpdateStoredBlock(storedBlock, true);
      } catch (SQLException e) {
        throw new BlockStoreException(e);
      }
    } catch (SQLException e) {
      if (!e.getSQLState().equals(POSTGRES_DUPLICATE_KEY_ERROR_CODE))
        throw new BlockStoreException(e);
    }
  }
  /**
   *   Handles when aides cover each other. They must tell
   *   us who they're covering so that that poor person
   *   doesn't get a missed shift. This of course means i
   *   have to work on MyHours some more... If they select
   *   a valid userid to cover for makes the appropriate
   *   entry in AIDELOG.
   *
   *   @param An SaoWorker who is covering someone else
   */
  public void WhoRUCovering(final SaoWorker w)
  {
    int i = 0;
    int h = bd.getHours();
    int m = bd.getMinutes();
    if (((m >= 20) && (m < 30)) || ((m >= 50) && (m < 60)))
    {
      if (m < 30) { m = m + 10; }
      else { m = m + 10 - 60; h = h + 1; }      
    }
    int dopp = bd.getDoPP();
    if (dopp > 7) { dopp = dopp - 7; }
    String slotid = bd.getSlot(h, m, dopp);
    String q = "select * from AIDESCHED where " + slotid + "=1";
    final String[] userids = {"", "", "", "", "", "", "", "", "", ""};
    final BatSQL bSQL = new BatSQL();
    ResultSet rs = bSQL.query(q);
    
    try
    {
      boolean more = rs.next();
      if (more) //because there might be only one person for this slot
      {
        while (more)
        {
          userids[i] = rs.getString(1);
          i++;
          more = rs.next();
        }
      } //end of if more
    } //end of try
    catch (SQLException ex)
    {
      System.out.println("!*******SQLException caught*******!");
      System.out.println("WhoRUCovering");
      while (ex != null)
      {
        System.out.println ("SQLState: " + ex.getSQLState ());
        System.out.println ("Message:  " + ex.getMessage ());
        System.out.println ("Vendor:   " + ex.getErrorCode ());
        ex = ex.getNextException ();
        System.out.println ("");
      }
      System.exit(0);
    } //end catching SQLExceptions
    catch (java.lang.Exception ex)
    {
      System.out.println("!*******Exception caught*******!");
      System.out.println("WhoRUCovering");      
      System.exit(0);
    } //end catching other Exceptions
    
    final Frame coverF = new Frame("Covering?");
    final Panel     p  = new Panel();
    final Panel  btnP  = new Panel();
    final List  coverL = new List();
    Button    ok = new Button("Cover");
    Button   nok = new Button("Cancel");
    final int i2 = i;
    
    ok.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
      {
        String id = coverL.getSelectedItem();
        BatSQL bS = new BatSQL();
        String a = "insert into aidelog values ('C', \"" + id + "\", \"" + bd.getDate() + "\", " + bd.getStringHours() + bd.getStringMinutes() + ", 'I')";
        bS.update(a);
        a = "update AIDEDIN set COVERING='" + id + "' where USERID='" + w.getUserID() + "'";
        bS.update(a);
        bS.disconnect();
        coverF.dispose();
      }
    });
    nok.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
      {
        coverF.dispose();
      }
    });
    
    btnP.setLayout(new FlowLayout());
    btnP.add(ok);
    btnP.add(nok);
    
    p.setLayout(new BorderLayout());
    p.add(new Label("Who are you covering for?"), BorderLayout.NORTH);
    int j;
    for (j = 0; j <= i; j++)
    {
      coverL.add(userids[j]);
    }
    p.add(coverL, BorderLayout.CENTER);
    p.add(btnP, BorderLayout.SOUTH);
    
    coverL.select(0);
    
    coverF.setLayout(new FlowLayout());
    coverF.add(p);    
    coverF.pack();
    coverF.setLocation(200, 200);
    coverF.show();

  } //end of WhoRUCovering
Exemple #19
0
  public static void main(String[] args) {

    Statement statement = null;
    Connection conn = null;
    ResultSet rsMin = null;

    PreparedStatement psInsert = null;
    LinkedList<Statement> allStatements = new LinkedList<Statement>();

    try {
      // Instantiate the driver
      Class.forName(JDBC_DRIVER);

    } catch (ClassNotFoundException cnfe) {
      System.out.println(
          "Can't instantiate driver class; check you have drives and classpath configured correctly?");
      cnfe.printStackTrace();
      System.exit(-1); // No driver? Need to fix before anything else will work. So quit the program
    }

    try {

      conn = DriverManager.getConnection(DB_CONNECTION_URL, USER, PASSWORD);
      statement = conn.createStatement();
      allStatements.add(statement);

      System.out.println("Average Weather Database Program");

      // Create a table in the database. Stores today's date, and the min and max temperatures
      // recorded.

      String createTableSQL = "CREATE TABLE temp (day date, mintemp double, maxtemp double)";
      String deleteTableSQL = "DROP TABLE temp";
      try {
        statement.executeUpdate(createTableSQL);
        System.out.println("Created temp table");
      } catch (SQLException sqle) {
        // Seems the table already exists. Delete it and recreate it
        if (sqle.getSQLState()
            .startsWith("42")) { // Error code for table already existing start with XO
          System.out.println("Temp table appears to exist already, delete and recreate");
          statement.executeUpdate(deleteTableSQL);
          statement.executeUpdate(createTableSQL);
        } else {
          // Something else went wrong. If we can't create the table, no point attempting
          // to run the rest of the code. Throw the exception again to be handled at the end of the
          // program.
          System.out.println("Got stuck in catch else " + sqle.getSQLState() + " is sql state");
          throw sqle;
        }
      }

      // Add some test data

      String prepStatInsert = "INSERT INTO temp VALUES ( ?, ?, ? )";

      psInsert = conn.prepareStatement(prepStatInsert);
      allStatements.add(psInsert);

      psInsert.setDate(1, Date.valueOf("2014-04-01"));
      psInsert.setDouble(2, 44.2);
      psInsert.setDouble(3, 58.7);
      psInsert.executeUpdate();

      psInsert.setDate(1, Date.valueOf("2014-04-02"));
      psInsert.setDouble(2, 34.6);
      psInsert.setDouble(3, 55.1);
      psInsert.executeUpdate();

      psInsert.setDate(1, Date.valueOf("2014-04-03"));
      psInsert.setDouble(2, 43.9);
      psInsert.setNull(
          3, Types.DOUBLE); // Forgot to record the max temperature for this date so set it to null.
      psInsert.executeUpdate();

      psInsert.setDate(1, Date.valueOf("2014-04-04"));
      psInsert.setDouble(2, 43.8);
      psInsert.setDouble(3, 47.2);
      psInsert.executeUpdate();

      System.out.println("Added test data to database");

      // Let's calculate the average minimum and average maximum temperature for all the days.
      // Add up all the maximum temperatures and divide by number of days to get average max
      // temperature.
      // Add up all the minimum temperatures and divide by number of days to get average min
      // temperature.

      double averageMaxTemp = 0;
      double averageMinTemp = 0;

      String getAvgsSQL = "SELECT AVG(mintemp) AS rsMin, AVG(maxtemp) AS rsMax FROM temp";
      rsMin = statement.executeQuery(getAvgsSQL);
      while (rsMin.next()) { // there is only one
        averageMinTemp = rsMin.getDouble("rsMin");
        System.out.println("Average min is " + averageMinTemp);
        averageMaxTemp = rsMin.getDouble("rsMax");
        System.out.println("Average max is " + averageMaxTemp);
      }

      System.out.println(
          "Average maximum temperature = "
              + averageMaxTemp
              + " , average minimum temperature = "
              + averageMinTemp);

    } catch (SQLException se) {
      se.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // A finally block runs whether an exception is thrown or not. Close resources and tidy up
      // whether this code worked or not.
      try {
        if (rsMin != null) {
          rsMin.close(); // Close result set
          System.out.println("ResultSet closed");
        }
      } catch (SQLException se) {
        se.printStackTrace();
      }

      // Close all of the statements. Stored a reference to each statement in allStatements so we
      // can loop over all of them and close them all.
      for (Statement s : allStatements) {

        if (s != null) {
          try {
            s.close();
            System.out.println("Statement closed");
          } catch (SQLException se) {
            System.out.println("Error closing statement");
            se.printStackTrace();
          }
        }
      }

      try {
        if (conn != null) {
          conn.close(); // Close connection to database
          System.out.println("Database connection closed");
        }
      } catch (SQLException se) {
        se.printStackTrace();
      }
    }

    System.out.println("End of program");
  }
  /* Clear all existing nodes from the tree model and rebuild from scratch.
   */
  protected void refreshTree() {

    DefaultMutableTreeNode propertiesNode;
    DefaultMutableTreeNode leaf;

    // First clear the existing tree by simply enumerating
    // over the root node's children and removing them one by one.
    while (treeModel.getChildCount(rootNode) > 0) {
      DefaultMutableTreeNode child = (DefaultMutableTreeNode) treeModel.getChild(rootNode, 0);

      treeModel.removeNodeFromParent(child);
      child.removeAllChildren();
      child.removeFromParent();
    }

    treeModel.nodeStructureChanged(rootNode);
    treeModel.reload();
    tScrollPane.repaint();

    // Now rebuild the tree below its root
    try {

      // Start by naming the root node from its URL:
      rootNode.setUserObject(dMeta.getURL());

      // get metadata about user tables by building a vector of table names
      String usertables[] = {"TABLE", "GLOBAL TEMPORARY", "VIEW"};
      ResultSet result = dMeta.getTables(null, null, null, usertables);
      Vector tables = new Vector();

      // sqlbob@users Added remarks.
      Vector remarks = new Vector();

      while (result.next()) {
        tables.addElement(result.getString(3));
        remarks.addElement(result.getString(5));
      }

      result.close();

      // For each table, build a tree node with interesting info
      for (int i = 0; i < tables.size(); i++) {
        String name = (String) tables.elementAt(i);
        DefaultMutableTreeNode tableNode = makeNode(name, rootNode);
        ResultSet col = dMeta.getColumns(null, null, name, null);

        // sqlbob@users Added remarks.
        String remark = (String) remarks.elementAt(i);

        if ((remark != null) && !remark.trim().equals("")) {
          makeNode(remark, tableNode);
        }

        // With a child for each column containing pertinent attributes
        while (col.next()) {
          String c = col.getString(4);
          DefaultMutableTreeNode columnNode = makeNode(c, tableNode);
          String type = col.getString(6);

          makeNode("Type: " + type, columnNode);

          boolean nullable = col.getInt(11) != DatabaseMetaData.columnNoNulls;

          makeNode("Nullable: " + nullable, columnNode);
        }

        col.close();

        DefaultMutableTreeNode indexesNode = makeNode("Indices", tableNode);
        ResultSet ind = dMeta.getIndexInfo(null, null, name, false, false);
        String oldiname = null;

        // A child node to contain each index - and its attributes
        while (ind.next()) {
          DefaultMutableTreeNode indexNode = null;
          boolean nonunique = ind.getBoolean(4);
          String iname = ind.getString(6);

          if ((oldiname == null || !oldiname.equals(iname))) {
            indexNode = makeNode(iname, indexesNode);

            makeNode("Unique: " + !nonunique, indexNode);

            oldiname = iname;
          }

          // And the ordered column list for index components
          makeNode(ind.getString(9), indexNode);
        }

        ind.close();
      }

      // Finally - a little additional metadata on this connection
      propertiesNode = makeNode("Properties", rootNode);

      makeNode("User: "******"ReadOnly: " + cConn.isReadOnly(), propertiesNode);
      makeNode("AutoCommit: " + cConn.getAutoCommit(), propertiesNode);
      makeNode("Driver: " + dMeta.getDriverName(), propertiesNode);
      makeNode("Product: " + dMeta.getDatabaseProductName(), propertiesNode);
      makeNode("Version: " + dMeta.getDatabaseProductVersion(), propertiesNode);
    } catch (SQLException se) {
      propertiesNode = makeNode("Error getting metadata:", rootNode);

      makeNode(se.getMessage(), propertiesNode);
      makeNode(se.getSQLState(), propertiesNode);
    }

    treeModel.nodeStructureChanged(rootNode);
    treeModel.reload();
    tScrollPane.repaint();
  }
Exemple #21
0
  public void deplacer(int tailleEchiquier) {

    boolean coordOk = false;
    System.out.println("Position actuelle : X=" + positionX + " | Y=" + positionY);
    System.out.println("Nouvelle position :");
    while (coordOk == false) {
      if (positionX - 1 < 1) {
        System.out.print("X [1 - " + (positionX + 1) + " ] = ");
      } else if (positionX + 1 > tailleEchiquier) {
        System.out.print("X [" + (positionX - 1) + " - " + (tailleEchiquier) + " ] = ");
      } else {
        System.out.print("X [" + (positionX - 1) + " - " + (positionX + 1) + " ] = ");
      }
      int nouvPositionX = IO.lireEntier();
      if (nouvPositionX < 1) {
        System.out.println("Impossible : coordonnee X < 1 !");
      } else if (nouvPositionX > tailleEchiquier) {
        System.out.println("Impossible : coordonnee X > " + tailleEchiquier + " !");
      } else if (nouvPositionX == positionX + 1
          || nouvPositionX == positionX - 1
          || nouvPositionX == positionX) {
        coordOk = true;
        positionX = nouvPositionX;
      } else {
        System.out.println("Impossible : Le déplacement est limité à 1 case");
      }
    }
    coordOk = false;
    while (coordOk == false) {
      if (positionY - 1 < 1) {
        System.out.print("Y [1 - " + (positionY + 1) + " ] = ");
      } else if (positionY + 1 > tailleEchiquier) {
        System.out.print("Y [" + (positionY - 1) + " - " + (tailleEchiquier) + " ] = ");
      } else {
        System.out.print("Y [" + (positionY - 1) + " - " + (positionY + 1) + " ] = ");
      }
      int nouvPositionY = IO.lireEntier();
      if (nouvPositionY < 1) {
        System.out.println("Impossible : coordonnee Y < 1 !");
      } else if (nouvPositionY > tailleEchiquier) {
        System.out.println("Impossible : coordonnee Y > " + tailleEchiquier + " !");
      } else if (nouvPositionY == positionY + 1
          || nouvPositionY == positionY - 1
          || nouvPositionY == positionY) {
        coordOk = true;
        positionY = nouvPositionY;
      } else {
        System.out.println("Impossible : Le déplacement est limité à 1 case");
      }
    }
    try {
      ResultSet rset =
          stmt.executeQuery(
              "select count (*) from objet where positionX = "
                  + this.positionX
                  + " and positionY="
                  + this.positionY);
      rset.first();
      int nbObjet = rset.getInt(1);
      if (nbObjet > 0) {
        System.out.println();
        System.out.println("Vous marchez sur quelque chose...");
      }
      proc = conn.prepareCall("{? = call deplacer_troll(?,?,?)}");
      proc.registerOutParameter(1, Types.VARCHAR);
      proc.setInt(2, idTroll);
      proc.setInt(3, positionX);
      proc.setInt(4, positionY);
      proc.executeUpdate();
      String mess = proc.getString(1);
      proc.close();

      proc = conn.prepareCall("{? = call pa_restants(?)}");
      proc.registerOutParameter(1, Types.INTEGER);
      proc.setInt(2, idTroll);
      proc.executeUpdate();
      paRestants = proc.getInt(1);
      proc.close();
      if (mess != null) {
        System.out.println(mess);
      }
    } catch (SQLException E) {
      System.err.println("SQLException: " + E.getMessage());
      System.err.println("SQLState:     " + E.getSQLState());
    }
  }
  /**
   * Perform the query on the database, and prepare the array of returned DO objects.
   *
   * @exception DataObjectException If a database access error occurs.
   * @exception NonUniqueQueryException If too many rows were found.
   */
  private void runQuery() throws DataObjectException, NonUniqueQueryException {
    needToRun = false;
    arrayIndex = -1;

    DBQuery dbQuery = null;
    try {
      Vector results;
      /*
         if ( cacheHits.size() > 0 ) {
      // The setQuery methods build up the cacheHits.
      // If the cache had our desired objects,
      // we don't query the database, so we have no ResultSet.
      results = cacheHits;	 // executeQuery saw cache hits
         } else {
      // If the cache doesn't exist, or could not handle the query,
      // then we actually query the database.
      dbQuery = Enhydra.getDatabaseManager().createQuery();
      dbQuery.query( this );    // invokes executeQuery
             results = new Vector();
             while ( resultSet.next() ) {
          results.addElement( new SoftwareCandidateDO ( resultSet ) );
             }
         }
         */
      if (/* partialCache && */ 0 == cacheHits.size()) hitDb = true;
      if (hitDb) {
        dbQuery = Enhydra.getDatabaseManager().createQuery();
        dbQuery.query(this); // invokes executeQuery
        results = new Vector();
        while (resultSet.next()) {
          //		    results.addElement( new SoftwareCandidateDO ( resultSet ) );
          results.addElement(SoftwareCandidateDO.createExisting(resultSet));
        }
      } else {
        results = cacheHits; // executeQuery saw cache hits
      }

      if (results.size() > 1 && uniqueInstance)
        throw new NonUniqueQueryException("Too many rows returned from database");
      DOs = new SoftwareCandidateDO[results.size()];
      for (int i = 0; i < results.size(); i++) {
        DOs[i] = (SoftwareCandidateDO) results.elementAt(i);
      }
      arrayIndex = 0;
    } catch (SQLException se) {
      if (null == se.getSQLState()) {
        throw new DataObjectException("Unknown SQLException", se);
      }
      if (se.getSQLState().startsWith("02") && se.getErrorCode() == 100) {
        throw new DataObjectException("Update or delete DO is out of synch", se);
      } else if (se.getSQLState().equals("S1000") && se.getErrorCode() == -268) {
        throw new DataObjectException("Integrity constraint violation", se);
      } else {
        throw new DataObjectException("Data Object Error", se);
      }
    } catch (ObjectIdException oe) {
      throw new DataObjectException("Object ID Error", oe);
    } catch (DatabaseManagerException de) {
      throw new DataObjectException("Database connection Error", de);
    } finally {
      if (null != dbQuery) dbQuery.release();
    }
  }
Exemple #23
0
  public boolean attaquer() {
    boolean reussite;
    boolean mort = false;
    int idTrollAdverse;
    int positionAdverseX = 0;
    int positionAdverseY = 0;
    if (idTroll == 1) {
      idTrollAdverse = 2;
    } else {
      idTrollAdverse = 1;
    }
    try {
      ResultSet rset =
          stmt.executeQuery(
              "select positionX, positionY from troll where idTroll=" + idTrollAdverse);
      rset.first();
      positionAdverseX = rset.getInt("positionX");
      positionAdverseY = rset.getInt("positionY");
    } catch (SQLException E) {
      System.err.println("SQLException: " + E.getMessage());
      System.err.println("SQLState:     " + E.getSQLState());
    }
    if (positionAdverseX == this.positionX && positionAdverseY == this.positionY) {
      reussite = loi_reussite();
      if (reussite) {
        int scoreAttaque = score_Des(att);
        System.out.println("Jet d'attaque : " + scoreAttaque);
        try {

          proc = conn.prepareCall("{? = call nb_des_esq(?)}");
          proc.registerOutParameter(1, Types.INTEGER);
          proc.setInt(2, idTrollAdverse);
          proc.executeUpdate();
          int esqAdverse = proc.getInt(1);
          proc.close();
          int scoreEsquiveAdversaire = score_Des(esqAdverse);
          System.out.println("Jet d'esquive de l'adversaire : " + scoreEsquiveAdversaire);
          if (scoreEsquiveAdversaire < scoreAttaque) {
            System.out.println("Esquive de l'adversaire ratée... PAF !!");
            int scoreDegats = score_Des(deg);
            System.out.print(
                "L'adversaire perd " + scoreDegats + " pts de vie, il lui en reste donc ");

            proc = conn.prepareCall("{? = call decrementer_vie(?,?)}");
            proc.registerOutParameter(1, Types.BOOLEAN);
            proc.setInt(2, idTrollAdverse);
            proc.setInt(3, scoreDegats);
            proc.executeUpdate();
            mort = proc.getBoolean(1);
            proc.close();

            ResultSet rset =
                stmt.executeQuery("select vie from troll where idTroll =" + idTrollAdverse);
            rset.first();
            System.out.println(rset.getInt("vie"));

            proc = conn.prepareCall("{call init_pa(?,?)}");
            proc.setInt(1, idTroll);
            proc.setInt(2, paRestants - 4);
            proc.executeUpdate();
            proc.close();

            paRestants = paRestants - 4;

          } else if (scoreEsquiveAdversaire == scoreAttaque) {
            System.out.println("Esquive de l'adversaire un peu tardive... PAF !!");
            int scoreDegats = score_Des(deg);
            System.out.println(
                "L'adversaire perd " + (scoreDegats / 2) + " pts de vie, il lui en reste donc ");
            proc = conn.prepareCall("{? = call decrementer_vie(?,?)}");
            proc.registerOutParameter(1, Types.BOOLEAN);
            proc.setInt(2, idTrollAdverse);
            proc.setInt(3, scoreDegats);
            proc.executeUpdate();
            mort = proc.getBoolean(1);
            proc.close();

            ResultSet rset =
                stmt.executeQuery("select vie from troll where idTroll =" + idTrollAdverse);
            rset.first();
            System.out.println(rset.getInt("vie"));

            proc = conn.prepareCall("{call init_pa(?,?)}");
            proc.setInt(1, idTroll);
            proc.setInt(2, paRestants - 4);
            proc.executeUpdate();
            proc.close();

            paRestants = paRestants - 4;
          } else {
            System.out.println(
                "Magnifique esquive de l'adversaire qui ne subira donc aucun dommage");
          }
        } catch (SQLException E) {
          System.err.println("SQLException: " + E.getMessage());
          System.err.println("SQLState:     " + E.getSQLState());
        }
      }
    } else {
      System.out.println("Le troll adverse n'est pas sur votre case !!");
    }
    return (mort);
  }
Exemple #24
0
  // constructeur
  public troll(int numtroll, int tailleEchiquier, Menu menu) {

    try {
      this.menu = menu;
      paRestants = 6;
      System.out.println();
      idTroll = numtroll;
      System.out.print("Nom du troll " + numtroll + ": ");
      nomTroll = IO.lireChaine();
      int points = 40;
      // System.out.println("Vous allez maitenant definir les carac de votre troll (attaque, degats,
      // esquive, vie)");
      boolean ok = false;
      while (ok == false) {
        System.out.println();
        System.out.print(
            "Nombre de D3 d'attaque (Il reste " + points + " a repartir dans 4 carac) : ");
        att = IO.lireEntier();
        if (att > points - 3) {
          System.out.println("Impossible de mettre autant de points dans 1 seule carac !!");
        } else {
          points = points - att;
          ok = true;
        }
      }
      ok = false;
      while (ok == false) {
        System.out.println();
        System.out.print(
            "Nombre de D3 de degats (Il reste " + points + " a repartir dans 3 carac) : ");
        deg = IO.lireEntier();
        if (deg > points - 2) {
          System.out.println("Impossible de mettre autant de points dans 1 seule carac !!");
        } else {
          points = points - deg;
          ok = true;
        }
      }
      ok = false;
      while (ok == false) {
        System.out.println();
        System.out.print(
            "Nombre de D3 d'esquive (Il reste " + points + " a repartir dans 2 carac) : ");
        esq = IO.lireEntier();
        if (esq > points - 1) {
          System.out.println("Impossible de mettre autant de points dans 1 seule carac !!");
        } else {
          points = points - esq;
          ok = true;
        }
      }
      System.out.println();
      System.out.println("Points de vie : " + points + "*" + "10 = " + points * 10);
      vie = points * 10;
      positionX = (int) Math.floor(Math.random() * (tailleEchiquier)) + 1;
      positionY = (int) Math.floor(Math.random() * (tailleEchiquier)) + 1;
      System.out.println("Il apparaitra en X=" + positionX + " Y=" + positionY);
      stmt.executeUpdate("delete from troll where idTroll=" + idTroll);
      proc = conn.prepareCall("{call init_troll(?,?,?,?,?,?,?,?)}");
      proc.setInt(1, numtroll);
      proc.setString(2, nomTroll);
      proc.setInt(3, att);
      proc.setInt(4, deg);
      proc.setInt(5, esq);
      proc.setInt(6, vie);
      proc.setInt(7, positionX);
      proc.setInt(8, positionY);
      proc.executeUpdate();
      proc.close();
    } catch (SQLException E) {
      System.err.println("SQLException: " + E.getMessage());
      System.err.println("SQLState:     " + E.getSQLState());
    }
    valeur = "" + nomTroll.charAt(0);
  }
  /**
   *   Finds out if a SaoWorker is supposed to be working now
   *   or not. It consults the tables AIDESCHED for this, and
   *   if they have a entry in the current slot then they're
   *   okay. Otherwise they're covering for somebody.<P>
   *
   *   Also, if it's 10 minutes before a new slot starts this
   *   looks at the next slot. This is to accomodate for the
   *   fact that sometimes aides will try to Aide In a few
   *   minutes before they're supposed to start working.<P>
   *
   *   What's more, if the SaoWorker trying to AIDE IN is a
   *   Supervisor or Programmer, the method considers them
   *   always scheduled. How convenient!
   *
   *   @param w The Aide trying to aide in
   *   @return True scheduled for this slot, or False not
   */
  public boolean Scheduled(SaoWorker w)
  {
    BatSQL bSQL = new BatSQL();
    String q = "select * from AIDESCHED where USERID='" + w.getUserID() + "'";
    ResultSet rs = bSQL.query(q);
    int h = bd.getHours();
    int m = bd.getMinutes();
    int slot = 0;
    int sched = 0;
    
    //first check if the worker is a Supervisor or Programmer
    //these two Titles are always Scheduled to work.
    if ((w.getTitle().equals("Supervisor")) || (w.getTitle().equals("Programmer")))
    {
      sched = 1;
    }
    else { //aides have to be in the correct slot      

    //this is the part where we check if they're early
    if (((m >= 20) && (m < 30)) || ((m >= 50) && (m < 60)))
    {
      if (m > 30) { h = h + 1; m = m + 10 - 60; }
      else { m = m + 10; }
      int dopp = bd.getDoPP();
      if (dopp > 7) { dopp = dopp - 7; }
      slot = bd.getIntSlot(h, m, dopp);
    }
    else 
    { 
      int dopp = bd.getDoPP();
    	 if (dopp > 7) { dopp = dopp - 7; }
    	 slot = bd.getIntSlot(h, m, dopp);
    }
    //now we carry on as usual

    try
    {
      rs.next();
      sched = rs.getInt(slot+1); //+1 to skip the USERID field!
    } //end of try
    catch (SQLException ex)
    {
      System.out.println("!*******SQLException caught*******!");
      System.out.println("Scheduled");
      while (ex != null)
      {
        System.out.println ("SQLState: " + ex.getSQLState ());
        System.out.println ("Message:  " + ex.getMessage ());
        System.out.println ("Vendor:   " + ex.getErrorCode ());
        ex = ex.getNextException ();
        System.out.println ("");
      }
      System.exit(0);
    } //end catching SQLExceptions
    catch (java.lang.Exception ex)
    {
      System.out.println("!*******Exception caught*******!");
      System.out.println("Scheduled");      
      System.exit(0);
    } //end catching other Exceptions
    
    } //end of else this is an aide
    
    boolean scheded = (sched == 1);
    return scheded;
  } //end of Scheduled?