I have an inherited project, a BMC Remedy application and never worked with this Remedy stuff. This project modifies Incidents and Work Orders from remedy through the Remedy API. I have literally no idea on this.
There's a process that closes incidents that are in resolved state and have not been modified in the last 36 hours. Sometimes, those incidents have the 'categorization' field empty, and the client wants to fill this categorization before closing it.
This is part of the code:
Connection to Remedy:
public static void main(String args[]) {
// Inicializamos el logger
java.util.logging.LogManager.getLogManager().reset();
try {
// Nos conectamos a Remedy y a MySQL
LOGGER.info("Conectando a bases de datos");
if (!connect()) {
throw new Exception("Fallo al conectar a Remedy o a MySQL");
}
// Metodo para cerrar incidecias resueltas
remedy.cerrarIncidencias(sql.queryResueltas36h());
// Desconectamos de Remedy y MySQL
disconnect();
} catch (Exception e) {
LOGGER.error("Error critico: ", e);
try {
remedy.desconectar();
} catch (Exception e1) {
}
try {
sql.desconectar();
} catch (Exception e1) {
}
}
}
Function to closing incidents:
public void cerrarIncidencias(List<String> incs) throws Exception {
int contador = 1;
for (String inc : incs) {
try {
// Obtenemos la incidencia
QualifierInfo qual = server.parseQualification("HPD:Help Desk", "'Incident Number' = \"" + inc + "\"");
List<Entry> entries = server.getListEntryObjects("HPD:Help Desk", qual, 0, 0, null,
Constantes.CAMPOS_HPD_HELP_DESK_CERRAR_INCIDENCIA, false, null);
// Rellenamos un comentario generico
Entry comment = new Entry();
comment.put(Constantes.HPD_WORKLOG_DETAILED_DESCRIPTION, new Value("Cierre automatico tras 36 horas en resuelto."));
comment.put(Constantes.HPD_WORKLOG_INCIDENT_NUMBER, new Value(inc));
comment.put(Constantes.HPD_WORKLOG_DESCRIPTION, new Value("----"));
comment.put(Constantes.HPD_WORKLOG_WORKLOG_TYPE, new Value(8000));
for (Entry entry : entries) {
entry.put(Constantes.HPD_HELP_DESK_STATUS, new Value(5)); // Estado a cerrado
if (entry.get(Constantes.HPD_HELP_DESK_ASSIGNEE_LOGIN_ID).getValue() == null) {
entry.put(Constantes.HPD_HELP_DESK_ASSIGNEE_LOGIN_ID, new Value("lmoren70"));
entry.put(Constantes.HPD_HELP_DESK_ASSIGNEE, new Value("Luis Manuel Moreno Rodriguez")); // Usuario asignado
}
server.setEntry("HPD:Help Desk", entry.getEntryId(), entry, null, 0);
server.createEntry("HPD:WorkLog", comment);
LOGGER.info("Incidencia " + inc + " cerrada con exito - " + contador + " de " + incs.size());
}
} catch (Exception e) {
LOGGER.error("Incidencia " + inc + " NO se ha podido cerrar - " + contador + " de " + incs.size() + "\n"
+ e.getMessage());
}
contador++;
}
}
Query:
I thought to do an update directly to the database BUT this database reads from Remedy, so I have to update Remedy.
public List<String> queryResueltas36h() {
String query = "SELECT inc FROM vdf_tickets, vdf_groups WHERE status = 'Resuelto' AND LENGTH(inc) > 9 "
+ "AND vdf_groups.group = creator_group AND (vdf_groups.categorization = 'TES' OR vdf_groups.group IN ('TES', 'ARCA', 'NetOps TES Assurance')) "
+ "AND last_resolved_date < DATE_ADD(NOW(), INTERVAL -36 HOUR) ORDER BY inc DESC";
List<String> incs = new ArrayList<String>();
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String inc = rs.getString("inc");
incs.add(inc);
}
stmt.close();
} catch (Exception e) {
LOGGER.error("Error al obtener lista de incidencias de la base de datos", e);
try {
stmt.close();
} catch (Exception e1) {
}
}
return incs;
}
What I want is to put the categorization to 'TES', in case there's no categorization.
One option I thought is to do an automation with Selenium and Python and not touching this code, but is far better to have all in the same project.
Any ideas? Thanks in advance!
You need to update your cerrarIncidencias function. But first you need to ask what categorisation you need to update.
There are three levels of categorisation.
Operational Categorisation
Product Categorisation
Resolution Categorisation
So decide which one you want to populate and get the field id for that field. For this example, I will say
Categorisation Tier 1 which is 1000000063
You'll need to add to CAMPOS_HPD_HELP_DESK_CATEGORISATION_TIER1=1000000063 to your Constantes file.
Then in your block
for (Entry entry : entries)
You need something like:
if (entry.get(Constantes.CAMPOS_HPD_HELP_DESK_CATEGORISATION_TIER1).getValue() == null) {
entry.put(Constantes.CAMPOS_HPD_HELP_DESK_CATEGORISATION_TIER1, new Value("Your Value for Categorisation Tier 1"));
}
Related
So I am trying to test this code:
#Test
public void faarFalse() throws IOException {
String filStiTilArrangementer = "src/main/java/gruppeeksamen/arrangementer.csv";
String filStiTilLoggetInn = "../../View/loggetInn.fxml";
ObservableList listeFor = FXCollections.observableArrayList();
dataHandler.hentDataHele(filStiTilArrangementer, listeFor);
navnPaaArrangement = "Test arrangement";
datoPaaArrangement = "2020-10-10";
typeIdrettPaaArrangement = "Ski";
leggTilArrangementController.leggeTilArrangementet(navnPaaArrangement, datoPaaArrangement, typeIdrettPaaArrangement, filStiTilArrangementer, filStiTilLoggetInn); //Line 148 ref. error message
ObservableList listeEtter = FXCollections.observableArrayList();
dataHandler.hentDataHele(filStiTilArrangementer, listeEtter);
assertTrue(listeFor.size() < listeEtter.size());
//fjernet linjen som er lagt til
RandomAccessFile f = new RandomAccessFile(filStiTilArrangementer, "rw");
long length = f.length() - 1;
byte b;
do {
length -= 1;
f.seek(length);
b = f.readByte();
} while(b != 10);
f.setLength(length+1);
f.close();
}
which is testing this code:
public class LeggTilArrangementController {
#FXML
private Button btnGaaTilbake;
public void leggeTilArrangementet(String arrangement, String dato, String idrett, String filstienTilArrangementene, String filstienTilLoggetInn) {
//sjekker om alle "forhåndsregler" er gjort for å kunne legge til et arrangement
if (sjekkOmAlleInputErFyltUt(arrangement, dato, idrett) && sjekkOmdagensDatoErMindreEnnDatePicker(dato) && arrangementPaaSammeDatoIkkeFinnes(arrangement, dato.replace("-","."), idrett)){
//lager en ny linje med navnet på arrangementet, antall utøvere (som fra start skal være 0), utøvere (som fra start skal være tom), datoen (åååå.mm.dd), type idrett
String nyttArrangement = arrangement + ";0"/*antall utøvere*/ + ";" /*utøvere*/ + ";" + dato.replace("-",".") + ";" + idrett + "\n";
//prøver å legge til arrangementet på sisten av arrangementer.csv
try {
FileWriter filenSomSkalSkrivesTil = new FileWriter(filstienTilArrangementene, true);
filenSomSkalSkrivesTil.append(nyttArrangement);
filenSomSkalSkrivesTil.flush();
filenSomSkalSkrivesTil.close();
} catch (IOException e) {
e.printStackTrace();
}
//lukker nåværende vindu
goBack(filstienTilLoggetInn); //Line 76 ref. error message
} else {
MainJavaFX.visAlertFeilmelding("Mangler arrangement, dato eller idrett","Må fylle inn en av delene");
}
}
private void goBack(String filstienTilLoggetInn) {
Stage stage = (Stage) btnGaaTilbake.getScene().getWindow(); //Line 50 ref. error message
stage.close();
DataHandler.sendTilNyScene(filstienTilLoggetInn, "Arrengementer", 500, 500);
}
}
The test is supposed to test if a new line has been wrote to a CSV-file, but when i try to run the test, all I get is this message:
java.lang.NullPointerException
at gruppeeksamen.Controller.LeggTilArrangementController.goBack(LeggTilArrangementController.java:50)
at gruppeeksamen.Controller.LeggTilArrangementController.leggeTilArrangementet(LeggTilArrangementController.java:76)
at gruppeeksamen.Controller.LeggTilArrangementControllerTest.faarFalse(LeggTilArrangementControllerTest.java:148)
Anyone know why I get this error message?
PS: When i delete/comment out line 76 ref. error message, the test works all fine, but then the program won't work.
Looking at the code and line that you have highlighted it could be due to one of two reasons:
btnGaaTilbake.getScene()
Either btnGaaTilbake is null or method getScene() is retuning null. Kindly check both the variables are returning correct values.
i try with this, but it is some times not working correctly..i used a while loop for loop the code. can i add some listner for this? any one can give me the correct answer for this? in need to get responce real time
while (true) {
msgList = new ArrayList<InboundMessage>();
Service.getInstance().readMessages(msgList, InboundMessage.MessageClasses.ALL);
for (InboundMessage im : msgList) {
if (last < im.getMemIndex()) {
ResultSet rs = DB.getConnection().createStatement().executeQuery("Select * From codes where code='" + im.getText() + "'");
if (rs.next()) {
ResultSet rs2 = DB.getConnection().createStatement().executeQuery("Select * From sms_log where code='" + im.getText() + "' AND tel_no='" + im.getOriginator() + "'");
if (rs2.next()) {
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "The Code is Already Sent... Thank You!.");
System.out.println("The Code is Already Sent... Thank You!.");
} else {
System.out.println("The Code Verified... Thank You!.");
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "The Code Verified... Thank You!.");
DB.getConnection().createStatement().execute("INSERT INTO sms_log (tel_no,code,status) values('" + im.getOriginator() + "','" + im.getText() + "',1)");
}
} else {
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "Invalid Code... Thank You!.");
System.out.println("Invalid Code... Thank You!.");
}
}
}
Thread.sleep(10000);
System.out.println("start");
}
I think IInboundMessageNotification is the interface you are looking for
public class InboundNotification implements IInboundMessageNotification {
#Override
public void process(AGateway aGateway, Message.MessageTypes messageTypes, InboundMessage inboundMessage) {
//add you logic for received messages here
}
}
Add notification class to smsLib service
Service.getInstance().setInboundMessageNotification(new InboundNotification())
From now on, process() method will be called every time your modem receives a message.
As far as I remember, smslib (version 3.5.x) does not delete received messages so it needs to be done manually
#Override
public void process(AGateway aGateway, Message.MessageTypes messageTypes, InboundMessage inboundMessage) {
try {
aGateway.deleteMessage(inboundMessage);
} catch (TimeoutException | GatewayException | InterruptedException | IOException e) {
e.printStackTrace();
}
// your logic here
}
otherwise you will keep receiving not deleted messages every time you receive a new one.
Hope you will find this useful.
I have a hibernate class that requires 3 different sessions. It currently uses 2 sessions and works perfectly. The first session is used to read data from an external db. The second session is used to save data to our internal db. I'm adding a third session because, we need to keep track on the transaction regardless of whether or not the main transaction is successful (the XXXXUpdate object). My problem is that the new session is hanging on tx.commit().
private synchronized void executeUpdate(Long manualUpdateTagIndex) throws Exception {
LogPersistenceLoggingContext ctx = new LogPersistenceThreadContext().getLogPersistenceLoggingContext();
DateTime minTriggerDate = parseDateTimeIfNotNull(minTriggerTime);
DateTime maxTriggerDate = parseDateTimeIfNotNull(maxTriggerTime);
Session webdataSession = null;
Session XXXXUpdateSession = null;
XXXXUpdate update = new XXXXUpdate();
update.setExecutedAt(new DateTime());
update.setStatus(WebdataUpdateStatus.Success);
boolean commit = true;
int tagCount = 0;
List<Period> tagPeriods = new ArrayList<>();
Map<Long, DateTime> tagIndexes = new LinkedHashMap<>();
try {
XXXXUpdateSession = accountingService.openUnmanagedSession();
XXXXUpdateSession.getTransaction().begin();
XXXXUpdateSession.save(update);
HierarchicalLogContext logCtx = new HierarchicalLogContext(String.valueOf(update.getId()));
ctx.pushLoggingContext(logCtx);
ctx.log(logger, Level.INFO, new XXXXLogMarker(), "Executing XXXX data transfer", new Object[]{});
if (webdataSessionFactory == null){
throw new Exception("Failed to obtain webdata session factory. See earlier log entries");
}
try {
webdataSession = webdataSessionFactory.openSession();
} catch (Exception ex) {
update.setStatus(WebdataUpdateStatus.ConnectionError);
throw new Exception("Failed to obtain webdata connection", ex);
}
webdataSession.getTransaction().begin();
if (manualUpdateTagIndex == null) { // automatic tags update
XXXXUpdate lastUpdate = (XXXXUpdate) HibernateUtil.getCurrentSpringManagedSession()
.createCriteria(XXXXUpdate.class)
.add(Restrictions.isNotNull("latestTriggerTimestamp"))
.add(Restrictions.eq("status", WebdataUpdateStatus.Success))
.add(Restrictions.eq("manualUpdate", false))
.addOrder(Order.desc("latestTriggerTimestamp"))
.setMaxResults(1).uniqueResult();
DateTime lastUpdatedDate = Period.defaultEffectiveInstant;
if (minTriggerDate != null) {
lastUpdatedDate = minTriggerDate;
}
if (lastUpdate != null && lastUpdate.getLatestTriggerTimestamp() != null) {
lastUpdatedDate = lastUpdate.getLatestTriggerTimestamp();
ctx.log(logger, Level.INFO, new XXXXLogMarker(),
"Querying for tag event triggers newer than last update timestamp [" + lastUpdate.getLatestTriggerTimestamp() + "]", new Object[]{});
} else {
ctx.log(logger, Level.INFO, new XXXXLogMarker(), "Update has never run. Catching up with history", new Object[]{});
}
#SuppressWarnings("unchecked")
List<XXXXProcessedTagRequest> processedReqs = HibernateUtil.getCurrentSpringManagedSession()
.createCriteria(XXXXProcessedTagRequest.class).list();
Query triggerQuery = webdataSession.createQuery(
"select trigger, "
+ "trigger.TagIndex,"
+ "req "
+ "from XXXXTagEventTrigger as trigger "
+ "join trigger.req as req "
+ "where trigger.EventType in (:eventTypes) "
+ "and trigger.timestamp > :lastUpdateMinusDelta "
+ (maxTriggerDate != null?"and trigger.timestamp < :maxDate ":"")
+ "and req.CurrentState = :currentState "
+ "order by trigger.timestamp,trigger.reqIndex");
triggerQuery.setParameterList("eventTypes", new Object[]{5, 9});
triggerQuery.setParameter("lastUpdateMinusDelta", lastUpdatedDate.minusHours(hoursToKeepProcessedReqs) );
if (maxTriggerDate != null){
triggerQuery.setParameter("maxDate", maxTriggerDate);
}
triggerQuery.setParameter("currentState", 2);
#SuppressWarnings("unchecked")
List<Object[]> allTriggers = triggerQuery.list();
List<Object[]> unprocessedTriggers = removeProcessedTags(new ArrayList<Object[]>(allTriggers),processedReqs,ctx);
for (Object[] row : unprocessedTriggers) {
XXXXTagEventTrigger trigger = (XXXXTagEventTrigger) row[0];
if (lastUpdatedDate == null || lastUpdatedDate.isBefore(trigger.getTimestamp().getMillis())) {
lastUpdatedDate = new DateTime(trigger.getTimestamp());
}
tagIndexes.put((Long) row[1], new DateTime(trigger.getTimestamp()));
XXXXProcessedTagRequest processedReq = new XXXXProcessedTagRequest();
processedReq.setReqIndex(((XXXXTagReq)row[2]).getReqIndex());
processedReq.setTimestamp(trigger.getTimestamp());
HibernateUtil.getCurrentSpringManagedSession().save(processedReq);
}
ctx.log(logger, Level.INFO, new XXXXLogMarker(),
"Found [" + unprocessedTriggers.size() + "] tag event triggers on [" + tagIndexes.size() + "] tags", new Object[]{});
update.setLatestTriggerTimestamp(lastUpdatedDate);
} else { // manual tag update
ctx.log(logger, Level.INFO, new XXXXLogMarker(), "Executing manual update for tag index [" + manualUpdateTagIndex + "]", new Object[]{});
DateTime now = new DateTime();
tagIndexes.put(manualUpdateTagIndex, now);
update.setLatestTriggerTimestamp(now);
update.setManualUpdate(true);
}
if (tagIndexes.size() > 0) {
int totalTagCount = tagIndexes.size();
while (!tagIndexes.isEmpty()) {
List<Long> batchIndexes = new ArrayList<>();
Iterator<Map.Entry<Long, DateTime>> indexIt = tagIndexes.entrySet().iterator();
while (indexIt.hasNext() && batchIndexes.size() < tagBatchSize) {
batchIndexes.add(indexIt.next().getKey());
indexIt.remove();
}
Map<Long, LocalTag> existingTags = new HashMap<>();
#SuppressWarnings("unchecked")
List<LocalTag> existingTagIds = HibernateUtil.getCurrentSpringManagedSession()
.createCriteria(LocalTag.class)
.add(Restrictions.in("tagIndex", batchIndexes))
.add(Restrictions.eq("currentVersion", true)).list();
for (LocalTag lt : existingTagIds) {
existingTags.put(lt.getTagIndex(), lt);
}
ctx.log(logger, Level.INFO, new XXXXLogMarker(),
"Processing tag updates [" + tagCount + "-" + (tagCount + batchIndexes.size()) + "] of [" + totalTagCount + "]", new Object[]{});
Criteria tagCriteria = webdataSession.createCriteria(XXXXTag.class);
tagCriteria.add(Restrictions.in("TagIndex", batchIndexes));
if (!includeTestTags) {
tagCriteria.add(Restrictions.eq("TestTag", "0"));
}
tagCriteria.setFetchMode("XXXXTagMS", FetchMode.JOIN);
tagCriteria.setFetchMode("XXXXTagPS", FetchMode.JOIN);
tagCriteria.setFetchMode("XXXXTagCCList", FetchMode.JOIN);
tagCriteria.setFetchMode("XXXXTagTA", FetchMode.JOIN);
tagCriteria.setFetchMode("XXXXTagCP", FetchMode.JOIN);
tagCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
#SuppressWarnings("unchecked")
List<XXXXTag> tags = tagCriteria.list();
if (manualUpdateTagIndex != null && tags.isEmpty()) {
throw new ValidationException("No tag found for manual update tag index [" + manualUpdateTagIndex + "]");
}
for (XXXXTag tag : tags) {
update.getProcessedTags().add(updateTag(tag, tagIndexes.get(tag.getTagIndex()), existingTags));
tagCount++;
if (fireEventLastActions.contains(tag.getLastAction().trim())) {
tagPeriods.add(new Period(tag.getStartTime().getMillis(), tag.getStopTime().getMillis()));
}
}
HibernateUtil.getCurrentSpringManagedSession().flush();
HibernateUtil.getCurrentSpringManagedSession().clear();
webdataSession.clear();
}
} else {
ctx.log(logger, Level.INFO, new XXXXLogMarker(), "No updates found", new Object[]{});
}
HibernateUtil.getCurrentSpringManagedSession()
.createQuery("delete XXXXUpdate where executedAt < :purgeDate")
.setParameter("purgeDate", new DateTime().minusDays(daysToKeepUpdateHistory))
.executeUpdate();
HibernateUtil.getCurrentSpringManagedSession()
.createQuery("delete XXXXProcessedTagRequest where timestamp < :purgeDate")
.setParameter("purgeDate", new DateTime().minusHours(hoursToKeepProcessedReqs))
.executeUpdate();
update.setStatus(WebdataUpdateStatus.Success);
update.setTagCount(update.getProcessedTags().size());
tagPeriods = Period.merge(tagPeriods);
for (Period p : tagPeriods) {
XXXXUpdatePeriod oup = new XXXXUpdatePeriod();
oup.setXXXXUpdate(update);
oup.setStartDate(p.getStart());
oup.setEndDate(p.getEnd());
update.getPeriods().add(oup);
}
HibernateUtil.getCurrentSpringManagedSession().flush();
ctx.log(logger, Level.INFO, new XXXXLogMarker(), "XXXX data transfer complete. Transferred [" + tagCount + "] tag updates", new Object[]{});
ctx.popLoggingContext(logCtx);
} catch (Exception ex) {
HibernateUtil.getCurrentSpringManagedSession().clear();
update.getProcessedTags().clear();
update.setTagCount(0);
update.setStatus(WebdataUpdateStatus.TransferError);
commit = false;
ctx.log(logger, Level.ERROR, new XXXXLogMarker(), "XXXX data transfer failed", new Object[]{}, ex);
throw new Exception("XXXX data transfer failed", ex);
} finally {
try {
XXXXUpdateSession.saveOrUpdate(update);
XXXXUpdateSession.getTransaction().commit();
} catch (Exception ex) {
commit = false;
ctx.log(logger, Level.ERROR, new XXXXLogMarker(), "Failed to save XXXX transfer update record", new Object[]{}, ex);
throw new Exception("Failed to save XXXX transfer update record", ex);
} finally {
if (!commit) {
webdataSession.getTransaction().rollback();
} else {
webdataSession.getTransaction().commit();
}
ResourceDisposer.dispose(webdataSession);
}
}
}
The new session is the XXXXUpdateSession. The only new code is that which is related to this session. It's some kind of timing issue because, when I use hibernate debug logging, the tx commits without issue. It also commits when I attempt to debug the hibernate commit(). I do not have much experience with hibernate so, I'm probably missing something obvious. Any help would be greatly appreciated. Thanks.
You have opened two transactions webdataSession.getTransaction().begin(); which is causing the issue (20 & 37 lines in the above code).
You can open the second transaction after committing the first transaction.
Also, it is not a best practice to have long methods like which will be very hard to debug the issues and become the nightmare for maintenance/support of the project.
I have an application with a list of people and you can change the info of one certain person when you click on a button. So I am trying to update my database but it says that I do not have a value for the 7th parameter, however I do have 7 values. When I print it, it does give me 7 values. It doesn't have a problem with the null (in my if else) because I already tried it without that.
This is my msql
CREATE TABLE Persoon(
persoonId int(3) NOT NULL AUTO_INCREMENT,
leeftijd int(3),
voornaam varchar(40) NOT NULL,
achternaam varchar (40) NOT NULL,
datum date,
locatieId int(3),
filmId int(3) NOT NULL,
PRIMARY KEY (persoonId),
FOREIGN KEY (filmId) references Film(filmId),
FOREIGN KEY (locatieId) references Locatie(locatieId));
My java code
private void btnWijzigenActionPerformed(java.awt.event.ActionEvent evt) {
Object geselecteerdeObject = lstPersonen.getSelectedValue();
Persoon geselecteerdePersoon = (Persoon) geselecteerdeObject;
if(txtLeeftijd.getText() != ""){
try {
String string = txtDatum.getText();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date datumString = format.parse(string);
Persoon nieuwePersoon = new Persoon(geselecteerdePersoon.getPersoonId(),Integer.parseInt(txtLeeftijd.getText()), txtVoornaam.getText(), txtAchternaam.getText(),datumString,geselecteerdePersoon.getLocatieId(),geselecteerdePersoon.getFilmId());
System.out.println("1p "+geselecteerdePersoon.getPersoonId() + " 2p " +Integer.parseInt(txtLeeftijd.getText()) + " 3p "+txtVoornaam.getText() + " 4p " + txtAchternaam.getText() + " 5p " + datumString + " 6p "+ geselecteerdePersoon.getLocatieId()+ " 7p " +geselecteerdePersoon.getFilmId());;
PersoonDao.updatePersoon(nieuwePersoon);
} catch (ParseException ex) {
Logger.getLogger(HoofdGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
Persoon nieuwePersoon = new Persoon(geselecteerdePersoon.getPersoonId(),0, txtVoornaam.getText(), txtAchternaam.getText(),null,geselecteerdePersoon.getLocatieId(),geselecteerdePersoon.getFilmId());
PersoonDao.updatePersoon(nieuwePersoon);
}
updatePersoonsLijst();
}
My method updatePersoonsLijst
public void updatePersoonsLijst() {
mijnModel.clear();
ArrayList<Persoon> lijstVanPersonen = PersoonDao.getPersonen();
for (Persoon huidigePersoon : lijstVanPersonen) {
mijnModel.addElement(huidigePersoon);
}
}
And my updatePersoon
public static int updatePersoon(Persoon nieuwePersoon) {
int aantalAangepasteRijen = 0;
try {
aantalAangepasteRijen = Database.voerSqlUitEnHaalAantalAangepasteRijenOp("UPDATE Persoon SET leeftijd=?,voornaam=?,achternaam=?,datum=?,locatieId=?,filmId=? WHERE persoonId=?", new Object[] { nieuwePersoon.getLeeftijd(),nieuwePersoon.getVoornaam(), nieuwePersoon.getAchternaam(), nieuwePersoon.getDatum(), nieuwePersoon.getLocatieId(),nieuwePersoon.getFilmId() });
} catch (SQLException ex) {
ex.printStackTrace();
// Foutafhandeling naar keuze
}
return aantalAangepasteRijen;
}
Your update statement is missing last parameter personid - your last is filmid currently.
aantalAangepasteRijen = Database.voerSqlUitEnHaalAantalAangepasteRijenOp("UPDATE Persoon
SET leeftijd=?,voornaam=?,achternaam=?,datum=?,locatieId=?,filmId=?
WHERE persoonId=?", new Object[]
{ nieuwePersoon.getLeeftijd(),
nieuwePersoon.getVoornaam(),
nieuwePersoon.getAchternaam(),
nieuwePersoon.getDatum(),
nieuwePersoon.getLocatieId(),
nieuwePersoon.getFilmId()
// persoonId missing!!
});
I am facing a problem while trying to persist the existing stock in a preproduction environment.
What I am trying to do is actually to loop on a text file and insert substrings from that file into the database.
Here is the class that I execute :
public class RepriseStock {
private static Session session;
public RepriseStock() {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
}
public static int insererPartenaires(String sCurrentLine, int i) {
String sql = "INSERT INTO PARTENAIRE(ID,"
+ "MVTSOC,"
+ " MVTAGR, "
+ "MVTNOMSOC,"
+ "MVTCPTTMAG,"
+ "DATEAGREMENT,"
+ "MVTCHAINE,"
+ "MVTRGPT,"
+ "MVTUNION,"
+ "MVTNOMMAG,"
+ "MVTTELSOC,"
+ "MVTADRMAG,"
+ "MVTVILMAG,"
+ "MVTMAIL,"
+ "MVTSITU)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
Query query = session.createSQLQuery(sql);
query.setInteger(0, i);
query.setInteger(1, Integer.parseInt(sCurrentLine.substring(0, 3)));
query.setInteger(2, Integer.parseInt(sCurrentLine.substring(3, 10)));
query.setString(3, sCurrentLine.substring(10, 34));
query.setInteger(4, Integer.parseInt(sCurrentLine.substring(48, 53)));
query.setString(5, sCurrentLine.substring(77, 83));
query.setInteger(6, Integer.parseInt(sCurrentLine.substring(86, 90)));
query.setInteger(7, Integer.parseInt(sCurrentLine.substring(90, 94)));
// union
query.setInteger(8, Integer.parseInt(sCurrentLine.substring(94, 98)));
// enseigne 30
query.setString(9, sCurrentLine.substring(248, 278));
// tel
query.setString(10, sCurrentLine.substring(278, 293));
// adresse
query.setString(11, sCurrentLine.substring(293, 323));
// ville
query.setString(12, sCurrentLine.substring(323, 348));
// mail
query.setString(13, sCurrentLine.substring(398, 448));
// situ
query.setString(14, sCurrentLine.substring(449, 452));
return query.executeUpdate();
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Module de remplacement de méthode auto-généré
BufferedReader br = null;
RepriseStock rs = new RepriseStock();
try {
String sCurrentLine;
br = new BufferedReader(
new FileReader(
"C:\\Users\\test\\Desktop\\test\\reprise de stock\\nouveauFichierPREPROD.dat"));
int i = 0;
sCurrentLine = br.readLine();
while ((sCurrentLine = br.readLine()) != null) {
i++;
RepriseStock.insererPartenaires(sCurrentLine, i);
System.out.println("Nombre de fois : " + i);
}
System.out.println("total (" + i + " )");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
After the script is executed, i have the total of loops is 1022 times. But the data is not persisted into oracle table (Partenaire)
My log doesn't display any error.
Do you see the issue ?
It looks like you're not committing the transaction.
If you want each update to be a separate transaction, try moving session.beginTransaction(); to the beginning of the insererPartenaires method and capturing the Transaction object returned from that statement in a variable. Then, after each update, make sure to call commit() on the Transaction object.
If you want all of the updates to be the same transaction, move the beginTransaction() and commit() methods to surround the while loop in the main method.
Also just note that you're unnecessarily mixing static and non-static here. Try changing public static int insererPartenaires(String sCurrentLine, int i) to public int insererPartenaires(String sCurrentLine, int i). Then just use the instantiated RepriseStock object to call the method instead of invoking it statically.
You'll also need to change private static Session session to be private Session session