/[PAMELA software]/chewbacca/PamOffLineSW/PacketUser.cpp
ViewVC logotype

Diff of /chewbacca/PamOffLineSW/PacketUser.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1.1.1 by mocchiut, Tue Sep 23 07:20:12 2008 UTC revision 1.17 by mocchiut, Wed Feb 3 14:11:38 2010 UTC
# Line 1  Line 1 
1  //============================================================================  //============================================================================
2  // $Id: PacketUser.cpp,v 1.67 2008-09-05 14:33:48 messineo Exp $  // $Id: PacketUser.cpp,v 1.16 2010/02/02 15:26:09 mocchiut Exp $
3  // Description :  // Description :
4  //============================================================================  //============================================================================
5  #include "PacketUser.h"  #include "PacketUser.h"
6  #include <sys/time.h>  #include <sys/time.h>
7    #include <iostream>
8    
9  namespace PamOffLineSW  namespace PamOffLineSW {
 {  
10  extern LogUtil* mainLogUtil;  extern LogUtil* mainLogUtil;
11  extern short compression ;  extern short compression;
12  extern  char *outDir;  extern char *outDir;
13  extern TSQLServer *sqlServer;  extern TSQLServer *sqlServer;
14  extern bool multiFile;  extern bool multiFile;
15  extern char* fni;  extern char* fni;
# Line 17  extern char * nome_output; Line 17  extern char * nome_output;
17  extern bool is_new_route;  extern bool is_new_route;
18  extern unsigned int download;  extern unsigned int download;
19    
20  extern unsigned int  mmm_number;  extern unsigned int mmm_number;
21  extern unsigned int orbit_number;        extern unsigned int orbit_number;
22  extern unsigned long int time_Offset;  extern unsigned long int time_Offset;
23  extern bool tryMerge;  extern bool tryMerge;
24    extern bool candelete; // EM
25  //marco_new_01  //marco_new_01
26  extern bool single_connection;  extern bool single_connection;
27    
# Line 28  extern bool single_connection; Line 29  extern bool single_connection;
29  extern bool do_cont_check;  extern bool do_cont_check;
30    
31  //marco_new_31:  //marco_new_31:
32  extern char*  db_user;  extern char* db_user;
33  extern char*  db_pwd;  extern char* db_pwd;
34  extern char* connection;          extern char* pelosconnection;
35    
36    //per tenere conto reset obt
37    extern unsigned long int max_pkt_obt;
38    
39    #define TAGVALUELEN 4
40    extern char tag_value[TAGVALUELEN];
41    
42  PacketUser PacketUser::instance;  PacketUser PacketUser::instance;
           
 int PacketUser::numDiscontinity=1;  
 int PacketUser::numPKT=0;  
 int PacketUser::numPKTSaved=0;  
   
 PacketUser& PacketUser::getInstance()  
 {  
         return instance;  
 }  
   
 PacketUser::PacketUser()  
 {        
         gROOT->SetBatch(kTRUE);          
         numDiscontinity=1;  
         numPKTSaved=0;  
         numPKT=0;        
         pkt_number_init=0;  
         obt_init=0;  
         pkt_number_last=0;  
         obt_last=0;  
         obt_time_sync=0;  
         last_time_sync_info=0;  
         real_time_init=0;  
         real_time_last=0;  
         bad_pkt=0;  
         bad_pkt_EventReader=0;  
         bad_pkt_CalibReader=0;  
         reader= NULL;  
         pRun=NULL;  
         reader=new pamela::techmodel::EventReader();  
         Table_ROOT_Good="ROOT_TABLE";  
         Table_ROOT_Bad="ROOT_TABLE_BAD";  
         Table_GL_RESURS_OFFSET="GL_RESURS_OFFSET";  
         Table_ROOT_Merging="ROOT_TABLE_MERGING";          
 //      good_pkt_Calib=0;  
         my_id=0;  
         boot_number=0;  
 }  
   
 PacketUser::~PacketUser()  
 {        
         if(reader){delete reader; reader = NULL;}  
         numDiscontinity=1;  
         numPKTSaved=0;  
         numPKT=0;  
         pkt_number_init=0;  
         obt_init=0;  
         pkt_number_last=0;  
         obt_last=0;  
         obt_time_sync = 0;  
         last_time_sync_info = 0;  
         real_time_init=0;  
         real_time_last=0;  
         bad_pkt=0;  
         bad_pkt_EventReader=0;  
         bad_pkt_CalibReader=0;  
 //      good_pkt_Calib=0;  
         my_id=0;          
         boot_number=0;  
 }  
   
 //Put the packet in a root file. Create a new ROOT file for each group of packets  
 void PacketUser::usePKT(char*& headerPkt, char*& pamPkt, long int length, bool isCons, bool isPKTGood, const PacketType* type,  
                 unsigned long int counter, unsigned long int obt)  
 {                        
         //If the packet type was not recognised before  
         if(!type){return;}  
             
           
 /*      //zzzzzz marco per debug mi salvo il pacchetto vardump  
         if(type==PacketType::VarDump)  
         {                
                 long int  dataLength = length - 2; //the block of data  
                 int b_offset = 4;  
                 while (b_offset < dataLength){  
                  boot_number  = (((UINT32)pamPkt[1+b_offset]<<24)&0xFF000000) + (((UINT32)pamPkt[2+b_offset]<<16)&0x00FF0000) +  (((UINT32)pamPkt[3+b_offset]<<8)&0x0000FF00) + (((UINT32)pamPkt[4+b_offset])&0x000000FF);  
                  cout<<"IN "<<numPKTSaved<<" boot_number "<<boot_number<<" al b_offset "<<b_offset<<" di "<<dataLength<<endl;  
                   
                  b_offset = b_offset + 5;  
                 }  
                   
                  cout<<"IN "<<numPKTSaved<<" FINAL boot_number "<<boot_number<<endl;  
                 savePKT_file(headerPkt,pamPkt,length,false,"vardump");  
                 numPKTSaved++;  
         }  
         return;  
 */  
           
           
         //in order to start ...  
         if(numPKT==0)  
         {                
                 //marco_new_31: metto qui se voglio avere come in origine apertura Connessione all'inizio e chiusura alla fine  
                 //marco_new_01    
                 if(single_connection){  
                         OpenDBConnection(NULL);  
                 }  
43    
44                  setInit(counter,obt);                            int PacketUser::numDiscontinity = 1;
45                  StartGroup();  int PacketUser::numPKT = 0;
46          }  int PacketUser::numPKTSaved = 0;
47                    
48          //here we know if the incoming packet can be considered consecutive to the previuos     one              PacketUser& PacketUser::getInstance() {
49          if((!isCons)&&(numPKT!=0))    return instance;
50          {                        }
51                  setReal_Time();                          
52                  //closing the  group in file rootfilename  PacketUser::PacketUser() {
53                  FinishGroup(rootfilename);                  gROOT->SetBatch(kTRUE);
54                      numDiscontinity = 1;
55                  //numDiscontinity++;    numPKTSaved = 0;
56                  //se gia' e' cambiato download nn cambio numdisco    numPKT = 0;
57                  if(!is_new_route) numDiscontinity++;    pkt_number_init = 0;
58                      obt_init = 0;
59                  //the current pkt will be placed in a new group: rootfilename              pkt_number_last = 0;
60                  setInit(counter,obt);                      obt_last = 0;
61                  StartGroup();    obt_time_sync = 0;
62          }    last_time_sync_info = 0;
63            
64          //add current packet to the group and calculate bad_pkt_EventReader and bad_pkt_CalibReader    //(tassa)
65          int ret=    obt_time_sync_prevvalue = 0;
66          reader->PKT_RunEvent(headerPkt, pamPkt, length, type);    last_time_sync_info_prevvalue = 0;
67          /*    time_is_estimated = false;
68            ret  
69              0    packet good    //EM
70              1    exception but used    //never happen    recoverlimit = 400;
71              2    CRC exception but used    idtorecover = new TArrayI(100);
72              3    CALIBRATION PACKET with error but used    arsize = 0;
73             -1    CRC exception  packet DISCARDED  
74             -2    FATAL exception packet DISCARDED //never happen    real_time_init = 0;
75             -3    No way to read events of this type. packet DISCARDED( es OLD CalibCal)    real_time_last = 0;
76          ret = 10 if the packet is good but comes from a cadre with VRL problems    bad_pkt = 0;
77          */    bad_pkt_EventReader = 0;
78              bad_pkt_CalibReader = 0;
79          //here we know if the packet comes from one or more corrupted cadres    reader = NULL;
80          //if(!isPKTGood){bad_pkt++;}    pRun = NULL;
81          if((!isPKTGood)&&(!ret)){ret=10;}          reader = new pamela::techmodel::EventReader();
82              Table_ROOT_Good = "ROOT_TABLE";
83          switch (ret)    Table_ROOT_Bad = "ROOT_TABLE_BAD";
84          {    Table_GL_RESURS_OFFSET = "GL_RESURS_OFFSET";
85                  case 0: {numPKTSaved++; break;}    Table_ROOT_Merging = "ROOT_TABLE_MERGING";
86                  case 1: {bad_pkt_EventReader++; numPKTSaved++; break;}    //    good_pkt_Calib=0;
87                  case 2: {bad_pkt_EventReader++;numPKTSaved++;  break;}    my_id = 0;
88                  case 3: {bad_pkt_CalibReader++; numPKTSaved++; break;}    boot_number = 0;
89                  case 10: {bad_pkt++; numPKTSaved++; break;}    //(tassa)
90                  default:{    boot_number_prevvalue = 0;
91                          stringstream oss;  
92                          oss.str()="";    //(tassa)
93                          oss<<"Packet DISCARDED, reason = "<<ret;    //        id_to_recover[1000]; // Emiliano: che si vuole fare con questa riga? cosi` non fa nulla...
94                          string msg = oss.str();    id_to_recover_index = 0;
95                          mainLogUtil->logAll(msg);  }
96                          break;  
97                  }  PacketUser::~PacketUser() {
98          }    if (reader) {
99        delete reader;
100        reader = NULL;
101      }
102      numDiscontinity = 1;
103      numPKTSaved = 0;
104      numPKT = 0;
105      pkt_number_init = 0;
106      obt_init = 0;
107      pkt_number_last = 0;
108      obt_last = 0;
109      obt_time_sync = 0;
110      last_time_sync_info = 0;
111      obt_time_sync_prevvalue = 0;
112      last_time_sync_info_prevvalue = 0;
113      time_is_estimated = false;
114    
115      real_time_init = 0;
116      real_time_last = 0;
117      bad_pkt = 0;
118      bad_pkt_EventReader = 0;
119      bad_pkt_CalibReader = 0;
120      //    good_pkt_Calib=0;
121      my_id = 0;
122      boot_number = 0;
123      boot_number_prevvalue = 0;
124    }
125    
126    //Put the packet in a root file. Create a new ROOT file for each group of packets
127    void PacketUser::usePKT(char*& headerPkt, char*& pamPkt, long int length, bool isCons, bool isPKTGood,
128        const PacketType* type, unsigned long int counter, unsigned long int obt) {
129      //If the packet type was not recognised before
130      if (!type) {
131        return;
132      }
133    
134      //in order to start ...
135      if (numPKT == 0) {
136        if (single_connection) {
137          OpenDBConnection(NULL);
138        }
139    
140        setInit(counter, obt);
141        StartGroup();
142      }
143    
144      //here we know if the incoming packet can be considered consecutive to the previuos   one
145      if ((!isCons) && (numPKT != 0)) {
146        setReal_Time();
147        //closing the group in file rootfilename
148        FinishGroup(rootfilename);
149    
150        //se gia' e' cambiato download non cambio numdisco
151        if (!is_new_route) {
152          numDiscontinity++;
153        }
154    
155        //the current pkt will be placed in a new group: rootfilename
156        setInit(counter, obt);
157        StartGroup();
158      }
159    
160      //add current packet to the group and calculate bad_pkt_EventReader and bad_pkt_CalibReader
161      int ret = reader->PKT_RunEvent(headerPkt, pamPkt, length, type);
162      /*
163       ret
164       0    packet good
165       1    exception but used    //never happen
166       2    CRC exception but used
167       3    CALIBRATION PACKET with error but used
168       -1    CRC exception  packet DISCARDED
169       -2    FATAL exception packet DISCARDED //never happen
170       -3    No way to read events of this type. packet DISCARDED( es OLD CalibCal)
171       ret = 10 if the packet is good but comes from a cadre with VRL problems
172       */
173    
174      //here we also know if the packet comes from one or more corrupted cadres
175      if ((!isPKTGood) && (!ret)) {
176        ret = 10;
177      }
178      switch (ret) {
179      case 0: {
180        numPKTSaved++;
181        break;
182      }
183      case 1: {
184        bad_pkt_EventReader++;
185        numPKTSaved++;
186        break;
187      }
188      case 2: {
189        bad_pkt_EventReader++;
190        numPKTSaved++;
191        break;
192      }
193      case 3: {
194        bad_pkt_CalibReader++;
195        numPKTSaved++;
196        break;
197      }
198      case 10: {
199        bad_pkt++;
200        numPKTSaved++;
201        break;
202      }
203      default: {
204        stringstream oss;
205        oss.str() = "";
206        oss << "Packet DISCARDED, reason = " << ret;
207        string msg = oss.str();
208        mainLogUtil->logAll(msg);
209        break;
210      }
211      }
212    
213      /*
214       if ((ret==0)&&((type==PacketType::CalibTrk1)||(type==PacketType::CalibTrk2)|| (type==PacketType::CalibCalPed)))
215       {
216       good_pkt_Calib++;//maybe I will remove this in future
217       }
218       */
219    
220  /*          if (ret >= 0)// only the packet not discarded of course
221          if ((ret==0)&&((type==PacketType::CalibTrk1)||(type==PacketType::CalibTrk2)|| (type==PacketType::CalibCalPed)))      setLast(counter, obt);
         {                                
                 good_pkt_Calib++;//maybe I will remove this in future  
         }  
 */        
           
         if(ret>=0)// only the packet not discarded of course  
                 setLast(counter,obt);  
           
 //TODO: decide what kind of packet I can use here  
 //      if((ret==0)||(ret==10))//I want to use only good packet  
         if(ret>=0)//I want to use only accepted packet  
         {        
                 setTimeSync(pamPkt, length, type);//marco_new: here I retrieve also the boot_number if packet type is vardump  
         }  
222    
223          //just to be sure ...    //TODO: decide what kind of packet I can use here
224          if(pamPkt){delete[] pamPkt; pamPkt = NULL;}        //    if((ret==0)||(ret==10))//I want to use only good packet
225          //just to be sure ...    if (ret >= 0)//I want to use only accepted packet
226          if(headerPkt){delete[] headerPkt; headerPkt = NULL;}    {
227        setTimeSync(pamPkt, length, type);//here I retrieve also the boot_number if packet type is vardump
228      }
229    
230      //just to be sure ...
231      if (pamPkt) {
232        delete[] pamPkt;
233        pamPkt = NULL;
234      }
235      if (headerPkt) {
236        delete[] headerPkt;
237        headerPkt = NULL;
238      }
239    
240          numPKT++;                  numPKT++;
241  }  }
242    
243  //set the value of the counter and obt of the first packet of the group  //set the value of the counter and obt of the first packet of the group
244  void PacketUser::setInit(unsigned long int counter, unsigned long int obt)  void PacketUser::setInit(unsigned long int counter, unsigned long int obt) {
245  {                                  sprintf(nnnn_mmm_ppp, "%05d_%03d_%03d", orbit_number, mmm_number, download);
246          sprintf(nnnn_mmm_ppp,"%05d_%03d_%03d", orbit_number, mmm_number, download);        sprintf(rootfilename, "%s_%s_%d", nome_output, nnnn_mmm_ppp, numDiscontinity);
247          sprintf(rootfilename,"%s_%s_%d", nome_output, nnnn_mmm_ppp, numDiscontinity);    pkt_number_init = counter;
248          pkt_number_init=counter;    obt_init = obt;
249          obt_init=obt;    pkt_number_last = 0;
250          pkt_number_last=0;    obt_last = 0;
251          obt_last=0;    real_time_init = 0;
252          real_time_init=0;    real_time_last = 0;
253          real_time_last=0;    bad_pkt = 0;
254          bad_pkt=0;          numPKTSaved = 0;
255          numPKTSaved=0;    bad_pkt_EventReader = 0;
256          bad_pkt_EventReader=0; bad_pkt_CalibReader=0;    bad_pkt_CalibReader = 0;
257          //good_pkt_Calib=0;    //good_pkt_Calib=0;
258            
259          //marco_NB:    //marco_NB:
260          //ogni volta che trovo una discontinuit� resetto come se mi trovassi in un nuovo download oppure uso i vecchi valori se esistono?    //ogni volta che trovo una discontinuita` resetto come se mi trovassi in un nuovo download oppure uso i vecchi valori se esistono?
261          obt_time_sync=0; last_time_sync_info=0; boot_number=0;  
262  //      NB: se ho discontinuita in genere non so a che download appartiene potrebbe proprio essere sbagliato tenere i vecchi valori    if ( obt_time_sync ) obt_time_sync_prevvalue = obt_time_sync; // save the last NOT NULL obt_time_sync! EM
263      if ( last_time_sync_info ) last_time_sync_info_prevvalue = last_time_sync_info; // save the last NOT NULL last_time_sync
264      time_is_estimated = false;
265      obt_time_sync = 0;
266      last_time_sync_info = 0;
267      boot_number_prevvalue = boot_number;
268      boot_number = 0;
269    
270      //    NB: se ho discontinuita in genere non so a che download appartiene potrebbe proprio essere sbagliato tenere i vecchi valori
271    
272  }  }
273    
274  //starts a new root file  //starts a new root file
275  void PacketUser::StartGroup()  void PacketUser::StartGroup() {
276  {          pRun = new PamelaRun(rootfilename, gSystem->ExpandPathName(outDir), multiFile, compression); // EMI
277          pRun = new PamelaRun(rootfilename, outDir , multiFile, compression);    strcat(rootfilename, ".root");
278          //marco_new: aggiunta estensione .root    reader->Init(pRun);
279          strcat(rootfilename,".root");    stringstream oss;
280          reader->Init(pRun);                        oss.str() = "";
281          stringstream oss;    oss << "######################### Start a new group in file: " << rootfilename << " ############################";
282          oss.str()="";    string msg = oss.str();
283          oss<<"######################### Start a new group in file: "<< rootfilename <<" ############################";    mainLogUtil->logInfo(msg);
         string msg = oss.str();  
         mainLogUtil->logInfo(msg);  
284  }  }
285    
286  //set the value of the counter and obt of the last packet of the group  //set the value of the counter and obt of the last packet of the group
287  void PacketUser::setLast(unsigned long int counter, unsigned long int obt)  void PacketUser::setLast(unsigned long int counter, unsigned long int obt) {
288  {    pkt_number_last = counter;
289          pkt_number_last=counter;    obt_last = obt;
290          obt_last=obt;  }
291  }  
292    //retrieve obt_time_sync and last_time_sync_info from packet if type has special values and BOOT_NUMBER
293    void PacketUser::setTimeSync(char* packet, long int pktLength, const PacketType* type) {
294      //do nothing
295  //retrieve obt_time_sync and last_time_sync_info from packet if type has special values    if (!do_cont_check) {
296  void PacketUser::setTimeSync(char* packet, long int pktLength, const PacketType* type)      if (is_new_route)
297  {        is_new_route = false;
298      //do nothing      return;
299          if(!do_cont_check) {    }
300                  if(is_new_route)  
301                          is_new_route=false;    //TODO: usare anche MCMD ... NOTA: questo da sempre errore ret != 0
302                  return;    //In RunHeader e RunTrailer sono in secondi(?), controllare se aggiungo altri tipi di paccheti se invece sono in secondi
303          }    // devo ricalcolare tutto non per ogni gruppetto (ROOT file) ma solo se cambia download
304              //When I found a new download I need to reset all values
305  //TODO: usare anche MCMD ... NOTA: questo da sempre errore ret != 0    if (is_new_route) {
306  //In RunHeader e RunTrailer sono in secondi(?), controllare se aggiungo altri tipi di paccheti se invece sono in secondi      //reset
307                is_new_route = false;
308                //(tassa) ci ho ripensato se stiamo in un secondo download non prendiamo i bootnumber e timesync del precedente!
309          // devo ricalcolare tutto non per ogni gruppetto (ROOT file) ma solo se cambia download      obt_time_sync_prevvalue = 0;//obt_time_sync;
310                last_time_sync_info_prevvalue = 0;//last_time_sync_info;
311          //When I found a new download I need to reset all values  
312          if(is_new_route)      obt_time_sync = 0;
313          {        last_time_sync_info = 0;
314            //reset      boot_number_prevvalue = 0;//boot_number;
315                  is_new_route=false;      boot_number = 0;
316                  obt_time_sync=0; last_time_sync_info=0;      time_is_estimated = false;
317                  boot_number=0;      if (time_Offset)
318                  if(time_Offset)        timeOffset = time_Offset;
319                          timeOffset=time_Offset;      else
320                  else                    timeOffset = retrieveTimeOffset(Table_GL_RESURS_OFFSET);
321                          timeOffset=retrieveTimeOffset(Table_GL_RESURS_OFFSET);    }
322          }  
323              //retrieve boot number if possible
324          //retrieve boot number if possible    setBootNumber(packet, pktLength, type);
325          setBootNumber(packet,pktLength,type);  
326      //Retrieve if possible obt_time_sync and last_time_sync_info
327          //Retrieve if possible obt_time_sync and last_time_sync_info    int offset = 0;
328          int offset=0;    if (type == PacketType::RunHeader) {
329          if(type==PacketType::RunHeader)      offset = 0;
330          {                  }
331                  offset=0;    else if (type == PacketType::RunTrailer) {
332          }      offset = 3;
333          else if(type==PacketType::RunTrailer)    }
334          {          else if (type == PacketType::Mcmd) {
335                  offset=3;      //          mainLogUtil->logAll("TODO: Packet Mcmd now is not used to retrieve Absolute time. This may cause problems somewhere.");
336          }      return;
337          else if(type==PacketType::Mcmd)    }
338          {          else {
339  //              mainLogUtil->logAll("TODO: Packet Mcmd now is not used to retrieve Absolute time. This may cause problems somewhere.");      return;
340                  return;    }
341          }  
342          else    //I don't need to retrieve them again if they are good
343          {          //  if ((obt_time_sync) || (last_time_sync_info))
344                  return;    //    return;
345          }                  // no, do it, since there is a (small indeed) time drift due to different clock of PAMELA CPU and RESURS CPU...
346            
347          //I don't need to retrieve them again if they are good    obt_time_sync = (((UINT32) packet[5 + offset] << 24) & 0xFF000000) + (((UINT32) packet[6 + offset] << 16)
348          if((obt_time_sync)||(last_time_sync_info)) return;        & 0x00FF0000) + (((UINT32) packet[7 + offset] << 8) & 0x0000FF00) + (((UINT32) packet[8 + offset]) & 0x000000FF);
349      last_time_sync_info = (((UINT32) packet[9 + offset] << 24) & 0xFF000000) + (((UINT32) packet[10 + offset] << 16)
350          obt_time_sync = (((UINT32)packet[5+offset]<<24)&0xFF000000) + (((UINT32)packet[6+offset]<<16)&0x00FF0000) + (((UINT32)packet[7+offset]<<8)&0x0000FF00) + (((UINT32)packet[8+offset])&0x000000FF);        & 0x00FF0000) + (((UINT32) packet[11 + offset] << 8) & 0x0000FF00)
351          last_time_sync_info = (((UINT32)packet[9+offset]<<24)&0xFF000000) + (((UINT32)packet[10+offset]<<16)&0x00FF0000) + (((UINT32)packet[11+offset]<<8)&0x0000FF00) + (((UINT32)packet[12+offset])&0x000000FF);                      + (((UINT32) packet[12 + offset]) & 0x000000FF);
352    
353          stringstream oss;    stringstream oss;
354          oss.str()="";    oss.str() = "";
355          oss<<"In download: "<<download<<" timeOffset: "<<timeOffset<<" obt_time_sync: "<<obt_time_sync<<" last_time_sync_info: "<<last_time_sync_info<<" using Packet Type: "<<type->GetName().c_str();    oss << "In download: " << download << " timeOffset: " << timeOffset << " obt_time_sync: " << obt_time_sync
356          string msg = oss.str();        << " last_time_sync_info: " << last_time_sync_info << " using Packet Type: " << type->GetName();
357          mainLogUtil->logAll(msg);    //    oss<<"In download: "<<download<<" timeOffset: "<<timeOffset<<" obt_time_sync: "<<obt_time_sync<<" last_time_sync_info: "<<last_time_sync_info<<" using Packet Type: "<<type->GetName().c_str();
358      string msg = oss.str();
359      mainLogUtil->logAll(msg);
360  }  }
361    
362  //Boot Number  //Boot Number
363  void PacketUser::setBootNumber(char* packet, long int pktLength, const PacketType* type)  void PacketUser::setBootNumber(char* packet, long int pktLength, const PacketType* type) {
364  {    //se gia calcolato esco: lo calcolo una volta per download e per continuita'
365          //se gia calcolato esco: lo calcolo una volta per download e per continuit�      if (boot_number)
366          if(boot_number) return;      return;
367  //todo: controlla se algo giusto: preso da VarDumpReader.cpp  
368  //mmm e' sbagliatissimo cambiare !!!        if (type == PacketType::VarDump) {
369          if(type==PacketType::VarDump)      int b_offset = 34;//4+5*6
370          {                            boot_number = (((UINT32) packet[1 + b_offset] << 24) & 0xFF000000) + (((UINT32) packet[2 + b_offset] << 16)
371                  long int  dataLength = pktLength - 2; //the block of data          & 0x00FF0000) + (((UINT32) packet[3 + b_offset] << 8) & 0x0000FF00) + (((UINT32) packet[4 + b_offset])
372                  int b_offset = 4;          & 0x000000FF);
373                  while (b_offset < dataLength){  
374                   boot_number  = (((UINT32)packet[1+b_offset]<<24)&0xFF000000) + (((UINT32)packet[2+b_offset]<<16)&0x00FF0000) +  (((UINT32)packet[3+b_offset]<<8)&0x0000FF00) + (((UINT32)packet[4+b_offset])&0x000000FF);      /*
375                   b_offset = b_offset + 5;       long int  dataLength = pktLength - 2; //the block of data
376                  }       int b_offset = 4;
377                  stringstream oss;       while (b_offset < dataLength){
378                  oss.str()="";       boot_number  = (((UINT32)packet[1+b_offset]<<24)&0xFF000000) + (((UINT32)packet[2+b_offset]<<16)&0x00FF0000) +  (((UINT32)packet[3+b_offset]<<8)&0x0000FF00) + (((UINT32)packet[4+b_offset])&0x000000FF);
379                  oss<<"In download: "<<download<<" boot_number: "<<boot_number<<" using Packet Type: "<<type->GetName().c_str();       b_offset = b_offset + 5;
380                  string msg = oss.str();       }
381                  mainLogUtil->logAll(msg);       */
382                  return;      stringstream oss;
383          }      oss.str() = "";
384          else      //          oss<<"In download: "<<download<<" boot_number: "<<boot_number<<" using Packet Type: "<<type->GetName().c_str();
385          {            oss << "In download: " << download << " boot_number: " << boot_number << " using Packet Type: " << type->GetName();
386                  return;      string msg = oss.str();
387          }                    mainLogUtil->logAll(msg);
388        return;
389      }
390      else {
391        return;
392      }
393    
394  }  }
395  //set the real time of the first packet and the last packet oif a group of packet if possible  //set the real time of the first packet and the last packet oif a group of packet if possible
396  void PacketUser::setReal_Time()  void PacketUser::setReal_Time() {
397  {  
398          if((obt_time_sync)||(last_time_sync_info))    if (!obt_time_sync && !last_time_sync_info && numPKTSaved > recoverlimit) {
399          {                    time_is_estimated = true;
400                  real_time_init=(obt_init/1000-obt_time_sync)+last_time_sync_info;      obt_time_sync = obt_time_sync_prevvalue;
401                  real_time_last=(obt_last/1000-obt_time_sync)+last_time_sync_info;            last_time_sync_info = last_time_sync_info_prevvalue;
402                  real_time_init+=timeOffset;    }
403                  real_time_last+=timeOffset;                if (obt_time_sync || last_time_sync_info) {
404          }            real_time_init = (obt_init / 1000 - obt_time_sync) + last_time_sync_info;
405        //se obt si e' resettato
406        if (obt_last < obt_init) {
407          real_time_last = (max_pkt_obt / 1000 + obt_last / 1000 - obt_time_sync) + last_time_sync_info;
408          stringstream oss;
409          oss.str() = "";
410          oss << "obt_last(" << obt_last << ") < obt_init(" << obt_init
411              << "). It is due to Pamela Reset. Adding max_pkt_obt(" << max_pkt_obt
412              << ") to obt_last in order to compute real_time_last";
413          string msg = oss.str();
414          mainLogUtil->logWarning(msg);
415        }
416        else
417          real_time_last = (obt_last / 1000 - obt_time_sync) + last_time_sync_info;
418        real_time_init += timeOffset;
419        real_time_last += timeOffset;
420      }
421    }
422    
423    void PacketUser::setReal_TimeRECOVERY(
424    unsigned long int & _real_time_init,
425    unsigned long int & _real_time_last,
426    unsigned long int _obt_init,
427    unsigned long int _obt_last
428    ) {
429      
430      if (obt_time_sync || last_time_sync_info) {
431        _real_time_init = (_obt_init / 1000 - obt_time_sync) + last_time_sync_info;
432        //se obt si e' resettato
433        if (_obt_last < _obt_init) {
434          _real_time_last = (max_pkt_obt / 1000 + _obt_last / 1000 - obt_time_sync) + last_time_sync_info;
435          stringstream oss;
436          oss.str() = "";
437          oss << "obt_last(" << obt_last << ") < obt_init(" << obt_init
438              << "). It is due to Pamela Reset. Adding max_pkt_obt(" << max_pkt_obt
439              << ") to obt_last in order to compute real_time_last";
440          string msg = oss.str();
441          mainLogUtil->logWarning(msg);
442        }
443        else
444          _real_time_last = (_obt_last / 1000 - obt_time_sync) + last_time_sync_info;
445        _real_time_init += timeOffset;
446        _real_time_last += timeOffset;
447      }
448  }  }
449    
450    
451  //timeOffset  //timeOffset
452  //retrieve from table Table_GL_RESURS_OFFSET timeOffset    //retrieve from table Table_GL_RESURS_OFFSET timeOffset  
453  unsigned long int PacketUser::retrieveTimeOffset(char * table)  unsigned long int PacketUser::retrieveTimeOffset(const char * table) {
454  {            if (!do_cont_check)
455          if(!do_cont_check) return 0;      return 0;
456            
457          //if(!table){table=Table_GL_RESURS_OFFSET}    //if(!table){table=Table_GL_RESURS_OFFSET}
458    
459      if (!single_connection) {
460        OpenDBConnection(NULL);// no, locak tutto Nota qui ho deciso di lockare solo questa tabella e non tutte
461      }
462    
463      UInt_t t0 = 0;//toffset
464      stringstream oss;
465      oss.str("");
466      oss
467          << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "
468          << table << " WHERE SPECIAL_FILE='" << nnnn_mmm_ppp << "';";
469    
470      string msg = oss.str();
471      mainLogUtil->logAll(msg);
472    
473      TSQLResult* res = NULL;
474      TSQLRow* row = NULL;
475      res = sqlServer->Query(oss.str().c_str());
476      if (!res) {
477        mainLogUtil->logError("DBError retrieveTimeOffset 1");
478        return 0;
479      }
480    
481      row = res->Next();
482      if (!row) {
483        if (res) {
484          delete res;
485          res = NULL;
486        }
487    
488          //marco_new_31:metto qui se voglio aprire e chiudere Connessione solo quando serve      oss.str("");
489          //marco_new_01        oss
490          if(!single_connection){          << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "
491                  OpenDBConnection(table);//Nota qui ho deciso di lockare solo questa tabella e non tutte          << table << " WHERE FROM_ORBIT < " << orbit_number << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
492          }  
493        string msg2 = oss.str();
494          UInt_t t0 = 0;  //toffset                    mainLogUtil->logAll(msg2);
495                            
496          stringstream oss;      res = sqlServer->Query(oss.str().c_str());
497          oss.str("");      if (!res) {
498          oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "<<      table <<" WHERE SPECIAL_FILE='"        mainLogUtil->logError("DBError retrieveTimeOffset 2");
499                << nnnn_mmm_ppp << "';";        return 0;
500        }
501          string msg = oss.str();      row = res->Next();
502          mainLogUtil->logAll(msg);            if (!row) {
503          mainLogUtil->logError("DBError retrieveTimeOffset 3");
504          TSQLResult* res=NULL;                                    return 0;
505          TSQLRow* row=NULL;            }
506          res= sqlServer->Query(oss.str().c_str());                          
507          if(!res)    }
508          {                
509                  mainLogUtil->logError("DBError retrieveTimeOffset 1");    TTimeStamp tu = TTimeStamp((UInt_t) atoi(row->GetField(0)), (UInt_t) atoi(row->GetField(1)), (UInt_t) atoi(
510                  return 0;        row->GetField(2)), (UInt_t) atoi(row->GetField(3)), (UInt_t) atoi(row->GetField(4)), (UInt_t) atoi(row->GetField(
511          }        5)), 0, true, 0);
512      t0 = (UInt_t) tu.GetSec();
513      row=res->Next();  
514      if (!row )    if (res) {
515      {      delete res;
516          if(res){delete res; res = NULL;}      res = NULL;
517      }
518          oss.str("");    if (row) {
519          oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM "<<      table <<" WHERE FROM_ORBIT < "      delete row;
520          << orbit_number << " order by FROM_ORBIT desc limit 1;";      row = NULL;
521              }
522                  string msg2 = oss.str();  
523                  mainLogUtil->logAll(msg2);    if (!single_connection) {
524        CloseDBConnection();
525                  res= sqlServer->Query(oss.str().c_str());                          }
526          if(!res)    return t0;
         {    
                 mainLogUtil->logError("DBError retrieveTimeOffset 2");  
                 return 0;  
         }  
         row=res->Next();  
         if (!row)  
         {  
                 mainLogUtil->logError("DBError retrieveTimeOffset 3");  
                 return 0;  
         }  
                   
      }  
       
       TTimeStamp tu = TTimeStamp((UInt_t)atoi(row->GetField(0)),(UInt_t)atoi(row->GetField(1)),(UInt_t)atoi(row->GetField(2)),(UInt_t)atoi(row->GetField(3)),(UInt_t)atoi(row->GetField(4)),(UInt_t)atoi(row->GetField(5)),0,true,0);  
       t0 = (UInt_t)tu.GetSec();  
         
         if(res){delete res; res = NULL;}  
         if(row){delete row; row = NULL;}          
   
         //marco_new_31:metto qui se voglio aprire e chiudere Connessione solo quando serve  
         //marco_new_01    
         if(!single_connection){  
                 CloseDBConnection();              
         }  
  return t0;  
527  }  }
528    
529  //this is public and can be called from the main at the end of the game  //this is public and can be called from the main at the end of the game
530  void PacketUser::FinishLastGroup()  void PacketUser::FinishLastGroup() {
531  {          mainLogUtil->logAll("######################### Closing the last group ############################");
532          mainLogUtil->logAll("######################### Closing the last group ############################");      setReal_Time();
533          setReal_Time();    FinishGroup(rootfilename);
534          FinishGroup(rootfilename);    mainLogUtil->logAll("######################### Closed the last group ############################");
535          mainLogUtil->logAll("######################### Closed the last group ############################");    //
536              if (single_connection) {
537          //marco_new_31:metto qui se voglio avere come in origine apertura Connessione all'inizio e chiusura alla fine      CloseDBConnection();
538          //marco_new_01      }
         if(single_connection){  
                 CloseDBConnection();              
         }  
539  }  }
540    
541  //Finish the old root file  //Finish the old root file
542  void PacketUser::FinishGroup(char * filename)  void PacketUser::FinishGroup(char * filename) {
543  {    if (pRun) {
544          if(pRun)      if ( !( !real_time_init && !real_time_last && numPKTSaved <= recoverlimit ) || !candelete  ) pRun->WriteFiles();
545          {      delete pRun;
546                  pRun->WriteFiles();                                  pRun = NULL;
547                  delete pRun; pRun = NULL;                    stringstream close;
548                  stringstream close;      close.str() = "";
549                  close.str()="";      string msg;
550                  string msg;  
551        close << "TAG XX ######################### Close group in file: " << rootfilename << " ############################";
552                  close<<"######################### Close group in file: "<< rootfilename <<" ############################";      msg = close.str();
553                  msg = close.str();      mainLogUtil->logInfo(msg);
554                  mainLogUtil->logInfo(msg);  
555        // se non faccio proprio controlli su continuita' neanche salvo su DB
556                  // se non faccio proprio controlli su continuita' neanche salvo su DB      if (!do_cont_check)
557                  if(!do_cont_check) return;        return;
558    
559        stringstream oss;
560        oss.str() = "";
561    
562        //TODO: check when I don't want to log in DB informations
563        // se non ho salvato nessun pacchetto
564        if (numPKTSaved == 0) {
565          stringstream err;
566          err.str() = "";
567          err << "NO PACKET SAVED in file: " << rootfilename << " The group is empty: you can remove this file.";
568          msg = err.str();
569          mainLogUtil->logError(msg);
570          //      return;
571        }
572    
573        //se non ho salvato nessun pacchetto buono
574        if ((numPKTSaved - bad_pkt_EventReader - bad_pkt_CalibReader - bad_pkt) == 0) {
575          stringstream err;
576          err.str() = "";
577          err << "NO GOOD PACKET SAVED in file: " << rootfilename << " The group is BAD: you may want to remove this file.";
578          msg = err.str();
579          mainLogUtil->logInfo(msg);
580          //                        mainLogUtil->logError(msg);
581          //                        return; //TODO: decidi se nn vuoi affatto usarlo o addirittura salvarlo tra i BAD???
582        }
583    
584        if (!single_connection) {
585          OpenDBConnection(NULL);//Nota qui ho deciso di lockare tutte le tabelle
586        }
587    
588    
589        //don't save in Table_ROOT_Good and don't search for ROOT files in the same temporal range
590        if ((!real_time_init) && (!real_time_last)) {
591          //saved in another table for future study
592          if (saveROOT_DB(
593              Table_ROOT_Bad,
594              outDir,// here outDir is good, no expand EMI
595              filename, pkt_number_init, pkt_number_last, obt_init, obt_last, obt_time_sync, last_time_sync_info,
596              real_time_init, real_time_last, boot_number, timeOffset, bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader,
597              numPKTSaved, fni, time_is_estimated) == true) {
598            oss.str() = "";
599            oss << "Saved information regarding file: " << filename << " in table " << Table_ROOT_Bad;
600            msg = oss.str();
601            mainLogUtil->logInfo(msg);
602          }
603          else {
604            oss.str() = "";
605            oss << "Problem storing information in DB regarding file: " << filename;
606            msg = oss.str();
607            mainLogUtil->logError(msg);
608          }
609    
610    
611    
612          if ( numPKTSaved > recoverlimit){ // EM
613            //
614            if ( obt_time_sync && last_time_sync_info ){
615              stringstream err;
616              err.str() = "";
617              err << "(EM): -- RECOVERING WHEN NUMPACKET > "<< recoverlimit <<"!! -- file=<" << filename << ">. We have a previous time sync, immediate recovery!\n";
618              msg = err.str();
619              mainLogUtil->logInfo(msg);
620              //
621              setReal_TimeRECOVERY(
622                                   real_time_init,
623                                   real_time_last,
624                                   obt_init,
625                                   obt_last
626                                   );
627              //
628            } else {
629              stringstream err;
630              err.str() = "";
631              err << "TAG(tassa): -- RECOVERING WHEN NUMPACKET > "<< recoverlimit <<"!! -- file=<" << filename << ">. Saving in a queue to try alfer to recover it!\n";
632              msg = err.str();
633              mainLogUtil->logInfo(msg);
634              
635              //      TString qu = Form("select ID_N from ROOT_TABLE_BAD order by INSERT_TIME desc limit 1;"); //  <=========================
636              TString qu = Form("select ID_N from ROOT_TABLE_BAD where FILE_NAME='%s' and PKT_NUMBER_INIT=%i and INSERTED_BY='%s';",filename,pkt_number_init,tag_value); //  <=========================
637              TSQLResult *result = sqlServer->Query(qu.Data());
638              TSQLRow    *row = result->Next();
639              Int_t eid = -1;
640              if ( row ) eid = (Int_t)atoi(row->GetField(0));
641              idtorecover->AddAt(eid,arsize);
642              arsize++;
643              if ( arsize > 100 ) idtorecover->Set(arsize);
644              //    dbinfo *app = new dbinfo( outDir,
645              //                              filename, pkt_number_init, pkt_number_last, obt_init, obt_last, boot_number, timeOffset, bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader,
646              //                              numPKTSaved, fni, time_is_estimated);
647              //    m_dbinfos.push_back(app);
648            }
649            
650            CleanDisk();
651            //      if (!single_connection) {
652            //        CloseDBConnection();
653            //      }
654            //      return; // commented here...
655    
656          };
657        }
658    
659        if ( real_time_init || real_time_last) {
660          //saves info in DB in table Table_ROOT
661          if (boot_number == 0)
662            boot_number = boot_number_prevvalue;
663          
664          if (saveROOT_DB(
665                          Table_ROOT_Good,
666                          outDir, // here outDir is good, no expand EMI
667                          filename, pkt_number_init, pkt_number_last, obt_init, obt_last, obt_time_sync, last_time_sync_info,
668                          real_time_init, real_time_last, boot_number, timeOffset, bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader,
669                          numPKTSaved, fni, time_is_estimated) == true) {
670            oss.str() = "";
671            oss << "Saved information regarding file: " << filename << " in table " << Table_ROOT_Good << " id= " << my_id;
672            msg = oss.str();
673            mainLogUtil->logInfo(msg);
674                    
675                  stringstream oss;          if (tryMerge) {
676                  oss.str()="";            merge_ROOTfiles();
677                            }
678                  //TODO: check when I don't want to log in DB informations        } else {
679          oss.str() = "";
680                  // se non ho salvato nessun pacchetto        oss << "Problem storing information in DB regarding file: " << filename;
681                  if(numPKTSaved==0){                            msg = oss.str();
682                          stringstream err;        mainLogUtil->logError(msg);
683                          err.str()="";        }
684                          err<<"NO PACKET SAVED in file: "<< rootfilename <<" The group is empty: you can remove this file.";      };
685                          msg = err.str();  
686                          mainLogUtil->logError(msg);      // if dbinfo is not empty than
687                          return;      if ( arsize > 0 ){
688                  }  
689                                  if ( !obt_time_sync || !last_time_sync_info ){
690                  //se non ho salvato nessun pacchetto buono          TString *nomino=new TString(rootfilename);
691                  if((numPKTSaved-bad_pkt_EventReader-bad_pkt_CalibReader-bad_pkt)==0){                            nomino->Remove(15);
692                          stringstream err;          TString qu = Form("select OBT_TIME_SYNC,LAST_TIME_SYNC_INFO from ROOT_TABLE where FILE_NAME like '%s_%%' and (abs(PKT_NUMBER_INIT-%lu)<50000 or abs(PKT_OBT_INIT-%lu)<3000000) limit 1;",nomino->Data(),pkt_number_init,obt_init);
693                          err.str()="";          //
694                          err<<"NO GOOD PACKET SAVED in file: "<< rootfilename <<" The group is BAD: you may want to remove this file.";          oss.str() = "";
695                          msg = err.str();          oss << "(EM) Trying to find obt_time_sync and last_time_sync_info from DB, query is: " << qu.Data();
696                          mainLogUtil->logInfo(msg);          msg = oss.str();
697  //                      mainLogUtil->logError(msg);          mainLogUtil->logInfo(msg);
698  //                      return; //TODO: decidi se nn vuoi affatto usarlo o addirittura salvarlo tra i BAD???          //
699                  }          TSQLResult *result = sqlServer->Query(qu.Data());
700            TSQLRow    *row = result->Next();
701                  //marco_new_31:metto qui se voglio aprire e chiudere Connessione solo quando serve          if ( row && result->GetRowCount() == 1 ){
702                  //marco_new_01              obt_time_sync = (unsigned long int)atoll(row->GetField(0));
703                  if(!single_connection){            last_time_sync_info = (unsigned long int)atoll(row->GetField(1));
704                          OpenDBConnection(NULL);//Nota qui ho deciso di lockare tutte le tabelle            oss.str() = "";
705                  }            oss << "(EM) found obt_time_sync and last_time_sync_info from DB! obt_time_sync =  " <<obt_time_sync <<" last_time_sync_info = " << last_time_sync_info;
706                              msg = oss.str();
707                  //don't save in Table_ROOT_Good and don't search for ROOT files in the same temporal range            mainLogUtil->logInfo(msg);
708                  if((!real_time_init)&&(!real_time_last))          };      
709                  {          delete nomino;
710                          //saved in another table for future study        };      
711                          if(saveROOT_DB(Table_ROOT_Bad, outDir,  
712                                                                  filename,        if ( obt_time_sync && last_time_sync_info ){
713                                                             pkt_number_init, pkt_number_last,          //    if(!m_dbinfos.empty()){
714                                                             obt_init, obt_last,          //       while(!m_dbinfos.empty()){
715                                                             obt_time_sync, last_time_sync_info,              //      dbinfo *app = m_dbinfos.back();
716                                                             real_time_init, real_time_last,          //      m_dbinfos.pop_back();
717                                                             boot_number,          Int_t ez=0;
718                                                             timeOffset,          while ( ez < arsize ){
719                                                             bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader, numPKTSaved,            Int_t eid = idtorecover->At(ez);
720                                                             fni)==true)            if ( eid > -1 ){
721                                  {            
722                                          oss.str()="";              TString qu = Form("select FOLDER_NAME,FILE_NAME,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL,BOOT_NUMBER,TIME_OFFSET,BAD_PKT,BAD_PKT_READ,BAD_PKT_CALREAD,NUM_PKT_SAVED,INPUT_NAME,TIME_IS_ESTIMATED from ROOT_TABLE_BAD where ID_N=%i;",eid);
723                                          oss<<"Saved information regarding file: "<<filename<<" in table "<<Table_ROOT_Bad;              TSQLResult *result = sqlServer->Query(qu.Data());
724                                          msg = oss.str();              TSQLRow    *row = result->Next();
725                                          mainLogUtil->logInfo(msg);                          
726                                  }              TString efolder_name="";
727                                  else              TString efile_name="";
728                                  {                    unsigned long int epkt_number_in=0ULL;
729                                          oss.str()="";              unsigned long int epkt_number_fin=0ULL;
730                                          oss<<"Problem storing information in DB regarding file: "<<filename;              unsigned long int eobt_in=0ULL;
731                                          msg = oss.str();              unsigned long int eobt_fin=0ULL;
732                                          mainLogUtil->logError(msg);                          unsigned long int emboot_num=0ULL;
733                                  }                                    unsigned long int etime_offset=0ULL;
734                                int ebad_pkt=0;
735                          //marco_new_31:metto qui se voglio aprire e chiudere Connessione solo quando serve              int ebad_pkt_read=0;
736                                  //marco_new_01                int ebad_pkt_CalRead=0;
737                          if(!single_connection){              int enum_PKT_Saved=0;
738                                  CloseDBConnection();                          TString enome_input="";
739                          }              bool e_time_is_estimated=false;
740    
741                  return;              if ( row ){
742                  }                efolder_name =                      (TString)row->GetField(0);
743                                                          efile_name =                        (TString)row->GetField(1);
744                  //saves info in DB in table Table_ROOT_Good                epkt_number_in =    (unsigned long int)atoll(row->GetField(2));
745                  if(saveROOT_DB(Table_ROOT_Good, outDir,                epkt_number_fin =   (unsigned long int)atoll(row->GetField(3));
746                                          filename,                eobt_in =           (unsigned long int)atoll(row->GetField(4));
747                                     pkt_number_init, pkt_number_last,                eobt_fin =          (unsigned long int)atoll(row->GetField(5));
748                                     obt_init, obt_last,                emboot_num =        (unsigned long int)atoll(row->GetField(6));
749                                     obt_time_sync, last_time_sync_info,                    etime_offset =      (unsigned long int)atoll(row->GetField(7));
750                                     real_time_init, real_time_last,                ebad_pkt =                         (int)atoi(row->GetField(8));
751                                     boot_number,                ebad_pkt_read =                    (int)atoi(row->GetField(9));
752                                     timeOffset,                ebad_pkt_CalRead =                (int)atoi(row->GetField(10));
753                                     bad_pkt, bad_pkt_EventReader, bad_pkt_CalibReader, numPKTSaved,                enum_PKT_Saved =                  (int)atoi(row->GetField(11));
754                                     fni)==true)                enome_input =                      (TString)row->GetField(12);
755                  {                                                              e_time_is_estimated =            (bool)atoi(row->GetField(13));
756                          oss<<"Saved information regarding file: "<<filename<<" in table "<<Table_ROOT_Good<< " id= "<<my_id;              };
757                          msg = oss.str();              delete result;
758                          mainLogUtil->logInfo(msg);        
759                                        setReal_TimeRECOVERY(
760                          //TODO : work on this ....                                                         real_time_init,
761                          if(tryMerge){                                                             real_time_last,
762                              merge_ROOTfiles();                                   eobt_in,
763                          }                                   eobt_fin
764                  }                                   );
765                  else              //
766                  {            
767                          oss<<"Problem storing information in DB regarding file: "<<filename;              if (saveROOT_DB(
768                          msg = oss.str();                              Table_ROOT_Good,
769                          mainLogUtil->logError(msg);                                  efolder_name.Data(),
770                  }                                                            efile_name.Data(),
771                                epkt_number_in,
772                  //marco_new_31:metto qui se voglio apriree chiudere Connessione solo quando serve                              epkt_number_fin, eobt_in, eobt_fin, obt_time_sync, last_time_sync_info,
773                          //marco_new_01                                real_time_init, real_time_last, emboot_num, etime_offset, ebad_pkt, ebad_pkt_read, ebad_pkt_CalRead,
774                  if(!single_connection){                              enum_PKT_Saved, enome_input.Data(), e_time_is_estimated) == true) {
775                          CloseDBConnection();                            oss.str() = "";
776                  }                oss << "\nTAG(tassa): RECOVERED!!!! Saved information regarding file: " << efile_name << " in table " << Table_ROOT_Good << " id= " << my_id;
777                  msg = oss.str();
778                  mainLogUtil->logInfo(msg);
779                  /*merging we use global variable. we haveto set with current value*/
780                
781                  strcpy(outDir,efolder_name.Data() );
782                  //            outDir=efolder_name.Data();
783                  strcpy(filename,efile_name.Data() );
784                  //            filename=efile_name.Data();
785                  pkt_number_init=epkt_number_in;
786                  pkt_number_last=epkt_number_fin;
787                  obt_init=eobt_in;
788                  obt_last=eobt_fin;
789                  boot_number=emboot_num;
790                  timeOffset=etime_offset;
791                  bad_pkt=ebad_pkt;
792                  bad_pkt_EventReader=ebad_pkt_read;
793                  bad_pkt_CalibReader=ebad_pkt_CalRead;
794                  numPKTSaved=enum_PKT_Saved;
795                  strcpy(fni,enome_input.Data() );
796                  //            fni=enome_input.Data();
797                  time_is_estimated=e_time_is_estimated;
798                
799                  if (tryMerge) {
800                    merge_ROOTfiles();
801                  }
802                
803                  TString qu2 = Form("update ROOT_TABLE_BAD set ON_DISK='MVD' where ID_N=%i;",eid);
804                  sqlServer->Query(qu2.Data());
805    
806                
807                }
808                else {
809                  oss.str() = "";
810                  oss << "Problem storing information in DB regarding file: " << filename;
811                  msg = oss.str();
812                  mainLogUtil->logError(msg);
813                }
814              
815              
816              };
817              ez++;
818            }
819            //
820            idtorecover->Reset();
821            delete idtorecover;
822            idtorecover = new TArrayI(100);
823            arsize =  0;
824            //      delete app;
825          };
826        };
827        
828        CleanDisk();
829        if (!single_connection) {
830          CloseDBConnection();
831        }
832    
833          }//pRun    }//pRun
834  }  }
835      
836      
837      void PacketUser::CleanDisk(){
838        if ( !candelete ) return;
839        //
840        // delete small files present in root_table_bad from disk:
841        //
842        TString qu = Form("select FOLDER_NAME,FILE_NAME from ROOT_TABLE_BAD where NUM_PKT_SAVED<=%i and INSERTED_BY='%s' and ON_DISK='YES';",recoverlimit,tag_value);
843        TSQLResult *result = sqlServer->Query(qu.Data());
844        TSQLRow    *row = result->Next();
845        while ( row ){
846          TString tbdel = (TString)gSystem->ExpandPathName(row->GetField(0))+"/"+ (TString)row->GetField(1);
847          stringstream err;
848          string msg;
849          err.str() = "";      
850          err << " Deleting file " << tbdel.Data() << " from disk! ";
851          msg = err.str();
852          mainLogUtil->logInfo(msg);
853          gSystem->Unlink(tbdel.Data());
854          //      printf("ciccio %s  \n",tbdel.Data());
855          TString q2u = Form("UPDATE ROOT_TABLE_BAD set ON_DISK='NO' where FOLDER_NAME='%s' and FILE_NAME='%s' and NUM_PKT_SAVED<=%i and INSERTED_BY='%s';",row->GetField(0),row->GetField(1),recoverlimit,tag_value);
856          //      printf("pluto %s \n",q2u.Data());
857          sqlServer->Query(q2u.Data());
858          //      printf("paperoga \n");
859          row=result->Next();
860          //
861        };
862        
863      }
864    
865  //save in Table_ROOT_Good or in Table_ROOT_Bad  //save in Table_ROOT_Good or in Table_ROOT_Bad
866  bool PacketUser::saveROOT_DB(char* table_name, char* folder_name, char* file_name,  bool PacketUser::saveROOT_DB(const char* table_name, const char* folder_name, const char* file_name,
867                  unsigned long int pkt_number_in, unsigned long int pkt_number_fin,      unsigned long int pkt_number_in, unsigned long int pkt_number_fin, unsigned long int obt_in,
868                  unsigned long int obt_in, unsigned long int obt_fin,      unsigned long int obt_fin, unsigned long int oT_sync, unsigned long int lT_sync_info, unsigned long int mtime_init,
869                  unsigned long int  oT_sync, unsigned long int lT_sync_info,              unsigned long int mtime_last, unsigned long int mboot_num, unsigned long int time_offset, int bad_pkt,
870                  unsigned long int mtime_init,   unsigned long int mtime_last,      int bad_pkt_read, int bad_pkt_CalRead, int num_PKT_Saved, const char* nome_input, bool _time_is_estimated) {
871                  unsigned long int mboot_num,    //TODO: forse far ritornare ID della cosa appena inserita se e' andatato tutto ok invece che true false?
872                  unsigned long int time_offset,      stringstream oss;
873                  int bad_pkt, int bad_pkt_read, int bad_pkt_CalRead, int num_PKT_Saved,              oss.str("");
874                  char* nome_input){                          oss << "INSERT INTO " << table_name
875          //TODO: forse far ritornare ID della cosa appena inserita se e' andatato tutto ok invece che true false?                << " (ID_N, FOLDER_NAME, FILE_NAME, PKT_NUMBER_INIT, PKT_NUMBER_FINAL, PKT_OBT_INIT, PKT_OBT_FINAL, OBT_TIME_SYNC, LAST_TIME_SYNC_INFO, REAL_TIME_INIT, REAL_TIME_LAST, BOOT_NUMBER, TIME_OFFSET,BAD_PKT,BAD_PKT_READ,BAD_PKT_CALREAD,NUM_PKT_SAVED,INPUT_NAME,INSERT_TIME,TIME_IS_ESTIMATED,INSERTED_BY)"
876          stringstream oss;        << " VALUES ('" << 0 << "','" << folder_name << "','" << file_name << "','" << pkt_number_in << "','"
877          oss.str("");            << pkt_number_fin << "','" << obt_in << "','" << obt_fin << "','" << oT_sync << "','" << lT_sync_info << "','"
878          oss << "INSERT INTO "<< table_name <<" (ID_N, FOLDER_NAME, FILE_NAME, PKT_NUMBER_INIT, PKT_NUMBER_FINAL, PKT_OBT_INIT, PKT_OBT_FINAL, OBT_TIME_SYNC, LAST_TIME_SYNC_INFO, REAL_TIME_INIT, REAL_TIME_LAST, BOOT_NUMBER, TIME_OFFSET,BAD_PKT,BAD_PKT_READ,BAD_PKT_CALREAD,NUM_PKT_SAVED,INPUT_NAME,INSERT_TIME)"        << mtime_init << "','" << mtime_last << "','" << mboot_num << "','" << time_offset << "','" << bad_pkt << "','"
879      << " VALUES ('"<<0<< "','" <<folder_name<<"','" <<file_name<< "','" << pkt_number_in <<"','"<< pkt_number_fin << "','"<< obt_in <<"','"<< obt_fin<< "','"        << bad_pkt_read << "','" << bad_pkt_CalRead << "','" << num_PKT_Saved << "','" << nome_input << "'," << "NULL,"
880      << oT_sync << "','" << lT_sync_info << "','"        << _time_is_estimated << ",'" << tag_value << "'" << ");";
881      << mtime_init << "','" << mtime_last << "','"    string msg = oss.str();
882          << mboot_num << "','"    mainLogUtil->logAll(msg);
883      << time_offset << "','"  
884      << bad_pkt <<"','" << bad_pkt_read <<"','"<< bad_pkt_CalRead <<"','"<< numPKTSaved<<"','"    stringstream oss1;
885      << nome_input <<"',"    oss1.str() = "";
886      <<"NULL"<<          string msg1;
887      ")";                string query;
888          string msg = oss.str();  
889          mainLogUtil->logAll(msg);          TSQLResult* res = NULL;
890            
891          stringstream oss1;    query = oss.str();
892          oss1.str()="";    msg1 = "SaveROOT_DB query: ";
893          string msg1;    msg1 += query;
894        mainLogUtil->logInfo(msg1);
895     TSQLResult* res=NULL;          
896     res= sqlServer->Query(oss.str().c_str());    res = sqlServer->Query(query.c_str());
897     if(!res)    if (!res) {
898     {          oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
899             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        msg1 = oss1.str();
900             msg1=oss1.str();      mainLogUtil->logError(msg1);
901             mainLogUtil->logError(msg1);        return false;
902             return false;    }
903     }  
904    
905      if(!strcmp(table_name,Table_ROOT_Good)) {
906        //the ID of the current ROOT file in table Table_ROOT_Good
907        my_id = select_maxIDN_DB(table_name);
908        if (!boot_number) {
909          if (id_to_recover_index < 1000)
910            id_to_recover[id_to_recover_index++] = my_id;
911        }
912        else if (boot_number && id_to_recover_index && !is_new_route) {
913          recover_boot_number();
914        }
915      }
916      //    cout<<"DBG: my_id = "<<my_id<<endl;
917      if (res) {
918        delete res;
919        res = NULL;
920      }
921      return true;
922    }
923    
924    void PacketUser::recover_boot_number() {
925      string msg1;
926      stringstream oss1;
927      stringstream oss;
928      oss.str("");
929      string query = "";
930      TSQLResult* res = NULL;
931      if (!boot_number || !id_to_recover_index)
932        return;
933    
934      for (int i = 0; i < id_to_recover_index; i++) {
935        oss.str("");
936        oss << "UPDATE " << Table_ROOT_Good << " SET BOOT_NUMBER=" << boot_number << " WHERE ID_N=" << id_to_recover[i]
937            << ";";
938        query = oss.str();
939        res = sqlServer->Query(query.c_str());
940        if (!res) {
941          oss1 << "DBError UNABLE to: " << query.c_str() << endl;
942          msg1 = oss1.str();
943          mainLogUtil->logError(msg1);
944          return;
945        }
946      }
947    
948      for (int i = 0; i < id_to_recover_index; i++) {
949        oss.str("");
950        oss << "UPDATE " << Table_ROOT_Merging << " SET BOOT_NUMBER=" << boot_number << " WHERE ROOT_ID_N="
951            << id_to_recover[i] << ";";
952        query = oss.str();
953        res = sqlServer->Query(query.c_str());
954        if (!res) {
955          oss1 << "DBError UNABLE to: " << query.c_str() << endl;
956          msg1 = oss1.str();
957          mainLogUtil->logError(msg1);
958          return;
959        }
960      }
961    
962     //marco_new: si pu� ottimizzare ...    id_to_recover_index = 0;
    //the ID of the current ROOT file in table Table_ROOT_Good  
          my_id = select_maxIDN_DB(table_name);  
 //      cout<<"DBG: my_id = "<<my_id<<endl;  
    if(res){delete res; res = NULL;}  
    return true;  
963  }  }
964    
965  /**********************************************************************************************/  /**********************************************************************************************/
966  /*###########################################################################################################*/  /*###########################################################################################################*/
967  /**********************************         MERGING          *************************************************/  /**********************************         MERGING          *************************************************/
968  /*###########################################################################################################*/  /*###########################################################################################################*/
969  //      Merge ROOT files: found other ROOT files in the same temporal ranges  //      Merge ROT files: find other ROOT files in the same temporal ranges
970  //    it finds ROOT files that covers particular temporal range of interest and save this info in DB  //    it finds ROOT files that covers particular temporal range of interest and save this info in DB
971  /**********************************************************************************************/  /**********************************************************************************************/
972  //try to merge current ROOT file with files in DB  //try to merge current ROOT file with files in DB
973  bool PacketUser::merge_ROOTfiles()  bool PacketUser::merge_ROOTfiles() {
974  {    stringstream log;
975          mainLogUtil->logInfo("Trying merging ROOT files");    log.str("");
976      string slog;
977    //marco_new: controlla  
978    double percentage=(double)(bad_pkt+bad_pkt_EventReader+bad_pkt_CalibReader)/numPKTSaved;    mainLogUtil->logInfo("Trying merging ROOT files");
979                      double percentage = (double) (bad_pkt + bad_pkt_EventReader + bad_pkt_CalibReader) / numPKTSaved;
980    TSQLResult* res=NULL;    
981    TSQLRow* row =NULL;    TSQLResult* res = NULL;
982      TSQLRow* row = NULL;
983      //numero di ROOT files trovati sul DB che hanno relaz di tipo dato
984      unsigned int num_rows = 0;
985    
986      //Record su DB:
987      unsigned int idN = 0;
988      unsigned int root_id_db = 0;
989      unsigned long int pkt_num_in_db = 0;
990      unsigned long int pkt_num_fin_db = 0;
991      unsigned long int pkt_obt_in_db = 0;
992      unsigned long int pkt_obt_fin_db = 0;
993      unsigned long int time_in_db = 0;
994      unsigned long int time_fin_db = 0;
995      unsigned int boot_num_db = 0;
996      double perc = 0;
997    
998    //marco_new: non considero mai caso di continuit�(mio finale=DB iniz o viceversa), non mi interessa    //marco_new: non considero mai caso di continuita'(mio finale=DB iniz o viceversa), non mi interessa
999    //marco_new: after e before contengono anche smaller ma con un bordo comune    //marco_new: after e before contengono anche smaller ma con un bordo comune
1000    for(int relaz=AFTER; relaz<=BIGGER; relaz++)    for (int relaz = AFTER; relaz <= BIGGER; relaz++) {
1001    {                  //marco_new: esci se sono arrivato a zero
1002          //marco_new: controlla tutto      if (real_time_last == real_time_init) {
1003          //marco_new: esci se sono arrivato a zero        log.str("");
1004          if(real_time_last==real_time_init){            log << "Current File Lenght=0; real_time_last=real_time_init= " << real_time_last;
1005                  mainLogUtil->logInfo("Finish merging ROOT files");                      slog = log.str();
1006                  if(res){delete res; res = NULL;}        mainLogUtil->logAll(slog);
1007                  if(row){delete row; row = NULL;}        mainLogUtil->logInfo("Finish merging ROOT files");
1008                  return true;                                    if (res) {
1009          }          delete res;
1010            res = NULL;
1011          res = Select_merging(Table_ROOT_Merging, real_time_init, real_time_last, (type_Rel_ROOT)relaz);        }
1012                  if (row) {
1013          unsigned int num_rows=0;          delete row;
1014           if (!res)          row = NULL;
1015           {        }
1016                  mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged RES=null");        return true;
1017                   return false;      }
1018           }  
1019        num_rows = 0;
1020           num_rows=res->GetRowCount();      res = Select_merging(Table_ROOT_Merging, real_time_init, real_time_last, (type_Rel_ROOT) relaz);
1021  //       cout<<"MMMMM trovati num_rows "<< num_rows<< " per relaz= "<<relaz;  
1022        if (!res) {
1023           if(num_rows>0)        mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged RES=null");
1024           {                              return false;
1025                   for(unsigned int i=0; i<num_rows; i++)      }
1026                   {  
1027                           row=res->Next();      num_rows = res->GetRowCount();
1028                           if (!row)      log.str("");
1029                           {      log << "Found " << num_rows << " ROOT file in DB with relation of kind = " << relaz;
1030                                   mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged. ROW=null");      slog = log.str();
1031                                  if(res){delete res; res = NULL;}      mainLogUtil->logAll(slog);
1032                                  return false;  
1033                           }      if (num_rows > 0) {
1034                                  for (unsigned int i = 0; i < num_rows; i++) {
1035            row = res->Next();
1036                          //TODO ricavare tutte le info che servono          if (!row) {
1037                          unsigned int idN = 0;                  mainLogUtil->logError("DB_ERROR: Unable to find ROOT files to be merged. ROW=null");
1038                          idN=atoi(row->GetField(0));            if (res) {
1039                                delete res;
1040                          double perc =0;                              res = NULL;
1041                          //marco_new:            }
1042                          perc=atof(row->GetField(9));            return false;
1043                          //unsigned long int M_pkt_number_in, M_pkt_number_fin, M_obt_in, M_obt_fin, M_mtime_init, M_mtime_last;          }
1044                          if(perc>percentage){  
1045                                  mainLogUtil->logInfo("Current ROOT file is better than the one in DB");                          //Leggi Record dal DB:
1046                                  //modifica DB          idN = atoll(row->GetField(0));
1047                                  updateMergeROOT_DB(Table_ROOT_Merging,          root_id_db = atoll(row->GetField(1));
1048                                          atoi(row->GetField(1)), atoi(row->GetField(2)),          pkt_num_in_db = atoll(row->GetField(2));
1049                                          atoi(row->GetField(3)), atoi(row->GetField(4)),          pkt_num_fin_db = atoll(row->GetField(3));
1050                                          atoi(row->GetField(5)), atoi(row->GetField(6)),          pkt_obt_in_db = atoll(row->GetField(4));
1051                                          atoi(row->GetField(7)), atoi(row->GetField(8)),          pkt_obt_fin_db = atoll(row->GetField(5));
1052                                          perc,          time_in_db = atoll(row->GetField(6));
1053                                          idN,(type_Rel_ROOT)relaz);          time_fin_db = atoll(row->GetField(7));
1054                          }          boot_num_db = atoll(row->GetField(8));
1055                          else{          perc = atof(row->GetField(9));
1056                                  mainLogUtil->logInfo("Found ROOT files in DB better than current ROOT file");            
1057            log.str("");
1058                                  if(relaz == AFTER){          log << "*** ROOT file found in DB has idN= " << idN << "  root_id_db= " << root_id_db;
1059                                          mainLogUtil->logInfo("Relaz:AFTER = Changing Init values of the Current ROOT file");          log << " pkt_num_in_db= " << pkt_num_in_db << "  pkt_num_fin_db= " << pkt_num_fin_db << "  pkt_obt_in_db= "
1060                                          pkt_number_init= atoi(row->GetField(3));              << pkt_obt_in_db << "  pkt_obt_fin_db= " << pkt_obt_fin_db;
1061                                          obt_init= atoi(row->GetField(5));          log << "  time_in_db= " << time_in_db << "  time_fin_db= " << time_fin_db << " boot_num_db= " << boot_num_db
1062                                          real_time_init= atoi(row->GetField(7));                                              << "  perc= " << perc << "  ***";
1063                                  }          log << "\n*** Current ROOT file has pkt_number_init= " << pkt_number_init << "  obt_init= " << obt_init
1064                                  else if(relaz == BEFORE){              << "  real_time_init= " << real_time_init;
1065                                          mainLogUtil->logInfo("Relaz:BEFORE = Changing Last values of the Current ROOT file");                    log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
1066                                          pkt_number_last= atoi(row->GetField(2));              << real_time_last << " ***";
1067                                          obt_last= atoi(row->GetField(4));          slog = log.str();
1068                                          real_time_last= atoi(row->GetField(6));          mainLogUtil->logAll(slog);
1069                                  }          if (perc > percentage) {
1070                                  else if(relaz == SMALLER)            mainLogUtil->logInfo("Current ROOT file is better than the one in DB");
1071                                  {            //modifica DB
1072                                          //non devo proprio salvarlo ed esco ...                                    updateMergeROOT_DB(Table_ROOT_Merging, root_id_db, pkt_num_in_db, pkt_num_fin_db, pkt_obt_in_db,
1073                                          mainLogUtil->logInfo("Relaz:SMALLER = Nothing to save");                pkt_obt_fin_db, time_in_db, time_fin_db, boot_num_db, perc, idN, (type_Rel_ROOT) relaz);
1074                                          mainLogUtil->logInfo("Finish merging ROOT files");          }
1075                                          if(res){delete res; res = NULL;}          else {
1076                                          if(row){delete row; row = NULL;}            mainLogUtil->logInfo("Found ROOT file in DB is better than current ROOT file");
1077                                          return true;            if (relaz == AFTER) {
1078                                  }              mainLogUtil->logInfo("Relaz:AFTER = Changing Init values of the Current ROOT file");
1079                                  else if(relaz == BIGGER)//spezzettamento              pkt_number_init = (pkt_num_fin_db + 1);
1080                                  {                    obt_init = pkt_obt_fin_db;
1081                                          mainLogUtil->logInfo("Relaz:BIGGER = (1st part) Saving the first part of the Current ROOT file");                                                                    real_time_init = time_fin_db;
1082                                          saveMergeROOT_DB(Table_ROOT_Merging, my_id,              log.str("");
1083                                                  pkt_number_init, atoi(row->GetField(2)),              log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
1084                                                  obt_init, atoi(row->GetField(4)),                  << obt_init << "  real_time_init= " << real_time_init;
1085                                                  real_time_init, atoi(row->GetField(6)),              log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
1086                                                  boot_number,                  << real_time_last << " ***";
1087                                                  percentage);              slog = log.str();
1088                                                                                mainLogUtil->logAll(slog);
1089                                          mainLogUtil->logInfo("Relaz:BIGGER = (2nd part)Changing Init values of the Current ROOT file");            }
1090                                          pkt_number_init= atoi(row->GetField(3));            else if (relaz == BEFORE) {
1091                                          obt_init= atoi(row->GetField(5));              mainLogUtil->logInfo("Relaz:BEFORE = Changing Last values of the Current ROOT file");
1092                                          real_time_init= atoi(row->GetField(7));              pkt_number_last = (pkt_num_in_db - 1);
1093                                  }              obt_last = pkt_obt_in_db;
1094                          }              real_time_last = time_in_db;
1095                  }//for num_rows      
1096            }              log.str("");
1097          else{              log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
1098                  //marco_new:                  << obt_init << "  real_time_init= " << real_time_init;
1099                  mainLogUtil->logInfo("Found 0 ROOT files in DB that can be merged with current ROOT file");                          log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
1100                    << real_time_last << " ***";
1101          }              slog = log.str();
1102                mainLogUtil->logAll(slog);
1103              }
1104              else if (relaz == SMALLER) {
1105                //non devo proprio salvarlo ed esco ...
1106                mainLogUtil->logInfo("Relaz:SMALLER = Nothing to save");
1107                mainLogUtil->logInfo("\nFinish merging ROOT files");
1108                if (res) {
1109                  delete res;
1110                  res = NULL;
1111                }
1112                if (row) {
1113                  delete row;
1114                  row = NULL;
1115                }
1116                return true;
1117              }
1118              else if (relaz == BIGGER)//spezzettamento
1119              {
1120                mainLogUtil->logInfo("Relaz:BIGGER = (1st part) Saving the first part of the Current ROOT file");
1121                saveMergeROOT_DB(Table_ROOT_Merging, my_id, pkt_number_init, (pkt_num_in_db - 1), obt_init, pkt_obt_in_db,
1122                    real_time_init, time_in_db, boot_number, percentage);
1123    
1124                mainLogUtil->logInfo("Relaz:BIGGER = (2nd part)Changing Init values of the Current ROOT file");
1125                pkt_number_init = (pkt_num_fin_db + 1);
1126                obt_init = pkt_obt_fin_db;
1127                real_time_init = time_fin_db;
1128    
1129                log.str("");
1130                log << "\n*** Current ROOT file becomes: pkt_number_init= " << pkt_number_init << "  obt_init= "
1131                    << obt_init << "  real_time_init= " << real_time_init;
1132                log << " pkt_number_last= " << pkt_number_last << "  obt_last= " << obt_last << "  real_time_last= "
1133                    << real_time_last << " ***";
1134                slog = log.str();
1135                mainLogUtil->logAll(slog);
1136              }//if relaz
1137            }//if perc
1138          }//for num_rows
1139        }//if num_rows
1140    
1141        if (res) {
1142          delete res;
1143          res = NULL;
1144        }
1145        if (row) {
1146          delete row;
1147          row = NULL;
1148        }
1149    
1150      }//for relaz
1151    
1152      mainLogUtil->logInfo("Saving Current ROOT file");
1153      saveMergeROOT_DB(Table_ROOT_Merging, my_id, pkt_number_init, pkt_number_last, obt_init, obt_last, real_time_init,
1154          real_time_last, boot_number, percentage);
1155    
1156          //marco_new:???    mainLogUtil->logInfo("Finish merging ROOT files");
         if(res){delete res; res = NULL;}  
         if(row){delete row; row = NULL;}          
 }//for  
   
         mainLogUtil->logInfo("Saving Current ROOT file");        
         saveMergeROOT_DB(Table_ROOT_Merging, my_id,  
                          pkt_number_init, pkt_number_last,  
                          obt_init, obt_last,  
                          real_time_init, real_time_last,  
                          boot_number,  
                          percentage);  
   
   
         mainLogUtil->logInfo("Finish merging ROOT files");        
1157    return true;    return true;
1158    
1159  }  }
1160    
1161  //unsigned int root_id,  percentage non le devo modificare  //unsigned int root_id,  percentage non le devo modificare
1162  bool PacketUser::updateMergeROOT_DB(char* table_name,  bool PacketUser::updateMergeROOT_DB(const char* table_name, unsigned int root_id, unsigned long int pkt_number_in,
1163                          unsigned  int root_id,      unsigned long int pkt_number_fin, unsigned long int obt_in, unsigned long int obt_fin,
1164                          unsigned long int pkt_number_in, unsigned long int pkt_number_fin,      unsigned long int mtime_init, unsigned long int mtime_last, unsigned long int mboot_num, double bad_perc,
1165                          unsigned long int obt_in, unsigned long int obt_fin,      unsigned int ID_record, type_Rel_ROOT type_rel) {
1166                  unsigned long int mtime_init,   unsigned long int mtime_last,  
1167                          unsigned long int mboot_num,    stringstream oss;
1168                          double bad_perc,    oss.str("");
1169                          unsigned int ID_record, type_Rel_ROOT type_rel){  
1170          stringstream oss;    if (type_rel == AFTER) {
1171          oss.str("");          mainLogUtil->logInfo("Relaz:AFTER = Updating Last values of the DB ROOT file");
1172                //marco_new:tolti tutti gli apici che qui non devono essere
1173          if(type_rel == AFTER){      
1174                  mainLogUtil->logInfo("Relaz:AFTER = Updating Last values of the DB ROOT file");      int good = 1;
1175                  //marco_new:tolti tutti gli apici che qui non devono essere      if ( pkt_number_in >= (pkt_number_init - 1) && abs((int)(pkt_number_in-(pkt_number_init-1)))<10 ) good = 0;
1176                  oss << "UPDATE "<< table_name      
1177                  << " SET PKT_NUMBER_FINAL ="<< pkt_number_init        oss << "UPDATE " << table_name << " SET PKT_NUMBER_FINAL =" << (pkt_number_init - 1) << ", PKT_OBT_FINAL ="
1178                          <<", PKT_OBT_FINAL ="<< obt_init          << obt_init << ", REAL_TIME_LAST =" << real_time_init << ", GOOD="<< good << " WHERE ID_N =" << ID_record << ";";
1179                      <<", REAL_TIME_LAST ="<< real_time_init<<" WHERE ID_N ="<< ID_record <<";";  
1180          }    }
1181          else if(type_rel == BEFORE){                else if (type_rel == BEFORE) {
1182                          mainLogUtil->logInfo("Relaz:BEFORE = Updating Init values of the DB ROOT file");              mainLogUtil->logInfo("Relaz:BEFORE = Updating Init values of the DB ROOT file");
1183                  oss << "UPDATE "<< table_name  
1184                  << " SET PKT_NUMBER_INIT ="<< pkt_number_last        int good = 1;
1185                          <<", PKT_OBT_INIT ="<< obt_last      if ( (pkt_number_last+1) >= pkt_number_fin && abs((int)((pkt_number_last+1)-pkt_number_fin))<10 ) good = 0;
1186                      <<", REAL_TIME_INIT ="<< real_time_last<<" WHERE ID_N ="<< ID_record<<";";      
1187          }      oss << "UPDATE " << table_name << " SET PKT_NUMBER_INIT =" << (pkt_number_last + 1) << ", PKT_OBT_INIT ="
1188          else if(type_rel == SMALLER){                    << obt_last << ", REAL_TIME_INIT =" << real_time_last << ", GOOD="<< good << " WHERE ID_N =" << ID_record << ";";
1189                  //spezzettamentento    }
1190                  mainLogUtil->logInfo("Relaz:SMALLER = (1st part) Updating Last values of the DB ROOT file");                                                        else if (type_rel == SMALLER) {
1191                //spezzettamentento
1192                  oss << "UPDATE "<< table_name      mainLogUtil->logInfo("Relaz:SMALLER = (1st part) Updating Last values of the DB ROOT file");
1193                          << " SET PKT_NUMBER_FINAL="<< pkt_number_init    
1194                          <<", PKT_OBT_FINAL ="<< obt_init      int good = 1;
1195                              <<", REAL_TIME_LAST ="<< real_time_init<<" WHERE ID_N ="<< ID_record<<";";      if ( pkt_number_in >= (pkt_number_init - 1) && abs((int)(pkt_number_in-(pkt_number_init-1)))<10 ) good = 0;
1196                    
1197                          mainLogUtil->logInfo("Relaz:SMALLER = (2nd part) Saving the second part of the DB ROOT file");                                                oss << "UPDATE " << table_name << " SET PKT_NUMBER_FINAL=" << (pkt_number_init - 1) << ", PKT_OBT_FINAL ="
1198            << obt_init << ", REAL_TIME_LAST =" << real_time_init << ", GOOD="<< good << " WHERE ID_N =" << ID_record << ";";
1199                          saveMergeROOT_DB(table_name, root_id,  
1200                           pkt_number_last, pkt_number_fin,      mainLogUtil->logInfo("Relaz:SMALLER = (2nd part) Saving the second part of the DB ROOT file");
1201                           obt_last, obt_fin,  
1202                           real_time_last, mtime_last,      saveMergeROOT_DB(table_name, root_id, (pkt_number_last + 1), pkt_number_fin, obt_last, obt_fin, real_time_last,
1203                           mboot_num,          mtime_last, mboot_num, bad_perc);
1204                           bad_perc);    }
1205          }    else if (type_rel == BIGGER) {
1206          else if(type_rel == BIGGER){      //marco_new: ok anche se coincidenti etc
1207          //marco_new: ok anche se coincidenti etc      //    oss << "DELETE FROM "<< table_name <<" WHERE ID_N ="<< ID_record<<";"; // EMILIANO
1208            oss << "DELETE FROM "<< table_name <<" WHERE ID_N ="<< ID_record<<";";      oss << "UPDATE " << table_name << " SET GOOD=0 WHERE ID_N =" << ID_record << ";"; // EMILIANO DO NOT DELETE FROM ROOT_TABLE_MERGING JUST SET GOOD FLAG TO ZERO
1209            mainLogUtil->logInfo("Rimosso record in Tabella merging");          mainLogUtil->logInfo("Record deleted from merging table");
1210          }    }
1211          else    else
1212                  return false;      return false;
1213    
1214      string msg = oss.str();
1215      mainLogUtil->logInfo(msg);
1216          string msg = oss.str();  
1217          mainLogUtil->logInfo(msg);          stringstream oss1;
1218              oss1.str() = "";
1219          stringstream oss1;    string msg1;
1220          oss1.str()="";  
1221          string msg1;    TSQLResult* res = NULL;
1222        res = sqlServer->Query(oss.str().c_str());
1223     TSQLResult* res=NULL;            if (!res) {
1224     res= sqlServer->Query(oss.str().c_str());      oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1225     if(!res)      msg1 = oss1.str();
1226     {          mainLogUtil->logError(msg1);
1227             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        return false;
1228             msg1=oss1.str();    }
1229             mainLogUtil->logError(msg1);      if (res) {
1230             return false;      delete res;
1231     }      res = NULL;
1232     if(res){delete res; res = NULL;}    }
1233     return true;    return true;
1234  }  }
1235    
1236  //marco_new: check here  //cerca eventuali ROOT files in DB che possono venire mergiati
1237  TSQLResult* PacketUser::Select_merging(char* table_name, unsigned long int mtime_init, unsigned long int mtime_last, type_Rel_ROOT type_rel)  //marco_new bordi: messo in after a before casi in cui smaller con un bordo in comune
1238  {  //marco_new bordi: messo in bigger casi con bordi in comune; tra questi anche caso particolare di coincidente
1239    //marco_new bordi: smaller resta solo caso in cui DB e' piu largo sia a dx che a sx
1240  //      unsigned  int idN=0;  TSQLResult* PacketUser::Select_merging(const char* table_name, unsigned long int mtime_init, unsigned long int mtime_last,
1241          TSQLResult* res=NULL;      type_Rel_ROOT type_rel) {
1242          stringstream query;    TSQLResult* res = NULL;
1243          query.str("");    stringstream query;
1244      query.str("");
1245          //marco_new bordi: messo in after a before casi in cui smaller con un bordo in comune  
1246          //marco_new bordi: messo in bigger casi con bordi in comune; tra questi anche caso particolare di coincidente    if (type_rel == AFTER)
1247          //marco_new bordi: smaller resta solo caso in cui DB � piu largo sia a dx che a sx      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_LAST > " << mtime_init
1248          if(type_rel == AFTER)          << " and REAL_TIME_LAST <= " << mtime_last << " and REAL_TIME_INIT < " << mtime_init; // EMI
1249            query<<"select * from "<<table_name<<" where REAL_TIME_LAST > "<< mtime_init <<" and REAL_TIME_LAST <= "<< mtime_last <<" and REAL_TIME_INIT < "<< mtime_init;    else if (type_rel == BEFORE)
1250          else if(type_rel == BEFORE)      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_INIT >= " << mtime_init
1251            query<<"select * from "<<table_name<<" where REAL_TIME_INIT >= "<< mtime_init <<" and REAL_TIME_INIT < "<< mtime_last <<" and REAL_TIME_LAST > "<< mtime_last;          << " and REAL_TIME_INIT < " << mtime_last << " and REAL_TIME_LAST > " << mtime_last; // EMI
1252          else if(type_rel == SMALLER)    else if (type_rel == SMALLER)
1253            query<<"select * from "<<table_name<<" where REAL_TIME_INIT < "<< mtime_init <<" and REAL_TIME_LAST > "<< mtime_last;      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_INIT < " << mtime_init
1254          else if(type_rel == BIGGER)          << " and REAL_TIME_LAST > " << mtime_last; // EMI
1255                  query<<"select * from "<<table_name<<" where REAL_TIME_INIT >= "<< mtime_init <<" and REAL_TIME_LAST <= "<< mtime_last;    else if (type_rel == BIGGER)
1256          else      query << "select * from " << table_name << " where GOOD=1 and REAL_TIME_INIT >= " << mtime_init
1257                  return 0;          << " and REAL_TIME_LAST <= " << mtime_last; // EMI
1258              else
1259          query<< " order by REAL_TIME_INIT ASC";//marco_new: inutile      return 0;
1260          //      query<<" and NUM_PKT_SAVED - BAD_PKT_CALREAD - BAD_PKT_READ - BAD_PKT >= 2" ;  
1261              query << " order by REAL_TIME_INIT ASC;";//marco_new: inutile
1262        //se volessi mettere un filtro sulla qualita'
1263          string msg = query.str();    //    query<<" and NUM_PKT_SAVED - BAD_PKT_CALREAD - BAD_PKT_READ - BAD_PKT >= 2" ;
1264          mainLogUtil->logAll(msg);    string msg = query.str();
1265      mainLogUtil->logAll(msg);
1266          res= sqlServer->Query(query.str().c_str());    res = sqlServer->Query(query.str().c_str());
1267              stringstream oss1;
1268          stringstream oss1;    oss1.str() = "";
1269           oss1.str()="";    string msg1;
1270           string msg1;  
1271        if (!res) {
1272           if (!res)      oss1 << "DBError UNABLE to: " << query.str().c_str() << endl;
1273           {      msg1 = oss1.str();
1274                   oss1<<"DBError UNABLE to: "<<query.str().c_str()<<endl;        mainLogUtil->logError(msg1);
1275                   msg1=oss1.str();    }
1276                   mainLogUtil->logError(msg1);    
1277           }          return res;
1278    }
1279          return res;  
1280  }  bool PacketUser::saveMergeROOT_DB(const char* table_name, unsigned int root_id, unsigned long int pkt_number_in,
1281        unsigned long int pkt_number_fin, unsigned long int obt_in, unsigned long int obt_fin,
1282  bool PacketUser::saveMergeROOT_DB(char* table_name,  unsigned int root_id,      unsigned long int mtime_init, unsigned long int mtime_last, unsigned long int mboot_num, double percentage) {
1283                          unsigned long int pkt_number_in, unsigned long int pkt_number_fin,  
1284                          unsigned long int obt_in, unsigned long int obt_fin,    int good = 1;
1285                  unsigned long int mtime_init,   unsigned long int mtime_last,    if ( pkt_number_in >= pkt_number_fin && abs((int)(pkt_number_fin-pkt_number_in))<10 ) good = 0;
1286                          unsigned long int mboot_num,  
1287                          double percentage)    stringstream oss;
1288  {    oss.str("");
1289      oss << "INSERT INTO " << table_name
1290          stringstream oss;        << " (ID_N, ROOT_ID_N, PKT_NUMBER_INIT, PKT_NUMBER_FINAL, PKT_OBT_INIT, PKT_OBT_FINAL, REAL_TIME_INIT, REAL_TIME_LAST, BOOT_NUMBER, BAD_PKT_PERCENTAGE, INSERT_TIME, INSERTED_BY,GOOD)"
1291          oss.str("");            << " VALUES ('" << 0 << "','" << root_id << "','" << pkt_number_in << "','" << pkt_number_fin << "','" << obt_in
1292          oss << "INSERT INTO "<< table_name <<" (ID_N, ROOT_ID_N, PKT_NUMBER_INIT, PKT_NUMBER_FINAL, PKT_OBT_INIT, PKT_OBT_FINAL, REAL_TIME_INIT, REAL_TIME_LAST, BOOT_NUMBER, BAD_PKT_PERCENTAGE, INSERT_TIME)"        << "','" << obt_fin << "','" << mtime_init << "','" << mtime_last << "','" << mboot_num << "','" << percentage
1293      << " VALUES ('"<<0<< "','" <<root_id<<"','"<< pkt_number_in <<"','"<< pkt_number_fin << "','"<< obt_in <<"','"<< obt_fin<< "','"        << "'," << "NULL" << ",'" << tag_value << "','" << good <<"');";
     << mtime_init << "','" << mtime_last << "','"  
         << mboot_num <<"','"  
         << percentage <<"',"        
     <<"NULL"<<        
     ")";  
   
         string msg = oss.str();  
         mainLogUtil->logAll(msg);        
   
         //marco_new: controlla  
         //marco_new: esci se sono arrivato a zero  
 //      if(real_time_last==real_time_init){      
         if(mtime_init==mtime_last){  
                 mainLogUtil->logAll("Nothing to be saved");      
                           
 //              if(res){delete res; res = NULL;}  
 //              if(row){delete row; row = NULL;}  
                 return true;                              
         }  
1294    
1295      string msg = oss.str();
1296      mainLogUtil->logAll(msg);
1297    
1298          stringstream oss1;    //marco_new: controlla
1299          oss1.str()="";    //marco_new: esci se sono arrivato a zero
1300          string msg1;    //    if(real_time_last==real_time_init){
1301      if (mtime_init == mtime_last) {
1302     TSQLResult* res=NULL;              mainLogUtil->logAll("Nothing to be saved");
1303     res= sqlServer->Query(oss.str().c_str());  
1304     if(!res)      //          if(res){delete res; res = NULL;}
1305     {          //          if(row){delete row; row = NULL;}
1306             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        return true;
1307             msg1=oss1.str();    }
1308             mainLogUtil->logError(msg1);    
1309             return false;    stringstream oss1;
1310     }    oss1.str() = "";
1311     if(res){delete res; res = NULL;}    string msg1;
1312     return true;  
1313      TSQLResult* res = NULL;
1314      res = sqlServer->Query(oss.str().c_str());
1315      if (!res) {
1316        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1317        msg1 = oss1.str();
1318        mainLogUtil->logError(msg1);
1319        return false;
1320      }
1321      if (res) {
1322        delete res;
1323        res = NULL;
1324      }
1325      return true;
1326  }  }
1327    
1328  //Utility: return max(IDN)  //Utility: return max(IDN)
1329  unsigned  int PacketUser::select_maxIDN_DB(char* table_name)  unsigned int PacketUser::select_maxIDN_DB(const char* table_name) {
 {  
1330    
1331  if (!strcmp(table_name,Table_ROOT_Bad))    if (!strcmp(table_name, Table_ROOT_Bad)) {
1332  {      return 0;
1333          return 0;          }
1334  }    unsigned int idN = 0;
1335          unsigned  int idN=0;    TSQLResult* res = NULL;
1336          TSQLResult* res=NULL;    stringstream oss;
1337          stringstream oss;    oss.str("");
1338      oss.str("");    oss << "select max(ID_N) from " << table_name;
1339      oss<<"select max(ID_N) from "<<table_name;    //    string msg = oss.str();
1340          string msg = oss.str();    //    mainLogUtil->logAll(msg);
1341          mainLogUtil->logAll(msg);          res = sqlServer->Query(oss.str().c_str());
1342      res= sqlServer->Query(oss.str().c_str());  
1343                      stringstream oss1;
1344          stringstream oss1;    oss1.str() = "";
1345          oss1.str()="";    string msg1;
1346          string msg1;  
1347              if (!res) {
1348          if(!res)      oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1349          {            msg1 = oss1.str();
1350             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        mainLogUtil->logError(msg1);
1351                  msg1=oss1.str();      return 0;
1352                  mainLogUtil->logError(msg1);      }
1353                  return 0;  
1354          }    TSQLRow* row = NULL;
1355                row = res->Next();
1356          TSQLRow* row=NULL;          if (!row) {
1357          row=res->Next();      oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1358      if (!row )      msg1 = oss1.str();
1359      {      mainLogUtil->logError(msg1);
1360             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        return 0;
1361                  msg1=oss1.str();    }
1362                  mainLogUtil->logError(msg1);    
1363                  return 0;    idN = atoi(row->GetField(0));
1364          }    if (row) {
1365        delete row;
1366          idN=atoi(row->GetField(0));      row = NULL;
1367          if(row){delete row; row = NULL;}    }
1368          if(res){delete res; res = NULL;}    if (res) {
1369          return idN;      delete res;
1370        res = NULL;
1371      }
1372    
1373      oss << ". idN = " << idN;
1374      string msg = oss.str();
1375      mainLogUtil->logAll(msg);
1376    
1377      return idN;
1378  }  }
1379    
1380  /**  /**
1381   * Lock par=table, if par=null lock all tables   * Lock par=table, if par=null lock all tables
1382   */   */
1383  int PacketUser::LockTables(char* tableTobeLocked)  int PacketUser::LockTables(const char* tableTobeLocked) {
1384  {      //se non ho il DB  :)
1385          //se non ho il DB  :)    if (!do_cont_check)
1386          if(!do_cont_check) return 999;      return 999;
1387    
1388          TSQLResult* res=NULL;    TSQLResult* res = NULL;
1389          stringstream oss;    stringstream oss;
1390      oss.str("");    oss.str("");
1391          if(!tableTobeLocked)    //  if (!tableTobeLocked)
1392                  oss << "lock table "<<Table_ROOT_Good<<" write, "<<Table_ROOT_Bad<<" write, "<<Table_GL_RESURS_OFFSET<<" write, "<<Table_ROOT_Merging<<" write;";    oss << "lock table " << Table_ROOT_Good << " write, " << Table_ROOT_Bad << " write, " << Table_GL_RESURS_OFFSET
1393          else        << " write, " << Table_ROOT_Merging << " write;";
1394                  oss << "lock table "<<tableTobeLocked<<" write; ";      //  else
1395        //    oss << "lock table " << tableTobeLocked << " write; ";
1396          string msg = oss.str();  
1397          mainLogUtil->logAll(msg);          string msg = oss.str();
1398      mainLogUtil->logAll(msg);
1399          res= sqlServer->Query(oss.str().c_str());  
1400                      res = sqlServer->Query(oss.str().c_str());
1401          stringstream oss1;  
1402          oss1.str()="";    stringstream oss1;
1403          string msg1;    oss1.str() = "";
1404              string msg1;
1405          if(!res)  
1406          {          if (!res) {
1407             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1408                  msg1=oss1.str();      msg1 = oss1.str();
1409                  mainLogUtil->logError(msg1);        mainLogUtil->logError(msg1);
1410                  return 1;      return 1;
1411          }    }
1412              
1413          if(res){delete res; res = NULL;}            if (res) {
1414          mainLogUtil->logAll("######################### TABLES LOCKED ############################");                          delete res;
1415          return 0;            res = NULL;
1416      }
1417      mainLogUtil->logAll("TABLES LOCKED");
1418      return 0;
1419  }  }
1420    
1421  /**  /**
1422   * UNLock tables   * UNLock tables
1423   */   */
1424  int PacketUser::UnLockTables(){    int PacketUser::UnLockTables() {
1425          //se non ho il DB  :)      //se non ho il DB  :)
1426          if(!do_cont_check) return 999;    if (!do_cont_check)
1427        return 999;
1428          TSQLResult* res=NULL;  
1429          stringstream oss;    TSQLResult* res = NULL;
1430      oss.str("");    stringstream oss;
1431          oss << "unlock tables;";    oss.str("");
1432      oss << "unlock tables;";
1433      string msg = oss.str();  
1434          mainLogUtil->logAll(msg);          string msg = oss.str();
1435              mainLogUtil->logAll(msg);
1436          res= sqlServer->Query(oss.str().c_str());  
1437                      res = sqlServer->Query(oss.str().c_str());
1438          stringstream oss1;  
1439          oss1.str()="";    stringstream oss1;
1440          string msg1;    oss1.str() = "";
1441              string msg1;
1442          if(!res)  
1443          {          if (!res) {
1444             oss1<<"DBError UNABLE to: "<<oss.str().c_str()<<endl;        oss1 << "DBError UNABLE to: " << oss.str().c_str() << endl;
1445                  msg1=oss1.str();      msg1 = oss1.str();
1446                  mainLogUtil->logError(msg1);        mainLogUtil->logError(msg1);
1447                  return 1;      return 1;
1448          }    }
1449                    
1450          if(res){delete res; res = NULL;}            if (res) {
1451          mainLogUtil->logAll("######################### TABLES UNLOCKED ############################");        delete res;
1452        res = NULL;
1453      }
1454      mainLogUtil->logAll("TABLES UNLOCKED");
1455    
1456          return 0;          return 0;
1457  }  }
1458    
1459  /*********************************************************/  /*********************************************************/
1460  //marco_new_31  //marco_new_31
1461  void PacketUser::OpenDBConnection(char* tableTobeLocked){  void PacketUser::OpenDBConnection(const char* tableTobeLocked) {
1462          mainLogUtil->logAll("######################### OpenDBConnection ############################");    if (do_cont_check) {
1463          if(do_cont_check){      //controllo che non sia gia' aperta
1464                  //controllo che non sia gi� aperta      if (!sqlServer) {
1465                  if(!sqlServer){        sqlServer = TSQLServer::Connect(pelosconnection, db_user, db_pwd);
1466                          sqlServer = TSQLServer::Connect(connection,db_user,db_pwd);        if ((!sqlServer) || (!(sqlServer->IsConnected()))) {
1467                          if ((!sqlServer)||(!(sqlServer->IsConnected()))){cout<<"Can not connect with MYSQL sever"<<endl;}                cout << "Can not connect with MYSQL sever" << endl;
1468          }
1469                          //marco_new: blocca tutte le tabelle        mainLogUtil->logAll("Connected to DB");
1470                          LockTables(tableTobeLocked);        stringstream myquery;
1471                          mainLogUtil->logAll("######################### OpenDBConnection OK ############################");              myquery.str("");
1472                  }        myquery << "SET time_zone='+0:00'";
1473          }        sqlServer->Query(myquery.str().c_str());
1474          //blocca le tabelle
1475          LockTables(tableTobeLocked);
1476        }
1477      }
1478    
1479  }  }
1480    
1481  //marco_new_31  //marco_new_31
1482  void PacketUser::CloseDBConnection(){  void PacketUser::CloseDBConnection() {
1483          mainLogUtil->logAll("######################### CloseDBConnection ############################");            if (do_cont_check) {
1484          if(do_cont_check){                                            //controllo che ce ne sia una aperta
1485                  //controllo che ce ne sia una aperta      if (sqlServer && sqlServer->IsConnected()) {
1486                  if(sqlServer && sqlServer->IsConnected()){        //marco_new: sblocca tutte le tabelle
1487                          //marco_new: sblocca tutte le tabelle        UnLockTables();
1488                          UnLockTables();                sqlServer->Close();
1489                          sqlServer->Close();        delete sqlServer;
1490          sqlServer = NULL;
1491                          //marco_new_01: ??        mainLogUtil->logAll("Closed Connection to DB");
1492                          delete sqlServer;      }
1493                              }
                         sqlServer=NULL;  
                         mainLogUtil->logAll("######################### CloseDBConnection OK ############################");      
                 }  
         }  
1494  }  }
1495    
   
   
1496  /***********************************************************************************************************************/  /***********************************************************************************************************************/
1497  /*#################################################### HIC SUNT LEONES ################################################*/  /*#################################################### HIC SUNT LEONES ################################################*/
1498  /***********************************************************************************************************************/  /***********************************************************************************************************************/
1499  //UNUSED: dbg functions...  //UNUSED: dbg functions...
1500    
1501  //Return the system time in ms  //Return the system time in ms
1502  unsigned long long PacketUser::Record_Time(){  unsigned long long PacketUser::Record_Time() {
1503          timeval tv;    timeval tv;
1504          gettimeofday(&tv,NULL);    gettimeofday(&tv, NULL);
1505          unsigned long long timems =  (unsigned long long)tv.tv_sec * (unsigned long long)1000 + tv.tv_usec / 1000;    unsigned long long timems = (unsigned long long) tv.tv_sec * (unsigned long long) 1000 + tv.tv_usec / 1000;
1506          return timems;      return timems;
1507  }  }
1508    
1509  //dbg_functions:  //dbg_functions:
1510    
1511  //UNUSED. save a packet in a file  //UNUSED. save a packet in a file
1512  void PacketUser::savePKT_file(char* headerPkt,  void PacketUser::savePKT_file(char* headerPkt, char* pamPkt, long int length, bool append, char* nomefile) {
1513                                                           char* pamPkt,    char fno[80] = "";
1514                                                           long int length,    ofstream fout;
1515                                                           bool append,    sprintf(fno, "%s/pkt%d_of_%s.pkt", gSystem->ExpandPathName(outDir), numPKTSaved, nomefile); // EMI
1516                                                           char* nomefile)  
1517  {    if (append == true)
1518          char fno[80]="";      fout.open(fno, ios::binary | ios::app);
1519          ofstream fout;    else
1520          sprintf(fno,"%s/pkt%d_of_%s.pkt", outDir, numPKTSaved, nomefile);      fout.open(fno, ios::binary);
1521    
1522          if(append==true)    if (!fout) {
1523                  fout.open(fno, ios::binary | ios::app);      cout << "can not open output file " << fno << endl;
1524          else      return;
1525                  fout.open(fno, ios::binary);                        }
1526                      fout.write(headerPkt, LENGTH_HEADER_PKT);
1527          if (!fout) {cout<<"can not open output file "<<fno<<endl; return;}                      fout.write(pamPkt, length);
1528          fout.write(headerPkt,LENGTH_HEADER_PKT);    fout.close();
         fout.write(pamPkt,length);  
         fout.close();      
1529  }  }
1530    
1531  //UNUSED  //UNUSED
1532  void PacketUser::saveALL_PKT(char* headerPkt, char* pamPkt, long int length, bool append)  void PacketUser::saveALL_PKT(char* headerPkt, char* pamPkt, long int length, bool append) {
1533  {    char fno[80] = "";
1534          char fno[80]="";    ofstream fout;
1535          ofstream fout;    if (append == true) {
1536          if(append==true)      sprintf(fno, "%s/packets.pkt", gSystem->ExpandPathName(outDir)); // EMI
1537          {                    fout.open(fno, ios::binary | ios::app);
1538                  sprintf(fno,"%s/packets.pkt", outDir);    }
1539                  fout.open(fno, ios::binary | ios::app);    else {
1540          }      sprintf(fno, "%s/packet%d.pkt", gSystem->ExpandPathName(outDir), numPKT); // EMI
1541          else{      fout.open(fno, ios::binary);
1542                  sprintf(fno,"%s/packet%d.pkt", outDir, numPKT );    }
1543                  fout.open(fno, ios::binary);                      
1544          }    if (!fout) {
1545                        cout << "can not open output file " << fno << endl;
1546          if (!fout) {cout<<"can not open output file "<<fno<<endl; return;}                        return;
1547          fout.write(headerPkt,LENGTH_HEADER_PKT);    }
1548          fout.write(pamPkt,length);    fout.write(headerPkt, LENGTH_HEADER_PKT);
1549          fout.close();        fout.write(pamPkt, length);
1550      fout.close();
1551  }  }
1552    
   
1553  }  }

Legend:
Removed from v.1.1.1.1  
changed lines
  Added in v.1.17

  ViewVC Help
Powered by ViewVC 1.1.23