text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf.test;
import com.google.protobuf.*;

import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.test.UnittestImport;
import protobuf_unittest.EnumWithNoOuter;
import protobuf_unittest.MessageWithNoOuter;
import protobuf_unittest.MultipleFilesTestProto;
import protobuf_unittest.NestedExtension.MyNestedExtension;
import protobuf_unittest.NonNestedExtension;
import protobuf_unittest.NonNestedExtension.MessageToBeExtended;
import protobuf_unittest.NonNestedExtension.MyNonNestedExtension;
import protobuf_unittest.ServiceWithNoOuter;
import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
import protobuf_unittest.UnittestOptimizeFor.TestOptionalOptimizedForSize;
import protobuf_unittest.UnittestOptimizeFor.TestRequiredOptimizedForSize;
import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.ForeignEnum;
import protobuf_unittest.UnittestProto.ForeignMessage;
import protobuf_unittest.UnittestProto.ForeignMessageOrBuilder;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;
import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestProto.TestUnpackedTypes;

import junit.framework.TestCase;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Unit test for generated messages and generated code.  See also
 * {@link MessageTest}, which tests some generated message functionality.
 *
 * @author kenton@google.com Kenton Varda
 */
public class GeneratedMessageTest extends TestCase {
  TestUtil.ReflectionTester reflectionTester =
    new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);

  public void testDefaultInstance() throws Exception {
    assertSame(TestAllTypes.getDefaultInstance(),
               TestAllTypes.getDefaultInstance().getDefaultInstanceForType());
    assertSame(TestAllTypes.getDefaultInstance(),
               TestAllTypes.newBuilder().getDefaultInstanceForType());
  }

  public void testMessageOrBuilder() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    TestAllTypes message = builder.build();
    TestUtil.assertAllFieldsSet(message);
  }

  public void testUsingBuilderMultipleTimes() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    // primitive field scalar and repeated
    builder.setOptionalSfixed64(100);
    builder.addRepeatedInt32(100);
    // enum field scalar and repeated
    builder.setOptionalImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
    builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
    // proto field scalar and repeated
    builder.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(1));
    builder.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(1));

    TestAllTypes value1 = builder.build();

    assertEquals(100, value1.getOptionalSfixed64());
    assertEquals(100, value1.getRepeatedInt32(0));
    assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
        value1.getOptionalImportEnum());
    assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
        value1.getRepeatedImportEnum(0));
    assertEquals(1, value1.getOptionalForeignMessage().getC());
    assertEquals(1, value1.getRepeatedForeignMessage(0).getC());

    // Make sure that builder didn't update previously created values
    builder.setOptionalSfixed64(200);
    builder.setRepeatedInt32(0, 200);
    builder.setOptionalImportEnum(UnittestImport.ImportEnum.IMPORT_FOO);
    builder.setRepeatedImportEnum(0, UnittestImport.ImportEnum.IMPORT_FOO);
    builder.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(2));
    builder.setRepeatedForeignMessage(0, ForeignMessage.newBuilder().setC(2));

    TestAllTypes value2 = builder.build();

    // Make sure value1 didn't change.
    assertEquals(100, value1.getOptionalSfixed64());
    assertEquals(100, value1.getRepeatedInt32(0));
    assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
        value1.getOptionalImportEnum());
    assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
        value1.getRepeatedImportEnum(0));
    assertEquals(1, value1.getOptionalForeignMessage().getC());
    assertEquals(1, value1.getRepeatedForeignMessage(0).getC());

    // Make sure value2 is correct
    assertEquals(200, value2.getOptionalSfixed64());
    assertEquals(200, value2.getRepeatedInt32(0));
    assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
        value2.getOptionalImportEnum());
    assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
        value2.getRepeatedImportEnum(0));
    assertEquals(2, value2.getOptionalForeignMessage().getC());
    assertEquals(2, value2.getRepeatedForeignMessage(0).getC());
  }

  public void testRepeatedArraysAreImmutable() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    builder.addRepeatedInt32(100);
    builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
    builder.addRepeatedForeignMessage(ForeignMessage.getDefaultInstance());
    assertIsUnmodifiable(builder.getRepeatedInt32List());
    assertIsUnmodifiable(builder.getRepeatedImportEnumList());
    assertIsUnmodifiable(builder.getRepeatedForeignMessageList());
    assertIsUnmodifiable(builder.getRepeatedFloatList());

    TestAllTypes value = builder.build();
    assertIsUnmodifiable(value.getRepeatedInt32List());
    assertIsUnmodifiable(value.getRepeatedImportEnumList());
    assertIsUnmodifiable(value.getRepeatedForeignMessageList());
    assertIsUnmodifiable(value.getRepeatedFloatList());
  }

  public void testParsedMessagesAreImmutable() throws Exception {
    TestAllTypes value = TestAllTypes.PARSER.parseFrom(
        TestUtil.getAllSet().toByteString());
    assertIsUnmodifiable(value.getRepeatedInt32List());
    assertIsUnmodifiable(value.getRepeatedInt64List());
    assertIsUnmodifiable(value.getRepeatedUint32List());
    assertIsUnmodifiable(value.getRepeatedUint64List());
    assertIsUnmodifiable(value.getRepeatedSint32List());
    assertIsUnmodifiable(value.getRepeatedSint64List());
    assertIsUnmodifiable(value.getRepeatedFixed32List());
    assertIsUnmodifiable(value.getRepeatedFixed64List());
    assertIsUnmodifiable(value.getRepeatedSfixed32List());
    assertIsUnmodifiable(value.getRepeatedSfixed64List());
    assertIsUnmodifiable(value.getRepeatedFloatList());
    assertIsUnmodifiable(value.getRepeatedDoubleList());
    assertIsUnmodifiable(value.getRepeatedBoolList());
    assertIsUnmodifiable(value.getRepeatedStringList());
    assertIsUnmodifiable(value.getRepeatedBytesList());
    assertIsUnmodifiable(value.getRepeatedGroupList());
    assertIsUnmodifiable(value.getRepeatedNestedMessageList());
    assertIsUnmodifiable(value.getRepeatedForeignMessageList());
    assertIsUnmodifiable(value.getRepeatedImportMessageList());
    assertIsUnmodifiable(value.getRepeatedNestedEnumList());
    assertIsUnmodifiable(value.getRepeatedForeignEnumList());
    assertIsUnmodifiable(value.getRepeatedImportEnumList());
  }

  private void assertIsUnmodifiable(List<?> list) {
    if (list == Collections.emptyList()) {
      // OKAY -- Need to check this b/c EmptyList allows you to call clear.
    } else {
      try {
        list.clear();
        fail("List wasn't immutable");
      } catch (UnsupportedOperationException e) {
        // good
      }
    }
  }

  public void testSettersRejectNull() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    try {
      builder.setOptionalString(null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.setOptionalBytes(null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.setOptionalNestedMessage((TestAllTypes.NestedMessage) null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.setOptionalNestedMessage(
          (TestAllTypes.NestedMessage.Builder) null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.setOptionalNestedEnum(null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.addRepeatedString(null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.addRepeatedBytes(null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.addRepeatedNestedMessage((TestAllTypes.NestedMessage) null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.addRepeatedNestedMessage(
          (TestAllTypes.NestedMessage.Builder) null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.addRepeatedNestedEnum(null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
  }

  public void testRepeatedSetters() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    TestUtil.modifyRepeatedFields(builder);
    TestAllTypes message = builder.build();
    TestUtil.assertRepeatedFieldsModified(message);
  }

  public void testRepeatedSettersRejectNull() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();

    builder.addRepeatedString("one");
    builder.addRepeatedString("two");
    try {
      builder.setRepeatedString(1, null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }

    builder.addRepeatedBytes(TestUtil.toBytes("one"));
    builder.addRepeatedBytes(TestUtil.toBytes("two"));
    try {
      builder.setRepeatedBytes(1, null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }

    builder.addRepeatedNestedMessage(
      TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
    builder.addRepeatedNestedMessage(
      TestAllTypes.NestedMessage.newBuilder().setBb(456).build());
    try {
      builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage) null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
    try {
      builder.setRepeatedNestedMessage(
          1, (TestAllTypes.NestedMessage.Builder) null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }

    builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.FOO);
    builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR);
    try {
      builder.setRepeatedNestedEnum(1, null);
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
  }

  public void testRepeatedAppend() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();

    builder.addAllRepeatedInt32(Arrays.asList(1, 2, 3, 4));
    builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ));

    ForeignMessage foreignMessage =
        ForeignMessage.newBuilder().setC(12).build();
    builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage));

    TestAllTypes message = builder.build();
    assertEquals(message.getRepeatedInt32List(), Arrays.asList(1, 2, 3, 4));
    assertEquals(message.getRepeatedForeignEnumList(),
        Arrays.asList(ForeignEnum.FOREIGN_BAZ));
    assertEquals(1, message.getRepeatedForeignMessageCount());
    assertEquals(12, message.getRepeatedForeignMessage(0).getC());
  }

  public void testRepeatedAppendRejectsNull() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();

    ForeignMessage foreignMessage =
        ForeignMessage.newBuilder().setC(12).build();
    try {
      builder.addAllRepeatedForeignMessage(
          Arrays.asList(foreignMessage, (ForeignMessage) null));
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }

    try {
      builder.addAllRepeatedForeignEnum(
          Arrays.asList(ForeignEnum.FOREIGN_BAZ, null));
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }

    try {
      builder.addAllRepeatedString(Arrays.asList("one", null));
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }

    try {
      builder.addAllRepeatedBytes(Arrays.asList(TestUtil.toBytes("one"), null));
      fail("Exception was not thrown");
    } catch (NullPointerException e) {
      // We expect this exception.
    }
  }

  public void testSettingForeignMessageUsingBuilder() throws Exception {
    TestAllTypes message = TestAllTypes.newBuilder()
        // Pass builder for foreign message instance.
        .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123))
        .build();
    TestAllTypes expectedMessage = TestAllTypes.newBuilder()
        // Create expected version passing foreign message instance explicitly.
        .setOptionalForeignMessage(
            ForeignMessage.newBuilder().setC(123).build())
        .build();
    // TODO(ngd): Upgrade to using real #equals method once implemented
    assertEquals(expectedMessage.toString(), message.toString());
  }

  public void testSettingRepeatedForeignMessageUsingBuilder() throws Exception {
    TestAllTypes message = TestAllTypes.newBuilder()
        // Pass builder for foreign message instance.
        .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456))
        .build();
    TestAllTypes expectedMessage = TestAllTypes.newBuilder()
        // Create expected version passing foreign message instance explicitly.
        .addRepeatedForeignMessage(
            ForeignMessage.newBuilder().setC(456).build())
        .build();
    assertEquals(expectedMessage.toString(), message.toString());
  }

  public void testDefaults() throws Exception {
    TestUtil.assertClear(TestAllTypes.getDefaultInstance());
    TestUtil.assertClear(TestAllTypes.newBuilder().build());

    TestExtremeDefaultValues message =
        TestExtremeDefaultValues.getDefaultInstance();
    assertEquals("\u1234", message.getUtf8String());
    assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble());
    assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble());
    assertTrue(Double.isNaN(message.getNanDouble()));
    assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat());
    assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat());
    assertTrue(Float.isNaN(message.getNanFloat()));
    assertEquals("? ? ?? ?? ??? ??/ ??-", message.getCppTrigraph());
  }

  public void testClear() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.assertClear(builder);
    TestUtil.setAllFields(builder);
    builder.clear();
    TestUtil.assertClear(builder);
  }

  public void testReflectionGetters() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    reflectionTester.assertAllFieldsSetViaReflection(builder);

    TestAllTypes message = builder.build();
    reflectionTester.assertAllFieldsSetViaReflection(message);
  }

  public void testReflectionSetters() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    reflectionTester.setAllFieldsViaReflection(builder);
    TestUtil.assertAllFieldsSet(builder);

    TestAllTypes message = builder.build();
    TestUtil.assertAllFieldsSet(message);
  }

  public void testReflectionSettersRejectNull() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    reflectionTester.assertReflectionSettersRejectNull(builder);
  }

  public void testReflectionRepeatedSetters() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    reflectionTester.setAllFieldsViaReflection(builder);
    reflectionTester.modifyRepeatedFieldsViaReflection(builder);
    TestUtil.assertRepeatedFieldsModified(builder);

    TestAllTypes message = builder.build();
    TestUtil.assertRepeatedFieldsModified(message);
  }

  public void testReflectionRepeatedSettersRejectNull() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    reflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
  }

  public void testReflectionDefaults() throws Exception {
    reflectionTester.assertClearViaReflection(
      TestAllTypes.getDefaultInstance());
    reflectionTester.assertClearViaReflection(
      TestAllTypes.newBuilder().build());
  }

  public void testEnumInterface() throws Exception {
    assertTrue(TestAllTypes.getDefaultInstance().getDefaultNestedEnum()
        instanceof ProtocolMessageEnum);
  }

  public void testEnumMap() throws Exception {
    Internal.EnumLiteMap<ForeignEnum> map = ForeignEnum.internalGetValueMap();

    for (ForeignEnum value : ForeignEnum.values()) {
      assertEquals(value, map.findValueByNumber(value.getNumber()));
    }

    assertTrue(map.findValueByNumber(12345) == null);
  }

  public void testParsePackedToUnpacked() throws Exception {
    TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder();
    TestUnpackedTypes message =
      builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
    TestUtil.assertUnpackedFieldsSet(message);
  }

  public void testParseUnpackedToPacked() throws Exception {
    TestPackedTypes.Builder builder = TestPackedTypes.newBuilder();
    TestPackedTypes message =
      builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
    TestUtil.assertPackedFieldsSet(message);
  }

  // =================================================================
  // Extensions.

  TestUtil.ReflectionTester extensionsReflectionTester =
    new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
                                  TestUtil.getExtensionRegistry());

  public void testExtensionMessageOrBuilder() throws Exception {
    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
    TestUtil.setAllExtensions(builder);
    TestAllExtensions message = builder.build();
    TestUtil.assertAllExtensionsSet(message);
  }

  public void testExtensionRepeatedSetters() throws Exception {
    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
    TestUtil.setAllExtensions(builder);
    TestUtil.modifyRepeatedExtensions(builder);
    TestAllExtensions message = builder.build();
    TestUtil.assertRepeatedExtensionsModified(message);
  }

  public void testExtensionDefaults() throws Exception {
    TestUtil.assertExtensionsClear(TestAllExtensions.getDefaultInstance());
    TestUtil.assertExtensionsClear(TestAllExtensions.newBuilder().build());
  }

  public void testExtensionReflectionGetters() throws Exception {
    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
    TestUtil.setAllExtensions(builder);
    extensionsReflectionTester.assertAllFieldsSetViaReflection(builder);

    TestAllExtensions message = builder.build();
    extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
  }

  public void testExtensionReflectionSetters() throws Exception {
    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
    extensionsReflectionTester.setAllFieldsViaReflection(builder);
    TestUtil.assertAllExtensionsSet(builder);

    TestAllExtensions message = builder.build();
    TestUtil.assertAllExtensionsSet(message);
  }

  public void testExtensionReflectionSettersRejectNull() throws Exception {
    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
    extensionsReflectionTester.assertReflectionSettersRejectNull(builder);
  }

  public void testExtensionReflectionRepeatedSetters() throws Exception {
    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
    extensionsReflectionTester.setAllFieldsViaReflection(builder);
    extensionsReflectionTester.modifyRepeatedFieldsViaReflection(builder);
    TestUtil.assertRepeatedExtensionsModified(builder);

    TestAllExtensions message = builder.build();
    TestUtil.assertRepeatedExtensionsModified(message);
  }

  public void testExtensionReflectionRepeatedSettersRejectNull()
      throws Exception {
    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
    extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(
        builder);
  }

  public void testExtensionReflectionDefaults() throws Exception {
    extensionsReflectionTester.assertClearViaReflection(
      TestAllExtensions.getDefaultInstance());
    extensionsReflectionTester.assertClearViaReflection(
      TestAllExtensions.newBuilder().build());
  }

  public void testClearExtension() throws Exception {
    // clearExtension() is not actually used in TestUtil, so try it manually.
    assertFalse(
      TestAllExtensions.newBuilder()
        .setExtension(UnittestProto.optionalInt32Extension, 1)
        .clearExtension(UnittestProto.optionalInt32Extension)
        .hasExtension(UnittestProto.optionalInt32Extension));
    assertEquals(0,
      TestAllExtensions.newBuilder()
        .addExtension(UnittestProto.repeatedInt32Extension, 1)
        .clearExtension(UnittestProto.repeatedInt32Extension)
        .getExtensionCount(UnittestProto.repeatedInt32Extension));
  }

  public void testExtensionCopy() throws Exception {
    TestAllExtensions original = TestUtil.getAllExtensionsSet();
    TestAllExtensions copy = TestAllExtensions.newBuilder(original).build();
    TestUtil.assertAllExtensionsSet(copy);
  }

  public void testExtensionMergeFrom() throws Exception {
    TestAllExtensions original =
      TestAllExtensions.newBuilder()
        .setExtension(UnittestProto.optionalInt32Extension, 1).build();
    TestAllExtensions merged =
        TestAllExtensions.newBuilder().mergeFrom(original).build();
    assertTrue(merged.hasExtension(UnittestProto.optionalInt32Extension));
    assertEquals(
        1, (int) merged.getExtension(UnittestProto.optionalInt32Extension));
  }

  // =================================================================
  // multiple_files_test

  public void testMultipleFilesOption() throws Exception {
    // We mostly just want to check that things compile.
    MessageWithNoOuter message =
      MessageWithNoOuter.newBuilder()
        .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1))
        .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1))
        .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ)
        .setForeignEnum(EnumWithNoOuter.BAR)
        .build();
    assertEquals(message, MessageWithNoOuter.parseFrom(message.toByteString()));

    assertEquals(MultipleFilesTestProto.getDescriptor(),
                 MessageWithNoOuter.getDescriptor().getFile());

    Descriptors.FieldDescriptor field =
      MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum");
    assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(),
                 message.getField(field));

    assertEquals(MultipleFilesTestProto.getDescriptor(),
                 ServiceWithNoOuter.getDescriptor().getFile());

    assertFalse(
      TestAllExtensions.getDefaultInstance().hasExtension(
        MultipleFilesTestProto.extensionWithOuter));
  }

  public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize()
    throws Exception {
    TestOptionalOptimizedForSize message =
        TestOptionalOptimizedForSize.getDefaultInstance();
    assertTrue(message.isInitialized());

    message = TestOptionalOptimizedForSize.newBuilder().setO(
        TestRequiredOptimizedForSize.newBuilder().buildPartial()
        ).buildPartial();
    assertFalse(message.isInitialized());

    message = TestOptionalOptimizedForSize.newBuilder().setO(
        TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial()
        ).buildPartial();
    assertTrue(message.isInitialized());
  }

  public void testUninitializedExtensionInOptimizedForSize()
      throws Exception {
    TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder();
    builder.setExtension(TestOptimizedForSize.testExtension2,
        TestRequiredOptimizedForSize.newBuilder().buildPartial());
    assertFalse(builder.isInitialized());
    assertFalse(builder.buildPartial().isInitialized());

    builder = TestOptimizedForSize.newBuilder();
    builder.setExtension(TestOptimizedForSize.testExtension2,
        TestRequiredOptimizedForSize.newBuilder().setX(10).buildPartial());
    assertTrue(builder.isInitialized());
    assertTrue(builder.buildPartial().isInitialized());
  }

  public void testToBuilder() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    TestAllTypes message = builder.build();
    TestUtil.assertAllFieldsSet(message);
    TestUtil.assertAllFieldsSet(message.toBuilder().build());
  }

  public void testFieldConstantValues() throws Exception {
    assertEquals(TestAllTypes.NestedMessage.BB_FIELD_NUMBER, 1);
    assertEquals(TestAllTypes.OPTIONAL_INT32_FIELD_NUMBER, 1);
    assertEquals(TestAllTypes.OPTIONALGROUP_FIELD_NUMBER, 16);
    assertEquals(TestAllTypes.OPTIONAL_NESTED_MESSAGE_FIELD_NUMBER, 18);
    assertEquals(TestAllTypes.OPTIONAL_NESTED_ENUM_FIELD_NUMBER, 21);
    assertEquals(TestAllTypes.REPEATED_INT32_FIELD_NUMBER, 31);
    assertEquals(TestAllTypes.REPEATEDGROUP_FIELD_NUMBER, 46);
    assertEquals(TestAllTypes.REPEATED_NESTED_MESSAGE_FIELD_NUMBER, 48);
    assertEquals(TestAllTypes.REPEATED_NESTED_ENUM_FIELD_NUMBER, 51);
  }

  public void testExtensionConstantValues() throws Exception {
    assertEquals(UnittestProto.TestRequired.SINGLE_FIELD_NUMBER, 1000);
    assertEquals(UnittestProto.TestRequired.MULTI_FIELD_NUMBER, 1001);
    assertEquals(UnittestProto.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1);
    assertEquals(UnittestProto.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16);
    assertEquals(
      UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18);
    assertEquals(UnittestProto.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 21);
    assertEquals(UnittestProto.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31);
    assertEquals(UnittestProto.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46);
    assertEquals(
      UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48);
    assertEquals(UnittestProto.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 51);
  }

  public void testRecursiveMessageDefaultInstance() throws Exception {
    UnittestProto.TestRecursiveMessage message =
        UnittestProto.TestRecursiveMessage.getDefaultInstance();
    assertTrue(message != null);
    assertTrue(message.getA() != null);
    assertTrue(message.getA() == message);
  }

  public void testSerialize() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    TestAllTypes expected = builder.build();
    ObjectOutputStream out = new ObjectOutputStream(baos);
    try {
      out.writeObject(expected);
    } finally {
      out.close();
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bais);
    TestAllTypes actual = (TestAllTypes) in.readObject();
    assertEquals(expected, actual);
  }

  public void testSerializePartial() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestAllTypes expected = builder.buildPartial();
    ObjectOutputStream out = new ObjectOutputStream(baos);
    try {
      out.writeObject(expected);
    } finally {
      out.close();
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bais);
    TestAllTypes actual = (TestAllTypes) in.readObject();
    assertEquals(expected, actual);
  }

  public void testEnumValues() {
     assertEquals(
         TestAllTypes.NestedEnum.BAR.getNumber(),
         TestAllTypes.NestedEnum.BAR_VALUE);
    assertEquals(
        TestAllTypes.NestedEnum.BAZ.getNumber(),
        TestAllTypes.NestedEnum.BAZ_VALUE);
    assertEquals(
        TestAllTypes.NestedEnum.FOO.getNumber(),
        TestAllTypes.NestedEnum.FOO_VALUE);
  }

  public void testNonNestedExtensionInitialization() {
    assertTrue(NonNestedExtension.nonNestedExtension
               .getMessageDefaultInstance() instanceof MyNonNestedExtension);
    assertEquals("nonNestedExtension",
                 NonNestedExtension.nonNestedExtension.getDescriptor().getName());
  }

  public void testNestedExtensionInitialization() {
    assertTrue(MyNestedExtension.recursiveExtension.getMessageDefaultInstance()
               instanceof MessageToBeExtended);
    assertEquals("recursiveExtension",
                 MyNestedExtension.recursiveExtension.getDescriptor().getName());
  }

  public void testBaseMessageOrBuilder() {
    // Mostly just makes sure the base interface exists and has some methods.
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestAllTypes message = builder.buildPartial();
    TestAllTypesOrBuilder builderAsInterface = (TestAllTypesOrBuilder) builder;
    TestAllTypesOrBuilder messageAsInterface = (TestAllTypesOrBuilder) message;

    assertEquals(
        messageAsInterface.getDefaultBool(),
        messageAsInterface.getDefaultBool());
    assertEquals(
        messageAsInterface.getOptionalDouble(),
        messageAsInterface.getOptionalDouble());
  }

  public void testMessageOrBuilderGetters() {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();

    // single fields
    assertSame(ForeignMessage.getDefaultInstance(),
        builder.getOptionalForeignMessageOrBuilder());
    ForeignMessage.Builder subBuilder =
        builder.getOptionalForeignMessageBuilder();
    assertSame(subBuilder, builder.getOptionalForeignMessageOrBuilder());

    // repeated fields
    ForeignMessage m0 = ForeignMessage.newBuilder().buildPartial();
    ForeignMessage m1 = ForeignMessage.newBuilder().buildPartial();
    ForeignMessage m2 = ForeignMessage.newBuilder().buildPartial();
    builder.addRepeatedForeignMessage(m0);
    builder.addRepeatedForeignMessage(m1);
    builder.addRepeatedForeignMessage(m2);
    assertSame(m0, builder.getRepeatedForeignMessageOrBuilder(0));
    assertSame(m1, builder.getRepeatedForeignMessageOrBuilder(1));
    assertSame(m2, builder.getRepeatedForeignMessageOrBuilder(2));
    ForeignMessage.Builder b0 = builder.getRepeatedForeignMessageBuilder(0);
    ForeignMessage.Builder b1 = builder.getRepeatedForeignMessageBuilder(1);
    assertSame(b0, builder.getRepeatedForeignMessageOrBuilder(0));
    assertSame(b1, builder.getRepeatedForeignMessageOrBuilder(1));
    assertSame(m2, builder.getRepeatedForeignMessageOrBuilder(2));

    List<? extends ForeignMessageOrBuilder> messageOrBuilderList =
        builder.getRepeatedForeignMessageOrBuilderList();
    assertSame(b0, messageOrBuilderList.get(0));
    assertSame(b1, messageOrBuilderList.get(1));
    assertSame(m2, messageOrBuilderList.get(2));
  }

  public void testGetFieldBuilder() {
    Descriptor descriptor = TestAllTypes.getDescriptor();

    FieldDescriptor fieldDescriptor =
        descriptor.findFieldByName("optional_nested_message");
    FieldDescriptor foreignFieldDescriptor =
        descriptor.findFieldByName("optional_foreign_message");
    FieldDescriptor importFieldDescriptor =
        descriptor.findFieldByName("optional_import_message");

    // Mutate the message with new field builder
    // Mutate nested message
    TestAllTypes.Builder builder1 = TestAllTypes.newBuilder();
    Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor)
        .mergeFrom((Message) builder1.getField(fieldDescriptor));
    FieldDescriptor subFieldDescriptor1 =
        fieldBuilder1.getDescriptorForType().findFieldByName("bb");
    fieldBuilder1.setField(subFieldDescriptor1, 1);
    builder1.setField(fieldDescriptor, fieldBuilder1.build());

    // Mutate foreign message
    Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(
        foreignFieldDescriptor)
        .mergeFrom((Message) builder1.getField(foreignFieldDescriptor));
    FieldDescriptor subForeignFieldDescriptor1 =
        foreignFieldBuilder1.getDescriptorForType().findFieldByName("c");
    foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2);
    builder1.setField(foreignFieldDescriptor, foreignFieldBuilder1.build());

    // Mutate import message
    Message.Builder importFieldBuilder1 = builder1.newBuilderForField(
        importFieldDescriptor)
        .mergeFrom((Message) builder1.getField(importFieldDescriptor));
    FieldDescriptor subImportFieldDescriptor1 =
        importFieldBuilder1.getDescriptorForType().findFieldByName("d");
    importFieldBuilder1.setField(subImportFieldDescriptor1, 3);
    builder1.setField(importFieldDescriptor, importFieldBuilder1.build());

    Message newMessage1 = builder1.build();

    // Mutate the message with existing field builder
    // Mutate nested message
    TestAllTypes.Builder builder2 = TestAllTypes.newBuilder();
    Message.Builder fieldBuilder2 = builder2.getFieldBuilder(fieldDescriptor);
    FieldDescriptor subFieldDescriptor2 =
        fieldBuilder2.getDescriptorForType().findFieldByName("bb");
    fieldBuilder2.setField(subFieldDescriptor2, 1);
    builder2.setField(fieldDescriptor, fieldBuilder2.build());

    // Mutate foreign message
    Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(
        foreignFieldDescriptor)
        .mergeFrom((Message) builder2.getField(foreignFieldDescriptor));
    FieldDescriptor subForeignFieldDescriptor2 =
        foreignFieldBuilder2.getDescriptorForType().findFieldByName("c");
    foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2);
    builder2.setField(foreignFieldDescriptor, foreignFieldBuilder2.build());

    // Mutate import message
    Message.Builder importFieldBuilder2 = builder2.newBuilderForField(
        importFieldDescriptor)
        .mergeFrom((Message) builder2.getField(importFieldDescriptor));
    FieldDescriptor subImportFieldDescriptor2 =
        importFieldBuilder2.getDescriptorForType().findFieldByName("d");
    importFieldBuilder2.setField(subImportFieldDescriptor2, 3);
    builder2.setField(importFieldDescriptor, importFieldBuilder2.build());

    Message newMessage2 = builder2.build();

    // These two messages should be equal.
    assertEquals(newMessage1, newMessage2);
  }

  public void testGetFieldBuilderWithInitializedValue() {
    Descriptor descriptor = TestAllTypes.getDescriptor();
    FieldDescriptor fieldDescriptor =
        descriptor.findFieldByName("optional_nested_message");

    // Before setting field, builder is initialized by default value.
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    NestedMessage.Builder fieldBuilder =
        (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
    assertEquals(0, fieldBuilder.getBb());

    // Setting field value with new field builder instance.
    builder = TestAllTypes.newBuilder();
    NestedMessage.Builder newFieldBuilder =
        builder.getOptionalNestedMessageBuilder();
    newFieldBuilder.setBb(2);
    // Then get the field builder instance by getFieldBuilder().
    fieldBuilder =
        (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
    // It should contain new value.
    assertEquals(2, fieldBuilder.getBb());
    // These two builder should be equal.
    assertSame(fieldBuilder, newFieldBuilder);
  }

  public void testGetFieldBuilderNotSupportedException() {
    Descriptor descriptor = TestAllTypes.getDescriptor();
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    try {
      builder.getFieldBuilder(descriptor.findFieldByName("optional_int32"));
      fail("Exception was not thrown");
    } catch (UnsupportedOperationException e) {
      // We expect this exception.
    }
    try {
      builder.getFieldBuilder(
          descriptor.findFieldByName("optional_nested_enum"));
      fail("Exception was not thrown");
    } catch (UnsupportedOperationException e) {
      // We expect this exception.
    }
    try {
      builder.getFieldBuilder(descriptor.findFieldByName("repeated_int32"));
      fail("Exception was not thrown");
    } catch (UnsupportedOperationException e) {
      // We expect this exception.
    }
    try {
      builder.getFieldBuilder(
          descriptor.findFieldByName("repeated_nested_enum"));
      fail("Exception was not thrown");
    } catch (UnsupportedOperationException e) {
      // We expect this exception.
    }
    try {
      builder.getFieldBuilder(
          descriptor.findFieldByName("repeated_nested_message"));
      fail("Exception was not thrown");
    } catch (UnsupportedOperationException e) {
      // We expect this exception.
    }
  }
}


text:
#include "config/stm32plus.h"
#include "config/filesystem.h"

namespace stm32plus {
  namespace fat {

    /*
     * Constructor
     */

    DirectoryEntryIterator::DirectoryEntryIterator(FatFileSystem& fs_,Options options_) :
      _fs(fs_) {
      _options=options_;
    }

    /*
     * return the current entry
     */

    DirectoryEntryWithLocation& DirectoryEntryIterator::current() {
      return _currentEntry;
    }

    /**
     * Return the current filename. If a long name is present then it will be returned.
     * @return The current filename.
     */

    const char *DirectoryEntryIterator::getFilename() {
      return _filename.getFilename();
    }

    /**
     * Get the filename handler.
     * @return A reference to the filename handler.
     */

    FilenameHandler& DirectoryEntryIterator::getFilenameHandler() {
      return _filename;
    }

    /**
     * @copydoc Iterator::next
     *
     * The options are taken into account and entries may be skipped if that's what has been specified.
     */

    bool DirectoryEntryIterator::next() {

      bool repeat,deleted;

      errorProvider.clear();

      _filename.reinitialise();

      do {

        if(!internalNext())
          return false;

        // handle filename as long as this entry is not deleted

        DirectoryEntry& dirent=_currentEntry.Dirent;

        deleted=dirent.sdir.DIR_Name[0] == 0xe5;
        if(!deleted && !_filename.handleEntry(_currentEntry))
          return false;

        // repeat if entry is deleted and we are skipping those or if entry
        // is a long name entry and we are parsing them in one step

        if(deleted)
          repeat=(_options & OPT_SKIP_DELETED) != 0;
        else if((dirent.sdir.DIR_Attr & DirectoryEntry::ATTR_LONG_NAME_MASK) == DirectoryEntry::ATTR_LONG_NAME)
          repeat=(_options & OPT_PARSE_LONG_NAMES) != 0;
        else
          repeat=false;

      } while(repeat);

      // reset the dates and times - these are lazily calculated as required

      _lastAccessDateTime=_lastWriteDateTime=_creationDateTime=INT32_MAX;

      return true;
    }

    /**
     * Get the last access date/time as a Unix time_t
     *
     * @return The last access date/time.
     */

    time_t DirectoryEntryIterator::getLastAccessDateTime() {

      if(_lastAccessDateTime != INT32_MAX)
        return _lastAccessDateTime;

      return calculateUnixTime(_currentEntry.Dirent.sdir.DIR_LstAccDate,0,_lastAccessDateTime);
    }

    /**
     * Get the last write date/time as a unix time_t
     *
     * @return The last write date/time.
     */

    time_t DirectoryEntryIterator::getLastWriteDateTime() {

      if(_lastWriteDateTime != INT32_MAX)
        return _lastWriteDateTime;

      DirectoryEntry& dirent=_currentEntry.Dirent;
      return calculateUnixTime(dirent.sdir.DIR_WrtDate,dirent.sdir.DIR_WrtTime,_lastWriteDateTime);
    }

    /**
     * Get the creation date/time as a unix time_t
     *
     * @return The creation date/time.
     */

    time_t DirectoryEntryIterator::getCreationDateTime() {
      if(_creationDateTime != INT32_MAX)
        return _creationDateTime;

      DirectoryEntry& dirent=_currentEntry.Dirent;
      return calculateUnixTime(dirent.sdir.DIR_CrtDate,dirent.sdir.DIR_CrtTime,_creationDateTime);
    }

    /**
     * Static helper to calculate Unix date/time from MSDOS date+time
     * @param[in] date_ MSDOS date.
     * @param[in] time_ MSDOS time.
     * @param[out] result_ The Unix time_t.
     *
     * @return The same as result_.
     */

    time_t DirectoryEntryIterator::calculateUnixTime(uint16_t date_,uint16_t time_,time_t& result_) {

      struct tm timeInfo;

      timeInfo.tm_mday=date_ & 31; // 5 bits (base=1)
      timeInfo.tm_mon=((date_ >> 5) & 15) - 1; // 4 bits (base=1)
      timeInfo.tm_year=((date_ >> 9) & 127) + 80; // 7 bits (base=1980)

      timeInfo.tm_sec=(time_ & 31) * 2; // 5 bits (resolution=2 secs)
      timeInfo.tm_min=(time_ >> 5) & 63; // 6 bits (base=0)
      timeInfo.tm_hour=(time_ >> 11) & 31; // 5 bits (base=0)

      result_=mktime(&timeInfo);
      return result_;
    }

    /**
     * Convert MSDOS date+time from unix time
     *
     * @param[in] unixTime_ The Unix time_t to convert.
     * @param[out] date_ The MSDOS FAT date.
     * @param[out] time_ The MSDOS FAT time.
     */

    void DirectoryEntryIterator::calculateFatDateTime(time_t unixTime_,uint16_t& date_,uint16_t& time_) {

      struct tm *timeInfo;

      // get components

      timeInfo=gmtime(&unixTime_);

      // set the date

      date_=(static_cast<uint32_t> (timeInfo->tm_year - 80) << 9) | (static_cast<uint32_t> (timeInfo->tm_mon + 1) << 5) | timeInfo->tm_mday;

      // set the time

      time_=(static_cast<uint32_t> (timeInfo->tm_hour) << 11) | (static_cast<uint32_t> (timeInfo->tm_min) << 5) | (static_cast<uint32_t> (timeInfo->tm_sec) >> 1);
    }

    /**
     * Write some new dirents to this directory. If the directory contains a contiguous sequence of deleted
     * large enough to hold the new sequence then these entries are used. If not then new entries are allocated
     * on the end of the directory. Whichever happens, the new dirents are guaranteed not to be broken up.
     *
     * @param[in] dirents_ The dirents to write to this directory.
     * @param[in] direntCount_ The number of dirents to write.
     * @return false if it fails.
     */

    bool DirectoryEntryIterator::writeDirents(DirectoryEntry *dirents_,int direntCount_) {

      DirectoryEntryWithLocation *entries;
      Options oldOptions;
      int foundCount,i;

      // save old options and make sure we see deleted entries now

      oldOptions=_options;
      _options=OPT_PARSE_LONG_NAMES;

      // reset the iterator

      reset();

      // start searching for deleted entries

      foundCount=0;
      entries=new DirectoryEntryWithLocation[direntCount_];

      while(next()) {

        if(current().Dirent.sdir.DIR_Name[0] == 0xE5) {

          // if first in sequence, remember it

          entries[foundCount++]=current(); // struct copy

          // if found enough, remember the last

          if(foundCount == direntCount_) {

            // finished with this

            _options=oldOptions;

            // now write the dirents

            for(i=0;i < foundCount;i++) {

              entries[i].Dirent=dirents_[i]; // struct copy

              if(!_fs.writeDirectoryEntry(entries[i])) {
                delete[] entries;
                return false;
              }
            }

            delete[] entries;
            return true;
          }
        } else
          foundCount=0; // reset the counter
      }

      // we're done with these

      delete[] entries;
      _options=oldOptions;

      // not enough contiguous deleted entries available
      // extend the directory to make space for them

      return extendDirectory(dirents_,direntCount_);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
  <title>Test for Bug 41737. PASS unless crash.</title>

Test for Bug 41737. PASS unless crash.

<keygen style='padding: 10000; border-radius: 1;'></keygen>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Test extends CI_Controller
{

	const USE_PRODUCTION_SERVER  = 0;
	const USE_DEVELOPMENT_SERVER = 1;

	const EXCEPTION_CURL = 10;

	private $params  = array();
	private $items   = array();
	private $success = false;
	private $error   = true;

	private $login;
	private $transkey;
	private $xml;
	private $json;
	private $ch;
	private $response_use;
	private $url_use;
	private $resultCode;
	private $code;
	private $text;
	private $profileId;
	private $validation;
	private $paymentProfileId;
	private $results;

	function __construct()
    {
        parent::__construct();
		$this->load->model('Users_model');
		$this->load->model('Content_model');
		$this->load->library("pagination");
		$this->load->library('ion_auth');
		$this->load->model("Common_model");
		$this->gallery_path = realpath(APPPATH . '../uploads');
		if (!$this->ion_auth->logged_in() && !$this->ion_auth->in_group(3)) {
			redirect(site_url('/'), 'refresh');
		}
    }

	public function __toString()
	{
		if (!$this->params)
		{
			return (string) $this;
		}
		$output  = '
' . "\n";
		$output .= '
' . "\n\t\t" . 'Outgoing Parameters	' . "\n" . '
' . "\n";
		foreach ($this->params as $key => $value)
		{
			$output .= "\t" . '
' . "\n\t\t" . '' . $key . '	';
			$output .= '' . $value . '	' . "\n" . '
' . "\n";
		}

		$output .= '
' . "\n";
		if (!empty($this->xml))
		{
			$output .= 'XML: ';
			$output .= htmlentities($this->xml);
		}
		return $output;
	}
	private function parseResults()
	{
		$response = str_replace('xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"', '', $this->response_use);
		$xml = new SimpleXMLElement($response);
		print_r($xml);
		$this->resultCode       = (string) $xml->messages->resultCode;
		$this->code             = (string) $xml->messages->message->code;
		$this->text             = (string) $xml->messages->message->text;
		$this->validation       = (string) $xml->validationDirectResponse;
		$this->directResponse   = (string) $xml->directResponse;
		$this->profileId        = (int) $xml->customerProfileId;
		$this->addressId        = (int) $xml->customerAddressId;
		$this->paymentProfileId = (int) $xml->customerPaymentProfileId;
		$this->results          = explode(',', $this->directResponse);
		//print_r($this->results);

	}
	private function parseCuResults()
	{
		$response = str_replace('xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"', '', $this->response_use);
		$xml = new SimpleXMLElement($response);
		print_r($xml);
		$this->resultCode       = (string) $xml->messages->resultCode;
		$this->code             = (string) $xml->messages->message->code;
		$this->text             = (string) $xml->messages->message->text;
		$responseCode           = $xml->transactionResponse->responseCode;
		$authCode               = $xml->transactionResponse->authCode;
		$avsResultCode               = $xml->transactionResponse->avsResultCode;
		$transId               = $xml->transactionResponse->transId;
		$transHash               = $xml->transactionResponse->transHash;
		$accountNumber               = $xml->transactionResponse->accountNumber;
		$result_arr = array("responseCode"=>$responseCode,
			"authCode"=>$authCode,
			"avsResultCode"=>$avsResultCode,
			"transId"=>$transId,
			"transHash"=>$transHash,
			"accountNumber"=>$accountNumber);
		$this->results = $result_arr;

	}
	private function process($charge_cus=false)
	{
		$this->ch = curl_init();
		curl_setopt($this->ch, CURLOPT_URL, $this->url_use);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($this->ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
		curl_setopt($this->ch, CURLOPT_HEADER, 0);
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->xml);
		curl_setopt($this->ch, CURLOPT_POST, 1);
		curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
		$this->response_use = curl_exec($this->ch);
		if($this->response_use)
		{

			$this->parseResults();

			if ($this->resultCode === 'Ok')
			{
				$this->success = true;
				$this->error   = false;
			}
			else
			{
				$this->success = false;
				$this->error   = true;
			}
			curl_close($this->ch);
			unset($this->ch);
		}
		else
		{
			curl_error($this->ch);
		}
	}
	public function createCustomerProfile($use_profiles = false, $type = 'credit')
	{
		$this->xml = '<?xml version="1.0" encoding="utf-8"?>
                      <createCustomerProfileRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
                          <merchantAuthentication>
                              <name>' . $this->login . '</name>
                              <transactionKey>' . $this->transkey . '</transactionKey>
                          </merchantAuthentication>';
		if (!empty($this->params['refId']))
		{
			$this->xml .= '
                          <refId>'. $this->params['refId'] .'</refId>';
		}
		$this->xml .= '
                          <profile>
                              <merchantCustomerId>'. $this->params['merchantCustomerId'].'</merchantCustomerId>
                              <description>'. $this->params['description'].'</description>
                              <email>'. $this->params['email'] .'</email>';

		if ($use_profiles == true)
		{
			$this->xml .= '
                              <paymentProfiles>
                                  <customerType>'. $this->params['customerType'].'</customerType>
                                  <billTo>
                                      <firstName>'. $this->params['billToFirstName'].'</firstName>
                                      <lastName>'. $this->params['billToLastName'].'</lastName>
                                      <company>'. $this->params['billToCompany'] .'</company>
                                      <address>'. $this->params['billToAddress'] .'</address>
                                      <city>'. $this->params['billToCity'] .'</city>
                                      <state>'. $this->params['billToState'] .'</state>
                                      <zip>'. $this->params['billToZip'] .'</zip>
                                      <country>'. $this->params['billToCountry'] .'</country>
                                      <phoneNumber>'. $this->params['billToPhoneNumber'].'</phoneNumber>
                                      <faxNumber>'. $this->params['billToFaxNumber'].'</faxNumber>
                                  </billTo>
                                  <payment>';
			if ($type === 'credit')
			{
				$this->xml .= '
                                      <creditCard>
                                          <cardNumber>'. $this->params['cardNumber'].'</cardNumber>
                                          <expirationDate>'.$this->params['expirationDate'].'</expirationDate>
                                      </creditCard>';
			}
			else if ($type === 'check')
			{
				$this->xml .= '
                                      <bankAccount>
                                          <accountType>'.$this->params['accountType'].'</accountType>
                                          <nameOnAccount>'.$this->params['nameOnAccount'].'</nameOnAccount>
                                          <echeckType>'. $this->params['echeckType'].'</echeckType>
                                          <bankName>'. $this->params['bankName'].'</bankName>
                                          <routingNumber>'.$this->params['routingNumber'].'</routingNumber>
                                          <accountNumber>'.$this->params['accountNumber'].'</accountNumber>
                                      </bankAccount>
                                      <driversLicense>
                                          <dlState>'. $this->params['dlState'].'</dlState>
                                          <dlNumber>'. $this->params['dlNumber'].'</dlNumber>
                                          <dlDateOfBirth>'.$this->params['dlDateOfBirth'].'</dlDateOfBirth>
                                      </driversLicense>';
			}
			$this->xml .= '
                                  </payment>
                              </paymentProfiles>
                              <shipToList>
                                  <firstName>'. $this->params['shipToFirstName'].'</firstName>
                                  <lastName>'. $this->params['shipToLastName'].'</lastName>
                                  <company>'. $this->params['shipToCompany'] .'</company>
                                  <address>'. $this->params['shipToAddress'] .'</address>
                                  <city>'. $this->params['shipToCity'] .'</city>
                                  <state>'. $this->params['shipToState'] .'</state>
                                  <zip>'. $this->params['shipToZip'] .'</zip>
                                  <country>'. $this->params['shipToCountry'] .'</country>
                                  <phoneNumber>'. $this->params['shipToPhoneNumber'].'</phoneNumber>
                                  <faxNumber>'. $this->params['shipToFaxNumber'].'</faxNumber>
                              </shipToList>';
		}
		$this->xml .= '
                          </profile>
                      </createCustomerProfileRequest>';

		$this->process();

	}

	public function getProfileID()
	{
		return $this->profileId;
	}
	public function setParameter($field = '', $value = null)
	{
		$field = (is_string($field)) ? trim($field) : $field;
		$value = (is_string($value)) ? trim($value) : $value;
		if (!is_string($field))
		{
			trigger_error(__METHOD__ . '() arg 1 must be a string: ' . gettype($field) . ' given.', E_USER_ERROR);
		}
		if (empty($field))
		{
			trigger_error(__METHOD__ . '() requires a parameter field to be named.', E_USER_ERROR);
		}
		if (!is_string($value) && !is_numeric($value) && !is_bool($value))
		{
			trigger_error(__METHOD__ . '() arg 2 (' . $field . ') must be a string, integer, or boolean value: ' . gettype($value) . ' given.', E_USER_ERROR);
		}
		if ($value === '' || is_null($value))
		{
			trigger_error(__METHOD__ . '() parameter "value" is empty or missing (parameter: ' . $field . ').', E_USER_NOTICE);
		}
		$this->params[$field] = $value;
	}
	public function createCustomerPaymentProfile($type = 'credit')
	{
		$this->xml = '<?xml version="1.0" encoding="utf-8"?>
                      <createCustomerPaymentProfileRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
                          <merchantAuthentication>
                              <name>' . $this->login . '</name>
                              <transactionKey>' . $this->transkey . '</transactionKey>
                          </merchantAuthentication>
                          <customerProfileId>'.$this->params['customerProfileId'].'</customerProfileId>
                          <paymentProfile>
                              <billTo>
                                  <firstName>'. @$this->params['billToFirstName'].'</firstName>
                                  <lastName>'. @$this->params['billToLastName'].'</lastName>
                                  <address>'. @$this->params['billToAddress'] .'</address>
                                  <city>'. @$this->params['billToCity'] .'</city>
                                  <state>'. @$this->params['billToState'] .'</state>
                                  <zip>'. @$this->params['billToZip'] .'</zip>
                                  <country>'. @$this->params['billToCountry'] .'</country>
                                  <phoneNumber>'. @$this->params['billToPhoneNumber'].'</phoneNumber>
                                  <faxNumber>'. @$this->params['billToFaxNumber'].'</faxNumber>
                              </billTo>
                              <payment>';
		if ($type === 'credit')
		{
			$this->xml .= '
                                  <creditCard>
                                      <cardNumber>'. $this->params['cardNumber'].'</cardNumber>
                                      <expirationDate>'.$this->params['expirationDate'].'</expirationDate>
                                  </creditCard>';
		}
		else if ($type === 'check')
		{
			$this->xml .= '
                                  <bankAccount>
                                      <accountType>'. $this->params['accountType'].'</accountType>
                                      <nameOnAccount>'.$this->params['nameOnAccount'].'</nameOnAccount>
                                      <echeckType>'. $this->params['echeckType'].'</echeckType>
                                      <bankName>'. $this->params['bankName'].'</bankName>
                                      <routingNumber>'.$this->params['routingNumber'].'</routingNumber>
                                      <accountNumber>'.$this->params['accountNumber'].'</accountNumber>
                                  </bankAccount>
                                  <driversLicense>
                                      <dlState>'. $this->params['dlState'] .'</dlState>
                                      <dlNumber>'. $this->params['dlNumber'].'</dlNumber>
                                      <dlDateOfBirth>'.$this->params['dlDateOfBirth'].'</dlDateOfBirth>
                                  </driversLicense>';
		}
		$this->xml .= '
                              </payment>
                          </paymentProfile>

                      </createCustomerPaymentProfileRequest>';
		$this->process();
	}
	public function getPaymentProfileId()
	{
		return $this->paymentProfileId;
	}
	public function createCustomerShippingAddress()
	{
		$this->xml = '<?xml version="1.0" encoding="utf-8"?>
                      <createCustomerShippingAddressRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
                          <merchantAuthentication>
                              <name>' . $this->login . '</name>
                              <transactionKey>' . $this->transkey . '</transactionKey>
                          </merchantAuthentication>
                          <refId>'. @$this->params['refId'] .'</refId>
                          <customerProfileId>'. $this->params['customerProfileId'].'</customerProfileId>
                          <address>
                              <firstName>'. $this->params['shipToFirstName'].'</firstName>
                              <lastName>'. $this->params['shipToLastName'].'</lastName>
                              <company>'. @$this->params['shipToCompany'] .'</company>
                              <address>'. $this->params['shipToAddress'] .'</address>
                              <city>'. $this->params['shipToCity'] .'</city>
                              <state>'. $this->params['shipToState'] .'</state>
                              <zip>'. $this->params['shipToZip'] .'</zip>
                              <country>'. $this->params['shipToCountry'] .'</country>
                              <phoneNumber>'. @$this->params['shipToPhoneNumber'].'</phoneNumber>
                              <faxNumber>'. @$this->params['shipToFaxNumber'].'</faxNumber>
                          </address>
                      </createCustomerShippingAddressRequest>';
		$this->process();
	}
	public function ChargeCustomerProfile(){
		$this->xml = '<createTransactionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
       <merchantAuthentication>
        <name>' . $this->login . '</name>
        <transactionKey>' . $this->transkey . '</transactionKey>
      </merchantAuthentication>

  <transactionRequest>
    <transactionType>authCaptureTransaction</transactionType>
    <amount>'.$this->params['amount'].'</amount>
    <profile>
      <customerProfileId>'.$this->params['customerProfileId'].'</customerProfileId>
      <paymentProfile>
        <paymentProfileId>'.$this->params['customerPaymentProfileId'].'</paymentProfileId>
      </paymentProfile>
    </profile>
    <shipTo>
      <firstName>China</firstName>
      <lastName>Bayles</lastName>
      <company>Thyme for Tea</company>
      <address>12 Main Street</address>
      <city>Pecan Springs</city>
      <state>TX</state>
      <zip>44628</zip>
      <country>USA</country>
    </shipTo>
  </transactionRequest>
</createTransactionRequest>';
		$this->process(true);
	}
	public function getCustomerAddressId()
	{
		return $this->addressId;
	}

	private function getLineItems()
	{
		$tempXml = '';
		foreach ($this->items as $item)
		{
			foreach ($item as $key => $value)
			{
				$tempXml .= "\t" . '<' . $key . '>' . $value . '</' . $key . '>' . "\n";
			}
		}
		return $tempXml;
	}

	public function createCustomerProfileTransaction($type = 'profileTransAuthCapture')
	{
		$types = array('profileTransAuthCapture', 'profileTransCaptureOnly','profileTransAuthOnly');
		if (!in_array($type, $types))
		{
			trigger_error('createCustomerProfileTransaction() parameter must be"profileTransAuthCapture", "profileTransCaptureOnly", "profileTransAuthOnly", or empty', E_USER_ERROR);
		}

		$this->xml = '<?xml version="1.0" encoding="utf-8"?>
                      <createCustomerProfileTransactionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
                          <merchantAuthentication>
                              <name>' . $this->login . '</name>
                              <transactionKey>' . $this->transkey . '</transactionKey>
                          </merchantAuthentication>
                          <refId>'. @$this->params['refId'] .'</refId>
                          <transaction>
                              <' . $type . '>
                                  <amount>'. $this->params['amount'] .'</amount>';
		if (isset($this->params['taxAmount']))
		{
			$this->xml .= '
                                  <tax>
                                       <amount>'. $this->params['taxAmount'].'</amount>
                                       <name>'. $this->params['taxName'] .'</name>
                                       <description>'.$this->params['taxDescription'].'</description>
                                  </tax>';
		}
		if (isset($this->params['shipAmount']))
		{
			$this->xml .= '
                                  <shipping>
                                       <amount>'. $this->params['shipAmount'].'</amount>
                                       <name>'. $this->params['shipName'] .'</name>
                                       <description>'.$this->params['shipDescription'].'</description>
                                  </shipping>';
		}
		if (isset($this->params['dutyAmount']))
		{
			$this->xml .= '
                                  <duty>
                                       <amount>'. $this->params['dutyAmount'].'</amount>
                                       <name>'. $this->params['dutyName'] .'</name>
                                       <description>'.$this->params['dutyDescription'].'</description>
                                  </duty>';
		}
		$this->xml .= '

                                  <customerProfileId>'.$this->params['customerProfileId'].'</customerProfileId>
                                  <customerPaymentProfileId>'.$this->params['customerPaymentProfileId'].'</customerPaymentProfileId>
                                  <customerShippingAddressId>'.$this->params['customerShippingAddressId'].'</customerShippingAddressId>';
		if (isset($this->params['orderInvoiceNumber']))
		{
			$this->xml .= '
                                  <order>
                                       <invoiceNumber>'.$this->params['invoiceNumber'].'</orderInvoiceNumber>
                                       <description>'.$this->params['description'].'</orderDescription>
                                       <purchaseOrderNumber>'.$this->params['purchaseOrderNumber'].'</orderPurchaseOrderNumber>
                                  </order>';
		}
		$this->xml .= '
                                  <cardCode>'. $this->params['cardCode'].'</cardCode>';
		if (isset($this->params['orderInvoiceNumber']))
		{
			$this->xml .= '
                                  <approvalCode>'. $this->params['approvalCode'].'</approvalCode>';
		}
		$this->xml .= '
                              </' . $type . '>
                          </transaction>
                      </createCustomerProfileTransactionRequest>';
		$this->process();
	}
	public function getResponseSummary()
	{
		return 'Response code: ' . $this->getCode() . ' Message: ' . $this->getResponse();
	}
	public function getResponse()
	{
		return strip_tags($this->text);
	}

	public function getCode()
	{
		return $this->code;
	}
	public function getAuthCode()
	{
		return $this->results[4];
	}
	public function setLineItem($itemId, $name, $description, $quantity, $unitprice,$taxable = 'false')
	{
		$this->items[] = array('itemId' => $itemId, 'name' => $name, 'description' => $description, 'quantity' => $quantity, 'unitPrice' => $unitprice, 'taxable' => $taxable);
	}
	public function getCustomerProfile()
	{
		$this->xml = '<?xml version="1.0" encoding="utf-8"?>
                      <getCustomerProfileRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
                          <merchantAuthentication>
                              <name>' . $this->login . '</name>
                              <transactionKey>' . $this->transkey . '</transactionKey>
                          </merchantAuthentication>
                          <customerProfileId>'. $this->params['customerProfileId'].'</customerProfileId>
                      </getCustomerProfileRequest>';
		$this->process();
	}
	public function saveAuthorize(){

		$url = 'https://test.authorize.net/gateway/transact.dll';
		$this->url_use = 'https://apitest.authorize.net/xml/v1/request.api';

		//$url = 'https://secure.networkmerchants.com/gateway/transact.dll';

		// oc_authorize_profile
		//$chk_profile = $this->db->query("select id from oc_authorize_profile");
		$this->setParameter('email', "asif@innovatorssoft.com");
		$this->setParameter('description', "no description");
		$this->setParameter('merchantCustomerId', uniqid());
		$this->login    = '6RG5b3yk9V';
		$this->transkey = '6VPpb7H5uGz7G92u';
		$this->createCustomerProfile();
		echo $this->profileId;

		//$profile_id     = 1811733206;
die('stop');
		//set parameters for create payment profile
		@$this->setParameter('customerProfileId', $profile_id);
		@$this->setParameter('billToFirstName', html_entity_decode('Yasir', ENT_QUOTES, 'UTF-8'));
		@$this->setParameter('billToLastName',  html_entity_decode('Shabbir', ENT_QUOTES, 'UTF-8'));
		@$this->setParameter('billToAddress',   html_entity_decode('New Civil Line', ENT_QUOTES, 'UTF-8'));
		//$this->setParameter('billToCompany', html_entity_decode($order_info['payment_company'], ENT_QUOTES, 'UTF-8'));
		@$this->setParameter('billToCity',      html_entity_decode('Faisalabad', ENT_QUOTES, 'UTF-8'));
		@$this->setParameter('billToState', html_entity_decode('Punjab', ENT_QUOTES, 'UTF-8'));
		@$this->setParameter('billToZip', html_entity_decode('38000', ENT_QUOTES, 'UTF-8'));
		@$this->setParameter('billToCountry', html_entity_decode('Pakistan', ENT_QUOTES, 'UTF-8'));
		@$this->setParameter('cardNumber', '4111111111111111');
		@$this->setParameter('expirationDate', '12-18');
		//$this->createCustomerPaymentProfile();

		$payment_profile_id = '1806251365';

		@$this->setParameter('cardCode', '4556199497445627');
		@$this->setParameter('customerPaymentProfileId', $payment_profile_id);
		@$this->setParameter('refId', $profile_id);
		@$this->setParameter('amount', 200);
		@$this->setParameter('cardCode', 200);
		@$this->setParameter('customerShippingAddressId', 112);

		/// create shipping address
		@$this->setParameter('shipToFirstName', 'Faisal');
		@$this->setParameter('shipToLastName', 'Shahzad');
		@$this->setParameter('shipToCompany', 'Business');
		@$this->setParameter('shipToAddress', 'New Civil Line');
		@$this->setParameter('shipToCity', 'Faisalabad');
		@$this->setParameter('shipToState', 'Punjab');
		@$this->setParameter('shipToZip', '38000');
		@$this->setParameter('shipToCountry', 'Pakistan');
		@$this->setParameter('shipToPhoneNumber', '09809809');
		@$this->setParameter('shipToFaxNumber', '0510980099');
		//$this->createCustomerShippingAddress();

		///create transaction
		@$this->setParameter('customerShippingAddressId', '1810464126');

		$this->createCustomerProfileTransaction();

	}

}// end class


text:
def shortest_string(list_of_words)
	if list_of_words.length == 0
		return nil
	elsif list_of_words.length == 1
		return list_of_words[0]
	end
  i = 1
  short = list_of_words[0]
  while i < list_of_words.length
  	if short.length > list_of_words[i].length
  		short = list_of_words[i]
  	end
  	i +=1
  end
  return short
end


text:
package com.amazonaws.services.cloudsearchv2.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.cloudsearchv2.AmazonCloudSearch#deleteSuggester(DeleteSuggesterRequest) DeleteSuggester operation}.
 *

 * Deletes a suggester. For more information, see
 *  Getting Search Suggestions
 * in the Amazon CloudSearch Developer Guide .
 *

 *
 * @see com.amazonaws.services.cloudsearchv2.AmazonCloudSearch#deleteSuggester(DeleteSuggesterRequest)
 */
public class DeleteSuggesterRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     * A string that represents the name of a domain. Domain names are unique
     * across the domains owned by an account within an AWS region. Domain
     * names start with a letter or number and can contain the following
     * characters: a-z (lowercase), 0-9, and - (hyphen).
     *

     * Constraints:

     * Length: 3 - 28

     * Pattern: [a-z][a-z0-9\-]+

     */
    private String domainName;

    /**
     * Specifies the name of the suggester you want to delete.
     *

     * Constraints:

     * Length: 1 - 64

     * Pattern: [a-z][a-z0-9_]*

     */
    private String suggesterName;

    /**
     * A string that represents the name of a domain. Domain names are unique
     * across the domains owned by an account within an AWS region. Domain
     * names start with a letter or number and can contain the following
     * characters: a-z (lowercase), 0-9, and - (hyphen).
     *

     * Constraints:

     * Length: 3 - 28

     * Pattern: [a-z][a-z0-9\-]+

     *
     * @return A string that represents the name of a domain. Domain names are unique
     *         across the domains owned by an account within an AWS region. Domain
     *         names start with a letter or number and can contain the following
     *         characters: a-z (lowercase), 0-9, and - (hyphen).
     */
    public String getDomainName() {
        return domainName;
    }

    /**
     * A string that represents the name of a domain. Domain names are unique
     * across the domains owned by an account within an AWS region. Domain
     * names start with a letter or number and can contain the following
     * characters: a-z (lowercase), 0-9, and - (hyphen).
     *

     * Constraints:

     * Length: 3 - 28

     * Pattern: [a-z][a-z0-9\-]+

     *
     * @param domainName A string that represents the name of a domain. Domain names are unique
     *         across the domains owned by an account within an AWS region. Domain
     *         names start with a letter or number and can contain the following
     *         characters: a-z (lowercase), 0-9, and - (hyphen).
     */
    public void setDomainName(String domainName) {
        this.domainName = domainName;
    }

    /**
     * A string that represents the name of a domain. Domain names are unique
     * across the domains owned by an account within an AWS region. Domain
     * names start with a letter or number and can contain the following
     * characters: a-z (lowercase), 0-9, and - (hyphen).
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 3 - 28

     * Pattern: [a-z][a-z0-9\-]+

     *
     * @param domainName A string that represents the name of a domain. Domain names are unique
     *         across the domains owned by an account within an AWS region. Domain
     *         names start with a letter or number and can contain the following
     *         characters: a-z (lowercase), 0-9, and - (hyphen).
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DeleteSuggesterRequest withDomainName(String domainName) {
        this.domainName = domainName;
        return this;
    }

    /**
     * Specifies the name of the suggester you want to delete.
     *

     * Constraints:

     * Length: 1 - 64

     * Pattern: [a-z][a-z0-9_]*

     *
     * @return Specifies the name of the suggester you want to delete.
     */
    public String getSuggesterName() {
        return suggesterName;
    }

    /**
     * Specifies the name of the suggester you want to delete.
     *

     * Constraints:

     * Length: 1 - 64

     * Pattern: [a-z][a-z0-9_]*

     *
     * @param suggesterName Specifies the name of the suggester you want to delete.
     */
    public void setSuggesterName(String suggesterName) {
        this.suggesterName = suggesterName;
    }

    /**
     * Specifies the name of the suggester you want to delete.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 64

     * Pattern: [a-z][a-z0-9_]*

     *
     * @param suggesterName Specifies the name of the suggester you want to delete.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DeleteSuggesterRequest withSuggesterName(String suggesterName) {
        this.suggesterName = suggesterName;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDomainName() != null) sb.append("DomainName: " + getDomainName() + ",");
        if (getSuggesterName() != null) sb.append("SuggesterName: " + getSuggesterName() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDomainName() == null) ? 0 : getDomainName().hashCode());
        hashCode = prime * hashCode + ((getSuggesterName() == null) ? 0 : getSuggesterName().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof DeleteSuggesterRequest == false) return false;
        DeleteSuggesterRequest other = (DeleteSuggesterRequest)obj;

        if (other.getDomainName() == null ^ this.getDomainName() == null) return false;
        if (other.getDomainName() != null && other.getDomainName().equals(this.getDomainName()) == false) return false;
        if (other.getSuggesterName() == null ^ this.getSuggesterName() == null) return false;
        if (other.getSuggesterName() != null && other.getSuggesterName().equals(this.getSuggesterName()) == false) return false;
        return true;
    }

    @Override
    public DeleteSuggesterRequest clone() {

            return (DeleteSuggesterRequest) super.clone();
    }

}


text:
@interface UIBarButtonItem (Extension)
+ (UIBarButtonItem *)itemWithTarget:(id)target action:(SEL)selector image:(NSString *)imgStr highLightedImg:(NSString *)hlImgStr;
@end


text:
<?php
declare(strict_types=1);

namespace Neos\Cache\Backend;

use Neos\Cache\Backend\AbstractBackend as IndependentAbstractBackend;
use Neos\Cache\Exception;
use Neos\Cache\Frontend\FrontendInterface;

/**
 * A caching backend which stores cache entries during one script run.
 *
 * @api
 */
class TransientMemoryBackend extends IndependentAbstractBackend implements TaggableBackendInterface
{
    /**
     * @var array
     */
    protected $entries = [];

    /**
     * @var array
     */
    protected $tagsAndEntries = [];

    /**
     * Saves data in the cache.
     *
     * @param string $entryIdentifier An identifier for this specific cache entry
     * @param string $data The data to be stored
     * @param array $tags Tags to associate with this cache entry
     * @param integer $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited lifetime.
     * @return void
     * @throws Exception if no cache frontend has been set.
     * @api
     */
    public function set(string $entryIdentifier, string $data, array $tags = [], int $lifetime = null): void
    {
        if (!$this->cache instanceof FrontendInterface) {
            throw new Exception('No cache frontend has been set yet via setCache().', 1238244992);
        }

        $this->entries[$entryIdentifier] = $data;
        foreach ($tags as $tag) {
            $this->tagsAndEntries[$tag][$entryIdentifier] = true;
        }
    }

    /**
     * Loads data from the cache.
     *
     * @param string $entryIdentifier An identifier which describes the cache entry to load
     * @return mixed The cache entry's content as a string or false if the cache entry could not be loaded
     * @api
     */
    public function get(string $entryIdentifier)
    {
        return $this->entries[$entryIdentifier] ?? false;
    }

    /**
     * Checks if a cache entry with the specified identifier exists.
     *
     * @param string $entryIdentifier An identifier specifying the cache entry
     * @return boolean true if such an entry exists, false if not
     * @api
     */
    public function has(string $entryIdentifier): bool
    {
        return isset($this->entries[$entryIdentifier]);
    }

    /**
     * Removes all cache entries matching the specified identifier.
     *
     * @param string $entryIdentifier Specifies the cache entry to remove
     * @return boolean true if the entry could be removed or false if no entry was found
     * @api
     */
    public function remove(string $entryIdentifier): bool
    {
        if (!isset($this->entries[$entryIdentifier])) {
            return false;
        }
        unset($this->entries[$entryIdentifier]);
        foreach (array_keys($this->tagsAndEntries) as $tag) {
            if (isset($this->tagsAndEntries[$tag][$entryIdentifier])) {
                unset($this->tagsAndEntries[$tag][$entryIdentifier]);
            }
        }
        return true;
    }

    /**
     * Finds and returns all cache entry identifiers which are tagged by the
     * specified tag.
     *
     * @param string $tag The tag to search for
     * @return string[] An array with identifiers of all matching entries. An empty array if no entries matched
     * @api
     */
    public function findIdentifiersByTag(string $tag): array
    {
        if (isset($this->tagsAndEntries[$tag])) {
            return array_map(
                static function ($value) {
                    return (string)$value;
                },
                array_keys($this->tagsAndEntries[$tag])
            );
        }
        return [];
    }

    /**
     * Removes all cache entries of this cache.
     *
     * @return void
     * @api
     */
    public function flush(): void
    {
        $this->entries = [];
        $this->tagsAndEntries = [];
    }

    /**
     * Removes all cache entries of this cache which are tagged by the specified tag.
     *
     * @param string $tag The tag the entries must have
     * @return integer The number of entries which have been affected by this flush
     * @api
     */
    public function flushByTag(string $tag): int
    {
        $identifiers = $this->findIdentifiersByTag($tag);
        foreach ($identifiers as $identifier) {
            $this->remove($identifier);
        }
        return count($identifiers);
    }

    /**
     * Removes all cache entries of this cache which are tagged by any of the specified tags.
     *
     * @api
     */
    public function flushByTags(array $tags): int
    {
        $flushed = 0;
        foreach ($tags as $tag) {
            $flushed += $this->flushByTag($tag);
        }
        return $flushed;
    }

    /**
     * Does nothing
     *
     * @return void
     * @api
     */
    public function collectGarbage(): void
    {
    }
}