コード例 #1
0
ファイル: RelationPlanner.java プロジェクト: Kagaherk/presto
  private PlanBuilder appendProjections(PlanBuilder subPlan, Iterable<Expression> expressions) {
    TranslationMap translations = new TranslationMap(subPlan.getRelationPlan(), analysis);

    // Carry over the translations from the source because we are appending projections
    translations.copyMappingsFrom(subPlan.getTranslations());

    ImmutableMap.Builder<Symbol, Expression> projections = ImmutableMap.builder();

    // add an identity projection for underlying plan
    for (Symbol symbol : subPlan.getRoot().getOutputSymbols()) {
      Expression expression = new QualifiedNameReference(symbol.toQualifiedName());
      projections.put(symbol, expression);
    }

    ImmutableMap.Builder<Symbol, Expression> newTranslations = ImmutableMap.builder();
    for (Expression expression : expressions) {
      Symbol symbol = symbolAllocator.newSymbol(expression, analysis.getType(expression));

      // TODO: CHECK IF THE REWRITE OF A SEMI JOINED EXPRESSION WILL WORK!!!!!!!

      projections.put(symbol, translations.rewrite(expression));
      newTranslations.put(symbol, expression);
    }
    // Now append the new translations into the TranslationMap
    for (Map.Entry<Symbol, Expression> entry : newTranslations.build().entrySet()) {
      translations.put(entry.getValue(), entry.getKey());
    }

    return new PlanBuilder(
        translations,
        new ProjectNode(idAllocator.getNextId(), subPlan.getRoot(), projections.build()),
        subPlan.getSampleWeight());
  }
コード例 #2
0
ファイル: SoySauceImpl.java プロジェクト: rgpower/plovr
    public SoySauceImpl create(
        CompiledTemplates templates,
        ImmutableMap<String, ? extends SoyFunction> soyFunctionMap,
        ImmutableMap<String, ? extends SoyPrintDirective> printDirectives) {
      // SoySauce has no need for SoyFunctions that are not SoyJavaFunctions
      // (it generates Java source code implementing BuiltinFunctions).
      // Filter them out.
      ImmutableMap.Builder<String, SoyJavaFunction> soyJavaFunctions = ImmutableMap.builder();
      for (Map.Entry<String, ? extends SoyFunction> entry : soyFunctionMap.entrySet()) {
        SoyFunction function = entry.getValue();
        if (function instanceof SoyJavaFunction) {
          soyJavaFunctions.put(entry.getKey(), (SoyJavaFunction) function);
        }
      }

      // SoySauce has no need for SoyPrintDirectives that are not SoyJavaPrintDirectives.
      // Filter them out.
      ImmutableMap.Builder<String, SoyJavaPrintDirective> soyJavaPrintDirectives =
          ImmutableMap.builder();
      for (Map.Entry<String, ? extends SoyPrintDirective> entry : printDirectives.entrySet()) {
        SoyPrintDirective printDirective = entry.getValue();
        if (printDirective instanceof SoyJavaPrintDirective) {
          soyJavaPrintDirectives.put(entry.getKey(), (SoyJavaPrintDirective) printDirective);
        }
      }
      return new SoySauceImpl(
          templates,
          apiCallScopeProvider,
          converterProvider.get(),
          soyJavaFunctions.build(),
          soyJavaPrintDirectives.build());
    }
コード例 #3
0
 private static ImmutableMap<String, String> getQueryMap(final String query)
     throws MalformedRequestException {
   if (StringUtils.isBlank(query)) {
     return ImmutableMap.of();
   } else {
     final Iterable<String> params = Splitter.on('&').split(query);
     final ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
     for (final String param : params) {
       final ImmutableList<String> strings = ImmutableList.copyOf(Splitter.on('=').split(param));
       final String name = strings.get(0);
       if (strings.size() > 2) {
         throw new MalformedRequestException("Multiple '=' for parameter " + name);
       }
       final String value;
       if (strings.size() > 1) {
         value = strings.get(1);
       } else {
         value = null;
       }
       if (map.build().keySet().contains(name)) {
         throw new MalformedRequestException("Duplicate value for parameter " + name);
       }
       map.put(name, value);
     }
     return map.build();
   }
 }
コード例 #4
0
ファイル: PlanBuilder.java プロジェクト: XLabWang/presto
  public PlanBuilder appendProjections(
      Iterable<Expression> expressions,
      SymbolAllocator symbolAllocator,
      PlanNodeIdAllocator idAllocator) {
    TranslationMap translations = copyTranslations();

    ImmutableMap.Builder<Symbol, Expression> projections = ImmutableMap.builder();

    // add an identity projection for underlying plan
    for (Symbol symbol : getRoot().getOutputSymbols()) {
      projections.put(symbol, symbol.toSymbolReference());
    }

    ImmutableMap.Builder<Symbol, Expression> newTranslations = ImmutableMap.builder();
    ParameterRewriter parameterRewriter = new ParameterRewriter(parameters, getAnalysis());
    for (Expression expression : expressions) {
      Expression rewritten = ExpressionTreeRewriter.rewriteWith(parameterRewriter, expression);
      translations.addIntermediateMapping(expression, rewritten);
      Symbol symbol =
          symbolAllocator.newSymbol(rewritten, getAnalysis().getTypeWithCoercions(expression));
      projections.put(symbol, translations.rewrite(rewritten));
      newTranslations.put(symbol, rewritten);
    }
    // Now append the new translations into the TranslationMap
    for (Map.Entry<Symbol, Expression> entry : newTranslations.build().entrySet()) {
      translations.put(entry.getValue(), entry.getKey());
    }

    return new PlanBuilder(
        translations,
        new ProjectNode(idAllocator.getNextId(), getRoot(), projections.build()),
        parameters);
  }
コード例 #5
0
 /**
  * Produces a factory that allows the union of the grants, and intersects policies where they
  * overlap on a particular granted attribute or element name.
  */
 public PolicyFactory and(PolicyFactory f) {
   ImmutableMap.Builder<String, ElementAndAttributePolicies> b = ImmutableMap.builder();
   // Merge this and f into a map of element names to attribute policies.
   for (Map.Entry<String, ElementAndAttributePolicies> e : policies.entrySet()) {
     String elName = e.getKey();
     ElementAndAttributePolicies p = e.getValue();
     ElementAndAttributePolicies q = f.policies.get(elName);
     if (q != null) {
       p = p.and(q);
     } else {
       // Mix in any globals that are not already taken into account in this.
       p = p.andGlobals(f.globalAttrPolicies);
     }
     b.put(elName, p);
   }
   // Handle keys that are in f but not in this.
   for (Map.Entry<String, ElementAndAttributePolicies> e : f.policies.entrySet()) {
     String elName = e.getKey();
     if (!policies.containsKey(elName)) {
       ElementAndAttributePolicies p = e.getValue();
       // Mix in any globals that are not already taken into account in this.
       p = p.andGlobals(f.globalAttrPolicies);
       b.put(elName, p);
     }
   }
   ImmutableSet<String> textContainers;
   if (this.textContainers.containsAll(f.textContainers)) {
     textContainers = this.textContainers;
   } else if (f.textContainers.containsAll(this.textContainers)) {
     textContainers = f.textContainers;
   } else {
     textContainers =
         ImmutableSet.<String>builder()
             .addAll(this.textContainers)
             .addAll(f.textContainers)
             .build();
   }
   ImmutableMap<String, AttributePolicy> allGlobalAttrPolicies;
   if (f.globalAttrPolicies.isEmpty()) {
     allGlobalAttrPolicies = this.globalAttrPolicies;
   } else if (this.globalAttrPolicies.isEmpty()) {
     allGlobalAttrPolicies = f.globalAttrPolicies;
   } else {
     ImmutableMap.Builder<String, AttributePolicy> ab = ImmutableMap.builder();
     for (Map.Entry<String, AttributePolicy> e : this.globalAttrPolicies.entrySet()) {
       String attrName = e.getKey();
       ab.put(
           attrName, AttributePolicy.Util.join(e.getValue(), f.globalAttrPolicies.get(attrName)));
     }
     for (Map.Entry<String, AttributePolicy> e : f.globalAttrPolicies.entrySet()) {
       String attrName = e.getKey();
       if (!this.globalAttrPolicies.containsKey(attrName)) {
         ab.put(attrName, e.getValue());
       }
     }
     allGlobalAttrPolicies = ab.build();
   }
   return new PolicyFactory(b.build(), textContainers, allGlobalAttrPolicies);
 }
コード例 #6
0
 public SetMessagesResponse build() {
   return new SetMessagesResponse(
       accountId,
       oldState,
       newState,
       created.build(),
       updated.build(),
       destroyed.build(),
       notCreated.build(),
       notUpdated.build(),
       notDestroyed.build());
 }
コード例 #7
0
    AllProjectRoles(Collection<ProjectRole> projectRoles) {
      final ImmutableMap.Builder<Long, ProjectRole> byId = ImmutableMap.builder();
      final ImmutableMap.Builder<String, ProjectRole> byName = ImmutableMap.builder();
      for (ProjectRole projectRole : projectRoles) {
        byId.put(projectRole.getId(), projectRole);
        byName.put(projectRole.getName(), projectRole);
      }

      this.projectRoles = ImmutableList.copyOf(projectRoles);
      this.projectRolesById = byId.build();
      this.projectRolesByName = byName.build();
    }
コード例 #8
0
  static {
    final ImmutableMap.Builder<String, JavadocTagInfo> textToTagBuilder =
        new ImmutableMap.Builder<>();

    final ImmutableMap.Builder<String, JavadocTagInfo> nameToTagBuilder =
        new ImmutableMap.Builder<>();

    for (final JavadocTagInfo tag : JavadocTagInfo.values()) {
      textToTagBuilder.put(tag.getText(), tag);
      nameToTagBuilder.put(tag.getName(), tag);
    }

    TEXT_TO_TAG = textToTagBuilder.build();
    NAME_TO_TAG = nameToTagBuilder.build();
  }
コード例 #9
0
    @Override
    public PlanNode visitWindow(WindowNode node, RewriteContext<Set<Symbol>> context) {
      ImmutableSet.Builder<Symbol> expectedInputs =
          ImmutableSet.<Symbol>builder()
              .addAll(context.get())
              .addAll(node.getPartitionBy())
              .addAll(node.getOrderBy());

      if (node.getFrame().getStartValue().isPresent()) {
        expectedInputs.add(node.getFrame().getStartValue().get());
      }
      if (node.getFrame().getEndValue().isPresent()) {
        expectedInputs.add(node.getFrame().getEndValue().get());
      }

      if (node.getHashSymbol().isPresent()) {
        expectedInputs.add(node.getHashSymbol().get());
      }

      ImmutableMap.Builder<Symbol, Signature> functions = ImmutableMap.builder();
      ImmutableMap.Builder<Symbol, FunctionCall> functionCalls = ImmutableMap.builder();
      for (Map.Entry<Symbol, FunctionCall> entry : node.getWindowFunctions().entrySet()) {
        Symbol symbol = entry.getKey();

        if (context.get().contains(symbol)) {
          FunctionCall call = entry.getValue();
          expectedInputs.addAll(DependencyExtractor.extractUnique(call));

          functionCalls.put(symbol, call);
          functions.put(symbol, node.getSignatures().get(symbol));
        }
      }

      PlanNode source = context.rewrite(node.getSource(), expectedInputs.build());

      return new WindowNode(
          node.getId(),
          source,
          node.getPartitionBy(),
          node.getOrderBy(),
          node.getOrderings(),
          node.getFrame(),
          functionCalls.build(),
          functions.build(),
          node.getHashSymbol(),
          node.getPrePartitionedInputs(),
          node.getPreSortedOrderPrefix());
    }
コード例 #10
0
ファイル: JdbcSchema.java プロジェクト: NGDATA/optiq
 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);
   }
 }
コード例 #11
0
  /** 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);
  }
コード例 #12
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();
 }
コード例 #13
0
ファイル: ProjectWorkspace.java プロジェクト: sdwilsh/buck
  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();
  }
コード例 #14
0
 @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;
 }
コード例 #15
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();
 }
コード例 #16
0
 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();
 }
コード例 #17
0
ファイル: AttributeService.java プロジェクト: noctarius/jimfs
  /**
   * 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();
  }
コード例 #18
0
 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();
 }
コード例 #19
0
    @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());
    }
コード例 #20
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();
  }
コード例 #21
0
  /**
   * 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());
    }
  }
コード例 #22
0
ファイル: MultiModel.java プロジェクト: devoidoflife/panoply
  @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());
  }
コード例 #23
0
ファイル: FileDataCache.java プロジェクト: bowlofstew/kythe
 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();
 }
コード例 #24
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();
 }
コード例 #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;
 }
コード例 #26
0
ファイル: JavadocUtils.java プロジェクト: Griznt/checkstyle
  // 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;
  }
コード例 #27
0
ファイル: ServicePorts.java プロジェクト: rootwzrd/helios
 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());
 }
コード例 #28
0
ファイル: RuleUtilsTest.java プロジェクト: nickpalmer/buck
  @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());
  }
コード例 #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
  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();
  }