/*
 * 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.lucene.index;

import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import java.io.IOException;
import java.util.Arrays;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.store.Directory;
import org.apache.lucene.tests.analysis.MockAnalyzer;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.BytesRef;
import org.junit.After;
import org.junit.Before;

/**
 * Tests that a useful exception is thrown when attempting to index a term that is too large
 *
 * @see IndexWriter#MAX_TERM_LENGTH
 */
public class TestExceedMaxTermLength extends LuceneTestCase {

  private static final int minTestTermLength = IndexWriter.MAX_TERM_LENGTH + 1;
  private static final int maxTestTermLength = IndexWriter.MAX_TERM_LENGTH * 2;

  Directory dir = null;

  @Before
  public void createDir() {
    dir = newDirectory();
  }

  @After
  public void destroyDir() throws IOException {
    dir.close();
    dir = null;
  }

  public void testTokenStream() throws Exception {

    MockAnalyzer mockAnalyzer = new MockAnalyzer(random());
    mockAnalyzer.setMaxTokenLength(Integer.MAX_VALUE);
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(random(), mockAnalyzer));
    try {
      final FieldType ft = new FieldType();
      ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
      ft.setStored(random().nextBoolean());
      ft.freeze();

      final Document doc = new Document();
      if (random().nextBoolean()) {
        // totally ok short field value
        doc.add(
            new Field(
                TestUtil.randomSimpleString(random(), 1, 10),
                TestUtil.randomSimpleString(random(), 1, 10),
                ft));
      }
      // problematic field
      final String name = TestUtil.randomSimpleString(random(), 1, 50);
      final String value =
          TestUtil.randomSimpleString(random(), minTestTermLength, maxTestTermLength);
      final Field f = new Field(name, value, ft);
      if (random().nextBoolean()) {
        // totally ok short field value
        doc.add(
            new Field(
                TestUtil.randomSimpleString(random(), 1, 10),
                TestUtil.randomSimpleString(random(), 1, 10),
                ft));
      }
      doc.add(f);

      IllegalArgumentException expected =
          expectThrows(
              IllegalArgumentException.class,
              () -> {
                w.addDocument(doc);
              });
      String maxLengthMsg = String.valueOf(IndexWriter.MAX_TERM_LENGTH);
      String msg = expected.getMessage();
      assertTrue(
          "IllegalArgumentException didn't mention 'immense term': " + msg,
          msg.contains("immense term"));
      assertTrue(
          "IllegalArgumentException didn't mention max length (" + maxLengthMsg + "): " + msg,
          msg.contains(maxLengthMsg));
      assertTrue(
          "IllegalArgumentException didn't mention field name (" + name + "): " + msg,
          msg.contains(name));
      assertTrue(
          "IllegalArgumentException didn't mention original message: " + msg,
          msg.contains("bytes can be at most") && msg.contains("in length; got"));
    } finally {
      w.close();
    }
  }

  public void testBinaryValue() throws Exception {

    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
    try {
      final FieldType ft = new FieldType();
      ft.setIndexOptions(
          RandomPicks.randomFrom(
              random(), Arrays.asList(IndexOptions.DOCS, IndexOptions.DOCS_AND_FREQS)));
      ft.setStored(random().nextBoolean());
      ft.setTokenized(false);
      ft.freeze();

      final Document doc = new Document();
      if (random().nextBoolean()) {
        // totally ok short field value
        doc.add(
            new Field(
                TestUtil.randomSimpleString(random(), 1, 10),
                TestUtil.randomBinaryTerm(random(), 10),
                ft));
      }
      // problematic field
      final String name = TestUtil.randomSimpleString(random(), 1, 50);
      final BytesRef value =
          TestUtil.randomBinaryTerm(
              random(), TestUtil.nextInt(random(), minTestTermLength, maxTestTermLength));
      final Field f = new Field(name, value, ft);
      if (random().nextBoolean()) {
        // totally ok short field value
        doc.add(
            new Field(
                TestUtil.randomSimpleString(random(), 1, 10),
                TestUtil.randomBinaryTerm(random(), 10),
                ft));
      }
      doc.add(f);

      IllegalArgumentException expected =
          expectThrows(
              IllegalArgumentException.class,
              () -> {
                w.addDocument(doc);
              });
      String maxLengthMsg = String.valueOf(IndexWriter.MAX_TERM_LENGTH);
      String msg = expected.getMessage();
      assertTrue(
          "IllegalArgumentException didn't mention 'immense term': " + msg,
          msg.contains("immense term"));
      assertTrue(
          "IllegalArgumentException didn't mention max length (" + maxLengthMsg + "): " + msg,
          msg.contains(maxLengthMsg));
      assertTrue(
          "IllegalArgumentException didn't mention field name (" + name + "): " + msg,
          msg.contains(name));
      assertTrue(
          "IllegalArgumentException didn't mention original message: " + msg,
          msg.contains("bytes can be at most") && msg.contains("in length; got"));
    } finally {
      w.close();
    }
  }
}
