示例#1
0
  public ExptLocatorTree(Genome g) {
    super();
    try {
      java.sql.Connection c = DatabaseFactory.getConnection(ExptLocator.dbRole);
      int species = g.getSpeciesDBID();
      int genome = g.getDBID();

      Statement s = c.createStatement();
      ResultSet rs = null;

      rs =
          s.executeQuery(
              "select e.name, e.version from experiment e, exptToGenome eg where e.active=1 and "
                  + "e.id=eg.experiment and eg.genome="
                  + genome);
      while (rs.next()) {
        String name = rs.getString(1);
        String version = rs.getString(2);
        ChipChipLocator loc = new ChipChipLocator(g, name, version);
        this.addElement(loc.getTreeAddr(), loc);
      }
      rs.close();

      rs =
          s.executeQuery(
              "select ra.name, ra.version from rosettaanalysis ra, rosettaToGenome rg where "
                  + "ra.id = rg.analysis and ra.active=1 and rg.genome="
                  + genome);
      while (rs.next()) {
        String name = rs.getString(1);
        String version = rs.getString(2);
        MSPLocator msp = new MSPLocator(g, name, version);
        this.addElement(msp.getTreeAddr(), msp);
      }
      rs.close();

      rs =
          s.executeQuery(
              "select ra.name, ra.version from bayesanalysis ra, bayesToGenome rg where "
                  + "ra.id = rg.analysis and ra.active=1 and rg.genome="
                  + genome);
      while (rs.next()) {
        String name2 = rs.getString(1);
        String version2 = rs.getString(2);
        ExptLocator loc2 = new BayesLocator(g, name2, version2);
        addElement(loc2.getTreeAddr(), loc2);
      }
      rs.close();
      s.close();

      DatabaseFactory.freeConnection(c);
    } catch (SQLException se) {
      se.printStackTrace(System.err);
      throw new RuntimeException(se);
    } catch (UnknownRoleException e) {
      e.printStackTrace();
    }
  }
  public void connectItems(String query)
        // PRE:  query must be initialized
        // POST: Updates the list of Items based on the query.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int rowcount; // Num objects in the resultSet
    int i; // Index for the array

    try { // Try connection to db

      Class.forName(driver).newInstance(); // Create our db driver

      myConnection = DriverManager.getConnection(url, user, pass); // Initalize our connection

      stmt =
          myConnection.createStatement(
              ResultSet.TYPE_SCROLL_INSENSITIVE,
              ResultSet.CONCUR_UPDATABLE); // Create a new statement
      results = stmt.executeQuery(query); // Store the results of our query

      rowcount = 0;
      if (results.last()) // Go to the last result
      {
        rowcount = results.getRow();
        results.beforeFirst();
      }
      itemsArray = new Item[rowcount];

      i = 0;
      while (results.next()) // Itterate through the results set
      {
        itemsArray[i] =
            new Item(
                results.getInt("item_id"),
                results.getString("item_name"),
                results.getString("item_type"),
                results.getInt("price"),
                results.getInt("owner_id"),
                results.getString("item_path")); // Creat new Item
        i++;
      }

      results.close(); // Close the ResultSet
      stmt.close(); // Close the statement
      myConnection.close(); // Close the connection to db

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong in connectItems!");
    }
  }
示例#3
0
  public boolean dbOpenList(Connection connection, String sql) {
    dbClearList();
    this.oldSql = sql;
    this.oldConnection = connection;
    // apre il resultset da abbinare
    ResultSet resu = null;
    ResultSetMetaData meta;
    try {
      stat = connection.createStatement();
      resu = stat.executeQuery(sql);
      meta = resu.getMetaData();

      if (meta.getColumnCount() > 1) {
        this.contieneChiavi = true;
      }

      // righe
      while (resu.next()) {
        for (int i = 1; i <= meta.getColumnCount(); ++i) {
          if (i == 1) {
            dbItems.add((Object) resu.getString(i));
            lm.addElement((Object) resu.getString(i));
          } else if (i == 2) {
            dbItemsK.add((Object) resu.getString(i));

            // debug
            // System.out.println("list:" + String.valueOf(i) + ":" + resu.getString(i));
          } else if (i == 3) {
            dbItemsK2.add((Object) resu.getString(i));
          }
        }
      }
      this.setModel(lm);

      // vado al primo
      if (dbTextAbbinato != null) {
        // debug
        // javax.swing.JOptionPane.showMessageDialog(null,this.getKey(0).toString());
        dbTextAbbinato.setText(this.getKey(0).toString());
      }

      return (true);
    } catch (Exception e) {
      javax.swing.JOptionPane.showMessageDialog(null, e.toString());
      e.printStackTrace();
      return (false);
    } finally {
      try {
        stat.close();
      } catch (Exception e) {
      }
      try {
        resu.close();
      } catch (Exception e) {
      }
      meta = null;
    }
  }
 private void close(ResultSet rs) {
   try {
     if (rs != null) {
       rs.close();
     }
   } catch (SQLException e) {
     LOGGER.error("error during closing:" + e.getMessage(), e);
   }
 }
  private void fullAssociated() {

    boolean associated = true;

    String SQL =
        "Select * "
            + "from XX_VMR_REFERENCEMATRIX "
            + "where M_product IS NULL AND XX_VMR_PO_LINEREFPROV_ID="
            + LineRefProv.get_ID();

    try {
      PreparedStatement pstmt = DB.prepareStatement(SQL, null);
      ResultSet rs = pstmt.executeQuery();

      while (rs.next()) {
        associated = false;
      }

      rs.close();
      pstmt.close();

    } catch (Exception a) {
      log.log(Level.SEVERE, SQL, a);
    }

    if (associated == true) {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='Y'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);

      //			LineRefProv.setXX_ReferenceIsAssociated(true);
      //			LineRefProv.save();

      int dialog = Env.getCtx().getContextAsInt("#Dialog_Associate_Aux");

      if (dialog == 1) {
        ADialog.info(m_WindowNo, m_frame, "MustRefresh");
        Env.getCtx().remove("#Dialog_Associate_Aux");
      }

    } else {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='N'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);
      //			LineRefProv.setXX_ReferenceIsAssociated(false);
      //			LineRefProv.save();
    }
  }
  public void cleanup() {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      conn = getConnection();
      ps = conn.prepareStatement("SELECT COUNT(*) FROM FILES");
      rs = ps.executeQuery();
      dbCount = 0;

      if (rs.next()) {
        dbCount = rs.getInt(1);
      }

      rs.close();
      ps.close();
      PMS.get().getFrame().setStatusLine(Messages.getString("DLNAMediaDatabase.2") + " 0%");
      int i = 0;
      int oldpercent = 0;

      if (dbCount > 0) {
        ps =
            conn.prepareStatement(
                "SELECT FILENAME, MODIFIED, ID FROM FILES",
                ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_UPDATABLE);
        rs = ps.executeQuery();
        while (rs.next()) {
          String filename = rs.getString("FILENAME");
          long modified = rs.getTimestamp("MODIFIED").getTime();
          File file = new File(filename);
          if (!file.exists() || file.lastModified() != modified) {
            rs.deleteRow();
          }
          i++;
          int newpercent = i * 100 / dbCount;
          if (newpercent > oldpercent) {
            PMS.get()
                .getFrame()
                .setStatusLine(Messages.getString("DLNAMediaDatabase.2") + newpercent + "%");
            oldpercent = newpercent;
          }
        }
      }
    } catch (SQLException se) {
      LOGGER.error(null, se);
    } finally {
      close(rs);
      close(ps);
      close(conn);
    }
  }
  public void updateTables(String updateQuery1, String updateQuery2, String updateQuery3)
        // PRE:  updateQuery1,updateQuery2, updateQuery3 must be initialized
        // POST: Updates the list of Items based on the querys.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int i; // Index for the array
    try // Try connection to db
    {

      Class.forName(driver).newInstance(); // Create our db driver

      myConnection = DriverManager.getConnection(url, user, pass); // Initalize our connection

      stmt =
          myConnection.createStatement(
              ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
      stmt.executeUpdate(updateQuery1);

      stmt.executeUpdate(updateQuery2);

      stmt.executeUpdate(updateQuery3);

      results = stmt.executeQuery(previous_query); // Call the previous query

      i = 0;
      while (results.next()) // Itterate through the results set
      {
        itemsArray[i] =
            new Item(
                results.getInt("item_id"),
                results.getString("item_name"),
                results.getString("item_type"),
                results.getInt("price"),
                results.getInt("owner_id"),
                results.getString("item_path"));
        i++;
      }
      results.close(); // Close the ResultSet
      stmt.close(); // Close the statement
      myConnection.close(); // Close the connection to db

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong! in updateTables");
    }
  }
  /**
   * verifica si hay productos asociados
   *
   * @param table table
   */
  private boolean verify() {
    String sql =
        "SELECT XX_VMR_ReferenceMatrix_ID "
            + "FROM XX_VMR_ReferenceMatrix "
            + "WHERE XX_VMR_PO_LINEREFPROV_ID="
            + (Integer) LineRefProv.getXX_VMR_PO_LineRefProv_ID();

    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
      pstmt = DB.prepareStatement(sql, null);
      rs = pstmt.executeQuery();

      while (rs.next()) {
        associatedReference_ID = rs.getInt("XX_VMR_ReferenceMatrix_ID");
        rs.close();
        pstmt.close();
        return true;
      }

    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    } finally {

      try {
        rs.close();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      try {
        pstmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    return false;
  } //  tableLoad
  /**
   * Method declaration
   *
   * @param r
   */
  void formatResultSet(ResultSet r) {

    if (r == null) {
      String g[] = new String[1];

      g[0] = "Result";

      gResult.setHead(g);

      g[0] = "(empty)";

      gResult.addRow(g);

      return;
    }

    try {
      ResultSetMetaData m = r.getMetaData();
      int col = m.getColumnCount();
      String h[] = new String[col];

      for (int i = 1; i <= col; i++) {
        h[i - 1] = m.getColumnLabel(i);
      }

      gResult.setHead(h);

      while (r.next()) {
        for (int i = 1; i <= col; i++) {
          h[i - 1] = r.getString(i);

          if (r.wasNull()) {
            h[i - 1] = "(null)";
          }
        }

        gResult.addRow(h);
      }

      r.close();
    } catch (SQLException e) {
    }
  }
示例#10
0
  private void fill_combo() {
    try {
      String sql = "select distinct townname from towntrends.trends ";
      pst = conn.prepareStatement(sql);
      rs = pst.executeQuery();

      while (rs.next()) {
        String name = rs.getString("townname");
        jComboBox1.addItem(name);
      }
    } catch (Exception ex) {
      JOptionPane.showMessageDialog(null, ex);
    } finally {
      try {
        pst.close();
        rs.close();
      } catch (Exception ex) {

      }
    }
  }
示例#11
0
  public void updateRecord() {
    String totalSeat, alotSeat, vacentSeat, strHostel;
    try {
      rs = statement.executeQuery("select hostelName from hostelStatus");
      while (rs.next()) {
        strHostel = rs.getString(1);

        try {
          rs1 = statement1.executeQuery("select count(*) from " + strHostel + "");
          rs1.next();
          totalSeat = rs1.getString(1);

          rs1 = statement1.executeQuery("select count(*) from " + strHostel + " where status='F'");
          rs1.next();
          alotSeat = rs1.getString(1);

          try {
            vacentSeat = String.valueOf(Integer.parseInt(totalSeat) - Integer.parseInt(alotSeat));
            statement1.executeUpdate(
                "update hostelStatus set totalSeat='"
                    + totalSeat
                    + "',vacentSeat='"
                    + vacentSeat
                    + "'where hostelName='"
                    + strHostel
                    + "'");
            statement1.executeUpdate("commit");
            rs1.close();
          } catch (SQLException sqle) {
            JOptionPane.showMessageDialog(null, sqle);
          }

        } catch (SQLException sqle) {
          JOptionPane.showMessageDialog(null, "Error " + sqle);
        }
      }
    } catch (SQLException sq) {
      JOptionPane.showMessageDialog(null, sq);
    }
  }
示例#12
0
  public void login() {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    String id, pw, sql;
    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url, "hr", "hr");
      stmt = con.createStatement();
      sql = "select * from chatuser where id = '" + lid.getText() + "'";
      rs = stmt.executeQuery(sql);
      if (rs.next()) {
        pw = rs.getString(2);
        nick = rs.getString(3);
        if (lpw.getText().equals(pw)) {
          jd.setVisible(false);
          setVisible(true);
        } else {
          lpw.setText("일치하지 않습니다.");
        }
      } else {
        lid.setText("일치하지 않습니다.");
      }
    } catch (Exception e1) {
      e1.printStackTrace();
      System.out.println("데이터 베이스 연결 실패!!");
    } finally {
      try {
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (con != null) con.close();
      } catch (Exception e1) {
        System.out.println(e1.getMessage());
      }
    }
  }
  private boolean isInMatrix() {

    String SQL =
        "Select * "
            + "from XX_VMR_REFERENCEMATRIX "
            + "where XX_VMR_PO_LINEREFPROV_ID="
            + LineRefProv.get_ID();

    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
      pstmt = DB.prepareStatement(SQL, null);
      rs = pstmt.executeQuery();

      while (rs.next()) {
        return true;
      }

    } catch (Exception a) {
      log.log(Level.SEVERE, SQL, a);
    } finally {

      try {
        rs.close();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      try {
        pstmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    return false;
  }
  public void init(boolean force) {
    dbCount = -1;
    String version = null;
    Connection conn = null;
    ResultSet rs = null;
    Statement stmt = null;

    try {
      conn = getConnection();
    } catch (SQLException se) {
      final File dbFile = new File(dbDir + File.separator + dbName + ".data.db");
      final File dbDirectory = new File(dbDir);
      if (dbFile.exists()
          || (se.getErrorCode() == 90048)) { // Cache is corrupt or wrong version, so delete it
        FileUtils.deleteQuietly(dbDirectory);
        if (!dbDirectory.exists()) {
          LOGGER.debug(
              "The cache has been deleted because it was corrupt or had the wrong version");
        } else {
          if (!PMS.isHeadless()) {
            JOptionPane.showMessageDialog(
                (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
                String.format(Messages.getString("DLNAMediaDatabase.5"), dbDir),
                Messages.getString("Dialog.Error"),
                JOptionPane.ERROR_MESSAGE);
          }
          LOGGER.debug(
              "Damaged cache can't be deleted. Stop the program and delete the folder \""
                  + dbDir
                  + "\" manually");
          configuration.setUseCache(false);
          return;
        }
      } else {
        LOGGER.debug("Cache connection error: " + se.getMessage());
        configuration.setUseCache(false);
        return;
      }
    }

    try {
      conn = getConnection();

      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT count(*) FROM FILES");
      if (rs.next()) {
        dbCount = rs.getInt(1);
      }
      rs.close();
      stmt.close();

      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT VALUE FROM METADATA WHERE KEY = 'VERSION'");
      if (rs.next()) {
        version = rs.getString(1);
      }
    } catch (SQLException se) {
      if (se.getErrorCode()
          != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in
        // following step
        LOGGER.error(null, se);
      }
    } finally {
      close(rs);
      close(stmt);
      close(conn);
    }
    boolean force_reinit =
        !PMS.getVersion().equals(version); // here we can force a deletion for a specific version
    if (force || dbCount == -1 || force_reinit) {
      LOGGER.debug("Database will be (re)initialized");
      try {
        conn = getConnection();
        executeUpdate(conn, "DROP TABLE FILES");
        executeUpdate(conn, "DROP TABLE METADATA");
        executeUpdate(conn, "DROP TABLE REGEXP_RULES");
        executeUpdate(conn, "DROP TABLE AUDIOTRACKS");
        executeUpdate(conn, "DROP TABLE SUBTRACKS");
      } catch (SQLException se) {
        if (se.getErrorCode()
            != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in
          // following step
          LOGGER.error(null, se);
        }
      }
      try {
        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLE FILES (");
        sb.append("  ID                INT AUTO_INCREMENT");
        sb.append(", FILENAME          VARCHAR2(1024)       NOT NULL");
        sb.append(", MODIFIED          TIMESTAMP            NOT NULL");
        sb.append(", TYPE              INT");
        sb.append(", DURATION          DOUBLE");
        sb.append(", BITRATE           INT");
        sb.append(", WIDTH             INT");
        sb.append(", HEIGHT            INT");
        sb.append(", SIZE              NUMERIC");
        sb.append(", CODECV            VARCHAR2(").append(SIZE_CODECV).append(")");
        sb.append(", FRAMERATE         VARCHAR2(").append(SIZE_FRAMERATE).append(")");
        sb.append(", ASPECT            VARCHAR2(").append(SIZE_ASPECT).append(")");
        sb.append(", ASPECTRATIOCONTAINER    VARCHAR2(")
            .append(SIZE_ASPECTRATIO_CONTAINER)
            .append(")");
        sb.append(", ASPECTRATIOVIDEOTRACK   VARCHAR2(")
            .append(SIZE_ASPECTRATIO_VIDEOTRACK)
            .append(")");
        sb.append(", REFRAMES          TINYINT");
        sb.append(", AVCLEVEL          VARCHAR2(").append(SIZE_AVC_LEVEL).append(")");
        sb.append(", BITSPERPIXEL      INT");
        sb.append(", THUMB             BINARY");
        sb.append(", CONTAINER         VARCHAR2(").append(SIZE_CONTAINER).append(")");
        sb.append(", MODEL             VARCHAR2(").append(SIZE_MODEL).append(")");
        sb.append(", EXPOSURE          INT");
        sb.append(", ORIENTATION       INT");
        sb.append(", ISO               INT");
        sb.append(", MUXINGMODE        VARCHAR2(").append(SIZE_MUXINGMODE).append(")");
        sb.append(", FRAMERATEMODE     VARCHAR2(").append(SIZE_FRAMERATE_MODE).append(")");
        sb.append(", constraint PK1 primary key (FILENAME, MODIFIED, ID))");
        executeUpdate(conn, sb.toString());
        sb = new StringBuilder();
        sb.append("CREATE TABLE AUDIOTRACKS (");
        sb.append("  FILEID            INT              NOT NULL");
        sb.append(", ID                INT              NOT NULL");
        sb.append(", LANG              VARCHAR2(").append(SIZE_LANG).append(")");
        sb.append(", FLAVOR            VARCHAR2(").append(SIZE_FLAVOR).append(")");
        sb.append(", NRAUDIOCHANNELS   NUMERIC");
        sb.append(", SAMPLEFREQ        VARCHAR2(").append(SIZE_SAMPLEFREQ).append(")");
        sb.append(", CODECA            VARCHAR2(").append(SIZE_CODECA).append(")");
        sb.append(", BITSPERSAMPLE     INT");
        sb.append(", ALBUM             VARCHAR2(").append(SIZE_ALBUM).append(")");
        sb.append(", ARTIST            VARCHAR2(").append(SIZE_ARTIST).append(")");
        sb.append(", SONGNAME          VARCHAR2(").append(SIZE_SONGNAME).append(")");
        sb.append(", GENRE             VARCHAR2(").append(SIZE_GENRE).append(")");
        sb.append(", YEAR              INT");
        sb.append(", TRACK             INT");
        sb.append(", DELAY             INT");
        sb.append(", MUXINGMODE        VARCHAR2(").append(SIZE_MUXINGMODE).append(")");
        sb.append(", BITRATE           INT");
        sb.append(", constraint PKAUDIO primary key (FILEID, ID))");
        executeUpdate(conn, sb.toString());
        sb = new StringBuilder();
        sb.append("CREATE TABLE SUBTRACKS (");
        sb.append("  FILEID            INT              NOT NULL");
        sb.append(", ID                INT              NOT NULL");
        sb.append(", LANG              VARCHAR2(").append(SIZE_LANG).append(")");
        sb.append(", FLAVOR            VARCHAR2(").append(SIZE_FLAVOR).append(")");
        sb.append(", TYPE              INT");
        sb.append(", constraint PKSUB primary key (FILEID, ID))");

        executeUpdate(conn, sb.toString());
        executeUpdate(
            conn,
            "CREATE TABLE METADATA (KEY VARCHAR2(255) NOT NULL, VALUE VARCHAR2(255) NOT NULL)");
        executeUpdate(conn, "INSERT INTO METADATA VALUES ('VERSION', '" + PMS.getVersion() + "')");
        executeUpdate(conn, "CREATE INDEX IDXARTIST on AUDIOTRACKS (ARTIST asc);");
        executeUpdate(conn, "CREATE INDEX IDXALBUM on AUDIOTRACKS (ALBUM asc);");
        executeUpdate(conn, "CREATE INDEX IDXGENRE on AUDIOTRACKS (GENRE asc);");
        executeUpdate(conn, "CREATE INDEX IDXYEAR on AUDIOTRACKS (YEAR asc);");
        executeUpdate(
            conn,
            "CREATE TABLE REGEXP_RULES ( ID VARCHAR2(255) PRIMARY KEY, RULE VARCHAR2(255), ORDR NUMERIC);");
        executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '###', '(?i)^\\W.+', 0 );");
        executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '0-9', '(?i)^\\d.+', 1 );");

        // Retrieve the alphabet property value and split it
        String[] chars = Messages.getString("DLNAMediaDatabase.1").split(",");

        for (int i = 0; i < chars.length; i++) {
          // Create regexp rules for characters with a sort order based on the property value
          executeUpdate(
              conn,
              "INSERT INTO REGEXP_RULES VALUES ( '"
                  + chars[i]
                  + "', '(?i)^"
                  + chars[i]
                  + ".+', "
                  + (i + 2)
                  + " );");
        }

        LOGGER.debug("Database initialized");
      } catch (SQLException se) {
        LOGGER.info("Error in table creation: " + se.getMessage());
      } finally {
        close(conn);
      }
    } else {
      LOGGER.debug("Database file count: " + dbCount);
      LOGGER.debug("Database version: " + version);
    }
  }
  /** 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();
  }
  /** Process Button Pressed - Process Matching */
  private void cmd_newProduct() {
    // Selecciono el departamento
    int depart = 0;
    String SQL =
        "Select XX_VMR_DEPARTMENT_ID "
            + "from XX_VMR_VENDORPRODREF "
            + "where XX_VMR_VENDORPRODREF_ID="
            + LineRefProv.getXX_VMR_VendorProdRef_ID();

    try {
      PreparedStatement pstmt = DB.prepareStatement(SQL, null);
      ResultSet rs = pstmt.executeQuery();

      while (rs.next()) {
        depart = rs.getInt("XX_VMR_DEPARTMENT_ID");
      }

      rs.close();
      pstmt.close();

    } catch (Exception a) {
      log.log(Level.SEVERE, SQL, a);
    }

    MVMRVendorProdRef vendorProdRef =
        new MVMRVendorProdRef(Env.getCtx(), LineRefProv.getXX_VMR_VendorProdRef_ID(), null);

    if (vendorProdRef.getXX_VMR_ProductClass_ID() > 0
        && vendorProdRef.getXX_VMR_TypeLabel_ID() > 0) {
      MOrder order = new MOrder(Env.getCtx(), LineRefProv.getC_Order_ID(), null);

      // Selecciono el departamento
      X_XX_VMR_Department dept =
          new X_XX_VMR_Department(Env.getCtx(), vendorProdRef.getXX_VMR_Department_ID(), null);
      int category = dept.getXX_VMR_Category_ID();

      // Selecciono la línea
      X_XX_VMR_Line line = new X_XX_VMR_Line(Env.getCtx(), vendorProdRef.getXX_VMR_Line_ID(), null);
      int typeInventory = line.getXX_VMR_TypeInventory_ID();

      MProduct newProduct =
          new MProduct(
              Env.getCtx(),
              vendorProdRef.getXX_VMR_Department_ID(),
              vendorProdRef.getXX_VMR_Line_ID(),
              vendorProdRef.getXX_VMR_Section_ID(),
              vendorProdRef.get_ID(),
              vendorProdRef.getC_TaxCategory_ID(),
              vendorProdRef.getXX_VME_ConceptValue_ID(),
              typeInventory,
              null);

      // Se buscará si por la referencia para producto ya existe para asignarle el Tipo de
      // Exhibición
      String sql =
          "select * from M_Product where XX_VMR_DEPARTMENT_ID = "
              + vendorProdRef.getXX_VMR_Department_ID()
              + " and "
              + "XX_VMR_LINE_ID = "
              + vendorProdRef.getXX_VMR_Line_ID()
              + " and XX_VMR_SECTION_ID = "
              + vendorProdRef.getXX_VMR_Section_ID()
              + " and "
              + "XX_VMR_VendorProdRef_id = "
              + vendorProdRef.getXX_VMR_VendorProdRef_ID()
              + " order by M_Product_ID desc";
      PreparedStatement pstmt = DB.prepareStatement(sql, null);
      ResultSet rs = null;
      try {
        rs = pstmt.executeQuery();
        if (rs.next())
          newProduct.setXX_VMR_TypeExhibition_ID(rs.getInt("XX_VMR_TypeExhibition_ID"));
      } catch (SQLException e) {

        e.printStackTrace();
      } finally {
        DB.closeResultSet(rs);
        DB.closeStatement(pstmt);
      }

      if (vendorProdRef.getXX_VMR_Section_ID() > 0) {
        X_XX_VMR_Section section =
            new X_XX_VMR_Section(Env.getCtx(), vendorProdRef.getXX_VMR_Section_ID(), null);
        newProduct.setName(section.getName());
      } else {
        newProduct.setName(vendorProdRef.getName());
      }
      newProduct.setXX_VMR_Category_ID(category);
      newProduct.setXX_VMR_LongCharacteristic_ID(vendorProdRef.getXX_VMR_LongCharacteristic_ID());
      newProduct.setXX_VMR_Brand_ID(vendorProdRef.getXX_VMR_Brand_ID());
      newProduct.setXX_VMR_UnitConversion_ID(vendorProdRef.getXX_VMR_UnitConversion_ID());
      newProduct.setXX_PiecesBySale_ID(vendorProdRef.getXX_PiecesBySale_ID());
      newProduct.setXX_VMR_UnitPurchase_ID(vendorProdRef.getXX_VMR_UnitPurchase_ID());
      newProduct.setXX_SaleUnit_ID(vendorProdRef.getXX_SaleUnit_ID());
      newProduct.setC_Country_ID(order.getC_Country_ID());
      newProduct.setIsActive(true);
      newProduct.setC_BPartner_ID(vendorProdRef.getC_BPartner_ID());
      newProduct.setXX_VMR_TypeLabel_ID(vendorProdRef.getXX_VMR_TypeLabel_ID());
      newProduct.setXX_VMR_ProductClass_ID(vendorProdRef.getXX_VMR_ProductClass_ID());
      newProduct.setM_AttributeSet_ID(Env.getCtx().getContextAsInt("#XX_L_P_ATTRIBUTESETST_ID"));
      newProduct.setProductType(X_Ref_M_Product_ProductType.ITEM.getValue());
      newProduct.save();

    } else {
      // Creo variables de sesion para atraparlas en la ventana producto
      Env.getCtx().setContext("#Depart_Aux", depart);
      Env.getCtx().setContext("#Section_Aux", LineRefProv.getXX_VMR_Section_ID());
      Env.getCtx().setContext("#Line_Aux", LineRefProv.getXX_VMR_Line_ID());
      Env.getCtx().setContext("#VendorRef_Aux", LineRefProv.getXX_VMR_VendorProdRef_ID());
      Env.getCtx().setContext("#FromProcess_Aux", "Y");

      AWindow window_product = new AWindow();
      Query query = Query.getNoRecordQuery("M_Product", true);
      window_product.initWindow(140, query);
      AEnv.showCenterScreen(window_product);

      // Obtenemos el GridController para setear la variable m_changed=true
      JRootPane jRootPane = ((JRootPane) window_product.getComponent(0));
      JLayeredPane jLayeredPane = (JLayeredPane) jRootPane.getComponent(1);
      JPanel jPanel = (JPanel) jLayeredPane.getComponent(0);
      APanel aPanel = (APanel) jPanel.getComponent(0);
      VTabbedPane vTabbedPane = (VTabbedPane) aPanel.getComponent(0);
      GridController gridController = (GridController) vTabbedPane.getComponent(0);
      GridTable mTable = gridController.getMTab().getTableModel();
      mTable.setChanged(true);

      MProduct.loadLineRefProv(LineRefProv, Env.getCtx());

      // Borro las variables de sesion creadas
      Env.getCtx().remove("#Depart_Aux");
      Env.getCtx().remove("#FromProcess_Aux");
      Env.getCtx().remove("#Line_Aux");
      Env.getCtx().remove("#Section_Aux");
      Env.getCtx().remove("#VendorRef_Aux");
    }
  } //  cmd_newProduct
  /** Dispose */
  public void dispose() {
    if (m_frame != null) m_frame.dispose();
    m_frame = null;

    MOrder order = new MOrder(Env.getCtx(), LineRefProv.getC_Order_ID(), null);
    String oS = order.getXX_OrderStatus();
    String compS = order.getDocStatus();
    if (!oS.equals("AN") && !compS.equals("CO")) {

      if (isInMatrix()) {

        fullAssociated();

      } else {
        String SQL10 =
            "UPDATE XX_VMR_PO_LineRefProv "
                + " SET XX_ReferenceIsAssociated='N'"
                + " WHERE XX_VMR_PO_LineRefProv_ID="
                + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

        DB.executeUpdate(null, SQL10);
        //				LineRefProv.setXX_ReferenceIsAssociated(false);
        //				LineRefProv.save();
      }
    }

    // pelle

    String SQL =
        ("SELECT A.XX_REFERENCEISASSOCIATED AS ASOCIATE "
            + "FROM XX_VMR_PO_LINEREFPROV A , C_ORDER B "
            + "WHERE A.C_ORDER_ID = B.C_ORDER_ID "
            + "AND A.C_ORDER_ID = '"
            + LineRefProv.getC_Order_ID()
            + "' ");

    try {

      PreparedStatement pstmt = DB.prepareStatement(SQL, null);
      ResultSet rs = pstmt.executeQuery();

      BigDecimal cifTotal = new BigDecimal(0);
      Boolean check = true;
      Integer maritimo = 0;
      Integer aereo = 0;
      Integer terrestre = 0;
      BigDecimal montoBs = new BigDecimal(0);
      BigDecimal rate = new BigDecimal(0);
      BigDecimal Seguro = new BigDecimal(0);
      BigDecimal perfleteInt = new BigDecimal(0);
      BigDecimal fleteInternac = new BigDecimal(0);

      Integer productid = 0;
      Integer poline = 0;
      BigDecimal costoitem = new BigDecimal(0);
      BigDecimal porcentitem = new BigDecimal(0);
      BigDecimal cifuni = new BigDecimal(0);
      BigDecimal percentarancel = new BigDecimal(0);
      BigDecimal arancelitem = new BigDecimal(0);
      BigDecimal rateseniat = new BigDecimal(0);
      BigDecimal montoseniat = new BigDecimal(0);
      BigDecimal ratetesoreria = new BigDecimal(0);
      BigDecimal montotesoreria = new BigDecimal(0);
      BigDecimal tasaaduana = new BigDecimal(0);
      BigDecimal part1 = new BigDecimal(0);
      BigDecimal part2 = new BigDecimal(0);
      BigDecimal iva = new BigDecimal(0);
      BigDecimal ivaactual = new BigDecimal(0);
      BigDecimal part = new BigDecimal(0);
      BigDecimal montesorerianac = new BigDecimal(0);

      while (rs.next()) {
        if (rs.getString("ASOCIATE").trim().equalsIgnoreCase("N")) {
          check = false;
        }
      }
      rs.close();
      pstmt.close();
      if (check == true) {

        String SQL2 =
            ("SELECT (A.TOTALLINES * B.MULTIPLYRATE) + A.XX_INTNACESTMEDAMOUNT + A.XX_ESTEEMEDINSURANCEAMOUNT  AS CIFTOTAL "
                + "FROM C_ORDER A, C_CONVERSION_RATE B "
                + "WHERE B.C_CONVERSION_RATE_ID = A.XX_CONVERSIONRATE_ID "
                + "AND A.C_ORDER_ID = '"
                + LineRefProv.getC_Order_ID()
                + "' "
                + "AND A.AD_Client_ID IN(0,"
                + Env.getCtx().getAD_Client_ID()
                + ") "
                + "AND B.AD_Client_ID IN(0,"
                + Env.getCtx().getAD_Client_ID()
                + ")");

        PreparedStatement pstmt2 = DB.prepareStatement(SQL2, null);
        ResultSet rs2 = pstmt2.executeQuery();

        if (rs2.next()) {
          // Calculo del CIF Total

          cifTotal = rs2.getBigDecimal("CIFTOTAL");
        }
        rs2.close();
        pstmt2.close();

        // Busco la via de despacho de la O/C
        String SQL3 =
            ("SELECT XX_L_DISPATCHROUTE AS AEREO, XX_L_DISPATCHROUTEMAR AS MARITIMO, XX_L_DISPATCHROUTETER AS TERRESTRE "
                + "FROM XX_VSI_KEYNAMEINFO ");

        PreparedStatement pstmt3 = DB.prepareStatement(SQL3, null);
        ResultSet rs3 = pstmt3.executeQuery();

        if (rs3.next()) {
          maritimo = rs3.getInt("MARITIMO");
          terrestre = rs3.getInt("TERRESTRE");
          aereo = rs3.getInt("AEREO");
        }
        rs3.close();
        pstmt3.close();

        String SQL4 =
            ("SELECT (A.TOTALLINES * B.MULTIPLYRATE) AS MONTO "
                + "FROM C_ORDER A, C_CONVERSION_RATE B "
                + "WHERE B.C_CONVERSION_RATE_ID = A.XX_CONVERSIONRATE_ID "
                + "AND A.C_ORDER_ID = '"
                + LineRefProv.getC_Order_ID()
                + "' ");

        PreparedStatement pstmt4 = DB.prepareStatement(SQL4, null);
        ResultSet rs4 = pstmt4.executeQuery();

        if (rs4.next()) {
          // Monto de la O/C en Bs
          montoBs = rs4.getBigDecimal("MONTO");
        }
        rs4.close();
        pstmt4.close();

        if (order.getXX_VLO_DispatchRoute_ID() == maritimo) {

          String SQL5 =
              ("SELECT XX_RATE AS RATE "
                  + "FROM XX_VLO_DispatchRoute "
                  + "WHERE XX_VLO_DispatchRoute_ID = '"
                  + maritimo
                  + "' ");

          PreparedStatement pstmt5 = DB.prepareStatement(SQL5, null);
          ResultSet rs5 = pstmt5.executeQuery();

          if (rs5.next()) {
            rate = rs5.getBigDecimal("RATE").divide(new BigDecimal(100));
            // (new BigDecimal(100), 2, RoundingMode.HALF_UP);

            // Calculo del Seguro con Via Maritimo
            Seguro = montoBs.multiply(rate);
          }
          rs5.close();
          pstmt5.close();

        } else if (order.getXX_VLO_DispatchRoute_ID() == aereo) {
          String SQL5 =
              ("SELECT XX_RATE AS RATE "
                  + "FROM XX_VLO_DispatchRoute "
                  + "WHERE XX_VLO_DispatchRoute_ID = '"
                  + aereo
                  + "' ");

          PreparedStatement pstmt5 = DB.prepareStatement(SQL5, null);
          ResultSet rs5 = pstmt5.executeQuery();

          if (rs5.next()) {
            rate = rs5.getBigDecimal("RATE").divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);

            // Calculo del Seguro con Via aereo
            Seguro = montoBs.multiply(rate);
          }
          rs5.close();
          pstmt5.close();
        } else if (order.getXX_VLO_DispatchRoute_ID() == terrestre) {
          String SQL5 =
              ("SELECT XX_RATE AS RATE "
                  + "FROM XX_VLO_DispatchRoute "
                  + "WHERE XX_VLO_DispatchRoute_ID = '"
                  + terrestre
                  + "' ");

          PreparedStatement pstmt5 = DB.prepareStatement(SQL5, null);
          ResultSet rs5 = pstmt5.executeQuery();

          if (rs5.next()) {
            rate = rs5.getBigDecimal("RATE").divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);

            // Calculo del Seguro con Via terrestre
            Seguro = montoBs.multiply(rate);
          }
          rs5.close();
          pstmt5.close();
        }

        // Busco el porcentaje del flete internacional segun el proveedor, puerto y pais de la O/C

        String SQL6 =
            ("SELECT DISTINCT A.XX_INTERFREESTIMATEPERT AS PERTFLEINTER "
                + "FROM XX_VLO_COSTSPERCENT A, C_ORDER B "
                + "WHERE B.XX_VLO_ARRIVALPORT_ID = '"
                + order.getXX_VLO_ArrivalPort_ID()
                + "' "
                + "AND B.C_BPARTNER_ID = '"
                + order.getC_BPartner_ID()
                + "' "
                + "AND B.C_COUNTRY_ID = '"
                + order.getC_Country_ID()
                + "' "
                + "AND B.XX_VLO_ARRIVALPORT_ID = A.XX_VLO_ARRIVALPORT_ID "
                + "AND B.XX_VLO_ARRIVALPORT_ID = A.XX_VLO_ARRIVALPORT_ID "
                + "AND B.C_BPARTNER_ID = A.C_BPARTNER_ID "
                + "AND B.C_COUNTRY_ID = A.C_COUNTRY_ID ");

        PreparedStatement pstmt6 = DB.prepareStatement(SQL6, null);
        ResultSet rs6 = pstmt6.executeQuery();

        if (rs6.next()) {
          // Porcentaje del flete internacional
          perfleteInt =
              rs6.getBigDecimal("PERTFLEINTER")
                  .divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);
          // Flete Internacional
          fleteInternac = montoBs.multiply(perfleteInt);
        }
        rs6.close();
        pstmt6.close();

        // Busco los productos que tienen asociados las Ref de la O/C

        String SQL7 =
            ("SELECT C.M_PRODUCT AS PRODUCT, A.XX_VMR_PO_LINEREFPROV_ID AS POLINE "
                + "FROM XX_VMR_PO_LINEREFPROV A, C_ORDER B, XX_VMR_REFERENCEMATRIX C "
                + "WHERE A.XX_VMR_PO_LINEREFPROV_ID = C.XX_VMR_PO_LINEREFPROV_ID "
                + "AND A.C_ORDER_ID = B.C_ORDER_ID "
                + "AND A.C_ORDER_ID = '"
                + LineRefProv.getC_Order_ID()
                + "' ");

        PreparedStatement pstmt7 = DB.prepareStatement(SQL7, null);
        ResultSet rs7 = pstmt7.executeQuery();

        while (rs7.next()) {
          // Calculo del Porcentaje de cada item = costo de cada item Bs / Monto O/C Bs
          productid = rs7.getInt("PRODUCT");
          poline = rs7.getInt("POLINE");

          // Costo de cada item Bs

          /*String SQL8 = ("SELECT (A.XX_UNITPURCHASEPRICE / B.XX_UNITCONVERSION) AS COSTO " +
          "FROM XX_VMR_PO_LINEREFPROV A, XX_VMR_UNITCONVERSION B, XX_VMR_REFERENCEMATRIX C, M_PRODUCT D " +
          "WHERE A.XX_VMR_UNITCONVERSION_ID = B.XX_VMR_UNITCONVERSION_ID " +
          "AND A.XX_VMR_PO_LINEREFPROV_ID = C.XX_VMR_PO_LINEREFPROV_ID " +
          "AND C.M_PRODUCT = D.M_PRODUCT_ID " +
          "AND C.M_PRODUCT = '"+productid+"' " +
          "AND A.XX_VMR_PO_LINEREFPROV_ID = '"+poline+"' ");*/

          String SQL8 =
              ("SELECT (A.LINENETAMT * E.MULTIPLYRATE) AS COSTO "
                  + "FROM XX_VMR_PO_LINEREFPROV A, XX_VMR_REFERENCEMATRIX C, M_PRODUCT D, C_CONVERSION_RATE E, C_ORDER F  "
                  + "WHERE A.XX_VMR_PO_LINEREFPROV_ID = C.XX_VMR_PO_LINEREFPROV_ID "
                  + "AND C.M_PRODUCT = D.M_PRODUCT_ID "
                  + "AND E.C_CONVERSION_RATE_ID = F.XX_CONVERSIONRATE_ID "
                  + "AND A.C_ORDER_ID = F.C_ORDER_ID "
                  + "AND C.M_PRODUCT = '"
                  + productid
                  + "' "
                  + "AND A.XX_VMR_PO_LINEREFPROV_ID = '"
                  + poline
                  + "' ");

          PreparedStatement pstmt8 = DB.prepareStatement(SQL8, null);
          ResultSet rs8 = pstmt8.executeQuery();

          if (rs8.next()) {
            costoitem = rs8.getBigDecimal("COSTO");

            // Porcentaje de cada item = costo de cada item Bs / Monto O/C Bs
            porcentitem = (costoitem.divide(montoBs, 8, RoundingMode.HALF_UP));

            // CIF Unitario = Porcentaje de cada Item * CIF total
            cifuni = porcentitem.multiply(cifTotal);

            // Busco Porcentaje Arancelario
            String SQL9 =
                ("SELECT (D.XX_PERCENTAGETARIFF/100) AS PERARANCEL "
                    + "FROM XX_VMR_PO_LINEREFPROV A, C_ORDER B, XX_VMR_REFERENCEMATRIX C, M_PRODUCT D "
                    + "WHERE A.XX_VMR_PO_LINEREFPROV_ID = C.XX_VMR_PO_LINEREFPROV_ID "
                    + "AND A.C_ORDER_ID = B.C_ORDER_ID "
                    + "AND C.M_PRODUCT = D.M_PRODUCT_ID "
                    + "AND D.M_PRODUCT_ID = '"
                    + productid
                    + "' "
                    + "AND A.C_ORDER_ID = '"
                    + LineRefProv.getC_Order_ID()
                    + "' ");

            PreparedStatement pstmt9 = DB.prepareStatement(SQL9, null);
            ResultSet rs9 = pstmt9.executeQuery();

            if (rs9.next()) {
              // Porcentaje Arancelario
              percentarancel = rs9.getBigDecimal("PERARANCEL");

              // Arancel de cada item = CIF unitario * Porcentaje Arancelario
              arancelitem = cifuni.multiply(percentarancel).add(arancelitem);
            }
            rs9.close();
            pstmt9.close();
          }
          rs8.close();
          pstmt8.close();

          // cif total(Creo que no hace falta) t arancel item se usan abajo
        } // end While rs7
        rs7.close();
        pstmt7.close();

        String SQL9 =
            ("SELECT XX_RATE/100 AS RATESENIAT FROM XX_VLO_IMPORTRATE WHERE NAME = 'Tasa de Servicio de aduanas SENIAT' "
                + "And AD_Client_ID IN(0,"
                + Env.getCtx().getAD_Client_ID()
                + ")");

        PreparedStatement pstmt9 = DB.prepareStatement(SQL9, null);
        ResultSet rs9 = pstmt9.executeQuery();

        if (rs9.next()) {
          rateseniat = rs9.getBigDecimal("RATESENIAT");
          montoseniat = arancelitem.multiply(rateseniat);

          String SQL10 =
              ("SELECT XX_RATE/100 AS RATETESORERIA FROM XX_VLO_IMPORTRATE WHERE NAME = 'Tasa de Servicio Aduana Tesorería' "
                  + "And AD_Client_ID IN(0,"
                  + Env.getCtx().getAD_Client_ID()
                  + ")");

          PreparedStatement pstmt10 = DB.prepareStatement(SQL10, null);
          ResultSet rs10 = pstmt10.executeQuery();

          if (rs10.next()) {
            ratetesoreria = rs10.getBigDecimal("RATETESORERIA");
            montotesoreria = arancelitem.multiply(ratetesoreria);

            // Monto Tasa aduanera =monto tasa seniat + monto tasa tesoreria
            tasaaduana = montoseniat.add(montotesoreria);
          }
          rs10.close();
          pstmt10.close();
        }
        rs9.close();
        pstmt9.close();

        // Calculo del IVA = (CIF total + Impuesto de importación + tasa aduanera) *%iva actual

        String SQL11 =
            ("SELECT MAX (VALIDFROM) AS FECHA, A.RATE/100 AS IVACT "
                + "FROM C_TAX A, C_TAXCATEGORY B "
                + "WHERE A.C_TAXCATEGORY_ID = B.C_TAXCATEGORY_ID "
                + "AND B.DESCRIPTION = 'Impuesto al Valor Agregado' "
                + "AND A.C_TAXCATEGORY_ID = B.C_TAXCATEGORY_ID "
                + "GROUP BY A.RATE ");

        PreparedStatement pstmt11 = DB.prepareStatement(SQL11, null);
        ResultSet rs11 = pstmt11.executeQuery();

        if (rs11.next()) {
          part1 = cifTotal.add(arancelitem);
          part2 = part1.add(tasaaduana);
          iva = part2.multiply(rs11.getBigDecimal("IVACT"));
        }
        rs11.close();
        pstmt11.close();

        // Monto tesorería Nacional = IVA + impuesto de importación + monto tasa tesoreria

        part = iva.add(arancelitem);
        montesorerianac = part.add(montotesoreria);

        // redondeo los BigDecimal
        montesorerianac = montesorerianac.setScale(2, BigDecimal.ROUND_UP);
        montoseniat = montoseniat.setScale(2, BigDecimal.ROUND_UP);

        String sql =
            "UPDATE C_Order po"
                + " SET XX_NatTreasuryEstAmount="
                + montesorerianac
                + "    , XX_SENIATESTEEMEDAMUNT="
                + montoseniat
                + " WHERE po.C_Order_ID="
                + LineRefProv.getC_Order_ID();
        DB.executeUpdate(null, sql);

      } // end if Check
      else {
        // alguna referencia no tiene producto asociado
        String sql =
            "UPDATE C_Order po"
                + " SET XX_NatTreasuryEstAmount="
                + 0
                + "    , XX_SENIATESTEEMEDAMUNT="
                + 0
                + " WHERE po.C_Order_ID="
                + LineRefProv.getC_Order_ID();
        DB.executeUpdate(null, sql);
      }

    } // end try
    catch (Exception e) {

    }
  } //	dispose
  public synchronized void insertData(String name, long modified, int type, DLNAMediaInfo media) {
    Connection conn = null;
    PreparedStatement ps = null;
    try {
      conn = getConnection();
      ps =
          conn.prepareStatement(
              "INSERT INTO FILES(FILENAME, MODIFIED, TYPE, DURATION, BITRATE, WIDTH, HEIGHT, SIZE, CODECV, FRAMERATE, ASPECT, ASPECTRATIOCONTAINER, ASPECTRATIOVIDEOTRACK, REFRAMES, AVCLEVEL, BITSPERPIXEL, THUMB, CONTAINER, MODEL, EXPOSURE, ORIENTATION, ISO, MUXINGMODE, FRAMERATEMODE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
      ps.setString(1, name);
      ps.setTimestamp(2, new Timestamp(modified));
      ps.setInt(3, type);
      if (media != null) {
        if (media.getDuration() != null) {
          ps.setDouble(4, media.getDurationInSeconds());
        } else {
          ps.setNull(4, Types.DOUBLE);
        }

        int databaseBitrate = 0;
        if (type != Format.IMAGE) {
          databaseBitrate = media.getBitrate();
          if (databaseBitrate == 0) {
            LOGGER.debug("Could not parse the bitrate from: " + name);
          }
        }
        ps.setInt(5, databaseBitrate);

        ps.setInt(6, media.getWidth());
        ps.setInt(7, media.getHeight());
        ps.setLong(8, media.getSize());
        ps.setString(9, left(media.getCodecV(), SIZE_CODECV));
        ps.setString(10, left(media.getFrameRate(), SIZE_FRAMERATE));
        ps.setString(11, left(media.getAspect(), SIZE_ASPECT));
        ps.setString(12, left(media.getAspect(), SIZE_ASPECTRATIO_CONTAINER));
        ps.setString(13, left(media.getAspect(), SIZE_ASPECTRATIO_VIDEOTRACK));
        ps.setByte(14, media.getReferenceFrameCount());
        ps.setString(15, left(media.getAvcLevel(), SIZE_AVC_LEVEL));
        ps.setInt(16, media.getBitsPerPixel());
        ps.setBytes(17, media.getThumb());
        ps.setString(18, left(media.getContainer(), SIZE_CONTAINER));
        if (media.getExtras() != null) {
          ps.setString(19, left(media.getExtrasAsString(), SIZE_MODEL));
        } else {
          ps.setString(19, left(media.getModel(), SIZE_MODEL));
        }
        ps.setInt(20, media.getExposure());
        ps.setInt(21, media.getOrientation());
        ps.setInt(22, media.getIso());
        ps.setString(23, left(media.getMuxingModeAudio(), SIZE_MUXINGMODE));
        ps.setString(24, left(media.getFrameRateMode(), SIZE_FRAMERATE_MODE));
      } else {
        ps.setString(4, null);
        ps.setInt(5, 0);
        ps.setInt(6, 0);
        ps.setInt(7, 0);
        ps.setLong(8, 0);
        ps.setString(9, null);
        ps.setString(10, null);
        ps.setString(11, null);
        ps.setString(12, null);
        ps.setString(13, null);
        ps.setByte(14, (byte) -1);
        ps.setString(15, null);
        ps.setInt(16, 0);
        ps.setBytes(17, null);
        ps.setString(18, null);
        ps.setString(19, null);
        ps.setInt(20, 0);
        ps.setInt(21, 0);
        ps.setInt(22, 0);
        ps.setString(23, null);
        ps.setString(24, null);
      }
      ps.executeUpdate();
      ResultSet rs = ps.getGeneratedKeys();
      int id = -1;
      while (rs.next()) {
        id = rs.getInt(1);
      }
      rs.close();
      if (media != null && id > -1) {
        PreparedStatement insert = null;
        if (media.getAudioTracksList().size() > 0) {
          insert =
              conn.prepareStatement(
                  "INSERT INTO AUDIOTRACKS VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        }

        for (DLNAMediaAudio audio : media.getAudioTracksList()) {
          insert.clearParameters();
          insert.setInt(1, id);
          insert.setInt(2, audio.getId());
          insert.setString(3, left(audio.getLang(), SIZE_LANG));
          insert.setString(4, left(audio.getFlavor(), SIZE_FLAVOR));
          insert.setInt(5, audio.getAudioProperties().getNumberOfChannels());
          insert.setString(6, left(audio.getSampleFrequency(), SIZE_SAMPLEFREQ));
          insert.setString(7, left(audio.getCodecA(), SIZE_CODECA));
          insert.setInt(8, audio.getBitsperSample());
          insert.setString(9, left(trimToEmpty(audio.getAlbum()), SIZE_ALBUM));
          insert.setString(10, left(trimToEmpty(audio.getArtist()), SIZE_ARTIST));
          insert.setString(11, left(trimToEmpty(audio.getSongname()), SIZE_SONGNAME));
          insert.setString(12, left(trimToEmpty(audio.getGenre()), SIZE_GENRE));
          insert.setInt(13, audio.getYear());
          insert.setInt(14, audio.getTrack());
          insert.setInt(15, audio.getAudioProperties().getAudioDelay());
          insert.setString(16, left(trimToEmpty(audio.getMuxingModeAudio()), SIZE_MUXINGMODE));
          insert.setInt(17, audio.getBitRate());

          try {
            insert.executeUpdate();
          } catch (JdbcSQLException e) {
            if (e.getErrorCode() == 23505) {
              LOGGER.debug(
                  "A duplicate key error occurred while trying to store the following file's audio information in the database: "
                      + name);
            } else {
              LOGGER.debug(
                  "An error occurred while trying to store the following file's audio information in the database: "
                      + name);
            }
            LOGGER.debug("The error given by jdbc was: " + e);
          }
        }

        if (media.getSubtitleTracksList().size() > 0) {
          insert = conn.prepareStatement("INSERT INTO SUBTRACKS VALUES (?, ?, ?, ?, ?)");
        }
        for (DLNAMediaSubtitle sub : media.getSubtitleTracksList()) {
          if (sub.getExternalFile() == null) { // no save of external subtitles
            insert.clearParameters();
            insert.setInt(1, id);
            insert.setInt(2, sub.getId());
            insert.setString(3, left(sub.getLang(), SIZE_LANG));
            insert.setString(4, left(sub.getFlavor(), SIZE_FLAVOR));
            insert.setInt(5, sub.getType().getStableIndex());
            try {
              insert.executeUpdate();
            } catch (JdbcSQLException e) {
              if (e.getErrorCode() == 23505) {
                LOGGER.debug(
                    "A duplicate key error occurred while trying to store the following file's subtitle information in the database: "
                        + name);
              } else {
                LOGGER.debug(
                    "An error occurred while trying to store the following file's subtitle information in the database: "
                        + name);
              }
              LOGGER.debug("The error given by jdbc was: " + e);
            }
          }
        }
        close(insert);
      }
    } catch (SQLException se) {
      if (se.getErrorCode() == 23001) {
        LOGGER.debug(
            "Duplicate key while inserting this entry: "
                + name
                + " into the database: "
                + se.getMessage());
      } else {
        LOGGER.error(null, se);
      }
    } finally {
      close(ps);
      close(conn);
    }
  }
  public ArrayList<DLNAMediaInfo> getData(String name, long modified) {
    ArrayList<DLNAMediaInfo> list = new ArrayList<DLNAMediaInfo>();
    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement stmt = null;
    try {
      conn = getConnection();
      stmt = conn.prepareStatement("SELECT * FROM FILES WHERE FILENAME = ? AND MODIFIED = ?");
      stmt.setString(1, name);
      stmt.setTimestamp(2, new Timestamp(modified));
      rs = stmt.executeQuery();
      while (rs.next()) {
        DLNAMediaInfo media = new DLNAMediaInfo();
        int id = rs.getInt("ID");
        media.setDuration(toDouble(rs, "DURATION"));
        media.setBitrate(rs.getInt("BITRATE"));
        media.setWidth(rs.getInt("WIDTH"));
        media.setHeight(rs.getInt("HEIGHT"));
        media.setSize(rs.getLong("SIZE"));
        media.setCodecV(rs.getString("CODECV"));
        media.setFrameRate(rs.getString("FRAMERATE"));
        media.setAspect(rs.getString("ASPECT"));
        media.setAspectRatioContainer(rs.getString("ASPECTRATIOCONTAINER"));
        media.setAspectRatioVideoTrack(rs.getString("ASPECTRATIOVIDEOTRACK"));
        media.setReferenceFrameCount(rs.getByte("REFRAMES"));
        media.setAvcLevel(rs.getString("AVCLEVEL"));
        media.setBitsPerPixel(rs.getInt("BITSPERPIXEL"));
        media.setThumb(rs.getBytes("THUMB"));
        media.setContainer(rs.getString("CONTAINER"));
        media.setModel(rs.getString("MODEL"));
        if (media.getModel() != null && !FormatConfiguration.JPG.equals(media.getContainer())) {
          media.setExtrasAsString(media.getModel());
        }
        media.setExposure(rs.getInt("EXPOSURE"));
        media.setOrientation(rs.getInt("ORIENTATION"));
        media.setIso(rs.getInt("ISO"));
        media.setMuxingMode(rs.getString("MUXINGMODE"));
        media.setFrameRateMode(rs.getString("FRAMERATEMODE"));
        media.setMediaparsed(true);
        PreparedStatement audios =
            conn.prepareStatement("SELECT * FROM AUDIOTRACKS WHERE FILEID = ?");
        audios.setInt(1, id);
        ResultSet subrs = audios.executeQuery();
        while (subrs.next()) {
          DLNAMediaAudio audio = new DLNAMediaAudio();
          audio.setId(subrs.getInt("ID"));
          audio.setLang(subrs.getString("LANG"));
          audio.setFlavor(subrs.getString("FLAVOR"));
          audio.getAudioProperties().setNumberOfChannels(subrs.getInt("NRAUDIOCHANNELS"));
          audio.setSampleFrequency(subrs.getString("SAMPLEFREQ"));
          audio.setCodecA(subrs.getString("CODECA"));
          audio.setBitsperSample(subrs.getInt("BITSPERSAMPLE"));
          audio.setAlbum(subrs.getString("ALBUM"));
          audio.setArtist(subrs.getString("ARTIST"));
          audio.setSongname(subrs.getString("SONGNAME"));
          audio.setGenre(subrs.getString("GENRE"));
          audio.setYear(subrs.getInt("YEAR"));
          audio.setTrack(subrs.getInt("TRACK"));
          audio.getAudioProperties().setAudioDelay(subrs.getInt("DELAY"));
          audio.setMuxingModeAudio(subrs.getString("MUXINGMODE"));
          audio.setBitRate(subrs.getInt("BITRATE"));
          media.getAudioTracksList().add(audio);
        }
        subrs.close();
        audios.close();

        PreparedStatement subs = conn.prepareStatement("SELECT * FROM SUBTRACKS WHERE FILEID = ?");
        subs.setInt(1, id);
        subrs = subs.executeQuery();
        while (subrs.next()) {
          DLNAMediaSubtitle sub = new DLNAMediaSubtitle();
          sub.setId(subrs.getInt("ID"));
          sub.setLang(subrs.getString("LANG"));
          sub.setFlavor(subrs.getString("FLAVOR"));
          sub.setType(SubtitleType.valueOfStableIndex(subrs.getInt("TYPE")));
          media.getSubtitleTracksList().add(sub);
        }
        subrs.close();
        subs.close();

        list.add(media);
      }
    } catch (SQLException se) {
      LOGGER.error(null, se);
      return null;
    } finally {
      close(rs);
      close(stmt);
      close(conn);
    }
    return list;
  }
  /* 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();
  }
  public void accionEjecutarMovimiento() {
    try {
      Connection conn = Conectar.conectar();

      Statement st = conn.createStatement();

      ResultSet rs =
          st.executeQuery("SELECT propietario FROM regiones WHERE idRegion = " + idRegionDestino);
      String propietario = "nulo";
      if (rs.next()) {
        propietario = rs.getString(1);
      }

      // Si el territorio esta
      // vacio****************************************************************************
      if (propietario.equalsIgnoreCase("Deshabitado")) {
        String nombre = generaNombre();

        st.executeQuery(
            "UPDATE regiones SET nombreRegion = '"
                + nombre
                + "', propietario = '"
                + usuario
                + "' WHERE idRegion = "
                + idRegionDestino);
        st.executeQuery(
            "INSERT INTO edificiosregion VALUES ("
                + idRegionDestino
                + ", "
                + 1400
                + ", "
                + 1
                + ")");
        for (int i = 0; i < pelotones.size(); i = i + 2) {
          st.executeQuery(
              "INSERT INTO despliegues VALUES ("
                  + idRegionDestino
                  + ", "
                  + pelotones.get(i)
                  + ", "
                  + pelotones.get(i + 1)
                  + ")");
        }
        st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);
        st.executeQuery("commit");

        System.out.println("Query ejecutado.");
      }

      // Si el territorio te pertenece
      // *******************************************************************************
      else if (propietario.equalsIgnoreCase(usuario)) {
        ResultSet rs2 =
            st.executeQuery("select * from despliegues where idRegion = " + idRegionDestino);
        ArrayList<Despliegue> despliegues = new ArrayList<Despliegue>();
        while (rs2.next()) {
          despliegues.add(new Despliegue(rs2.getInt(1), rs2.getInt(2), rs2.getInt(3)));
        }
        Boolean encontrado = false;

        for (int i = 0; i < pelotones.size(); i = i + 2) {
          encontrado = false;

          for (Despliegue despliegue : despliegues) {
            if (pelotones.get(i).equals(despliegue.getIdUnidad())) {
              st.executeQuery(
                  "update despliegues set cantidad = "
                      + (despliegue.getCantidad() + pelotones.get(i + 1))
                      + " where idRegion = "
                      + idRegionDestino
                      + " and idUnidad = "
                      + despliegue.getIdUnidad());
              encontrado = true;
            }
          }
          if (!encontrado) {
            st.executeQuery(
                "INSERT INTO despliegues VALUES ("
                    + idRegionDestino
                    + ", "
                    + pelotones.get(i)
                    + ", "
                    + pelotones.get(i + 1)
                    + ")");
          }
        }
        st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);
        st.executeQuery("commit");

        System.out.println("Query ejecutado.");
        rs2.close();
      }

      // Si es un territorio enemigo ( COMBATE )
      // *****************************************************************************
      else {
        int ataque = 0;
        int defensa = 0;
        int defenemiga = 0;
        int ataenemigo = 0;

        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        java.util.Date fecha = new java.util.Date();
        String fechahora = formato.format(fecha);

        // Recolectamos el ataque y la defensa del enemigo
        ResultSet rs3 =
            st.executeQuery("select * from despliegues where idRegion = " + idRegionDestino);
        ArrayList<Despliegue> despliegues = new ArrayList<Despliegue>();
        while (rs3.next()) {
          despliegues.add(new Despliegue(rs3.getInt(1), rs3.getInt(2), rs3.getInt(3)));
        }

        for (Despliegue despliegue : despliegues) {
          if (despliegue.getIdUnidad() == 4100) {
            ataenemigo = ataenemigo + (15 * despliegue.getCantidad());
            defenemiga = defenemiga + (30 * despliegue.getCantidad());
          } else if (despliegue.getIdUnidad() == 4101) {
            ataenemigo = ataenemigo + (25 * despliegue.getCantidad());
            defenemiga = defenemiga + (50 * despliegue.getCantidad());
          } else if (despliegue.getIdUnidad() == 4102) {
            ataenemigo = ataenemigo + (55 * despliegue.getCantidad());
            defenemiga = defenemiga + (20 * despliegue.getCantidad());
          } else if (despliegue.getIdUnidad() == 4103) {
            ataenemigo = ataenemigo + 800;
            ataenemigo = ataenemigo * ((ataenemigo * 10) / 100);
            defenemiga = defenemiga + 600;
          } else if (despliegue.getIdUnidad() == 4104) {
            ataenemigo = ataenemigo + (400 * despliegue.getCantidad());
            defenemiga = defenemiga + (100 * despliegue.getCantidad());
          } else if (despliegue.getIdUnidad() == 4102) {
            ataenemigo = ataenemigo + (50 * despliegue.getCantidad());
            defenemiga = defenemiga + (800 * despliegue.getCantidad());
          }
        }

        // Recolectamos informacion de edificios defensivos
        ResultSet rs4 =
            st.executeQuery("select * from edificiosregion where idRegion = " + idRegionDestino);
        ArrayList<EdificiosRegion> despliegues2 = new ArrayList<EdificiosRegion>();
        while (rs4.next()) {
          despliegues2.add(new EdificiosRegion(rs4.getInt(1), rs4.getInt(2), rs4.getInt(3)));
        }

        for (EdificiosRegion despliegue2 : despliegues2) {
          if (despliegue2.idEdificio == 1300) {
            ataenemigo = ataenemigo + (200 * despliegue2.cantidad);
            defenemiga = defenemiga + (1000 * despliegue2.cantidad);
          } else if (despliegue2.idEdificio == 1301) {
            ataenemigo = ataenemigo + (500 * despliegue2.cantidad);
            defenemiga = defenemiga + (500 * despliegue2.cantidad);
          }
        }

        // Recolectamos ataque y defensa nuestra***************************
        for (int i = 0; i < pelotones.size(); i = i + 2) {
          if (pelotones.get(i) == 4100) {
            ataque = ataque + (15 * pelotones.get(i + 1));
            defensa = defensa + (30 * pelotones.get(i + 1));
          } else if (pelotones.get(i) == 4101) {
            ataque = ataque + (25 * pelotones.get(i + 1));
            defensa = defensa + (50 * pelotones.get(i + 1));
          } else if (pelotones.get(i) == 4102) {
            ataque = ataque + (55 * pelotones.get(i + 1));
            defensa = defensa + (20 * pelotones.get(i + 1));
          } else if (pelotones.get(i) == 4103) {
            ataque = ataque + 800;
            ataque = ataque * ((ataenemigo * 10) / 100);
            defensa = defensa + 600;
          } else if (pelotones.get(i) == 4104) {
            ataque = ataque + (400 * pelotones.get(i + 1));
            defensa = defensa + (100 * pelotones.get(i + 1));
          } else if (pelotones.get(i) == 4100) {
            ataque = ataque + (50 * pelotones.get(i + 1));
            defensa = defensa + (800 * pelotones.get(i + 1));
          }
        }

        int ataque1 = defenemiga - ataque;
        int ataque2 = defensa - ataenemigo;
        // Capturamos el nick del enemigo***************
        String enemigo = "Deshabitado";
        ResultSet rsenemigo =
            st.executeQuery("select propietario from regiones where idRegion = " + idRegionDestino);
        if (rsenemigo.next()) {
          enemigo = rsenemigo.getString(1);
        }

        // 1 ---  Si el enemigo tiene vida inferior a 0 y tu no
        if (ataque1 <= 0 && ataque2 > 0) {
          // Se conquista el territorio, se compra aldea y se recolocan las unidades sobrantes
          // dependiendo del ataque 2

          st.executeQuery(
              "UPDATE regiones SET propietario = '"
                  + usuario
                  + "' WHERE idRegion = "
                  + idRegionDestino);

          st.executeQuery(
              "DELETE edificiosregion WHERE idRegion = "
                  + idRegionDestino
                  + " AND idEdificio != "
                  + 1400);

          st.executeQuery("DELETE despliegues WHERE idRegion = " + idRegionDestino);

          st.executeQuery("DELETE construcciones WHERE idRegion = " + idRegionDestino);

          st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);

          // Escribimos un mensaje al usuario con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + usuario
                  + "', 'Informe de Batalla', '"
                  + "¡Enhorabuena!#Has ganado la batalla en el territorio ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataenemigo
                  + ".#Daño causado-> "
                  + ataque
                  + ".', '"
                  + fechahora
                  + "')");

          // Escribimos un mensaje al enemigo con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + enemigo
                  + "', 'Informe de Batalla', '"
                  + "Lo siento.#Has perdido la batalla en el territorio ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataque
                  + ".#Daño causado-> "
                  + ataenemigo
                  + ".', '"
                  + fechahora
                  + "')");

          System.out.println(ataque2);
          // Algoritmo para ver el porcentaje de unidades que me quedan
          int porcperdido = (int) (ataque2 * 100) / defensa;

          for (int i = 0; i < pelotones.size(); i = i + 2) {
            pelotones.set(i + 1, (int) (pelotones.get(i + 1) * porcperdido) / 100);
          }
          for (int i = 0; i < pelotones.size(); i = i + 2) {
            st.executeQuery(
                "INSERT INTO despliegues VALUES ("
                    + idRegionDestino
                    + ", "
                    + pelotones.get(i)
                    + ", "
                    + pelotones.get(i + 1)
                    + ")");
          }
        }

        // 2 --- Los 2 tienen la vida a 0 o menos
        else if (ataque1 <= 0 && ataque2 <= 0) {
          // El enemigo se queda con el territorio pero pierde todos los edificios y se recolocan
          // unidades dependiendo de ataque1.

          st.executeQuery(
              "DELETE edificiosregion WHERE idRegion = "
                  + idRegionDestino
                  + " AND idEdificio != "
                  + 1400);

          st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);

          st.executeQuery("DELETE despliegues WHERE idRegion = " + idRegionDestino);

          // Escribimos un mensaje al usuario con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + usuario
                  + "', 'Informe de Batalla', '"
                  + "Lo siento.#Has perdido la batalla en el territorio ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataenemigo
                  + ".#Daño causado-> "
                  + ataque
                  + ".', '"
                  + fechahora
                  + "')");

          // Escribimos un mensaje al enemigo con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + enemigo
                  + "', 'Informe de Batalla', '"
                  + "¡Enhorabuena!#Has conseguido defender tu territorio ubicado en ["
                  + idRegionDestino
                  + "].#"
                  + "Aunque has perdido todas tus tropas y edificios.#Daño Recibido-> "
                  + ataque
                  + ".#Daño causado-> "
                  + ataenemigo
                  + ".', '"
                  + fechahora
                  + "')");
        }

        // 3 -- Tu pierdes la batalla
        else if (ataque1 > 0 && ataque2 <= 0) {
          // El enemigo recoloca unidades y tu lo pierdes todo
          st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);

          int porcperdido = (int) (ataque1 * 100) / defenemiga;

          for (Despliegue despliegue : despliegues) {
            despliegue.setCantidad((int) (despliegue.getCantidad() * porcperdido) / 100);
          }
          for (Despliegue despliegue : despliegues) {
            st.executeQuery(
                "UPDATE despliegues SET cantidad = "
                    + despliegue.getCantidad()
                    + " WHERE idRegion = "
                    + idRegionDestino
                    + " AND idUnidad = "
                    + despliegue.getIdUnidad());
          }

          // Escribimos un mensaje al usuario con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + usuario
                  + "', 'Informe de Batalla', '"
                  + "Lo siento.#Has perdido la batalla en el territorio ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataenemigo
                  + ".#Daño causado-> "
                  + ataque
                  + ".', '"
                  + fechahora
                  + "')");

          // Escribimos un mensaje al enemigo con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + enemigo
                  + "', 'Informe de Batalla', '"
                  + "¡Enhorabuena!#Has conseguido defender tu territorio ubicado en ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataque
                  + ".#Daño causado-> "
                  + ataenemigo
                  + ".', '"
                  + fechahora
                  + "')");

        }
        // 4 --- Los 2 quedan con vida**************************************************************
        else if (ataque1 > 0 && ataque2 > 0) {
          // Se recolocan unidades en los 2.

          st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);

          int porcperdido1 = (int) (ataque1 * 100) / defenemiga;

          for (Despliegue despliegue : despliegues) {
            despliegue.setCantidad((int) (despliegue.getCantidad() * porcperdido1) / 100);
          }
          for (Despliegue despliegue : despliegues) {
            st.executeQuery(
                "UPDATE despliegues SET cantidad = "
                    + despliegue.getCantidad()
                    + " WHERE idRegion = "
                    + idRegionDestino
                    + " AND idUnidad = "
                    + despliegue.getIdUnidad());
          }

          int porcperdido2 = (int) (ataque2 * 100) / defensa;

          for (int i = 0; i < pelotones.size(); i = i + 2) {
            pelotones.set(i + 1, (int) (pelotones.get(i + 1) * porcperdido2) / 100);
          }
          for (int i = 0; i < pelotones.size(); i = i + 2) {
            st.executeQuery(
                "UPDATE despliegues SET cantidad = (SELECT cantidad+"
                    + pelotones.get(i + 1)
                    + " FROM despliegues WHERE idRegion = "
                    + idRegion
                    + " AND idUnidad = "
                    + pelotones.get(i)
                    + ") WHERE idRegion = "
                    + idRegion
                    + " AND idUnidad = "
                    + pelotones.get(i));
          }

          // Escribimos un mensaje al usuario con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + usuario
                  + "', 'Informe de Batalla', '"
                  + "Lo siento.#Has perdido la batalla en la region ["
                  + idRegionDestino
                  + "].#"
                  + "Aunque has recuperado algunas unidades.#Daño Recibido-> "
                  + ataenemigo
                  + ".#Daño causado-> "
                  + ataque
                  + ".', '"
                  + fechahora
                  + "')");

          // Escribimos un mensaje al enemigo con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + enemigo
                  + "', 'Informe de Batalla', '"
                  + "¡Enhorabuena!#Has conseguido defender tu territorio ubicado en ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataque
                  + ".#Daño causado-> "
                  + ataenemigo
                  + ".', '"
                  + fechahora
                  + "')");
        }

        st.executeQuery("commit");
        rs3.close();
        rs4.close();
        rsenemigo.close();
      }

      st.close();
      rs.close();
      conn.close();
    } catch (SQLException e) {
      System.out.println(e.getMessage() + " Fallo ejecutar movimiento.");
    }
  }
示例#22
0
  public void actionPerformed(ActionEvent evt) {
    String arg = evt.getActionCommand();
    if (arg.equals("Query")) { // 用户按下Query按钮
      ResultSet rs = null;
      try {
        String author = (String) authors.getSelectedItem();
        String publisher = (String) publishers.getSelectedItem();
        if (!author.equals("Any") && !publisher.equals("Any")) {
          if (authorPublisherQueryStmt == null) {
            //  根据用户选择的出版社名和作者名查询相关的书名和书价
            String authorPublisherQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, BooksAuthors, Authors, Publishers "
                    + "WHERE Authors.Author_Id = BooksAuthors.Author_Id AND "
                    + "BooksAuthors.ISBN = Books.ISBN AND "
                    + "Books.Publisher_Id = Publishers.Publisher_Id AND "
                    + "Authors.Name = ? AND "
                    + "Publishers.Name = ?";
            authorPublisherQueryStmt = con.prepareStatement(authorPublisherQuery);
          }

          authorPublisherQueryStmt.setString(1, author);
          authorPublisherQueryStmt.setString(2, publisher);
          rs = authorPublisherQueryStmt.executeQuery();
        } else if (!author.equals("Any") && publisher.equals("Any")) {
          if (authorQueryStmt == null) {
            //  根据用户选择的作者名查询相关的书名和书价
            String authorQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, BooksAuthors, Authors "
                    + "WHERE Authors.Author_Id = BooksAuthors.Author_Id AND "
                    + "BooksAuthors.ISBN = Books.ISBN AND "
                    + "Authors.Name = ?";
            authorQueryStmt = con.prepareStatement(authorQuery);
          }
          authorQueryStmt.setString(1, author);
          rs = authorQueryStmt.executeQuery();
        } else if (author.equals("Any") && !publisher.equals("Any")) {
          if (publisherQueryStmt == null) {
            //  根据用户选择的出版社名查询相关的书名和书价
            String publisherQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, Publishers "
                    + "WHERE Books.Publisher_Id = Publishers.Publisher_Id AND "
                    + "Publishers.Name = ?";
            publisherQueryStmt = con.prepareStatement(publisherQuery);
          }
          publisherQueryStmt.setString(1, publisher);
          rs = publisherQueryStmt.executeQuery();
        } else {
          if (allQueryStmt == null) {
            // 若用户未选任何信息,则输出所有的书名和对应的书价
            String allQuery = "SELECT Books.Price, Books.Title FROM Books";
            allQueryStmt = con.prepareStatement(allQuery);
          }
          rs = allQueryStmt.executeQuery();
        }

        result.setText("");
        while (rs.next()) result.append(rs.getString(1) + " | " + rs.getString(2) + "\n");
        rs.close();
      } catch (Exception e) {
        result.setText("Error " + e);
      }
    } else if (arg.equals("Change prices")) { //  用户选择“Change prices”按钮
      String publisher = (String) publishers.getSelectedItem();
      if (publisher.equals("Any")) result.setText("I am sorry, but I cannot do that.");
      else
        try {
          // 根据用户输入的新的书价更新Books表的数据
          String updateStatement =
              "UPDATE Books "
                  + "SET Price = Price + "
                  + priceChange.getText()
                  + " WHERE Books.Publisher_Id = "
                  + "(SELECT Publisher_Id FROM Publishers WHERE Name = '"
                  + publisher
                  + "')";
          int r = stmt.executeUpdate(updateStatement);
          result.setText(r + " records updated.");
        } catch (Exception e) {
          result.setText("Error " + e);
        }
    }
  }