/*
 * 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.druid.segment.data;

import com.google.common.collect.Iterables;
import org.apache.druid.collections.ResourceHolder;
import org.apache.druid.java.util.common.ByteBufferUtils;
import org.apache.druid.java.util.common.io.Closer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RunWith(Parameterized.class)
public class CompressionStrategyTest
{
  @Parameterized.Parameters
  public static Iterable<Object[]> compressionStrategies()
  {
    return Iterables.transform(
        Arrays.asList(CompressionStrategy.noNoneValues()),
        compressionStrategy -> new Object[]{compressionStrategy}
    );
  }

  protected final CompressionStrategy compressionStrategy;

  public CompressionStrategyTest(CompressionStrategy compressionStrategy)
  {
    this.compressionStrategy = compressionStrategy;
  }

  // MUST be smaller than CompressedPools.BUFFER_SIZE
  private static final int DATA_SIZER = 0xFFFF;
  private static byte[] originalData;

  @BeforeClass
  public static void setupClass()
  {
    originalData = new byte[DATA_SIZER];
    Random random = new Random(54671457);
    random.nextBytes(originalData);
  }

  private Closer closer;

  @Before
  public void createCloser()
  {
    closer = Closer.create();
  }

  @After
  public void closeCloser() throws IOException
  {
    closer.close();
  }

  @Test
  public void testBasicOperations()
  {
    ByteBuffer compressionOut = compressionStrategy.getCompressor().allocateOutBuffer(originalData.length, closer);
    ByteBuffer compressionIn = compressionStrategy.getCompressor().allocateInBuffer(originalData.length, closer);
    try (final ResourceHolder<ByteBuffer> holder = ByteBufferUtils.allocateDirect(originalData.length)) {
      final ByteBuffer output = holder.get();
      compressionIn.put(originalData);
      compressionIn.rewind();
      ByteBuffer compressed = compressionStrategy.getCompressor().compress(compressionIn, compressionOut);
      compressionStrategy.getDecompressor().decompress(compressed, compressed.remaining(), output);
      byte[] checkArray = new byte[DATA_SIZER];
      output.get(checkArray);
      Assert.assertArrayEquals("Uncompressed data does not match", originalData, checkArray);
    }
  }

  @Test(timeout = 60_000L)
  public void testConcurrency() throws Exception
  {
    final int numThreads = 20;
    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(numThreads);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
        numThreads,
        numThreads,
        100,
        TimeUnit.MILLISECONDS,
        queue
    );
    Collection<Future<Boolean>> results = new ArrayList<>();
    for (int i = 0; i < numThreads; ++i) {
      results.add(
          threadPoolExecutor.submit(
              () -> {
                ByteBuffer compressionOut = compressionStrategy.getCompressor()
                                                               .allocateOutBuffer(originalData.length, closer);
                ByteBuffer compressionIn = compressionStrategy.getCompressor()
                                                              .allocateInBuffer(originalData.length, closer);
                try {
                  compressionIn.put(originalData);
                  compressionIn.position(0);
                  ByteBuffer compressed = compressionStrategy.getCompressor().compress(compressionIn, compressionOut);
                  ByteBuffer output = compressionStrategy.getCompressor().allocateOutBuffer(originalData.length, closer);
                  compressionStrategy.getDecompressor().decompress(compressed, compressed.remaining(), output);
                  byte[] checkArray = new byte[DATA_SIZER];
                  output.get(checkArray);
                  Assert.assertArrayEquals("Uncompressed data does not match", originalData, checkArray);
                  return true;
                }
                finally {
                  ByteBufferUtils.free(compressionIn);
                  ByteBufferUtils.free(compressionOut);
                }
              }
          )
      );
    }
    threadPoolExecutor.shutdown();
    for (Future<Boolean> result : results) {
      Assert.assertTrue(result.get());
    }
  }
}

@@ -4470,32 +4470,8 @@
 r);%0A
-                try %7B%0A  
     
@@ -4523,34 +4523,32 @@
                 
-  
 compressionIn.po
@@ -4566,34 +4566,32 @@
                 
- 
- 
 ByteBuffer compr
@@ -4667,34 +4667,32 @@
 ompressionOut);%0A
-  
                 
@@ -4803,34 +4803,32 @@
                 
- 
- 
 compressionStrat
@@ -4901,26 +4901,24 @@
 ), output);%0A
-  
             
@@ -4975,26 +4975,24 @@
             
-  
 output.get(c
@@ -4995,34 +4995,32 @@
 et(checkArray);%0A
-  
                 
@@ -5123,18 +5123,16 @@
         
-  
 return t
@@ -5140,181 +5140,8 @@
 ue;%0A
-                %7D%0A                finally %7B%0A                  ByteBufferUtils.free(compressionIn);%0A                  ByteBufferUtils.free(compressionOut);%0A                %7D%0A
     

fix compression-strategy-test (#12575)