예제 #1
0
  /**
   * Execute the request and return the POJO that represent the response.
   *
   * @param <T> The POJO that represents the response object
   * @param params the request parameters
   * @param operation the alchemy operation
   * @param returnType the POJO class to be parsed from the response
   * @param acceptedFormats the accepted input formats e.g. "html", "text"...
   * @return the POJO object that represent the response
   */
  private <T> T executeRequest(
      Map<String, Object> params,
      AlchemyAPI operation,
      Class<T> returnType,
      String... acceptedFormats) {
    // Get the input format and check for missing parameters
    String format = getInputFormat(params, acceptedFormats);
    // Get the path that represent this operation based on the operation and format
    String path = AlchemyEndPoints.getPath(operation, format);

    // Return json
    params.put(OUTPUT_MODE, "json");

    // Prevent jsonp to be returned
    params.remove(JSONP);

    Request request = Request.Post(path);
    for (String param : params.keySet()) {
      request.withForm(param, params.get(param));
    }
    HttpRequestBase requestBase = request.build();
    try {
      HttpResponse response = execute(requestBase);
      return ResponseUtil.getObject(response, returnType);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  /**
   * Classifies the images against the label groups and labels. The response includes a score for a
   * label if the score meets the minimum threshold of 0.5. If no score meets the threshold for an
   * image, no labels are returned.
   *
   * @param image the file image
   * @param labelSet the labels to classify against
   * @return the visual recognition images
   */
  public RecognizedImage recognize(final File image, final LabelSet labelSet) {
    if (image == null) throw new IllegalArgumentException("image can not be null");
    try {

      Request request = Request.Post("/v1/tag/recognize");

      MultipartEntity reqEntity = new MultipartEntity();

      // Set the image_file
      FileBody bin = new FileBody(image);
      reqEntity.addPart(IMG_FILE, bin);

      if (labelSet != null) {
        StringBody labels =
            new StringBody(GsonSingleton.getGson().toJson(labelSet), Charset.forName("UTF-8"));

        // Set the labels_to_check
        reqEntity.addPart(LABELS_TO_CHECK, labels);
      }
      request.withEntity(reqEntity);

      HttpResponse response = execute(request.build());
      String resultJson = ResponseUtil.getString(response);
      VisualRecognitionImages recognizedImages =
          GsonSingleton.getGson().fromJson(resultJson, VisualRecognitionImages.class);
      return recognizedImages.getImages().get(0);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
예제 #3
0
  /**
   * Returns a CSV profile.
   *
   * @param options the {@link ProfileOptions}
   * @param includeHeaders if true returns the CSV headers
   * @return the CSV profile
   */
  public String getProfileAsCSV(final ProfileOptions options, final boolean includeHeaders) {
    final RequestBuilder requestBuilder = buildProfileRequest(options);

    requestBuilder.withHeader(HttpHeaders.ACCEPT, HttpMediaType.TEXT_CSV);
    requestBuilder.withQuery(HEADERS, includeHeaders);
    final Response response = execute(requestBuilder.build());
    return ResponseUtil.getString(response);
  }
 /**
  * Gets the labels and label groups.
  *
  * @return the labels and label groups
  */
 public LabelSet getLabelSet() {
   HttpRequestBase request = Request.Get("/v1/tag/labels").build();
   try {
     HttpResponse response = execute(request);
     String jsonLabelSet = ResponseUtil.getString(response);
     return GsonSingleton.getGson().fromJson(jsonLabelSet, LabelSet.class);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
예제 #5
0
  /**
   * Converts a document and returns an {@link InputStream}.
   *
   * @param document The file to convert
   * @param mediaType Internet media type of the file
   * @param conversionTarget The conversion target to use
   * @param customConfig The additional config params to use
   * @return Converted document in the specified format
   * @see {@link HttpMediaType} for available media types
   */
  private InputStream convertDocument(
      final File document,
      final String mediaType,
      final ConversionTarget conversionTarget,
      final JsonObject customConfig) {

    if (document == null || !document.exists())
      throw new IllegalArgumentException("document cannot be null and must exist");

    if (customConfig == null) throw new NullPointerException("custom config must not be null");

    final String type =
        mediaType != null ? mediaType : ConversionUtils.getMediaTypeFromFile(document);
    if (type == null) {
      throw new RuntimeException("mediaType cannot be null or empty");
    } else if (!ConversionUtils.isValidMediaType(type)) {
      throw new IllegalArgumentException("file with the given media type is not supported");
    }

    final JsonObject configJson = new JsonObject();
    // Do this since we shouldn't mutate customConfig
    for (Map.Entry<String, JsonElement> entry : customConfig.entrySet()) {
      configJson.add(entry.getKey(), entry.getValue());
    }
    // Add or override the conversion target
    configJson.addProperty(CONVERSION_TARGET, conversionTarget.toString());

    final MediaType mType = MediaType.parse(type);
    final RequestBody body =
        new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addPart(
                Headers.of(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"config\""),
                RequestBody.create(HttpMediaType.JSON, configJson.toString()))
            .addPart(
                Headers.of(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"file\""),
                RequestBody.create(mType, document))
            .build();

    final Request request =
        RequestBuilder.post(CONVERT_DOCUMENT_PATH)
            .withQuery(VERSION, versionDate)
            .withBody(body)
            .build();

    final Response response = execute(request);
    return ResponseUtil.getInputStream(response);
  }
예제 #6
0
 /**
  * Execute the request and return the POJO that represent the response.
  *
  * @param <T> The POJO that represents the response object
  * @param resourcePath the resource path
  * @param params the request parameters
  * @param returnType the POJO class to be parsed from the response
  * @return the POJO object that represent the response
  */
 private <T> T executeRequest(
     String resourcePath, Map<String, Object> params, Class<T> returnType) {
   Request request = Request.Get(resourcePath);
   if (params != null && !params.isEmpty()) {
     for (Map.Entry<String, Object> entry : params.entrySet()) {
       request.withQuery(entry.getKey(), entry.getValue());
     }
   }
   HttpRequestBase requestBase = request.build();
   try {
     HttpResponse response = execute(requestBase);
     return ResponseUtil.getObject(response, returnType);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
예제 #7
0
  /**
   * Identifies concepts in a piece of text.
   *
   * @param parameters The parameters to be used in the service call, account_id, graph and text are
   *     required.
   *     <ul>
   *       <li>String account_id - The account identifier.<br>
   *       <li>String graph - The graph name.<br>
   *       <li>String text - The text to annotate.<br>
   *     </ul>
   *
   * @return {@link Annotations}
   */
  public Annotations annotateText(Map<String, Object> parameters) {
    Validate.notNull(parameters.get(ACCOUNT_ID), "account_id can't be null");
    Validate.notNull(parameters.get(GRAPH), "graph can't be null");
    Validate.notNull(parameters.get(TEXT), "text can't be null");
    String graphId =
        createGraphIdPath((String) parameters.get(ACCOUNT_ID), (String) parameters.get(GRAPH));

    HttpRequestBase request =
        Request.Post(graphId + ANNOTATE_TEXT_PATH)
            .withContent((String) parameters.get(TEXT), MediaType.TEXT_PLAIN)
            .withHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
            .build();

    try {
      HttpResponse response = execute(request);
      Annotations annotations =
          GsonSingleton.getGson().fromJson(ResponseUtil.getString(response), Annotations.class);
      return annotations;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }