示例#1
0
 @Override
 public PythonPackageComponents getPythonPackageComponents(
     TargetGraph targetGraph, PythonPlatform pythonPlatform, CxxPlatform cxxPlatform) {
   if (headerOnly.apply(cxxPlatform)) {
     return PythonPackageComponents.of();
   }
   if (linkage == Linkage.STATIC) {
     return PythonPackageComponents.of();
   }
   if (!isPlatformSupported(cxxPlatform)) {
     return PythonPackageComponents.of();
   }
   ImmutableMap.Builder<Path, SourcePath> libs = ImmutableMap.builder();
   String sharedLibrarySoname =
       soname.or(
           CxxDescriptionEnhancer.getDefaultSharedLibrarySoname(getBuildTarget(), cxxPlatform));
   BuildRule sharedLibraryBuildRule =
       requireBuildRule(
           targetGraph, cxxPlatform.getFlavor(), CxxDescriptionEnhancer.SHARED_FLAVOR);
   libs.put(
       Paths.get(sharedLibrarySoname),
       new BuildTargetSourcePath(sharedLibraryBuildRule.getBuildTarget()));
   return PythonPackageComponents.of(
       /* modules */ ImmutableMap.<Path, SourcePath>of(),
       /* resources */ ImmutableMap.<Path, SourcePath>of(),
       /* nativeLibraries */ libs.build(),
       /* prebuiltLibraries */ ImmutableSet.<SourcePath>of(),
       /* zipSafe */ Optional.<Boolean>absent());
 }
示例#2
0
 /**
  * Convert this node tree into a map of the defined nodes in this tree.
  *
  * @return An immutable map representation of the nodes defined in this tree
  */
 public Map<String, Integer> asMap() {
   ImmutableMap.Builder<String, Integer> ret = ImmutableMap.builder();
   for (Map.Entry<String, Node> ent : this.rootNode.children.entrySet()) {
     populateMap(ret, ent.getKey(), ent.getValue());
   }
   return ret.build();
 }
示例#3
0
  /**
   * Creates a new attribute service using the given providers and user provided default attribute
   * values.
   */
  public AttributeService(
      Iterable<? extends AttributeProvider> providers, Map<String, ?> userProvidedDefaults) {
    ImmutableMap.Builder<String, AttributeProvider> byViewNameBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<Class<?>, AttributeProvider> byViewTypeBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<Class<?>, AttributeProvider> byAttributesTypeBuilder =
        ImmutableMap.builder();

    ImmutableList.Builder<FileAttribute<?>> defaultAttributesBuilder = ImmutableList.builder();

    for (AttributeProvider provider : providers) {
      byViewNameBuilder.put(provider.name(), provider);
      byViewTypeBuilder.put(provider.viewType(), provider);
      if (provider.attributesType() != null) {
        byAttributesTypeBuilder.put(provider.attributesType(), provider);
      }

      for (Map.Entry<String, ?> entry : provider.defaultValues(userProvidedDefaults).entrySet()) {
        defaultAttributesBuilder.add(new SimpleFileAttribute<>(entry.getKey(), entry.getValue()));
      }
    }

    this.providersByName = byViewNameBuilder.build();
    this.providersByViewType = byViewTypeBuilder.build();
    this.providersByAttributesType = byAttributesTypeBuilder.build();
    this.defaultValues = defaultAttributesBuilder.build();
  }
示例#4
0
  @Override
  public IFlexibleBakedModel bake(
      IModelState state,
      VertexFormat format,
      Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) {
    IFlexibleBakedModel bakedBase = null;

    if (base != null) bakedBase = base.bake(state, format, bakedTextureGetter);

    ImmutableMap.Builder<String, IFlexibleBakedModel> mapBuilder = ImmutableMap.builder();

    for (Entry<String, Pair<IModel, IModelState>> entry : parts.entrySet()) {
      Pair<IModel, IModelState> pair = entry.getValue();
      mapBuilder.put(
          entry.getKey(), pair.getLeft().bake(pair.getRight(), format, bakedTextureGetter));
    }

    if (bakedBase == null && parts.isEmpty()) {
      FMLLog.log(
          Level.ERROR,
          "MultiModel %s is empty (no base model or parts were provided/resolved)",
          location);
      IModel missing = ModelLoaderRegistry.getMissingModel();
      return missing.bake(missing.getDefaultState(), format, bakedTextureGetter);
    }
    return new Baked(location, true, bakedBase, mapBuilder.build());
  }
 private static Map<FileLike, String> traverse(Collection<File> files) throws IOException {
   Collection<Path> paths =
       FluentIterable.from(files)
           .transform(
               new Function<File, Path>() {
                 @Override
                 public Path apply(File file) {
                   return file.toPath();
                 }
               })
           .toList();
   final ImmutableMap.Builder<FileLike, String> completeList = ImmutableMap.builder();
   ClasspathTraverser traverser = new DefaultClasspathTraverser();
   ProjectFilesystem filesystem = new ProjectFilesystem(Paths.get(".").toAbsolutePath());
   traverser.traverse(
       new ClasspathTraversal(paths, filesystem) {
         @Override
         public void visit(FileLike fileLike) {
           String contents;
           try {
             contents = new FileLikeCharSource(fileLike).read();
           } catch (IOException e) {
             throw Throwables.propagate(e);
           }
           completeList.put(fileLike, contents);
         }
       });
   return completeList.build();
 }
示例#6
0
  public Map<String, Path> buildMultipleAndReturnOutputs(String... args) throws IOException {
    // Add in `--show-output` to the build, so we can parse the output paths after the fact.
    ImmutableList<String> buildArgs =
        ImmutableList.<String>builder().add("--show-output").add(args).build();
    ProjectWorkspace.ProcessResult buildResult =
        runBuckBuild(buildArgs.toArray(new String[buildArgs.size()]));
    buildResult.assertSuccess();

    // Grab the stdout lines, which have the build outputs.
    List<String> lines =
        Splitter.on(CharMatcher.anyOf(System.lineSeparator()))
            .trimResults()
            .omitEmptyStrings()
            .splitToList(buildResult.getStdout());

    // Skip the first line, which is just "The outputs are:".
    assertThat(lines.get(0), Matchers.equalTo("The outputs are:"));
    lines = lines.subList(1, lines.size());

    Splitter lineSplitter = Splitter.on(' ').trimResults();
    ImmutableMap.Builder<String, Path> builder = ImmutableMap.builder();
    for (String line : lines) {
      List<String> fields = lineSplitter.splitToList(line);
      assertThat(fields, Matchers.hasSize(2));
      builder.put(fields.get(0), getPath(fields.get(1)));
    }

    return builder.build();
  }
  /** Unpacks the response from remote TF manager into this object. */
  @Override
  protected CommandResult unpackResponseFromJson(JSONObject json) throws JSONException {
    Status status = Status.NOT_ALLOCATED;
    FreeDeviceState state = FreeDeviceState.AVAILABLE;
    String statusString = json.getString(STATUS);
    try {
      status = CommandResult.Status.valueOf(statusString);
    } catch (IllegalArgumentException e) {
      throw new JSONException(String.format("unrecognized status '%s'", statusString));
    }

    String errorDetails = json.optString(INVOCATION_ERROR, null);
    String freeDeviceString = json.optString(FREE_DEVICE_STATE, null);
    if (freeDeviceString != null) {
      try {
        state = FreeDeviceState.valueOf(freeDeviceString);
      } catch (IllegalArgumentException e) {
        throw new JSONException(String.format("unrecognized state '%s'", freeDeviceString));
      }
    }

    Map<String, String> runMetricsMap = null;
    JSONArray jsonRunMetricsArray = json.optJSONArray(RUN_METRICS);
    if (jsonRunMetricsArray != null && jsonRunMetricsArray.length() > 0) {
      ImmutableMap.Builder<String, String> mapBuilder = new ImmutableMap.Builder<String, String>();
      for (int i = 0; i < jsonRunMetricsArray.length(); i++) {
        JSONObject runMetricJson = jsonRunMetricsArray.getJSONObject(i);
        final String key = runMetricJson.getString(RUN_METRICS_KEY);
        final String value = runMetricJson.getString(RUN_METRICS_VALUE);
        mapBuilder.put(key, value);
      }
      runMetricsMap = mapBuilder.build();
    }
    return new CommandResult(status, errorDetails, state, runMetricsMap);
  }
示例#8
0
  @Test
  public void extractSourcePaths() {
    ImmutableSortedSet.Builder<SourcePath> files = ImmutableSortedSet.naturalOrder();
    ImmutableMap.Builder<SourcePath, String> perFileCompileFlags = ImmutableMap.builder();

    ImmutableList<Either<SourcePath, Pair<SourcePath, String>>> input =
        ImmutableList.of(
            newEntry("foo.m"),
            newEntry("bar.m", "-flag1 -flag2"),
            newEntry("baz.m"),
            newEntry("quox.m", "-flag1"));

    RuleUtils.extractSourcePaths(files, perFileCompileFlags, input);
    assertEquals(
        ImmutableSortedSet.<SourcePath>of(
            new FileSourcePath("foo.m"),
            new FileSourcePath("bar.m"),
            new FileSourcePath("baz.m"),
            new FileSourcePath("quox.m")),
        files.build());
    assertEquals(
        ImmutableMap.<SourcePath, String>of(
            new FileSourcePath("bar.m"), "-flag1 -flag2",
            new FileSourcePath("quox.m"), "-flag1"),
        perFileCompileFlags.build());
  }
 @Override
 public JobModel from(UriInfo uriInfo, Job job) {
   JobModel jobModel = new JobModel();
   jobModel.setId(job.getId());
   jobModel.setName(job.getJobName());
   jobModel.setExternalIds(job.getExternalIds());
   jobModel.setType(job.getJobType().name());
   jobModel.setStatus(
       new ResourceStatusModel(
           job.getStatus().name(),
           ZonedDateTime.ofInstant(job.getStatusTimestamp().toInstant(), ZoneId.systemDefault())));
   jobModel.setPriority(job.getPriority());
   jobModel.setCreated(
       ZonedDateTime.ofInstant(job.getCreated().toInstant(), ZoneId.systemDefault()));
   jobModel.setCreatedBy(job.getCreatedBy());
   jobModel.setLastModified(
       ZonedDateTime.ofInstant(job.getLastModified().toInstant(), ZoneId.systemDefault()));
   jobModel.setLastModifiedBy(job.getLastModifiedBy());
   ImmutableMap.Builder<String, Href> builder = ImmutableMap.builder();
   builder.put("self", new Href(getJobResourceUrlAsString(uriInfo, job, null)));
   builder.put(
       "configuration", new Href(getJobResourceUrlAsString(uriInfo, job, "configuration")));
   builder.put("status", new Href(getJobResourceUrlAsString(uriInfo, job, "status")));
   jobModel.setLinks(builder.build());
   return jobModel;
 }
示例#10
0
 private static ImmutableMap<Integer, Integer> makePositionToColumnMap(List<Tok> toks) {
   ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builder();
   for (Tok tok : toks) {
     builder.put(tok.getPosition(), tok.getColumn());
   }
   return builder.build();
 }
示例#11
0
  /**
   * Create all the modules we are capable of representing in IntelliJ from the supplied graph.
   *
   * @param targetGraph graph whose nodes will be converted to {@link IjModule}s.
   * @return map which for every BuildTarget points to the corresponding IjModule. Multiple
   *     BuildTarget can point to one IjModule (many:one mapping), the BuildTargets which can't be
   *     prepresented in IntelliJ are missing from this mapping.
   */
  public static ImmutableMap<BuildTarget, IjModule> createModules(
      TargetGraph targetGraph, IjModuleFactory moduleFactory) {
    ImmutableSet<TargetNode<?>> supportedTargets =
        FluentIterable.from(targetGraph.getNodes())
            .filter(IjModuleFactory.SUPPORTED_MODULE_TYPES_PREDICATE)
            .toSet();
    ImmutableListMultimap<Path, TargetNode<?>> baseTargetPathMultimap =
        FluentIterable.from(supportedTargets)
            .index(
                new Function<TargetNode<?>, Path>() {
                  @Override
                  public Path apply(TargetNode<?> input) {
                    return input.getBuildTarget().getBasePath();
                  }
                });

    ImmutableMap.Builder<BuildTarget, IjModule> moduleMapBuilder = new ImmutableMap.Builder<>();

    for (Path baseTargetPath : baseTargetPathMultimap.keySet()) {
      ImmutableSet<TargetNode<?>> targets =
          FluentIterable.from(baseTargetPathMultimap.get(baseTargetPath)).toSet();

      IjModule module = moduleFactory.createModule(baseTargetPath, targets);

      for (TargetNode<?> target : targets) {
        moduleMapBuilder.put(target.getBuildTarget(), module);
      }
    }

    return moduleMapBuilder.build();
  }
示例#12
0
 private static ImmutableMap<String, TokenKind> buildKeywords(TokenKind start, TokenKind end) {
   ImmutableMap.Builder<String, TokenKind> map = ImmutableMap.builder();
   for (TokenKind keyword : EnumSet.range(start, end)) {
     map.put(keyword.value, keyword);
   }
   return map.build();
 }
示例#13
0
  /** Returns an object of the same type as {@code o}, or null if it is not retained. */
  private Object retainAll(Schema schema, MarkSet markSet, ProtoType type, Object o) {
    if (!markSet.contains(type)) {
      return null; // Prune this type.

    } else if (o instanceof Map) {
      ImmutableMap.Builder<ProtoMember, Object> builder = ImmutableMap.builder();
      for (Map.Entry<?, ?> entry : ((Map<?, ?>) o).entrySet()) {
        ProtoMember protoMember = (ProtoMember) entry.getKey();
        if (!markSet.contains(protoMember)) continue; // Prune this field.
        Field field = schema.getField(protoMember);
        Object retainedValue = retainAll(schema, markSet, field.type(), entry.getValue());
        if (retainedValue != null) {
          builder.put(protoMember, retainedValue); // This retained field is non-empty.
        }
      }
      ImmutableMap<ProtoMember, Object> map = builder.build();
      return !map.isEmpty() ? map : null;

    } else if (o instanceof List) {
      ImmutableList.Builder<Object> builder = ImmutableList.builder();
      for (Object value : ((List) o)) {
        Object retainedValue = retainAll(schema, markSet, type, value);
        if (retainedValue != null) {
          builder.add(retainedValue); // This retained value is non-empty.
        }
      }
      ImmutableList<Object> list = builder.build();
      return !list.isEmpty() ? list : null;

    } else {
      return o;
    }
  }
  @Override
  public int execute(ExecutionContext context) {
    File inputDirectory = inputDirectoryPath.toFile();
    Preconditions.checkState(
        inputDirectory.exists() && inputDirectory.isDirectory(),
        "%s must be a directory.",
        inputDirectoryPath);

    try {
      ImmutableMap.Builder<File, ZipEntry> zipEntriesBuilder = ImmutableMap.builder();
      addDirectoryToZipEntryList(inputDirectory, "", zipEntriesBuilder);
      ImmutableMap<File, ZipEntry> zipEntries = zipEntriesBuilder.build();

      if (!zipEntries.isEmpty()) {
        try (CustomZipOutputStream outputStream =
            ZipOutputStreams.newOutputStream(outputZipPath.toFile())) {
          for (Map.Entry<File, ZipEntry> zipEntry : zipEntries.entrySet()) {
            outputStream.putNextEntry(zipEntry.getValue());
            ByteStreams.copy(Files.newInputStreamSupplier(zipEntry.getKey()), outputStream);
            outputStream.closeEntry();
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace(context.getStdErr());
      return 1;
    }
    return 0;
  }
 @Override
 public Map<String, String> toMetadataRecord() {
   ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
   builder.put("id", getId());
   if (getDisplayName() != null) builder.put("displayName", getDisplayName());
   return builder.build();
 }
  /**
   * Build a {@link HeaderSymlinkTree} of all the shared libraries found via the top-level rule's
   * transitive dependencies.
   */
  public static SymlinkTree createSharedLibrarySymlinkTree(
      TargetGraph targetGraph,
      BuildRuleParams params,
      SourcePathResolver pathResolver,
      CxxPlatform cxxPlatform,
      Predicate<Object> traverse) {

    BuildTarget symlinkTreeTarget =
        createSharedLibrarySymlinkTreeTarget(params.getBuildTarget(), cxxPlatform.getFlavor());
    Path symlinkTreeRoot =
        getSharedLibrarySymlinkTreePath(params.getBuildTarget(), cxxPlatform.getFlavor());

    ImmutableSortedMap<String, SourcePath> libraries =
        NativeLinkables.getTransitiveSharedLibraries(
            targetGraph, cxxPlatform, params.getDeps(), Linker.LinkableDepType.SHARED, traverse);

    ImmutableMap.Builder<Path, SourcePath> links = ImmutableMap.builder();
    for (Map.Entry<String, SourcePath> ent : libraries.entrySet()) {
      links.put(Paths.get(ent.getKey()), ent.getValue());
    }
    try {
      return new SymlinkTree(
          params.copyWithChanges(
              symlinkTreeTarget,
              Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of()),
              Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of())),
          pathResolver,
          symlinkTreeRoot,
          links.build());
    } catch (SymlinkTree.InvalidSymlinkTreeException e) {
      throw new RuntimeException(e.getMessage());
    }
  }
示例#17
0
  // Using reflection gets all token names and values from JavadocTokenTypes class
  // and saves to TOKEN_NAME_TO_VALUE and TOKEN_VALUE_TO_NAME collections.
  static {
    final ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();

    final Field[] fields = JavadocTokenTypes.class.getDeclaredFields();

    String[] tempTokenValueToName = new String[0];

    for (final Field f : fields) {

      // Only process public int fields.
      if (!Modifier.isPublic(f.getModifiers()) || f.getType() != Integer.TYPE) {
        continue;
      }

      final String name = f.getName();

      final int tokenValue = Utils.getIntFromField(f, name);
      builder.put(name, tokenValue);
      if (tokenValue > tempTokenValueToName.length - 1) {
        final String[] temp = new String[tokenValue + 1];
        System.arraycopy(tempTokenValueToName, 0, temp, 0, tempTokenValueToName.length);
        tempTokenValueToName = temp;
      }
      if (tokenValue == -1) {
        tempTokenValueToName[0] = name;
      } else {
        tempTokenValueToName[tokenValue] = name;
      }
    }

    TOKEN_NAME_TO_VALUE = builder.build();
    TOKEN_VALUE_TO_NAME = tempTokenValueToName;
  }
示例#18
0
文件: PexStep.java 项目: sagiru/buck
  private ImmutableMap<Path, Path> getExpandedSourcePaths(
      ExecutionContext context, ImmutableMap<Path, Path> paths) throws IOException {
    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
    ImmutableMap.Builder<Path, Path> sources = ImmutableMap.builder();

    for (ImmutableMap.Entry<Path, Path> ent : paths.entrySet()) {
      if (ent.getValue().toString().endsWith(SRC_ZIP)) {
        Path destinationDirectory = projectFilesystem.resolve(tempDir.resolve(ent.getKey()));
        Files.createDirectories(destinationDirectory);

        ImmutableList<Path> zipPaths =
            Unzip.extractZipFile(
                projectFilesystem.resolve(ent.getValue()),
                destinationDirectory,
                Unzip.ExistingFileMode.OVERWRITE);
        for (Path path : zipPaths) {
          Path modulePath = destinationDirectory.relativize(path);
          sources.put(modulePath, path);
        }
      } else {
        sources.put(ent.getKey(), ent.getValue());
      }
    }

    return sources.build();
  }
示例#19
0
 private static ImmutableMap<String, JetToken> tokenSetToMap(TokenSet tokens) {
   ImmutableMap.Builder<String, JetToken> builder = ImmutableMap.builder();
   for (IElementType token : tokens.getTypes()) {
     builder.put(token.toString(), (JetToken) token);
   }
   return builder.build();
 }
    @Override
    public ProjectMap getProjectsByIdList(List<Integer> projIdList) {
      if (projIdList.isEmpty()) {
        return ProjectMap.empty();
      }

      List<StoredProject> projs =
          autoCommit(
              (handle, dao) ->
                  handle
                      .createQuery(
                          "select * from projects"
                              + " where site_id = :siteId"
                              + " and id "
                              + inLargeIdListExpression(projIdList))
                      .bind("siteId", siteId)
                      .map(new StoredProjectMapper(cfm))
                      .list());

      ImmutableMap.Builder<Integer, StoredProject> builder = ImmutableMap.builder();
      for (StoredProject proj : projs) {
        builder.put(proj.getId(), proj);
      }
      return new ProjectMap(builder.build());
    }
示例#21
0
 private ImmutableMap<String, JdbcTable> computeTables() {
   Connection connection = null;
   ResultSet resultSet = null;
   try {
     connection = dataSource.getConnection();
     DatabaseMetaData metaData = connection.getMetaData();
     resultSet = metaData.getTables(catalog, schema, null, null);
     final ImmutableMap.Builder<String, JdbcTable> builder = ImmutableMap.builder();
     while (resultSet.next()) {
       final String tableName = resultSet.getString(3);
       final String catalogName = resultSet.getString(1);
       final String schemaName = resultSet.getString(2);
       final String tableTypeName = resultSet.getString(4);
       // Clean up table type. In particular, this ensures that 'SYSTEM TABLE',
       // returned by Phoenix among others, maps to TableType.SYSTEM_TABLE.
       // We know enum constants are upper-case without spaces, so we can't
       // make things worse.
       final String tableTypeName2 = tableTypeName.toUpperCase().replace(' ', '_');
       final TableType tableType = Util.enumVal(TableType.class, tableTypeName2);
       final JdbcTable table = new JdbcTable(this, catalogName, schemaName, tableName, tableType);
       builder.put(tableName, table);
     }
     return builder.build();
   } catch (SQLException e) {
     throw new RuntimeException("Exception while reading tables", e);
   } finally {
     close(connection, null, resultSet);
   }
 }
 public static Map<Long, ZoneId> listToMap(List<IdTimeZone> list) {
   ImmutableMap.Builder<Long, ZoneId> builder = ImmutableMap.builder();
   for (IdTimeZone pair : list) {
     builder.put(pair.id, pair.timeZone);
   }
   return builder.build();
 }
示例#23
0
 public FileDataCache(Iterable<FileData> fileData) {
   ImmutableMap.Builder<String, byte[]> builder = ImmutableMap.builder();
   for (FileData data : fileData) {
     builder.put(data.getInfo().getDigest(), data.getContent().toByteArray());
   }
   fileContents = builder.build();
 }
 public FetchNotificationsResult a(
     FetchNotificationsParams paramFetchNotificationsParams, ApiResponse paramApiResponse) {
   paramApiResponse.g();
   FqlResultHelper localFqlResultHelper = new FqlResultHelper(paramApiResponse.c());
   JsonNode localJsonNode1 = localFqlResultHelper.a("notifications");
   JsonNode localJsonNode2 = localFqlResultHelper.a("profiles");
   ImmutableList.Builder localBuilder = ImmutableList.e();
   Iterator localIterator1 = localJsonNode1.iterator();
   while (localIterator1.hasNext()) {
     JsonNode localJsonNode4 = (JsonNode) localIterator1.next();
     localBuilder.b(
         FacebookNotification.a(FBJsonFactory.a.createJsonParser(localJsonNode4.toString())));
   }
   ImmutableMap.Builder localBuilder1 = ImmutableMap.k();
   Iterator localIterator2 = localJsonNode2.iterator();
   while (localIterator2.hasNext()) {
     JsonNode localJsonNode3 = (JsonNode) localIterator2.next();
     FacebookProfile localFacebookProfile =
         FacebookProfile.a(FBJsonFactory.a.createJsonParser(localJsonNode3.toString()));
     localBuilder1.b(Long.valueOf(localFacebookProfile.mId), localFacebookProfile);
   }
   return new FetchNotificationsResult(
       DataFreshnessResult.FROM_SERVER,
       localBuilder.b(),
       localBuilder1.b(),
       System.currentTimeMillis());
 }
示例#25
0
文件: CxxTest.java 项目: sdwilsh/buck
 public CxxTest(
     BuildRuleParams params,
     SourcePathResolver resolver,
     final ImmutableMap<String, String> toolEnv,
     final Supplier<ImmutableMap<String, String>> env,
     Supplier<ImmutableList<String>> args,
     ImmutableSortedSet<SourcePath> resources,
     Supplier<ImmutableSortedSet<BuildRule>> additionalDeps,
     ImmutableSet<Label> labels,
     ImmutableSet<String> contacts,
     boolean runTestSeparately,
     Optional<Long> testRuleTimeoutMs) {
   super(params, resolver);
   this.env =
       Suppliers.memoize(
           () -> {
             ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
             builder.putAll(toolEnv);
             builder.putAll(env.get());
             return builder.build();
           });
   this.args = Suppliers.memoize(args);
   this.resources = resources;
   this.additionalDeps = Suppliers.memoize(additionalDeps);
   this.labels = labels;
   this.contacts = contacts;
   this.runTestSeparately = runTestSeparately;
   this.testRuleTimeoutMs = testRuleTimeoutMs;
 }
  public ImmutableMap<String, Method> build() {

    final ImmutableMap.Builder<String, Method> lResultBuilder =
        new ImmutableMap.Builder<String, Method>();

    // iterate based on mMethodsOrdered to maintain
    // the order
    for (String lBeanPropName : mMethodsOrdered) {

      final NavigableSet<Method> lAllMethods = mMethodCache.getUnchecked(lBeanPropName);
      final Method lMostPreciseMethod = lAllMethods.last();

      LOGGER.trace(
          "propName [{}] selected method [{}] all methods[{}]",
          new Object[] {lBeanPropName, lMostPreciseMethod, lAllMethods});

      if (mBeanMethodFilter.accepts(lMostPreciseMethod, lBeanPropName)) {
        lResultBuilder.put(lBeanPropName, lMostPreciseMethod);
      } else {
        LOGGER.trace("rejected [{}]", lBeanPropName);
      }
    }

    return lResultBuilder.build();
  }
示例#27
0
 private static ServicePorts of(final Iterable<String> ports) {
   final ImmutableMap.Builder<String, ServicePortParameters> builder = ImmutableMap.builder();
   for (final String port : ports) {
     builder.put(port, new ServicePortParameters());
   }
   return new ServicePorts(builder.build());
 }
  private void performPlaceHolderSubstitution(
      ManifestInfo manifestInfo,
      XmlDocument xmlDocument,
      MergingReport.Builder mergingReportBuilder) {

    // check for placeholders presence, switch first the packageName and application id if
    // it is not explicitly set.
    Map<String, Object> finalPlaceHolderValues = mPlaceHolderValues;
    if (!mPlaceHolderValues.containsKey("applicationId")) {
      String packageName =
          manifestInfo.getMainManifestPackageName().isPresent()
              ? manifestInfo.getMainManifestPackageName().get()
              : xmlDocument.getPackageName();
      // add all existing placeholders except package name that will be swapped.
      ImmutableMap.Builder<String, Object> builder = ImmutableMap.<String, Object>builder();
      for (Map.Entry<String, Object> entry : mPlaceHolderValues.entrySet()) {
        if (!entry.getKey().equals(PlaceholderHandler.PACKAGE_NAME)) {
          builder.put(entry);
        }
      }
      finalPlaceHolderValues =
          builder
              .put(PlaceholderHandler.PACKAGE_NAME, packageName)
              .put(PlaceholderHandler.APPLICATION_ID, packageName)
              .build();
    }

    KeyBasedValueResolver<String> placeHolderValueResolver =
        new MapBasedKeyBasedValueResolver<String>(finalPlaceHolderValues);
    PlaceholderHandler placeholderHandler = new PlaceholderHandler();
    placeholderHandler.visit(
        mMergeType, xmlDocument, placeHolderValueResolver, mergingReportBuilder);
  }
示例#29
0
 static {
   ImmutableMap.Builder<String, GttCommand> builder = ImmutableMap.builder();
   for (GttCommand command : GttCommand.values()) {
     builder.put(command.name().toLowerCase(), command);
   }
   NAME_TO_COMMAND_MAP = builder.build();
 }
示例#30
0
 /**
  * Unify the two types symmetrically, given that we have already instantiated the type variables
  * of interest in {@code nt1} and {@code nt2}, treating JSType.UNKNOWN as a "hole" to be filled.
  *
  * @return The unified type, or null if unification fails
  */
 static NominalType unifyUnknowns(NominalType nt1, NominalType nt2) {
   if (!nt1.rawType.equals(nt2.rawType)) {
     return null;
   }
   Map<String, JSType> m1 = nt1.typeMap;
   Map<String, JSType> m2 = nt2.typeMap;
   if (m1.isEmpty() && m2.isEmpty()) {
     return nt1;
   } else if (m1.isEmpty() || m2.isEmpty()) {
     return null;
   }
   ImmutableMap.Builder<String, JSType> builder = ImmutableMap.builder();
   for (Map.Entry<String, JSType> entry : m1.entrySet()) {
     String typeVar = entry.getKey();
     JSType t1 = entry.getValue();
     JSType t2 = m2.get(typeVar);
     if (t1.isUnknown()) {
       builder.put(typeVar, t2);
     } else if (t2.isUnknown()) {
       builder.put(typeVar, t1);
     } else {
       JSType newType = JSType.unifyUnknowns(t1, t2);
       if (newType == null) {
         return null;
       }
       builder.put(typeVar, newType);
     }
   }
   return new NominalType(builder.build(), nt1.rawType);
 }