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

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

First version including zoo_service shared library

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