Пример #1
0
  /**
   * Translate text
   *
   * @param text The text to be translated
   * @param target The target language code, for example "en"
   * @param source The source language code, for example "nl". Optional
   * @return
   * @throws Exception
   */
  public String translate(
      @Name("text") String text,
      @Name("target") String target,
      @Name("source") @Required(false) String source)
      throws Exception {
    String key = getState().get("key", String.class);
    if (key == null) {
      throw new Exception(
          "No valid API Key set. "
              + "Google Translate API is a paid service "
              + "and requires an API Key for billing.");
    }

    String url =
        TRANSLATE_API_URL
            + "?q="
            + URLEncoder.encode(text, "UTF-8")
            + "&key="
            + URLEncoder.encode(key, "UTF-8")
            + "&target="
            + URLEncoder.encode(target, "UTF-8");
    if (source != null) {
      url += "&source=" + URLEncoder.encode(source, "UTF-8");
    }
    String resp = HttpUtil.get(url);

    return resp;
  }
Пример #2
0
  /**
   * Evaluate given expression For example expr="2.5 + 3 / sqrt(16)" will return "3.25"
   *
   * @param expr
   * @return result
   * @throws Exception
   */
  public String eval(@Name("expr") String expr) throws Exception {
    String url = CALC_API_URL + "?q=" + URLEncoder.encode(expr, "UTF-8");
    String resp = HttpUtil.get(url);

    // the field names in resp are not enclosed by quotes :(
    resp = resp.replaceAll("lhs:", "\"lhs\":");
    resp = resp.replaceAll("rhs:", "\"rhs\":");
    resp = resp.replaceAll("error:", "\"error\":");
    resp = resp.replaceAll("icc:", "\"icc\":");

    ObjectMapper mapper = JOM.getInstance();
    ObjectNode json = mapper.readValue(resp, ObjectNode.class);

    String error = json.get("error").asText();
    if (error != null && !error.isEmpty()) {
      throw new Exception(error);
    }

    String rhs = json.get("rhs").asText();
    return rhs;
  }