public int retornaIdResp(String nome, int tipo) throws SQLException {
    if (tipo == 0) {

      sql = "select idgrupo from grupo where descricao = ?";
      if (!FabricaConexoes.verificaConexao()) FabricaConexoes.getConexao();
      stm = FabricaConexoes.returnStatement(sql);
      stm.setString(1, nome);
      rs = FabricaConexoes.returnResult(stm);
      rs.next();
      return rs.getInt("idgrupo");

    } else if (tipo == 1) {
      sql = "select idusuario from usuario where nome = ?";
      if (!FabricaConexoes.verificaConexao()) FabricaConexoes.getConexao();
      stm = FabricaConexoes.returnStatement(sql);
      stm.setString(1, nome);
      rs = FabricaConexoes.returnResult(stm);
      rs.next();
      return rs.getInt("idusuario");
    } else if (tipo == 2) {
      return 0;
    } else if (tipo == 3) {
      return 3;
    } else {
      return 0;
    }
  }
 public String getONT() {
   Connection con;
   String ontid = null;
   String JsonStr = "{\"ont\": [";
   try {
     con = DataSource.getConnection();
     PreparedStatement pst = con.prepareStatement("select ont_id from ont");
     ResultSet rs = pst.executeQuery();
     int flag = 1;
     while (rs.next()) {
       flag = 0;
       ontid = rs.getString("ont_id");
       JsonStr += "{\"ont_id\":\"" + ontid + "\"},";
     }
     if (flag == 1) {
       JsonStr += ",";
     }
     int len = JsonStr.length();
     JsonStr = JsonStr.substring(0, len - 1);
     JsonStr += "],";
   } catch (SQLException | ClassNotFoundException e) {
     System.out.println("error connection to the database getponids" + e.getMessage());
     return "";
   }
   System.out.println(JsonStr);
   DataSource.returnConnection(con);
   return JsonStr;
 }
 public boolean isValidParty(PartyLovVO partyLovVO) throws Exception {
   boolean validParty = false;
   Connection connection = null;
   StringBuilder finalQry = new StringBuilder();
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   QueryFields fields = null;
   String whereCond = "";
   try {
     fields = new QueryFields();
     fields.put("BP.DCS_STATUS", "1");
     fields.put("PR.DCS_CODE", partyLovVO.getPartyRole());
     fields.put("BP.DCS_CODE", partyLovVO.getPartyId());
     if (!StringUtility.isNullEmpty(partyLovVO.getRelatedParty())) {
       fields.put("BP.DCS_CODE", partyLovVO.getRelatedParty());
       fields.put("PR.DCS_CODE", partyLovVO.getRelationShipType());
     }
     whereCond = " AND " + QueryBuilderUtil.buildWhereCond(fields);
     finalQry.append(PartyLovQueries.validatePartyIdQry).append(whereCond);
     connection = getConnection();
     pstmt = connection.prepareStatement(finalQry.toString());
     rs = pstmt.executeQuery();
     if (rs.next()) {
       if (rs.getInt(1) > 0) {
         validParty = true;
       } else {
         validParty = false;
       }
     }
   } finally {
     ConnectionUtil.closeConnection(connection, pstmt, rs);
   }
   return validParty;
 }
Example #4
1
 /**
  * checks if a particular chained task is ready for processing
  *
  * @param chain_id the id this process is part off order
  * @param process_id the process_id
  * @return
  * @throws java.sql.SQLException
  */
 public boolean canExecute(int chain_id, int process_id) throws SQLException {
   boolean isReady = false;
   try (AutoCloseableDBConnection c = new AutoCloseableDBConnection();
       PreparedStatement getChain =
           c.prepareStatement(
               "SELECT process_id,busy FROM chain_activities WHERE (chain_id=?) ORDER BY process_id")) {
     getChain.setInt(1, chain_id);
     LinkedHashMap<Integer, Boolean> clearedToRunMap = new LinkedHashMap<>();
     try (ResultSet executeQuery = getChain.executeQuery()) {
       while (executeQuery.next()) {
         clearedToRunMap.put(executeQuery.getInt("process_id"), executeQuery.getBoolean("busy"));
       }
     }
     int predecessingProcess = -1;
     for (Entry<Integer, Boolean> aProcess : clearedToRunMap.entrySet()) {
       if (aProcess.getKey() == process_id) {
         break;
       } else {
         predecessingProcess = aProcess.getKey();
         // check if this process is already busy
       }
     }
     if (predecessingProcess == -1) {
       // then there's no predecessing process, meaning it can be run for sure
       isReady = true;
     } else if (clearedToRunMap.get(predecessingProcess)) {
       try ( // then it's busy, but it can be that it's not yet done !
       ProcessDAO pdao = ProcessDAO.getInstance()) {
         isReady = pdao.isCompletedProcess(process_id);
       }
     }
   }
   return isReady;
 }
Example #5
1
 public Collection ejbGetRuoliSicurezza_View() {
   BMPConnection bmp = getConnection();
   try {
     PreparedStatement ps =
         bmp.prepareStatement(
             "SELECT "
                 + "COD_RUO_SIC, NOM_RUO_SIC, DES_RUO_SIC "
                 + "FROM "
                 + "ANA_RUO_SIC_TAB "
                 + "ORDER BY "
                 + "NOM_RUO_SIC");
     ResultSet rs = ps.executeQuery();
     java.util.ArrayList al = new java.util.ArrayList();
     while (rs.next()) {
       RuoliSicurezza_View obj = new RuoliSicurezza_View();
       obj.COD_RUO_SIC = rs.getLong(1);
       obj.NOM_RUO_SIC = rs.getString(2);
       obj.DES_RUO_SIC = rs.getString(3);
       al.add(obj);
     }
     bmp.close();
     return al;
   } catch (Exception ex) {
     throw new EJBException(ex);
   } finally {
     bmp.close();
   }
 }
Example #6
1
  private FileContent getFileContentWithChunkChecksums(FileChecksum fileChecksum) {
    try (PreparedStatement preparedStatement =
        getStatement("filecontent.select.all.getFileContentByChecksumWithChunkChecksums.sql")) {
      preparedStatement.setString(1, fileChecksum.toString());

      try (ResultSet resultSet = preparedStatement.executeQuery()) {
        FileContent fileContent = null;

        while (resultSet.next()) {
          if (fileContent == null) {
            fileContent = new FileContent();

            fileContent.setChecksum(
                FileChecksum.parseFileChecksum(resultSet.getString("checksum")));
            fileContent.setSize(resultSet.getLong("size"));
          }

          // Add chunk references
          ChunkChecksum chunkChecksum =
              ChunkChecksum.parseChunkChecksum(resultSet.getString("chunk_checksum"));
          fileContent.addChunk(chunkChecksum);
        }

        return fileContent;
      }
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }
  /** Creates new form SessionLog */
  public SessionLog() {
    initComponents();

    try {
      Connection con = DBConnection.getConnection();
      String query = "select * from user_session where user_id=?";
      PreparedStatement psmt = con.prepareStatement(query);
      psmt.setString(1, "ababab");
      ResultSet rs = psmt.executeQuery();
      ResultSetMetaData rsmd;
      rsmd = rs.getMetaData();
      Vector column = new Vector();
      int count = rsmd.getColumnCount();
      DefaultTableModel dtm = new DefaultTableModel();
      for (int i = 1; i <= count; i++) {
        column.addElement(rsmd.getColumnName(i));
      }
      dtm.setColumnIdentifiers(column);
      while (rs.next()) {
        Vector row = new Vector();
        for (int i = 1; i <= count; i++) {
          row.addElement(rs.getString(i));
        }
        dtm.addRow(row);
      }
      jTable1.setModel(dtm);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Example #8
1
 public void updateTravellerCount(int id) {
   // how many travellers are in the TARDIS?
   Statement statement = null;
   ResultSet rsCount = null;
   try {
     Connection connection = service.getConnection();
     statement = connection.createStatement();
     String queryCount = "SELECT COUNT (*) AS count FROM travellers WHERE tardis_id = " + id;
     rsCount = statement.executeQuery(queryCount);
     if (rsCount.next()) {
       int count = rsCount.getInt("count");
       plugin.trackTravellers.put(id, count);
     }
     rsCount.close();
     statement.close();
   } catch (SQLException e) {
     plugin.console.sendMessage(plugin.pluginName + " /TARDIS travel to location Error: " + e);
   } finally {
     try {
       rsCount.close();
     } catch (Exception e) {
     }
     try {
       statement.close();
     } catch (Exception e) {
     }
   }
 }
 public UserProfile mapRow(ResultSet rs, int numRow) throws SQLException {
   UserProfile userProfile = new UserProfile();
   userProfile.setUserProfileId(rs.getString("USER_PROFILE_ID"));
   userProfile.setUserName(rs.getString("NAME"));
   userProfile.setEmail(rs.getString("EMAIL"));
   return userProfile;
 }
  public static List<Message> getMessagesByUser(User user) {

    List<Message> messages = new ArrayList<Message>();
    ResultSet resultSet;
    Message message;
    String text, hash;
    int id;
    boolean valid = true;

    String sql = "SELECT * FROM mail WHERE userid = " + user.getId() + " ;";

    try {
      resultSet = getStatement().executeQuery(sql);

      while (resultSet.next()) {
        id = resultSet.getInt("mailid");
        text = resultSet.getString("message");
        hash = resultSet.getString("hash");
        message = Message.create(id, text, text.length(), hash, valid);
        messages.add(message);
      }

      getStatement().close();

    } catch (SQLException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }

    return messages;
  }
  public static boolean mailAlreadyExsists(String hash, User user) {

    String sql = "SELECT * FROM mail WHERE hash like '" + hash + "';";

    boolean mail = false;

    ResultSet resultSet;

    try {
      resultSet = getStatement().executeQuery(sql);

      while (resultSet.next()) {
        mail = true;
      }

      resultSet.close();
      getStatement().close();

    } catch (SQLException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }

    return mail;
  }
  public static void saveMail(User user, Message message) {

    ResultSet resultSet = null;

    try {

      String sql =
          "INSERT INTO mail (mailid,userid,hash,message) values("
              + message.getId()
              + ","
              + user.getId()
              + ",'"
              + message.getHash()
              + "','"
              + message.getContent()
              + "');";

      getStatement().execute(sql);

      resultSet.close();
      getStatement().close();

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
  @Deprecated
  public static void addNewMessageToUser(User user, Message message) {

    String sql = "SELECT MAX(mailid) as 'maxid' FROM mail;";

    ResultSet resultSet = null;
    int number = 10000;

    try {
      resultSet = getStatement().executeQuery(sql);

      resultSet.next();
      number = resultSet.getInt("maxid");

      number++;
      sql =
          "INSERT INTO mail (mailid,userid,hash,message) values("
              + number
              + ","
              + user.getId()
              + ",'"
              + message.getHash()
              + "','"
              + message.getContent().replace("'", "\"")
              + "');";

      getStatement().execute(sql);

      resultSet.close();
      getStatement().close();

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
 public Integer add(WheelsBCD entity) {
   Integer generatedId = null;
   ResultSet resultSet = null;
   Connection connection = null;
   PreparedStatement preparedStatement = null;
   if (checkEntity(entity)) {
     try {
       connection = connectionPool.getConnection();
       preparedStatement =
           (PreparedStatement)
               connection.prepareStatement(addRequest, PreparedStatement.RETURN_GENERATED_KEYS);
       preparedStatement.setString(1, entity.getValue());
       preparedStatement.execute();
       resultSet = preparedStatement.getGeneratedKeys();
       if (resultSet.next()) {
         generatedId = resultSet.getInt(1);
       }
     } catch (SQLException ex) {
       generatedId = null;
     } finally {
       closeAll(resultSet, preparedStatement, connection);
     }
   }
   return generatedId;
 }
  /**
   * This method collects payment for the current transaction.
   *
   * @param amount the amount of money collected from the customer.
   * @param payment no idea what this is (TODO: ask about class diagram)
   * @return no idea what this is suppose to return.
   * @throws SQLException if sql error.
   * @throws ClassNotFoundException if sql error.
   * @throws IllegalStateException if there are no items on the invoice.
   */
  public double pay(String paymentMethod, int amount)
      throws IllegalStateException, SQLException, ClassNotFoundException, Exception {
    if (myTransaction.getNumberOfItems() == 0) {
      throw new IllegalStateException("There are no items on the Invoice.");
    }
    JDBCConnection JDBC = new JDBCConnection();
    Statement st = JDBC.createStatement();
    String table = "invoice";
    String column = "invoiceID";
    String SQL = "SELECT " + column + " FROM " + table + " GROUP BY " + column;
    ResultSet rs = st.executeQuery(SQL);
    // rs.last();
    int nextInvoiceID = 0;
    if (rs.last()) {
      int LastID = rs.getInt(column);
      nextInvoiceID = LastID + 1;
    }

    // use these two lines if you want invoices to be numbered 1000 and up
    // int starting = 999;
    // int nextInvoiceID = mySQLhelper.getTotalNumberOfInvoices() + 1;
    //		int nextInvoiceID = mySQLhelper.getTotalNumberOfRows(SQLhelper.TRANSACTION_TABLE_NAME,
    // SQLhelper.TRANSACTION_TABLE_PK) + 1;
    // Payment myPayment = new Payment(amount, paymentMethod);
    double change = myTransaction.markPaid(paymentMethod, amount, nextInvoiceID);
    myTransaction.UpdateItem();
    process();
    return change;
  }
Example #16
0
 /**
  * Get Accessible Goals
  *
  * @param ctx context
  * @return array of goals
  */
 public static MGoal[] getGoals(Ctx ctx) {
   ArrayList<MGoal> list = new ArrayList<MGoal>();
   String sql = "SELECT * FROM PA_Goal WHERE IsActive='Y' " + "ORDER BY SeqNo";
   sql =
       MRole.getDefault(ctx, false)
           .addAccessSQL(sql, "PA_Goal", false, true); // 	RW to restrict Access
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, (Trx) null);
     rs = pstmt.executeQuery();
     while (rs.next()) {
       MGoal goal = new MGoal(ctx, rs, null);
       goal.updateGoal(false);
       list.add(goal);
     }
   } catch (Exception e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   MGoal[] retValue = new MGoal[list.size()];
   list.toArray(retValue);
   return retValue;
 } //	getGoals
  /**
   * Creates a new appointment.
   *
   * @param appointment which shall be inserted into the underlying persistance layer. must not be
   *     null, id must be null
   * @return the given appointment for further usage
   * @throws PersistenceException if there are complications with the persitance layer
   */
  @Override
  public Appointment create(Appointment appointment) throws PersistenceException {
    LOGGER.info("Creating a new appointment in db.. " + appointment);
    try {
      if (appointment == null) {
        LOGGER.error("Create parameter (appointment) was null.");
        throw new PersistenceException("Appointment to be create must not be null");
      }

      Statement appointmentNextValStm = connection.createStatement();
      ResultSet rs_appointmentNextVal =
          appointmentNextValStm.executeQuery("SELECT NEXTVAL('appointment_seq')");
      rs_appointmentNextVal.next();
      appointment.setId(rs_appointmentNextVal.getInt(1));

      createStm.setInt(1, appointment.getId());
      createStm.setDate(2, new java.sql.Date(appointment.getDatum().getTime()));
      createStm.setInt(3, appointment.getSession_id());
      createStm.setInt(4, appointment.getUser_id());
      createStm.setBoolean(5, appointment.getIsTrained());
      createStm.setBoolean(6, appointment.getIsDeleted());

      createStm.execute();
    } catch (SQLException e) {
      LOGGER.error("Failed to create record into appointment table. - " + e.getMessage());
      throw new PersistenceException("Failed to create record into appointment table.", e);
    }

    LOGGER.info("Record successfully created in appointment table.");
    return appointment;
  }
Example #18
0
  public ValoresAtualizaJob retornaNovosValores(Connection conn, JobLote job) throws SQLException {

    PreparedStatement stmt = null;
    ResultSet rs = null;
    ValoresAtualizaJob obj = null;

    String sql =
        " select sum(qtd_transf) qtd_transf, sum(qtd_sucata) qtd_sucata, sum(hr_tot) hr_tot from joblote\n"
            + " where job = ? and operacao = ? ";

    stmt = conn.prepareStatement(sql);
    stmt.setString(1, job.getJob().trim().replace(".", ""));
    stmt.setInt(2, job.getOperNum());
    rs = stmt.executeQuery();

    if (rs.next()) {

      obj = new ValoresAtualizaJob();
      obj.setQtdTransf(rs.getDouble("qtd_transf"));
      obj.setQtdSucata(rs.getDouble("qtd_sucata"));
      obj.setHoraTotal(rs.getDouble("hr_tot"));
    }

    return obj;
  }
Example #19
0
  private Map<FileChecksum, FileContent> createFileContents(ResultSet resultSet)
      throws SQLException {
    Map<FileChecksum, FileContent> fileContents = new HashMap<FileChecksum, FileContent>();
    FileChecksum currentFileChecksum = null;

    while (resultSet.next()) {
      FileChecksum fileChecksum = FileChecksum.parseFileChecksum(resultSet.getString("checksum"));
      FileContent fileContent = null;

      if (currentFileChecksum != null && currentFileChecksum.equals(fileChecksum)) {
        fileContent = fileContents.get(fileChecksum);
      } else {
        fileContent = new FileContent();

        fileContent.setChecksum(fileChecksum);
        fileContent.setSize(resultSet.getLong("size"));
      }

      ChunkChecksum chunkChecksum =
          ChunkChecksum.parseChunkChecksum(resultSet.getString("chunk_checksum"));
      fileContent.addChunk(chunkChecksum);

      fileContents.put(fileChecksum, fileContent);
      currentFileChecksum = fileChecksum;
    }

    return fileContents;
  }
Example #20
0
  private HashMap<String, String> getLoginInfo(
      String url, String db, String userName, String password) throws SQLException {
    Connection con = null;
    String driver = "com.mysql.jdbc.Driver";
    HashMap<String, String> info = new HashMap<String, String>();
    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url + db, userName, password);
      String selectStatement = "SELECT userId,userName FROM Users";
      Statement st = con.createStatement();
      ResultSet linksRecords = st.executeQuery(selectStatement);

      while (linksRecords.next()) {
        info.put(linksRecords.getString("userId"), linksRecords.getString("userName"));
      }
      linksRecords.close();
    } catch (SQLException s) {
      // System.out.println("SQL statement is not executed!\n"+s.getMessage());
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        con.close();
      } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return info;
  }
Example #21
0
  /**
   * @param process_id the process id a worker will work on
   * @param worker_id the hostname of the worker
   * @return a boolean if the registration was succesful
   * @throws SQLException
   * @throws IllegalArgumentException
   */
  public boolean resetOnChain(int process_id) throws SQLException, IllegalArgumentException {
    boolean created = false;
    try (AutoCloseableDBConnection c = new AutoCloseableDBConnection(false);
        PreparedStatement queryProcess =
            c.prepareStatement("SELECT chain_id FROM chain_activities WHERE process_id=?");
        PreparedStatement updateWorker =
            c.prepareStatement(
                "UPDATE chain_activities SET worker_id=?, busy=0 WHERE (process_id=? AND chain_id=?)"); ) {
      int chain_id = -1;
      queryProcess.setInt(1, process_id);
      ResultSet executeQuery = queryProcess.executeQuery();
      if (executeQuery.next()) {
        chain_id = executeQuery.getInt("chain_id");

        updateWorker.setString(1, "-");
        updateWorker.setInt(2, process_id);
        updateWorker.setInt(3, chain_id);
        updateWorker.executeUpdate();
        created = true;
        c.commit();
      }
      //    ResultSet rs = updateWorker.getGeneratedKeys();
      return created;
    }
  }
Example #22
0
  private List<LinkCandidate> getLinksCandidates(
      String url, String db, String userName, String password) throws SQLException {
    // JDBCConnectionPool x=new SimpleJDBCConnectionPool("com.mysql.jdbc.Driver",
    // "jdbc:mysql://localhost:3306/", "hgf", "xxxxx");
    List<LinkCandidate> infoList = new ArrayList<LinkCandidate>();
    Connection con = null;
    String driver = "com.mysql.jdbc.Driver";
    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url + db, userName, password);
      String selectStatement = "SELECT * FROM Links";
      Statement st = con.createStatement();
      ResultSet linksRecords = st.executeQuery(selectStatement);

      while (linksRecords.next()) {
        // infoList.add(new
        // LinkCandidate(linksRecords.getString("sourceURI"),linksRecords.getString("destinationURI"), linksRecords.getString("relationMapping")));
      }
      linksRecords.close();
    } catch (SQLException s) {

    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        con.close();
      } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return infoList;
  }
Example #23
0
 public void ejbLoad() {
   BMPConnection bmp = getConnection();
   try {
     PreparedStatement ps =
         bmp.prepareStatement(
             "SELECT "
                 + "COD_RUO_SIC, NOM_RUO_SIC, DES_RUO_SIC "
                 + "FROM "
                 + "ANA_RUO_SIC_TAB "
                 + "WHERE "
                 + "COD_RUO_SIC=?");
     ps.setLong(1, COD_RUO_SIC);
     ResultSet rs = ps.executeQuery();
     if (rs.next()) {
       this.COD_RUO_SIC = rs.getLong("COD_RUO_SIC");
       this.NOM_RUO_SIC = rs.getString("NOM_RUO_SIC");
       this.DES_RUO_SIC = rs.getString("DES_RUO_SIC");
     } else {
       throw new NoSuchEntityException("Ruolo per la sicurezza con ID= non trovato");
     }
   } catch (Exception ex) {
     throw new EJBException(ex);
   } finally {
     bmp.close();
   }
 }
  public String ConectarBD(String... strings) {

    String ls_usuario = "COMERCIAL";
    String ls_clave = "COMERCIAL";
    String ls_sql = "select pvp from INV_ARTICULO where cod_barras ='" + strings[1] + "'";
    /* String ls_sql = "select pvp from INV_ARTICULO where cod_barras ='9788431681111'";*/

    try {
      Class.forName("oracle.jdbc.OracleDriver");
      conexion = DriverManager.getConnection(strings[0], ls_usuario, ls_clave);
      Statement estado = conexion.createStatement();
      resultado = (ResultSet) estado.executeQuery(ls_sql);
      while (resultado.next()) {
        ls_precio = "Precio: " + resultado.getString(1);
      }

      System.out.println("Conexion realizada " + ls_precio);

      resultado.close();
      estado.close();
      conexion.close();

    } catch (ClassNotFoundException e) {
      /*Toast.makeText(getApplicationContext(), "ERROR:" + e.getMessage(), Toast.LENGTH_SHORT).show();*/
      e.printStackTrace();
    } catch (SQLException e) {
      /*Toast.makeText(getApplicationContext(), "ERROR: " + e.getMessage(), Toast.LENGTH_SHORT).show();*/
      e.printStackTrace();
    }

    return ls_precio;
  }
Example #25
0
  private int insertPageContent(
      String text, int resultPageNumber, String searchEngineName, int crawlRecordId) {
    try {
      PreparedStatement pstmt =
          con.prepareStatement(
              "INSERT INTO pagecontent (htmlcontent, resultPageNumber, searchEngineName, crawlRecordId,queryText) VALUES (?,?,?,?,?);",
              Statement.RETURN_GENERATED_KEYS);
      pstmt.setString(1, text);
      pstmt.setInt(2, resultPageNumber);
      pstmt.setString(3, searchEngineName);
      pstmt.setInt(4, crawlRecordId);
      pstmt.setString(5, query);

      pstmt.executeUpdate();

      java.sql.ResultSet generatedKeys = pstmt.getGeneratedKeys();
      if (generatedKeys.next()) {
        return generatedKeys.getInt(1);
      }
      pstmt.close();

    } catch (Exception ex) {
      String a = "";
      String b = "";
    }
    return 0;
  }
  private boolean login(String[] part) {
    ResultSet rs = null;

    try {
      rs = beanOracle.selection("PASSWORD", "UTILISATEURS", "LOGIN = '" + part[1] + "'");
    } catch (SQLException e) {
      System.err.println(e.getStackTrace());
    }

    String pwd = null;

    try {
      if (!rs.next()) {
        SendMsg("ERR#Login invalide");
      } else pwd = rs.getString("PASSWORD");
    } catch (SQLException ex) {
      System.err.println(ex.getStackTrace());
    }

    if (pwd.equals(part[2])) {
      SendMsg("ACK");
      return true;
    } else SendMsg("ERR#Mot de passe incorrecte");

    return false;
  }
 private String[] getDeptsForBranch(String branch, boolean isInvoicingDept) throws Exception {
   String[] departmentArray = null;
   PreparedStatement getDepartmentPstmt = null;
   ResultSet rs = null;
   Connection connection = null;
   int count = 0;
   try {
     connection = getConnection();
     getDepartmentPstmt =
         connection.prepareStatement(
             PartyLovQueries.getDepartmentQuery,
             ResultSet.TYPE_SCROLL_INSENSITIVE,
             ResultSet.CONCUR_READ_ONLY);
     getDepartmentPstmt.setString(1, branch);
     getDepartmentPstmt.setInt(2, isInvoicingDept ? 1 : 0);
     rs = getDepartmentPstmt.executeQuery();
     while (rs.next()) count++;
     departmentArray = new String[count];
     rs.beforeFirst();
     count = 0;
     while (rs.next()) {
       departmentArray[count] = rs.getString("DEPARTMENT");
       count++;
     }
   } finally {
     ConnectionUtil.closeConnection(connection, getDepartmentPstmt, rs);
   }
   return departmentArray;
 }
Example #28
0
  @Override
  protected GetRequest getContainerRequest(
      Connection _con,
      long ID,
      Long NEXTJOBID,
      long CREATIONTIME,
      long LIFETIME,
      int STATE,
      String ERRORMESSAGE,
      SRMUser user,
      String SCHEDULERID,
      long SCHEDULER_TIMESTAMP,
      int NUMOFRETR,
      int MAXNUMOFRETR,
      long LASTSTATETRANSITIONTIME,
      Long CREDENTIALID,
      int RETRYDELTATIME,
      boolean SHOULDUPDATERETRYDELTATIME,
      String DESCRIPTION,
      String CLIENTHOST,
      String STATUSCODE,
      GetFileRequest[] fileRequests,
      ResultSet set,
      int next_index)
      throws SQLException {

    String sqlStatementString =
        "SELECT PROTOCOL FROM " + getProtocolsTableName() + " WHERE RequestID=" + ID;
    Statement sqlStatement = _con.createStatement();
    logger.debug("executing statement: " + sqlStatementString);
    ResultSet fileIdsSet = sqlStatement.executeQuery(sqlStatementString);
    List<String> protocols = new ArrayList<>();
    while (fileIdsSet.next()) {
      protocols.add(fileIdsSet.getString(1));
    }
    sqlStatement.close();
    Job.JobHistory[] jobHistoryArray = getJobHistory(ID, _con);
    return new GetRequest(
        ID,
        NEXTJOBID,
        CREATIONTIME,
        LIFETIME,
        STATE,
        ERRORMESSAGE,
        user,
        SCHEDULERID,
        SCHEDULER_TIMESTAMP,
        NUMOFRETR,
        MAXNUMOFRETR,
        LASTSTATETRANSITIONTIME,
        jobHistoryArray,
        CREDENTIALID,
        fileRequests,
        RETRYDELTATIME,
        SHOULDUPDATERETRYDELTATIME,
        DESCRIPTION,
        CLIENTHOST,
        STATUSCODE,
        protocols);
  }
Example #29
0
 /**
  * Get Restriction Lines
  *
  * @param reload reload data
  * @return array of lines
  */
 public MGoalRestriction[] getRestrictions(boolean reload) {
   if (m_restrictions != null && !reload) return m_restrictions;
   ArrayList<MGoalRestriction> list = new ArrayList<MGoalRestriction>();
   //
   String sql =
       "SELECT * FROM PA_GoalRestriction "
           + "WHERE PA_Goal_ID=? AND IsActive='Y' "
           + "ORDER BY Org_ID, C_BPartner_ID, M_Product_ID";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, get_Trx());
     pstmt.setInt(1, getPA_Goal_ID());
     rs = pstmt.executeQuery();
     while (rs.next()) list.add(new MGoalRestriction(getCtx(), rs, get_Trx()));
   } catch (Exception e) {
     log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   //
   m_restrictions = new MGoalRestriction[list.size()];
   list.toArray(m_restrictions);
   return m_restrictions;
 } //	getRestrictions
  public String retornaResp(int tipo, int id) throws SQLException {
    if (tipo == 0) {

      sql = "select descricao from grupo where idgrupo = ?";
      if (!FabricaConexoes.verificaConexao()) FabricaConexoes.getConexao();
      stm = FabricaConexoes.returnStatement(sql);
      stm.setInt(1, id);
      rs = FabricaConexoes.returnResult(stm);
      rs.next();
      return rs.getString("Descricao");

    } else if (tipo == 1) {
      sql = "select nome from usuario where idusuario = ?";
      if (!FabricaConexoes.verificaConexao()) FabricaConexoes.getConexao();
      stm = FabricaConexoes.returnStatement(sql);
      stm.setInt(1, id);
      rs = FabricaConexoes.returnResult(stm);
      rs.next();
      return rs.getString("nome");
    } else if (tipo == 2) {
      return "Destinado";
    } else {
      return "";
    }
  }