content: /**
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing,
   * software distributed under the License is distributed on an
   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   * KIND, either express or implied.  See the License for the
   * specific language governing permissions and limitations
   * under the License.
   */
  package org.apache.apex.malhar.contrib.elasticsearch;
  
  import java.io.IOException;
  
  import org.elasticsearch.action.percolate.PercolateResponse;
  import org.elasticsearch.common.xcontent.XContentBuilder;
  import org.elasticsearch.common.xcontent.XContentFactory;
  import org.elasticsearch.index.query.QueryBuilder;
  
  import com.datatorrent.netlet.util.DTThrowable;
  
  /**
   *
   * @since 2.1.0
   */
  public class ElasticSearchPercolatorStore extends ElasticSearchConnectable
  {
    private static final String PERCOLATOR_TYPE = ".percolator";
  
    ElasticSearchPercolatorStore(String hostName, int port)
    {
      setHostName(hostName);
      setPort(port);
    }
  
    public void registerPercolateQuery(String indexName, String queryName, QueryBuilder queryBuilder)
    {
      try {
  
        client.prepareIndex(indexName, PERCOLATOR_TYPE, queryName)
          .setSource(XContentFactory.jsonBuilder()
              .startObject()
              .field("query", queryBuilder)
              .endObject())
          .setRefresh(true)
          .execute().actionGet();
  
      } catch (IOException e) {
        DTThrowable.rethrow(e);
      }
    }
  
    public PercolateResponse percolate(String[] indexNames, String documentType, Object tuple)
    {
      XContentBuilder docBuilder;
      try {
  
        docBuilder = XContentFactory.jsonBuilder().startObject();
        docBuilder.field("doc").startObject(); //This is needed to designate the document
        docBuilder.field("content", tuple);
        docBuilder.endObject(); //End of the doc field
        docBuilder.endObject();//End of the JSON root object
  
        return client.preparePercolate().setIndices(indexNames)
            .setDocumentType(documentType)
            .setSource(docBuilder)
            .execute().actionGet();
      } catch (IOException e) {
        DTThrowable.rethrow(e);
      }
      return null;
    }
  }
  