package quba.service;
import exceptions.PoseidonException;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.db.DB;
import play.mvc.Http;
import quba.models.QubaStation;
import service.PoseidonPropertyService;
import java.sql.*;
public class QubaSubjectiveFetcher {
private final static Logger logger = LoggerFactory.getLogger(QubaSubjectiveFetcher.class);
public boolean fetchSubjective(String name, DateTime dateOfProduction, Integer termin) {
boolean result = false;
QubaStation station = QubaStation.findStationByName(name);
if ( station == null ){
logger.info("Fant ikke station i quba med navn {}", name);
return false;
}
Connection connection = DB.getConnection("quba");
ResultSet rs=null;
PreparedStatement statement = null;
try {
int pindexTemp = PoseidonPropertyService.getIntProperty("quba.temperature.pindexid");
int pindexWind = PoseidonPropertyService.getIntProperty("quba.strongwind.pindexid");
String sql = "select run " +
"from subjective " +
"where stationid = ? " +
"and pindexid in (?,?) " +
"and levelid = 0 " +
"and run = valid " +
"and run = ?";
java.util.Date d = dateOfProduction.withHourOfDay(termin != null ? termin : 0).toDate();
logger.info("d {} - {}", d,d.getTime());
Timestamp ts = new Timestamp(d.getTime());
statement = connection.prepareStatement(sql);
statement.setLong(1, station.stationid);
statement.setLong(2, pindexTemp);
statement.setLong(3, pindexWind);
statement.setTimestamp(4, ts);
try {
logger.debug("Kjører sql {} med stationid {} og run {}", sql, station.stationid,d);
rs = statement.executeQuery();
while (rs.next()) {
result = true;
}
} finally {
if ( rs != null ) {
rs.close();
}
}
} catch (SQLException e) {
throw new PoseidonException(Http.Status.INTERNAL_SERVER_ERROR, "En feil oppstod i kommunikasjon med databasen. Feilen har blitt logget", e);
}
finally {
try {
if ( statement!= null && !statement.isClosed()){
statement.close();
}
if (connection != null && !connection.isClosed()){
connection.close();
}
} catch (SQLException e) {
throw new PoseidonException(Http.Status.INTERNAL_SERVER_ERROR, "En feil oppstod i kommunikasjon med databasen. Feilen har blitt logget", e);
}
}
logger.info("Station {} har {} data på dato {} og termin {} ",name,result?"":"ikke", dateOfProduction,termin);
return result;
}
}