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;
    }
  }
Ejemplo n.º 2
1
  public boolean savePassword(String password) {
    if (passwordExist()) {
      _log.warning(
          "[SecondaryPasswordAuth]" + _activeClient.getAccountName() + " forced savePassword");
      _activeClient.closeNow();
      return false;
    }

    if (!validatePassword(password)) {
      _activeClient.sendPacket(new Ex2ndPasswordAck(0, Ex2ndPasswordAck.WRONG_PATTERN));
      return false;
    }

    password = cryptPassword(password);

    try (Connection con = DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement = con.prepareStatement(INSERT_PASSWORD)) {
      statement.setString(1, _activeClient.getAccountName());
      statement.setString(2, VAR_PWD);
      statement.setString(3, password);
      statement.execute();
    } catch (Exception e) {
      _log.log(Level.SEVERE, "Error while writing password.", e);
      return false;
    }
    _password = password;
    return true;
  }
Ejemplo n.º 3
0
 public boolean guardarUsuario() {
   boolean resp = false;
   try {
     // Realizar consulta INSERT
     String sql =
         "INSERT INTO usuarios(nombres,apellidos, nacimiento,identificador, tipo, correo, telefono, estado_usuario, nick, contraseña, materia) "
             + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)";
     PreparedStatement cmd = cn.prepareStatement(sql);
     // Llenar los parámetros
     cmd.setString(1, nombres);
     cmd.setString(2, apellidos);
     cmd.setString(3, nacimiento);
     cmd.setString(4, identificador);
     cmd.setString(5, tipo);
     cmd.setString(6, correo);
     cmd.setString(7, telefono);
     cmd.setBoolean(8, estado);
     cmd.setString(9, usuario);
     cmd.setString(10, contraseña);
     cmd.setString(11, materia);
     // Si da error devuelve 1, caso contrario 0
     // Tomar en cuenta el "!" de negación
     if (!cmd.execute()) {
       resp = true;
     }
     //        cmd.close();
     //        cn.close();
   } catch (Exception e) {
     System.out.println(e.toString());
   }
   return resp;
 }
 public static void insertCountry(Connection conn, String name, String abbrev)
     throws SQLException {
   PreparedStatement stmt = conn.prepareStatement("INSERT INTO countries VALUES (NULL, ?, ?)");
   stmt.setString(1, name);
   stmt.setString(2, abbrev);
   stmt.execute();
 }
Ejemplo n.º 5
0
  private void setParam(PreparedStatement pst, Object param, int i) throws SQLException {

    if (param instanceof Integer) {
      int value = ((Integer) param).intValue();
      pst.setInt(i + 1, value);
    } else if (param instanceof String) {
      String s = (String) param;
      pst.setString(i + 1, s);
    } else if (param instanceof Double) {
      double d = ((Double) param).doubleValue();
      pst.setDouble(i + 1, d);
    } else if (param instanceof Float) {
      float f = ((Float) param).floatValue();
      pst.setFloat(i + 1, f);
    } else if (param instanceof Long) {
      long l = ((Long) param).longValue();
      pst.setLong(i + 1, l);
    } else if (param instanceof Boolean) {
      boolean b = ((Boolean) param).booleanValue();
      pst.setBoolean(i + 1, b);
    } else if (param instanceof Date) {
      Date d = (Date) param;
      pst.setDate(i + 1, d);
    } else if (param instanceof Timestamp) {
      Timestamp d = (Timestamp) param;
      pst.setTimestamp(i + 1, d);
    } else if (param instanceof Object) {
      pst.setString(i + 1, param.toString());
    }
  }
 private void writeToDatabase(Date time, Value<?> value) {
   try {
     Parameter<?> parameter = value.getParameter();
     if (!parameter.isNumeric()) {
       throw new IllegalArgumentException("The value '" + value.toString() + "' is not numeric!");
     }
     BigDecimal decimalValue = null;
     BigInteger integerValue = null;
     if (Long.class.isAssignableFrom(parameter.getType())) {
       integerValue = BigInteger.valueOf((Long) value.getValue());
     } else {
       decimalValue = BigDecimal.valueOf((Double) value.getValue());
     }
     preparedStatement.setTime(1, new Time(time.getTime()));
     preparedStatement.setString(2, server);
     preparedStatement.setString(3, parameter.getName());
     preparedStatement.setString(4, parameter.getUnit());
     preparedStatement.setString(5, parameter.getType().getName());
     preparedStatement.setString(6, parameter.getDescription());
     preparedStatement.setBigDecimal(7, decimalValue);
     preparedStatement.setLong(8, integerValue.longValue());
     preparedStatement.setString(9, parameter.getLevelOfMeasurement().name());
     preparedStatement.execute();
   } catch (SQLException e) {
     throw new RuntimeException("Could not insert event into event log.", e);
   }
 }
Ejemplo n.º 7
0
  public boolean eDitAlk(AnliKu ht) {
    String sql =
        "UPDATE alk SET casetitle=?,casecontent=?,keyword=?,taxtype=?,"
            + "area=?,note=? WHERE id=?";
    try {
      ////////////////////////////////
      conn = (Connection) DruidConn.getConnection();
      DruidConn.startTransaction();
      ps = conn.prepareStatement(sql);

      ps.setString(1, ht.getCasetitle());
      ps.setString(2, ht.getCasecontent());
      ps.setString(3, ht.getKeyword());
      ps.setString(4, ht.getTaxtype());
      ps.setString(5, ht.getArea());
      ps.setString(6, ht.getNote());
      ps.setInt(7, ht.getId());

      if (ps.executeUpdate() == 1) {
        return true;
      }
      ///////////////////////////////////

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      DruidConn.commit();
      close();
    }
    return false;
  }
 public void addContent(DeweyID deweyID, StringBuilder contentBuilder, int parentCID)
     throws IOException, Exception {
   String content = new String(contentBuilder);
   try {
     if (con != null) {
       String sqlQuery =
           "INSERT INTO \"OrderedByCID\" (\"CID\", \"DeweyID\" , \"Value\") VALUES (?, ? ,?);";
       PreparedStatement pst = con.prepareStatement(sqlQuery);
       pst.setInt(1, deweyID.getCID());
       pst.setString(2, deweyID.toString());
       pst.setString(3, content);
       pst.executeUpdate();
       pst.close();
     }
   } catch (SQLException e) {
     System.out.println("JDBC Driver is not Configured Correctly !");
     e.printStackTrace();
     return;
   }
   // text contents are not added to element index,thier CID shouldn be Zero
   // elemIndex.insert(0,deweyID);
   //         bTreeIndex.insert(deweyID,-2,content);
   //         System.out.println("CID: -2");
   // structSumIndex.add(-2,content,parentCID);THIS IS NOT NEEDED
   // checkBufPool();
 }
Ejemplo n.º 9
0
  @Override
  public void put(Emp object) {

    Emp emp = object;
    String sql;
    if (emp.getId() == null) {

      emp.setId(DBSrv.getInstance().getNextId());
      sql = "INSERT INTO DDT_EMP(lname,fname,mname,d_hire,d_fire,id) " + "VALUES(?,?,?,?,?,?)";
    } else {
      sql =
          "UPDATE DDT_EMP SET "
              + " lname = ?, "
              + " fname = ?, "
              + " mname = ?, "
              + " d_hire = ?, "
              + " d_fire = ?  "
              + " WHERE id = ?";
    }
    try {
      PreparedStatement st = conn.prepareStatement(sql);
      st.setString(1, emp.getLastName());
      st.setString(2, emp.getFirstName());
      st.setString(3, emp.getMiddleName());
      st.setDate(4, DBSrv.UtilToSQL(emp.getHireDate()));
      st.setDate(5, DBSrv.UtilToSQL(emp.getFireDate()));
      st.setInt(6, emp.getId());
      st.executeUpdate();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
 public CFSecurityTSecGroupBuff lockBuff(
     CFSecurityAuthorization Authorization, CFSecurityTSecGroupPKey PKey) {
   final String S_ProcName = "lockBuff";
   if (!schema.isTransactionOpen()) {
     throw CFLib.getDefaultExceptionFactory()
         .newUsageException(getClass(), S_ProcName, "Transaction not open");
   }
   ResultSet resultSet = null;
   try {
     Connection cnx = schema.getCnx();
     long TenantId = PKey.getRequiredTenantId();
     int TSecGroupId = PKey.getRequiredTSecGroupId();
     String sql =
         "SELECT * FROM "
             + schema.getLowerDbSchemaName()
             + ".sp_lock_tsecgrp( ?, ?, ?, ?, ?"
             + ", "
             + "?"
             + ", "
             + "?"
             + " )";
     if (stmtLockBuffByPKey == null) {
       stmtLockBuffByPKey = cnx.prepareStatement(sql);
     }
     int argIdx = 1;
     stmtLockBuffByPKey.setLong(
         argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
     stmtLockBuffByPKey.setString(
         argIdx++, (Authorization == null) ? "" : Authorization.getSecUserId().toString());
     stmtLockBuffByPKey.setString(
         argIdx++, (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
     stmtLockBuffByPKey.setLong(
         argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
     stmtLockBuffByPKey.setLong(
         argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
     stmtLockBuffByPKey.setLong(argIdx++, TenantId);
     stmtLockBuffByPKey.setInt(argIdx++, TSecGroupId);
     resultSet = stmtLockBuffByPKey.executeQuery();
     if (resultSet.next()) {
       CFSecurityTSecGroupBuff buff = unpackTSecGroupResultSetToBuff(resultSet);
       if (resultSet.next()) {
         throw CFLib.getDefaultExceptionFactory()
             .newRuntimeException(getClass(), S_ProcName, "Did not expect multi-record response");
       }
       return (buff);
     } else {
       return (null);
     }
   } catch (SQLException e) {
     throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
   } finally {
     if (resultSet != null) {
       try {
         resultSet.close();
       } catch (SQLException e) {
       }
       resultSet = null;
     }
   }
 }
Ejemplo n.º 11
0
 /**
  * Adds a LOINCCode to an office visit.
  *
  * @param LOINCCode A string of the code being added.
  * @param visitID The ID of the office visit the code is being added to.
  * @param pid The patient's MID associated with this transaction.
  * @return The unique ID of the code that was added.
  * @throws DBException
  */
 public long addLabProcedureToOfficeVisit(String LOINCCode, long visitID, long pid)
     throws DBException {
   Connection conn = null;
   PreparedStatement ps = null;
   try {
     conn = factory.getConnection();
     ps =
         conn.prepareStatement(
             "INSERT INTO LabProcedure (LaboratoryProcedureCode,OfficeVisitID,"
                 + "Commentary, Results, PatientMID, Status, Rights) VALUES (?,?,?,?,?,?,?)");
     ps.setString(1, LOINCCode);
     ps.setLong(2, visitID);
     ps.setString(3, "");
     ps.setString(4, "");
     ps.setLong(5, pid);
     ps.setString(6, LabProcedureBean.Not_Received);
     ps.setString(7, "ALLOWED");
     ps.executeUpdate();
     return DBUtil.getLastInsert(conn);
   } catch (SQLException e) {
     e.printStackTrace();
     throw new DBException(e);
   } finally {
     DBUtil.closeConnection(conn, ps);
   }
 }
 public void setValues(PreparedStatement ps) throws SQLException {
   ps.setString(1, job.getJobStatus().name());
   ps.setString(2, job.getErrorMessage());
   ps.setTimestamp(3, new Timestamp(job.getModifiedAt().getTime()));
   ps.setInt(4, job.getReturnCode());
   ps.setString(5, job.getJobId());
 }
Ejemplo n.º 13
0
Archivo: SQLDB.java Proyecto: Serios/Fe
  protected void saveAccount(String name, double money) {
    if (accountExists(name)) {
      String sql = "UPDATE " + accounts + " SET " + pbalance + "=? WHERE " + pname + "=?";

      try {
        PreparedStatement prest = database.prepare(sql);

        prest.setDouble(1, money);

        prest.setString(2, name);

        prest.executeUpdate();

        prest.close();
      } catch (SQLException e) {

      }
    } else {
      String sql = "INSERT INTO " + accounts + " (" + pname + ", " + pbalance + ") VALUES (?, ?)";

      try {
        PreparedStatement prest = database.prepare(sql);

        prest.setString(1, name);

        prest.setDouble(2, money);

        prest.executeUpdate();

        prest.close();
      } catch (SQLException e) {

      }
    }
  }
Ejemplo n.º 14
0
    @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;
    }
Ejemplo n.º 15
0
 /**
  * 更新任务
  *
  * @param task
  * @throws SQLException
  */
 public long update(Task task) throws SQLException {
   // ID,NAME,STATUS,CTIME,FTIME,MESSAGE
   String upSql =
       "update " + TABLE_NAME + " set NAME=?,STATUS=?,CTIME=?,FTIME=?,MESSAGE=? where ID=?";
   Connection conn = null;
   PreparedStatement upStmt = null;
   try {
     conn = DBUtil.getConnection();
     conn.setAutoCommit(false);
     upStmt = conn.prepareStatement(upSql);
     upStmt.setString(1, task.getName());
     upStmt.setInt(2, task.getStatus());
     upStmt.setLong(3, task.getcTime());
     upStmt.setLong(4, task.getfTime());
     upStmt.setString(5, task.getMessage());
     upStmt.setLong(6, task.getId());
     upStmt.execute();
     this.orderDAO.update(conn, task.getOrders());
     conn.commit();
     return task.getId();
   } catch (Exception e) {
     LOG.error("Will rollback");
     conn.rollback();
     LOG.error(e.getMessage(), e);
     throw new RuntimeException(e);
   } finally {
     if (upStmt != null) {
       upStmt.close();
     }
     if (conn != null) {
       conn.close();
     }
   }
 }
Ejemplo n.º 16
0
  /**
   * Method called by the Form panel to delete existing data.
   *
   * @param persistentObject value object to delete
   * @return an ErrorResponse value object in case of errors, VOResponse if the operation is
   *     successfully completed
   */
  public Response deleteRecord(ValueObject persistentObject) throws Exception {
    PreparedStatement stmt = null;
    try {
      EmpVO vo = (EmpVO) persistentObject;

      // delete from WORKING_DAYS...
      stmt = conn.prepareStatement("delete from WORKING_DAYS where EMP_CODE=?");
      stmt.setString(1, vo.getEmpCode());
      stmt.execute();
      stmt.close();

      // delete from EMP...
      stmt = conn.prepareStatement("delete from EMP where EMP_CODE=?");
      stmt.setString(1, vo.getEmpCode());
      stmt.execute();
      gridFrame.reloadData();

      frame.getGrid().clearData();

      return new VOResponse(vo);
    } catch (SQLException ex) {
      ex.printStackTrace();
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        stmt.close();
        conn.commit();
      } catch (SQLException ex1) {
      }
    }
  }
Ejemplo n.º 17
0
  public boolean ModificarUsuario() {
    boolean resp = false;
    try {
      // Realizar consulta INSERT
      String sql =
          "UPDATE usuarios SET nombres=?,apellidos=?,nacimiento=?, identificador=?, tipo=?, correo=?, telefono=?, estado_usuario=?, nick=?, contraseña=?, materia=?  WHERE id_usuario=?";
      PreparedStatement cmd = cn.prepareStatement(sql);
      // Llenar los parámetros
      cmd.setString(1, nombres);
      cmd.setString(2, apellidos);
      cmd.setString(3, nacimiento);
      cmd.setString(4, identificador);
      cmd.setString(5, tipo);
      cmd.setString(6, correo);
      cmd.setString(7, telefono);
      cmd.setBoolean(8, estado);
      cmd.setString(9, usuario);
      cmd.setString(10, contraseña);
      cmd.setString(11, materia);
      cmd.setInt(12, id);

      // Si da error devuelve 1, caso contrario 0
      // Tomar en cuenta el "!" de negación
      if (!cmd.execute()) {
        resp = true;
      }
      //        cmd.close();
      //        cn.close();
    } catch (Exception e) {
      System.out.println(e.toString());
    }
    return resp;
  }
Ejemplo n.º 18
0
 /**
  * Returns a list of information related to prescription reports given all of the office visits
  * and the patient ID. The patient ID is necessary in case the office visit IDs are for different
  * patients (the disambiguation is for security reasons).
  *
  * @param ovIDs A java.util.List of Longs for the office visits.
  * @param patientID A long representing the MID of the patient in question.
  * @return A java.util.List of prescription reports.
  * @throws DBException
  */
 public List<PrescriptionReportBean> getPrescriptionReportsByDate(
     long patientID, String startDate, String endDate) throws DBException {
   Connection conn = null;
   PreparedStatement ps = null;
   try {
     conn = factory.getConnection();
     ps =
         conn.prepareStatement(
             "SELECT * FROM NDCodes, OVMedication, OfficeVisits "
                 + "WHERE NDCodes.Code=OVMedication.NDCode AND OVMedication.VisitID=OfficeVisits.ID "
                 + "AND PatientID=? AND ((DATE(?) < OVMedication.EndDate AND DATE(?) > OVMedication.StartDate)"
                 + "OR (DATE(?) > OVMedication.StartDate  AND DATE(?) < OVMedication.EndDate ) OR "
                 + "(DATE(?) <= OVMedication.StartDate AND DATE(?) >= OVMedication.StartDate)) "
                 + "ORDER BY VisitDate DESC");
     ps.setLong(1, patientID);
     ps.setString(2, startDate);
     ps.setString(3, startDate);
     ps.setString(4, endDate);
     ps.setString(5, endDate);
     ps.setString(6, startDate);
     ps.setString(7, endDate);
     ResultSet rs = ps.executeQuery();
     return prescriptionReportBeanLoader.loadList(rs);
   } catch (SQLException e) {
     e.printStackTrace();
     throw new DBException(e);
   } finally {
     DBUtil.closeConnection(conn, ps);
   }
 }
  public void addValue(DeweyID deweyID, String value, int parentCID) throws IOException, Exception {
    // we may have problem here
    // maybe we should update previously inserted attributes instead of insert new one

    // FOR ATTrib Values (Actually they are behaved the same as text contents)
    // text contents are not added to element index,thier CID shouldn be Zero
    // elemIndex.insert(0,deweyID);
    // bTreeIndex.insert(deweyID,-1,value);
    logManager.LogManager.log(6, value);
    logManager.LogManager.log(6, "Value: " + deweyID.toString());
    try {
      if (con != null) {
        String sqlQuery =
            "INSERT INTO \"OrderedByCID\" (\"CID\", \"DeweyID\" , \"Value\") VALUES (?, ? ,?);";
        PreparedStatement pst = con.prepareStatement(sqlQuery);
        pst.setInt(1, deweyID.getCID());
        pst.setString(2, deweyID.toString());
        pst.setString(3, value);
        pst.executeUpdate();
        pst.close();
      }
    } catch (SQLException e) {
      System.out.println("JDBC Driver is not Configured Correctly !");
      e.printStackTrace();
      return;
    }

    // structSumIndex.add(-1,value,parentCID);THIS IS NOT NEEDED!
    // checkBufPool();
  }
Ejemplo n.º 20
0
 private void setValues(PreparedStatement ps, OfficeVisitBean ov) throws SQLException {
   ps.setDate(1, new java.sql.Date(ov.getVisitDate().getTime()));
   ps.setString(2, ov.getNotes());
   ps.setLong(3, ov.getHcpID());
   ps.setLong(4, ov.getPatientID());
   ps.setString(5, ov.getHospitalID());
 }
 public void setString(PreparedStatement ps, int param, String value) {
   try {
     if (getDatastoreAdapter().supportsOption(DatastoreAdapter.BLOB_SET_USING_SETSTRING)) {
       if (value == null) {
         if (column.isDefaultable() && column.getDefaultValue() != null) {
           ps.setString(param, column.getDefaultValue().toString().trim());
         } else {
           ps.setNull(param, getJDBCType());
         }
       } else {
         ps.setString(param, value);
       }
     } else {
       if (value == null) {
         if (column != null && column.isDefaultable() && column.getDefaultValue() != null) {
           ps.setBlob(param, new BlobImpl(column.getDefaultValue().toString().trim()));
         } else {
           ps.setNull(param, getJDBCType());
         }
       } else {
         ps.setBlob(param, new BlobImpl(value));
       }
     }
   } catch (SQLException e) {
     throw new NucleusDataStoreException(
         Localiser.msg("055001", "String", "" + value, column, e.getMessage()), e);
   } catch (IOException e) {
     throw new NucleusDataStoreException(
         Localiser.msg("055001", "String", "" + value, column, e.getMessage()), e);
   }
 }
Ejemplo n.º 22
0
  public static void Update(Unlocked p) throws ResponseException {
    PreparedStatement statement = null;
    String query =
        "Update unlocked SET fk_profile_id=?,bonus_info=?,content_info=? where fk_profile_id=?;";
    Connection connect = null;
    IConnection c = MiscUtil.getIConnection();

    try {
      connect = c.init();
      statement = connect.prepareStatement(query);
      statement.setLong(1, p.getProfileId());
      statement.setString(2, p.getBonusInfo());
      statement.setString(3, p.getContentInfo());
      statement.setLong(4, p.getProfileId());
      statement.executeUpdate();
    } catch (SQLException e) {
      logger.error("SQL Error", e);
      throw new ResponseException("SQL Error", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ResponseException e) {
      throw e;
    } finally {
      try {
        if (statement != null) statement.close();
        if (connect != null) connect.close();
      } catch (SQLException e) {
        logger.error("SQL Error", e);
      }
    }
  }
Ejemplo n.º 23
0
  protected void updateURLTitle(long groupId, String articleId, String urlTitle) throws Exception {

    String normalizedURLTitle = FriendlyURLNormalizerUtil.normalize(urlTitle, _friendlyURLPattern);

    if (urlTitle.equals(normalizedURLTitle)) {
      return;
    }

    normalizedURLTitle =
        JournalArticleLocalServiceUtil.getUniqueUrlTitle(groupId, articleId, normalizedURLTitle);

    Connection con = null;
    PreparedStatement ps = null;

    try {
      con = DataAccess.getUpgradeOptimizedConnection();

      ps = con.prepareStatement("update JournalArticle set urlTitle = ? where urlTitle = ?");

      ps.setString(1, normalizedURLTitle);
      ps.setString(2, urlTitle);

      ps.executeUpdate();
    } finally {
      DataAccess.cleanUp(con, ps);
    }
  }
Ejemplo n.º 24
0
  public boolean changePassword(String oldPassword, String newPassword) {
    if (!passwordExist()) {
      _log.warning(
          "[SecondaryPasswordAuth]" + _activeClient.getAccountName() + " forced changePassword");
      _activeClient.closeNow();
      return false;
    }

    if (!checkPassword(oldPassword, true)) {
      return false;
    }

    if (!validatePassword(newPassword)) {
      _activeClient.sendPacket(new Ex2ndPasswordAck(2, Ex2ndPasswordAck.WRONG_PATTERN));
      return false;
    }

    newPassword = cryptPassword(newPassword);

    try (Connection con = DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement = con.prepareStatement(UPDATE_PASSWORD)) {
      statement.setString(1, newPassword);
      statement.setString(2, _activeClient.getAccountName());
      statement.setString(3, VAR_PWD);
      statement.execute();
    } catch (Exception e) {
      _log.log(Level.SEVERE, "Error while reading password.", e);
      return false;
    }

    _password = newPassword;
    _authed = false;
    return true;
  }
Ejemplo n.º 25
0
  public static final void reportPost(Report report) {
    Connection connection = null;
    PreparedStatement stmt = null;
    String sql =
        "INSERT INTO luser_reports_post (post_id,whistleblower_id,wrongdoing_id,category,reason) VALUES (?,?,?,?,?)";
    try {
      connection = DBConnection.getConnection();
      stmt = connection.prepareStatement(sql);
      stmt.setInt(1, report.getPostId());
      stmt.setString(2, report.getWhistleblowerId());
      stmt.setString(3, report.getWrongdoingId());
      stmt.setString(4, report.getCategory());
      stmt.setString(5, report.getReason());
      stmt.executeUpdate();
    } catch (SQLException ex) {
      Logger.getLogger(PostMapper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (stmt != null)
        try {
          stmt.close();
        } catch (SQLException e1) {
          e1.printStackTrace();
        }

      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 26
0
  public void addToDataBase(String userName, String email) {
    Connection koneksi = null;
    PreparedStatement pstmt = null;
    String str = "";
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      koneksi =
          DriverManager.getConnection("jdbc:mysql://localhost/shopkartdb", "shopkart", "welcome");
      System.out.println("I am Here " + koneksi);

      String sql = "INSERT INTO loginInfo(" + "userName," + "emailID) " + "VALUES(?,?)";

      pstmt = koneksi.prepareStatement(sql);
      pstmt.setString(1, userName);
      pstmt.setString(2, email);
      pstmt.executeUpdate();
      System.out.println("Hello");

      koneksi.close();
    } catch (SQLException sqle) {
      str = "SQLException error";
    } catch (ClassNotFoundException cnfe) {
      str = "ClassNotFoundException error";
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 27
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;
  }
Ejemplo n.º 28
0
  public User gerUserByLogin(String email, String password) {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    User user = new User();
    String selectQuery = "SELECT * FROM users WHERE user_email = ? AND user_password = ?";

    try {
      connection = datasource.getConnection();
      statement = connection.prepareStatement(selectQuery);
      statement.setString(1, email);
      statement.setString(2, password);
      resultSet = statement.executeQuery();

      while (resultSet.next()) {
        int userId = resultSet.getInt("user_id");
        String userName = resultSet.getString("user_name");
        String userPassword = resultSet.getString("user_password");
        String userEmail = resultSet.getString("user_email");
        String userStatus = resultSet.getString("user_status");
        user.setUserId(userId);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setUserEmail(userEmail);
        user.setUserStatus(userStatus);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      datasource.closePreparedStatement(statement);
      datasource.closeConnection(connection);
      datasource.closeResultSet(resultSet);
    }
    return user;
  }
Ejemplo n.º 29
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;
  }
Ejemplo n.º 30
0
  /*
   * (non-Javadoc)
   *
   * @see
   * sg.edu.nus.iss.phoenix.authenticate.dao.impl.UserDao#save(java.sql.Connection
   * , sg.edu.nus.iss.phoenix.authenticate.entity.User)
   */
  @Override
  public void save(User valueObject) throws NotFoundException, SQLException {

    String sql = "UPDATE user SET password = ?, name = ?, role = ? WHERE (id = ? ) ";
    PreparedStatement stmt = null;

    try {
      stmt = this.connection.prepareStatement(sql);
      stmt.setString(1, valueObject.getPassword());
      stmt.setString(2, valueObject.getName());
      stmt.setString(3, valueObject.getRoles().get(0).getRole());

      stmt.setString(4, valueObject.getId());

      int rowcount = databaseUpdate(stmt);
      if (rowcount == 0) {
        // System.out.println("Object could not be saved! (PrimaryKey not found)");
        throw new NotFoundException("Object could not be saved! (PrimaryKey not found)");
      }
      if (rowcount > 1) {
        // System.out.println("PrimaryKey Error when updating DB! (Many objects were affected!)");
        throw new SQLException("PrimaryKey Error when updating DB! (Many objects were affected!)");
      }
    } finally {
      if (stmt != null) stmt.close();
    }
  }