public void eliminarConfiguracion(int usuario) throws DAOException {
    log.info("eliminarConfiguracion(int usuario)");
    Connection cons = null;
    PreparedStatement stmt = null;
    try {
      String query = "DELETE FROM cv_servicio_usuario WHERE IDUSUARIO=?";
      cons = dataSource.getConnection();
      stmt = cons.prepareStatement(query);
      stmt.setInt(1, usuario);
      stmt.executeUpdate();

      query =
          "insert into cv_servicio_usuario(idusuario,idservicio,columna,posicion,visible,estado) "
              + "select ?,idservicio,columna,posicion,usuario_visible,usuario_estado "
              + "from cv_servicio_maestro";
      stmt = cons.prepareStatement(query);
      stmt.setInt(1, usuario);
      stmt.executeUpdate();
    } catch (SQLException e) {
      log.info(e.toString());
      throw new DAOException(e.toString());
    } catch (Exception e) {
      log.info(e.toString());
      throw new DAOException(e.toString());
    } finally {
      closeStatement(stmt);
      closeConnection(cons);
    }
  }
  @Override
  public void updatePRICE_nNO(int change_PRICE, int need_orderproductNO) throws Exception {

    Connection conn = null;
    PreparedStatement pstmt = null;

    try {
      conn = getConnection();
      pstmt =
          conn.prepareStatement(
              "UPDATE " + "ORDER_PRODUCT " + "SET OP_PRICE=?  " + "WHERE OP_NO=?");
      pstmt.setInt(1, change_PRICE);
      pstmt.setInt(2, need_orderproductNO);

      pstmt.executeUpdate();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (pstmt != null)
        try {
          pstmt.close();
        } catch (SQLException se) {
        }
      if (conn != null)
        try {
          conn.close();
        } catch (SQLException se) {
        }
    }
  }
  public boolean updateModuleVedioMapDetail(ModuleVedioMapVo vo) throws LmsDaoException {
    System.out.println("id =" + vo.getVedioId());
    boolean status = true;

    // Database connection start
    Connection conn = null;
    PreparedStatement stmt = null;
    try {

      conn = getConnection();
      String sql = "UPDATE module_video_map set VEDIO_ID=?\n" + "    WHERE MODULE_VEDIO_MAP=?";
      stmt = conn.prepareStatement(sql);
      stmt.setInt(1, vo.getVedioId());
      stmt.setInt(2, vo.getModuleVedioMap());

      stmt.executeUpdate();
      System.out.println("updated records into the table...");

    } catch (SQLException e) {
      System.out.println("getUserCourseMapDetail # " + e);
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("getUserCourseMapDetail # " + e);
      e.printStackTrace();
    } finally {
      closeResources(conn, stmt, null);
    }

    System.out.println("Successfully updated....");
    return status;
    // End writting code to save into database
  }
Exemple #4
0
  // Metodo para alteração de dados
  public String alterar(Evento evento) {
    String sql = "update evento set ";
    sql += " descricao=?";
    sql += " where dia=? and mes=? and ano=?";
    Connection con = Conexao.abrirConexao();

    try {
      PreparedStatement pst = con.prepareStatement(sql);
      pst.setString(1, evento.getDescricao());
      pst.setInt(2, evento.getDia());
      pst.setInt(3, evento.getMes());
      pst.setInt(4, evento.getAno());

      if ((pst.executeUpdate() > 0)) {
        Conexao.fecharConexao(con);
        return "Registro alterado com sucesso.";
      } else {
        Conexao.fecharConexao(con);
        return "Erro ao alterar registro";
      }

    } catch (SQLException e) {
      Conexao.fecharConexao(con);
      return e.getMessage();
    }
  }
Exemple #5
0
  public int addDevice(Object o) {
    int rowsAdded = 0;
    try {
      Connection connect = conn.use();

      Device dev = (Device) o;

      String SQL =
          "INSERT INTO device(Brand, Model, Serial_Number, Computer_Name, Location, Asset_Tag, Cost, Start_Date, End_Date, Term) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

      PreparedStatement ps = connect.prepareStatement(SQL);

      ps.setString(1, dev.getBrand());
      ps.setString(2, dev.getModel());
      ps.setString(3, dev.getSerialNumber());
      ps.setString(4, dev.getComputerName());
      ps.setString(5, dev.getLocation());
      ps.setString(6, dev.getAssetTag());
      ps.setInt(7, dev.getCost());
      ps.setDate(8, dev.getStartDate());
      ps.setDate(9, dev.getEndDate());
      ps.setInt(10, dev.getTerm());

      rowsAdded = ps.executeUpdate();

      ps.close();
      conn.release(connect);
    } catch (SQLException ex) {
      System.out.println("Error in add device: ");
      Logger.getLogger(DeviceBroker.class.getName()).log(Level.SEVERE, null, ex);
    }

    return rowsAdded;
  }
Exemple #6
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;
    }
  }
Exemple #7
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;
  }
  public int verificaTipo(int idproc, int chave) {
    /*
     *  tipos de retorno
     *  0 - Atividade
     *  1 - Finalização
     *  2 - Link
     *  3 - erro
     *  4 - Raiz
     * */
    if (chave == 0) return 4;
    sql = "SELECT * FROM processo_atividade WHERE IDproc = ? AND chave = ?";
    try {
      if (!FabricaConexoes.verificaConexao()) FabricaConexoes.getConexao();
      stm = FabricaConexoes.returnStatement(sql);
      stm.setInt(1, idproc);
      stm.setInt(2, chave);
      rs = FabricaConexoes.returnResult(stm);
      rs.next();

      if (rs.getInt("idfin") == 0) {
        return 0;
      } else if (rs.getInt("idfin") != 0 && rs.getInt("link") == 0) {
        return 1;
      } else if (rs.getInt("idfin") != 0 && rs.getInt("link") != 0) {
        return 2;
      } else {
        return 3;
      }

    } catch (SQLException s) {
      JOptionPane.showMessageDialog(null, s.getMessage(), "Erro", 0);
      return 3;
    }
  }
  /**
   * Updating a given appointment with new values in the persistence.
   *
   * @param appointment which shall be updated must not be null, id must not be null and must not be
   *     changed
   * @return given appointment with updated values
   * @throws PersistenceException if there are complications with the persitance layer
   */
  @Override
  public Appointment update(Appointment appointment) throws PersistenceException {
    LOGGER.info("Updating record in appointment table..");
    try {
      if (appointment == null) {
        LOGGER.error("Update parameter (appointment) was null.");
        throw new PersistenceException("Appointment to be updated must not be null");
      }

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

      updateStm.executeUpdate();

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

    LOGGER.info("Record successfully updated in appointment table. " + appointment);
    return appointment;
  }
Exemple #10
0
 /**
  * Method updateOwnerInDB.
  *
  * @param clan Clan
  */
 private void updateOwnerInDB(Clan clan) {
   _owner = clan;
   Connection con = null;
   PreparedStatement statement = null;
   try {
     con = DatabaseFactory.getInstance().getConnection();
     statement =
         con.prepareStatement("UPDATE clan_data SET hasFortress=0 WHERE hasFortress=? LIMIT 1");
     statement.setInt(1, getId());
     statement.execute();
     DbUtils.close(statement);
     if (clan != null) {
       statement =
           con.prepareStatement("UPDATE clan_data SET hasFortress=? WHERE clan_id=? LIMIT 1");
       statement.setInt(1, getId());
       statement.setInt(2, getOwnerId());
       statement.execute();
       clan.broadcastClanStatus(true, false, false);
     }
   } catch (Exception e) {
     _log.error("", e);
   } finally {
     DbUtils.closeQuietly(con, statement);
   }
 }
 /**
  * Adds a feature to the Account attribute of the ProjectUtils class
  *
  * @param db The feature to be added to the Account attribute
  * @param projectId The feature to be added to the Account attribute
  * @param orgId The feature to be added to the Account attribute
  * @throws SQLException Description of the Exception
  */
 public static synchronized void addAccount(Connection db, int projectId, int orgId)
     throws SQLException {
   OrganizationList organizationList = new OrganizationList();
   organizationList.setProjectId(projectId);
   organizationList.setOrgId(orgId);
   organizationList.buildList(db);
   if (organizationList.size() == 0) {
     int i = 0;
     int seqId = DatabaseUtils.getNextSeq(db, "project_accounts_id_seq");
     PreparedStatement pst =
         db.prepareStatement(
             "INSERT INTO project_accounts "
                 + "("
                 + (seqId > -1 ? "id, " : "")
                 + "project_id, org_id) "
                 + "VALUES ("
                 + (seqId > -1 ? "?, " : "")
                 + "?, ?) ");
     if (seqId > -1) {
       pst.setInt(++i, seqId);
     }
     pst.setInt(++i, projectId);
     pst.setInt(++i, orgId);
     pst.execute();
     pst.close();
   }
 }
 @Override
 protected void map(Project project, PreparedStatement stmt) throws SQLException {
   // id
   stmt.setInt(1, seq.get(Sequence.PROJECT, project.id));
   // ref_id
   stmt.setString(2, project.id);
   // name
   stmt.setString(3, project.name);
   // description
   stmt.setString(4, project.description);
   // f_category
   if (Category.isNull(project.categoryid)) stmt.setNull(5, java.sql.Types.INTEGER);
   else stmt.setInt(5, seq.get(Sequence.CATEGORY, project.categoryid));
   // creation_date
   stmt.setDate(6, project.creationdate);
   // functional_unit
   stmt.setString(7, project.functionalunit);
   // last_modification_date
   stmt.setDate(8, project.lastmodificationdate);
   // goal
   stmt.setString(9, project.goal);
   // f_author
   if (project.f_author == null) stmt.setNull(10, java.sql.Types.INTEGER);
   else stmt.setInt(10, seq.get(Sequence.ACTOR, project.f_author));
   // f_impact_method
   stmt.setNull(11, java.sql.Types.INTEGER);
   // f_nwset
   stmt.setNull(12, java.sql.Types.INTEGER);
   stmt.setLong(13, System.currentTimeMillis());
   stmt.setLong(14, 4294967296L);
 }
 public static void contents(Integer convID, Integer fromMsgID) {
   if (fromMsgID == null) {
     fromMsgID = 0;
   }
   Connection c = DB.getConnection();
   try {
     PreparedStatement stmt =
         c.prepareStatement(
             "select M.id, UR.name, U.id, M.contents, M.timeSent from `Person` as U, `Conversations` as C, `Messages` as M, `UserRoles` as UR "
                 + "where UR.id = U.role_id and C.id=M.conversation_id and U.id=M.user_id and C.id = ? and M.id>? "
                 + "ORDER BY M.id");
     stmt.setInt(1, convID);
     stmt.setInt(2, fromMsgID);
     ResultSet rs = stmt.executeQuery();
     rs.beforeFirst();
     ArrayList<ChatMessage> msgdata = new ArrayList<ChatMessage>();
     Integer maxID = fromMsgID;
     while (rs.next()) {
       ChatMessage msg =
           new ChatMessage(
               rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5));
       if (msg.name.equals(Security.connected())) {
         msg.name = "You";
         msg.role = "";
       }
       maxID = Math.max(maxID, msg.id);
       msgdata.add(msg);
     }
     render(msgdata, maxID);
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
 /**
  * @user admin
  * @param CandidateAction object
  * @return true if candidate information added in database else false Generates a unique candidate
  *     id for each candidate and fills the candidate information into the database
  */
 public boolean addCandidate(CandidateAction ca) {
   conn = Connect.createConn();
   try {
     int j = genCandidateid();
     query = "insert into its_candidateinformation_tbl values(?,?,?,?,?,?,?,?,?,?,?, default)";
     pstmt = conn.prepareStatement(query);
     pstmt.setInt(1, j);
     pstmt.setString(2, ca.getFname());
     pstmt.setString(3, ca.getLname());
     pstmt.setString(4, ca.getDegree());
     pstmt.setString(5, ca.getStream());
     pstmt.setString(6, ca.getPskillset());
     pstmt.setString(7, ca.getSskillset());
     pstmt.setInt(8, ca.getExperience());
     pstmt.setString(9, ca.getDesignation());
     pstmt.setString(10, ca.getJoining());
     pstmt.setString(11, ca.getLocation());
     int i = pstmt.executeUpdate();
     if (i == 1) {
       message = "Candidate successfully added. Candidate ID is:" + j;
       return true;
     }
     if (i == 0) {
       message = "Candidate could not be added";
       return false;
     }
   } catch (SQLException e) {
     message = "exception occured ";
     System.out.println("Cannot add data into candidate table " + e);
     return false;
   } finally {
     closeConn();
   }
   return false;
 }
Exemple #15
0
  @Override
  public void newIndividualProperty(
      String propertyName,
      int schemaId,
      String tableName,
      String propertyValue,
      String className,
      String classValue)
      throws DataSourceConnectionException, SQLException {
    log.debug(
        "Creating a new individual individual of URI "
            + propertyName
            + "with value "
            + propertyValue);
    Connection con = null;
    PreparedStatement pst = null;

    con = factory.getConnection();
    pst = con.prepareStatement(SQL_NEW_INDIVIDUAL_PROPERTY);
    pst.setInt(1, schemaId);
    pst.setString(2, propertyName);
    pst.setString(3, propertyValue);
    pst.setInt(4, schemaId);
    pst.setString(5, className);
    pst.setString(6, classValue);

    if ((!this.existsIndividualProperty(
            schemaId, propertyName, propertyValue, className, classValue))
        && (this.exists(tableName, schemaId, propertyName))) pst.executeUpdate();

    con.commit();
  }
Exemple #16
0
  // Metodo para excluir dados
  public String excluir(Evento evento) {
    String sql = "delete from evento";
    sql += " where dia=? and mes=? and ano=?";
    Connection con = Conexao.abrirConexao();

    try {
      PreparedStatement pst = con.prepareStatement(sql);

      pst.setInt(1, evento.getDia());
      pst.setInt(2, evento.getMes());
      pst.setInt(3, evento.getAno());

      if (pst.executeUpdate() > 0) {
        Conexao.fecharConexao(con);
        return "Registro excluido com sucesso.";
      } else {
        Conexao.fecharConexao(con);
        return "Erro ao excluir registro.";
      }

    } catch (SQLException e) {
      Conexao.fecharConexao(con);
      return e.getMessage();
    }
  }
  public void saveModuleVedioMapDetail(ModuleVedioMapVo vo) throws LmsDaoException {
    // Database connection start
    Connection conn = null;
    PreparedStatement stmt = null;
    try {

      conn = getConnection();
      String sql = "INSERT INTO module_video_map(VEDIO_ID, MODULE_VEDIO_MAP)  VALUES(?, ?)";
      stmt = conn.prepareStatement(sql);
      stmt.setInt(1, vo.getVedioId());
      stmt.setInt(2, vo.getModuleVedioMap());

      // ...
      stmt.executeUpdate();
      System.out.println("Inserted records into the table...");

    } catch (SQLException se) {
      System.out.println("getUserCourseMapDetail # " + se);
      se.printStackTrace();
    } catch (Exception e) {
      System.out.println("getUserCourseMapDetail # " + e);
      e.printStackTrace();
    } finally {
      closeResources(conn, stmt, null);
    }

    System.out.println("Successfully saved....");
  }
  /**
   * @param conn
   * @param fingerprint
   * @param sampleID
   * @return
   * @throws SQLException
   */
  private static void insertSampleSet(Connection conn, Fingerprint fingerprint, Integer sampleID)
      throws SQLException {
    if (fingerprint.getSampleSetID() == null) {
      /*
       * Insert whole new SampleSetID.
       */
      String query = "INSERT INTO `SampleSets`(`SampleID`) VALUES(?);";
      PreparedStatement insertSampleSet =
          conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);

      insertSampleSet.setInt(1, sampleID);
      insertSampleSet.execute();

      ResultSet rs = insertSampleSet.getGeneratedKeys();
      if (rs.next()) {
        fingerprint.setSampleSetID(rs.getInt(1));
      }
      rs.close();
      insertSampleSet.close();
    } else {
      /*
       * Insert new SampleID for existing SampleSetID.
       */
      String query = "INSERT INTO `SampleSets`(`SampleSetID`,`SampleID`) VALUES(?, ?);";
      PreparedStatement insertSampleSet = conn.prepareStatement(query);

      insertSampleSet.setInt(1, fingerprint.getSampleSetID());
      insertSampleSet.setInt(2, sampleID);
      insertSampleSet.execute();

      insertSampleSet.close();
    }
  }
  /** Returns event_id of newly created logging entry. */
  private Integer logEvent(IClient client, String eventText, InputStream logFileSteam, Connection c)
      throws SQLException {
    PreparedStatement stmt = null;
    int id = 0;
    try {
      long longId = getSequenceId("seq_client_log_event_ids", c);
      if (longId > Integer.MAX_VALUE) {
        // dat_client_log_events.event_id is a 32 bit integer numeric type.

        // this is a bad problem; ensure it's logged; don't depend on whoever's catching
        // the exception.
        m_logger.log("seq_client_log_event_ids overflowed").error();
        throw new IllegalStateException("seq_client_log_event_ids overflowed.");
      }
      id = (int) longId;
      stmt =
          c.prepareStatement(
              "insert into dat_client_log_events "
                  + "(event_id, customer_id, user_id, event_time, description, has_log_file) "
                  + "values "
                  + "(?, ?, ?, current_timestamp, ?, ?)");

      stmt.setInt(1, id);
      stmt.setInt(2, client.getCustomerId());
      stmt.setInt(3, client.getUserId());
      stmt.setString(4, eventText);
      stmt.setInt(5, logFileSteam == null ? 0 : 1);
      if (stmt.executeUpdate() != 1) {
        throw new SQLException("Can't insert client event for " + client);
      }
    } finally {
      DbUtils.safeClose(stmt);
    }
    return new Integer(id);
  }
Exemple #20
0
 /**
  * Obtener un precio de producto a partir del producto y de la versión de la tarifa
  *
  * @param ctx contexto
  * @param priceListVersionID id de la versión de tarifa
  * @param productID id del producto
  * @param trxName nombre de la transacción en curso
  * @return precio de producto o null si no existe
  */
 public static MProductPrice get(
     Properties ctx, int priceListVersionID, int productID, String trxName) {
   String sql =
       "SELECT * FROM " + Table_Name + " WHERE m_pricelist_version_id = ? and m_product_id = ?";
   MProductPrice price = null;
   PreparedStatement ps = null;
   ResultSet rs = null;
   try {
     ps = DB.prepareStatement(sql, trxName);
     ps.setInt(1, priceListVersionID);
     ps.setInt(2, productID);
     rs = ps.executeQuery();
     if (rs.next()) {
       price = new MProductPrice(ctx, rs, trxName);
     }
   } catch (Exception e) {
     s_log.severe("Error finding product price, method get. " + e.getMessage());
   } finally {
     try {
       if (ps != null) ps.close();
       if (rs != null) rs.close();
     } catch (Exception e2) {
       s_log.severe("Error finding product price, method get. " + e2.getMessage());
     }
   }
   return price;
 }
  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 "";
    }
  }
    @Override
    protected Profile createConcrete() throws SQLException {
      PreparedStatement insert =
          conn.prepareStatement(
              "INSERT INTO profile (id, surname,givenName, user, organization) VALUES (?,?,?,?,?)");
      insert.setInt(1, input.getId());
      insert.setString(2, input.getSurname());
      insert.setString(3, input.getGivenName());
      if (input.getUserId() == null) {
        insert.setNull(4, Types.INTEGER);
      } else {
        insert.setInt(4, input.getUserId());
      }
      insert.setInt(5, input.getOrganizationId());

      int insertCount = insert.executeUpdate();
      if (insertCount != 1) {
        throw new GeneralException("Unexpected insert count: " + insertCount);
      }

      if (input.getUserId() != null) {
        authorizationPersistenceHelper.grantToCollectionsInOrganization(
            conn, ROLE_ADMIN, input.getOrganizationId(), input.getId());
      }

      return input;
    }
  /**
   * 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;
  }
 ////// Renombrar a grabarPortalMaestro()
 public void guardarPortalGestionar(Collection<String[]> array) throws DAOException {
   log.info("guardarPortalGestionar(Collection<String[]> array)");
   Connection cons = null;
   PreparedStatement stmt = null;
   try {
     String query = "update cv_servicio_maestro set columna=? , posicion=? where idservicio=?";
     cons = dataSource.getConnection();
     stmt = cons.prepareStatement(query);
     int posicion = 0;
     for (String[] item : array) {
       stmt.setInt(1, posicion++);
       for (int u = 0; u < item.length; u++) {
         stmt.setInt(2, u);
         stmt.setString(3, item[u]);
         stmt.executeUpdate();
       }
     }
   } catch (SQLException e) {
     log.error(e);
     throw new DAOException(e.toString());
   } catch (Exception e) {
     log.error(e);
     throw new DAOException(e.toString());
   } finally {
     closeStatement(stmt);
     closeConnection(cons);
   }
 }
Exemple #25
0
 /**
  * @param chain_id
  * @param processIds the ids of the processes part of this chain
  * @param chainID the chainID for the processing chain
  * @return the success of creating
  * @throws SQLException
  */
 public boolean addChain(int run_id, int chain_id, Collection<Integer> processIds)
     throws SQLException {
   boolean created;
   try (AutoCloseableDBConnection c = new AutoCloseableDBConnection(false);
       PreparedStatement queryWorker =
           c.prepareStatement("SELECT chain_id FROM chain_activities WHERE chain_id=?");
       PreparedStatement updateWorker =
           c.prepareStatement(
               "INSERT INTO chain_activities(run_id,chain_id,process_id) VALUES(?,?,?)",
               Statement.RETURN_GENERATED_KEYS); ) {
     queryWorker.setInt(1, chain_id);
     if (!queryWorker.executeQuery().next()) {
       for (int aProcessId : processIds) {
         updateWorker.setInt(1, run_id);
         updateWorker.setInt(2, chain_id);
         updateWorker.setInt(3, aProcessId);
         updateWorker.addBatch();
       }
       updateWorker.executeBatch();
       //    ResultSet rs = updateWorker.getGeneratedKeys();
       created = true;
       c.commit();
     } else {
       created = false;
     }
   }
   return created;
 }
Exemple #26
0
 private void initNpcCommanders() {
   _npcCommanders.clear();
   try (Connection con = ConnectionFactory.getInstance().getConnection();
       PreparedStatement ps =
           con.prepareStatement(
               "SELECT id, npcId, x, y, z, heading FROM fort_spawnlist WHERE fortId = ? AND spawnType = ? ORDER BY id")) {
     ps.setInt(1, getResidenceId());
     ps.setInt(2, 1);
     try (ResultSet rs = ps.executeQuery()) {
       while (rs.next()) {
         final L2Spawn spawnDat = new L2Spawn(rs.getInt("npcId"));
         spawnDat.setAmount(1);
         spawnDat.setX(rs.getInt("x"));
         spawnDat.setY(rs.getInt("y"));
         spawnDat.setZ(rs.getInt("z"));
         spawnDat.setHeading(rs.getInt("heading"));
         spawnDat.setRespawnDelay(60);
         _npcCommanders.add(spawnDat);
       }
     }
   } catch (Exception e) {
     // problem with initializing spawn, go to next one
     _log.log(
         Level.WARNING,
         "Fort "
             + getResidenceId()
             + " initNpcCommanders: Spawn could not be initialized: "
             + e.getMessage(),
         e);
   }
 }
    @Override
    protected ProfileSummary retrieveConcrete() throws SQLException {
      PreparedStatement select =
          conn.prepareStatement(
              "SELECT p.id, p.organization, e.version, p.surname, p.givenName, p.user, "
                  + "o.name, IF(acl.acl_object_identity IS NOT NULL, TRUE, FALSE) AS isAdmin "
                  + "FROM profile p "
                  + "JOIN organization o ON p.organization=o.id "
                  + "JOIN systemEntity e ON p.id=e.id "
                  + "LEFT OUTER JOIN acl_entry acl ON p.id=acl.sid AND p.organization=acl.acl_object_identity"
                  + " AND acl.mask=16 "
                  + "WHERE p.user=? AND p.organization=?");
      select.setInt(1, userId);
      select.setInt(2, input);

      ResultSet results = select.executeQuery();
      if (!results.next()) {
        return null;
      }

      Profile profile = new Profile(results.getInt(1), results.getInt(2), results.getInt(3));
      profile.setSurname(results.getString(4));
      profile.setGivenName(results.getString(5));
      profile.setUserId(results.getInt(6));
      ProfileSummary profileSummary =
          new ProfileSummary(profile, results.getString(7), results.getBoolean(8));

      results.close();
      select.close();

      return profileSummary;
    }
Exemple #28
0
 public int updateAssignToNode(String node, int i, int numNodes, long maxtime)
     throws DatabaseException {
   if (__log.isDebugEnabled())
     __log.debug(
         "updateAsssignToNode node=" + node + " " + i + "/" + numNodes + " maxtime=" + maxtime);
   Connection con = null;
   PreparedStatement ps = null;
   try {
     con = getConnection();
     if (_dialect == Dialect.SQLSERVER) {
       ps = con.prepareStatement(UPGRADE_JOB_SQLSERVER);
     } else if (_dialect == Dialect.DB2) {
       ps = con.prepareStatement(UPGRADE_JOB_DB2);
     } else if (_dialect == Dialect.SYBASE) {
       ps = con.prepareStatement(UPGRADE_JOB_SYBASE);
     } else if (_dialect == Dialect.SYBASE12) {
       ps = con.prepareStatement(UPGRADE_JOB_SYBASE12);
     } else {
       ps = con.prepareStatement(UPGRADE_JOB_DEFAULT);
     }
     ps.setString(1, node);
     ps.setInt(2, numNodes);
     ps.setInt(3, i);
     ps.setLong(4, maxtime);
     return ps.executeUpdate();
   } catch (SQLException se) {
     throw new DatabaseException(se);
   } finally {
     close(ps);
     close(con);
   }
 }
    @Override
    public Void process() {
      try {
        PreparedStatement deleteProfile = conn.prepareStatement("DELETE FROM profile WHERE id = ?");
        deleteProfile.setInt(1, input);
        deleteProfile.executeUpdate();

        PreparedStatement deleteEntity = conn.prepareStatement("DELETE FROM entity WHERE id=?");
        deleteEntity.setInt(1, input);
        int deleteCount = deleteEntity.executeUpdate();
        if (deleteCount != 1) {
          throw new GeneralException("Unexpected insert count: " + deleteCount);
        }

        PreparedStatement deleteSystemEntity =
            conn.prepareStatement("DELETE FROM systemEntity WHERE id=?");
        deleteSystemEntity.setInt(1, input);
        deleteCount = deleteSystemEntity.executeUpdate();
        if (deleteCount != 1) {
          throw new GeneralException("Unexpected insert count: " + deleteCount);
        }
      } catch (SQLException e) {
        throw new GeneralException(e);
      }

      return null;
    }
Exemple #30
0
 private void initNpcs() {
   try (Connection con = ConnectionFactory.getInstance().getConnection();
       PreparedStatement ps =
           con.prepareStatement(
               "SELECT * FROM fort_spawnlist WHERE fortId = ? AND spawnType = ?")) {
     ps.setInt(1, getResidenceId());
     ps.setInt(2, 0);
     try (ResultSet rs = ps.executeQuery()) {
       while (rs.next()) {
         L2Spawn spawnDat = new L2Spawn(rs.getInt("npcId"));
         spawnDat.setAmount(1);
         spawnDat.setX(rs.getInt("x"));
         spawnDat.setY(rs.getInt("y"));
         spawnDat.setZ(rs.getInt("z"));
         spawnDat.setHeading(rs.getInt("heading"));
         spawnDat.setRespawnDelay(60);
         SpawnTable.getInstance().addNewSpawn(spawnDat, false);
         spawnDat.doSpawn();
         spawnDat.startRespawn();
       }
     }
   } catch (Exception e) {
     _log.log(
         Level.WARNING,
         "Fort "
             + getResidenceId()
             + " initNpcs: Spawn could not be initialized: "
             + e.getMessage(),
         e);
   }
 }