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

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

Add OTB Application Observer.

  • Property svn:keywords set to Id
File size: 13.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
31using namespace otb::Wrapper;
32
33class MyCommand : public itk::Command
34{
35 public:
36  itkNewMacro( MyCommand );
37 public:
38
39  void Execute(itk::Object *caller, const itk::EventObject & event)
40  {
41    Execute( (const itk::Object *)caller, event);
42  }
43 
44  void Execute(const itk::Object * object, const itk::EventObject & event)
45  {
46    const AddProcessToWatchEvent* eventToWatch = dynamic_cast< const AddProcessToWatchEvent*> ( &event );
47    std::string m_CurrentDescription = eventToWatch->GetProcessDescription();
48    std::cerr << "err_service_zooo start ccalled." << m_CurrentDescription << std::endl;
49    ZooWatcher * watch = new ZooWatcher(eventToWatch->GetProcess(),
50                                        eventToWatch->GetProcessDescription());
51    watch->SetConf(&m_Conf);
52    m_WatcherList.push_back(watch);
53  }
54
55
56
57};
58
59
60std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
61    size_t start_pos = 0;
62    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
63        str.replace(start_pos, from.length(), to);
64        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
65    }
66    return str;
67}
68
69int zoo_otb_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){
70  maps* m=*main_conf;
71  maps* inputs=*real_inputs;
72  maps* outputs=*real_outputs;
73  map* tmp0=getMapFromMaps(*main_conf,"lenv","cwd");
74  char *ntmp=tmp0->value;
75  map* tmp=NULL;
76  int res=-1;
77
78  std::vector<std::string> list = ApplicationRegistry::GetAvailableApplications();
79  if (list.size() == 0){
80    map* tmps=createMap("text","No OTB Application found.");
81    addToMap(tmps,"code","InternalError");
82    printExceptionReportResponse(m,tmps);
83    freeMap(&tmps);
84    free(tmps);
85    res=-1;
86  }
87  else{
88    for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it){
89      if(s->name==*it){
90        Application::Pointer m_Application=ApplicationRegistry::CreateApplication(*it);
91        if (m_Application.IsNull()){
92          char tmpS[1024];
93          sprintf(tmpS, "The OTB Application %s cannot be loaded.", (*it).c_str());
94          map* tmps=createMap("text",tmpS);
95          addToMap(tmps,"code","InternalError");
96          printExceptionReportResponse(m,tmps);
97          freeMap(&tmps);
98          free(tmps);
99          res=-1;
100        }else{
101          // Create Observer on AddProcessToWatchEvent
102          m_Conf=m;
103          MyCommand::Pointer myCommand = MyCommand::New();
104          m_Application->AddObserver(AddProcessToWatchEvent(), myCommand);
105          char tmpS[1024];
106          const std::vector<std::string> appKeyList = m_Application->GetParametersKeys(true);
107          for (unsigned int i = 0; i < appKeyList.size(); i++){
108            const std::string paramKey(appKeyList[i]);
109            std::vector<std::string> values;
110            Parameter::Pointer param = m_Application->GetParameterByKey(paramKey);
111            ParameterType type = m_Application->GetParameterType(paramKey);
112            if (type != ParameterType_Group && paramKey!="inxml" && paramKey!="outxml"){
113              map* test=getMapFromMaps(inputs,paramKey.c_str(),"cache_file");
114              if(test==NULL){
115                test=getMapFromMaps(inputs,paramKey.c_str(),"inRequest");
116                map* tmpPath=getMapFromMaps(m,"main","tmpPath");
117                map* tmpSid=getMapFromMaps(m,"lenv","usid");
118                char tmp[1024];
119                map* tmpVal=getMapFromMaps(outputs,paramKey.c_str(),"mimeType");
120                if(test!=NULL && test->value!=NULL && strncasecmp(test->value,"true",4)==0){
121                  test=getMapFromMaps(inputs,paramKey.c_str(),"value");
122                  if(type == ParameterType_OutputImage){
123                    ImagePixelType outPixType = ImagePixelType_float;
124                    if (strncasecmp(test->value,"uint8",5)==0)
125                      outPixType = ImagePixelType_uint8;
126                    else if (strncasecmp(test->value,"int16",5)==0)
127                      outPixType = ImagePixelType_int16;
128                    else if (strncasecmp(test->value,"uint16",6)==0)
129                      outPixType = ImagePixelType_uint16;
130                    else if (strncasecmp(test->value,"int32",5)==0)
131                      outPixType = ImagePixelType_int32;
132                    else if (strncasecmp(test->value,"uint32",6)==0)
133                      outPixType = ImagePixelType_uint32;
134                    else if (strncasecmp(test->value,"double",6)==0)
135                      outPixType = ImagePixelType_double;
136                    char* ext="tiff";
137                    if(tmpVal!=NULL){
138                      if(strncasecmp(tmpVal->value,"image/jp2",9)==0)
139                         ext="j2k";
140                      else
141                        if(strncasecmp(tmpVal->value,"image/png",9)==0)
142                         ext="png";
143                        else
144                          if(strncasecmp(tmpVal->value,"image/jpeg",10)==0)
145                            ext="jpeg";
146                    }
147                    sprintf(tmp,"%s/%s_%s.%s",tmpPath->value,s->name,tmpSid->value,ext);
148                    m_Application->SetParameterString(paramKey, tmp);
149                    setMapInMaps(inputs,paramKey.c_str(),"generated_file",tmp);
150                    dynamic_cast<OutputImageParameter *> (param.GetPointer())->SetPixelType(outPixType);
151                  }else{
152                    if(test->value!=NULL)
153                      m_Application->SetParameterString(paramKey, test->value);
154                  }
155
156                }else{
157                  if(type == ParameterType_OutputVectorData){
158                      char* ext="json";
159                      if(tmpVal!=NULL){
160                        if(strncasecmp(tmpVal->value,"text/xml",8)==0)
161                        ext="gml";
162                      else
163                        if(strncasecmp(tmpVal->value,"applicaton/json",15)==0)
164                          ext="json";
165                        else
166                          if(strncasecmp(tmpVal->value,"application/zip",14)==0)
167                            ext="shp";
168                          else
169                            if(strncasecmp(tmpVal->value,"application/vnd.google-earth.kml+xml",36)==0)
170                              ext="kml";
171                      }
172                      sprintf(tmp,"%s/%s_%s.%s",tmpPath->value,s->name,tmpSid->value,ext);
173                      m_Application->SetParameterString(paramKey, tmp);
174                      setMapInMaps(inputs,paramKey.c_str(),"generated_file",tmp);
175                  }
176                  else
177                    if(type == ParameterType_OutputFilename){
178                      char* ext="txt";
179                      if(tmpVal!=NULL){
180                        if(strncasecmp(tmpVal->value,"text/xml",8)==0)
181                          ext="xml";
182                        else
183                          if(strncasecmp(tmpVal->value,"text/csv",15)==0)
184                            ext="csv";
185                          else
186                            if(strncasecmp(tmpVal->value,"application/zip",14)==0)
187                              ext="shp";
188                            else
189                            if(strncasecmp(tmpVal->value,"application/vnd.google-earth.kml+xml",36)==0)
190                              ext="kml";
191                      }
192                      sprintf(tmp,"%s/%s_%s.%s",tmpPath->value,s->name,tmpSid->value,ext);
193                      m_Application->SetParameterString(paramKey, tmp);
194                      setMapInMaps(inputs,paramKey.c_str(),"generated_file",tmp);
195                    }
196
197                }
198              }else{
199                if(type == ParameterType_InputImageList){
200                  values.push_back(test->value);
201                  map* tmpPath=getMapFromMaps(inputs,paramKey.c_str(),"length");
202                  if(tmpPath!=NULL){
203                    int len=atoi(tmpPath->value);
204                    for(int k=1;k<len;k++){
205                      char tmp[15];
206                      sprintf(tmp,"cache_file_%d",k);
207                      map* tmpVal=getMapFromMaps(inputs,paramKey.c_str(),tmp);
208                      if(tmpVal!=NULL){
209                        values.push_back(tmpVal->value);
210                      }
211                    }
212                  }
213                  dynamic_cast<InputImageListParameter *> (param.GetPointer())->SetListFromFileName(values);
214                }
215                else
216                  if(type == ParameterType_InputVectorData || type == ParameterType_InputFilename){
217                    map* tmpPath=getMapFromMaps(m,"main","tmpPath");
218                    map* tmpSid=getMapFromMaps(m,"lenv","sid");
219                    char tmp[1024];
220                    map* tmpVal=getMapFromMaps(inputs,paramKey.c_str(),"mimeType");
221                    char* ext="json";
222                    if(tmpVal!=NULL){
223                      if(strncasecmp(tmpVal->value,"application/zip",14)==0){
224                        char tmpName[1024];
225                        symlink(test->value,ReplaceAll(test->value,".zca",".zip").c_str());
226                        sprintf(tmpName,"/vsizip/%s",ReplaceAll(test->value,".zca",".zip").c_str());
227                        char **files=VSIReadDir(tmpName);
228                        int nFiles = CSLCount( files );
229                        char tmpSSName[1024];
230                        sprintf(tmpSSName,"%s/Input_%s_%s",tmpPath->value,s->name,tmpSid->value);
231                        mkdir(tmpSSName,0777);
232                           
233                        char tmpSName[1024];
234                        for(int kk=0;kk<nFiles;kk++){
235                          sprintf(tmpSName,"%s/%s",tmpName,files[kk]);
236                          VSILFILE* fmain=VSIFOpenL(tmpSName, "rb");
237                          if(fmain!=NULL){
238                            VSIFSeekL(fmain,0,SEEK_END);
239                            long count=VSIFTellL(fmain);
240                            VSIRewindL(fmain);
241
242                            char *content=(char*) malloc((count+1)*sizeof(char)); 
243                            VSIFReadL(content,1,count*sizeof(char),fmain);
244                         
245                            char tmpSSSName[1024];
246                            sprintf(tmpSSSName,"%s/%s",tmpSSName,files[kk]);
247                           
248                            FILE* fx=fopen(tmpSSSName, "wb");
249                            fwrite(content,1,count,fx);
250                            fclose(fx);
251                            VSIFCloseL(fmain);
252                            free(content);
253                            std::string test1(tmpSSSName);
254                            if(test1.find(".shp")!=std::string::npos){
255                              setMapInMaps(inputs,paramKey.c_str(),"cache_file",tmpSSSName);
256                              test=getMapFromMaps(inputs,paramKey.c_str(),"cache_file");
257                            }
258                          }
259                        }
260                      }
261                    }
262                   
263                    m_Application->SetParameterString(paramKey, test->value);
264                  }
265                  else
266                    if(type == ParameterType_InputImage
267                       || type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData
268                       || type == ParameterType_InputFilename){
269                      m_Application->SetParameterString(paramKey, test->value);
270                  }               
271              }
272            }
273            param->SetUserValue(true);
274            m_Application->UpdateParameters();
275          }
276
277          try{
278            if( m_Application->ExecuteAndWriteOutput() == 0 ){
279              std::vector< std::pair<std::string, std::string> > paramList;
280              paramList = m_Application->GetOutputParametersSumUp();
281              if(paramList.size()>0)
282                for( unsigned int i=0; i<paramList.size(); i++){
283                  setMapInMaps(outputs,paramList[i].first.c_str(),"value",paramList[i].second.c_str());
284                }
285              else{
286                const std::vector<std::string> appKeyList = m_Application->GetParametersKeys(true);
287                for (unsigned int i = 0; i < appKeyList.size(); i++){
288                  const std::string paramKey(appKeyList[i]);
289                  std::vector<std::string> values;
290                  Parameter::Pointer param = m_Application->GetParameterByKey(paramKey);
291                  ParameterType type = m_Application->GetParameterType(paramKey);
292                  if (type != ParameterType_Group && paramKey!="inxml" && paramKey!="outxml"
293                      && (type == ParameterType_OutputImage || type == ParameterType_OutputFilename
294                          || type == ParameterType_OutputVectorData ) ){
295                    if(type == ParameterType_OutputImage || type == ParameterType_OutputFilename || type == ParameterType_OutputVectorData){
296                      map* test=getMapFromMaps(outputs,paramKey.c_str(),"mimeType");
297                      if(test!=NULL && strncasecmp(test->value,"application/zip",15)==0){
298                       
299                        test=getMapFromMaps(inputs,paramKey.c_str(),"generated_file");
300                        char tmpName[1024];
301                        sprintf(tmpName,"/vsizip/%s",ReplaceAll(test->value,".shp",".zip").c_str());
302                        VSILFILE* fmain=VSIFOpenL(tmpName, "w");
303                        FILE * file;
304                        char *tmp;
305                        char tmpSName[1024];
306                        long count;
307                       
308                        char *exts[4];
309                        exts[0]=".shp";
310                        exts[1]=".shx";
311                        exts[2]=".dbf";
312                        exts[3]=".prj";
313                        for(int c=0;c<4;c++){
314                          sprintf(tmpSName,"%s/result%s",tmpName,exts[c]);
315                         
316                          file=fopen(ReplaceAll(test->value,".shp",exts[c]).c_str(),"rb");
317                          if(file!=NULL){
318                            fseek(file, 0, SEEK_END);
319                            count = ftell(file);
320                            rewind(file);
321                           
322                            tmp=(char*) malloc((count+1)*sizeof(char)); 
323                            fread(tmp,1,count*sizeof(char),file);
324                           
325                            VSILFILE* fx=VSIFOpenL(tmpSName, "wb");
326                            VSIFWriteL(tmp,1,count,fx);
327                            VSIFCloseL(fx);
328                            fclose(file);
329                            free(tmp);
330                          }
331                        }
332                       
333                        VSIFCloseL(fmain);
334                       
335                        FILE* file1=fopen(ReplaceAll(test->value,".shp",".zip").c_str(), "rb");
336                        fseek(file1, 0, SEEK_END);
337                        count=ftell(file1);
338                        rewind(file1);
339                       
340                        tmp=(char*) malloc((count+1)*sizeof(char)); 
341                        fread(tmp,1,count*sizeof(char),file1);
342                       
343                        file=fopen(ReplaceAll(test->value,".shp",".zip").c_str(),"wb");
344                        fwrite(tmp,1,count,file);
345                        fclose(file);
346                        free(tmp);
347                        fclose(file1);
348                        setMapInMaps(inputs,paramKey.c_str(),"generated_file",ReplaceAll(test->value,".shp",".zip").c_str());
349                      }
350                      test=getMapFromMaps(inputs,paramKey.c_str(),"generated_file");
351
352                      if(test!=NULL){
353                        setMapInMaps(outputs,paramKey.c_str(),"generated_file",test->value);
354                      }
355
356                    }
357                  }
358                }
359              }
360              res=3;
361              break;
362            }
363            else{
364              sprintf(tmpS, "The OTB Application %s cannot be run.", s->name);
365              setMapInMaps(m,"lenv","message",tmpS);
366              res=SERVICE_FAILED;
367            }
368          }
369          catch(std::exception& err){
370            setMapInMaps(m,"lenv","message",err.what());
371            return SERVICE_FAILED;
372           
373          }
374          catch(...){
375            setMapInMaps(m,"lenv","message","An unknown exception has been raised during application execution");
376            res=SERVICE_FAILED;
377          }
378          break;
379        }
380      }
381    }
382  }
383
384  for (unsigned int i = 0; i < m_WatcherList.size(); i++){
385    m_WatcherList[i]->FreeConf();
386    delete m_WatcherList[i];
387    m_WatcherList[i] = NULL;
388  }
389  m_WatcherList.clear();
390
391  return res;
392}
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