REConnectionHadoop.java
Go to the documentation of this file.
00001 /* \file REConnectionHadoop.java
00002  * \brief Connection to Hadoop based RoboEarthDB
00003  *
00004  * The connection class for a Hadoop based RoboEarthDB installation.
00005  * 
00006  * This file is part of the RoboEarth ROS re_comm_core package.
00007  * 
00008  * It was originally created for <a href="http://www.roboearth.org/">RoboEarth</a>.
00009  * The research leading to these results has received funding from the 
00010  * European Union Seventh Framework Programme FP7/2007-2013 
00011  * under grant agreement no248942 RoboEarth.
00012  *
00013  * Copyright (C) 2010 by 
00014  * <a href=" mailto:perzylo@cs.tum.edu">Alexander Perzylo</a>
00015  * Technische Universitaet Muenchen
00016  * 
00017  * Redistribution and use in source and binary forms, with or without
00018  * modification, are permitted provided that the following conditions are met:
00019  * 
00020  *    <UL>
00021  *     <LI> Redistributions of source code must retain the above copyright
00022  *       notice, this list of conditions and the following disclaimer.
00023  *     <LI> Redistributions in binary form must reproduce the above copyright
00024  *       notice, this list of conditions and the following disclaimer in the
00025  *       documentation and/or other materials provided with the distribution.
00026  *     <LI> Neither the name of Willow Garage, Inc. nor the names of its
00027  *       contributors may be used to endorse or promote products derived from
00028  *       this software without specific prior written permission.
00029  *    </UL>
00030  * 
00031  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00032  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00033  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00034  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
00035  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
00036  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
00037  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00038  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
00039  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
00040  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
00041  * POSSIBILITY OF SUCH DAMAGE.
00042  *
00043  * \author Alexander Perzylo
00044  * \version 1.0
00045  * \date 2010
00046  * \image html http://www.roboearth.org/sites/default/files/RoboEarth.org_logo.gif
00047  * \image latex http://www.roboearth.org/sites/default/files/RoboEarth.org_logo.gif
00048  */
00049 package roboearth.wp5.conn;
00050 
00051 import static argo.jdom.JsonNodeFactories.aJsonField;
00052 import static argo.jdom.JsonNodeFactories.aJsonObject;
00053 import static argo.jdom.JsonNodeFactories.aJsonString;
00054 
00055 import java.io.ByteArrayInputStream;
00056 import java.io.ByteArrayOutputStream;
00057 import java.io.File;
00058 import java.io.FileInputStream;
00059 import java.io.FileOutputStream;
00060 import java.io.IOException;
00061 import java.io.InputStream;
00062 import java.io.UnsupportedEncodingException;
00063 import java.net.MalformedURLException;
00064 import java.net.URL;
00065 import java.net.URLConnection;
00066 import java.util.AbstractList;
00067 import java.util.ArrayList;
00068 import java.util.Iterator;
00069 import java.util.List;
00070 import java.util.Map;
00071 import java.util.Set;
00072 import java.util.StringTokenizer;
00073 
00074 import org.apache.http.Header;
00075 import org.apache.http.HttpEntity;
00076 import org.apache.http.HttpResponse;
00077 import org.apache.http.StatusLine;
00078 import org.apache.http.client.HttpClient;
00079 import org.apache.http.client.methods.HttpDelete;
00080 import org.apache.http.client.methods.HttpGet;
00081 import org.apache.http.client.methods.HttpPost;
00082 import org.apache.http.client.methods.HttpPut;
00083 import org.apache.http.entity.StringEntity;
00084 import org.apache.http.entity.mime.MultipartEntity;
00085 import org.apache.http.entity.mime.content.InputStreamBody;
00086 import org.apache.http.entity.mime.content.StringBody;
00087 import org.apache.http.impl.client.DefaultHttpClient;
00088 import org.apache.http.message.BasicHeader;
00089 import org.apache.http.params.HttpConnectionParams;
00090 import org.apache.http.params.HttpParams;
00091 import org.apache.http.util.EntityUtils;
00092 import org.semanticweb.owlapi.model.OWLOntology;
00093 
00094 import roboearth.wp5.owl.Inference;
00095 import roboearth.wp5.owl.OWLIO;
00096 import argo.format.JsonFormatter;
00097 import argo.format.PrettyJsonFormatter;
00098 import argo.jdom.JdomParser;
00099 import argo.jdom.JsonNode;
00100 import argo.jdom.JsonNodeSelector;
00101 import argo.jdom.JsonNodeSelectors;
00102 import argo.jdom.JsonRootNode;
00103 import argo.jdom.JsonStringNode;
00104 import argo.saj.InvalidSyntaxException;
00105 
00116 public class REConnectionHadoop implements REInterface {
00117 
00121         public final static String roboEarthBaseURL = "http://api.roboearth.org";
00122 
00126         private final String apiKey;
00127 
00131         public final static String requestObjectSuffix = "/api/object/";
00132 
00136         public final static String requestActionRecipeSuffix = "/api/recipe/";
00137 
00141         public final static String requestEnvironmentSuffix = "/api/environment/";
00142 
00146         public final static String requestRobotSuffix = "/api/robot/";  
00147         
00151         public final static String requestObjectBinariesSuffix = "/data/objects/";
00152 
00156         public final static String requestEnvironmentBinariesSuffix = "/data/environments/";
00157         
00161         public final static String submitObjectSuffix = "/api/object";
00162 
00166         public final static String submitActionRecipeSuffix = "/api/recipe";
00167 
00171         public final static String submitEnvironmentSuffix = "/api/environment";
00172 
00176         public final static String submitObjectBinariesSuffix = "/api/binary/objects/";
00177         
00181         public final static String submitEnvironmentBinariesSuffix = "/api/binary/environments/";
00182         
00186         public final static String querySuffix = "/api/serql";
00187 
00191         public final static String mapExtractorSuffix = "/api/service/3dto2dmap";
00192         
00196         private final static JdomParser json_parser = new JdomParser();
00197 
00201         private final static JsonFormatter JSON_FORMATTER = new PrettyJsonFormatter();
00202 
00206         public final static int timoutInMs = 60000;
00207         
00208         @Deprecated
00209         private final static String fileIdObjImage = "image";
00210         @Deprecated
00211         private final static String fileIdObjModel = "model";
00212         @Deprecated
00213         private final static String fileIdObjArticModel = "articulationModel";
00214 
00215 
00226         public REConnectionHadoop(String apiKey) {
00227 
00228                 this.apiKey = apiKey;
00229 
00230         }
00231 
00232         
00233         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
00234         // 
00235         // Download action recipes from the DB
00236         //
00237         
00238         @Override
00239         public String requestActionRecipe(String uid) {
00240                 if (uid != null) {
00241                         return requestActionRecipeFromURL(roboEarthBaseURL+requestActionRecipeSuffix+uid);
00242                 } else {
00243                         System.out.println("\ndownload recipe '"+uid+"': parameter error (null pointer)");
00244                 }
00245                 return null;
00246         }
00247 
00254         public String requestActionRecipeFromURL(String url) {
00255 
00256                 String responseBody = "";
00257                 if (url != null) {
00258 
00259                         responseBody = requestData(url);
00260                         if (responseBody!= null && (responseBody.startsWith("[") || responseBody.startsWith("{"))) {
00261 
00262                                 try {
00263                                         // Create a list of returned recipes and their time stamps, ...
00264                                         RecipeList recipes = new RecipeList(responseBody);
00265                                         responseBody = recipes.get(0);
00266 
00267                                 } catch (InvalidSyntaxException e) {
00268                                         e.printStackTrace();
00269                                 }
00270 
00271                         }
00272 
00273                 } else {
00274                         System.out.println("parameter error (null pointer)");
00275                 }
00276                 return responseBody;
00277         }
00278 
00279         
00280         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
00281         // 
00282         // Download environment maps from the DB
00283         //
00284         
00285 
00286         public String requestEnvironment(String uid) {
00287                 return requestEnvironment(uid, null, null);
00288         }
00289 
00304         public String requestEnvironment(String uid, ArrayList<String> outFilenames, ArrayList<String> outFileURLs) {
00305                 if (uid != null) {
00306                         return requestEnvironmentFromURL(roboEarthBaseURL+requestEnvironmentSuffix+uid, outFilenames, outFileURLs);
00307                 } else {
00308                         System.out.println("\ndownload environment '"+uid+"': parameter error (null pointer)");
00309                         return null;
00310                 }
00311         }
00312         
00319         public String requestEnvironmentFromURL(String url) {
00320                 return requestEnvironmentFromURL(url, null, null);
00321         }
00322         
00337         public String requestEnvironmentFromURL(String url, ArrayList<String> outFilenames, ArrayList<String> outFileURLs) {
00338 
00339                 String env = null;
00340                 if (url != null) {
00341 
00342                         String responseBody = requestData(url);
00343 
00344                         if (responseBody!=null && (responseBody.startsWith("[") || responseBody.startsWith("{"))) {
00345 
00346                                 try {
00347                                         // Create a list of returned environments and their time stamps, ...
00348                                         EnvironmentList envs = new EnvironmentList(responseBody);
00349                                         responseBody = envs.get(0);
00350 
00351                                         if (responseBody != null && !responseBody.isEmpty()) {
00352                                                 env = responseBody;     
00353 
00354                                                 if (outFilenames != null) {
00355                                                         outFilenames.clear();
00356                                                         String[] names = envs.getFilenames(0);
00357                                                         if (names != null) {
00358                                                                 for (String name : names) {
00359                                                                         outFilenames.add(name);
00360                                                                 }                                                               
00361                                                         }                               
00362                                                 }
00363 
00364                                                 if (outFileURLs  != null) {
00365                                                         outFileURLs.clear();
00366                                                         String[] ourls = envs.getFileURLs(0);
00367                                                         if (ourls != null) {
00368                                                                 for (String ourl : ourls) {
00369                                                                         outFileURLs.add(ourl);
00370                                                                 }                                                               
00371                                                         }                               
00372 
00373                                                 }
00374                                         }
00375 
00376                                 } catch (InvalidSyntaxException e) {
00377                                         e.printStackTrace();
00378                                 }
00379 
00380                         }
00381 
00382                 } else {
00383                         System.out.println("parameter error (null pointer)");
00384                 }
00385                 return env;
00386         }
00387 
00388         
00389         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
00390         // 
00391         // Download robot descriptions from the DB
00392         //
00393         
00394         
00395         @Override
00396         public String requestRobot(String uid) {
00397                 if (uid != null) {
00398                         return requestRobotFromURL(roboEarthBaseURL+requestRobotSuffix+uid);
00399                 } else {
00400                         System.out.println("\ndownload robot '"+uid+"': parameter error (null pointer)");
00401                 }
00402                 return null;
00403         }
00404 
00411         public String requestRobotFromURL(String url) {
00412 
00413                 String responseBody = "";
00414                 if (url != null) {
00415 
00416                         responseBody = requestData(url);
00417                         if (responseBody!= null && (responseBody.startsWith("[") || responseBody.startsWith("{"))) {
00418 
00419                                 try {
00420                                         // Create a list of returned robots and their time stamps, ...
00421                                         RobotList robots = new RobotList(responseBody);
00422                                         responseBody = robots.get(0);
00423 
00424                                 } catch (InvalidSyntaxException e) {
00425                                         e.printStackTrace();
00426                                 }
00427 
00428                         }
00429 
00430                 } else {
00431                         System.out.println("parameter error (null pointer)");
00432                 }
00433                 return responseBody;
00434         }
00435         
00436         
00437         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
00438         // 
00439         // Download object models from the DB
00440         //
00441         
00448         public String requestObject(String uid) {
00449                 return requestObject(uid, null, null);
00450         }
00451         
00452         @Override
00453         public String requestObject(String uid, ArrayList<String> outFilenames, ArrayList<String> outFileURLs) {
00454                 if (uid != null) {
00455                         return requestObjectFromURL(roboEarthBaseURL+requestObjectSuffix+uid, outFilenames, outFileURLs);
00456                 } else {
00457                         System.out.println("\ndownload object '"+uid+"': parameter error (null pointer)");
00458                         return null;    
00459                 }
00460                 
00461         }
00462 
00469         public String requestObjectFromURL(String url) {
00470                 return requestObjectFromURL(url, null, null);
00471         }
00472         
00487         public String requestObjectFromURL(String url, ArrayList<String> outFilenames, ArrayList<String> outFileURLs) {
00488 
00489                 String obj = null;
00490 
00491                 if (url != null) {
00492 
00493                         String responseBody = requestData(url);
00494                         if (responseBody!=null && (responseBody.startsWith("[") || responseBody.startsWith("{"))) {
00495 
00496                                 try {
00497                                         // Create a list of returned object models and their time stamps, ...
00498                                         ObjectList objects = new ObjectList(responseBody);
00499                                         responseBody = objects.get(0);
00500 
00501                                         if (responseBody != null && !responseBody.isEmpty()) {
00502                                                 obj = responseBody;
00503                                                 
00504                                                 if (outFilenames != null) {
00505                                                         outFilenames.clear();
00506                                                         String[] names = objects.getFilenames(0);
00507                                                         if (names != null) {
00508                                                                 for (String name : names) {
00509                                                                         outFilenames.add(name);
00510                                                                 }                                                               
00511                                                         }                               
00512                                                 }
00513 
00514                                                 if (outFileURLs  != null) {
00515                                                         outFileURLs.clear();
00516                                                         String[] ourls = objects.getFileURLs(0);
00517                                                         if (ourls != null) {
00518                                                                 for (String ourl : ourls) {
00519                                                                         outFileURLs.add(ourl);
00520                                                                 }                                                               
00521                                                         }                               
00522                                                 }                                                       
00523 
00524                                         }
00525 
00526                                 } catch (InvalidSyntaxException e) {
00527                                         e.printStackTrace();
00528                                 }
00529 
00530                         }
00531 
00532                 } else {
00533                         System.out.println("parameter error (null pointer)");
00534                 }
00535                 return obj;
00536 
00537         }
00538 
00539         
00540         
00541         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
00542         // 
00543         // Download binary files
00544         //
00545         
00552         public byte[] requestBinaryFile(URL fileURL) {
00553 
00554                 byte[] requestedFile = null;
00555 
00556                 if (fileURL != null) {
00557 
00558                         InputStream is = null;
00559                         
00560                         try {
00561 
00562                                 URLConnection urlCon = fileURL.openConnection();
00563                                 urlCon.setDoInput(true);
00564                                 urlCon.setConnectTimeout(timoutInMs);
00565                                 urlCon.setReadTimeout(timoutInMs);
00566                                 urlCon.connect();
00567                                 is = urlCon.getInputStream();
00568                                 
00569                                 ByteArrayOutputStream bos = new ByteArrayOutputStream(10240);   
00570                                 byte[] data = new byte[4096];                           
00571                                 int i = 0;
00572                                 while ((i = is.read(data)) != -1) {
00573                                         bos.write(data, 0, i);
00574                                 }
00575                                 is.close();
00576 
00577                                 requestedFile = bos.toByteArray();
00578 
00579                         } catch (Exception e) {
00580                                 System.out.print("rejected, ");
00581                                 System.out.println(e.getLocalizedMessage());
00582                                 
00583                                 if (is != null) {
00584                                         try {
00585                                                 is.close();
00586                                         } catch (IOException ioe) {}
00587                                 }
00588                         }
00589 
00590                 } else {
00591                         System.out.println("parameter error (null pointer)");
00592                 }
00593                 return requestedFile;
00594                 
00595         }
00596         
00604         public File requestBinaryFile(URL fileURL, String targetPath) {
00605 
00606                 File requestedFile = null;
00607 
00608                 if (fileURL != null && targetPath != null) {
00609 
00610                         InputStream is = null;
00611                         FileOutputStream fos = null;
00612                         
00613                         try {
00614                                 
00615                                 URLConnection urlCon = fileURL.openConnection();
00616                                 urlCon.setDoInput(true);
00617                                 urlCon.setConnectTimeout(timoutInMs);
00618                                 urlCon.setReadTimeout(timoutInMs);
00619                                 urlCon.connect();
00620                                 is = urlCon.getInputStream();
00621                                 
00622                                 if (!targetPath.endsWith(File.separator)) {
00623                                         targetPath += File.separator;
00624                                 }
00625                                 
00626                                 String url = fileURL.toString();
00627                                 url = url.substring(url.lastIndexOf("/")+1, url.length());
00628                                 
00629                                 File fileToWrite = new File(targetPath + url);
00630                                 if (fileToWrite.exists()) {
00631                                         fileToWrite.delete();
00632                                 }
00633                                 fileToWrite.createNewFile();
00634                                 fos = new FileOutputStream(fileToWrite);        
00635                                 
00636                                 byte[] data = new byte[4096];
00637                                 int i = 0;
00638                                 while ((i = is.read(data)) != -1) {
00639                                         fos.write(data, 0, i);
00640                                 }
00641                                 fos.close();
00642                                 is.close();
00643                                 
00644                                 requestedFile = fileToWrite;
00645                                 
00646                         } catch (Exception e) {
00647                                 System.out.print("rejected, ");
00648                                 System.out.println(e.getLocalizedMessage());
00649                                 
00650                                 if (is != null) {
00651                                         try {
00652                                                 is.close();
00653                                         } catch (IOException ioe) {}
00654                                 }
00655                                 if (fos != null) {
00656                                         try {
00657                                                 fos.close();
00658                                         } catch (IOException ioe) {}
00659                                 }
00660                         }
00661 
00662                 } else {
00663                         System.out.println("parameter error (null pointer)");
00664                 }
00665 
00666                 return requestedFile;
00667 
00668         }
00669         
00670         @Override
00671         public byte[] requestObjectBinaryFile(String objectUID, String filename) {
00672 
00673                 byte[] requestedFile = null;
00674 
00675                 if (objectUID != null && filename != null) {
00676 
00677                         String fileURL = roboEarthBaseURL + requestObjectBinariesSuffix
00678                                         + objectUID.replace(".", "/") + "/" + filename;
00679                         
00680                         try {
00681                                 URL url = new URL(fileURL);
00682                                 requestedFile = requestBinaryFile(url);
00683                         } catch (MalformedURLException e) {
00684                                 System.out.print("\ndownload file '" + fileURL + "' "
00685                                                 + "(obj. uid '" + objectUID + "'): ");
00686                                 System.out.println(e.getLocalizedMessage());
00687                         }
00688 
00689                 } else {
00690                         System.out.println("\ndownload file '"+filename+"' "
00691                                         +"(obj. uid '" + objectUID + "'): parameter error (null pointer)");
00692                 }
00693                 return requestedFile;
00694 
00695         }
00696         
00697         @Override
00698         public File requestObjectBinaryFile(String objectUID, String filename, String targetPath) {
00699 
00700                 File file = null;
00701 
00702                 if (objectUID != null && filename != null && targetPath != null) {
00703                         
00704                         String fileURL = roboEarthBaseURL + requestObjectBinariesSuffix
00705                                         + objectUID.replace(".", "/") + "/" + filename;
00706 
00707                         try {
00708                                 URL url = new URL(fileURL);
00709                                 file = requestBinaryFile(url, targetPath);
00710                         } catch (MalformedURLException e) {
00711                                 System.out.print("\ndownload file '" + fileURL + "' "
00712                                                 + "(obj. uid '" + objectUID + "'): ");
00713                                 System.out.println(e.getLocalizedMessage());
00714                         }                       
00715                         
00716                 } else {
00717                         System.out.println("\ndownload file '"+filename+"' "
00718                                         + "(obj. uid '" + objectUID + "'): parameter error (null pointer)");
00719                 }
00720                 return file;
00721 
00722         }
00723         
00724         @Override
00725         public byte[] requestEnvironmentBinaryFile(String envUID, String filename) {
00726 
00727                 byte[] requestedFile = null;
00728 
00729                 if (envUID != null && filename != null) {
00730 
00731                         String fileURL = roboEarthBaseURL + requestEnvironmentBinariesSuffix
00732                                         + envUID.replace(".", "/") + "/" + filename;
00733                         
00734                         try {
00735                                 URL url = new URL(fileURL);
00736                                 requestedFile = requestBinaryFile(url);
00737                         } catch (MalformedURLException e) {
00738                                 System.out.print("\ndownload file '" + fileURL + "' "
00739                                                 + "(env. uid '" + envUID + "'): ");
00740                                 System.out.println(e.getLocalizedMessage());
00741                         }
00742 
00743                 } else {
00744                         System.out.println("\ndownload file '" + filename + "' "
00745                                         + "(env. uid '" + envUID + "'): parameter error (null pointer)");
00746                 }
00747                 return requestedFile;
00748 
00749         }
00750         
00751         @Override
00752         public File requestEnvironmentBinaryFile(String envUID, String filename, String targetPath) {
00753 
00754                 File file = null;
00755 
00756                 if (envUID != null && filename != null && targetPath != null) {
00757                         
00758                         String fileURL = roboEarthBaseURL + requestEnvironmentBinariesSuffix
00759                                         + envUID.replace(".", "/") + "/" + filename;
00760 
00761                         try {
00762                                 URL url = new URL(fileURL);
00763                                 file = requestBinaryFile(url, targetPath);
00764                         } catch (MalformedURLException e) {
00765                                 System.out.print("\ndownload file '" + fileURL + "' "
00766                                                 + "(env. uid '" + envUID + "'): ");
00767                                 System.out.println(e.getLocalizedMessage());
00768                         }                       
00769                         
00770                 } else {
00771                         System.out.println("\ndownload file '" + filename + "' "
00772                                         + "(env. uid '" + envUID + "'): parameter error (null pointer)");
00773                 }
00774                 return file;
00775 
00776         }
00777 
00778 
00785         protected static String requestData(String requestURL) {
00786 
00787                 String responseBody = null;
00788 
00789                 if (requestURL != null) {
00790 
00791                         HttpClient httpclient = null;
00792                         try {
00793 
00794                                 httpclient = new DefaultHttpClient();
00795                                 HttpParams params = httpclient.getParams();
00796                                 HttpConnectionParams.setConnectionTimeout(params, timoutInMs);
00797                                 HttpConnectionParams.setSoTimeout(params, timoutInMs);
00798                                 
00799                                 HttpGet httpget = new HttpGet(requestURL);
00800                                 HttpResponse response = httpclient.execute(httpget);
00801                                 if (isHTTPRequestProcessedCorrectly(response)) {
00802                                         HttpEntity entitity = response.getEntity();
00803                                         responseBody = EntityUtils.toString(entitity);          
00804                                 }
00805 
00806                         } catch (Exception e) {
00807                                 System.out.println(e.getLocalizedMessage());
00808                         } finally {
00809                                 if (httpclient != null) {
00810                                         httpclient.getConnectionManager().shutdown();
00811                                 }
00812                         }
00813 
00814                 }
00815 
00816                 return responseBody;
00817 
00818         }
00819 
00820         
00821         
00822         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
00823         // 
00824         // Upload information to the DB
00825         //
00826         
00827         
00828         @Override
00829         public boolean submitActionRecipe(OWLOntology actionRecipe, String cls, String id, String description) {
00830                 return submitActionRecipe(OWLIO.saveOntologyToString(actionRecipe), cls, id, description);
00831         }
00832         
00833         public boolean submitActionRecipe(String owlData, String cls, String id, String description) {
00834 
00835                 System.out.print("\nupload recipe '"+cls+"."+id+"': ");
00836                 
00837                 boolean ok = false;
00838 
00839                 if (apiKey != null && owlData != null && cls != null && 
00840                                 id != null && description != null) {
00841 
00842                         JsonRootNode json = aJsonObject(
00843                                         aJsonField("class", aJsonString(cls)),
00844                                         aJsonField("id", aJsonString(id)),
00845                                         aJsonField("description", aJsonString(description)),
00846                                         aJsonField("recipe", aJsonString(owlData)),
00847                                         aJsonField("api_key", aJsonString(apiKey))
00848                                         );
00849                         ok = submitData(JSON_FORMATTER.format(json), roboEarthBaseURL+submitActionRecipeSuffix);
00850 
00851                 } else {
00852                         System.out.println("parameter error (null pointer)");
00853                 }
00854 
00855                 return ok;
00856 
00857         }
00858 
00859         @Override
00860         public boolean submitEnvironment(OWLOntology map, String cls, String id, String description) {
00861                 return submitEnvironment(OWLIO.saveOntologyToString(map), cls, id, description);
00862         }
00863         
00864         public boolean submitEnvironment(String owlData, String cls, String id, String description) {
00865 
00866                 System.out.print("\nupload environment '"+cls+"."+id+"': ");
00867                 
00868                 boolean ok = false;
00869 
00870                 if (apiKey != null && owlData != null && cls != null && 
00871                                 id != null && description != null) {
00872 
00873                         JsonRootNode json = aJsonObject(
00874                                         aJsonField("class", aJsonString(cls)),
00875                                         aJsonField("id", aJsonString(id)),
00876                                         aJsonField("description", aJsonString(description)),
00877                                         aJsonField("environment", aJsonString(owlData)),
00878                                         aJsonField("api_key", aJsonString(apiKey))
00879                                         );
00880                         ok = submitData(JSON_FORMATTER.format(json), roboEarthBaseURL+submitEnvironmentSuffix);
00881 
00882                 } else {
00883                         System.out.println("parameter error (null pointer)");
00884                 }
00885 
00886                 return ok;
00887 
00888         }
00889 
00890         @Override
00891         public boolean submitEnvironment(OWLOntology map, String cls, String id, 
00892                         String description, ArrayList<File> binaryFiles) {
00893                 return submitEnvironment(OWLIO.saveOntologyToString(map), cls, id, description, binaryFiles);
00894         }
00895         
00896         
00897         public boolean submitEnvironment(String owlData, String cls, String id, 
00898                         String description, ArrayList<File> binaryFiles) {
00899                 
00900                 boolean ok = submitEnvironment(owlData, cls, id, description);
00901 
00902                 if (ok && binaryFiles != null) {
00903                         String uid = cls+"."+id;
00904                         for (File f : binaryFiles) {
00905                                 if (ok) {
00906                                         ok &= submitEnvironmentBinaryFile(uid, f);      
00907                                 }
00908                         }
00909                         if (!ok) {
00910                                 deleteEnvironment(uid);
00911                         }
00912                 }
00913 
00914                 return ok;
00915 
00916         }
00917 
00918         @Override
00919         public boolean submitEnvironment(OWLOntology map, String cls, String id, 
00920                         String description, ArrayList<byte[]> binaryData, 
00921                         ArrayList<String> filenames) {
00922                 return submitEnvironment(OWLIO.saveOntologyToString(map), cls, id, description,  binaryData, filenames);
00923         }
00924 
00925         public boolean submitEnvironment(String owlData, String cls, String id, 
00926                         String description, ArrayList<byte[]> binaryData, 
00927                         ArrayList<String> filenames) {
00928                 
00929                 boolean ok = submitEnvironment(owlData, cls, id, description);
00930 
00931                 if (ok && binaryData != null && filenames != null &&
00932                                 binaryData.size() == filenames.size()) {
00933                         String uid = cls+"."+id;
00934                         for (int i=0;i< binaryData.size() && ok; i++) {
00935                                 ok &= submitEnvironmentBinaryFile(uid, binaryData.get(i), filenames.get(i));
00936                         }
00937                         if (!ok) {
00938                                 deleteEnvironment(uid);
00939                         }
00940                 }
00941 
00942                 return ok;
00943 
00944         }
00945 
00946         @Override
00947         public boolean submitObject(OWLOntology object, String cls, String id, String description) {
00948                 return submitObject(OWLIO.saveOntologyToString(object), cls, id, description);
00949         }
00950         
00951         public boolean submitObject(String owlData, String cls, String id, String description) {
00952                 
00953                 System.out.print("\nupload object '"+cls+"."+id+"': ");
00954                 
00955                 boolean ok = false;
00956 
00957                 if (apiKey != null && owlData != null && cls != null && id != null && description != null) {
00958 
00959                         JsonRootNode json = aJsonObject(
00960                                         aJsonField("class", aJsonString(cls)),
00961                                         aJsonField("id", aJsonString(id)),
00962                                         aJsonField("description", aJsonString(description)),
00963                                         aJsonField("object_description", aJsonString(owlData)),
00964                                         aJsonField("api_key", aJsonString(apiKey))
00965                                         );
00966                         ok = submitData(JSON_FORMATTER.format(json), roboEarthBaseURL+submitObjectSuffix);
00967 
00968                 } else {
00969                         System.out.println("parameter error (null pointer)");
00970                 }
00971 
00972                 return ok;
00973 
00974         }
00975 
00976         @Override
00977         public boolean submitObject(OWLOntology object, String cls, String id, 
00978                         String description, ArrayList<File> binaryFiles) {
00979                 return submitObject(OWLIO.saveOntologyToString(object), cls, id, description, binaryFiles);
00980         }
00981 
00982         public boolean submitObject(String owlData, String cls, String id, 
00983                         String description, ArrayList<File> binaryFiles) {
00984 
00985                 boolean ok = submitObject(owlData, cls, id, description);
00986 
00987                 if (ok && binaryFiles != null) {
00988                         String uid = cls+"."+id;
00989                         for (File f : binaryFiles) {
00990                                 if (ok) {
00991                                         ok &= submitObjectBinaryFile(uid, f);   
00992                                 }
00993                         }
00994                         if (!ok) {
00995                                 deleteObject(uid);
00996                         }
00997                 }
00998 
00999                 return ok;
01000 
01001         }
01002 
01003         @Override
01004         public boolean submitObject(OWLOntology object, String cls, String id, 
01005                         String description, ArrayList<byte[]> binaryData, 
01006                         ArrayList<String> filenames) {
01007                 return submitObject(OWLIO.saveOntologyToString(object), cls, id, description, binaryData, filenames);
01008         }
01009         
01010         public boolean submitObject(String owlData, String cls, String id, 
01011                         String description, ArrayList<byte[]> binaryData, 
01012                         ArrayList<String> filenames) {
01013 
01014                 boolean ok = submitObject(owlData, cls, id, description);
01015 
01016                 if (ok && binaryData != null && filenames != null &&
01017                                 binaryData.size() == filenames.size()) {
01018                         String uid = cls+"."+id;
01019                         for (int i=0;i< binaryData.size() && ok; i++) {
01020                                 ok &= submitObjectBinaryFile(uid, binaryData.get(i), filenames.get(i));
01021                         }
01022                         if (!ok) {
01023                                 deleteObject(uid);
01024                         }
01025                 }
01026 
01027                 return ok;
01028 
01029         }
01030 
01031         @Override
01032         public boolean submitObjectBinaryFile(String uid, final File file) {
01033 
01034                 System.out.print("\nupload object file '"+file.getName()+"' (uid '"+uid+"')");
01035                 
01036                 FileInputStream fis;
01037                 try {
01038                         fis = new FileInputStream(file);
01039                 } catch (Exception e) {
01040                         System.out.println(": Couldn't create file input stream!");
01041                         return false;
01042                 }
01043 
01044                 if (!file.canRead()) {
01045                         System.out.println(": Can't read from file!");
01046                         return false;
01047                 }
01048                 
01049                 System.out.print(" ["+(file.length()/1024)+"KiB]: ");
01050 
01051                 InputStreamBody streamBody = new InputStreamBody(fis, "application/octet-stream", file.getName()) {
01052                         @Override
01053                         public long getContentLength() {
01054                                 return file.length();
01055                         }
01056                 };              
01057 
01058                 return submitBinaryFile(roboEarthBaseURL+submitObjectBinariesSuffix+uid, streamBody);
01059 
01060         }
01061 
01062         @Override
01063         public boolean submitObjectBinaryFile(String uid, final byte[] data, String filename) {
01064 
01065                 System.out.print("\nupload object file '"+filename+"' (uid '"+uid+"')");
01066                 
01067                 if (data == null || filename == null || filename.length() == 0) {
01068                         System.out.println(": parameter error (null pointer)");
01069                         return false;
01070                 }
01071                 
01072                 System.out.print(" ["+(data.length/1024)+"KiB]: ");
01073 
01074                 ByteArrayInputStream bis = new ByteArrayInputStream(data);
01075 
01076                 InputStreamBody streamBody = new InputStreamBody(bis, "application/octet-stream", filename) {
01077                         @Override
01078                         public long getContentLength() {
01079                                 return data.length;
01080                         }
01081                 };
01082 
01083                 return submitBinaryFile(roboEarthBaseURL+submitObjectBinariesSuffix+uid, streamBody);
01084 
01085         }
01086         
01087         @Override
01088         public boolean submitEnvironmentBinaryFile(String uid, final File file) {
01089 
01090                 System.out.print("\nupload environment file '"+file.getName()+"' (uid '"+uid+"')");
01091                 
01092                 FileInputStream fis;
01093                 try {
01094                         fis = new FileInputStream(file);
01095                 } catch (Exception e) {
01096                         System.out.println(": Couldn't create file input stream!");
01097                         return false;
01098                 }
01099 
01100                 if (!file.canRead()) {
01101                         System.out.println(": Can't read from file!");
01102                         return false;
01103                 }
01104                 
01105                 System.out.print(" ["+(file.length()/1024)+"KiB]: ");
01106 
01107                 InputStreamBody streamBody = new InputStreamBody(fis, "application/octet-stream", file.getName()) {
01108                         @Override
01109                         public long getContentLength() {
01110                                 return file.length();
01111                         }
01112                 };              
01113 
01114                 return submitBinaryFile(roboEarthBaseURL+submitEnvironmentBinariesSuffix+uid, streamBody);
01115 
01116         }
01117         
01118         @Override
01119         public boolean submitEnvironmentBinaryFile(String uid, final byte[] data, String filename) {
01120 
01121                 System.out.print("\nupload environment file '"+filename+"' (uid '"+uid+"')");
01122                 
01123                 if (data == null || filename == null || filename.length() == 0) {
01124                         System.out.println(": parameter error (null pointer)");
01125                         return false;
01126                 }
01127 
01128                 System.out.print(" ["+(data.length/1024)+"KiB]: ");
01129                 
01130                 ByteArrayInputStream bis = new ByteArrayInputStream(data);
01131 
01132                 InputStreamBody streamBody = new InputStreamBody(bis, "application/octet-stream", filename) {
01133                         @Override
01134                         public long getContentLength() {
01135                                 return data.length;
01136                         }
01137                 };
01138 
01139                 return submitBinaryFile(roboEarthBaseURL+submitEnvironmentBinariesSuffix+uid, streamBody);
01140 
01141         }
01142         
01152         protected boolean submitBinaryFile(String url, InputStreamBody isb) {
01153 
01154                 boolean ok = false;
01155 
01156                 if (apiKey != null && url != null && isb != null && 
01157                                 isb.getFilename() != null && isb.getFilename().length() > 0) {
01158 
01159                         HttpClient httpclient = null;
01160 
01161                         try {
01162 
01163                                 httpclient = new DefaultHttpClient();
01164                                 HttpParams params = httpclient.getParams();
01165                                 HttpConnectionParams.setConnectionTimeout(params, timoutInMs);
01166                                 HttpConnectionParams.setSoTimeout(params, timoutInMs);
01167                                 
01168                                 HttpPost httppost = new HttpPost(url);
01169 
01170                                 StringBody apiKeyBody = new StringBody(apiKey);
01171                                 StringBody typeBody = new StringBody(isb.getFilename());
01172 
01173                                 MultipartEntity mpEntity = new MultipartEntity();
01174                                 mpEntity.addPart("api_key", apiKeyBody);
01175                                 mpEntity.addPart("type", typeBody);
01176                                 mpEntity.addPart("file", isb);
01177                                 httppost.setEntity(mpEntity);
01178 
01179                                 HttpResponse response = httpclient.execute(httppost);
01180                                 ok = isHTTPRequestProcessedCorrectly(response);
01181 
01182                         } catch (Exception e) {
01183                                 System.out.println(e.getLocalizedMessage());
01184                         } finally {
01185                                 if (httpclient != null) {
01186                                         httpclient.getConnectionManager().shutdown();
01187                                 }
01188                                 System.out.println();
01189                         }
01190 
01191                 } else {
01192                         System.out.println("parameter error (null pointer)");
01193                 }
01194 
01195                 return ok;
01196 
01197         }
01198 
01199 
01208         protected static boolean submitData(String jsonData, String submitURL) {
01209 
01210                 boolean ok = false;
01211 
01212                 if (jsonData != null && submitURL != null) {
01213 
01214                         HttpClient httpclient = null;
01215 
01216                         try {
01217 
01218                                 httpclient = new DefaultHttpClient();
01219                                 HttpParams params = httpclient.getParams();
01220                                 HttpConnectionParams.setConnectionTimeout(params, timoutInMs);
01221                                 HttpConnectionParams.setSoTimeout(params, timoutInMs);
01222                                 
01223                                 Header header = new BasicHeader("Content-Type","application/json");
01224                                 StringEntity entity = new StringEntity(jsonData, "UTF-8");
01225 
01226                                 HttpPost httppost = new HttpPost(submitURL);
01227                                 httppost.setEntity(entity);
01228                                 httppost.setHeader(header);
01229 
01230                                 HttpResponse response = httpclient.execute(httppost);
01231                                 ok = isHTTPRequestProcessedCorrectly(response);
01232 
01233                         } catch (Exception e) {
01234                                 System.out.println(e.getLocalizedMessage());
01235                         } finally {
01236                                 if (httpclient != null) {
01237                                         httpclient.getConnectionManager().shutdown();
01238                                 }
01239                         }
01240 
01241                 }
01242 
01243                 return ok;
01244 
01245         }
01246 
01247         
01248         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
01249         // 
01250         // Query Sesame repository
01251         //
01252         
01253         @Override
01254         public String queryActionRecipeDB(String seRQLquery) {
01255                 return querySemanticDB(seRQLquery, "recipes");
01256         }
01257 
01258         @Override
01259         public String queryObjectDB(String seRQLquery) {
01260                 return querySemanticDB(seRQLquery, "objects");
01261 
01262         }
01263 
01264         @Override
01265         public String queryEnvironmentDB(String seRQLquery) {
01266                 return querySemanticDB(seRQLquery, "environments");
01267         }
01268 
01277         protected static String querySemanticDB(String seRQLquery, String repository) {
01278 
01279                 String result = null;
01280 
01281                 if (seRQLquery != null) {
01282 
01283                         HttpClient httpclient = null;
01284 
01285                         try {
01286 
01287                                 httpclient = new DefaultHttpClient();
01288                                 HttpParams params = httpclient.getParams();
01289                                 HttpConnectionParams.setConnectionTimeout(params, timoutInMs);
01290                                 HttpConnectionParams.setSoTimeout(params, timoutInMs);
01291 
01292                                 JsonRootNode json = aJsonObject(
01293                                                 aJsonField("query", aJsonString(seRQLquery)),
01294                                                 aJsonField("repository", aJsonString(repository))
01295                                                 );
01296 
01297                                 String jsonText = JSON_FORMATTER.format(json);
01298 
01299                                 Header header = new BasicHeader("Content-Type","application/json");
01300                                 StringEntity entity = new StringEntity(jsonText, "UTF-8");
01301 
01302                                 HttpPost httppost = new HttpPost(roboEarthBaseURL+querySuffix);
01303                                 httppost.setEntity(entity);
01304                                 httppost.setHeader(header);
01305 
01306                                 HttpResponse response = httpclient.execute(httppost);
01307                                 if (isHTTPRequestProcessedCorrectly(response)) {
01308                                         HttpEntity entitity = response.getEntity();
01309                                         if (entitity != null) {
01310                                                 result = EntityUtils.toString(entitity);
01311                                         }
01312                                 }
01313 
01314                         } catch (Exception e) {
01315                                 System.out.println(e.getLocalizedMessage());
01316                         } finally {
01317                                 if (httpclient != null) {
01318                                         httpclient.getConnectionManager().shutdown();
01319                                 }
01320                         }
01321 
01322                 }
01323 
01324                 return result;
01325 
01326         }
01327 
01328         
01329         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
01330         // 
01331         // Delete information from the DB
01332         //
01333         
01334         @Override
01335         public boolean deleteActionRecipe(String uid) {
01336                 return deleteData(roboEarthBaseURL+requestActionRecipeSuffix+uid+"/"+apiKey);
01337 
01338         }
01339 
01340         @Override
01341         public boolean deleteObject(String uid) {
01342                 return deleteData(roboEarthBaseURL+requestObjectSuffix+uid+"/"+apiKey);
01343 
01344         }
01345 
01346         @Override
01347         public boolean deleteEnvironment(String uid) {
01348                 return deleteData(roboEarthBaseURL+requestEnvironmentSuffix+uid+"/"+apiKey); 
01349 
01350         }
01351 
01352         @Override
01353         public boolean deleteObjectBinaryFile(String objectUid, String fileID) {
01354                 return deleteData(roboEarthBaseURL+requestObjectSuffix+objectUid+"/"+apiKey+"/"+fileID);
01355 
01356         }
01357 
01358         @Override
01359         public boolean deleteEnvironmentBinaryFile(String envUid, String fileID) {
01360                 return deleteData(roboEarthBaseURL+requestEnvironmentSuffix+envUid+"/"+apiKey+"/"+fileID);
01361 
01362         }
01363         
01371         protected static boolean deleteData(String deleteURL) {
01372 
01373                 boolean ok = false;
01374 
01375                 if (deleteURL != null) {
01376 
01377                         HttpClient httpclient = null;
01378 
01379                         try {
01380 
01381                                 httpclient = new DefaultHttpClient();
01382                                 HttpParams params = httpclient.getParams();
01383                                 HttpConnectionParams.setConnectionTimeout(params, timoutInMs);
01384                                 HttpConnectionParams.setSoTimeout(params, timoutInMs);
01385                                 
01386                                 HttpDelete httpdel = new HttpDelete(deleteURL);
01387                                 HttpResponse response = httpclient.execute(httpdel);
01388                                 ok = isHTTPRequestProcessedCorrectly(response);
01389 
01390                         } catch (Exception e) {
01391                                 System.out.println(e.getLocalizedMessage());
01392                         } finally {
01393                                 if (httpclient != null) {
01394                                         httpclient.getConnectionManager().shutdown();
01395                                 }
01396                         }
01397                 }
01398 
01399                 return ok;
01400 
01401         }
01402 
01403         
01404         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
01405         // 
01406         // Update information in the DB
01407         //
01408         
01409         @Override
01410         public boolean updateActionRecipe(String uid, OWLOntology actionRecipe, String description) {
01411                 return updateActionRecipe(uid, OWLIO.saveOntologyToString(actionRecipe), description);
01412         }
01413         
01414         public boolean updateActionRecipe(String uid, String owlData, String description) {
01415                 
01416                 boolean ok = false;
01417 
01418                 if (apiKey != null && owlData != null && uid != null && description != null) {
01419 
01420                         JsonRootNode json = aJsonObject(
01421                                         aJsonField("description", aJsonString(description)),
01422                                         aJsonField("recipe", aJsonString(owlData)),
01423                                         aJsonField("api_key", aJsonString(apiKey))
01424                                         );
01425                         ok = updateData(JSON_FORMATTER.format(json), roboEarthBaseURL+requestActionRecipeSuffix+uid);
01426 
01427                 } else {
01428                         System.out.println("parameter error (null pointer)");
01429                 }
01430                 return ok;
01431 
01432         }
01433 
01434         @Override
01435         public boolean updateEnvironment(String uid, OWLOntology env, String description) {
01436                 return updateEnvironment(uid, OWLIO.saveOntologyToString(env), description);
01437         }
01438         
01439 
01440         public boolean updateEnvironment(String uid, String owlData, String description) {
01441                 
01442                 boolean ok = false;
01443 
01444                 if (apiKey != null && owlData != null && uid != null && description != null) {
01445 
01446                         JsonRootNode json = aJsonObject(
01447                                         aJsonField("description", aJsonString(description)),
01448                                         aJsonField("environment", aJsonString(owlData)),
01449                                         aJsonField("api_key", aJsonString(apiKey))
01450                                         );
01451                         ok = updateData(JSON_FORMATTER.format(json), roboEarthBaseURL+requestEnvironmentSuffix+uid);
01452 
01453                 } else {
01454                         System.out.println("parameter error (null pointer)");
01455                 }
01456                 return ok;
01457 
01458         }
01459         
01460         
01461 
01462         @Override
01463         public boolean updateEnvironmentBinaryFile(String uid, File file) {
01464 
01465                 boolean ok = false;
01466 
01467                 if (uid != null && file != null && file.canRead()) {
01468                         ok = deleteEnvironmentBinaryFile(uid, file.getName());
01469                         if (ok) {
01470                                 ok = submitEnvironmentBinaryFile(uid, file);    
01471                         }
01472                 }
01473                 return ok;
01474         }
01475 
01476         @Override
01477         public boolean updateEnvironmentBinaryFile(String uid, byte[] data, String filename) {
01478 
01479                 boolean ok = false;
01480 
01481                 if (uid != null && data != null && filename != null) {
01482                         ok = deleteEnvironmentBinaryFile(uid, filename);
01483                         if (ok) {
01484                                 ok = submitEnvironmentBinaryFile(uid, data, filename);  
01485                         }
01486                 } 
01487                 return ok;
01488         }
01489         
01490         @Override
01491         public boolean updateObject(String uid, OWLOntology object, String description) {
01492                  return updateObject(uid, OWLIO.saveOntologyToString(object), description);
01493         }
01494         
01495         @Override
01496         public boolean updateObject(String uid, String object, String description) {
01497                 
01498                 boolean ok = false;
01499 
01500                 if (apiKey != null && object != null && uid != null && description != null) {
01501 
01502                         String owlData = object;
01503                         JsonRootNode json = aJsonObject(
01504                                         aJsonField("description", aJsonString(description)),
01505                                         aJsonField("object_description", aJsonString(owlData)),
01506                                         aJsonField("api_key", aJsonString(apiKey))
01507                                         );
01508                         
01509                         ok = updateData(JSON_FORMATTER.format(json), roboEarthBaseURL+requestObjectSuffix+uid);
01510 
01511                         if(!ok)
01512                                 System.err.println("updateData failed");
01513                         
01514                 } else {
01515                         System.out.println("parameter error (null pointer)");
01516                 }
01517                 return ok;
01518 
01519         }
01520 
01521         @Override
01522         public boolean updateObjectBinaryFile(String uid, File file) {
01523 
01524                 boolean ok = false;
01525 
01526                 if (uid != null && file != null && file.canRead()) {
01527                         ok = deleteObjectBinaryFile(uid, file.getName());
01528                         if (ok) {
01529                                 ok = submitObjectBinaryFile(uid, file); 
01530                         }
01531                 }
01532                 return ok;
01533         }
01534 
01535         @Override
01536         public boolean updateObjectBinaryFile(String uid, byte[] data, String filename) {
01537 
01538                 boolean ok = false;
01539 
01540                 if (uid != null && data != null && filename != null) {
01541                         ok = deleteObjectBinaryFile(uid, filename);
01542                         if (ok) {
01543                                 ok = submitObjectBinaryFile(uid, data, filename);       
01544                         }
01545                 }
01546                 return ok;
01547         }
01548 
01557         protected static boolean updateData(String jsonData, String updateURL) {
01558 
01559                 boolean ok = false;
01560 
01561                 if (jsonData != null && updateURL != null) {
01562 
01563                         HttpClient httpclient = null;
01564 
01565                         try {
01566 
01567                                 httpclient = new DefaultHttpClient();
01568                                 HttpParams params = httpclient.getParams();
01569                                 HttpConnectionParams.setConnectionTimeout(params, timoutInMs);
01570                                 HttpConnectionParams.setSoTimeout(params, timoutInMs);
01571                                 
01572                                 Header header = new BasicHeader("Content-Type","application/json");
01573                                 StringEntity entity = new StringEntity(jsonData, "UTF-8");
01574 
01575                                 HttpPut httpput = new HttpPut(updateURL);
01576                                 httpput.setEntity(entity);
01577                                 httpput.setHeader(header);
01578                                 
01579                                 HttpResponse response = httpclient.execute(httpput);
01580                                 ok = isHTTPRequestProcessedCorrectly(response);
01581 
01582                         } catch (Exception e) {
01583                                 System.out.println(e.getLocalizedMessage());
01584                         } finally {
01585                                 if (httpclient != null) {
01586                                         httpclient.getConnectionManager().shutdown();
01587                                 }
01588                         }
01589 
01590                 }
01591 
01592                 return ok;
01593 
01594         }
01595 
01596         
01597         // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
01598         // 
01599         // Search for information in the DB
01600         //
01601         
01602         @Override
01603         public String[] searchActionRecipes(String searchID, ArrayList<String> outUIDs) {
01604                 
01605                 String[] actionRecipes = null;
01606                 if (searchID != null) {
01607 
01608                         String responseBody = requestData(roboEarthBaseURL+requestActionRecipeSuffix+searchID);
01609                         if (responseBody != null && (responseBody.startsWith("[") || responseBody.startsWith("{"))) {
01610 
01611                                 try {
01612                                         // Create a list of returned recipes and their time stamps, ...
01613                                         RecipeList recipes = new RecipeList(responseBody);
01614 
01615                                         if (recipes != null) {
01616 
01617                                                 if (outUIDs != null) {
01618                                                         outUIDs.clear();
01619                                                 }
01620 
01621                                                 actionRecipes = new String[recipes.size()];
01622                                                 for (int i=0;i<actionRecipes.length; i++) {
01623                                                         responseBody = recipes.get(i);
01624                                                         actionRecipes[i] = responseBody;
01625                                                         if (outUIDs != null) {
01626                                                                 outUIDs.add(recipes.getUID(i)); 
01627                                                         }
01628                                                 }
01629                                         }
01630 
01631                                 } catch (InvalidSyntaxException e) {
01632                                         e.printStackTrace();
01633                                 }
01634 
01635                         }
01636 
01637                 } else {
01638                         System.out.println("parameter error (null pointer)");
01639                 }
01640                 return actionRecipes;
01641 
01642         }
01643 
01644         @Override
01645         public String[] searchEnvironments(String searchID, ArrayList<String> outUIDs,
01646                         ArrayList<ArrayList<String>> outFilenames,
01647                         ArrayList<ArrayList<String>> outFileURLs) {
01648                 
01649                 String[] environments = null;
01650                 if (searchID != null) {
01651 
01652                         String responseBody = requestData(roboEarthBaseURL+requestEnvironmentSuffix+searchID);
01653                         if (responseBody != null && (responseBody.startsWith("[") || responseBody.startsWith("{"))) {
01654 
01655                                 try {
01656                                         // Create a list of returned environments and their time stamps, ...
01657                                         EnvironmentList envs = new EnvironmentList(responseBody);
01658 
01659                                         if (envs != null) {
01660 
01661                                                 if (outUIDs != null) {
01662                                                         outUIDs.clear();
01663                                                 }
01664                                                 if (outFilenames != null) {
01665                                                         outFilenames.clear();
01666                                                 }
01667                                                 if (outFileURLs != null) {
01668                                                         outFileURLs.clear();
01669                                                 }
01670 
01671                                                 environments = new String[envs.size()];
01672                                                 for (int i=0;i<environments.length; i++) {
01673                                                         responseBody = envs.get(i);
01674                                                         environments[i] = responseBody;
01675                                                         if (outUIDs != null) {
01676                                                                 outUIDs.add(envs.getUID(i));    
01677                                                         }
01678                                                         if (outFilenames != null) {
01679                                                                 String[] names = envs.getFilenames(i);
01680                                                                 if (names != null) {
01681                                                                         ArrayList<String> nameList = new ArrayList<String>();
01682                                                                         for (String name : names) {
01683                                                                                 nameList.add(name);
01684                                                                         }
01685                                                                         outFilenames.add(nameList);
01686                                                                 }
01687                                                         }
01688                                                         if (outFileURLs != null) {
01689                                                                 String[] urls = envs.getFileURLs(i);
01690                                                                 if (urls != null) {
01691                                                                         ArrayList<String> urlList = new ArrayList<String>();
01692                                                                         for (String url : urls) {
01693                                                                                 urlList.add(url);
01694                                                                         }
01695                                                                         outFileURLs.add(urlList);
01696                                                                 }
01697                                                         }
01698                                                 }
01699                                         }
01700 
01701                                 } catch (InvalidSyntaxException e) {
01702                                         e.printStackTrace();
01703                                 }
01704 
01705                         }
01706 
01707                 } else {
01708                         System.out.println("parameter error (null pointer)");
01709                 }
01710                 return environments;
01711 
01712         }
01713 
01714         @Override
01715         public String[] searchObjects(String searchID, ArrayList<String> outUIDs,
01716                         ArrayList<ArrayList<String>> outFilenames,
01717                         ArrayList<ArrayList<String>> outFileURLs) {
01718 
01719                 String[] objects = null;
01720                 if (searchID != null) {
01721 
01722                         String responseBody = requestData(roboEarthBaseURL+requestObjectSuffix+searchID);
01723                         if (responseBody != null && (responseBody.startsWith("[") || responseBody.startsWith("{"))) {
01724 
01725                                 try {
01726                                         // Create a list of returned objects and their time stamps, ...
01727                                         ObjectList objList = new ObjectList(responseBody);
01728 
01729                                         if (objList != null) {
01730 
01731                                                 if (outUIDs != null) {
01732                                                         outUIDs.clear();
01733                                                 }
01734                                                 if (outFilenames != null) {
01735                                                         outFilenames.clear();
01736                                                 }
01737                                                 if (outFileURLs != null) {
01738                                                         outFileURLs.clear();
01739                                                 }
01740 
01741                                                 objects = new String[objList.size()];
01742                                                 for (int i=0;i<objects.length; i++) {
01743                                                         responseBody = objList.get(i);
01744                                                         objects[i] = responseBody;
01745                                                         if (outUIDs != null) {
01746                                                                 outUIDs.add(objList.getUID(i)); 
01747                                                         }
01748                                                         if (outFilenames != null) {
01749                                                                 String[] names = objList.getFilenames(i);
01750                                                                 if (names != null) {
01751                                                                         ArrayList<String> nameList = new ArrayList<String>();
01752                                                                         for (String name : names) {
01753                                                                                 nameList.add(name);
01754                                                                         }
01755                                                                         outFilenames.add(nameList);
01756                                                                 }
01757                                                         }
01758                                                         if (outFileURLs != null) {
01759                                                                 String[] urls = objList.getFileURLs(i);
01760                                                                 if (urls != null) {
01761                                                                         ArrayList<String> urlList = new ArrayList<String>();
01762                                                                         for (String url : urls) {
01763                                                                                 urlList.add(url);
01764                                                                         }
01765                                                                         outFileURLs.add(urlList);
01766                                                                 }
01767                                                         }
01768                                                 }
01769                                         }
01770 
01771                                 } catch (InvalidSyntaxException e) {
01772                                         e.printStackTrace();
01773                                 }
01774 
01775                         }
01776 
01777                 } else {
01778                         System.out.println("parameter error (null pointer)");
01779                 }
01780                 return objects;
01781 
01782         }
01783 
01784         @Override
01785         public ArrayList<byte[]> request2dMap(String envUid, OWLOntology srdl,
01786                         String baseScannerLink, String simpleMapNameWithoutExt) {
01787 
01788                 System.out.println("\nrequest 2d map for env. '" + envUid + "': ");
01789                 
01790                 ArrayList<byte[]> map = null;
01791                 
01792                 if (envUid != null && srdl != null && baseScannerLink != null &&
01793                                 simpleMapNameWithoutExt != null) {
01794 
01795                         double z = Inference.getZCoordinate(srdl, baseScannerLink);
01796                         if (!Double.isNaN(z)) {
01797                                 
01798                                 JsonRootNode json = aJsonObject(
01799                                                 aJsonField("env", aJsonString(envUid)),
01800                                                 aJsonField("z_min", aJsonString(String.valueOf(z)))
01801                                                 );
01802                                 
01803                                 String url = roboEarthBaseURL+mapExtractorSuffix;
01804                                 String jsonData = JSON_FORMATTER.format(json);
01805                                 String responseBody = requestService(jsonData, url);
01806                                 
01807                                 try {
01808                                         EnvironmentList envs = new EnvironmentList(responseBody);
01809                                         map = envs.get2dMap(0, simpleMapNameWithoutExt);
01810                                 } catch (InvalidSyntaxException e) {
01811                                         e.printStackTrace();
01812                                 }
01813                                 
01814                         } else {
01815                                 System.out.println("couldn't determine pose of link '"+ baseScannerLink +"'");  
01816                         }
01817                         
01818                 } else {
01819                         System.out.println("parameter error (null pointer)");
01820                 }
01821                 
01822                 return map;
01823         }
01824         
01825         @Override
01826         public ArrayList<byte[]> requestProjected2dMap(String envUid, double minZ,
01827                         double maxZ, String simpleMapNameWithoutExt) {
01828 
01829                 double z1, z2;
01830                 
01831                 if (minZ <= maxZ) {
01832                         z1 = minZ;
01833                         z2 = maxZ;
01834                 } else {
01835                         z2 = minZ;
01836                         z1 = maxZ;                      
01837                 }
01838                 
01839                 System.out.print("\nrequest projected 2d map for env. '" + 
01840                                 envUid + "' (z1 "+z1+", z2 "+z2+"): ");
01841                 
01842                 ArrayList<byte[]> map = null;
01843                 
01844                 JsonRootNode json = aJsonObject(
01845                                 aJsonField("env", aJsonString(envUid)),
01846                                 aJsonField("z_min", aJsonString(String.valueOf(z1))),
01847                                 aJsonField("z_max", aJsonString(String.valueOf(z2)))
01848                                 );
01849                 
01850                 String url = roboEarthBaseURL+mapExtractorSuffix;
01851                 String jsonData = JSON_FORMATTER.format(json);
01852                 String responseBody = requestService(jsonData, url);
01853                 
01854                 try {
01855                         EnvironmentList envs = new EnvironmentList(responseBody);
01856                         map = envs.get2dMap(0, simpleMapNameWithoutExt);
01857                 } catch (InvalidSyntaxException e) {
01858                         e.printStackTrace();
01859                 }
01860                 
01861                 return map;
01862                 
01863         }
01864         
01865         protected static String requestService(String jsonData, String url) {
01866 
01867                 String responseBody = null;
01868 
01869                 if (jsonData != null && url != null) {
01870                         
01871                         HttpClient httpclient = null;
01872 
01873                         try {
01874 
01875                                 httpclient = new DefaultHttpClient();
01876                                 HttpParams params = httpclient.getParams();
01877                                 HttpConnectionParams.setConnectionTimeout(params, timoutInMs);
01878                                 HttpConnectionParams.setSoTimeout(params, timoutInMs);
01879                                 
01880                                 Header header = new BasicHeader("Content-Type","application/json");
01881                                 StringEntity entity = new StringEntity(jsonData, "UTF-8");
01882 
01883                                 HttpPost httppost = new HttpPost(url);
01884                                 httppost.setEntity(entity);
01885                                 httppost.setHeader(header);
01886 
01887                                 HttpResponse response = httpclient.execute(httppost);
01888                                 if (isHTTPRequestProcessedCorrectly(response)) {
01889                                         HttpEntity entitity = response.getEntity();
01890                                         responseBody = EntityUtils.toString(entitity);
01891                                 }
01892 
01893                         } catch (Exception e) {
01894                                 System.out.println(e.getLocalizedMessage());
01895                         } finally {
01896                                 if (httpclient != null) {
01897                                         httpclient.getConnectionManager().shutdown();
01898                                 }
01899                         }
01900                         
01901                 }
01902                 
01903                 return responseBody;
01904                 
01905         }
01906         
01913         public static boolean isHTTPRequestProcessedCorrectly(HttpResponse response) {
01914 
01915                 boolean ok;
01916 
01917                 StatusLine stl = response.getStatusLine();
01918                 int status = stl.getStatusCode();
01919                 if (status >=200 && status <300) {
01920                         ok = true;
01921                 } else {
01922                         ok = false;
01923                 }
01924                 return ok;
01925         }
01926 
01937         public static class RecipeList extends AbstractList<String> {
01938 
01939                 private final JsonRootNode json;
01940 
01941                 // pre-built JSON node selectors, used to extract specific nodes
01942                 private final static JsonNodeSelector<JsonNode, List<JsonNode>> JSON_RECIPES = 
01943                                 JsonNodeSelectors.anArrayNode("recipes");
01944 
01945                 private final static JsonNodeSelector<JsonNode, String> JSON_RECIPE = 
01946                                 JsonNodeSelectors.aStringNode("recipe");
01947 
01948                 private final static JsonNodeSelector<JsonNode, String> JSON_TIMESTAMP = 
01949                                 JsonNodeSelectors.aNumberNode("timestamp");
01950 
01951                 private final static JsonNodeSelector<JsonNode, String> JSON_AUTHOR = 
01952                                 JsonNodeSelectors.aStringNode("author");
01953 
01954                 private final static JsonNodeSelector<JsonNode, String> JSON_DESCRIPTION = 
01955                                 JsonNodeSelectors.aStringNode("description");
01956 
01957                 private final static JsonNodeSelector<JsonNode, String> JSON_UID = 
01958                                 JsonNodeSelectors.aStringNode("id");
01959 
01960                 public RecipeList(String jsonText) throws InvalidSyntaxException {
01961                         json = json_parser.parse(jsonText);
01962                 }
01963 
01964                 @Override
01965                 public String get(int index) {
01966 
01967                         JsonNode recipe = json.getArrayNode().get(index);
01968                         List<JsonNode> recipeVariants = JSON_RECIPES.getValue(recipe);
01969                         return JSON_RECIPE.getValue(recipeVariants.get(0));
01970 
01971                 }
01972 
01973                 public long getTimestamp(int index) {
01974 
01975                         List<JsonNode> recipes = json.getArrayNode();
01976                         List<JsonNode> recipeVariants = JSON_RECIPES.getValue(recipes.get(index));
01977                         return Long.parseLong(JSON_TIMESTAMP.getValue(recipeVariants.get(0)));
01978 
01979                 }
01980 
01981                 public String getDescription(int index) {
01982                         return JSON_DESCRIPTION.getValue(json.getArrayNode().get(index));
01983                 }
01984 
01985                 public String getAuthor(int index) {
01986                         return JSON_AUTHOR.getValue(json.getArrayNode().get(index));
01987                 }
01988 
01989                 public String getUID(int index) {
01990                         return JSON_UID.getValue(json.getArrayNode().get(index));
01991                 }
01992 
01993                 @Override
01994                 public int size() {
01995                         return json.getArrayNode().size();
01996                 }
01997 
01998         }
01999 
02010         public static class ObjectList extends AbstractList<String> {
02011 
02012                 private final JsonRootNode json;
02013 
02014                 // pre-built JSON node selectors, used to extract specific nodes
02015                 private final static JsonNodeSelector<JsonNode, List<JsonNode>> JSON_OBJECTS = 
02016                                 JsonNodeSelectors.anArrayNode("object_description");
02017 
02018                 private final static JsonNodeSelector<JsonNode, String> JSON_OBJECT = 
02019                                 JsonNodeSelectors.aStringNode("description");
02020 
02021                 private final static JsonNodeSelector<JsonNode, String> JSON_TIMESTAMP = 
02022                                 JsonNodeSelectors.aNumberNode("timestamp");
02023 
02024                 private final static JsonNodeSelector<JsonNode, String> JSON_AUTHOR = 
02025                                 JsonNodeSelectors.aStringNode("author");
02026 
02027                 private final static JsonNodeSelector<JsonNode, String> JSON_DESCRIPTION = 
02028                                 JsonNodeSelectors.aStringNode("description");
02029 
02030                 private final static JsonNodeSelector<JsonNode, String> JSON_UID = 
02031                                 JsonNodeSelectors.aStringNode("id");
02032 
02033                 private final static JsonNodeSelector<JsonNode, Map<JsonStringNode,JsonNode>> JSON_FILES = 
02034                                 JsonNodeSelectors.anObjectNode("files");
02035 
02036                 private final static JsonNodeSelector<JsonNode, String> JSON_URL = 
02037                                 JsonNodeSelectors.aStringNode("url");
02038 
02039                 
02040                 @Deprecated
02041                 private final static JsonNodeSelector<JsonNode, String> JSON_IMAGE_PATH = 
02042                 JsonNodeSelectors.aStringNode("files",fileIdObjImage,"url");
02043 
02044                 @Deprecated
02045                 private final static JsonNodeSelector<JsonNode, String> JSON_MODEL_PATH = 
02046                 JsonNodeSelectors.aStringNode("files",fileIdObjModel,"url");
02047 
02048                 @Deprecated
02049                 private final static JsonNodeSelector<JsonNode, String> JSON_ARTICULATION_PATH = 
02050                 JsonNodeSelectors.aStringNode("files",fileIdObjArticModel,"url");
02051 
02052 
02053                 public ObjectList(String jsonText) throws InvalidSyntaxException {
02054                         json = json_parser.parse(jsonText);
02055                 }
02056 
02057                 @Override
02058                 public String get(int index) {
02059 
02060                         JsonNode obj = json.getArrayNode().get(index);
02061                         List<JsonNode> objVariants = JSON_OBJECTS.getValue(obj);
02062                         return JSON_OBJECT.getValue(objVariants.get(0));
02063 
02064                 }
02065 
02066                 public long getTimestamp(int index) {
02067 
02068                         List<JsonNode> objs = json.getArrayNode();
02069                         List<JsonNode> objVariants = JSON_OBJECTS.getValue(objs.get(index));
02070                         return Long.parseLong(JSON_TIMESTAMP.getValue(objVariants.get(0)));
02071 
02072                 }
02073 
02074                 public String getDescription(int index) {
02075                         return JSON_DESCRIPTION.getValue(json.getArrayNode().get(index));
02076                 }
02077 
02078                 public String getAuthor(int index) {
02079                         return JSON_AUTHOR.getValue(json.getArrayNode().get(index));
02080                 }
02081 
02082                 public String getUID(int index) {
02083                         return JSON_UID.getValue(json.getArrayNode().get(index));
02084                 }
02085 
02086                 public String[] getFilenames(int index) {
02087 
02088                         String[] filenames = null;
02089 
02090                         JsonNode objNode = json.getArrayNode().get(index);
02091 
02092                         if (JSON_FILES.matches(objNode)) {
02093                                 Map<JsonStringNode,JsonNode> files = JSON_FILES.getValue(objNode);
02094                                 filenames = new String[files.size()];
02095                                 Set<JsonStringNode> keys = files.keySet();
02096                                 int i = 0;
02097                                 for (JsonStringNode key : keys) {
02098                                         JsonNode fileNode = files.get(key);
02099                                         if (JSON_URL.matches(fileNode)) {
02100                                                 filenames[i++] = key.getText();
02101                                         }
02102                                 }
02103                         }
02104 
02105                         return filenames;
02106 
02107                 }
02108 
02109                 public String[] getFileURLs(int index) {
02110 
02111                         String[] fileURLs = null;
02112 
02113                         JsonNode objNode = json.getArrayNode().get(index);
02114 
02115                         if (JSON_FILES.matches(objNode)) {
02116                                 Map<JsonStringNode,JsonNode> files = JSON_FILES.getValue(objNode);
02117                                 fileURLs = new String[files.size()];
02118                                 Set<JsonStringNode> keys = files.keySet();
02119                                 int i = 0;
02120                                 for (JsonStringNode key : keys) {
02121                                         JsonNode urlNode = files.get(key);
02122                                         if (JSON_URL.matches(urlNode)) {
02123                                                 fileURLs[i++] = JSON_URL.getValue(urlNode);
02124                                         }
02125                                 }
02126                         }
02127 
02128                         return fileURLs;
02129 
02130                 }
02131 
02132                 @Deprecated
02133                 public String getPathToImage(int index) {
02134                         String path = null;
02135 
02136                         JsonNode objNode = json.getArrayNode().get(index);
02137 
02138                         if (JSON_IMAGE_PATH.matches(objNode)) {
02139                                 path = JSON_IMAGE_PATH.getValue(objNode);
02140                         }
02141                         return path;
02142                 }
02143 
02144                 @Deprecated
02145                 public String getPathToModel(int index) {
02146                         String path = null;
02147 
02148                         JsonNode objNode = json.getArrayNode().get(index);
02149 
02150                         if (JSON_MODEL_PATH.matches(objNode)) {
02151                                 path = JSON_MODEL_PATH.getValue(objNode);
02152                         }
02153                         return path;
02154                 }
02155 
02156                 @Deprecated
02157                 public String getPathToArticulationModel(int index) {
02158                         String path = null;
02159 
02160                         JsonNode objNode = json.getArrayNode().get(index);
02161 
02162                         if (JSON_ARTICULATION_PATH.matches(objNode)) {
02163                                 path = JSON_ARTICULATION_PATH.getValue(objNode);
02164                         }
02165                         return path;
02166                 }
02167 
02168                 @Override
02169                 public int size() {
02170                         return json.getArrayNode().size();
02171                 }
02172 
02173         }
02174 
02185         public static class EnvironmentList extends AbstractList<String> {
02186 
02187                 private final JsonRootNode json;
02188 
02189                 // pre-built JSON node selectors, used to extract specific nodes
02190                 private final static JsonNodeSelector<JsonNode, List<JsonNode>> JSON_ENVIRONMENTS = 
02191                                 JsonNodeSelectors.anArrayNode("environments");
02192 
02193                 private final static JsonNodeSelector<JsonNode, String> JSON_ENVIRONMENT = 
02194                                 JsonNodeSelectors.aStringNode("environment");
02195 
02196                 private final static JsonNodeSelector<JsonNode, String> JSON_TIMESTAMP = 
02197                                 JsonNodeSelectors.aNumberNode("timestamp");
02198 
02199                 private final static JsonNodeSelector<JsonNode, String> JSON_AUTHOR = 
02200                                 JsonNodeSelectors.aStringNode("author");
02201 
02202                 private final static JsonNodeSelector<JsonNode, String> JSON_DESCRIPTION = 
02203                                 JsonNodeSelectors.aStringNode("description");
02204 
02205                 private final static JsonNodeSelector<JsonNode, String> JSON_UID = 
02206                                 JsonNodeSelectors.aStringNode("id");
02207 
02208                 private final static JsonNodeSelector<JsonNode, Map<JsonStringNode,JsonNode>> JSON_FILES = 
02209                         JsonNodeSelectors.anObjectNode("files");
02210 
02211                 private final static JsonNodeSelector<JsonNode, String> JSON_URL = 
02212                         JsonNodeSelectors.aStringNode("url");
02213                 
02214                 private final static JsonNodeSelector<JsonNode, Map<JsonStringNode,JsonNode>> JSON_MAPS = 
02215                         JsonNodeSelectors.anObjectNode("2dmap");
02216                 
02217                 public EnvironmentList(String jsonText) throws InvalidSyntaxException {
02218                         json = json_parser.parse(jsonText);
02219                 }
02220 
02221                 @Override
02222                 public String get(int index) {
02223 
02224                         JsonNode env = json.getArrayNode().get(index);
02225                         List<JsonNode> envVariants = JSON_ENVIRONMENTS.getValue(env);
02226                         return JSON_ENVIRONMENT.getValue(envVariants.get(0));
02227 
02228                 }
02229 
02230                 public long getTimestamp(int index) {
02231 
02232                         List<JsonNode> env = json.getArrayNode();
02233                         List<JsonNode> envVariants = JSON_ENVIRONMENTS.getValue(env.get(index));
02234                         return Long.parseLong(JSON_TIMESTAMP.getValue(envVariants.get(0)));
02235 
02236                 }
02237 
02238                 public String getDescription(int index) {
02239                         return JSON_DESCRIPTION.getValue(json.getArrayNode().get(index));
02240                 }
02241 
02242                 public String getAuthor(int index) {
02243                         return JSON_AUTHOR.getValue(json.getArrayNode().get(index));
02244                 }
02245 
02246                 public String getUID(int index) {
02247                         return JSON_UID.getValue(json.getArrayNode().get(index));
02248                 }
02249 
02250                 public String[] getFilenames(int index) {
02251 
02252                         String[] filenames = null;
02253 
02254                         JsonNode objNode = json.getArrayNode().get(index);
02255 
02256                         if (JSON_FILES.matches(objNode)) {
02257                                 Map<JsonStringNode,JsonNode> files = JSON_FILES.getValue(objNode);
02258                                 filenames = new String[files.size()];
02259                                 Set<JsonStringNode> keys = files.keySet();
02260                                 int i = 0;
02261                                 for (JsonStringNode key : keys) {
02262                                         JsonNode fileNode = files.get(key);
02263                                         if (JSON_URL.matches(fileNode)) {
02264                                                 filenames[i++] = key.getText();
02265                                         }
02266                                 }
02267                         }
02268 
02269                         return filenames;
02270 
02271                 }
02272 
02273                 public String[] getFileURLs(int index) {
02274 
02275                         String[] fileURLs = null;
02276 
02277                         JsonNode objNode = json.getArrayNode().get(index);
02278 
02279                         if (JSON_FILES.matches(objNode)) {
02280                                 Map<JsonStringNode,JsonNode> files = JSON_FILES.getValue(objNode);
02281                                 fileURLs = new String[files.size()];
02282                                 Set<JsonStringNode> keys = files.keySet();
02283                                 int i = 0;
02284                                 for (JsonStringNode key : keys) {
02285                                         JsonNode urlNode = files.get(key);
02286                                         if (JSON_URL.matches(urlNode)) {
02287                                                 fileURLs[i++] = JSON_URL.getValue(urlNode);
02288                                         }
02289                                 }
02290                         }
02291 
02292                         return fileURLs;
02293 
02294                 }
02295                 
02296                 public ArrayList<byte[]> get2dMap(int index, String targetFileNameWithoutExt) {
02297                         
02298                         ArrayList<byte[]> map = null;
02299                         
02300                         JsonNode objNode = json.getArrayNode().get(index);
02301                         
02302                         if (JSON_MAPS.matches(objNode)) {
02303                                 Map<JsonStringNode,JsonNode> maps = JSON_MAPS.getValue(objNode);
02304                                 Set<JsonStringNode> keys = maps.keySet();
02305                                 if (keys.size() == 2) {
02306                                         map = new ArrayList<byte[]>(2);
02307                                         Iterator<JsonStringNode> it = keys.iterator();
02308                                         JsonStringNode key1 = it.next();
02309                                         JsonStringNode key2 = it.next();
02310                                         
02311                                         // TODO fix database HTTP response to send binary files instead of strings (after workshop?)
02312                                         
02313                                         String pgm = "";
02314                                         String pgmTmp = null;
02315                                         if (key1.getText().equals("pgm")) {
02316                                                 pgmTmp = maps.get(key1).getText();
02317                                         } else if (key2.getText().equals("pgm")) {
02318                                                 pgmTmp = maps.get(key2).getText();
02319                                         } else {
02320                                                 System.out.println("unexpected response from RoboEarth server ('pgm' missing)");
02321                                                 return null;
02322                                         }
02323                                         
02324                                         if (!pgmTmp.startsWith("P5")) {
02325                                                 System.out.println("2d map received is not a pgm file");
02326                                                 return null;
02327                                         }
02328                                         StringTokenizer st = new StringTokenizer(pgmTmp, "\n");
02329                                         int count = 0;
02330                                         while (st.hasMoreTokens()) {
02331                                                 String s = st.nextToken();
02332                                                 if (s.trim().startsWith("#")) {
02333                                                         continue;
02334                                                 }
02335                                                 
02336                                                 pgm += s+"\n";
02337                                                 
02338                                                 if (++count == 3) {
02339                                                         break;
02340                                                 }
02341                                         }
02342 
02343                                         try {
02344                                                 byte[] pgmBytes = pgm.getBytes("ASCII");
02345                                                 
02346                                                 if (st.hasMoreTokens()) {
02347 
02348                                                         String pixels = st.nextToken().trim();
02349                                                         st = new StringTokenizer(pixels, " ");
02350                                                         
02351                                                         int length = st.countTokens() + pgmBytes.length;
02352                                                         byte[] tmp = pgmBytes;
02353                                                         pgmBytes = new byte[length];
02354                                                         System.arraycopy(tmp, 0, pgmBytes, 0, tmp.length);
02355                                                         
02356                                                         int pixIndex = tmp.length;
02357                                                         while (st.hasMoreTokens()) {
02358                                                                 String t = st.nextToken();
02359                                                                 if (t.equals("0")) {
02360                                                                         pgmBytes[pixIndex++] = 0;                                                                       
02361                                                                 } else if (t.equals("205")) {
02362                                                                         pgmBytes[pixIndex++] = -51;
02363                                                                 } else if (t.equals("254")) {
02364                                                                         pgmBytes[pixIndex++] = -1;
02365                                                                 } else {
02366                                                                         System.out.println("unknown pixel value: "+t);
02367                                                                         return null;
02368                                                                 }
02369                                                         }
02370                                                         
02371                                                 } else {
02372                                                         System.out.println("pgm file is incomplete");
02373                                                         return null;
02374                                                 }
02375                                                 
02376                                                 map.add(pgmBytes);
02377                                         } catch (UnsupportedEncodingException e) {
02378                                                 System.out.println("'ASCII' encoding is not supported");
02379                                         }
02380                                         
02381                                         String yaml = null;
02382                                         if (key1.getText().equals("desc")) {
02383                                                 yaml = maps.get(key1).getText();
02384                                         } else if (key2.getText().equals("desc")) {
02385                                                 yaml = maps.get(key2).getText();
02386                                         } else {
02387                                                 System.out.println("unexpected response from RoboEarth server ('desc' missing)");
02388                                                 return null;
02389                                         }
02390 
02391                                         if (yaml.indexOf("proj2dmap.pgm") >= 0) {
02392                                                 yaml = yaml.replace("proj2dmap.pgm", targetFileNameWithoutExt+".pgm");  
02393                                         } else if (yaml.indexOf("2dmap.pgm") >= 0) {
02394                                                 yaml = yaml.replace("2dmap.pgm", targetFileNameWithoutExt+".pgm");
02395                                         } else {
02396                                                 System.out.println("unexpected format of yaml file");
02397                                                 return null;
02398                                         }
02399                                         
02400                                         try {
02401                                                 map.add(yaml.getBytes("UTF8"));
02402                                         } catch (UnsupportedEncodingException e) {
02403                                                 System.out.println("'UTF8' encoding is not supported");
02404                                         }
02405                                         
02406                                 }
02407                         }
02408                         
02409                         return map;
02410                         
02411                 }
02412                 
02413                 @Override
02414                 public int size() {
02415                         return json.getArrayNode().size();
02416                 }
02417 
02418         }
02419 
02429         public static class RobotList extends AbstractList<String> {
02430 
02431                 private final JsonRootNode json;
02432 
02433                 // pre-built JSON node selectors, used to extract specific nodes
02434                 private final static JsonNodeSelector<JsonNode, String> JSON_SRDL = 
02435                                 JsonNodeSelectors.aStringNode("srdl");
02436 
02437                 private final static JsonNodeSelector<JsonNode, String> JSON_PICTURE = 
02438                                 JsonNodeSelectors.aNumberNode("picture");
02439 
02440                 private final static JsonNodeSelector<JsonNode, String> JSON_AUTHOR = 
02441                                 JsonNodeSelectors.aStringNode("author");
02442 
02443                 private final static JsonNodeSelector<JsonNode, String> JSON_DESCRIPTION = 
02444                                 JsonNodeSelectors.aStringNode("description");
02445 
02446                 private final static JsonNodeSelector<JsonNode, String> JSON_UID = 
02447                                 JsonNodeSelectors.aStringNode("id");
02448 
02449                 public RobotList(String jsonText) throws InvalidSyntaxException {
02450                         json = json_parser.parse(jsonText);
02451                 }
02452 
02453                 @Override
02454                 public String get(int index) {
02455                         JsonNode robot = json.getArrayNode().get(index);
02456                         return JSON_SRDL.getValue(robot);
02457                 }
02458 
02459                 public String getPicture(int index) {
02460                         JsonNode robot = json.getArrayNode().get(index);
02461                         return JSON_PICTURE.getValue(robot);
02462                 }
02463                 
02464                 public String getDescription(int index) {
02465                         return JSON_DESCRIPTION.getValue(json.getArrayNode().get(index));
02466                 }
02467 
02468                 public String getAuthor(int index) {
02469                         return JSON_AUTHOR.getValue(json.getArrayNode().get(index));
02470                 }
02471 
02472                 public String getUID(int index) {
02473                         return JSON_UID.getValue(json.getArrayNode().get(index));
02474                 }
02475 
02476                 @Override
02477                 public int size() {
02478                         return json.getArrayNode().size();
02479                 }
02480 
02481         }
02482         
02483 }


re_comm_core
Author(s): Alexander Perzylo
autogenerated on Sun Jan 5 2014 11:29:33