LCOV - code coverage report
Current view: top level - alma/ASDM - FocusTable.cc (source / functions) Hit Total Coverage
Test: casacpp_coverage.info Lines: 0 468 0.0 %
Date: 2024-10-04 18:58:15 Functions: 0 38 0.0 %

          Line data    Source code
       1             : 
       2             : /*
       3             :  * ALMA - Atacama Large Millimeter Array
       4             :  * (c) European Southern Observatory, 2002
       5             :  * (c) Associated Universities Inc., 2002
       6             :  * Copyright by ESO (in the framework of the ALMA collaboration),
       7             :  * Copyright by AUI (in the framework of the ALMA collaboration),
       8             :  * All rights reserved.
       9             :  * 
      10             :  * This library is free software; you can redistribute it and/or
      11             :  * modify it under the terms of the GNU Lesser General Public
      12             :  * License as published by the Free software Foundation; either
      13             :  * version 2.1 of the License, or (at your option) any later version.
      14             :  * 
      15             :  * This library is distributed in the hope that it will be useful,
      16             :  * but WITHOUT ANY WARRANTY, without even the implied warranty of
      17             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      18             :  * Lesser General Public License for more details.
      19             :  * 
      20             :  * You should have received a copy of the GNU Lesser General Public
      21             :  * License along with this library; if not, write to the Free Software
      22             :  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
      23             :  * MA 02111-1307  USA
      24             :  *
      25             :  * Warning!
      26             :  *  -------------------------------------------------------------------- 
      27             :  * | This is generated code!  Do not modify this file.                  |
      28             :  * | If you do, all changes will be lost when the file is re-generated. |
      29             :  *  --------------------------------------------------------------------
      30             :  *
      31             :  * File FocusTable.cpp
      32             :  */
      33             : #include <alma/ASDM/ConversionException.h>
      34             : #include <alma/ASDM/DuplicateKey.h>
      35             : #include <alma/ASDM/OutOfBoundsException.h>
      36             : 
      37             : using asdm::ConversionException;
      38             : using asdm::DuplicateKey;
      39             : using asdm::OutOfBoundsException;
      40             : 
      41             : #include <alma/ASDM/ASDM.h>
      42             : #include <alma/ASDM/FocusTable.h>
      43             : #include <alma/ASDM/FocusRow.h>
      44             : #include <alma/ASDM/Parser.h>
      45             : 
      46             : using asdm::ASDM;
      47             : using asdm::FocusTable;
      48             : using asdm::FocusRow;
      49             : using asdm::Parser;
      50             : 
      51             : #include <iostream>
      52             : #include <fstream>
      53             : #include <iterator>
      54             : #include <sstream>
      55             : #include <set>
      56             : #include <algorithm>
      57             : using namespace std;
      58             : 
      59             : #include <alma/ASDM/Misc.h>
      60             : using namespace asdm;
      61             : 
      62             : #include <libxml/parser.h>
      63             : #include <libxml/tree.h>
      64             : 
      65             : #ifndef WITHOUT_BOOST
      66             : #include "boost/filesystem/operations.hpp"
      67             : #include <boost/algorithm/string.hpp>
      68             : #else
      69             : #include <sys/stat.h>
      70             : #endif
      71             : 
      72             : namespace asdm {
      73             :         // The name of the entity we will store in this table.
      74             :         static string entityNameOfFocus = "Focus";
      75             :         
      76             :         // An array of string containing the names of the columns of this table.
      77             :         // The array is filled in the order : key, required value, optional value.
      78             :         //
      79             :         static string attributesNamesOfFocus_a[] = {
      80             :                 
      81             :                         "antennaId"
      82             :                 ,
      83             :                         "timeInterval"
      84             :                 
      85             :                 
      86             :                         , "focusTracking"
      87             :                 
      88             :                         , "focusOffset"
      89             :                 
      90             :                         , "focusRotationOffset"
      91             :                 
      92             :                         , "focusModelId"
      93             :                                 
      94             :                 
      95             :                         , "measuredFocusPosition"
      96             :                 
      97             :                         , "measuredFocusRotation"
      98             :                                 
      99             :         };
     100             :         
     101             :         // A vector of string whose content is a copy of the strings in the array above.
     102             :         //
     103             :         static vector<string> attributesNamesOfFocus_v (attributesNamesOfFocus_a, attributesNamesOfFocus_a + sizeof(attributesNamesOfFocus_a) / sizeof(attributesNamesOfFocus_a[0]));
     104             : 
     105             :         // An array of string containing the names of the columns of this table.
     106             :         // The array is filled in the order where the names would be read by default in the XML header of a file containing
     107             :         // the table exported in binary mode.
     108             :         //      
     109             :         static string attributesNamesInBinOfFocus_a[] = {
     110             :     
     111             :          "antennaId" , "timeInterval" , "focusTracking" , "focusOffset" , "focusRotationOffset" , "focusModelId" 
     112             :         ,
     113             :          "measuredFocusPosition" , "measuredFocusRotation" 
     114             :     
     115             :         };
     116             :                                         
     117             :         // A vector of string whose content is a copy of the strings in the array above.
     118             :         //
     119             :         static vector<string> attributesNamesInBinOfFocus_v(attributesNamesInBinOfFocus_a, attributesNamesInBinOfFocus_a + sizeof(attributesNamesInBinOfFocus_a) / sizeof(attributesNamesInBinOfFocus_a[0]));             
     120             :         
     121             : 
     122             :         // The array of attributes (or column) names that make up key key.
     123             :         //
     124             :         string keyOfFocus_a[] = {
     125             :         
     126             :                 "antennaId"
     127             :         ,
     128             :                 "timeInterval"
     129             :                  
     130             :         };
     131             :          
     132             :         // A vector of strings which are copies of those stored in the array above.
     133             :         vector<string> keyOfFocus_v(keyOfFocus_a, keyOfFocus_a + sizeof(keyOfFocus_a) / sizeof(keyOfFocus_a[0]));
     134             : 
     135             :         /**
     136             :          * Return the list of field names that make up key key
     137             :          * as a const reference to a vector of strings.
     138             :          */     
     139           0 :         const vector<string>& FocusTable::getKeyName() {
     140           0 :                 return keyOfFocus_v;
     141             :         }
     142             : 
     143             : 
     144           0 :         FocusTable::FocusTable(ASDM &c) : container(c) {
     145             : 
     146             :                 // Define a default entity.
     147           0 :                 entity.setEntityId(EntityId("uid://X0/X0/X0"));
     148           0 :                 entity.setEntityIdEncrypted("na");
     149           0 :                 entity.setEntityTypeName("FocusTable");
     150           0 :                 entity.setEntityVersion("1");
     151           0 :                 entity.setInstanceVersion("1");
     152             :                 
     153             :                 // Archive XML
     154           0 :                 archiveAsBin = false;
     155             :                 
     156             :                 // File XML
     157           0 :                 fileAsBin = false;
     158             :                 
     159             :                 // By default the table is considered as present in memory
     160           0 :                 presentInMemory = true;
     161             :                 
     162             :                 // By default there is no load in progress
     163           0 :                 loadInProgress = false;
     164           0 :         }
     165             :         
     166             : /**
     167             :  * A destructor for FocusTable.
     168             :  */
     169           0 :         FocusTable::~FocusTable() {
     170           0 :                 for (unsigned int i = 0; i < privateRows.size(); i++) 
     171           0 :                         delete(privateRows.at(i));
     172           0 :         }
     173             : 
     174             :         /**
     175             :          * Container to which this table belongs.
     176             :          */
     177           0 :         ASDM &FocusTable::getContainer() const {
     178           0 :                 return container;
     179             :         }
     180             : 
     181             :         /**
     182             :          * Return the number of rows in the table.
     183             :          */
     184           0 :         unsigned int FocusTable::size() const {
     185           0 :                 if (presentInMemory) 
     186           0 :                         return privateRows.size();
     187             :                 else
     188           0 :                         return declaredSize;
     189             :         }
     190             :         
     191             :         /**
     192             :          * Return the name of this table.
     193             :          */
     194           0 :         string FocusTable::getName() const {
     195           0 :                 return entityNameOfFocus;
     196             :         }
     197             :         
     198             :         /**
     199             :          * Return the name of this table.
     200             :          */
     201           0 :         string FocusTable::name() {
     202           0 :                 return entityNameOfFocus;
     203             :         }
     204             :         
     205             :         /**
     206             :          * Return the the names of the attributes (or columns) of this table.
     207             :          */
     208           0 :         const vector<string>& FocusTable::getAttributesNames() { return attributesNamesOfFocus_v; }
     209             :         
     210             :         /**
     211             :          * Return the the names of the attributes (or columns) of this table as they appear by default
     212             :          * in an binary export of this table.
     213             :          */
     214           0 :         const vector<string>& FocusTable::defaultAttributesNamesInBin() { return attributesNamesInBinOfFocus_v; }
     215             : 
     216             :         /**
     217             :          * Return this table's Entity.
     218             :          */
     219           0 :         Entity FocusTable::getEntity() const {
     220           0 :                 return entity;
     221             :         }
     222             : 
     223             :         /**
     224             :          * Set this table's Entity.
     225             :          */
     226           0 :         void FocusTable::setEntity(Entity e) {
     227           0 :                 this->entity = e; 
     228           0 :         }
     229             :         
     230             :         //
     231             :         // ====> Row creation.
     232             :         //
     233             :         
     234             :         /**
     235             :          * Create a new row.
     236             :          */
     237           0 :         FocusRow *FocusTable::newRow() {
     238           0 :                 return new FocusRow (*this);
     239             :         }
     240             :         
     241             : 
     242             :         /**
     243             :          * Create a new row initialized to the specified values.
     244             :          * @return a pointer on the created and initialized row.
     245             :         
     246             :          * @param antennaId 
     247             :         
     248             :          * @param timeInterval 
     249             :         
     250             :          * @param focusTracking 
     251             :         
     252             :          * @param focusOffset 
     253             :         
     254             :          * @param focusRotationOffset 
     255             :         
     256             :          * @param focusModelId 
     257             :         
     258             :      */
     259           0 :         FocusRow* FocusTable::newRow(Tag antennaId, ArrayTimeInterval timeInterval, bool focusTracking, std::vector<Length > focusOffset, std::vector<Angle > focusRotationOffset, int focusModelId){
     260           0 :                 FocusRow *row = new FocusRow(*this);
     261             :                         
     262           0 :                 row->setAntennaId(antennaId);
     263             :                         
     264           0 :                 row->setTimeInterval(timeInterval);
     265             :                         
     266           0 :                 row->setFocusTracking(focusTracking);
     267             :                         
     268           0 :                 row->setFocusOffset(focusOffset);
     269             :                         
     270           0 :                 row->setFocusRotationOffset(focusRotationOffset);
     271             :                         
     272           0 :                 row->setFocusModelId(focusModelId);
     273             :         
     274           0 :                 return row;             
     275             :         }       
     276             :         
     277             : 
     278             : 
     279           0 : FocusRow* FocusTable::newRow(FocusRow* row) {
     280           0 :         return new FocusRow(*this, row);
     281             : }
     282             : 
     283             :         //
     284             :         // Append a row to its table.
     285             :         //
     286             : 
     287             :         
     288             :         
     289             :                 
     290             :                 
     291             :         /** 
     292             :          * Returns a string built by concatenating the ascii representation of the
     293             :          * parameters values suffixed with a "_" character.
     294             :          */
     295           0 :          string FocusTable::Key(Tag antennaId) {
     296           0 :                 ostringstream ostrstr;
     297             :                         ostrstr  
     298             :                         
     299           0 :                                 <<  antennaId.toString()  << "_"
     300             :                         
     301             :                         ;
     302           0 :                 return ostrstr.str();           
     303           0 :          }
     304             :          
     305             :                         
     306             :                         
     307           0 :         FocusRow* FocusTable::add(FocusRow* x) {
     308           0 :                 ArrayTime startTime = x->getTimeInterval().getStart();
     309             : 
     310             :                 /*
     311             :                  * Is there already a context for this combination of not temporal 
     312             :                  * attributes ?
     313             :                  */
     314             :                 string k = Key(
     315           0 :                                                 x->getAntennaId()
     316           0 :                                            );
     317             :  
     318           0 :                 if (context.find(k) == context.end()) { 
     319             :                         // There is not yet a context ...
     320             :                         // Create and initialize an entry in the context map for this combination....
     321           0 :                         TIME_ROWS v;
     322           0 :                         context[k] = v;                 
     323           0 :                 }
     324             :                 
     325           0 :                 return insertByStartTime(x, context[k]);
     326           0 :         }       
     327             :                         
     328             :                 
     329             :         
     330             :                 
     331           0 :         void FocusTable::addWithoutCheckingUnique(FocusRow * x) {
     332           0 :                 FocusRow * dummy = checkAndAdd(x, true); // We require the check for uniqueness to be skipped.
     333             :                                                            // by passing true in the second parameter
     334             :                                                            // whose value by default is false.
     335             :                 // this statement is never executed, but it hides the unused return value from the compiler to silence that warning.
     336             :                 if (false) cout << (unsigned long long) dummy;
     337           0 :         }
     338             :         
     339             : 
     340             : 
     341             : 
     342             :         // 
     343             :         // A private method to append a row to its table, used by input conversion
     344             :         // methods, with row uniqueness.
     345             :         //
     346             : 
     347             :         
     348             :         
     349             :                 
     350             :                 
     351             :                         
     352             :                         
     353             :                         
     354             :                         
     355           0 :         FocusRow*  FocusTable::checkAndAdd(FocusRow* x, bool /* skipCheckUniqueness */ ) {
     356             :                 string keystr = Key( 
     357           0 :                                                 x->getAntennaId() 
     358           0 :                                            ); 
     359           0 :                 if (context.find(keystr) == context.end()) {
     360           0 :                         vector<FocusRow *> v;
     361           0 :                         context[keystr] = v;
     362           0 :                 }
     363             :                 
     364           0 :                 vector<FocusRow*>& found = context.find(keystr)->second;
     365           0 :                 return insertByStartTime(x, found);                     
     366           0 :         }
     367             :                         
     368             :                                         
     369             :                 
     370             : 
     371             : 
     372             : 
     373             :         //
     374             :         // A private method to brutally append a row to its table, without checking for row uniqueness.
     375             :         //
     376             : 
     377           0 :         void FocusTable::append(FocusRow *x) {
     378           0 :                 privateRows.push_back(x);
     379           0 :                 x->isAdded(true);
     380           0 :         }
     381             : 
     382             : 
     383             : 
     384             : 
     385             : 
     386           0 :          vector<FocusRow *> FocusTable::get() {
     387           0 :                 checkPresenceInMemory();
     388           0 :             return privateRows;
     389             :          }
     390             :          
     391           0 :          const vector<FocusRow *>& FocusTable::get() const {
     392           0 :                 const_cast<FocusTable&>(*this).checkPresenceInMemory();       
     393           0 :             return privateRows;
     394             :          }       
     395             :                 
     396             : 
     397             : 
     398             : 
     399             : 
     400             :         
     401             : 
     402             :         
     403             :         
     404             :                 
     405           0 :          vector<FocusRow *> *FocusTable::getByContext(Tag antennaId) {
     406             :                 //if (getContainer().checkRowUniqueness() == false)
     407             :                         //throw IllegalAccessException ("The method 'getByContext' can't be called because the dataset has been built without checking the row uniqueness.", "FocusTable");
     408             : 
     409           0 :                 checkPresenceInMemory();
     410           0 :                 string k = Key(antennaId);
     411             :  
     412           0 :             if (context.find(k) == context.end()) return 0;
     413           0 :            else return &(context[k]);               
     414           0 :         }               
     415             :                 
     416             :         
     417             : 
     418             : 
     419             :         
     420             :                 
     421             :                 
     422             :                         
     423             :                         
     424             :                         
     425             : /*
     426             :  ** Returns a FocusRow* given a key.
     427             :  ** @return a pointer to the row having the key whose values are passed as parameters, or 0 if
     428             :  ** no row exists for that key.
     429             :  **
     430             :  */
     431             :                                 
     432             :                                 
     433           0 :         FocusRow* FocusTable::getRowByKey(Tag antennaId, ArrayTimeInterval timeInterval)  {
     434           0 :                 checkPresenceInMemory();
     435           0 :                 string keystr = Key(antennaId);
     436           0 :                 vector<FocusRow *> row;
     437             :                 
     438           0 :                 if ( context.find(keystr)  == context.end()) return 0;
     439             :                 
     440           0 :                 row = context[keystr];
     441             :                 
     442             :                 // Is the vector empty...impossible in principle !
     443           0 :                 if (row.size() == 0) return 0;
     444             :                 
     445             :                 // Only one element in the vector
     446           0 :                 if (row.size() == 1) {
     447           0 :                         FocusRow* r = row.at(0);
     448           0 :                         if ( r->getTimeInterval().contains(timeInterval.getStart()))
     449           0 :                                 return r;
     450             :                         else
     451           0 :                                 return 0;
     452             :                 }
     453             :                 
     454             :                 // Optimizations
     455           0 :                 FocusRow* last = row.at(row.size()-1);
     456           0 :                 if (timeInterval.getStart().get() >= (last->getTimeInterval().getStart().get()+last->getTimeInterval().getDuration().get())) return 0;
     457             :                 
     458           0 :                 FocusRow* first = row.at(0);
     459           0 :                 if (timeInterval.getStart().get() < first->getTimeInterval().getStart().get()) return 0;
     460             :                 
     461             :                 
     462             :                 // More than one row 
     463             :                 // Let's use a dichotomy method for the general case..  
     464           0 :                 int k0 = 0;
     465           0 :                 int k1 = row.size() - 1;
     466           0 :                 FocusRow* r = 0;
     467           0 :                 while (k0!=k1) {
     468             :                 
     469             :                         // Is the start time contained in the time interval of row #k0
     470           0 :                         r = row.at(k0);
     471           0 :                         if (r->getTimeInterval().contains(timeInterval.getStart())) return r;
     472             :                         
     473             :                         // Is the start contained in the time interval of row #k1
     474           0 :                         r = row.at(k1);
     475           0 :                         if (r->getTimeInterval().contains(timeInterval.getStart())) return r;
     476             :                         
     477             :                         // Are the rows #k0 and #k1 consecutive
     478             :                         // Then we know for sure that there is no row containing the start of timeInterval
     479           0 :                         if (k1==(k0+1)) return 0;
     480             :                         
     481             :                         // Proceed to the next step of dichotomy.
     482           0 :                         r = row.at((k0+k1)/2);
     483           0 :                         if ( timeInterval.getStart().get() <= r->getTimeInterval().getStart().get())
     484           0 :                                 k1 = (k0 + k1) / 2;
     485             :                         else
     486           0 :                                 k0 = (k0 + k1) / 2;
     487             :                 }
     488           0 :                 return 0;       
     489           0 :         }
     490             :                                                         
     491             :                         
     492             :                 
     493             :                 
     494             :                 
     495             :         
     496             : 
     497             : 
     498             : 
     499             : #ifndef WITHOUT_ACS
     500             :         using asdmIDL::FocusTableIDL;
     501             : #endif
     502             : 
     503             : #ifndef WITHOUT_ACS
     504             :         // Conversion Methods
     505             : 
     506             :         FocusTableIDL *FocusTable::toIDL() {
     507             :                 FocusTableIDL *x = new FocusTableIDL ();
     508             :                 unsigned int nrow = size();
     509             :                 x->row.length(nrow);
     510             :                 vector<FocusRow*> v = get();
     511             :                 for (unsigned int i = 0; i < nrow; ++i) {
     512             :                         //x->row[i] = *(v[i]->toIDL());
     513             :                         v[i]->toIDL(x->row[i]);
     514             :                 }
     515             :                 return x;
     516             :         }
     517             :         
     518             :         void FocusTable::toIDL(asdmIDL::FocusTableIDL& x) const {
     519             :                 unsigned int nrow = size();
     520             :                 x.row.length(nrow);
     521             :                 vector<FocusRow*> v = get();
     522             :                 for (unsigned int i = 0; i < nrow; ++i) {
     523             :                         v[i]->toIDL(x.row[i]);
     524             :                 }
     525             :         }       
     526             : #endif
     527             :         
     528             : #ifndef WITHOUT_ACS
     529             :         void FocusTable::fromIDL(FocusTableIDL x) {
     530             :                 unsigned int nrow = x.row.length();
     531             :                 for (unsigned int i = 0; i < nrow; ++i) {
     532             :                         FocusRow *tmp = newRow();
     533             :                         tmp->setFromIDL(x.row[i]);
     534             :                         // checkAndAdd(tmp);
     535             :                         add(tmp);
     536             :                 }
     537             :         }       
     538             : #endif
     539             : 
     540             :         
     541           0 :         string FocusTable::toXML()  {
     542           0 :                 string buf;
     543             : 
     544           0 :                 buf.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> ");
     545           0 :                 buf.append("<FocusTable xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:focus=\"http://Alma/XASDM/FocusTable\" xsi:schemaLocation=\"http://Alma/XASDM/FocusTable http://almaobservatory.org/XML/XASDM/4/FocusTable.xsd\" schemaVersion=\"4\" schemaRevision=\"-1\">\n");
     546             :         
     547           0 :                 buf.append(entity.toXML());
     548           0 :                 string s = container.getEntity().toXML();
     549             :                 // Change the "Entity" tag to "ContainerEntity".
     550           0 :                 buf.append("<Container" + s.substr(1,s.length() - 1)+" ");
     551           0 :                 vector<FocusRow*> v = get();
     552           0 :                 for (unsigned int i = 0; i < v.size(); ++i) {
     553             :                         try {
     554           0 :                                 buf.append(v[i]->toXML());
     555           0 :                         } catch (const NoSuchRow &e) {
     556           0 :                         }
     557           0 :                         buf.append("  ");
     558             :                 }               
     559           0 :                 buf.append("</FocusTable> ");
     560           0 :                 return buf;
     561           0 :         }
     562             : 
     563             :         
     564           0 :         string FocusTable::getVersion() const {
     565           0 :                 return version;
     566             :         }
     567             :         
     568             : 
     569           0 :         void FocusTable::fromXML(string& tableInXML)  {
     570             :                 //
     571             :                 // Look for a version information in the schemaVersion of the XML
     572             :                 //
     573             :                 xmlDoc *doc;
     574             : #if LIBXML_VERSION >= 20703
     575           0 :         doc = xmlReadMemory(tableInXML.data(), tableInXML.size(), "XMLTableHeader.xml", NULL, XML_PARSE_NOBLANKS|XML_PARSE_HUGE);
     576             : #else
     577             :                 doc = xmlReadMemory(tableInXML.data(), tableInXML.size(), "XMLTableHeader.xml", NULL, XML_PARSE_NOBLANKS);
     578             : #endif
     579           0 :                 if ( doc == NULL )
     580           0 :                         throw ConversionException("Failed to parse the xmlHeader into a DOM structure.", "Focus");
     581             :                 
     582           0 :                 xmlNode* root_element = xmlDocGetRootElement(doc);
     583           0 :                 if ( root_element == NULL || root_element->type != XML_ELEMENT_NODE )
     584           0 :                 throw ConversionException("Failed to retrieve the root element in the DOM structure.", "Focus");
     585             :                 
     586           0 :         xmlChar * propValue = xmlGetProp(root_element, (const xmlChar *) "schemaVersion");
     587           0 :         if ( propValue != 0 ) {
     588           0 :                 version = string( (const char*) propValue);
     589           0 :                 xmlFree(propValue);             
     590             :         }
     591             :                                                                         
     592           0 :                 Parser xml(tableInXML);
     593           0 :                 if (!xml.isStr("<FocusTable")) 
     594           0 :                         error();
     595             :                 // cout << "Parsing a FocusTable" << endl;
     596           0 :                 string s = xml.getElement("<Entity","/>");
     597           0 :                 if (s.length() == 0) 
     598           0 :                         error();
     599           0 :                 Entity e;
     600           0 :                 e.setFromXML(s);
     601           0 :                 if (e.getEntityTypeName() != "FocusTable")
     602           0 :                         error();
     603           0 :                 setEntity(e);
     604             :                 // Skip the container's entity; but, it has to be there.
     605           0 :                 s = xml.getElement("<ContainerEntity","/>");
     606           0 :                 if (s.length() == 0) 
     607           0 :                         error();
     608             : 
     609             :                 // Get each row in the table.
     610           0 :                 s = xml.getElementContent("<row>","</row>");
     611             :                 FocusRow *row;
     612           0 :                 if (getContainer().checkRowUniqueness()) {
     613             :                         try {
     614           0 :                                 while (s.length() != 0) {
     615           0 :                                         row = newRow();
     616           0 :                                         row->setFromXML(s);
     617           0 :                                         checkAndAdd(row);
     618           0 :                                         s = xml.getElementContent("<row>","</row>");
     619             :                                 }
     620             :                                 
     621             :                         }
     622           0 :                         catch (const DuplicateKey &e1) {
     623           0 :                                 throw ConversionException(e1.getMessage(),"FocusTable");
     624           0 :                         } 
     625           0 :                         catch (const UniquenessViolationException &e1) {
     626           0 :                                 throw ConversionException(e1.getMessage(),"FocusTable");      
     627           0 :                         }
     628           0 :                         catch (...) {
     629             :                                 // cout << "Unexpected error in FocusTable::checkAndAdd called from FocusTable::fromXML " << endl;
     630           0 :                         }
     631             :                 }
     632             :                 else {
     633             :                         try {
     634           0 :                                 while (s.length() != 0) {
     635           0 :                                         row = newRow();
     636           0 :                                         row->setFromXML(s);
     637           0 :                                         addWithoutCheckingUnique(row);
     638           0 :                                         s = xml.getElementContent("<row>","</row>");
     639             :                                 }
     640             :                         }
     641           0 :                         catch (const DuplicateKey &e1) {
     642           0 :                                 throw ConversionException(e1.getMessage(),"FocusTable");
     643           0 :                         } 
     644           0 :                         catch (...) {
     645             :                                 // cout << "Unexpected error in FocusTable::addWithoutCheckingUnique called from FocusTable::fromXML " << endl;
     646           0 :                         }
     647             :                 }                               
     648             :                                 
     649             :                                 
     650           0 :                 if (!xml.isStr("</FocusTable>")) 
     651           0 :                 error();
     652             :                 
     653             :                 //Does not change the convention defined in the model.  
     654             :                 //archiveAsBin = false;
     655             :                 //fileAsBin = false;
     656             : 
     657             :                 // clean up the xmlDoc pointer
     658           0 :                 if ( doc != NULL ) xmlFreeDoc(doc);
     659             :                 
     660           0 :         }
     661             : 
     662             :         
     663           0 :         void FocusTable::error()  {
     664           0 :                 throw ConversionException("Invalid xml document","Focus");
     665             :         }
     666             :         
     667             :         
     668           0 :         string FocusTable::MIMEXMLPart(const asdm::ByteOrder* byteOrder) {
     669           0 :                 string UID = getEntity().getEntityId().toString();
     670           0 :                 string withoutUID = UID.substr(6);
     671           0 :                 string containerUID = getContainer().getEntity().getEntityId().toString();
     672           0 :                 ostringstream oss;
     673           0 :                 oss << "<?xml version='1.0'  encoding='ISO-8859-1'?>";
     674           0 :                 oss << "\n";
     675           0 :                 oss << "<FocusTable xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:focus=\"http://Alma/XASDM/FocusTable\" xsi:schemaLocation=\"http://Alma/XASDM/FocusTable http://almaobservatory.org/XML/XASDM/4/FocusTable.xsd\" schemaVersion=\"4\" schemaRevision=\"-1\">\n";
     676           0 :                 oss<< "<Entity entityId='"<<UID<<"' entityIdEncrypted='na' entityTypeName='FocusTable' schemaVersion='1' documentVersion='1'/>\n";
     677           0 :                 oss<< "<ContainerEntity entityId='"<<containerUID<<"' entityIdEncrypted='na' entityTypeName='ASDM' schemaVersion='1' documentVersion='1'/>\n";
     678           0 :                 oss << "<BulkStoreRef file_id='"<<withoutUID<<"' byteOrder='"<<byteOrder->toString()<<"' />\n";
     679           0 :                 oss << "<Attributes>\n";
     680             : 
     681           0 :                 oss << "<antennaId/>\n"; 
     682           0 :                 oss << "<timeInterval/>\n"; 
     683           0 :                 oss << "<focusTracking/>\n"; 
     684           0 :                 oss << "<focusOffset/>\n"; 
     685           0 :                 oss << "<focusRotationOffset/>\n"; 
     686           0 :                 oss << "<focusModelId/>\n"; 
     687             : 
     688           0 :                 oss << "<measuredFocusPosition/>\n"; 
     689           0 :                 oss << "<measuredFocusRotation/>\n"; 
     690           0 :                 oss << "</Attributes>\n";         
     691           0 :                 oss << "</FocusTable>\n";
     692             : 
     693           0 :                 return oss.str();                               
     694           0 :         }
     695             :         
     696           0 :         string FocusTable::toMIME(const asdm::ByteOrder* byteOrder) {
     697           0 :                 EndianOSStream eoss(byteOrder);
     698             :                 
     699           0 :                 string UID = getEntity().getEntityId().toString();
     700             :                 
     701             :                 // The MIME Header
     702           0 :                 eoss <<"MIME-Version: 1.0";
     703           0 :                 eoss << "\n";
     704           0 :                 eoss << "Content-Type: Multipart/Related; boundary='MIME_boundary'; type='text/xml'; start= '<header.xml>'";
     705           0 :                 eoss <<"\n";
     706           0 :                 eoss <<"Content-Description: Correlator";
     707           0 :                 eoss <<"\n";
     708           0 :                 eoss <<"alma-uid:" << UID;
     709           0 :                 eoss <<"\n";
     710           0 :                 eoss <<"\n";            
     711             :                 
     712             :                 // The MIME XML part header.
     713           0 :                 eoss <<"--MIME_boundary";
     714           0 :                 eoss <<"\n";
     715           0 :                 eoss <<"Content-Type: text/xml; charset='ISO-8859-1'";
     716           0 :                 eoss <<"\n";
     717           0 :                 eoss <<"Content-Transfer-Encoding: 8bit";
     718           0 :                 eoss <<"\n";
     719           0 :                 eoss <<"Content-ID: <header.xml>";
     720           0 :                 eoss <<"\n";
     721           0 :                 eoss <<"\n";
     722             :                 
     723             :                 // The MIME XML part content.
     724           0 :                 eoss << MIMEXMLPart(byteOrder);
     725             : 
     726             :                 // The MIME binary part header
     727           0 :                 eoss <<"--MIME_boundary";
     728           0 :                 eoss <<"\n";
     729           0 :                 eoss <<"Content-Type: binary/octet-stream";
     730           0 :                 eoss <<"\n";
     731           0 :                 eoss <<"Content-ID: <content.bin>";
     732           0 :                 eoss <<"\n";
     733           0 :                 eoss <<"\n";    
     734             :                 
     735             :                 // The MIME binary content
     736           0 :                 entity.toBin(eoss);
     737           0 :                 container.getEntity().toBin(eoss);
     738           0 :                 eoss.writeInt((int) privateRows.size());
     739           0 :                 for (unsigned int i = 0; i < privateRows.size(); i++) {
     740           0 :                         privateRows.at(i)->toBin(eoss);      
     741             :                 }
     742             :                 
     743             :                 // The closing MIME boundary
     744           0 :                 eoss << "\n--MIME_boundary--";
     745           0 :                 eoss << "\n";
     746             :                 
     747           0 :                 return eoss.str();      
     748           0 :         }
     749             : 
     750             :         
     751           0 :         void FocusTable::setFromMIME(const string & mimeMsg) {
     752           0 :     string xmlPartMIMEHeader = "Content-ID: <header.xml>\n\n";
     753             :     
     754           0 :     string binPartMIMEHeader = "--MIME_boundary\nContent-Type: binary/octet-stream\nContent-ID: <content.bin>\n\n";
     755             :     
     756             :     // Detect the XML header.
     757           0 :     string::size_type loc0 = mimeMsg.find(xmlPartMIMEHeader, 0);
     758           0 :     if ( loc0 == string::npos) {
     759             :       // let's try with CRLFs
     760           0 :       xmlPartMIMEHeader = "Content-ID: <header.xml>\r\n\r\n";
     761           0 :       loc0 = mimeMsg.find(xmlPartMIMEHeader, 0);
     762           0 :       if  ( loc0 == string::npos ) 
     763           0 :               throw ConversionException("Failed to detect the beginning of the XML header", "Focus");
     764             :     }
     765             : 
     766           0 :     loc0 += xmlPartMIMEHeader.size();
     767             :     
     768             :     // Look for the string announcing the binary part.
     769           0 :     string::size_type loc1 = mimeMsg.find( binPartMIMEHeader, loc0 );
     770             :     
     771           0 :     if ( loc1 == string::npos ) {
     772           0 :       throw ConversionException("Failed to detect the beginning of the binary part", "Focus");
     773             :     }
     774             :     
     775             :     //
     776             :     // Extract the xmlHeader and analyze it to find out what is the byte order and the sequence
     777             :     // of attribute names.
     778             :     //
     779           0 :     string xmlHeader = mimeMsg.substr(loc0, loc1-loc0);
     780             :     xmlDoc *doc;
     781           0 :     doc = xmlReadMemory(xmlHeader.data(), xmlHeader.size(), "BinaryTableHeader.xml", NULL, XML_PARSE_NOBLANKS);
     782           0 :     if ( doc == NULL ) 
     783           0 :       throw ConversionException("Failed to parse the xmlHeader into a DOM structure.", "Focus");
     784             :     
     785             :    // This vector will be filled by the names of  all the attributes of the table
     786             :    // in the order in which they are expected to be found in the binary representation.
     787             :    //
     788           0 :     vector<string> attributesSeq;
     789             :       
     790           0 :     xmlNode* root_element = xmlDocGetRootElement(doc);
     791           0 :     if ( root_element == NULL || root_element->type != XML_ELEMENT_NODE )
     792           0 :       throw ConversionException("Failed to parse the xmlHeader into a DOM structure.", "Focus");
     793             :     
     794           0 :     const ByteOrder* byteOrder=0;
     795           0 :     if ( string("ASDMBinaryTable").compare((const char*) root_element->name) == 0) {
     796             :       // Then it's an "old fashioned" MIME file for tables.
     797             :       // Just try to deserialize it with Big_Endian for the bytes ordering.
     798           0 :       byteOrder = asdm::ByteOrder::Big_Endian;
     799             :       
     800             :          //
     801             :     // Let's consider a  default order for the sequence of attributes.
     802             :     //
     803             :     
     804             :          
     805           0 :     attributesSeq.push_back("antennaId") ; 
     806             :          
     807           0 :     attributesSeq.push_back("timeInterval") ; 
     808             :          
     809           0 :     attributesSeq.push_back("focusTracking") ; 
     810             :          
     811           0 :     attributesSeq.push_back("focusOffset") ; 
     812             :          
     813           0 :     attributesSeq.push_back("focusRotationOffset") ; 
     814             :          
     815           0 :     attributesSeq.push_back("focusModelId") ; 
     816             :         
     817             :          
     818           0 :     attributesSeq.push_back("measuredFocusPosition") ; 
     819             :          
     820           0 :     attributesSeq.push_back("measuredFocusRotation") ; 
     821             :         
     822             :      
     823             :     
     824             :     
     825             :     // And decide that it has version == "2"
     826           0 :     version = "2";         
     827             :      }
     828           0 :     else if (string("FocusTable").compare((const char*) root_element->name) == 0) {
     829             :       // It's a new (and correct) MIME file for tables.
     830             :       //
     831             :       // 1st )  Look for a BulkStoreRef element with an attribute byteOrder.
     832             :       //
     833           0 :       xmlNode* bulkStoreRef = 0;
     834           0 :       xmlNode* child = root_element->children;
     835             :       
     836           0 :       if (xmlHasProp(root_element, (const xmlChar*) "schemaVersion")) {
     837           0 :         xmlChar * value = xmlGetProp(root_element, (const xmlChar *) "schemaVersion");
     838           0 :         version = string ((const char *) value);
     839           0 :         xmlFree(value); 
     840             :       }
     841             :       
     842             :       // Skip the two first children (Entity and ContainerEntity).
     843           0 :       bulkStoreRef = (child ==  0) ? 0 : ( (child->next) == 0 ? 0 : child->next->next );
     844             :       
     845           0 :       if ( bulkStoreRef == 0 || (bulkStoreRef->type != XML_ELEMENT_NODE)  || (string("BulkStoreRef").compare((const char*) bulkStoreRef->name) != 0))
     846           0 :         throw ConversionException ("Could not find the element '/FocusTable/BulkStoreRef'. Invalid XML header '"+ xmlHeader + "'.", "Focus");
     847             :         
     848             :       // We found BulkStoreRef, now look for its attribute byteOrder.
     849           0 :       _xmlAttr* byteOrderAttr = 0;
     850           0 :       for (struct _xmlAttr* attr = bulkStoreRef->properties; attr; attr = attr->next) 
     851           0 :           if (string("byteOrder").compare((const char*) attr->name) == 0) {
     852           0 :            byteOrderAttr = attr;
     853           0 :            break;
     854             :          }
     855             :       
     856           0 :       if (byteOrderAttr == 0) 
     857           0 :              throw ConversionException("Could not find the element '/FocusTable/BulkStoreRef/@byteOrder'. Invalid XML header '" + xmlHeader +"'.", "Focus");
     858             :       
     859           0 :       string byteOrderValue = string((const char*) byteOrderAttr->children->content);
     860           0 :       if (!(byteOrder = asdm::ByteOrder::fromString(byteOrderValue)))
     861           0 :                 throw ConversionException("No valid value retrieved for the element '/FocusTable/BulkStoreRef/@byteOrder'. Invalid XML header '" + xmlHeader + "'.", "Focus");
     862             :                 
     863             :          //
     864             :          // 2nd) Look for the Attributes element and grab the names of the elements it contains.
     865             :          //
     866           0 :          xmlNode* attributes = bulkStoreRef->next;
     867           0 :      if ( attributes == 0 || (attributes->type != XML_ELEMENT_NODE)  || (string("Attributes").compare((const char*) attributes->name) != 0))     
     868           0 :         throw ConversionException ("Could not find the element '/FocusTable/Attributes'. Invalid XML header '"+ xmlHeader + "'.", "Focus");
     869             :  
     870           0 :         xmlNode* childOfAttributes = attributes->children;
     871             :         
     872           0 :         while ( childOfAttributes != 0 && (childOfAttributes->type == XML_ELEMENT_NODE) ) {
     873           0 :                 attributesSeq.push_back(string((const char*) childOfAttributes->name));
     874           0 :                 childOfAttributes = childOfAttributes->next;
     875             :     }
     876           0 :     }
     877             :     // Create an EndianISStream from the substring containing the binary part.
     878           0 :     EndianISStream eiss(mimeMsg.substr(loc1+binPartMIMEHeader.size()), byteOrder);
     879             :     
     880           0 :     entity = Entity::fromBin((EndianIStream&) eiss);
     881             :     
     882             :     // We do nothing with that but we have to read it.
     883           0 :     Entity containerEntity = Entity::fromBin((EndianIStream&) eiss);
     884             : 
     885             :         // Let's read numRows but ignore it and rely on the value specified in the ASDM.xml file.    
     886           0 :     int numRows = ((EndianIStream&) eiss).readInt();
     887           0 :     if ((numRows != -1)                        // Then these are *not* data produced at the EVLA.
     888           0 :         && ((unsigned int) numRows != this->declaredSize )) { // Then the declared size (in ASDM.xml) is not equal to the one 
     889             :                                                // written into the binary representation of the table.
     890           0 :                 cout << "The a number of rows ('" 
     891             :                          << numRows
     892           0 :                          << "') declared in the binary representation of the table is different from the one declared in ASDM.xml ('"
     893           0 :                          << this->declaredSize
     894           0 :                          << "'). I'll proceed with the value declared in ASDM.xml"
     895           0 :                          << endl;
     896             :     }                                           
     897             : 
     898           0 :         if (getContainer().checkRowUniqueness()) {
     899             :         try {
     900           0 :                 for (uint32_t i = 0; i < this->declaredSize; i++) {
     901           0 :                                 FocusRow* aRow = FocusRow::fromBin((EndianIStream&) eiss, *this, attributesSeq);
     902           0 :                                 checkAndAdd(aRow);
     903             :                 }
     904             :         }
     905           0 :         catch (const DuplicateKey &e) {
     906           0 :                 throw ConversionException("Error while writing binary data , the message was "
     907           0 :                                 + e.getMessage(), "Focus");
     908           0 :         }
     909           0 :         catch (const TagFormatException &e) {
     910           0 :                  throw ConversionException("Error while reading binary data , the message was "
     911           0 :                                 + e.getMessage(), "Focus");
     912           0 :         }
     913             :     }
     914             :     else {
     915           0 :                 for (uint32_t i = 0; i < this->declaredSize; i++) {
     916           0 :                         FocusRow* aRow = FocusRow::fromBin((EndianIStream&) eiss, *this, attributesSeq);
     917           0 :                         append(aRow);
     918             :         }       
     919             :     }
     920             :     //Does not change the convention defined in the model.      
     921             :     //archiveAsBin = true;
     922             :     //fileAsBin = true;
     923           0 :     if ( doc != NULL ) xmlFreeDoc(doc);
     924             : 
     925           0 :         }
     926             :         
     927           0 :         void FocusTable::setUnknownAttributeBinaryReader(const string& attributeName, BinaryAttributeReaderFunctor* barFctr) {
     928             :                 //
     929             :                 // Is this attribute really unknown ?
     930             :                 //
     931           0 :                 for (vector<string>::const_iterator iter = attributesNamesOfFocus_v.begin(); iter != attributesNamesOfFocus_v.end(); iter++) {
     932           0 :                         if ((*iter).compare(attributeName) == 0) 
     933           0 :                                 throw ConversionException("the attribute '"+attributeName+"' is known you can't override the way it's read in the MIME binary file containing the table.", "Focus"); 
     934             :                 }
     935             :                 
     936             :                 // Ok then register the functor to activate when an unknown attribute is met during the reading of a binary table?
     937           0 :                 unknownAttributes2Functors[attributeName] = barFctr;
     938           0 :         }
     939             :         
     940           0 :         BinaryAttributeReaderFunctor* FocusTable::getUnknownAttributeBinaryReader(const string& attributeName) const {
     941           0 :                 map<string, BinaryAttributeReaderFunctor*>::const_iterator iter = unknownAttributes2Functors.find(attributeName);
     942           0 :                 return (iter == unknownAttributes2Functors.end()) ? 0 : iter->second;
     943             :         }
     944             : 
     945             :         
     946           0 :         void FocusTable::toFile(string directory) {
     947           0 :                 if (!directoryExists(directory.c_str()) &&
     948           0 :                         !createPath(directory.c_str())) {
     949           0 :                         throw ConversionException("Could not create directory " , directory);
     950             :                 }
     951             : 
     952           0 :                 string fileName = directory + "/Focus.xml";
     953           0 :                 ofstream tableout(fileName.c_str(),ios::out|ios::trunc);
     954           0 :                 if (tableout.rdstate() == ostream::failbit)
     955           0 :                         throw ConversionException("Could not open file " + fileName + " to write ", "Focus");
     956           0 :                 if (fileAsBin) 
     957           0 :                         tableout << MIMEXMLPart();
     958             :                 else
     959           0 :                         tableout << toXML() << endl;
     960           0 :                 tableout.close();
     961           0 :                 if (tableout.rdstate() == ostream::failbit)
     962           0 :                         throw ConversionException("Could not close file " + fileName, "Focus");
     963             : 
     964           0 :                 if (fileAsBin) {
     965             :                         // write the bin serialized
     966           0 :                         string fileName = directory + "/Focus.bin";
     967           0 :                         ofstream tableout(fileName.c_str(),ios::out|ios::trunc);
     968           0 :                         if (tableout.rdstate() == ostream::failbit)
     969           0 :                                 throw ConversionException("Could not open file " + fileName + " to write ", "Focus");
     970           0 :                         tableout << toMIME() << endl;
     971           0 :                         tableout.close();
     972           0 :                         if (tableout.rdstate() == ostream::failbit)
     973           0 :                                 throw ConversionException("Could not close file " + fileName, "Focus");
     974           0 :                 }
     975           0 :         }
     976             : 
     977             :         
     978           0 :         void FocusTable::setFromFile(const string& directory) {
     979             : #ifndef WITHOUT_BOOST
     980             :     if (boost::filesystem::exists(boost::filesystem::path(uniqSlashes(directory + "/Focus.xml"))))
     981             :       setFromXMLFile(directory);
     982             :     else if (boost::filesystem::exists(boost::filesystem::path(uniqSlashes(directory + "/Focus.bin"))))
     983             :       setFromMIMEFile(directory);
     984             : #else 
     985             :     // alternative in Misc.h
     986           0 :     if (file_exists(uniqSlashes(directory + "/Focus.xml")))
     987           0 :       setFromXMLFile(directory);
     988           0 :     else if (file_exists(uniqSlashes(directory + "/Focus.bin")))
     989           0 :       setFromMIMEFile(directory);
     990             : #endif
     991             :     else
     992           0 :       throw ConversionException("No file found for the Focus table", "Focus");
     993           0 :         }                       
     994             : 
     995             :         
     996           0 :   void FocusTable::setFromMIMEFile(const string& directory) {
     997           0 :     string tablePath ;
     998             :     
     999           0 :     tablePath = directory + "/Focus.bin";
    1000           0 :     ifstream tablefile(tablePath.c_str(), ios::in|ios::binary);
    1001           0 :     if (!tablefile.is_open()) { 
    1002           0 :       throw ConversionException("Could not open file " + tablePath, "Focus");
    1003             :     }
    1004             :     // Read in a stringstream.
    1005           0 :     stringstream ss; ss << tablefile.rdbuf();
    1006             :     
    1007           0 :     if (tablefile.rdstate() == istream::failbit || tablefile.rdstate() == istream::badbit) {
    1008           0 :       throw ConversionException("Error reading file " + tablePath,"Focus");
    1009             :     }
    1010             :     
    1011             :     // And close.
    1012           0 :     tablefile.close();
    1013           0 :     if (tablefile.rdstate() == istream::failbit)
    1014           0 :       throw ConversionException("Could not close file " + tablePath,"Focus");
    1015             :     
    1016           0 :     setFromMIME(ss.str());
    1017           0 :   }     
    1018             : /* 
    1019             :   void FocusTable::openMIMEFile (const string& directory) {
    1020             :                 
    1021             :         // Open the file.
    1022             :         string tablePath ;
    1023             :     tablePath = directory + "/Focus.bin";
    1024             :     ifstream tablefile(tablePath.c_str(), ios::in|ios::binary);
    1025             :     if (!tablefile.is_open())
    1026             :       throw ConversionException("Could not open file " + tablePath, "Focus");
    1027             :       
    1028             :         // Locate the xmlPartMIMEHeader.
    1029             :     string xmlPartMIMEHeader = "CONTENT-ID: <HEADER.XML>\n\n";
    1030             :     CharComparator comparator;
    1031             :     istreambuf_iterator<char> BEGIN(tablefile.rdbuf());
    1032             :     istreambuf_iterator<char> END;
    1033             :     istreambuf_iterator<char> it = search(BEGIN, END, xmlPartMIMEHeader.begin(), xmlPartMIMEHeader.end(), comparator);
    1034             :     if (it == END) 
    1035             :         throw ConversionException("failed to detect the beginning of the XML header", "Focus");
    1036             :     
    1037             :     // Locate the binaryPartMIMEHeader while accumulating the characters of the xml header.     
    1038             :     string binPartMIMEHeader = "--MIME_BOUNDARY\nCONTENT-TYPE: BINARY/OCTET-STREAM\nCONTENT-ID: <CONTENT.BIN>\n\n";
    1039             :     string xmlHeader;
    1040             :         CharCompAccumulator compaccumulator(&xmlHeader, 100000);
    1041             :         ++it;
    1042             :         it = search(it, END, binPartMIMEHeader.begin(), binPartMIMEHeader.end(), compaccumulator);
    1043             :         if (it == END) 
    1044             :                 throw ConversionException("failed to detect the beginning of the binary part", "Focus");
    1045             :         
    1046             :         cout << xmlHeader << endl;
    1047             :         //
    1048             :         // We have the xmlHeader , let's parse it.
    1049             :         //
    1050             :         xmlDoc *doc;
    1051             :     doc = xmlReadMemory(xmlHeader.data(), xmlHeader.size(), "BinaryTableHeader.xml", NULL, XML_PARSE_NOBLANKS);
    1052             :     if ( doc == NULL ) 
    1053             :       throw ConversionException("Failed to parse the xmlHeader into a DOM structure.", "Focus");
    1054             :     
    1055             :    // This vector will be filled by the names of  all the attributes of the table
    1056             :    // in the order in which they are expected to be found in the binary representation.
    1057             :    //
    1058             :     vector<string> attributesSeq(attributesNamesInBinOfFocus_v);
    1059             :       
    1060             :     xmlNode* root_element = xmlDocGetRootElement(doc);
    1061             :     if ( root_element == NULL || root_element->type != XML_ELEMENT_NODE )
    1062             :       throw ConversionException("Failed to parse the xmlHeader into a DOM structure.", "Focus");
    1063             :     
    1064             :     const ByteOrder* byteOrder=0;
    1065             :     if ( string("ASDMBinaryTable").compare((const char*) root_element->name) == 0) {
    1066             :       // Then it's an "old fashioned" MIME file for tables.
    1067             :       // Just try to deserialize it with Big_Endian for the bytes ordering.
    1068             :       byteOrder = asdm::ByteOrder::Big_Endian;
    1069             :         
    1070             :       // And decide that it has version == "2"
    1071             :     version = "2";         
    1072             :      }
    1073             :     else if (string("FocusTable").compare((const char*) root_element->name) == 0) {
    1074             :       // It's a new (and correct) MIME file for tables.
    1075             :       //
    1076             :       // 1st )  Look for a BulkStoreRef element with an attribute byteOrder.
    1077             :       //
    1078             :       xmlNode* bulkStoreRef = 0;
    1079             :       xmlNode* child = root_element->children;
    1080             :       
    1081             :       if (xmlHasProp(root_element, (const xmlChar*) "schemaVersion")) {
    1082             :         xmlChar * value = xmlGetProp(root_element, (const xmlChar *) "schemaVersion");
    1083             :         version = string ((const char *) value);
    1084             :         xmlFree(value); 
    1085             :       }
    1086             :       
    1087             :       // Skip the two first children (Entity and ContainerEntity).
    1088             :       bulkStoreRef = (child ==  0) ? 0 : ( (child->next) == 0 ? 0 : child->next->next );
    1089             :       
    1090             :       if ( bulkStoreRef == 0 || (bulkStoreRef->type != XML_ELEMENT_NODE)  || (string("BulkStoreRef").compare((const char*) bulkStoreRef->name) != 0))
    1091             :         throw ConversionException ("Could not find the element '/FocusTable/BulkStoreRef'. Invalid XML header '"+ xmlHeader + "'.", "Focus");
    1092             :         
    1093             :       // We found BulkStoreRef, now look for its attribute byteOrder.
    1094             :       _xmlAttr* byteOrderAttr = 0;
    1095             :       for (struct _xmlAttr* attr = bulkStoreRef->properties; attr; attr = attr->next) 
    1096             :           if (string("byteOrder").compare((const char*) attr->name) == 0) {
    1097             :            byteOrderAttr = attr;
    1098             :            break;
    1099             :          }
    1100             :       
    1101             :       if (byteOrderAttr == 0) 
    1102             :              throw ConversionException("Could not find the element '/FocusTable/BulkStoreRef/@byteOrder'. Invalid XML header '" + xmlHeader +"'.", "Focus");
    1103             :       
    1104             :       string byteOrderValue = string((const char*) byteOrderAttr->children->content);
    1105             :       if (!(byteOrder = asdm::ByteOrder::fromString(byteOrderValue)))
    1106             :                 throw ConversionException("No valid value retrieved for the element '/FocusTable/BulkStoreRef/@byteOrder'. Invalid XML header '" + xmlHeader + "'.", "Focus");
    1107             :                 
    1108             :          //
    1109             :          // 2nd) Look for the Attributes element and grab the names of the elements it contains.
    1110             :          //
    1111             :          xmlNode* attributes = bulkStoreRef->next;
    1112             :      if ( attributes == 0 || (attributes->type != XML_ELEMENT_NODE)  || (string("Attributes").compare((const char*) attributes->name) != 0))     
    1113             :         throw ConversionException ("Could not find the element '/FocusTable/Attributes'. Invalid XML header '"+ xmlHeader + "'.", "Focus");
    1114             :  
    1115             :         xmlNode* childOfAttributes = attributes->children;
    1116             :         
    1117             :         while ( childOfAttributes != 0 && (childOfAttributes->type == XML_ELEMENT_NODE) ) {
    1118             :                 attributesSeq.push_back(string((const char*) childOfAttributes->name));
    1119             :                 childOfAttributes = childOfAttributes->next;
    1120             :     }
    1121             :     }
    1122             :     // Create an EndianISStream from the substring containing the binary part.
    1123             :     EndianIFStream eifs(&tablefile, byteOrder);
    1124             :     
    1125             :     entity = Entity::fromBin((EndianIStream &) eifs);
    1126             :     
    1127             :     // We do nothing with that but we have to read it.
    1128             :     Entity containerEntity = Entity::fromBin((EndianIStream &) eifs);
    1129             : 
    1130             :         // Let's read numRows but ignore it and rely on the value specified in the ASDM.xml file.    
    1131             :     int numRows = eifs.readInt();
    1132             :     if ((numRows != -1)                        // Then these are *not* data produced at the EVLA.
    1133             :         && ((unsigned int) numRows != this->declaredSize )) { // Then the declared size (in ASDM.xml) is not equal to the one 
    1134             :                                                // written into the binary representation of the table.
    1135             :                 cout << "The a number of rows ('" 
    1136             :                          << numRows
    1137             :                          << "') declared in the binary representation of the table is different from the one declared in ASDM.xml ('"
    1138             :                          << this->declaredSize
    1139             :                          << "'). I'll proceed with the value declared in ASDM.xml"
    1140             :                          << endl;
    1141             :     }
    1142             :     // clean up xmlDoc pointer
    1143             :     if ( doc != NULL ) xmlFreeDoc(doc);    
    1144             :   } 
    1145             :  */
    1146             : 
    1147             :         
    1148           0 : void FocusTable::setFromXMLFile(const string& directory) {
    1149           0 :     string tablePath ;
    1150             :     
    1151           0 :     tablePath = directory + "/Focus.xml";
    1152             :     
    1153             :     /*
    1154             :     ifstream tablefile(tablePath.c_str(), ios::in|ios::binary);
    1155             :     if (!tablefile.is_open()) { 
    1156             :       throw ConversionException("Could not open file " + tablePath, "Focus");
    1157             :     }
    1158             :       // Read in a stringstream.
    1159             :     stringstream ss;
    1160             :     ss << tablefile.rdbuf();
    1161             :     
    1162             :     if  (tablefile.rdstate() == istream::failbit || tablefile.rdstate() == istream::badbit) {
    1163             :       throw ConversionException("Error reading file '" + tablePath + "'", "Focus");
    1164             :     }
    1165             :     
    1166             :     // And close
    1167             :     tablefile.close();
    1168             :     if (tablefile.rdstate() == istream::failbit)
    1169             :       throw ConversionException("Could not close file '" + tablePath + "'", "Focus");
    1170             : 
    1171             :     // Let's make a string out of the stringstream content and empty the stringstream.
    1172             :     string xmlDocument = ss.str(); ss.str("");
    1173             :         
    1174             :     // Let's make a very primitive check to decide
    1175             :     // whether the XML content represents the table
    1176             :     // or refers to it via a <BulkStoreRef element.
    1177             :     */
    1178             :     
    1179           0 :     string xmlDocument;
    1180             :     try {
    1181           0 :         xmlDocument = getContainer().getXSLTransformer()(tablePath);
    1182           0 :         if (getenv("ASDM_DEBUG")) cout << "About to read " << tablePath << endl;
    1183             :     }
    1184           0 :     catch (const XSLTransformerException &e) {
    1185           0 :         throw ConversionException("Caugth an exception whose message is '" + e.getMessage() + "'.", "Focus");
    1186           0 :     }
    1187             :     
    1188           0 :     if (xmlDocument.find("<BulkStoreRef") != string::npos)
    1189           0 :       setFromMIMEFile(directory);
    1190             :     else
    1191           0 :       fromXML(xmlDocument);
    1192           0 :   }
    1193             : 
    1194             :         
    1195             : 
    1196             :         
    1197             : 
    1198             :                         
    1199             :         
    1200             :                 
    1201             :                 
    1202             :         /**
    1203             :          * Insert a FocusRow* in a vector of FocusRow* so that it's ordered by ascending start time.
    1204             :          *
    1205             :          * @param FocusRow* x . The pointer to be inserted.
    1206             :          * @param vector <FocusRow*>& row. A reference to the vector where to insert x.
    1207             :          *
    1208             :          */
    1209           0 :          FocusRow* FocusTable::insertByStartTime(FocusRow* x, vector<FocusRow*>& row) {
    1210             :                                 
    1211           0 :                 vector <FocusRow*>::iterator theIterator;
    1212             :                 
    1213           0 :                 ArrayTime start = x->timeInterval.getStart();
    1214             : 
    1215             :         // Is the row vector empty ?
    1216           0 :         if (row.size() == 0) {
    1217           0 :                 row.push_back(x);
    1218           0 :                 privateRows.push_back(x);
    1219           0 :                 x->isAdded(true);
    1220           0 :                 return x;
    1221             :         }
    1222             :         
    1223             :         // Optimization for the case of insertion by ascending time.
    1224           0 :         FocusRow* last = *(row.end()-1);
    1225             :         
    1226           0 :         if ( start > last->timeInterval.getStart() ) {
    1227             :                 //
    1228             :                 // Modify the duration of last if and only if the start time of x
    1229             :                 // is located strictly before the end time of last.
    1230             :                 //
    1231           0 :                         if ( start < (last->timeInterval.getStart() + last->timeInterval.getDuration()))               
    1232           0 :                         last->timeInterval.setDuration(start - last->timeInterval.getStart());
    1233           0 :                 row.push_back(x);
    1234           0 :                 privateRows.push_back(x);
    1235           0 :                 x->isAdded(true);
    1236           0 :                 return x;
    1237             :         }
    1238             :         
    1239             :         // Optimization for the case of insertion by descending time.
    1240           0 :         FocusRow* first = *(row.begin());
    1241             :         
    1242           0 :         if ( start < first->timeInterval.getStart() ) {
    1243             :                         //
    1244             :                         // Modify the duration of x if and only if the start time of first
    1245             :                         // is located strictly before the end time of x.
    1246             :                         //
    1247           0 :                         if ( first->timeInterval.getStart() < (start + x->timeInterval.getDuration()) )                        
    1248           0 :                         x->timeInterval.setDuration(first->timeInterval.getStart() - start);
    1249           0 :                 row.insert(row.begin(), x);
    1250           0 :                 privateRows.push_back(x);
    1251           0 :                 x->isAdded(true);
    1252           0 :                 return x;
    1253             :         }
    1254             :         
    1255             :         // Case where x has to be inserted inside row; let's use a dichotomy
    1256             :         // method to find the insertion index.
    1257           0 :                 unsigned int k0 = 0;
    1258           0 :                 unsigned int k1 = row.size() - 1;
    1259             :         
    1260           0 :                 while (k0 != (k1 - 1)) {
    1261           0 :                         if (start == row[k0]->timeInterval.getStart()) {
    1262           0 :                                 if (row[k0]->equalByRequiredValue(x))
    1263           0 :                                         return row[k0];
    1264             :                                 else
    1265           0 :                                         throw DuplicateKey("DuplicateKey exception in ", "FocusTable");     
    1266             :                         }
    1267           0 :                         else if (start == row[k1]->timeInterval.getStart()) {
    1268           0 :                                 if (row[k1]->equalByRequiredValue(x))
    1269           0 :                                         return row[k1];
    1270             :                                 else
    1271           0 :                                         throw DuplicateKey("DuplicateKey exception in ", "FocusTable");     
    1272             :                         }
    1273             :                         else {
    1274           0 :                                 if (start <= row[(k0+k1)/2]->timeInterval.getStart())
    1275           0 :                                         k1 = (k0 + k1) / 2;
    1276             :                                 else
    1277           0 :                                         k0 = (k0 + k1) / 2;                             
    1278             :                         }       
    1279             :                 }
    1280             : 
    1281           0 :                 if (start == row[k0]->timeInterval.getStart()) {
    1282           0 :                         if (row[k0]->equalByRequiredValue(x))
    1283           0 :                                 return row[k0];
    1284             :                         else
    1285           0 :                                 throw DuplicateKey("DuplicateKey exception in ", "FocusTable");     
    1286             :                 }
    1287           0 :                 else if (start == row[k1]->timeInterval.getStart()) {
    1288           0 :                         if (row[k1]->equalByRequiredValue(x))
    1289           0 :                                 return row[k1];
    1290             :                         else
    1291           0 :                                 throw DuplicateKey("DuplicateKey exception in ", "FocusTable");     
    1292             :                 }       
    1293             : 
    1294           0 :                 row[k0]->timeInterval.setDuration(start-row[k0]->timeInterval.getStart());
    1295           0 :                 x->timeInterval.setDuration(row[k0+1]->timeInterval.getStart() - start);
    1296           0 :                 row.insert(row.begin()+(k0+1), x);
    1297           0 :                 privateRows.push_back(x);
    1298           0 :                 x->isAdded(true);
    1299           0 :                 return x;   
    1300           0 :     } 
    1301             :         
    1302             :         
    1303             :         
    1304             : 
    1305             :         
    1306             : } // End namespace asdm
    1307             :  

Generated by: LCOV version 1.16