/** * upDate the sensor with new start and end time and also enabled/disabled information in Database * * @param sensor */ public static void updateSensor(Sensor sensor) { System.out.println("Update sensor " + sensor.toString()); try { conn = DriverManager.getConnection( "jdbc:mysql://localhost/sosecurity?" + "user=ssuser&password=sspwd"); try { // String getSensor = "UPDATE sensor SET subAreaID=2, userID=1, // isArmed = true WHERE sensorID=1"; String updateSubArea = "UPDATE sensor SET subAreaID= ? , userID= ?, isArmed=?, start_time=?, end_time= ? " + "WHERE sensorID=?"; System.out.println(updateSubArea); PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(updateSubArea); preparedStmt.setInt(1, sensor.getSubAreaID()); preparedStmt.setLong(2, sensor.getUserID()); preparedStmt.setBoolean(3, sensor.getIsArmed()); preparedStmt.setDate(4, new java.sql.Date(sensor.getFromTime().getTime())); if (sensor.getToDate() == null) { preparedStmt.setDate(5, null); } else { preparedStmt.setDate(5, new java.sql.Date(sensor.getToDate().getTime())); } preparedStmt.setInt(6, sensor.getSensorID()); // execute the java prepared statement int affectedRow = preparedStmt.executeUpdate(); System.out.println(affectedRow); } finally { // It's important to close the connection when you are done with // it try { conn.close(); } catch (Throwable ignore) { /* * Propagate the original exception instead of this one that * you may want just logged */ ignore.printStackTrace(); } } } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } return; }
/** * Change a reservation * * @param email current user's email * @param date date to change * @param partySize number of guests to change * @return true if success, false otherwise * @throws SQLException */ public boolean changeReservation(String email, Date date, int partySize) throws SQLException { boolean success = false; PreparedStatement updateReservation = null; int customerID = getCID(email); String query = "update reservation set reservationDate = ?, partysize = ? where cid = ?"; try { connection.setAutoCommit(false); updateReservation = (PreparedStatement) connection.prepareStatement(query); updateReservation.setDate(1, date); updateReservation.setInt(2, partySize); updateReservation.setInt(3, customerID); updateReservation.execute(); connection.commit(); success = true; } catch (SQLException e) { e.printStackTrace(); success = false; } finally { if (updateReservation != null) { updateReservation.close(); } connection.setAutoCommit(true); return success; } }
/** * Cancel a reservation * * @param email * @param d * @return */ public boolean cancelReservation(String email, Date d) { boolean success = false; int cid = getCID(email); if (cid != -1) { String queryCancelReservation = "DELETE FROM Reservation WHERE cID=? AND reservationDate=?"; try { PreparedStatement statement = (PreparedStatement) connection.prepareStatement(queryCancelReservation); statement.setInt(1, cid); statement.setDate(2, d); statement.execute(); statement.close(); success = true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); success = false; System.out.println("Failed: " + e.getMessage()); } finally { return success; } } else { return false; } }
/** * Reserve a table * * @param partySize number of people in a party * @param d reservation date * @param tID table id * @param c a customer * @return true if succeed, false otherwise */ public boolean reserveTable(int partySize, Date d, int tID, Customer c) { PreparedStatement statement = null; int customerid = getCID(c.getEmail()); String sql_reserve = "INSERT INTO Restaurant.Reservation (reservationDate,partySize,cID,tID) values(?, ?, ?,?)"; try { connection.setAutoCommit(false); statement = (PreparedStatement) connection.prepareStatement(sql_reserve); statement.setDate(1, d); statement.setInt(2, partySize); statement.setInt(3, customerid); statement.setInt(4, tID); statement.executeUpdate(); connection.commit(); if (statement != null) { statement.close(); } connection.setAutoCommit(true); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("Failed: " + e.getMessage()); return false; } }
@Override public boolean guardar() { boolean ret = false; try { String sql = "UPDATE expulsiones SET ano=?,alumno_id=?,fecha=?,dias=? WHERE id=?"; if (getId() == null) { sql = "INSERT INTO expulsiones (ano,alumno_id,fecha,dias,id) VALUES(?,?,?,?,?)"; } PreparedStatement st = (PreparedStatement) MaimonidesApp.getApplication() .getConector() .getConexion() .prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); st.setInt(1, getAnoEscolar().getId()); st.setInt(2, getAlumno().getId()); st.setDate(3, new java.sql.Date(getFecha().getTimeInMillis())); st.setInt(4, getDias()); st.setObject(5, getId()); ret = st.executeUpdate() > 0; if (ret && getId() == null) { setId((int) st.getLastInsertID()); } st.close(); ret = true; } catch (SQLException ex) { Logger.getLogger(Conducta.class.getName()) .log(Level.SEVERE, "Error guardando datos de expulsion: " + this, ex); } return ret; }
public static int getNumeroExpulsiones(Alumno alumno, GregorianCalendar fecha) { int ret = 0; PreparedStatement st = null; ResultSet res = null; try { // Tenemos que ver si hay expulsiones para ese alumno st = (PreparedStatement) MaimonidesApp.getApplication() .getConector() .getConexion() .prepareStatement( "SELECT count(*) FROM expulsiones WHERE alumno_id=? AND fecha<=?"); st.setInt(1, alumno.getId()); st.setDate(2, new java.sql.Date(fecha.getTimeInMillis())); res = st.executeQuery(); if (res.next()) { ret = res.getInt(1); } } catch (SQLException ex) { Logger.getLogger(Expulsion.class.getName()).log(Level.SEVERE, null, ex); } Obj.cerrar(st, res); return ret; }
/** * Calcula si un alumno esta expulsado. Se sabe si un alumno está expulsado por el número de dias * escolares entre la fecha de expulsión y la de parte. Un día escolar es el numero de partes con * fecha distinta entre dos fechas. * * @param anoEscolar Año escola * @param alumno Alumno * @param fecha Fecha en la que se quiere saber si el alumno estça expulsado * @return true si está expulsado en la fecha del parte, false si no lo está */ public static Boolean isAlumnoExpulsado(Alumno alumno, GregorianCalendar fecha) { boolean ret = false; try { // Tenemos que ver si hay expulsiones para ese alumno PreparedStatement st = (PreparedStatement) MaimonidesApp.getApplication() .getConector() .getConexion() .prepareStatement("SELECT * FROM expulsiones WHERE alumno_id=? AND fecha<=?"); st.setInt(1, alumno.getId()); st.setDate(2, new java.sql.Date(fecha.getTimeInMillis())); ResultSet res = st.executeQuery(); while (res.next() && !ret) { // Si hay expulsiones tenemos que ver si son válidas // Para eso tenemos que contar los partes desde la fecha de expulsión hasta ahora GregorianCalendar fechaExpulsion = Fechas.toGregorianCalendar(res.getDate("fecha")); if (fechaExpulsion != null) { // Como la fecha de expulsión esta incluida tenemos que quitarle un día fechaExpulsion.add(GregorianCalendar.DATE, -1); // Y vemos la diferencia en días int dias = res.getInt("dias"); long diasTranscurridos = Fechas.getDiferenciaTiempoEn(fecha, fechaExpulsion, GregorianCalendar.DATE); ret = diasTranscurridos <= dias; } } Obj.cerrar(st, res); } catch (SQLException ex) { Logger.getLogger(Expulsion.class.getName()).log(Level.SEVERE, null, ex); } return ret; }
public ArrayList<String> exportarFaltas( GregorianCalendar fechaDesde, GregorianCalendar fechaHasta, ArrayList<String> cursos) { ArrayList<String> err = new ArrayList<String>(); setFaltasExportadas(false); String texto = "Procesando... "; if (Fechas.getDiferenciaTiempoEn(fechaDesde, fechaHasta, GregorianCalendar.DATE) == 0) { texto += Fechas.format(fechaHasta, "dd/MM"); } else { texto += Fechas.format(fechaDesde, "dd/MM") + " a " + Fechas.format(fechaHasta, "dd/MM"); } PreparedStatement st = null; try { firePropertyChange("message", null, "Recuperando datos..."); StringBuilder sbCursos = new StringBuilder(); boolean primero = true; for (String c : cursos) { if (primero) { primero = false; } else { sbCursos.append(","); } sbCursos.append("\"").append(c).append("\""); } String sql = "SELECT p.id as idParte,p.fecha,t.cod AS codTramo,pa.asistencia,a.id AS idAlumno FROM partes_alumnos AS pa " + " JOIN partes AS p ON p.id=pa.parte_id " + " JOIN alumnos AS a ON a.id=pa.alumno_id " + " LEFT JOIN alumnos_problemas_envio AS ap ON a.id=ap.alumno_id " + " JOIN horarios AS h ON h.id=pa.horario_id " + " LEFT JOIN calendario_escolar AS ce ON ce.ano=p.ano AND p.fecha=ce.dia AND ce.docentes " + // TODO Esta linea elimina a caso hecho a los alumnos "MIXTOS" ya que séneca da un // error con ellos. " JOIN unidades AS u ON a.unidad_id=u.id AND a.curso_id=u.curso_id " + " JOIN tramos AS t ON t.id=h.tramo_id " + // Sólo hay que recuperar las que sean de actividad doncencia de alumnos con código // de faltas y que no están borrados, y que no son festivos " WHERE ce.id IS NULL AND (ap.id IS NULL || ap.excluir=0 ) AND h.actividad_id=" + Actividad.getIdActividadDocencia(MaimonidesApp.getApplication().getAnoEscolar()) + " AND a.borrado=0 AND a.codFaltas!='' AND p.fecha BETWEEN ? AND ? AND p.curso IN (" + sbCursos.toString() + ") AND pa.asistencia > " + ParteFaltas.FALTA_ASISTENCIA + " AND p.ano=? ORDER BY a.curso_id,a.unidad_id,idAlumno,p.fecha,asistencia,t.hora"; System.out.println(sql); PreparedStatement actuParte = (PreparedStatement) MaimonidesApp.getApplication() .getConector() .getConexion() .prepareStatement( "UPDATE partes SET enviado=1, justificado=1 WHERE fecha BETWEEN ? AND ? AND curso IN (" + sbCursos.toString() + ") AND ano=? "); st = (PreparedStatement) MaimonidesApp.getApplication().getConector().getConexion().prepareStatement(sql); st.setDate(1, new java.sql.Date(fechaDesde.getTime().getTime())); st.setDate(2, new java.sql.Date(fechaHasta.getTime().getTime())); st.setInt(3, MaimonidesApp.getApplication().getAnoEscolar().getId()); actuParte.setDate(1, new java.sql.Date(fechaDesde.getTime().getTime())); actuParte.setDate(2, new java.sql.Date(fechaHasta.getTime().getTime())); actuParte.setInt(3, MaimonidesApp.getApplication().getAnoEscolar().getId()); ResultSet res = st.executeQuery(); Curso ultimoCurso = null; Unidad ultimaUnidad = null; Alumno ultimoAlumno = null; Element nCursos = getDocumento().createElement("CURSOS"); Element nCurso = null; Element nUnidades = null; Element nUnidad = null; Element nAlumnos = null; Element nAlumno = null; Element nFaltas = null; while (res.next() && !isCancelado()) { setFaltasExportadas(true); GregorianCalendar fecha = Fechas.toGregorianCalendar(res.getDate("fecha")); // firePropertyChange("message", null, "Procesando asistencia ..."); // int idParte = res.getInt("idParte"); int tramo = res.getInt("codTramo"); int asistencia = res.getInt("asistencia"); int idAlumno = res.getInt("idAlumno"); Alumno a = Alumno.getAlumno(idAlumno); Curso c = Curso.getCurso(a.getIdCurso()); Unidad u = a.getUnidad(); firePropertyChange("message", null, texto + " " + u + " " + a + "..."); if (ultimoCurso == null || !ultimoCurso.equals(c)) { nCurso = getDocumento().createElement("CURSO"); nCursos.appendChild(nCurso); // Creamos la linea <X_OFERTAMATRIG>2063</X_OFERTAMATRIG> nCurso.appendChild(crearTag("X_OFERTAMATRIG", c.getCodigo())); // Creamos la linea <D_OFERTAMATRIG>1º de Bachillerato (Humanidades y Ciencias // Sociales)</D_OFERTAMATRIG> nCurso.appendChild(crearTag("D_OFERTAMATRIG", c.getDescripcion())); // Ahora creamos el comienzo de la unidad nUnidades = getDocumento().createElement("UNIDADES"); nCurso.appendChild(nUnidades); } if (ultimaUnidad == null || !ultimaUnidad.equals(u)) { // Creamos una nueva unidad nUnidad = getDocumento().createElement("UNIDAD"); nUnidades.appendChild(nUnidad); // Creamos la linea <X_UNIDAD>601648</X_UNIDAD> nUnidad.appendChild(crearTag("X_UNIDAD", u.getCodigo())); // Creamos la linea <T_NOMBRE>1BTO-A</T_NOMBRE> nUnidad.appendChild(crearTag("T_NOMBRE", u.getCursoGrupo())); // Ahora creamos el comienzo de la unidad nAlumnos = getDocumento().createElement("ALUMNOS"); nUnidad.appendChild(nAlumnos); } if (ultimoAlumno == null || !ultimoAlumno.equals(a)) { nAlumno = getDocumento().createElement("ALUMNO"); nAlumno.appendChild(crearTag("X_MATRICULA", a.getCodFaltas())); // Y Creamos el inicio para las faltas de asistencia de este alumno nFaltas = getDocumento().createElement("FALTAS_ASISTENCIA"); nAlumno.appendChild(nFaltas); nAlumnos.appendChild(nAlumno); } addFalta(fecha, tramo, asistencia, nFaltas); ultimoCurso = c; ultimaUnidad = u; ultimoAlumno = a; } if (isFaltasExportadas() && !isCancelado()) { firePropertyChange("message", null, "Generando fichero..."); generarCabeceraFaltas(fechaDesde, fechaHasta, nCursos); File f = generarFicheroFaltas(fechaDesde, fechaHasta, cursos); if (isEnviarASeneca()) { firePropertyChange("message", null, "Enviando fichero a Séneca..."); String nombre = f.getName().substring(0, f.getName().length() - 4); String codigoOperacion = Cripto.md5(nombre + "" + Math.random()); int ret = enviarFichero(f, codigoOperacion); if (ret == GestorEnvioFaltas.RET_OK) { firePropertyChange( "message", null, "Fichero enviado correctamente. Marcando faltas como enviadas..."); actuParte.executeUpdate(); File enviados = new File(f.getParent(), "enviados"); enviados.mkdirs(); f.renameTo(new File(enviados, f.getName())); firePropertyChange("message", null, "Envío de faltas terminado."); } else { if (ret == GestorEnvioFaltas.RET_ERROR_PROCESANDO) { firePropertyChange( "message", null, "Séneca ha dado errores procesando el fichero enviado."); File nuevo = new File(getCarpetaFallidos(), nombre + "-ID" + codigoOperacion + ".xml"); f.renameTo(nuevo); // Creamos el fichero de propiedades del nuevo File info = new File(nuevo.getParentFile(), nuevo.getName() + ".info"); Properties p = new Properties(); p.setProperty("desde", fechaDesde.getTimeInMillis() + ""); p.setProperty("hasta", fechaHasta.getTimeInMillis() + ""); p.setProperty("cursos", Str.implode(cursos, ",")); p.setProperty("archivo", nuevo.getAbsolutePath()); p.setProperty("codigo", codigoOperacion); p.setProperty("error", getClienteSeneca().getUltimoError()); FileOutputStream fos = new FileOutputStream(info); p.store(fos, "Error enviando fichero de faltas"); Obj.cerrar(fos); err.add( "<html>Séneca ha dado errores procesando el fichero enviado:<br/> " + nombre + ".<br/><br/>"); if (!getClienteSeneca().getUltimoError().equals("")) { err.add(getClienteSeneca().getUltimoError()); } } else { firePropertyChange("message", null, "No se ha podido enviar el fichero a Séneca."); f.delete(); err.add("<html>No se ha podido enviar el fichero:<br/> " + nombre + ".<br/><br/>"); if (!getClienteSeneca().getUltimoError().equals("")) { err.add(getClienteSeneca().getUltimoError()); } } // Si no se está loggeado cancelamos el proceso if (!getClienteSeneca().isLoggeado()) { setCancelado(true); } } } else { firePropertyChange("message", null, "Marcando faltas como enviadas..."); actuParte.executeUpdate(); } } Obj.cerrar(actuParte, st, res); } catch (Exception ex) { Logger.getLogger(GeneradorFicherosSeneca.class.getName()).log(Level.SEVERE, null, ex); } return err; }
public ArrayList<String> exportarFaltas( GregorianCalendar fechaDesde, GregorianCalendar fechaHasta) { setFicherosGenerados(false); getErrores().clear(); if (MaimonidesApp.getApplication().getAnoEscolar() == null) { getErrores().add("No hay año escolar asignado."); } else { // Ponemos el tema de h.materia_id IS NOT NULL para que no introduzca la actvidaddes. Podría // ponerse directamente un tipo de actividad. // No queremos que meta actividades porque séneca no admite faltas en las actividades sólo en // las materias. // El envío de faltas hay que hacerlo siempre por cursos completos para una fecha por lo que // primero tenemos que sacar fechas y cursos String sql = "SELECT distinct p.fecha,p.curso FROM partes_alumnos AS pa " + " JOIN partes AS p ON p.id=pa.parte_id " + " JOIN alumnos AS a ON a.id=pa.alumno_id " + " LEFT JOIN alumnos_problemas_envio AS ap ON a.id=ap.alumno_id " + " JOIN horarios AS h ON h.id=pa.horario_id " + " JOIN tramos AS t ON t.id=h.tramo_id " + " LEFT JOIN calendario_escolar AS ce ON ce.ano=p.ano AND p.fecha=ce.dia AND ce.docentes " + // TODO Esta linea elimina a caso hecho a los alumnos "MIXTOS" ya que séneca da un // error con ellos. " JOIN unidades AS u ON a.unidad_id=u.id AND a.curso_id=u.curso_id " + // Sólo hay que recuperar las que sean de actividad doncencia de alumnos con código // de faltas y que no están borrados, y que no son festivos " WHERE ce.id IS NULL AND (ap.id IS NULL || ap.excluir=0 ) AND h.actividad_id=" + Actividad.getIdActividadDocencia(MaimonidesApp.getApplication().getAnoEscolar()) + " AND a.borrado=0 AND a.codFaltas!='' AND pa.asistencia>" + ParteFaltas.FALTA_ASISTENCIA + " AND p.enviado=0 AND p.ano=? AND (p.justificado OR p.fecha<? )" + ((fechaDesde != null) ? " AND p.fecha>=? " : "") + ((fechaHasta != null) ? " AND p.fecha<=? " : "") + " ORDER BY p.fecha ASC,p.curso"; PreparedStatement st = null; ResultSet res = null; try { st = (PreparedStatement) MaimonidesApp.getApplication().getConector().getConexion().prepareStatement(sql); int pos = 1; st.setInt(pos++, MaimonidesApp.getApplication().getAnoEscolar().getId()); GregorianCalendar fechaFiltro = new GregorianCalendar(); // Asignamos el principio de la semana siempre fechaFiltro.add( GregorianCalendar.DATE, fechaFiltro.get(GregorianCalendar.DAY_OF_WEEK) * -1); st.setDate(pos++, new java.sql.Date(fechaFiltro.getTime().getTime())); if (fechaDesde != null) { st.setDate(pos++, new java.sql.Date(fechaDesde.getTime().getTime())); } if (fechaHasta != null) { st.setDate(pos++, new java.sql.Date(fechaHasta.getTime().getTime())); } GregorianCalendar fechaMin = null; GregorianCalendar fechaMax = null; ArrayList<String> cursos = new ArrayList<String>(); res = st.executeQuery(); while (res.next() && !isCancelado()) { GregorianCalendar f = Fechas.toGregorianCalendar(res.getDate("fecha")); String c = res.getString("curso"); if (fechaMin == null) { fechaMin = f; fechaMax = f; } else { // vemos la diferencia entre fechas boolean cambiarDeFichero = isCambiarDeFichero(f, fechaMax); if (cambiarDeFichero) { // Si es mayor de un dia hay que crear un fichero nuevo getErrores().addAll(procesarFaltas(fechaMin, fechaMax, cursos)); fechaMin = f; fechaMax = f; cursos.clear(); } else { // Si no asignamos ese dia simplemente fechaMax = f; } } if (!cursos.contains(c)) { firePropertyChange("message", null, "Procesando " + Fechas.format(f) + " " + c + "..."); cursos.add(c); } } if (cursos.size() > 0) { // Y procesamos la última tanda getErrores().addAll(procesarFaltas(fechaMin, fechaMax, cursos)); } } catch (SQLException ex) { Logger.getLogger(GeneradorFicherosSeneca.class.getName()).log(Level.SEVERE, null, ex); } finally { Obj.cerrar(st, res); } } return getErrores(); }