source: trunk/zoo-project/zoo-kernel/service_internal_otb.c @ 646

Last change on this file since 646 was 646, checked in by djay, 9 years ago

Remove uneeded debug messages in OTB support

  • Property svn:keywords set to Id
File size: 16.4 KB
Line 
1/*
2 * Author : Gérald FENOY
3 *
4 * Copyright (c) 2015 GeoLabs SARL
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 * See Ref: http://hg.orfeo-toolbox.org/OTB/ Copyright
25 * Some parts of this code are derived from ITK. See ITKCopyright.txt for
26 * details.
27 */
28
29#include "service_internal_otb.h"
30#include "response_print.h"
31#include "server_internal.h"
32
33using namespace otb::Wrapper;
34
35/**
36 * Global OTB counter
37 */
38int otbCounter=0;
39
40/**
41 * The ZooWatcher list
42 */
43WatcherListType m_WatcherList;
44/**
45 * A pointer to the conf maps containing the main.cfg settings
46 */
47maps* m_Conf;
48
49/**
50 * The command to create a ZooWatcher and add it to the global m_WatcherList
51 */
52class MyCommand : public itk::Command
53{
54 public:
55  itkNewMacro( MyCommand );
56 public:
57
58  /**
59   * The method that defines the action to be taken by the command.
60   *
61   * @param caller an itk::Object pointer
62   * @param event an itk::EventObject pointer
63   */
64  void Execute(itk::Object *caller, const itk::EventObject & event)
65  {
66    Execute( (const itk::Object *)caller, event);
67  }
68 
69  /**
70   * The method that defines the action to be taken by the command.
71   * Create a new ZooWatcher instance then add it to the m_WatcherList.
72   *
73   * @param caller a const itk::Object pointer
74   * @param event an itk::EventObject pointer
75   * @see ZooWatcher,ZooWatcher::SetConf
76   */
77  void Execute(const itk::Object *caller, const itk::EventObject & event)
78  {
79    const AddProcessToWatchEvent* eventToWatch = dynamic_cast< const AddProcessToWatchEvent*> ( &event );
80    std::string m_CurrentDescription = eventToWatch->GetProcessDescription();
81    ZooWatcher * watch = new ZooWatcher(eventToWatch->GetProcess(),
82                                        eventToWatch->GetProcessDescription());
83    watch->SetConf(&m_Conf);
84    m_WatcherList.push_back(watch);
85  }
86
87};
88
89/**
90 * Replace all occurence of from by to in a str string
91 *
92 * @param str the string to transform
93 * @param from the string to replace
94 * @param to the string used as replacement
95 * @return the resulting string
96 */
97std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
98    size_t start_pos = 0;
99    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
100        str.replace(start_pos, from.length(), to);
101        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
102    }
103    return str;
104}
105
106/**
107 * Load and run an OTB Application corresponding to the service by using inputs parameters.
108 * Define the m_Conf
109 *
110 * @param main_conf the conf maps containing the main.cfg settings
111 * @param request the map containing the HTTP request
112 * @param s the service structure
113 * @param real_inputs the maps containing the inputs
114 * @param real_outputs the maps containing the outputs
115 */
116int zoo_otb_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){
117  maps* m=*main_conf;
118  maps* inputs=*real_inputs;
119  maps* outputs=*real_outputs;
120  map* tmp0=getMapFromMaps(*main_conf,"lenv","cwd");
121  char *ntmp=tmp0->value;
122  map* tmp=NULL;
123  int res=-1;
124  std::vector<std::string> list = ApplicationRegistry::GetAvailableApplications();
125  if (list.size() == 0){
126    map* tmps=createMap("text","No OTB Application found.");
127    addToMap(tmps,"code","InternalError");
128    printExceptionReportResponse(m,tmps);
129    freeMap(&tmps);
130    free(tmps);
131    res=-1;
132    return res;
133  }
134  else{
135    dumpMapsValuesToFiles(main_conf,real_inputs);
136    for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it){
137      if(s->name==*it){
138        Application::Pointer m_Application=ApplicationRegistry::CreateApplication(*it);
139        if (m_Application.IsNull()){
140          char tmpS[1024];
141          sprintf(tmpS, "The OTB Application %s cannot be loaded.", (*it).c_str());
142          map* tmps=createMap("text",tmpS);
143          addToMap(tmps,"code","InternalError");
144          printExceptionReportResponse(m,tmps);
145          freeMap(&tmps);
146          free(tmps);
147          res=-1;
148        }else{
149          // Create Observer on AddProcessToWatchEvent
150          m_Conf=m;
151          MyCommand::Pointer myCommand = MyCommand::New();
152          m_Application->AddObserver(AddProcessToWatchEvent(), myCommand);
153          char tmpS[1024];
154          const std::vector<std::string> appKeyList = m_Application->GetParametersKeys(true);
155          for (unsigned int i = 0; i < appKeyList.size(); i++){
156            const std::string paramKey(appKeyList[i]);
157            Parameter::Pointer param = m_Application->GetParameterByKey(paramKey);
158            ParameterType type = m_Application->GetParameterType(paramKey);
159            if (type != ParameterType_Group && paramKey!="inxml" && paramKey!="outxml"){
160              map* test=getMapFromMaps(inputs,paramKey.c_str(),"cache_file");
161              if(test==NULL){
162                test=getMapFromMaps(inputs,paramKey.c_str(),"inRequest");
163                map* tmpPath=getMapFromMaps(m,"main","tmpPath");
164                map* tmpSid=getMapFromMaps(m,"lenv","usid");
165                char tmp[1024];
166                map* tmpVal=getMapFromMaps(outputs,paramKey.c_str(),"mimeType");
167                maps* tmpMaps=getMaps(outputs,paramKey.c_str());
168                if(tmpMaps!=NULL && test!=NULL && test->value!=NULL && strncasecmp(test->value,"true",4)==0){
169                  test=getMapFromMaps(inputs,paramKey.c_str(),"value");
170                  if(type == ParameterType_OutputImage){
171                    ImagePixelType outPixType = ImagePixelType_float;
172                    if (strncasecmp(test->value,"uint8",5)==0)
173                      outPixType = ImagePixelType_uint8;
174                    else if (strncasecmp(test->value,"int16",5)==0)
175                      outPixType = ImagePixelType_int16;
176                    else if (strncasecmp(test->value,"uint16",6)==0)
177                      outPixType = ImagePixelType_uint16;
178                    else if (strncasecmp(test->value,"int32",5)==0)
179                      outPixType = ImagePixelType_int32;
180                    else if (strncasecmp(test->value,"uint32",6)==0)
181                      outPixType = ImagePixelType_uint32;
182                    else if (strncasecmp(test->value,"double",6)==0)
183                      outPixType = ImagePixelType_double;
184                    const char* ext="tiff";
185                    if(tmpVal!=NULL){
186                      if(strncasecmp(tmpVal->value,"image/jp2",9)==0)
187                         ext="j2k";
188                      else
189                        if(strncasecmp(tmpVal->value,"image/png",9)==0)
190                         ext="png";
191                        else
192                          if(strncasecmp(tmpVal->value,"image/jpeg",10)==0)
193                            ext="jpeg";
194                    }
195                    sprintf(tmp,"%s/%s_%d_%s.%s",tmpPath->value,s->name,otbCounter,tmpSid->value,ext);
196                    otbCounter++;
197                    m_Application->SetParameterString(paramKey, tmp);
198                    setMapInMaps(inputs,paramKey.c_str(),"generated_file",tmp);
199                    dynamic_cast<OutputImageParameter *> (param.GetPointer())->SetPixelType(outPixType);
200                  }
201                }else{
202                  if(type == ParameterType_OutputVectorData){
203                      char* ext="json";
204                      if(tmpVal!=NULL){
205                        if(strncasecmp(tmpVal->value,"text/xml",8)==0)
206                        ext="gml";
207                      else
208                        if(strncasecmp(tmpVal->value,"applicaton/json",15)==0)
209                          ext="json";
210                        else
211                          if(strncasecmp(tmpVal->value,"application/zip",14)==0)
212                            ext="shp";
213                          else
214                            if(strncasecmp(tmpVal->value,"application/vnd.google-earth.kml+xml",36)==0)
215                              ext="kml";
216                      }
217                      sprintf(tmp,"%s/%s_%d_%s.%s",tmpPath->value,s->name,otbCounter,tmpSid->value,ext);
218                      otbCounter++;
219                      m_Application->SetParameterString(paramKey, tmp);
220                      setMapInMaps(inputs,paramKey.c_str(),"generated_file",tmp);
221                  }
222                  else
223                    if(type == ParameterType_OutputFilename){
224                      char* ext="txt";
225                      if(tmpVal!=NULL){
226                        if(strncasecmp(tmpVal->value,"text/xml",8)==0)
227                          ext="xml";
228                        else
229                          if(strncasecmp(tmpVal->value,"text/csv",15)==0)
230                            ext="csv";
231                          else
232                            if(strncasecmp(tmpVal->value,"application/zip",14)==0)
233                              ext="shp";
234                            else
235                              if(strncasecmp(tmpVal->value,"application/vnd.google-earth.kml+xml",36)==0)
236                                ext="kml";
237                              else
238                                if(strncasecmp(tmpVal->value,"application/vnd.google-earth.kmz",32)==0){
239                                  ext="kmz";
240                                  sprintf(tmp,"%s/%s_%d_%sxt.%s",tmpPath->value,s->name,otbCounter,tmpSid->value,ext);
241                                  m_Application->SetParameterString(paramKey, tmp);
242                                  setMapInMaps(outputs,paramKey.c_str(),"expected_generated_file",tmp);
243                                }
244
245                      }
246                      sprintf(tmp,"%s/%s_%d_%s.%s",tmpPath->value,s->name,otbCounter,tmpSid->value,ext);
247                      otbCounter++;
248                      m_Application->SetParameterString(paramKey, tmp);
249                      setMapInMaps(inputs,paramKey.c_str(),"generated_file",tmp);
250                    }
251                    else{
252                      test=getMapFromMaps(inputs,paramKey.c_str(),"value");
253                      if(test!=NULL && type!=ParameterType_ListView){
254                        m_Application->SetParameterString(paramKey, test->value);
255                      }
256                      else
257                        if(type==ParameterType_ListView){
258                          std::vector<std::string> values;
259                          values.push_back(test->value);
260                          map* tmpLength=getMapFromMaps(inputs,paramKey.c_str(),"length");
261                          if(tmpLength!=NULL){
262                            int len=atoi(tmpLength->value);
263                            for(int k=1;k<len;k++){
264                              char tmp[15];
265                              sprintf(tmp,"cache_file_%d",k);
266                              map* tmpVal=getMapFromMaps(inputs,paramKey.c_str(),tmp);
267                              if(tmpVal!=NULL){
268                                values.push_back(tmpVal->value);
269                              }
270                            }
271                          }
272                          dynamic_cast<ListViewParameter *> (param.GetPointer())->SetSelectedItems(values);
273                        }
274                    }
275                }
276              }else{
277                if(type == ParameterType_InputImageList){
278                  std::vector<std::string> values;
279                  values.push_back(test->value);
280                  map* tmpPath=getMapFromMaps(inputs,paramKey.c_str(),"length");
281                  if(tmpPath!=NULL){
282                    int len=atoi(tmpPath->value);
283                    for(int k=1;k<len;k++){
284                      char tmp[15];
285                      sprintf(tmp,"cache_file_%d",k);
286                      map* tmpVal=getMapFromMaps(inputs,paramKey.c_str(),tmp);
287                      if(tmpVal!=NULL){
288                        values.push_back(tmpVal->value);
289                      }
290                    }
291                  }
292                  dynamic_cast<InputImageListParameter *> (param.GetPointer())->SetListFromFileName(values);
293                }
294                else
295                  if(type == ParameterType_InputVectorData || type == ParameterType_InputFilename){
296                    map* tmpPath=getMapFromMaps(m,"main","tmpPath");
297                    map* tmpSid=getMapFromMaps(m,"lenv","sid");
298                    char tmp[1024];
299                    map* tmpVal=getMapFromMaps(inputs,paramKey.c_str(),"mimeType");
300                    char* ext="json";
301                    if(tmpVal!=NULL){
302                      if(strncasecmp(tmpVal->value,"application/zip",14)==0){
303                        char *tmpName=(char*)malloc((strlen(test->value)+9)*sizeof(char));
304                        std::string test0(test->value);
305                        if(test0.find(".zca")!=std::string::npos){
306                          symlink(test->value,ReplaceAll(test->value,".zca",".zip").c_str());
307                          sprintf(tmpName,"/vsizip/%s",ReplaceAll(test->value,".zca",".zip").c_str());
308                        }else
309                          sprintf(tmpName,"/vsizip/%s",test->value);
310                        char **files=VSIReadDir(tmpName);
311                        int nFiles = CSLCount( files );
312                        char *tmpSSName=(char*)malloc((strlen(tmpPath->value)+strlen(paramKey.c_str())+strlen(tmpSid->value)+9)*sizeof(char));
313                        sprintf(tmpSSName,"%s/Input_%s_%s",tmpPath->value,paramKey.c_str(),tmpSid->value);
314                        mkdir(tmpSSName,0777);
315                           
316                        for(int kk=0;kk<nFiles;kk++){
317                          char *tmpSName=(char*)malloc((strlen(tmpName)+strlen(files[kk])+2)*sizeof(char));
318                          sprintf(tmpSName,"%s/%s",tmpName,files[kk]);
319                          VSILFILE* fmain=VSIFOpenL(tmpSName, "rb");
320                          if(fmain!=NULL){
321                            VSIFSeekL(fmain,0,SEEK_END);
322                            long count=VSIFTellL(fmain);
323                            VSIRewindL(fmain);
324
325                            char *content=(char*) malloc((count+1)*sizeof(char)); 
326                            VSIFReadL(content,1,count*sizeof(char),fmain);
327                         
328                            char *tmpSSSName=(char*)malloc((strlen(tmpSSName)+strlen(files[kk])+2)*sizeof(char));
329                            sprintf(tmpSSSName,"%s/%s",tmpSSName,files[kk]);
330                           
331                            FILE* fx=fopen(tmpSSSName, "wb");
332                            fwrite(content,1,count,fx);
333                            fclose(fx);
334                            VSIFCloseL(fmain);
335                            free(content);
336                            std::string test1(tmpSSSName);
337                            if(test1.find(".shp")!=std::string::npos){
338                              setMapInMaps(inputs,paramKey.c_str(),"cache_file",tmpSSSName);
339                              test=getMapFromMaps(inputs,paramKey.c_str(),"cache_file");
340                            }
341                            free(tmpSSSName);
342                          }
343                          free(tmpSName);
344                        }
345                        free(tmpSSName);
346                        free(tmpName);
347                      }
348                    }
349                   
350                    m_Application->SetParameterString(paramKey, test->value);
351                  }
352                  else
353                    if(type == ParameterType_InputImage
354                       || type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData
355                       || type == ParameterType_InputFilename){
356                      m_Application->SetParameterString(paramKey, test->value);
357                  }
358              }
359            }
360            param->SetUserValue(true);
361            m_Application->UpdateParameters();
362          }
363
364          try{
365            if( m_Application->ExecuteAndWriteOutput() == 0 ){
366              std::vector< std::pair<std::string, std::string> > paramList;
367              paramList = m_Application->GetOutputParametersSumUp();
368              if(paramList.size()>0)
369                for( unsigned int i=0; i<paramList.size(); i++){
370                  setMapInMaps(outputs,paramList[i].first.c_str(),"value",paramList[i].second.c_str());
371                }
372              else{
373                const std::vector<std::string> appKeyList = m_Application->GetParametersKeys(true);
374                for (unsigned int i = 0; i < appKeyList.size(); i++){
375                  const std::string paramKey(appKeyList[i]);
376                  std::vector<std::string> values;
377                  Parameter::Pointer param = m_Application->GetParameterByKey(paramKey);
378                  ParameterType type = m_Application->GetParameterType(paramKey);
379                  if (type != ParameterType_Group && paramKey!="inxml" && paramKey!="outxml"
380                      && (type == ParameterType_OutputImage || type == ParameterType_OutputFilename
381                          || type == ParameterType_OutputVectorData ) ){
382                    if(type == ParameterType_OutputImage || type == ParameterType_OutputFilename || type == ParameterType_OutputVectorData){
383                      map* test=getMapFromMaps(outputs,paramKey.c_str(),"mimeType");
384                      if(test!=NULL && strncasecmp(test->value,"application/zip",15)==0){
385                       
386                        test=getMapFromMaps(inputs,paramKey.c_str(),"generated_file");
387                        char tmpName[1024];
388                        sprintf(tmpName,"/vsizip/%s",ReplaceAll(test->value,".shp",".zip").c_str());
389                        VSILFILE* fmain=VSIFOpenL(tmpName, "w");
390                        FILE * file;
391                        char *tmp;
392                        char tmpSName[1024];
393                        long count;
394                       
395                        char *exts[4];
396                        exts[0]=".shp";
397                        exts[1]=".shx";
398                        exts[2]=".dbf";
399                        exts[3]=".prj";
400                        for(int c=0;c<4;c++){
401                          sprintf(tmpSName,"%s/result%s",tmpName,exts[c]);
402                         
403                          file=fopen(ReplaceAll(test->value,".shp",exts[c]).c_str(),"rb");
404                          if(file!=NULL){
405                            fseek(file, 0, SEEK_END);
406                            count = ftell(file);
407                            rewind(file);
408                           
409                            tmp=(char*) malloc((count+1)*sizeof(char)); 
410                            fread(tmp,1,count*sizeof(char),file);
411                           
412                            VSILFILE* fx=VSIFOpenL(tmpSName, "wb");
413                            VSIFWriteL(tmp,1,count,fx);
414                            VSIFCloseL(fx);
415                            fclose(file);
416                            free(tmp);
417                          }
418                        }
419                       
420                        VSIFCloseL(fmain);
421                       
422                        FILE* file1=fopen(ReplaceAll(test->value,".shp",".zip").c_str(), "rb");
423                        fseek(file1, 0, SEEK_END);
424                        count=ftell(file1);
425                        rewind(file1);
426                       
427                        tmp=(char*) malloc((count+1)*sizeof(char)); 
428                        fread(tmp,1,count*sizeof(char),file1);
429                       
430                        file=fopen(ReplaceAll(test->value,".shp",".zip").c_str(),"wb");
431                        fwrite(tmp,1,count,file);
432                        fclose(file);
433                        free(tmp);
434                        fclose(file1);
435                        setMapInMaps(inputs,paramKey.c_str(),"generated_file",ReplaceAll(test->value,".shp",".zip").c_str());
436                      }
437                      test=getMapFromMaps(inputs,paramKey.c_str(),"generated_file");
438
439                      if(test!=NULL){
440                        setMapInMaps(outputs,paramKey.c_str(),"generated_file",test->value);
441                      }
442
443                    }
444                  }
445                }
446              }
447              res=3;
448              break;
449            }
450            else{
451              sprintf(tmpS, "The OTB Application %s cannot be run.", s->name);
452              setMapInMaps(m,"lenv","message",tmpS);
453              res=SERVICE_FAILED;
454            }
455          }
456          catch(std::exception& err){
457            setMapInMaps(m,"lenv","message",err.what());
458            return SERVICE_FAILED;
459           
460          }
461          catch(...){
462            setMapInMaps(m,"lenv","message","An unknown exception has been raised during application execution");
463            res=SERVICE_FAILED;
464          }
465          break;
466        }
467      }
468    }
469  }
470
471  for (unsigned int i = 0; i < m_WatcherList.size(); i++){
472    m_WatcherList[i]->FreeConf();
473    delete m_WatcherList[i];
474    m_WatcherList[i] = NULL;
475  }
476  m_WatcherList.clear();
477
478  return res;
479}
Note: See TracBrowser for help on using the repository browser.

Search

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png