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

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

Small fix in OTB support

  • Property svn:keywords set to Id
File size: 16.6 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(test!=NULL && test->value!=NULL)                 
203                      m_Application->SetParameterString(paramKey, test->value);                 
204                  } 
205                }else{
206                  if(type == ParameterType_OutputVectorData){
207                      char* ext="json";
208                      if(tmpVal!=NULL){
209                        if(strncasecmp(tmpVal->value,"text/xml",8)==0)
210                        ext="gml";
211                      else
212                        if(strncasecmp(tmpVal->value,"applicaton/json",15)==0)
213                          ext="json";
214                        else
215                          if(strncasecmp(tmpVal->value,"application/zip",14)==0)
216                            ext="shp";
217                          else
218                            if(strncasecmp(tmpVal->value,"application/vnd.google-earth.kml+xml",36)==0)
219                              ext="kml";
220                      }
221                      sprintf(tmp,"%s/%s_%d_%s.%s",tmpPath->value,s->name,otbCounter,tmpSid->value,ext);
222                      otbCounter++;
223                      m_Application->SetParameterString(paramKey, tmp);
224                      setMapInMaps(inputs,paramKey.c_str(),"generated_file",tmp);
225                  }
226                  else
227                    if(type == ParameterType_OutputFilename){
228                      char* ext="txt";
229                      if(tmpVal!=NULL){
230                        if(strncasecmp(tmpVal->value,"text/xml",8)==0)
231                          ext="xml";
232                        else
233                          if(strncasecmp(tmpVal->value,"text/csv",15)==0)
234                            ext="csv";
235                          else
236                            if(strncasecmp(tmpVal->value,"application/zip",14)==0)
237                              ext="shp";
238                            else
239                              if(strncasecmp(tmpVal->value,"application/vnd.google-earth.kml+xml",36)==0)
240                                ext="kml";
241                              else
242                                if(strncasecmp(tmpVal->value,"application/vnd.google-earth.kmz",32)==0){
243                                  ext="kmz";
244                                  sprintf(tmp,"%s/%s_%d_%sxt.%s",tmpPath->value,s->name,otbCounter,tmpSid->value,ext);
245                                  m_Application->SetParameterString(paramKey, tmp);
246                                  setMapInMaps(outputs,paramKey.c_str(),"expected_generated_file",tmp);
247                                }
248
249                      }
250                      sprintf(tmp,"%s/%s_%d_%s.%s",tmpPath->value,s->name,otbCounter,tmpSid->value,ext);
251                      otbCounter++;
252                      m_Application->SetParameterString(paramKey, tmp);
253                      setMapInMaps(inputs,paramKey.c_str(),"generated_file",tmp);
254                    }
255                    else{
256                      test=getMapFromMaps(inputs,paramKey.c_str(),"value");
257                      if(test!=NULL && type!=ParameterType_ListView){
258                        m_Application->SetParameterString(paramKey, test->value);
259                      }
260                      else
261                        if(type==ParameterType_ListView){
262                          std::vector<std::string> values;
263                          values.push_back(test->value);
264                          map* tmpLength=getMapFromMaps(inputs,paramKey.c_str(),"length");
265                          if(tmpLength!=NULL){
266                            int len=atoi(tmpLength->value);
267                            for(int k=1;k<len;k++){
268                              char tmp[15];
269                              sprintf(tmp,"cache_file_%d",k);
270                              map* tmpVal=getMapFromMaps(inputs,paramKey.c_str(),tmp);
271                              if(tmpVal!=NULL){
272                                values.push_back(tmpVal->value);
273                              }
274                            }
275                          }
276                          dynamic_cast<ListViewParameter *> (param.GetPointer())->SetSelectedItems(values);
277                        }
278                    }
279                }
280              }else{
281                if(type == ParameterType_InputImageList){
282                  std::vector<std::string> values;
283                  values.push_back(test->value);
284                  map* tmpPath=getMapFromMaps(inputs,paramKey.c_str(),"length");
285                  if(tmpPath!=NULL){
286                    int len=atoi(tmpPath->value);
287                    for(int k=1;k<len;k++){
288                      char tmp[15];
289                      sprintf(tmp,"cache_file_%d",k);
290                      map* tmpVal=getMapFromMaps(inputs,paramKey.c_str(),tmp);
291                      if(tmpVal!=NULL){
292                        values.push_back(tmpVal->value);
293                      }
294                    }
295                  }
296                  dynamic_cast<InputImageListParameter *> (param.GetPointer())->SetListFromFileName(values);
297                }
298                else
299                  if(type == ParameterType_InputVectorData || type == ParameterType_InputFilename){
300                    map* tmpPath=getMapFromMaps(m,"main","tmpPath");
301                    map* tmpSid=getMapFromMaps(m,"lenv","sid");
302                    char tmp[1024];
303                    map* tmpVal=getMapFromMaps(inputs,paramKey.c_str(),"mimeType");
304                    char* ext="json";
305                    if(tmpVal!=NULL){
306                      if(strncasecmp(tmpVal->value,"application/zip",14)==0){
307                        char *tmpName=(char*)malloc((strlen(test->value)+9)*sizeof(char));
308                        std::string test0(test->value);
309                        if(test0.find(".zca")!=std::string::npos){
310                          symlink(test->value,ReplaceAll(test->value,".zca",".zip").c_str());
311                          sprintf(tmpName,"/vsizip/%s",ReplaceAll(test->value,".zca",".zip").c_str());
312                        }else
313                          sprintf(tmpName,"/vsizip/%s",test->value);
314                        char **files=VSIReadDir(tmpName);
315                        int nFiles = CSLCount( files );
316                        char *tmpSSName=(char*)malloc((strlen(tmpPath->value)+strlen(paramKey.c_str())+strlen(tmpSid->value)+9)*sizeof(char));
317                        sprintf(tmpSSName,"%s/Input_%s_%s",tmpPath->value,paramKey.c_str(),tmpSid->value);
318                        mkdir(tmpSSName,0777);
319                           
320                        for(int kk=0;kk<nFiles;kk++){
321                          char *tmpSName=(char*)malloc((strlen(tmpName)+strlen(files[kk])+2)*sizeof(char));
322                          sprintf(tmpSName,"%s/%s",tmpName,files[kk]);
323                          VSILFILE* fmain=VSIFOpenL(tmpSName, "rb");
324                          if(fmain!=NULL){
325                            VSIFSeekL(fmain,0,SEEK_END);
326                            long count=VSIFTellL(fmain);
327                            VSIRewindL(fmain);
328
329                            char *content=(char*) malloc((count+1)*sizeof(char)); 
330                            VSIFReadL(content,1,count*sizeof(char),fmain);
331                         
332                            char *tmpSSSName=(char*)malloc((strlen(tmpSSName)+strlen(files[kk])+2)*sizeof(char));
333                            sprintf(tmpSSSName,"%s/%s",tmpSSName,files[kk]);
334                           
335                            FILE* fx=fopen(tmpSSSName, "wb");
336                            fwrite(content,1,count,fx);
337                            fclose(fx);
338                            VSIFCloseL(fmain);
339                            free(content);
340                            std::string test1(tmpSSSName);
341                            if(test1.find(".shp")!=std::string::npos){
342                              setMapInMaps(inputs,paramKey.c_str(),"cache_file",tmpSSSName);
343                              test=getMapFromMaps(inputs,paramKey.c_str(),"cache_file");
344                            }
345                            free(tmpSSSName);
346                          }
347                          free(tmpSName);
348                        }
349                        free(tmpSSName);
350                        free(tmpName);
351                      }
352                    }
353                   
354                    m_Application->SetParameterString(paramKey, test->value);
355                  }
356                  else
357                    if(type == ParameterType_InputImage
358                       || type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData
359                       || type == ParameterType_InputFilename){
360                      m_Application->SetParameterString(paramKey, test->value);
361                  }
362              }
363            }
364            param->SetUserValue(true);
365            m_Application->UpdateParameters();
366          }
367
368          try{
369            if( m_Application->ExecuteAndWriteOutput() == 0 ){
370              std::vector< std::pair<std::string, std::string> > paramList;
371              paramList = m_Application->GetOutputParametersSumUp();
372              if(paramList.size()>0)
373                for( unsigned int i=0; i<paramList.size(); i++){
374                  setMapInMaps(outputs,paramList[i].first.c_str(),"value",paramList[i].second.c_str());
375                }
376              else{
377                const std::vector<std::string> appKeyList = m_Application->GetParametersKeys(true);
378                for (unsigned int i = 0; i < appKeyList.size(); i++){
379                  const std::string paramKey(appKeyList[i]);
380                  std::vector<std::string> values;
381                  Parameter::Pointer param = m_Application->GetParameterByKey(paramKey);
382                  ParameterType type = m_Application->GetParameterType(paramKey);
383                  if (type != ParameterType_Group && paramKey!="inxml" && paramKey!="outxml"
384                      && (type == ParameterType_OutputImage || type == ParameterType_OutputFilename
385                          || type == ParameterType_OutputVectorData ) ){
386                    if(type == ParameterType_OutputImage || type == ParameterType_OutputFilename || type == ParameterType_OutputVectorData){
387                      map* test=getMapFromMaps(outputs,paramKey.c_str(),"mimeType");
388                      if(test!=NULL && strncasecmp(test->value,"application/zip",15)==0){
389                       
390                        test=getMapFromMaps(inputs,paramKey.c_str(),"generated_file");
391                        char tmpName[1024];
392                        sprintf(tmpName,"/vsizip/%s",ReplaceAll(test->value,".shp",".zip").c_str());
393                        VSILFILE* fmain=VSIFOpenL(tmpName, "w");
394                        FILE * file;
395                        char *tmp;
396                        char tmpSName[1024];
397                        long count;
398                       
399                        char *exts[4];
400                        exts[0]=".shp";
401                        exts[1]=".shx";
402                        exts[2]=".dbf";
403                        exts[3]=".prj";
404                        for(int c=0;c<4;c++){
405                          sprintf(tmpSName,"%s/result%s",tmpName,exts[c]);
406                         
407                          file=fopen(ReplaceAll(test->value,".shp",exts[c]).c_str(),"rb");
408                          if(file!=NULL){
409                            fseek(file, 0, SEEK_END);
410                            count = ftell(file);
411                            rewind(file);
412                           
413                            tmp=(char*) malloc((count+1)*sizeof(char)); 
414                            fread(tmp,1,count*sizeof(char),file);
415                           
416                            VSILFILE* fx=VSIFOpenL(tmpSName, "wb");
417                            VSIFWriteL(tmp,1,count,fx);
418                            VSIFCloseL(fx);
419                            fclose(file);
420                            free(tmp);
421                          }
422                        }
423                       
424                        VSIFCloseL(fmain);
425                       
426                        FILE* file1=fopen(ReplaceAll(test->value,".shp",".zip").c_str(), "rb");
427                        fseek(file1, 0, SEEK_END);
428                        count=ftell(file1);
429                        rewind(file1);
430                       
431                        tmp=(char*) malloc((count+1)*sizeof(char)); 
432                        fread(tmp,1,count*sizeof(char),file1);
433                       
434                        file=fopen(ReplaceAll(test->value,".shp",".zip").c_str(),"wb");
435                        fwrite(tmp,1,count,file);
436                        fclose(file);
437                        free(tmp);
438                        fclose(file1);
439                        setMapInMaps(inputs,paramKey.c_str(),"generated_file",ReplaceAll(test->value,".shp",".zip").c_str());
440                      }
441                      test=getMapFromMaps(inputs,paramKey.c_str(),"generated_file");
442
443                      if(test!=NULL){
444                        setMapInMaps(outputs,paramKey.c_str(),"generated_file",test->value);
445                      }
446
447                    }
448                  }
449                }
450              }
451              res=3;
452              break;
453            }
454            else{
455              sprintf(tmpS, "The OTB Application %s cannot be run.", s->name);
456              setMapInMaps(m,"lenv","message",tmpS);
457              res=SERVICE_FAILED;
458            }
459          }
460          catch(std::exception& err){
461            setMapInMaps(m,"lenv","message",err.what());
462            return SERVICE_FAILED;
463           
464          }
465          catch(...){
466            setMapInMaps(m,"lenv","message","An unknown exception has been raised during application execution");
467            res=SERVICE_FAILED;
468          }
469          break;
470        }
471      }
472    }
473  }
474
475  for (unsigned int i = 0; i < m_WatcherList.size(); i++){
476    m_WatcherList[i]->FreeConf();
477    delete m_WatcherList[i];
478    m_WatcherList[i] = NULL;
479  }
480  m_WatcherList.clear();
481
482  return res;
483}
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