text:
package com.facebook.buck.cxx;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.cli.BuckConfig;
import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.io.MorePaths;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BinaryBuildRuleToolProvider;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.DependencyAggregationTestUtil;
import com.facebook.buck.rules.FakeBuildRule;
import com.facebook.buck.rules.FakeSourcePath;
import com.facebook.buck.rules.PathSourcePath;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TestBuildRuleParams;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.shell.ShBinary;
import com.facebook.buck.shell.ShBinaryBuilder;
import com.facebook.buck.testutil.AllExistingProjectFilesystem;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@SuppressWarnings("PMD.TestClassWithoutTestCases")
@RunWith(Enclosed.class)
public class CxxSourceRuleFactoryTest {

  private static final ProjectFilesystem PROJECT_FILESYSTEM = new FakeProjectFilesystem();

  private static final CxxPlatform CXX_PLATFORM =
      CxxPlatformUtils.build(new CxxBuckConfig(FakeBuckConfig.builder().build()));

  private static <T> void assertContains(ImmutableList<T> container, Iterable<T> items) {
    for (T item : items) {
      assertThat(container, Matchers.hasItem(item));
    }
  }

  public static class CxxSourceRuleFactoryTests {
    private static FakeBuildRule createFakeBuildRule(String target, BuildRule... deps) {
      BuildTarget buildTarget = BuildTargetFactory.newInstance(target);
      return new FakeBuildRule(
          buildTarget,
          new FakeProjectFilesystem(),
          TestBuildRuleParams.create().withDeclaredDeps(ImmutableSortedSet.copyOf(deps)));
    }

    @Test
    public void createPreprocessAndCompileBuildRulePropagatesCxxPreprocessorDeps() {
      BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
      BuildRuleResolver resolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

      FakeBuildRule dep = resolver.addToIndex(new FakeBuildRule("//:dep1"));

      CxxPreprocessorInput cxxPreprocessorInput =
          CxxPreprocessorInput.builder().addRules(dep.getBuildTarget()).build();

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(resolver)
              .setPathResolver(pathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(CXX_PLATFORM)
              .addCxxPreprocessorInput(cxxPreprocessorInput)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      String name = "foo/bar.cpp";
      SourcePath input = new PathSourcePath(PROJECT_FILESYSTEM, target.getBasePath().resolve(name));
      CxxSource cxxSource = CxxSource.of(CxxSource.Type.CXX, input, ImmutableList.of());

      BuildRule cxxPreprocess =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(name, cxxSource);
      assertThat(
          DependencyAggregationTestUtil.getDisaggregatedDeps(cxxPreprocess)::iterator,
          contains((BuildRule) dep));
      cxxPreprocess = cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(name, cxxSource);
      assertThat(
          DependencyAggregationTestUtil.getDisaggregatedDeps(cxxPreprocess)::iterator,
          contains((BuildRule) dep));
    }

    @Test
    public void preprocessFlagsFromPlatformArePropagated() {
      BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
      BuildRuleResolver resolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

      ImmutableList<String> platformFlags = ImmutableList.of("-some", "-flags");
      CxxPlatform platform =
          CxxPlatformUtils.build(
              new CxxBuckConfig(
                  FakeBuckConfig.builder()
                      .setSections(
                          ImmutableMap.of(
                              "cxx",
                              ImmutableMap.of("cxxppflags", Joiner.on(" ").join(platformFlags))))
                      .build()));

      CxxPreprocessorInput cxxPreprocessorInput = CxxPreprocessorInput.EMPTY;

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(resolver)
              .setPathResolver(pathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(platform)
              .addCxxPreprocessorInput(cxxPreprocessorInput)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      String name = "source.cpp";
      CxxSource cxxSource =
          CxxSource.of(CxxSource.Type.CXX, new FakeSourcePath(name), ImmutableList.of());

      // Verify that platform flags make it to the compile rule.
      CxxPreprocessAndCompile cxxPreprocess =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(name, cxxSource);
      assertNotEquals(
          -1,
          Collections.indexOfSubList(
              Arg.stringify(
                  cxxPreprocess
                      .getPreprocessorDelegate()
                      .get()
                      .getCommand(CxxToolFlags.of(), Optional.empty()),
                  pathResolver),
              platformFlags));
      CxxPreprocessAndCompile cxxPreprocessAndCompile =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(name, cxxSource);
      assertNotEquals(
          -1,
          Collections.indexOfSubList(
              Arg.stringify(
                  cxxPreprocessAndCompile
                      .getPreprocessorDelegate()
                      .get()
                      .getCommand(CxxToolFlags.of(), Optional.empty()),
                  pathResolver),
              platformFlags));
    }

    @Test
    public void createCompileBuildRulePropagatesBuildRuleSourcePathDeps() {
      BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
      BuildRuleResolver resolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

      FakeBuildRule dep = createFakeBuildRule("//:test");
      dep.setOutputFile("foo");
      resolver.addToIndex(dep);
      SourcePath input = dep.getSourcePathToOutput();
      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(resolver)
              .setPathResolver(pathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(CXX_PLATFORM)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      String nameCompile = "foo/bar.ii";
      CxxSource cxxSourceCompile =
          CxxSource.of(CxxSource.Type.CXX_CPP_OUTPUT, input, ImmutableList.of());
      CxxPreprocessAndCompile cxxCompile =
          cxxSourceRuleFactory.requireCompileBuildRule(nameCompile, cxxSourceCompile);
      assertEquals(ImmutableSortedSet.<BuildRule>of(dep), cxxCompile.getBuildDeps());

      String namePreprocessAndCompile = "foo/bar.cpp";
      CxxSource cxxSourcePreprocessAndCompile =
          CxxSource.of(CxxSource.Type.CXX, input, ImmutableList.of());
      CxxPreprocessAndCompile cxxPreprocessAndCompile =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(
              namePreprocessAndCompile, cxxSourcePreprocessAndCompile);
      assertThat(
          DependencyAggregationTestUtil.getDisaggregatedDeps(cxxPreprocessAndCompile)::iterator,
          contains((BuildRule) dep));
    }

    @Test
    public void createCompileBuildRulePicOption() {
      BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
      BuildRuleResolver resolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
      Path scratchDir = Paths.get("scratchDir");

      CxxSourceRuleFactory.Builder cxxSourceRuleFactoryBuilder =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(resolver)
              .setPathResolver(pathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(CXX_PLATFORM);
      CxxSourceRuleFactory cxxSourceRuleFactoryPDC =
          cxxSourceRuleFactoryBuilder.setPicType(CxxSourceRuleFactory.PicType.PDC).build();
      CxxSourceRuleFactory cxxSourceRuleFactoryPIC =
          cxxSourceRuleFactoryBuilder.setPicType(CxxSourceRuleFactory.PicType.PIC).build();

      String name = "foo/bar.ii";
      CxxSource cxxSource =
          CxxSource.of(CxxSource.Type.CXX_CPP_OUTPUT, new FakeSourcePath(name), ImmutableList.of());

      // Verify building a non-PIC compile rule does *not* have the "-fPIC" flag and has the
      // expected compile target.
      CxxPreprocessAndCompile noPicCompile =
          cxxSourceRuleFactoryPDC.requireCompileBuildRule(name, cxxSource);
      assertFalse(
          noPicCompile
              .makeMainStep(pathResolver, scratchDir, false)
              .getCommand()
              .contains("-fPIC"));
      assertEquals(
          cxxSourceRuleFactoryPDC.createCompileBuildTarget(name), noPicCompile.getBuildTarget());

      // Verify building a PIC compile rule *does* have the "-fPIC" flag and has the
      // expected compile target.
      CxxPreprocessAndCompile picCompile =
          cxxSourceRuleFactoryPIC.requireCompileBuildRule(name, cxxSource);
      assertTrue(
          picCompile.makeMainStep(pathResolver, scratchDir, false).getCommand().contains("-fPIC"));
      assertEquals(
          cxxSourceRuleFactoryPIC.createCompileBuildTarget(name), picCompile.getBuildTarget());

      name = "foo/bar.cpp";
      cxxSource = CxxSource.of(CxxSource.Type.CXX, new FakeSourcePath(name), ImmutableList.of());

      // Verify building a non-PIC compile rule does *not* have the "-fPIC" flag and has the
      // expected compile target.
      CxxPreprocessAndCompile noPicPreprocessAndCompile =
          cxxSourceRuleFactoryPDC.requirePreprocessAndCompileBuildRule(name, cxxSource);
      assertFalse(
          noPicPreprocessAndCompile
              .makeMainStep(pathResolver, scratchDir, false)
              .getCommand()
              .contains("-fPIC"));
      assertEquals(
          cxxSourceRuleFactoryPDC.createCompileBuildTarget(name),
          noPicPreprocessAndCompile.getBuildTarget());

      // Verify building a PIC compile rule *does* have the "-fPIC" flag and has the
      // expected compile target.
      CxxPreprocessAndCompile picPreprocessAndCompile =
          cxxSourceRuleFactoryPIC.requirePreprocessAndCompileBuildRule(name, cxxSource);
      assertTrue(
          picPreprocessAndCompile
              .makeMainStep(pathResolver, scratchDir, false)
              .getCommand()
              .contains("-fPIC"));
      assertEquals(
          cxxSourceRuleFactoryPIC.createCompileBuildTarget(name),
          picPreprocessAndCompile.getBuildTarget());
    }

    @Test
    public void checkPrefixHeaderIsIncluded() {
      BuildRuleResolver buildRuleResolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(buildRuleResolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
      BuildTarget target = BuildTargetFactory.newInstance("//:target");
      ProjectFilesystem filesystem = new AllExistingProjectFilesystem();
      Path scratchDir = Paths.get("scratchDir");

      BuckConfig buckConfig =
          FakeBuckConfig.builder()
              .setFilesystem(filesystem)
              .setSections(ImmutableMap.of("cxx", ImmutableMap.of("pch_enabled", "false")))
              .build();
      CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(buckConfig);
      CxxPlatform platform = CxxPlatformUtils.build(cxxBuckConfig);

      String prefixHeaderName = "test.pch";
      SourcePath prefixHeaderSourcePath = new FakeSourcePath(filesystem, prefixHeaderName);

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(buildRuleResolver)
              .setPathResolver(pathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(cxxBuckConfig)
              .setCxxPlatform(platform)
              .setPrefixHeader(prefixHeaderSourcePath)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      String objcSourceName = "test.m";
      CxxSource objcSource =
          CxxSource.of(CxxSource.Type.OBJC, new FakeSourcePath(objcSourceName), ImmutableList.of());
      CxxPreprocessAndCompile objcPreprocessAndCompile =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(objcSourceName, objcSource);

      ImmutableList<String> explicitPrefixHeaderRelatedFlags =
          ImmutableList.of("-include", filesystem.resolve(prefixHeaderName).toString());

      CxxPreprocessAndCompileStep step =
          objcPreprocessAndCompile.makeMainStep(pathResolver, scratchDir, false);
      assertContains(step.getCommand(), explicitPrefixHeaderRelatedFlags);
    }

    @Test
    public void duplicateRuleFetchedFromResolverShouldCreateTheSameTarget() {
      BuildRuleResolver buildRuleResolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(buildRuleResolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
      BuildTarget target = BuildTargetFactory.newInstance("//:target");
      ProjectFilesystem filesystem = new AllExistingProjectFilesystem();

      BuckConfig buckConfig = FakeBuckConfig.builder().setFilesystem(filesystem).build();
      CxxPlatform platform = CxxPlatformUtils.build(new CxxBuckConfig(buckConfig));

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(buildRuleResolver)
              .setPathResolver(pathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(platform)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      String objcSourceName = "test.m";
      CxxSource objcSource =
          CxxSource.of(CxxSource.Type.OBJC, new FakeSourcePath(objcSourceName), ImmutableList.of());
      CxxPreprocessAndCompile objcCompile =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(objcSourceName, objcSource);

      // Make sure we can get the same build rule twice.
      CxxPreprocessAndCompile objcCompile2 =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(objcSourceName, objcSource);

      assertEquals(objcCompile.getBuildTarget(), objcCompile2.getBuildTarget());
    }

    @Test
    public void createPreprocessAndCompileBuildRulePropagatesToolDeps() throws Exception {
      BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
      BuildRuleResolver resolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

      ShBinary cxxpp =
          new ShBinaryBuilder(BuildTargetFactory.newInstance("//:cxxpp"))
              .setMain(new FakeSourcePath("blah"))
              .build(resolver);
      ShBinary cxx =
          new ShBinaryBuilder(BuildTargetFactory.newInstance("//:cxx"))
              .setMain(new FakeSourcePath("blah"))
              .build(resolver);

      CxxPlatform cxxPlatform =
          CXX_PLATFORM
              .withCxxpp(
                  new PreprocessorProvider(
                      new BinaryBuildRuleToolProvider(cxxpp.getBuildTarget(), ""),
                      CxxToolProvider.Type.GCC))
              .withCxx(
                  new CompilerProvider(
                      new BinaryBuildRuleToolProvider(cxx.getBuildTarget(), ""),
                      CxxToolProvider.Type.GCC));

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(resolver)
              .setPathResolver(pathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(cxxPlatform)
              .addCxxPreprocessorInput(CxxPreprocessorInput.EMPTY)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      String name = "foo/bar.cpp";
      SourcePath input = new PathSourcePath(PROJECT_FILESYSTEM, target.getBasePath().resolve(name));
      CxxSource cxxSource = CxxSource.of(CxxSource.Type.CXX, input, ImmutableList.of());

      BuildRule cxxPreprocess =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(name, cxxSource);
      assertThat(cxxPreprocess.getBuildDeps(), hasItems(cxx, cxxpp));
      cxxPreprocess = cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(name, cxxSource);
      assertThat(cxxPreprocess.getBuildDeps(), hasItems(cxx, cxxpp));
    }
  }

  @RunWith(Parameterized.class)
  public static class RulesForDifferentSourcesShouldCreateSeaparateTargets {
    @SuppressWarnings("serial")
    Map<String, String[]> testExampleSourceSets =
        new HashMap<String, String[]>() {
          {
            put("Preprocessable type", new String[] {"1/2/3.c", "1_2/3.c", "1/2_3.c", "1_2_3.c"});
            put("Compilable type", new String[] {"1/2/3.i", "1_2/3.i", "1/2_3.i", "1_2_3.i"});
            put(
                "Same file in different directories",
                new String[] {"one-path/file1.c", "another-path/file1.c"});
            put(
                "Various ASCII chars",
                new String[] {
                  "special/chars.c",
                  "special_chars.c",
                  "special chars.c",
                  "special!chars.c",
                  "special(chars.c",
                  "special,chars.c"
                });
            put(
                "Non-ASCII chars",
                new String[] {
                  "special/chars.c", "specialאchars.c", "special漢chars.c", "specialДchars.c"
                });
            put("One-char names", new String[] {"_.c", ",.c", "漢.c"});
          }
        };

    @Parameterized.Parameters(name = "{0}")
    public static Collection<Object> data() {
      return Arrays.asList(
          new Object[] {
            "Preprocessable type",
            "Compilable type",
            "Same file in different directories",
            "Various ASCII chars",
            "Non-ASCII chars",
            "One-char names",
          });
    }

    @Parameterized.Parameter(0)
    public String testExampleSourceSet;

    @Test
    public void test() {
      BuildRuleResolver buildRuleResolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(buildRuleResolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
      BuildTarget target = BuildTargetFactory.newInstance("//:target");
      ProjectFilesystem filesystem = new AllExistingProjectFilesystem();

      BuckConfig buckConfig = FakeBuckConfig.builder().setFilesystem(filesystem).build();
      CxxPlatform platform = CxxPlatformUtils.build(new CxxBuckConfig(buckConfig));

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(buildRuleResolver)
              .setPathResolver(pathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(platform)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      String[] sourceNames = testExampleSourceSets.get(testExampleSourceSet);
      Map<String, CxxSource> sources = new HashMap<>();
      for (String sourceName : sourceNames) {
        sources.put(
            sourceName,
            CxxSource.of(CxxSource.Type.OBJC, new FakeSourcePath(sourceName), ImmutableList.of()));
      }

      ImmutableMap<CxxPreprocessAndCompile, SourcePath> rules =
          cxxSourceRuleFactory.requirePreprocessAndCompileRules(ImmutableMap.copyOf(sources));

      assertEquals(
          String.format("Expected %d rules, but found only %d", sourceNames.length, rules.size()),
          sourceNames.length,
          rules.size());
    }
  }

  @RunWith(Parameterized.class)
  public static class CorrectFlagsAreUsedForCompileAndPreprocessBuildRules {

    private static final ImmutableList<String> asflags = ImmutableList.of("-asflag", "-asflag");
    private static final ImmutableList<String> cflags = ImmutableList.of("-cflag", "-cflag");
    private static final ImmutableList<String> cxxflags = ImmutableList.of("-cxxflag", "-cxxflag");
    private static final ImmutableList<String> asppflags =
        ImmutableList.of("-asppflag", "-asppflag");
    private static final ImmutableList<String> cppflags = ImmutableList.of("-cppflag", "-cppflag");
    private static final ImmutableList<String> cxxppflags =
        ImmutableList.of("-cxxppflag", "-cxxppflag");

    private static final ImmutableList<String> explicitCompilerFlags =
        ImmutableList.of("-explicit-compilerflag");
    private static final ImmutableList<String> explicitCppflags =
        ImmutableList.of("-explicit-cppflag");
    private static final ImmutableList<String> explicitCxxppflags =
        ImmutableList.of("-explicit-cxxppflag");

    private static final ImmutableList<String> empty = ImmutableList.of();

    @Parameterized.Parameters(name = "{0}")
    public static Collection<Object[]> data() {
      return Arrays.asList(
          new Object[][] {
            {"test.i", cflags, explicitCompilerFlags, empty, empty},
            {"test.c", cflags, explicitCompilerFlags, cppflags, explicitCppflags},
            {"test.ii", cxxflags, explicitCompilerFlags, empty, empty},
            {"test.cpp", cxxflags, explicitCompilerFlags, cxxppflags, explicitCxxppflags},

            // asm do not have compiler specific flags, nor (non-as) file type specific flags.
            {"test.s", empty, empty, asppflags, explicitCppflags},

            // ObjC
            {"test.mi", cflags, explicitCompilerFlags, empty, empty},
            {"test.m", cflags, explicitCompilerFlags, cppflags, explicitCppflags},
            {"test.mii", cxxflags, explicitCompilerFlags, empty, empty},
            {"test.mm", cxxflags, explicitCompilerFlags, cxxppflags, explicitCxxppflags},
          });
    }

    @Parameterized.Parameter(0)
    public String sourceName;

    @Parameterized.Parameter(1)
    public ImmutableList<String> expectedTypeSpecificFlags;

    @Parameterized.Parameter(2)
    public ImmutableList<String> expectedCompilerFlags;

    @Parameterized.Parameter(3)
    public ImmutableList<String> expectedTypeSpecificPreprocessorFlags;

    @Parameterized.Parameter(4)
    public ImmutableList<String> expectedPreprocessorFlags;

    // Some common boilerplate.
    private BuildRuleResolver buildRuleResolver =
        new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
    private SourcePathRuleFinder sourcePathRuleFinder = new SourcePathRuleFinder(buildRuleResolver);
    private SourcePathResolver sourcePathResolver =
        DefaultSourcePathResolver.from(sourcePathRuleFinder);
    private BuildTarget target = BuildTargetFactory.newInstance("//:target");
    private Joiner space = Joiner.on(" ");

    @Test
    public void forPreprocess() {
      CxxSource.Type sourceType =
          CxxSource.Type.fromExtension(MorePaths.getFileExtension(Paths.get(sourceName))).get();
      Assume.assumeTrue(sourceType.isPreprocessable());

      CxxPreprocessorInput cxxPreprocessorInput =
          CxxPreprocessorInput.builder()
              .putAllPreprocessorFlags(CxxSource.Type.C, StringArg.from(explicitCppflags))
              .putAllPreprocessorFlags(CxxSource.Type.OBJC, StringArg.from(explicitCppflags))
              .putAllPreprocessorFlags(
                  CxxSource.Type.ASSEMBLER_WITH_CPP, StringArg.from(explicitCppflags))
              .putAllPreprocessorFlags(CxxSource.Type.CXX, StringArg.from(explicitCxxppflags))
              .putAllPreprocessorFlags(CxxSource.Type.OBJCXX, StringArg.from(explicitCxxppflags))
              .build();
      BuckConfig buckConfig =
          FakeBuckConfig.builder()
              .setSections(
                  ImmutableMap.of(
                      "cxx",
                      ImmutableMap.<String, String>builder()
                          .put("asppflags", space.join(asppflags))
                          .put("cppflags", space.join(cppflags))
                          .put("cxxppflags", space.join(cxxppflags))
                          .build()))
              .setFilesystem(PROJECT_FILESYSTEM)
              .build();
      CxxPlatform platform = CxxPlatformUtils.build(new CxxBuckConfig(buckConfig));

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(buildRuleResolver)
              .setPathResolver(sourcePathResolver)
              .setRuleFinder(sourcePathRuleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(platform)
              .addCxxPreprocessorInput(cxxPreprocessorInput)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      List<String> perFileFlags = ImmutableList.of("-per-file-flag", "-and-another-per-file-flag");
      CxxSource cSource = CxxSource.of(sourceType, new FakeSourcePath(sourceName), perFileFlags);
      CxxPreprocessAndCompile cPreprocess =
          cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(sourceName, cSource);
      ImmutableList<String> cPreprocessCommand =
          Arg.stringify(
              cPreprocess
                  .getPreprocessorDelegate()
                  .get()
                  .getCommand(CxxToolFlags.of(), Optional.empty()),
              sourcePathResolver);
      assertContains(cPreprocessCommand, expectedTypeSpecificPreprocessorFlags);
      assertContains(cPreprocessCommand, expectedPreprocessorFlags);
      assertContains(cPreprocessCommand, perFileFlags);
    }

    @Test
    public void forCompile() {
      CxxSource.Type sourceType =
          CxxSource.Type.fromExtension(MorePaths.getFileExtension(Paths.get(sourceName))).get();

      Path scratchDir = Paths.get("scratchDir");
      BuckConfig buckConfig =
          FakeBuckConfig.builder()
              .setSections(
                  ImmutableMap.of(
                      "cxx",
                      ImmutableMap.<String, String>builder()
                          .put("asflags", space.join(asflags))
                          .put("cflags", space.join(cflags))
                          .put("cxxflags", space.join(cxxflags))
                          .build()))
              .setFilesystem(PROJECT_FILESYSTEM)
              .build();
      CxxPlatform platform = CxxPlatformUtils.build(new CxxBuckConfig(buckConfig));

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(buildRuleResolver)
              .setPathResolver(sourcePathResolver)
              .setRuleFinder(sourcePathRuleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(platform)
              .setCompilerFlags(CxxFlags.toLanguageFlags(StringArg.from(expectedCompilerFlags)))
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      List<String> perFileFlags = ImmutableList.of("-per-file-flag");
      CxxSource source = CxxSource.of(sourceType, new FakeSourcePath(sourceName), perFileFlags);
      CxxPreprocessAndCompile rule;
      if (source.getType().isPreprocessable()) {
        rule = cxxSourceRuleFactory.requirePreprocessAndCompileBuildRule(sourceName, source);
      } else {
        rule = cxxSourceRuleFactory.requireCompileBuildRule(sourceName, source);
      }
      ImmutableList<String> command =
          rule.makeMainStep(sourcePathResolver, scratchDir, false).getCommand();
      assertContains(command, expectedCompilerFlags);
      assertContains(command, expectedTypeSpecificFlags);
      assertContains(command, asflags);
      assertContains(command, perFileFlags);
    }

    @Test
    public void testHashStringsWithAndWithoutIncludePaths() {
      CxxSource.Type sourceType =
          CxxSource.Type.fromExtension(MorePaths.getFileExtension(Paths.get(sourceName))).get();
      Assume.assumeTrue(sourceType.isPreprocessable());

      BuildRuleResolver ruleResolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver);
      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

      CxxPreprocessorInput cxxPreprocessorInput =
          CxxPreprocessorInput.builder()
              .addIncludes(
                  CxxHeadersDir.of(
                      CxxPreprocessables.IncludeType.SYSTEM, new FakeSourcePath("/tmp/sys")))
              .build();

      BuckConfig buckConfig =
          FakeBuckConfig.builder()
              .setSections(
                  ImmutableMap.of(
                      "cxx",
                      ImmutableMap.<String, String>builder()
                          .put("cflags", "-fno-omit-frame-pointer")
                          .put("cxxflags", "-fno-rtti -fno-exceptions")
                          .build()))
              .setFilesystem(PROJECT_FILESYSTEM)
              .build();
      CxxPlatform platform = CxxPlatformUtils.build(new CxxBuckConfig(buckConfig));

      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(ruleResolver)
              .setRuleFinder(ruleFinder)
              .setPathResolver(pathResolver)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(platform)
              .addCxxPreprocessorInput(cxxPreprocessorInput)
              .setCompilerFlags(CxxFlags.toLanguageFlags(StringArg.from(expectedCompilerFlags)))
              .setPicType(CxxSourceRuleFactory.PicType.PIC)
              .build();

      CxxSource source =
          CxxSource.of(sourceType, new FakeSourcePath(sourceName), ImmutableList.of("-DFOO=1"));

      ImmutableList<String> withPaths =
          Arg.stringify(cxxSourceRuleFactory.getFlagsForSource(source, true), pathResolver);
      ImmutableList<String> withoutPaths =
          Arg.stringify(cxxSourceRuleFactory.getFlagsForSource(source, false), pathResolver);

      // these should differ by include path flags:
      assertNotEquals(-1, Joiner.on("#").join(withPaths).indexOf("-isystem#/tmp/sys"));
      assertEquals(-1, Joiner.on("#").join(withoutPaths).indexOf("-isystem#/tmp/sys"));

      // the "with" set is a strict superset of the "without" set
      assertContains(withPaths, withoutPaths);

      // things that should be in both:
      // per-source-file flag:
      assertContains(withPaths, ImmutableList.of("-DFOO=1"));
      assertContains(withoutPaths, ImmutableList.of("-DFOO=1"));
      // pic option, set in the cxxSourceRuleFactory:
      assertContains(withPaths, ImmutableList.of("-fPIC"));
      assertContains(withoutPaths, ImmutableList.of("-fPIC"));
    }
  }

  @RunWith(Parameterized.class)
  public static class LanguageFlagsArePassed {
    @Parameterized.Parameters(name = "{0} -> {1}")
    public static Collection<Object[]> data() {
      return Arrays.asList(
          new Object[][] {
            {"foo/bar.ii", "c++-cpp-output"},
            {"foo/bar.mi", "objective-c-cpp-output"},
            {"foo/bar.mii", "objective-c++-cpp-output"},
            {"foo/bar.i", "cpp-output"},
          });
    }

    @Parameterized.Parameter(0)
    public String name;

    @Parameterized.Parameter(1)
    public String expected;

    @Test
    public void test() {
      BuildRuleResolver buildRuleResolver =
          new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(buildRuleResolver);
      SourcePathResolver sourcePathResolver = DefaultSourcePathResolver.from(ruleFinder);
      BuildTarget target = BuildTargetFactory.newInstance("//:target");
      Path scratchDir = Paths.get("scratchDir");
      CxxSourceRuleFactory cxxSourceRuleFactory =
          CxxSourceRuleFactory.builder()
              .setProjectFilesystem(PROJECT_FILESYSTEM)
              .setBaseBuildTarget(target)
              .setResolver(buildRuleResolver)
              .setPathResolver(sourcePathResolver)
              .setRuleFinder(ruleFinder)
              .setCxxBuckConfig(CxxPlatformUtils.DEFAULT_CONFIG)
              .setCxxPlatform(CXX_PLATFORM)
              .setPicType(CxxSourceRuleFactory.PicType.PDC)
              .build();

      SourcePath input = new PathSourcePath(PROJECT_FILESYSTEM, target.getBasePath().resolve(name));
      CxxSource cxxSource =
          CxxSource.of(
              CxxSource.Type.fromExtension(MorePaths.getFileExtension(Paths.get(name))).get(),
              input,
              ImmutableList.of());
      CxxPreprocessAndCompile cxxCompile =
          cxxSourceRuleFactory.requireCompileBuildRule(name, cxxSource);
      assertThat(
          cxxCompile.makeMainStep(sourcePathResolver, scratchDir, false).getCommand(),
          hasItems("-x", expected));
    }
  }
}


text:
package org.openqa.selenium.remote.server.handler;

import org.openqa.selenium.remote.server.Session;

public class AcceptAlert extends WebDriverHandler<Void> {
  public AcceptAlert(Session session) {
    super(session);
  }

  @Override
  public Void call() {
    getDriver().switchTo().alert().accept();
    return null;
  }

  @Override
  public String toString() {
    return "[accept alert]";
  }
}

redpajama_set_name: RedPajamaGithub


text:
BEGIN;
UPDATE zabbix_partition_arch
   SET archive_ind = :v_archive_ind
      ,archive_full_path_name = :v_archive_full_path
      ,dtmodified = localtimestamp
 WHERE archive_table_name = :v_arch_table_name;
INSERT INTO zabbix_partition_log (
 pk1,
 zabbix_partition_pk1,
 dtcreated,
 message )
VALUES (
 nextval('zabbix_partition_log_seq'),
 :v_zabbix_partition_pk1,
 localtimestamp,
 'Archive old partion ' || :v_arch_table_name || ' to ' || :v_archive_full_path );
COMMIT;


text:
#include <aws/cloudformation/model/Output.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace CloudFormation
{
namespace Model
{

Output::Output() :
    m_outputKeyHasBeenSet(false),
    m_outputValueHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_exportNameHasBeenSet(false)
{
}

Output::Output(const XmlNode& xmlNode) :
    m_outputKeyHasBeenSet(false),
    m_outputValueHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_exportNameHasBeenSet(false)
{
  *this = xmlNode;
}

Output& Output::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode outputKeyNode = resultNode.FirstChild("OutputKey");
    if(!outputKeyNode.IsNull())
    {
      m_outputKey = StringUtils::Trim(outputKeyNode.GetText().c_str());
      m_outputKeyHasBeenSet = true;
    }
    XmlNode outputValueNode = resultNode.FirstChild("OutputValue");
    if(!outputValueNode.IsNull())
    {
      m_outputValue = StringUtils::Trim(outputValueNode.GetText().c_str());
      m_outputValueHasBeenSet = true;
    }
    XmlNode descriptionNode = resultNode.FirstChild("Description");
    if(!descriptionNode.IsNull())
    {
      m_description = StringUtils::Trim(descriptionNode.GetText().c_str());
      m_descriptionHasBeenSet = true;
    }
    XmlNode exportNameNode = resultNode.FirstChild("ExportName");
    if(!exportNameNode.IsNull())
    {
      m_exportName = StringUtils::Trim(exportNameNode.GetText().c_str());
      m_exportNameHasBeenSet = true;
    }
  }

  return *this;
}

void Output::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_outputKeyHasBeenSet)
  {
      oStream << location << index << locationValue << ".OutputKey=" << StringUtils::URLEncode(m_outputKey.c_str()) << "&";
  }

  if(m_outputValueHasBeenSet)
  {
      oStream << location << index << locationValue << ".OutputValue=" << StringUtils::URLEncode(m_outputValue.c_str()) << "&";
  }

  if(m_descriptionHasBeenSet)
  {
      oStream << location << index << locationValue << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&";
  }

  if(m_exportNameHasBeenSet)
  {
      oStream << location << index << locationValue << ".ExportName=" << StringUtils::URLEncode(m_exportName.c_str()) << "&";
  }

}

void Output::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_outputKeyHasBeenSet)
  {
      oStream << location << ".OutputKey=" << StringUtils::URLEncode(m_outputKey.c_str()) << "&";
  }
  if(m_outputValueHasBeenSet)
  {
      oStream << location << ".OutputValue=" << StringUtils::URLEncode(m_outputValue.c_str()) << "&";
  }
  if(m_descriptionHasBeenSet)
  {
      oStream << location << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&";
  }
  if(m_exportNameHasBeenSet)
  {
      oStream << location << ".ExportName=" << StringUtils::URLEncode(m_exportName.c_str()) << "&";
  }
}

} // namespace Model
} // namespace CloudFormation
} // namespace Aws


text:
package apple.mediaplayer;

import apple.NSObject;
import apple.coregraphics.struct.CGSize;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.NSURL;
import apple.mediaplayer.protocol.MPMediaPlayback;
import apple.uikit.UIImage;
import apple.uikit.UIView;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * -----------------------------------------------------------------------------
 * Movie Player
 * <p>
 * See MPMediaPlayback.h for the playback methods.
 */
@Deprecated
@Generated
@Library("MediaPlayer")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class MPMoviePlayerController extends NSObject implements MPMediaPlayback {
    static {
        NatJ.register();
    }

    @Generated
    protected MPMoviePlayerController(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native MPMoviePlayerController alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native MPMoviePlayerController allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native MPMoviePlayerController new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    /**
     * Returns an object that represents a snapshot of the network access log. Can be nil.
     */
    @Generated
    @Deprecated
    @Selector("accessLog")
    public native MPMovieAccessLog accessLog();

    /**
     * Indicates whether the movie player allows AirPlay video playback. Defaults to YES on iOS 5.0 and later.
     */
    @Deprecated
    @Generated
    @Selector("allowsAirPlay")
    public native boolean allowsAirPlay();

    /**
     * A view for customization which is always displayed behind movie content.
     */
    @Deprecated
    @Generated
    @Selector("backgroundView")
    public native UIView backgroundView();

    @Generated
    @Selector("beginSeekingBackward")
    public native void beginSeekingBackward();

    @Generated
    @Selector("beginSeekingForward")
    public native void beginSeekingForward();

    /**
     * Cancels all pending asynchronous thumbnail requests.
     */
    @Deprecated
    @Generated
    @Selector("cancelAllThumbnailImageRequests")
    public native void cancelAllThumbnailImageRequests();

    @Deprecated
    @Generated
    @Selector("contentURL")
    public native NSURL contentURL();

    /**
     * The style of the playback controls. Defaults to MPMovieControlStyleDefault.
     */
    @Deprecated
    @Generated
    @Selector("controlStyle")
    @NInt
    public native long controlStyle();

    @Generated
    @Selector("currentPlaybackRate")
    public native float currentPlaybackRate();

    @Generated
    @Selector("currentPlaybackTime")
    public native double currentPlaybackTime();

    /**
     * The duration of the movie, or 0.0 if not known.
     */
    @Deprecated
    @Generated
    @Selector("duration")
    public native double duration();

    /**
     * The end time of movie playback. Defaults to NaN, which indicates natural end time of the movie.
     */
    @Deprecated
    @Generated
    @Selector("endPlaybackTime")
    public native double endPlaybackTime();

    @Generated
    @Selector("endSeeking")
    public native void endSeeking();

    /**
     * Returns an object that represents a snapshot of the error log. Can be nil.
     */
    @Generated
    @Deprecated
    @Selector("errorLog")
    public native MPMovieErrorLog errorLog();

    @Generated
    @Selector("init")
    public native MPMoviePlayerController init();

    @Deprecated
    @Generated
    @Selector("initWithContentURL:")
    public native MPMoviePlayerController initWithContentURL(NSURL url);

    /**
     * The start time of movie playback. Defaults to NaN, indicating the natural start time of the movie.
     */
    @Deprecated
    @Generated
    @Selector("initialPlaybackTime")
    public native double initialPlaybackTime();

    /**
     * Indicates whether the movie player is currently playing video via AirPlay.
     */
    @Deprecated
    @Generated
    @Selector("isAirPlayVideoActive")
    public native boolean isAirPlayVideoActive();

    /**
     * Determines if the movie is presented in the entire screen (obscuring all other application content). Default is
     * NO.
     * Setting this property to YES before the movie player's view is visible will have no effect.
     */
    @Deprecated
    @Generated
    @Selector("isFullscreen")
    public native boolean isFullscreen();

    /**
     * Determines if the movie is presented in the entire screen (obscuring all other application content). Default is
     * NO.
     * Setting this property to YES before the movie player's view is visible will have no effect.
     */
    @Deprecated
    @Generated
    @Selector("setFullscreen:")
    public native void setFullscreen(boolean value);

    @Generated
    @Selector("isPreparedToPlay")
    public native boolean isPreparedToPlay();

    /**
     * Returns the network load state of the movie player.
     */
    @Deprecated
    @Generated
    @Selector("loadState")
    @NUInt
    public native long loadState();

    /**
     * The types of media in the movie, or MPMovieMediaTypeNone if not known.
     */
    @Deprecated
    @Generated
    @Selector("movieMediaTypes")
    @NUInt
    public native long movieMediaTypes();

    /**
     * The playback type of the movie. Defaults to MPMovieSourceTypeUnknown.
     * Specifying a playback type before playing the movie can result in faster load times.
     */
    @Deprecated
    @Generated
    @Selector("movieSourceType")
    @NInt
    public native long movieSourceType();

    /**
     * The natural size of the movie, or CGSizeZero if not known/applicable.
     */
    @Deprecated
    @Generated
    @Selector("naturalSize")
    @ByValue
    public native CGSize naturalSize();

    @Generated
    @Selector("pause")
    public native void pause();

    @Generated
    @Selector("play")
    public native void play();

    /**
     * The currently playable duration of the movie, for progressively downloaded network content.
     */
    @Deprecated
    @Generated
    @Selector("playableDuration")
    public native double playableDuration();

    /**
     * Returns the current playback state of the movie player.
     */
    @Deprecated
    @Generated
    @Selector("playbackState")
    @NInt
    public native long playbackState();

    @Generated
    @Selector("prepareToPlay")
    public native void prepareToPlay();

    /**
     * Returns YES if the first video frame has been made ready for display for the current item.
     * Will remain NO for items that do not have video tracks associated.
     */
    @Generated
    @Selector("readyForDisplay")
    public native boolean readyForDisplay();

    /**
     * Determines how the movie player repeats when reaching the end of playback. Defaults to MPMovieRepeatModeNone.
     */
    @Deprecated
    @Generated
    @Selector("repeatMode")
    @NInt
    public native long repeatMode();

    /**
     * Asynchronously request thumbnails for one or more times, provided as an array of NSNumbers (double).
     * Posts MPMoviePlayerThumbnailImageRequestDidFinishNotification on completion.
     */
    @Deprecated
    @Generated
    @Selector("requestThumbnailImagesAtTimes:timeOption:")
    public native void requestThumbnailImagesAtTimesTimeOption(NSArray<?> playbackTimes, @NInt long option);

    /**
     * Determines how the content scales to fit the view. Defaults to MPMovieScalingModeAspectFit.
     */
    @Deprecated
    @Generated
    @Selector("scalingMode")
    @NInt
    public native long scalingMode();

    /**
     * Indicates whether the movie player allows AirPlay video playback. Defaults to YES on iOS 5.0 and later.
     */
    @Deprecated
    @Generated
    @Selector("setAllowsAirPlay:")
    public native void setAllowsAirPlay(boolean value);

    @Deprecated
    @Generated
    @Selector("setContentURL:")
    public native void setContentURL(NSURL value);

    /**
     * The style of the playback controls. Defaults to MPMovieControlStyleDefault.
     */
    @Deprecated
    @Generated
    @Selector("setControlStyle:")
    public native void setControlStyle(@NInt long value);

    @Generated
    @Selector("setCurrentPlaybackRate:")
    public native void setCurrentPlaybackRate(float value);

    @Generated
    @Selector("setCurrentPlaybackTime:")
    public native void setCurrentPlaybackTime(double value);

    /**
     * The end time of movie playback. Defaults to NaN, which indicates natural end time of the movie.
     */
    @Deprecated
    @Generated
    @Selector("setEndPlaybackTime:")
    public native void setEndPlaybackTime(double value);

    @Deprecated
    @Generated
    @Selector("setFullscreen:animated:")
    public native void setFullscreenAnimated(boolean fullscreen, boolean animated);

    /**
     * The start time of movie playback. Defaults to NaN, indicating the natural start time of the movie.
     */
    @Deprecated
    @Generated
    @Selector("setInitialPlaybackTime:")
    public native void setInitialPlaybackTime(double value);

    /**
     * The playback type of the movie. Defaults to MPMovieSourceTypeUnknown.
     * Specifying a playback type before playing the movie can result in faster load times.
     */
    @Deprecated
    @Generated
    @Selector("setMovieSourceType:")
    public native void setMovieSourceType(@NInt long value);

    /**
     * Determines how the movie player repeats when reaching the end of playback. Defaults to MPMovieRepeatModeNone.
     */
    @Deprecated
    @Generated
    @Selector("setRepeatMode:")
    public native void setRepeatMode(@NInt long value);

    /**
     * Determines how the content scales to fit the view. Defaults to MPMovieScalingModeAspectFit.
     */
    @Deprecated
    @Generated
    @Selector("setScalingMode:")
    public native void setScalingMode(@NInt long value);

    /**
     * Indicates if a movie should automatically start playback when it is likely to finish uninterrupted based on e.g.
     * network conditions. Defaults to YES.
     */
    @Deprecated
    @Generated
    @Selector("setShouldAutoplay:")
    public native void setShouldAutoplay(boolean value);

    /**
     * Indicates if the movie player should inherit the application's audio session instead of creating a new session
     * (which would interrupt the application's session).
     * Defaults to YES. Setting this property during playback will not take effect until playback is stopped and started
     * again.
     */
    @Generated
    @Deprecated
    @Selector("setUseApplicationAudioSession:")
    public native void setUseApplicationAudioSession(boolean value);

    /**
     * Indicates if a movie should automatically start playback when it is likely to finish uninterrupted based on e.g.
     * network conditions. Defaults to YES.
     */
    @Deprecated
    @Generated
    @Selector("shouldAutoplay")
    public native boolean shouldAutoplay();

    @Generated
    @Selector("stop")
    public native void stop();

    /**
     * Returns a thumbnail at the given time.
     * Deprecated. Use -requestThumbnailImagesAtTimes:timeOption: /
     * MPMoviePlayerThumbnailImageRequestDidFinishNotification instead.
     */
    @Deprecated
    @Generated
    @Selector("thumbnailImageAtTime:timeOption:")
    public native UIImage thumbnailImageAtTimeTimeOption(double playbackTime, @NInt long option);

    /**
     * Returns an array of the most recent MPTimedMetadata objects provided by the media stream.
     */
    @Generated
    @Deprecated
    @Selector("timedMetadata")
    public native NSArray<?> timedMetadata();

    /**
     * Indicates if the movie player should inherit the application's audio session instead of creating a new session
     * (which would interrupt the application's session).
     * Defaults to YES. Setting this property during playback will not take effect until playback is stopped and started
     * again.
     */
    @Generated
    @Deprecated
    @Selector("useApplicationAudioSession")
    public native boolean useApplicationAudioSession();

    /**
     * The view in which the media and playback controls are displayed.
     */
    @Deprecated
    @Generated
    @Selector("view")
    public native UIView view();
}


text:
package com.nirima.jenkins.plugins.docker.client;

import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.common.CertificateCredentials;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.KeystoreSSLConfig;
import com.nirima.jenkins.plugins.docker.DockerCloud;
import hudson.security.ACL;
import jenkins.model.Jenkins;

import javax.annotation.Nullable;
import java.net.URI;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.cloudbees.plugins.credentials.CredentialsMatchers.firstOrNull;
import static com.cloudbees.plugins.credentials.CredentialsMatchers.withId;
import static com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials;
import static com.github.dockerjava.core.DockerClientConfig.createDefaultConfigBuilder;
import static org.apache.commons.lang.StringUtils.isNotBlank;

/**
 * @author lanwen (Merkushev Kirill)
 */
public class ClientConfigBuilderForPlugin {

    private static final Logger LOGGER = Logger.getLogger(ClientConfigBuilderForPlugin.class.getName());

    private DockerClientConfig.DockerClientConfigBuilder config = createDefaultConfigBuilder();

    private ClientConfigBuilderForPlugin() {
    }

    public static ClientConfigBuilderForPlugin dockerClientConfig() {
        return new ClientConfigBuilderForPlugin();
    }

    /**
     * Provides ready to use docker client with information from docker cloud
     *
     * @param cloud docker cloud with info about url, version, creds and timeout
     *
     * @return docker-java client
     */
    public ClientConfigBuilderForPlugin forCloud(DockerCloud cloud) {
        LOGGER.log(Level.FINE, "Building connection to docker host \"{0}\" at: {1}",
                new Object[]{cloud.getDisplayName(), cloud.serverUrl});

        forServer(cloud.serverUrl, cloud.version);

        return withCredentials(cloud.credentialsId);
    }

    /**
     * Method to setup url and docker-api version. Convenient for test-connection purposes and quick requests
     *
     * @param uri     docker server uri
     * @param version docker-api version
     *
     * @return this builder
     */
    public ClientConfigBuilderForPlugin forServer(String uri, @Nullable String version) {
        config.withUri(URI.create(uri).toString())
                .withVersion(version);
        return this;
    }

    /**
     * Sets username and password or ssl config by credentials id
     *
     * @param credentialsId credentials to find in jenkins
     *
     * @return docker-java client
     */
    public ClientConfigBuilderForPlugin withCredentials(String credentialsId) {
        if (isNotBlank(credentialsId)) {
            Credentials credentials = lookupSystemCredentials(credentialsId);

            if (credentials instanceof CertificateCredentials) {
                CertificateCredentials certificateCredentials = (CertificateCredentials) credentials;
                config.withSSLConfig(new KeystoreSSLConfig(
                        certificateCredentials.getKeyStore(),
                        certificateCredentials.getPassword().getPlainText()
                ));
            } else if (credentials instanceof StandardUsernamePasswordCredentials) {
                StandardUsernamePasswordCredentials usernamePasswordCredentials =
                        ((StandardUsernamePasswordCredentials) credentials);

                config.withUsername(usernamePasswordCredentials.getUsername());
                config.withPassword(usernamePasswordCredentials.getPassword().getPlainText());
            }
        }
        return this;
    }

    /**
     * Build the config
     * @return
     */
    public DockerClientConfig build() {
        return config.build();
    }

    /**
     * Shortcut to build an actual client.
     *
     * Consider if you actually want to do this or alternatively
     * build the config then build the client, as if your activity is on a remote
     * node, the client will fail to serialize.
     * @return
     */
    public DockerClient buildClient() {
        return ClientBuilderForPlugin.builder().withDockerClientConfig(build()).build();
    }

    /**
     * For test purposes mostly
     *
     * @return docker config builder
     */
    /* package */ DockerClientConfig.DockerClientConfigBuilder config() {
        return config;
    }

    /**
     * Util method to find credential by id in jenkins
     *
     * @param credentialsId credentials to find in jenkins
     *
     * @return {@link CertificateCredentials} or {@link StandardUsernamePasswordCredentials} expected
     */
    private static Credentials lookupSystemCredentials(String credentialsId) {
        return firstOrNull(
                lookupCredentials(
                        Credentials.class,
                        Jenkins.getInstance(),
                        ACL.SYSTEM,
                        Collections.<DomainRequirement>emptyList()
                ),
                withId(credentialsId)
        );
    }

}


text:
// Code generated by go-swagger; DO NOT EDIT.

package operations

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/3dsim/simulation-goclient/models"
)

// GetBuildFileGeometryURLReader is a Reader for the GetBuildFileGeometryURL structure.
type GetBuildFileGeometryURLReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *GetBuildFileGeometryURLReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewGetBuildFileGeometryURLOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 401:
		result := NewGetBuildFileGeometryURLUnauthorized()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 403:
		result := NewGetBuildFileGeometryURLForbidden()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 404:
		result := NewGetBuildFileGeometryURLNotFound()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		result := NewGetBuildFileGeometryURLDefault(response.Code())
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		if response.Code()/100 == 2 {
			return result, nil
		}
		return nil, result
	}
}

// NewGetBuildFileGeometryURLOK creates a GetBuildFileGeometryURLOK with default headers values
func NewGetBuildFileGeometryURLOK() *GetBuildFileGeometryURLOK {
	return &GetBuildFileGeometryURLOK{}
}

/*GetBuildFileGeometryURLOK handles this case with default header values.

URL to the part STL file
*/
type GetBuildFileGeometryURLOK struct {
	Payload string
}

func (o *GetBuildFileGeometryURLOK) Error() string {
	return fmt.Sprintf("[GET /buildfiles/{id}/geometryurl][%d] getBuildFileGeometryUrlOK  %+v", 200, o.Payload)
}

func (o *GetBuildFileGeometryURLOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	// response payload
	if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewGetBuildFileGeometryURLUnauthorized creates a GetBuildFileGeometryURLUnauthorized with default headers values
func NewGetBuildFileGeometryURLUnauthorized() *GetBuildFileGeometryURLUnauthorized {
	return &GetBuildFileGeometryURLUnauthorized{}
}

/*GetBuildFileGeometryURLUnauthorized handles this case with default header values.

Not authorized
*/
type GetBuildFileGeometryURLUnauthorized struct {
	Payload *models.Error
}

func (o *GetBuildFileGeometryURLUnauthorized) Error() string {
	return fmt.Sprintf("[GET /buildfiles/{id}/geometryurl][%d] getBuildFileGeometryUrlUnauthorized  %+v", 401, o.Payload)
}

func (o *GetBuildFileGeometryURLUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.Error)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewGetBuildFileGeometryURLForbidden creates a GetBuildFileGeometryURLForbidden with default headers values
func NewGetBuildFileGeometryURLForbidden() *GetBuildFileGeometryURLForbidden {
	return &GetBuildFileGeometryURLForbidden{}
}

/*GetBuildFileGeometryURLForbidden handles this case with default header values.

Forbidden
*/
type GetBuildFileGeometryURLForbidden struct {
	Payload *models.Error
}

func (o *GetBuildFileGeometryURLForbidden) Error() string {
	return fmt.Sprintf("[GET /buildfiles/{id}/geometryurl][%d] getBuildFileGeometryUrlForbidden  %+v", 403, o.Payload)
}

func (o *GetBuildFileGeometryURLForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.Error)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewGetBuildFileGeometryURLNotFound creates a GetBuildFileGeometryURLNotFound with default headers values
func NewGetBuildFileGeometryURLNotFound() *GetBuildFileGeometryURLNotFound {
	return &GetBuildFileGeometryURLNotFound{}
}

/*GetBuildFileGeometryURLNotFound handles this case with default header values.

build file not found
*/
type GetBuildFileGeometryURLNotFound struct {
}

func (o *GetBuildFileGeometryURLNotFound) Error() string {
	return fmt.Sprintf("[GET /buildfiles/{id}/geometryurl][%d] getBuildFileGeometryUrlNotFound ", 404)
}

func (o *GetBuildFileGeometryURLNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	return nil
}

// NewGetBuildFileGeometryURLDefault creates a GetBuildFileGeometryURLDefault with default headers values
func NewGetBuildFileGeometryURLDefault(code int) *GetBuildFileGeometryURLDefault {
	return &GetBuildFileGeometryURLDefault{
		_statusCode: code,
	}
}

/*GetBuildFileGeometryURLDefault handles this case with default header values.

unexpected error
*/
type GetBuildFileGeometryURLDefault struct {
	_statusCode int

	Payload *models.Error
}

// Code gets the status code for the get build file geometry Url default response
func (o *GetBuildFileGeometryURLDefault) Code() int {
	return o._statusCode
}

func (o *GetBuildFileGeometryURLDefault) Error() string {
	return fmt.Sprintf("[GET /buildfiles/{id}/geometryurl][%d] getBuildFileGeometryUrl default  %+v", o._statusCode, o.Payload)
}

func (o *GetBuildFileGeometryURLDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.Error)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}


text:
package com.linkedin.gms.factory.entity;

import com.linkedin.metadata.entity.ebean.EbeanAspectV2;
import io.ebean.EbeanServer;
import io.ebean.config.ServerConfig;
import javax.annotation.Nonnull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
public class EbeanServerFactory {
  public static final String EBEAN_MODEL_PACKAGE = EbeanAspectV2.class.getPackage().getName();

  @Autowired
  ApplicationContext applicationContext;

  @Bean(name = "ebeanServer")
  @DependsOn({"gmsEbeanServiceConfig"})
  @Nonnull
  protected EbeanServer createServer() {
    ServerConfig serverConfig = applicationContext.getBean(ServerConfig.class);
    // Make sure that the serverConfig includes the package that contains DAO's Ebean model.
    if (!serverConfig.getPackages().contains(EBEAN_MODEL_PACKAGE)) {
      serverConfig.getPackages().add(EBEAN_MODEL_PACKAGE);
    }
    // TODO: Consider supporting SCSI
    return io.ebean.EbeanServerFactory.create(serverConfig);
  }
}


text:
<?php

namespace MabeEnumTest\TestAsset;

use MabeEnum\Enum;

class EnumExtendedAmbiguous extends EnumBasic
{
    const AMBIGOUS_ONE = 1;
}