/**
 * 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.drill.exec.server.rest;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

import javax.xml.bind.annotation.XmlRootElement;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.primitives.Primitives;
import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.exec.client.DrillClient;
import org.apache.drill.exec.coord.ClusterCoordinator;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.proto.UserBitShared;
import org.apache.drill.exec.record.RecordBatchLoader;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.rpc.RpcException;
import org.apache.drill.exec.rpc.user.ConnectionThrottle;
import org.apache.drill.exec.rpc.user.QueryDataBatch;
import org.apache.drill.exec.rpc.user.UserResultsListener;
import org.apache.drill.exec.vector.ValueVector;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import parquet.Preconditions;

@XmlRootElement
public class QueryWrapper {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(QueryWrapper.class);

  private String query;
  private String queryType;

  @JsonCreator
  public QueryWrapper(@JsonProperty("query") String query, @JsonProperty("queryType") String queryType) {
    this.query = query;
    this.queryType = queryType;
  }

  public String getQuery() {
    return query;
  }

  public String getQueryType() {
    return queryType;
  }

  public UserBitShared.QueryType getType() {
    UserBitShared.QueryType type = UserBitShared.QueryType.SQL;
    switch (queryType) {
      case "SQL" : type = UserBitShared.QueryType.SQL; break;
      case "LOGICAL" : type = UserBitShared.QueryType.LOGICAL; break;
      case "PHYSICAL" : type = UserBitShared.QueryType.PHYSICAL; break;
    }
    return type;
  }

  public QueryResult run(DrillConfig config, ClusterCoordinator coordinator, BufferAllocator allocator)
    throws Exception {
    try(DrillClient client = new DrillClient(config, coordinator, allocator)){
      Listener listener = new Listener(allocator);

      client.connect();
      client.runQuery(getType(), query, listener);

      listener.waitForCompletion();
      if (listener.results.isEmpty()) {
        listener.results.add(Maps.<String, Object>newHashMap());
      }
      final Map<String, Object> first = listener.results.get(0);
      for (String columnName : listener.columns) {
        if (!first.containsKey(columnName)) {
          first.put(columnName, null);
        }
      }

      return new QueryResult(listener.columns, listener.results);
    }
  }

  public static class QueryResult {
    public final Collection<String> columns;
    public final List<Map<String, Object>> rows;

    public QueryResult(Collection<String> columns, List<Map<String, Object>> rows) {
      this.columns = columns;
      this.rows = rows;
    }
  }

  @Override
  public String toString() {
    return "QueryRequest [queryType=" + queryType + ", query=" + query + "]";
  }


  private static class Listener implements UserResultsListener {
    private volatile Exception exception;
    private final CountDownLatch latch = new CountDownLatch(1);
    private final BufferAllocator allocator;
    public final List<Map<String, Object>> results = Lists.newArrayList();
    public final Set<String> columns = Sets.newLinkedHashSet();

    Listener(BufferAllocator allocator) {
      this.allocator = Preconditions.checkNotNull(allocator, "allocator cannot be null");
    }

    @Override
    public void submissionFailed(RpcException ex) {
      exception = ex;
      logger.error("Query Failed", ex);
      latch.countDown();
    }

    @Override
    public void queryCompleted() {
      latch.countDown();
    }

    @Override
    public void dataArrived(QueryDataBatch result, ConnectionThrottle throttle) {
      try {
        final int rows = result.getHeader().getRowCount();
        if (result.hasData()) {
          final RecordBatchLoader loader = new RecordBatchLoader(allocator);
          loader.load(result.getHeader().getDef(), result.getData());
          for (int i = 0; i < loader.getSchema().getFieldCount(); ++i) {
            columns.add(loader.getSchema().getColumn(i).getPath().getAsUnescapedPath());
          }
          for (int i = 0; i < rows; ++i) {
            final Map<String, Object> record = Maps.newHashMap();
            for (VectorWrapper<?> vw : loader) {
              final String field = vw.getValueVector().getMetadata().getNamePart().getName();
              final ValueVector.Accessor accessor = vw.getValueVector().getAccessor();
              final Object value = i < accessor.getValueCount() ? accessor.getObject(i) : null;
              final Object display = Primitives.isWrapperType(value.getClass()) ? value : value.toString();
              record.put(field, display);
            }
            results.add(record);
          }
        }
      } catch (SchemaChangeException e) {
        throw new RuntimeException(e);
      } finally {
        result.release();
      }
    }

    @Override
    public void queryIdArrived(UserBitShared.QueryId queryId) {
    }

    public void waitForCompletion() throws Exception {
      latch.await();
      if (exception != null) {
        throw exception;
      }
    }
  }
}

@@ -5805,16 +5805,33 @@
 isplay =
+ value == null %7C%7C
  Primiti

Fix null serialization issue