Java Code Examples for com.google.common.collect.ImmutableSet#forEach()

The following examples show how to use com.google.common.collect.ImmutableSet#forEach() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TaskVars.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
private void updateDedicatedCounters(IScheduledTask task, ScheduleStatus newState) {
  final String host = task.getAssignedTask().getSlaveHost();
  ImmutableSet<String> dedicatedRoles;
  if (Strings.isNullOrEmpty(host)) {
    dedicatedRoles = ImmutableSet.of();
  } else {
    dedicatedRoles = storage.read(store ->
        StreamSupport.stream(
              AttributeStore.Util.attributesOrNone(store, host).spliterator(),
              false)
            .filter(attr -> "dedicated".equals(attr.getName()))
            .findFirst()
            .map(IAttribute::getValues)
            .orElse(ImmutableSet.of())
    );
  }

  // Always dummy-read the lost-tasks-per-role stat. This ensures that there is at least a zero
  // exported for all roles.
  dedicatedRoles.forEach(s -> counters.getUnchecked(dedicatedRoleStatName(s)));

  if (newState == ScheduleStatus.LOST) {
    dedicatedRoles.forEach(s -> counters.getUnchecked(dedicatedRoleStatName(s)).increment());
  }
}
 
Example 2
Source File: FileParserPool.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public void close() {
  reportProfile();
  ImmutableSet<ResourcePool<FileParser<T>>> resourcePools;
  ImmutableSet<FileParser<T>> parsers;
  synchronized (this) {
    Preconditions.checkState(!closing.get());
    closing.set(true);
    resourcePools = ImmutableSet.copyOf(parserResourcePools.values());
    parsers = ImmutableSet.copyOf(nonPooledCells.values());
  }
  for (FileParser<T> parser : parsers) {
    try {
      parser.close();
    } catch (InterruptedException | IOException e) {
      throw new RuntimeException("Could not properly close a parser.", e);
    }
  }
  resourcePools.forEach(ResourcePool::close);
}
 
Example 3
Source File: JpaTransactionManagerImpl.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private int internalDelete(VKey<?> key) {
  checkArgumentNotNull(key, "key must be specified");
  assertInTransaction();
  EntityType<?> entityType = getEntityType(key.getKind());
  ImmutableSet<EntityId> entityIds = getEntityIdsFromSqlKey(entityType, key.getSqlKey());
  String sql =
      String.format("DELETE FROM %s WHERE %s", entityType.getName(), getAndClause(entityIds));
  Query query = getEntityManager().createQuery(sql);
  entityIds.forEach(entityId -> query.setParameter(entityId.name, entityId.value));
  return query.executeUpdate();
}
 
Example 4
Source File: SkyframeExecutor.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Keep in sync with {@link StarlarkTransition#getBuildSettingPackages} */
private Map<PackageValue.Key, PackageValue> getBuildSettingPackages(
    ConfigurationTransition transition, ExtendedEventHandler eventHandler)
    throws TransitionException {
  HashMap<PackageValue.Key, PackageValue> buildSettingPackages = new HashMap<>();
  // This happens before cycle detection so keep track of all seen build settings to ensure
  // we don't get stuck in endless loops (e.g. //alias1->//alias2 && //alias2->alias1)
  Set<Label> allSeenBuildSettings = new HashSet<>();
  ImmutableSet<Label> unverifiedBuildSettings =
      StarlarkTransition.getAllBuildSettings(transition);
  while (!unverifiedBuildSettings.isEmpty()) {
    for (Label buildSetting : unverifiedBuildSettings) {
      if (!allSeenBuildSettings.add(buildSetting)) {
        throw new TransitionException(
            String.format(
                "Error with aliased build settings related to '%s'. Either your aliases form a"
                    + " dependency cycle or you're attempting to set both an alias its actual"
                    + " target in the same transition.",
                buildSetting));
      }
    }
    ImmutableSet<PackageValue.Key> buildSettingPackageKeys =
        StarlarkTransition.getPackageKeysFromLabels(unverifiedBuildSettings);
    EvaluationResult<SkyValue> newlyLoaded =
        evaluateSkyKeys(eventHandler, buildSettingPackageKeys, true);
    if (newlyLoaded.hasError()) {
      throw new TransitionException(
          new NoSuchPackageException(
              ((PackageValue.Key) newlyLoaded.getError().getRootCauseOfException()).argument(),
              "Unable to find build setting package",
              newlyLoaded.getError().getException()));
    }
    buildSettingPackageKeys.forEach(
        k -> buildSettingPackages.put(k, (PackageValue) newlyLoaded.get(k)));
    unverifiedBuildSettings =
        StarlarkTransition.verifyBuildSettingsAndGetAliases(
            buildSettingPackages, unverifiedBuildSettings);
  }
  return buildSettingPackages;
}
 
Example 5
Source File: BatfishTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostProcessInterfaceDependenciesBind() {
  NetworkFactory nf = new NetworkFactory();
  Configuration c1 =
      nf.configurationBuilder()
          .setHostname("c1")
          .setConfigurationFormat(ConfigurationFormat.CISCO_IOS)
          .build();
  Vrf vrf = nf.vrfBuilder().setOwner(c1).setName(Configuration.DEFAULT_VRF_NAME).build();

  Interface.Builder ib = nf.interfaceBuilder().setOwner(c1).setVrf(vrf);

  ib.setName("eth0").setActive(false).build();
  ib.setName("eth1")
      .setActive(true)
      .setDependencies(ImmutableSet.of(new Dependency("eth0", DependencyType.BIND)))
      .build();
  ib.setName("eth2")
      .setActive(true)
      .setDependencies(ImmutableSet.of(new Dependency("eth1", DependencyType.BIND)))
      .build();
  ib.setName("eth9").setDependencies(ImmutableSet.of()).setActive(true).build();

  ImmutableSet<String> activeIfaces = ImmutableSet.of("eth9");
  ImmutableSet<String> inactiveIfaces = ImmutableSet.of("eth0", "eth1", "eth2");

  // Test
  postProcessInterfaceDependencies(ImmutableMap.of("c1", c1));

  activeIfaces.forEach(
      name -> assertThat(c1.getAllInterfaces().get(name).getActive(), equalTo(true)));
  inactiveIfaces.forEach(
      name -> assertThat(c1.getAllInterfaces().get(name).getActive(), equalTo(false)));
}
 
Example 6
Source File: Elasticsearch7SearchIndex.java    From vertexium with Apache License 2.0 5 votes vote down vote up
@Override
public <TElement extends Element> void updateElement(
    Graph graph,
    ExistingElementMutation<TElement> elementMutation,
    Authorizations authorizations
) {
    TElement element = elementMutation.getElement();

    if (MUTATION_LOGGER.isTraceEnabled()) {
        MUTATION_LOGGER.trace("updateElement: %s", elementMutation.getId());
    }

    if (!getConfig().isIndexEdges() && elementMutation.getElementType() == ElementType.EDGE) {
        return;
    }

    addMutationPropertiesToIndex(graph, elementMutation);
    addUpdateForMutationToBulk(graph, elementMutation);

    if (elementMutation.getNewElementVisibility() != null && element.getFetchHints().isIncludeExtendedDataTableNames()) {
        ImmutableSet<String> extendedDataTableNames = element.getExtendedDataTableNames();
        if (extendedDataTableNames != null && !extendedDataTableNames.isEmpty()) {
            extendedDataTableNames.forEach(tableName ->
                alterExtendedDataElementTypeVisibility(
                    graph,
                    elementMutation,
                    element.getExtendedData(tableName),
                    elementMutation.getOldElementVisibility(),
                    elementMutation.getNewElementVisibility()
                ));
        }
    }

    if (getConfig().isAutoFlush()) {
        flush(graph);
    }
}
 
Example 7
Source File: SafeBrowsingTransforms.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Buffers {@link Subdomain} objects until we reach the batch size, then bulk-evaluate the URLs
 * with the SafeBrowsing API.
 */
@ProcessElement
public void processElement(ProcessContext context) {
  Subdomain subdomain = context.element();
  subdomainBuffer.put(subdomain.fullyQualifiedDomainName(), subdomain);
  if (subdomainBuffer.size() >= BATCH_SIZE) {
    ImmutableSet<KV<Subdomain, ThreatMatch>> results = evaluateAndFlush();
    results.forEach(context::output);
  }
}
 
Example 8
Source File: DistributionMetricSubject.java    From java-monitoring-client-library with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the distribution for the given label can be constructed from the given data set.
 *
 * <p>Note that this only tests that the distribution has the same binned histogram, along with
 * the same mean, and sum of squared deviation as it would if it had recorded the specified data
 * points. It could have in fact collected different data points that resulted in the same
 * distribution, but that information is lost to us and cannot be tested.
 */
public And<DistributionMetricSubject> hasDataSetForLabels(
    ImmutableSet<? extends Number> dataSet, String... labels) {
  ImmutableList<MetricPoint<Distribution>> metricPoints = actual.getTimestampedValues();
  if (metricPoints.isEmpty()) {
    failWithBadResults(
        "has a distribution for labels", Joiner.on(':').join(labels), "has", "no values");
  }
  MutableDistribution targetDistribution =
      new MutableDistribution(metricPoints.get(0).value().distributionFitter());
  dataSet.forEach(data -> targetDistribution.add(data.doubleValue()));
  return hasValueForLabels(ImmutableDistribution.copyOf(targetDistribution), labels);
}
 
Example 9
Source File: WorkspaceAndProjectGenerator.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Add a workspace scheme for each extension bundled with the source target of the workspace.
 *
 * @param projectGraph
 * @param schemeName
 * @param schemeArguments
 * @param schemeConfigsBuilder
 * @param schemeNameToSrcTargetNodeBuilder
 */
private static void addWorkspaceExtensionSchemes(
    TargetGraph projectGraph,
    String schemeName,
    XcodeWorkspaceConfigDescriptionArg schemeArguments,
    ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
    ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
        schemeNameToSrcTargetNodeBuilder) {
  if (!schemeArguments.getSrcTarget().isPresent()) {
    return;
  }

  LOG.debug("Potentially adding extension schemes for %s", schemeName);

  BuildTarget sourceBuildTarget = schemeArguments.getSrcTarget().get();
  TargetNode<?> sourceTargetNode = projectGraph.get(sourceBuildTarget);
  Set<BuildTarget> sourceTargetBuildDeps = sourceTargetNode.getBuildDeps();

  // Filter all of the source target's deps to find the bundled extensions that get an implicit
  // scheme.
  ImmutableSet<BuildTarget> implicitSchemeBuildTargets =
      sourceTargetBuildDeps.stream()
          .filter(t -> shouldIncludeImplicitExtensionSchemeForTargetNode(projectGraph.get(t)))
          .collect(ImmutableSet.toImmutableSet());

  // Create scheme for each bundled extension to allow Xcode to automatically begin debugging them
  // when this scheme it selected.
  implicitSchemeBuildTargets.forEach(
      (buildTarget -> {
        String extensionSchemeName = schemeName + "+" + buildTarget.getShortName();
        TargetNode<?> targetNode = projectGraph.get(buildTarget);

        schemeConfigsBuilder.put(
            extensionSchemeName, createImplicitExtensionWorkspaceArgs(sourceBuildTarget));

        schemeNameToSrcTargetNodeBuilder.put(extensionSchemeName, Optional.of(sourceTargetNode));
        schemeNameToSrcTargetNodeBuilder.put(extensionSchemeName, Optional.of(targetNode));
      }));
}
 
Example 10
Source File: SysImageServiceImpl.java    From paas with Apache License 2.0 5 votes vote down vote up
@Override
public ResultVO listExportPorts(String imageId, String userId) {
    SysImage sysImage = getById(imageId);
    if(sysImage == null) {
        return ResultVOUtils.error(ResultEnum.IMAGE_NOT_EXIST);
    }

    // 鉴权
    if(!hasAuthImage(userId,sysImage)) {
        return ResultVOUtils.error(ResultEnum.PERMISSION_ERROR);
    }

    // 获取端口号
    try {
        ImageInfo info = dockerClient.inspectImage(sysImage.getFullName());
        // 形如:["80/tcp"]
        ImmutableSet<String> exposedPorts = info.containerConfig().exposedPorts();

        Set<String> res = new HashSet<>();

        // 取出端口号信息
        if(exposedPorts != null && exposedPorts.size() > 0) {
            exposedPorts.forEach(s -> {
                res.add(s.split("/")[0]);
            });
        }

        return ResultVOUtils.success(new ArrayList<>(res));
    } catch (DockerRequestException requestException){
        return ResultVOUtils.error(ResultEnum.DOCKER_EXCEPTION.getCode(), HttpClientUtils.getErrorMessage(requestException.getMessage()));
    }catch (Exception e) {
        log.error("获取镜像暴露端口错误,出错位置:{},出错镜像ID:{},错误栈:{}",
                "SysImageServiceImpl.listExportPorts()", imageId, HttpClientUtils.getStackTraceAsString(e));
        return null;
    }
}
 
Example 11
Source File: ServerReflectionClient.java    From grpc-swagger with MIT License 5 votes vote down vote up
@Override
public void onNext(ServerReflectionResponse response) {
    MessageResponseCase responseCase = response.getMessageResponseCase();
    switch (responseCase) {
        case FILE_DESCRIPTOR_RESPONSE:
            ImmutableSet<FileDescriptorProto> descriptors =
                    parseDescriptors(response.getFileDescriptorResponse().getFileDescriptorProtoList());
            descriptors.forEach(d -> resolvedDescriptors.put(d.getName(), d));
            descriptors.forEach(this::processDependencies);
            break;
        default:
            logger.warn("Got unknown reflection response type: " + responseCase);
            break;
    }
}
 
Example 12
Source File: ServerReflectionClient.java    From milkman with MIT License 5 votes vote down vote up
@Override
public void onNext(ServerReflectionResponse response) {
  MessageResponseCase responseCase = response.getMessageResponseCase();
  switch (responseCase) {
    case FILE_DESCRIPTOR_RESPONSE:
      ImmutableSet<FileDescriptorProto> descriptors =
          parseDescriptors(response.getFileDescriptorResponse().getFileDescriptorProtoList());
      descriptors.forEach(d -> resolvedDescriptors.put(d.getName(), d));
      descriptors.forEach(d -> processDependencies(d));
      break;
    default:
      logger.warn("Got unknown reflection response type: " + responseCase);
      break;
  }
}
 
Example 13
Source File: BuildableSupportTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeriveDepsFromAddsToRuleKeys() {
  BuildTarget target = BuildTargetFactory.newInstance("//some", "name");
  ProjectFilesystem filesystem = new FakeProjectFilesystem();
  ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
  BuildRule rule1 = makeRule(target, filesystem, "rule1");
  BuildRule rule2 = makeRule(target, filesystem, "rule2");
  BuildRule rule3 = makeRule(target, filesystem, "rule3");
  BuildRule rule4 = makeRule(target, filesystem, "rule4");
  BuildRule rule5 = makeRule(target, filesystem, "rule5");
  ImmutableSet<BuildRule> rules = ImmutableSet.of(rule1, rule2, rule3, rule4, rule5);
  rules.forEach(graphBuilder::addToIndex);

  AddsToRuleKey rule =
      new AddsToRuleKey() {
        @AddToRuleKey int value = 0;
        @AddToRuleKey BuildRule bareRule = rule1;
        @AddToRuleKey SourcePath sourcePath = rule2.getSourcePathToOutput();

        @AddToRuleKey
        Object ruleKeyAppendable =
            new AddsToRuleKey() {
              @AddToRuleKey Object key = rule3;
            };

        @AddToRuleKey ImmutableList<BuildRule> list = ImmutableList.of(rule4);
        @AddToRuleKey Optional<SourcePath> optional = Optional.of(rule5.getSourcePathToOutput());
      };

  MoreAsserts.assertSetEquals(
      rules,
      BuildableSupport.deriveDeps(rule, graphBuilder).collect(ImmutableSet.toImmutableSet()));
}
 
Example 14
Source File: AppleCxxPlatformsTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void appleTVOSSimulatorPlatformSetsLinkerFlags() {
  AppleSdkPaths appleSdkPaths =
      AppleSdkPaths.builder()
          .setDeveloperPath(developerDir)
          .addToolchainPaths(developerDir.resolve("Toolchains/XcodeDefault.xctoolchain"))
          .setPlatformPath(developerDir.resolve("Platforms/AppleTVSimulator.platform"))
          .setSdkPath(
              developerDir.resolve(
                  "Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator9.1.sdk"))
          .build();

  ImmutableSet<Path> paths =
      ImmutableSet.<Path>builder()
          .addAll(getCommonKnownPaths(developerDir))
          .add(
              developerDir.resolve(
                  "Platforms/AppleTVSimulator.platform/Developer/usr/bin/libtool"))
          .add(developerDir.resolve("Platforms/AppleTVSimulator.platform/Developer/usr/bin/ar"))
          .build();
  paths.forEach(this::touchFile);

  AppleToolchain toolchain =
      AppleToolchain.builder()
          .setIdentifier("com.apple.dt.XcodeDefault")
          .setPath(developerDir.resolve("Toolchains/XcodeDefault.xctoolchain"))
          .setVersion("1")
          .build();

  AppleSdk targetSdk =
      AppleSdk.builder()
          .setApplePlatform(ApplePlatform.APPLETVSIMULATOR)
          .setName("appletvsimulator9.1")
          .setVersion("9.1")
          .setToolchains(ImmutableList.of(toolchain))
          .build();

  BuckConfig buckConfig = FakeBuckConfig.builder().build();
  AppleCxxPlatform appleCxxPlatform =
      AppleCxxPlatforms.buildWithXcodeToolFinder(
          projectFilesystem,
          targetSdk,
          "9.1",
          "arm64",
          appleSdkPaths,
          buckConfig,
          new XcodeToolFinder(buckConfig.getView(AppleConfig.class)),
          new AppleCxxPlatforms.XcodeBuildVersionCache());

  CxxPlatform cxxPlatform = appleCxxPlatform.getCxxPlatform();
  BuildRuleResolver ruleResolver = new TestActionGraphBuilder();
  SourcePathResolverAdapter resolver = ruleResolver.getSourcePathResolver();

  assertThat(
      Arg.stringify(cxxPlatform.getCflags(), resolver),
      hasItem("-mtvos-simulator-version-min=9.1"));
  assertThat(
      Arg.stringify(cxxPlatform.getLdflags(), resolver),
      hasItem("-mtvos-simulator-version-min=9.1"));
}
 
Example 15
Source File: AppleLibraryDescriptionSwiftEnhancer.java    From buck with Apache License 2.0 4 votes vote down vote up
public static BuildRule createSwiftCompileRule(
    BuildTarget target,
    CellPathResolver cellRoots,
    ActionGraphBuilder graphBuilder,
    AppleNativeTargetDescriptionArg args,
    ProjectFilesystem filesystem,
    CxxPlatform platform,
    AppleCxxPlatform applePlatform,
    SwiftBuckConfig swiftBuckConfig,
    ImmutableSet<CxxPreprocessorInput> inputs) {

  SwiftLibraryDescriptionArg.Builder delegateArgsBuilder = SwiftLibraryDescriptionArg.builder();
  SwiftDescriptions.populateSwiftLibraryDescriptionArg(
      swiftBuckConfig, graphBuilder.getSourcePathResolver(), delegateArgsBuilder, args, target);
  delegateArgsBuilder.setTargetSdkVersion(args.getTargetSdkVersion());
  SwiftLibraryDescriptionArg swiftArgs = delegateArgsBuilder.build();

  Preprocessor preprocessor =
      platform.getCpp().resolve(graphBuilder, target.getTargetConfiguration());

  ImmutableSet<BuildRule> inputDeps =
      RichStream.from(inputs)
          .flatMap(input -> RichStream.from(input.getDeps(graphBuilder)))
          .toImmutableSet();

  ImmutableSortedSet.Builder<BuildRule> sortedDeps = ImmutableSortedSet.naturalOrder();
  sortedDeps.addAll(inputDeps);

  PreprocessorFlags.Builder flagsBuilder = PreprocessorFlags.builder();
  inputs.forEach(input -> flagsBuilder.addAllIncludes(input.getIncludes()));
  inputs.forEach(input -> flagsBuilder.addAllFrameworkPaths(input.getFrameworks()));
  PreprocessorFlags preprocessorFlags = flagsBuilder.build();

  Optional<CxxPreprocessorInput> underlyingModule =
      AppleLibraryDescription.underlyingModuleCxxPreprocessorInput(
          target, graphBuilder, platform);

  SwiftPlatform swiftPlatform = applePlatform.getSwiftPlatform().get();

  return SwiftLibraryDescription.createSwiftCompileRule(
      platform,
      swiftPlatform,
      swiftBuckConfig,
      target,
      graphBuilder,
      cellRoots,
      filesystem,
      swiftArgs,
      preprocessor,
      preprocessorFlags,
      underlyingModule.isPresent(),
      args.getTargetSdkVersion()
          .map(version -> swiftPlatform.getSwiftTarget().withTargetSdkVersion(version)));
}
 
Example 16
Source File: AppleCxxPlatformsTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void iphoneOSSimulatorPlatformSetsLinkerFlags() {
  AppleSdkPaths appleSdkPaths =
      AppleSdkPaths.builder()
          .setDeveloperPath(developerDir)
          .addToolchainPaths(developerDir.resolve("Toolchains/XcodeDefault.xctoolchain"))
          .setPlatformPath(developerDir.resolve("Platforms/iPhoneOS.platform"))
          .setSdkPath(
              developerDir.resolve(
                  "Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneSimulator8.0.sdk"))
          .build();

  ImmutableSet<Path> paths =
      ImmutableSet.<Path>builder()
          .addAll(getCommonKnownPaths(developerDir))
          .add(developerDir.resolve("Platforms/iPhoneOS.platform/Developer/usr/bin/libtool"))
          .add(developerDir.resolve("Platforms/iPhoneOS.platform/Developer/usr/bin/ar"))
          .add(developerDir.resolve("Tools/otest"))
          .build();
  paths.forEach(this::touchFile);

  AppleToolchain toolchain =
      AppleToolchain.builder()
          .setIdentifier("com.apple.dt.XcodeDefault")
          .setPath(developerDir.resolve("Toolchains/XcodeDefault.xctoolchain"))
          .setVersion("1")
          .build();

  AppleSdk targetSdk =
      AppleSdk.builder()
          .setApplePlatform(ApplePlatform.IPHONESIMULATOR)
          .setName("iphonesimulator8.0")
          .setVersion("8.0")
          .setToolchains(ImmutableList.of(toolchain))
          .build();

  BuckConfig buckConfig = FakeBuckConfig.builder().build();
  AppleCxxPlatform appleCxxPlatform =
      AppleCxxPlatforms.buildWithXcodeToolFinder(
          projectFilesystem,
          targetSdk,
          "7.0",
          "armv7",
          appleSdkPaths,
          buckConfig,
          new XcodeToolFinder(buckConfig.getView(AppleConfig.class)),
          new AppleCxxPlatforms.XcodeBuildVersionCache());

  CxxPlatform cxxPlatform = appleCxxPlatform.getCxxPlatform();
  BuildRuleResolver ruleResolver = new TestActionGraphBuilder();
  SourcePathResolverAdapter resolver = ruleResolver.getSourcePathResolver();

  assertThat(
      Arg.stringify(cxxPlatform.getCflags(), resolver),
      hasItem("-mios-simulator-version-min=7.0"));
  assertThat(
      Arg.stringify(cxxPlatform.getLdflags(), resolver),
      hasItem("-mios-simulator-version-min=7.0"));
}
 
Example 17
Source File: AppleCxxPlatformsTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void cxxToolParamsReadFromBuckConfig() {
  AppleSdkPaths appleSdkPaths =
      AppleSdkPaths.builder()
          .setDeveloperPath(developerDir)
          .addToolchainPaths(developerDir.resolve("Toolchains/XcodeDefault.xctoolchain"))
          .setPlatformPath(developerDir.resolve("Platforms/iPhoneOS.platform"))
          .setSdkPath(
              developerDir.resolve("Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.0.sdk"))
          .build();

  ImmutableSet<Path> paths =
      ImmutableSet.<Path>builder()
          .addAll(getCommonKnownPaths(developerDir))
          .add(developerDir.resolve("Platforms/iPhoneOS.platform/Developer/usr/bin/libtool"))
          .add(developerDir.resolve("Platforms/iPhoneOS.platform/Developer/usr/bin/ar"))
          .add(developerDir.resolve("Tools/otest"))
          .build();
  paths.forEach(this::touchFile);

  AppleToolchain toolchain =
      AppleToolchain.builder()
          .setIdentifier("com.apple.dt.XcodeDefault")
          .setPath(developerDir.resolve("Toolchains/XcodeDefault.xctoolchain"))
          .setVersion("1")
          .build();

  AppleSdk targetSdk =
      AppleSdk.builder()
          .setApplePlatform(ApplePlatform.IPHONEOS)
          .setName("iphoneos8.0")
          .setVersion("8.0")
          .setToolchains(ImmutableList.of(toolchain))
          .build();

  BuckConfig buckConfig =
      FakeBuckConfig.builder()
          .setSections(
              ImmutableMap.of(
                  "cxx",
                  ImmutableMap.of(
                      "cflags", "-std=gnu11",
                      "cppflags", "-DCTHING",
                      "cxxflags", "-std=c++11",
                      "cxxppflags", "-DCXXTHING")))
          .build();

  AppleCxxPlatform appleCxxPlatform =
      AppleCxxPlatforms.buildWithXcodeToolFinder(
          projectFilesystem,
          targetSdk,
          "7.0",
          "armv7",
          appleSdkPaths,
          buckConfig,
          new XcodeToolFinder(buckConfig.getView(AppleConfig.class)),
          new AppleCxxPlatforms.XcodeBuildVersionCache());

  CxxPlatform cxxPlatform = appleCxxPlatform.getCxxPlatform();
  BuildRuleResolver ruleResolver = new TestActionGraphBuilder();
  SourcePathResolverAdapter resolver = ruleResolver.getSourcePathResolver();

  assertThat(Arg.stringify(cxxPlatform.getCflags(), resolver), hasItem("-std=gnu11"));
  assertThat(Arg.stringify(cxxPlatform.getCppflags(), resolver), hasItems("-DCTHING"));
  assertThat(Arg.stringify(cxxPlatform.getCxxflags(), resolver), hasItem("-std=c++11"));
  assertThat(Arg.stringify(cxxPlatform.getCxxppflags(), resolver), hasItems("-DCXXTHING"));
}
 
Example 18
Source File: EmptyJarTracker.java    From intellij with Apache License 2.0 4 votes vote down vote up
public Builder removeEntries(ImmutableSet<ArtifactState> removedOutputs) {
  removedOutputs.forEach(trackerBuilder::remove);
  return this;
}
 
Example 19
Source File: AppleCxxPlatformsTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void watchOSSimulatorPlatformSetsLinkerFlags() {
  AppleSdkPaths appleSdkPaths =
      AppleSdkPaths.builder()
          .setDeveloperPath(developerDir)
          .addToolchainPaths(developerDir.resolve("Toolchains/XcodeDefault.xctoolchain"))
          .setPlatformPath(developerDir.resolve("Platforms/WatchSimulator.platform"))
          .setSdkPath(
              developerDir.resolve(
                  "Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator2.0.sdk"))
          .build();

  ImmutableSet<Path> paths =
      ImmutableSet.<Path>builder()
          .addAll(getCommonKnownPaths(developerDir))
          .add(
              developerDir.resolve("Platforms/WatchSimulator.platform/Developer/usr/bin/libtool"))
          .add(developerDir.resolve("Platforms/WatchSimulator.platform/Developer/usr/bin/ar"))
          .build();
  paths.forEach(this::touchFile);

  AppleToolchain toolchain =
      AppleToolchain.builder()
          .setIdentifier("com.apple.dt.XcodeDefault")
          .setPath(developerDir.resolve("Toolchains/XcodeDefault.xctoolchain"))
          .setVersion("1")
          .build();

  AppleSdk targetSdk =
      AppleSdk.builder()
          .setApplePlatform(ApplePlatform.WATCHSIMULATOR)
          .setName("watchsimulator2.0")
          .setVersion("2.0")
          .setToolchains(ImmutableList.of(toolchain))
          .build();

  BuckConfig buckConfig = FakeBuckConfig.builder().build();
  AppleCxxPlatform appleCxxPlatform =
      AppleCxxPlatforms.buildWithXcodeToolFinder(
          projectFilesystem,
          targetSdk,
          "2.0",
          "armv7k",
          appleSdkPaths,
          buckConfig,
          new XcodeToolFinder(buckConfig.getView(AppleConfig.class)),
          new AppleCxxPlatforms.XcodeBuildVersionCache());

  CxxPlatform cxxPlatform = appleCxxPlatform.getCxxPlatform();
  BuildRuleResolver ruleResolver = new TestActionGraphBuilder();
  SourcePathResolverAdapter resolver = ruleResolver.getSourcePathResolver();

  assertThat(
      Arg.stringify(cxxPlatform.getCflags(), resolver),
      hasItem("-mwatchos-simulator-version-min=2.0"));
  assertThat(
      Arg.stringify(cxxPlatform.getLdflags(), resolver),
      hasItem("-mwatchos-simulator-version-min=2.0"));
}
 
Example 20
Source File: BatfishTest.java    From batfish with Apache License 2.0 4 votes vote down vote up
@Test
public void testPostProcessInterfaceDependenciesAggregate() {
  NetworkFactory nf = new NetworkFactory();
  Configuration c1 =
      nf.configurationBuilder()
          .setHostname("c1")
          .setConfigurationFormat(ConfigurationFormat.CISCO_IOS)
          .build();
  Vrf vrf = nf.vrfBuilder().setOwner(c1).setName(Configuration.DEFAULT_VRF_NAME).build();

  Interface.Builder ib = nf.interfaceBuilder().setOwner(c1).setVrf(vrf);

  ib.setName("eth0").setActive(false).setType(InterfaceType.PHYSICAL).build();
  ib.setName("eth1").setActive(true).setType(InterfaceType.PHYSICAL).build();
  ib.setName("eth2")
      .setActive(true)
      .setType(InterfaceType.AGGREGATED)
      .setDependencies(
          ImmutableSet.of(
              new Dependency("eth1", DependencyType.AGGREGATE),
              new Dependency("eth0", DependencyType.AGGREGATE)))
      .build();

  ib.setName("eth3").setActive(false).setType(InterfaceType.PHYSICAL).build();
  ib.setName("eth4")
      .setActive(true)
      .setType(InterfaceType.AGGREGATED)
      .setDependencies(
          ImmutableSet.of(
              new Dependency("eth0", DependencyType.AGGREGATE),
              new Dependency("eth3", DependencyType.AGGREGATE)))
      .build();

  ImmutableSet<String> activeIfaces = ImmutableSet.of("eth1", "eth2");
  ImmutableSet<String> inactiveIfaces = ImmutableSet.of("eth0", "eth3", "eth4");

  // Test
  postProcessInterfaceDependencies(ImmutableMap.of("c1", c1));

  activeIfaces.forEach(
      name -> assertThat(c1.getAllInterfaces().get(name).getActive(), equalTo(true)));
  inactiveIfaces.forEach(
      name -> assertThat(c1.getAllInterfaces().get(name).getActive(), equalTo(false)));
}