close

  
<p> function JavaCodeGenerator(code_generator){
  code_generator.reset();
  this.code_generator = code_generator;
  this.code_generator.json_options['null_value'] = 'None';
  this.code_generator.json_options['true_value'] = 'True';
  this.code_generator.json_options['false_value'] = 'False';
  this.code_generator.addPreGenerator('java', 'generateImports');
  this.code_generator.addPreGenerator('java', 'generateClient');
  this.code_generator.addServiceGenerator('java', 'mqlread');
//  this.code_generator.addServiceGenerator('java', 'search');
//  this.code_generator.addServiceGenerator('java', 'topic');
  this.code_generator.addPostGenerator('java', 'generateClientEnd');
  this.indent = [];
}

CodeGenerator.generatorsByLanguage['java'] = JavaCodeGenerator;

JavaCodeGenerator.prototype.getLibraries = function(params, options) {
  var libs = [];
  if (options['library'] != null) {
    libs.push({
      'name': 'Google APIs Client Library for Java',
      'url': 'http://code.google.com/p/google-api-java-client/'
    });
  } else {
    libs.push({
      'name': 'Apache HttpComponents',
      'url': 'http://hc.apache.org/'
    });
  }
  libs.concat([{
    'name': 'json-simple',
    'url': 'http://code.google.com/p/json-simple/'
  },{
    'name': 'json-path',
    'url': 'http://code.google.com/p/json-path/'
  }]);
  return libs;
}

JavaCodeGenerator.prototype.generateImports = function(params, options) {
  var output  = "";
  var libs = [];
  libs.push('com.jayway.jsonpath.JsonPath');
  if (options['library'] != null) {
    libs.concat([
      'com.freebase.FreebaseClient'
    ]);
  } else {
    libs.concat([
      'org.apache.http.HttpResponse',
      'org.apache.http.NameValuePair',
      'org.apache.http.client.HttpClient',
      'org.apache.http.client.methods.HttpGet',
      'org.apache.http.client.utils.URLEncodedUtils',
      'org.apache.http.impl.client.DefaultHttpClient',
      'org.apache.http.message.BasicNameValuePair',
      'org.apache.http.util.EntityUtils'
    ]);
  }
  libs.concat([
    'org.json.simple.JSONArray',
    'org.json.simple.JSONObject',
    'org.json.simple.parser.JSONParser',
    'java.util.ArrayList',
    'java.util.List'
  ]);
  for (i in libs) {
    output += "import " + libs[i] + ";\n";
  }
  output += "\n";
  return output;
}
  
JavaCodeGenerator.prototype.generateClient = function(params, options) {
  var service = options['service'];
  var output  = "";
  var class_name = 'Freebase' + service.toUpperCase().charAt(0) + service.substring(1) + 'Example';
  output += "public class " + class_name + " {\n";
  this.increaseIndent();
  output += this.getIndent() + "public static void main(String[] args) {\n";
  this.increaseIndent();
  output += this.getIndent() + "try {\n";
  this.increaseIndent();
  output += this.getIndent() + this.const("developer_key") + " = open('DEVELOPER_KEY').read()\n"
  if (options['library'] != null) {
    output += this.getIndent() + "FreebaseClient " + this.var("freebase_client") + " = new FreebaseClient(" + this.const("developer_key");
    if (options['version'] != CodeGenerator.defaultApiVersion) {
      output += ", version='" + options['version'] + "')\n";
    } else {
      output +=  ");\n";
    }
  } else {
    var service_url = "https://" + options['domain'] + "/" + options['api'] + "/" + options['version'] + "/" + service;
    output += this.getIndent() + "String " + this.var("service_url") + " = '" + service_url + "'\n";
  }
  return output;
}
  
JavaCodeGenerator.prototype.generateClientEnd = function(params, options) {
  var output  = "";
  this.decreaseIndent();
  output += this.getIndent() + "} catch (Exception ex) {\n";
  this.increaseIndent();
  output += this.getIndent() + "ex.printStackTrace();\n";
  this.decreaseIndent();
  output += this.getIndent() + "}\n";
  this.decreaseIndent();
  output += this.getIndent() + "}\n";
  this.decreaseIndent();
  output += this.getIndent() + "}\n";
  this.decreaseIndent();
  return output;
}

JavaCodeGenerator.prototype.formatVariableName = function(name_parts, is_constant) {
  if (!is_constant) {
      name_parts[0] = name_parts[0].toLowerCase();
  }
  var var_name = name_parts.join(is_constant ? '_' : '');
  return is_constant ? var_name.toUpperCase() : var_name;
}

JavaCodeGenerator.prototype.var = function(key) {
  return this.formatVariableName(CodeGenerator.variableNames[key], false);
}

JavaCodeGenerator.prototype.const = function(key) {
  return this.formatVariableName(CodeGenerator.variableNames[key], true);
}
  
JavaCodeGenerator.prototype.getIndent = function() {
  return this.indent.join('');
}
  
JavaCodeGenerator.prototype.increaseIndent = function() {
  return this.indent.push(CodeGenerator.tab);
}
  
JavaCodeGenerator.prototype.decreaseIndent = function() {
  return this.indent.pop();
}
  
JavaCodeGenerator.prototype.generateMqlread = function(params, options) {
  var query = JSON.parse(params['query']);
  var multiresult_query = ((query instanceof Array) &amp;&amp; query.length == 1) || !params['cursor'];
  var output  = "";
  output += this.getIndent() + "String " + this.var("query") + " = " + this.formatMqlQuery(query) + ";\n";
  // mqlread with client library
  if (options['library'] != null) {
    // mqlreaditer
    if (params['cursor'] == '') {
      var filtered_params = this.code_generator.filterParams(params, ["query","cursor"]);
      output += this.getIndent() + "Iterator " + this.var("results") + " = " + this.var("freebase_client") + ".mqlreaditer(" + this.var("query");
      if (filtered_params.size() &gt; 0) {
        output += "," + this.formatParams(filtered_params, options) + ")\n\n";
      } else {
        output += ");\n";
      }
      if (multiresult_query) {
        output += "\n" + this.getIndent() + "for " + this.var("topic") + " in " + this.var("results") + ":\n" + CodeGenerator.tab;
      } else {
        output += this.getIndent() + "JSONObject " + this.var("topic") + " = " + this.var("response") + "['result']\n\n";
      }
    // mqlread
    } else {
      var filtered_params = this.code_generator.filterParams(params, ["query"]);
      output += this.getIndent() + "JSONObject " + this.var("response") + " = " + this.var("freebase_client") + ".mqlread(" + this.var("query");
      if (filtered_params.size() &gt; 0) {
        output += "," + this.formatParams(filtered_params, options) + ")\n\n";
      } else {
        output += ");\n";
      }
      if (multiresult_query) {
        output += "\n" + this.getIndent() + "for " + this.var("topic") + " in " + this.var("response") + "['result']:\n" + CodeGenerator.tab;
      } else {
        output += this.getIndent() + "JSONObject " + this.var("topic") + " = " + this.var("response") + "['result']\n\n";
      }
    }
  // mqlread without client library
  } else {
    var filtered_params = this.code_generator.filterParams(params, ["query"]);
    if (filtered_params.size() &gt; 0) {
      output += this.formatParams(filtered_params, options);
    }
    output += this.getIndent() + "String " + this.var("url") + " = " + this.var("service_url") + " + '?query=' + " + "URLEncoder.encode(" + this.var("query") + ".toJSONString(), \"UTF-8\")";
    if (filtered_params.size() &gt; 0) {
      output += "\n" + this.getIndent() + "             + URLEncoder.encode(" + this.var("params") + ".toJSONString(), \"UTF-8\")\;\n";
    } else {
      output += ";\n";
    }
    output += "\n" + this.getIndent() + "HttpClient httpclient = new DefaultHttpClient();\n";
    output += this.getIndent() + "HttpResponse " + this.var("response") + " = httpclient.execute(new HttpGet(" + this.var("url") + "));\n\n";
    if (multiresult_query) {
      output += this.getIndent() + "for (Object " + this.var("result") + " : " + this.var("results") + ") {\n";
      this.increaseIndent();
    } else {
      output += this.getIndent() + "JSONObject " + this.var("result") + " = " + this.var("response") + "['result']\n\n";
    }
  }
  var path = this.code_generator.getQuerySamplePath(query);
  output += this.getIndent() + "System.out.println(JsonPath.read(" + this.var("result") + ",\"" + this.formatPath(path) + "\").toString());\n";
  if (multiresult_query) {
    this.decreaseIndent();
    output += this.getIndent() + "}\n";
  }
  return output;
}
  
PythonCodeGenerator.prototype.generateMqlReadResults = function(params, options) {
  var output = "";
  if (options['library'] != null) {
  } else {
    output += this.getIndent() + "List params = new ArrayList();\n";
    output += this.getIndent() + "params.add(new BasicNameValuePair(\"query\", query));\n";
    output += this.getIndent() + "params.add(new BasicNameValuePair(\"cursor\", cursor));\n";
    output += this.getIndent() + "String url = service_url + \"?\" + URLEncodedUtils.format(params, \"UTF-8\");\n";
    output += this.getIndent() + "HttpGet request = new HttpGet(url);\n";
    output += this.getIndent() + "HttpResponse httpResponse = httpclient.execute(request);\n";
    output += this.getIndent() + "JSONObject response = (JSONObject)parser.parse(EntityUtils.toString(httpResponse.getEntity()));\n";
    output += this.getIndent() + "JSONArray results = (JSONArray)response.get(\"result\");\n";
    output += this.getIndent() + "for (Object " + this.var("result") + " : results) {\n";
    this.increaseIndent();
    output += this.getIndent() + "System.out.println(JsonPath.read(" + this.var("result") + ", \"" + this.formatPath(path) + "\").toString());\n";
    this.decreaseIndent();
    output += this.getIndent() + "}\n";
  }
  return output;
}

JavaCodeGenerator.prototype.formatParams = function(params, options) {
  var output  = "";
  output += this.getIndent() + "HttpParams params = new BasicHttpParams();\n";
  for (key in params.params) {
    output += this.getIndent() + "params.setParameter(\"" + key + "\", \"" + params[key] + "\");\n";
  }
  output += this.getIndent() + "method.setParams(params);\n";
  return output;
}
  
JavaCodeGenerator.prototype.formatMqlQuery = function(mql_query, params, options) {
  var query = this.code_generator.formatJSON(mql_query, false);
  if (query.length &gt; 80) {
    query = this.code_generator.formatJSON(mql_query, true);
  }
  return query;
}
  
JavaCodeGenerator.prototype.formatPath = function(path, params, options) {
  var output = "$";
  for (var i=0; i= 0) {
          output += "['" + key + "']";
      } else {
        output += "." + key;
      }
    } else {
      output += "[" + key + "]";
    }
  }
  return output;
} </p>

Comments

Hide