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

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

Add kmz output support, small fix in readGeneratedFile.

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