Java Code Examples for com.google.common.collect.ImmutableSortedSet#isEmpty()

The following examples show how to use com.google.common.collect.ImmutableSortedSet#isEmpty() . 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: MultiarchFileInfos.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the format string for the fat rule output. If all the thin rules have the same output
 * file name, use this as the file name for the fat rule output. Otherwise, default to simple
 * string substitution.
 */
@VisibleForTesting
static String getMultiarchOutputFormatString(
    SourcePathResolverAdapter pathResolver, ImmutableSortedSet<SourcePath> inputs) {
  if (inputs.isEmpty()) {
    return BASE_OUTPUT_FORMAT_STRING;
  }

  String outputFileName = pathResolver.getAbsolutePath(inputs.first()).getFileName().toString();

  for (SourcePath input : inputs) {
    String inputFileName = pathResolver.getAbsolutePath(input).getFileName().toString();

    if (!outputFileName.equals(inputFileName)) {
      // not all input files have the same name, so don't try to match them
      return BASE_OUTPUT_FORMAT_STRING;
    }
  }

  // all input files have same output file name, match it for the output
  return NESTED_OUTPUT_FORMAT_STRING + outputFileName;
}
 
Example 2
Source File: FileTreeComputation.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableSet<FileTreeKey> discoverDeps(FileTreeKey key, ComputationEnvironment env) {
  DirectoryList currentDir = env.getDep(ImmutableDirectoryListKey.of(key.getPath()));
  ImmutableSortedSet<Path> subDirs = currentDir.getDirectories();
  if (subDirs.isEmpty()) {
    return ImmutableSet.of();
  }

  ImmutableSet.Builder<FileTreeKey> depsBuilder =
      ImmutableSet.builderWithExpectedSize(subDirs.size());

  for (Path path : subDirs) {
    depsBuilder.add(ImmutableFileTreeKey.of(path));
  }

  return depsBuilder.build();
}
 
Example 3
Source File: MangleNicks.java    From VileBot with MIT License 6 votes vote down vote up
private static String mangleNicks( ImmutableSortedSet<String> nicks, String message )
{

    if ( nicks.isEmpty() )
    {
        return message;
    }

    StringBuilder reply = new StringBuilder();
    for ( String word : message.split( " " ) )
    {
        reply.append( " " );
        reply.append( inside( nicks, word ) ? mangled( word ) : word );
    }
    return reply.toString().trim();
}
 
Example 4
Source File: BoundingBox.java    From activitystreams with Apache License 2.0 6 votes vote down vote up
private static BoundingBox buildBoundingBox(
  ImmutableSortedSet<Float> xs,
  ImmutableSortedSet<Float> ys,
  ImmutableSortedSet<Float> zs) {
  BoundingBox.Builder bbox = 
    new BoundingBox.Builder()
      .add(xs.first())
      .add(ys.first());
  if (!zs.isEmpty())
    bbox.add(zs.first());
  bbox.add(xs.last());
  bbox.add(ys.last());
  if (!zs.isEmpty())
    bbox.add(zs.last());
  return bbox.get();
}
 
Example 5
Source File: AbstractLocationMacroExpander.java    From buck with Apache License 2.0 5 votes vote down vote up
private Arg resolveArgWithBracketSyntax(OutputLabel outputLabel, BuildRule rule)
    throws MacroException {
  if (rule instanceof HasSupplementaryOutputs) {
    SourcePath output =
        ((HasSupplementaryOutputs) rule)
            .getSourcePathToSupplementaryOutput(OutputLabel.internals().getLabel(outputLabel));
    if (output == null) {
      throw new MacroException(
          String.format(
              "%s used in location macro does not produce supplementary output %s",
              rule.getBuildTarget(), outputLabel));
    }
    return SourcePathArg.of(output);
  } else if (rule instanceof HasMultipleOutputs) {
    ImmutableSortedSet<SourcePath> outputs =
        ((HasMultipleOutputs) rule).getSourcePathToOutput(outputLabel);
    if (outputs == null || outputs.isEmpty()) {
      throw new MacroException(
          String.format(
              "%s used in location macro does not produce outputs with label [%s]",
              rule.getBuildTarget(), outputLabel));
    }
    try {
      return SourcePathArg.of(Iterables.getOnlyElement(outputs));
    } catch (IllegalArgumentException e) {
      throw new MacroException(
          String.format(
              "%s[%s] produces multiple outputs but location macro accepts only one output",
              rule.getBuildTarget(), outputLabel));
    }
  }
  throw new MacroException(
      String.format(
          "%s used in location macro does not produce supplementary output or output groups",
          rule.getBuildTarget()));
}
 
Example 6
Source File: GetAnnotationProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Optional<Integer> getMaxSizeOfOversizedItems(List<MailboxAnnotation> mailboxAnnotations, final Integer maxsize) {
    Predicate<MailboxAnnotation> filterOverSizedAnnotation = annotation -> annotation.size() > maxsize;

    ImmutableSortedSet<Integer> overLimitSizes = mailboxAnnotations.stream()
        .filter(filterOverSizedAnnotation)
        .map(MailboxAnnotation::size)
        .collect(Guavate.toImmutableSortedSet(Comparator.reverseOrder()));

    if (overLimitSizes.isEmpty()) {
        return Optional.empty();
    }
    return Optional.of(overLimitSizes.first());
}
 
Example 7
Source File: SourceSortedSetAttribute.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void validateCoercedValue(ImmutableSortedSet<SourcePath> paths)
    throws CoerceFailedException {
  if (!getAllowEmpty() && paths.isEmpty()) {
    throw new CoerceFailedException("List of source paths may not be empty");
  }
}
 
Example 8
Source File: RuleAnalysisLegacyBuildRuleView.java    From buck with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public SourcePath getSourcePathToOutput() {
  ImmutableSortedSet<SourcePath> output = getSourcePathToOutput(OutputLabel.defaultLabel());
  if (output.isEmpty()) {
    return null;
  }
  return Iterables.getOnlyElement(output);
}
 
Example 9
Source File: HasMultipleOutputs.java    From buck with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
default SourcePath getSourcePathToOutput() {
  ImmutableSortedSet<SourcePath> sourcePaths = getSourcePathToOutput(OutputLabel.defaultLabel());
  return sourcePaths == null || sourcePaths.isEmpty()
      ? null
      : Iterables.getOnlyElement(sourcePaths);
}
 
Example 10
Source File: FlavorSet.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Constructor. */
public static FlavorSet copyOf(ImmutableSortedSet<Flavor> flavors) {
  if (flavors.isEmpty()) {
    return NO_FLAVORS;
  } else {
    return new FlavorSet(ImmutableSortedSet.copyOf(FLAVOR_ORDERING, flavors));
  }
}
 
Example 11
Source File: DefaultSourcePathResolver.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
protected ImmutableSortedSet<SourcePath> resolveDefaultBuildTargetSourcePath(
    DefaultBuildTargetSourcePath targetSourcePath) {
  BuildTargetWithOutputs buildTargetWithOutputs = targetSourcePath.getTargetWithOutputs();
  BuildRule rule = ruleFinder.getRule(targetSourcePath);
  if (rule instanceof HasMultipleOutputs) {
    ImmutableSortedSet<SourcePath> resolvedPaths =
        ((HasMultipleOutputs) rule)
            .getSourcePathToOutput(buildTargetWithOutputs.getOutputLabel());
    if (resolvedPaths == null || resolvedPaths.isEmpty()) {
      throw new HumanReadableException(
          "No known output for: %s", targetSourcePath.getTargetWithOutputs());
    }
    return resolvedPaths;
  }
  Preconditions.checkState(
      buildTargetWithOutputs.getOutputLabel().isDefault(),
      "Multiple outputs not supported for %s target %s",
      rule.getType(),
      targetSourcePath.getTargetWithOutputs());
  SourcePath resolvedPath = rule.getSourcePathToOutput();
  if (resolvedPath == null) {
    throw new HumanReadableException(
        "No known output for: %s", targetSourcePath.getTargetWithOutputs());
  }
  return ImmutableSortedSet.of(resolvedPath);
}
 
Example 12
Source File: ConfigFeatureFlagTaggedTrimmingTransitionFactory.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public PatchTransition create(Rule rule) {
  NonconfigurableAttributeMapper attrs = NonconfigurableAttributeMapper.of(rule);
  RuleClass ruleClass = rule.getRuleClassObject();
  if (ruleClass.getName().equals(ConfigRuleClasses.ConfigFeatureFlagRule.RULE_NAME)) {
    return new ConfigFeatureFlagTaggedTrimmingTransition(ImmutableSortedSet.of(rule.getLabel()));
  }

  ImmutableSortedSet.Builder<Label> requiredLabelsBuilder =
      new ImmutableSortedSet.Builder<>(Ordering.natural());
  if (attrs.isAttributeValueExplicitlySpecified(attributeName)
      && !attrs.get(attributeName, NODEP_LABEL_LIST).isEmpty()) {
    requiredLabelsBuilder.addAll(attrs.get(attributeName, NODEP_LABEL_LIST));
  }
  if (ruleClass.getTransitionFactory() instanceof ConfigFeatureFlagTransitionFactory) {
    String settingAttribute =
        ((ConfigFeatureFlagTransitionFactory) ruleClass.getTransitionFactory())
            .getAttributeName();
    // Because the process of setting a flag also creates a dependency on that flag, we need to
    // include all the set flags, even if they aren't actually declared as used by this rule.
    requiredLabelsBuilder.addAll(attrs.get(settingAttribute, LABEL_KEYED_STRING_DICT).keySet());
  }

  ImmutableSortedSet<Label> requiredLabels = requiredLabelsBuilder.build();
  if (requiredLabels.isEmpty()) {
    return ConfigFeatureFlagTaggedTrimmingTransition.EMPTY;
  }

  return new ConfigFeatureFlagTaggedTrimmingTransition(requiredLabels);
}
 
Example 13
Source File: XProjectManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** Publish issues for the resource with the given URI to the {@link #issueRegistry}. */
protected void publishIssues(URI uri, Iterable<? extends LSPIssue> issues) {
	String projectName = projectConfig.getName();
	if (isResourceWithHiddenIssues(uri)) {
		// nothing to publish, BUT because the result value of #isResourceWithHiddenIssues() can change over time
		// for the same URI (e.g. source folders being added/removed in an existing project), we need to ensure to
		// remove issues that might have been published earlier:
		ImmutableSortedSet<LSPIssue> oldIssues = issueRegistry.getIssuesOfPersistedState(projectName, uri);
		if (oldIssues != null && !oldIssues.isEmpty()) {
			issueRegistry.clearIssuesOfPersistedState(projectName, uri);
		}
		return;
	}
	issueRegistry.setIssuesOfPersistedState(projectConfig.getName(), uri, issues);
}
 
Example 14
Source File: PathUtils.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Returns absolute path to the output rule, if the rule has an output. Cannot currently handle
 * multiple outputs since it returns either no path or one path only.
 *
 * @throws IllegalStateException if the given rule implements {@link HasMultipleOutputs} and
 *     returns more than one output from {@link
 *     HasMultipleOutputs#getSourcePathToOutput(OutputLabel)}
 */
static Optional<Path> getUserFacingOutputPath(
    SourcePathResolverAdapter pathResolver,
    BuildRule rule,
    boolean buckOutCompatLink,
    OutputLabel outputLabel,
    boolean showOutputLabels) {
  Optional<Path> outputPathOptional;
  if (rule instanceof HasMultipleOutputs) {
    if (!showOutputLabels && !outputLabel.isDefault()) {
      throw new HumanReadableException(
          "%s target %s[%s] should use --show-outputs",
          rule.getType(), rule.getFullyQualifiedName(), outputLabel);
    }
    ImmutableSortedSet<SourcePath> sourcePaths =
        ((HasMultipleOutputs) rule).getSourcePathToOutput(outputLabel);
    outputPathOptional =
        sourcePaths == null || sourcePaths.isEmpty()
            ? Optional.empty()
            : Optional.of(pathResolver.getRelativePath(Iterables.getOnlyElement(sourcePaths)));
  } else {
    Preconditions.checkState(
        outputLabel.isDefault(),
        "Multiple outputs not supported for %s target %s",
        rule.getType(),
        rule.getFullyQualifiedName());
    outputPathOptional =
        Optional.ofNullable(rule.getSourcePathToOutput()).map(pathResolver::getRelativePath);
  }
  // When using buck out compat mode, we favor using the default buck output path in the UI, so
  // amend the output paths when this is set.
  if (outputPathOptional.isPresent() && buckOutCompatLink) {
    BuckPaths paths = rule.getProjectFilesystem().getBuckPaths();
    if (outputPathOptional.get().startsWith(paths.getConfiguredBuckOut())) {
      outputPathOptional =
          Optional.of(
              paths
                  .getBuckOut()
                  .resolve(
                      outputPathOptional
                          .get()
                          .subpath(
                              paths.getConfiguredBuckOut().getNameCount(),
                              outputPathOptional.get().getNameCount())));
    }
  }

  return outputPathOptional.map(rule.getProjectFilesystem()::resolve);
}
 
Example 15
Source File: MultiarchFileInfos.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Generate a fat rule from thin rules.
 *
 * <p>Invariant: thinRules contain all the thin rules listed in info.getThinTargets().
 */
public static BuildRule requireMultiarchRule(
    BuildTarget buildTarget,
    ProjectFilesystem projectFilesystem,
    BuildRuleParams params,
    ActionGraphBuilder graphBuilder,
    MultiarchFileInfo info,
    ImmutableSortedSet<BuildRule> thinRules,
    CxxBuckConfig cxxBuckConfig,
    FlavorDomain<UnresolvedAppleCxxPlatform> appleCxxPlatformsFlavorDomain) {
  Optional<BuildRule> existingRule = graphBuilder.getRuleOptional(info.getFatTarget());
  if (existingRule.isPresent()) {
    return existingRule.get();
  }

  // Thin rules filtered to remove those with null output
  ImmutableSortedSet<SourcePath> inputs =
      FluentIterable.from(thinRules)
          .transform(BuildRule::getSourcePathToOutput)
          .filter(SourcePath.class)
          .toSortedSet(Ordering.natural());

  // If any thin rule exists with output, use `MultiarchFile` to generate binary. Otherwise,
  // use a `NoopBuildRule` to handle inputs like those without any sources.
  if (!inputs.isEmpty()) {
    String multiarchOutputPathFormat =
        getMultiarchOutputFormatString(graphBuilder.getSourcePathResolver(), inputs);

    AppleCxxPlatform applePlatform =
        appleCxxPlatformsFlavorDomain
            .getValue(info.getRepresentativePlatformFlavor())
            .resolve(graphBuilder);
    MultiarchFile multiarchFile =
        new MultiarchFile(
            buildTarget,
            projectFilesystem,
            params.withoutDeclaredDeps().withExtraDeps(thinRules),
            graphBuilder,
            applePlatform.getLipo(),
            inputs,
            cxxBuckConfig.shouldCacheLinks(),
            BuildTargetPaths.getGenPath(
                projectFilesystem, buildTarget, multiarchOutputPathFormat));
    graphBuilder.addToIndex(multiarchFile);
    return multiarchFile;
  } else {
    return new NoopBuildRule(buildTarget, projectFilesystem);
  }
}
 
Example 16
Source File: AppleDescriptions.java    From buck with Apache License 2.0 4 votes vote down vote up
public static Optional<AppleAssetCatalog> createBuildRuleForTransitiveAssetCatalogDependencies(
    XCodeDescriptions xcodeDescriptions,
    TargetGraph targetGraph,
    BuildTarget buildTarget,
    ProjectFilesystem projectFilesystem,
    SourcePathRuleFinder ruleFinder,
    Optional<String> productType,
    ApplePlatform applePlatform,
    String targetSDKVersion,
    Tool actool,
    AppleAssetCatalog.ValidationType assetCatalogValidation,
    AppleAssetCatalogsCompilationOptions appleAssetCatalogsCompilationOptions,
    Predicate<BuildTarget> filter) {
  TargetNode<?> targetNode = targetGraph.get(buildTarget);

  ImmutableSet<AppleAssetCatalogDescriptionArg> assetCatalogArgs =
      AppleBuildRules.collectRecursiveAssetCatalogs(
          xcodeDescriptions,
          targetGraph,
          Optional.empty(),
          ImmutableList.of(targetNode),
          RecursiveDependenciesMode.COPYING,
          filter);

  ImmutableSortedSet.Builder<SourcePath> assetCatalogDirsBuilder =
      ImmutableSortedSet.naturalOrder();

  Optional<String> appIcon = Optional.empty();
  Optional<String> launchImage = Optional.empty();

  for (AppleAssetCatalogDescriptionArg arg : assetCatalogArgs) {
    assetCatalogDirsBuilder.addAll(arg.getDirs());
    if (arg.getAppIcon().isPresent()) {
      if (appIcon.isPresent()) {
        throw new HumanReadableException(
            "At most one asset catalog in the dependencies of %s " + "can have a app_icon",
            buildTarget);
      }

      appIcon = arg.getAppIcon();
    }

    if (arg.getLaunchImage().isPresent()) {
      if (launchImage.isPresent()) {
        throw new HumanReadableException(
            "At most one asset catalog in the dependencies of %s " + "can have a launch_image",
            buildTarget);
      }

      launchImage = arg.getLaunchImage();
    }
  }

  ImmutableSortedSet<SourcePath> assetCatalogDirs = assetCatalogDirsBuilder.build();

  if (assetCatalogDirs.isEmpty()) {
    return Optional.empty();
  }

  validateAssetCatalogs(
      assetCatalogDirs,
      buildTarget,
      projectFilesystem,
      ruleFinder.getSourcePathResolver(),
      assetCatalogValidation);

  BuildTarget assetCatalogBuildTarget = buildTarget.withAppendedFlavors(AppleAssetCatalog.FLAVOR);
  if (buildTarget.getFlavors().contains(AppleBinaryDescription.LEGACY_WATCH_FLAVOR)) {
    // If the target is a legacy watch target, we need to provide the watchos platform to
    // the AppleAssetCatalog for it to generate assets in a format that's for watchos.
    applePlatform = ApplePlatform.WATCHOS;
    targetSDKVersion = "1.0";
  }
  return Optional.of(
      new AppleAssetCatalog(
          assetCatalogBuildTarget,
          projectFilesystem,
          ruleFinder,
          applePlatform.getName(),
          targetSDKVersion,
          actool,
          assetCatalogDirs,
          appIcon,
          launchImage,
          productType,
          appleAssetCatalogsCompilationOptions,
          MERGED_ASSET_CATALOG_NAME));
}
 
Example 17
Source File: ScalacToJarStepFactory.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public void createCompileStep(
    BuildContext context,
    ProjectFilesystem projectFilesystem,
    BuildTarget invokingRule,
    CompilerParameters parameters,
    /* output params */
    Builder<Step> steps,
    BuildableContext buildableContext) {

  ImmutableSortedSet<Path> classpathEntries = parameters.getClasspathEntries();
  ImmutableSortedSet<Path> sourceFilePaths = parameters.getSourceFilePaths();
  Path outputDirectory = parameters.getOutputPaths().getClassesDir();

  if (sourceFilePaths.stream().anyMatch(SCALA_PATH_MATCHER::matches)) {
    steps.add(
        new ScalacStep(
            scalac,
            ImmutableList.<String>builder()
                .addAll(configCompilerFlags)
                .addAll(extraArguments)
                .addAll(
                    Iterables.transform(
                        compilerPlugins,
                        input ->
                            "-Xplugin:" + context.getSourcePathResolver().getRelativePath(input)))
                .build(),
            context.getSourcePathResolver(),
            outputDirectory,
            sourceFilePaths,
            ImmutableSortedSet.<Path>naturalOrder()
                .addAll(
                    Optional.ofNullable(extraClassPath.getExtraClasspath())
                        .orElse(ImmutableList.of()))
                .addAll(classpathEntries)
                .build(),
            projectFilesystem));
  }

  ImmutableSortedSet<Path> javaSourceFiles =
      ImmutableSortedSet.copyOf(
          sourceFilePaths.stream()
              .filter(JAVA_PATH_MATCHER::matches)
              .collect(Collectors.toSet()));

  // Don't invoke javac if we don't have any java files.
  if (!javaSourceFiles.isEmpty()) {
    CompilerParameters javacParameters =
        CompilerParameters.builder()
            .from(parameters)
            .setClasspathEntries(
                ImmutableSortedSet.<Path>naturalOrder()
                    .add(outputDirectory)
                    .addAll(
                        Optional.ofNullable(extraClassPath.getExtraClasspath())
                            .orElse(ImmutableList.of()))
                    .addAll(classpathEntries)
                    .build())
            .setSourceFilePaths(javaSourceFiles)
            .build();
    new JavacToJarStepFactory(javac, javacOptions, extraClassPath)
        .createCompileStep(
            context, projectFilesystem, invokingRule, javacParameters, steps, buildableContext);
  }
}
 
Example 18
Source File: JavacPipelineState.java    From buck with Apache License 2.0 4 votes vote down vote up
public static ImmutableList<String> getOptions(
    JavacOptions javacOptions,
    ProjectFilesystem filesystem,
    SourcePathResolverAdapter pathResolver,
    Path outputDirectory,
    Path generatedCodeDirectory,
    ExecutionContext context,
    ImmutableSortedSet<Path> buildClasspathEntries) {
  ImmutableList.Builder<String> builder = ImmutableList.builder();

  javacOptions.appendOptionsTo(
      new OptionsConsumer() {
        @Override
        public void addOptionValue(String option, String value) {
          if (option.equals("bootclasspath")) {
            builder
                .add("-bootclasspath")
                .add(
                    Arrays.stream(value.split(File.pathSeparator))
                        .map(path -> filesystem.resolve(path).toString())
                        .collect(Collectors.joining(File.pathSeparator)));
          } else {
            builder.add("-" + option).add(value);
          }
        }

        @Override
        public void addFlag(String flagName) {
          builder.add("-" + flagName);
        }

        @Override
        public void addExtras(Collection<String> extras) {
          builder.addAll(extras);
        }
      },
      pathResolver,
      filesystem);

  // verbose flag, if appropriate.
  if (context.getVerbosity().shouldUseVerbosityFlagIfAvailable()) {
    builder.add("-verbose");
  }

  // Specify the output directory.
  builder.add("-d").add(filesystem.resolve(outputDirectory).toString());

  if (!javacOptions.getJavaAnnotationProcessorParams().isEmpty()) {
    builder.add("-s").add(filesystem.resolve(generatedCodeDirectory).toString());
  }

  // Build up and set the classpath.
  if (!buildClasspathEntries.isEmpty()) {
    String classpath = Joiner.on(File.pathSeparator).join(buildClasspathEntries);
    builder.add("-classpath", classpath);
  } else {
    builder.add("-classpath", "''");
  }

  return builder.build();
}
 
Example 19
Source File: StringSortedSetAttribute.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public void validateCoercedValue(ImmutableSortedSet<String> values) throws CoerceFailedException {
  if (!getAllowEmpty() && values.isEmpty()) {
    throw new CoerceFailedException("List of strings may not be empty");
  }
}
 
Example 20
Source File: SearchServlet.java    From stash-codesearch-plugin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private ImmutableMap<String, Object> searchHitToDataMap(
    SearchHit hit,
    Map<String, Repository> repoMap, // null iff no permission validation required
    int maxPreviewLines,
    int maxMatchLines,
    ImmutableSet<String> noHighlight) {
    ImmutableMap.Builder<String, Object> hitData = new ImmutableMap.Builder<String, Object>();
    Map<String, Object> hitSource = hit.getSource();

    String type = hit.getType();
    hitData.put("type", type);

    String project = getStringFromMap(hitSource, "project");
    hitData.put("project", project);

    String repository = getStringFromMap(hitSource, "repository");
    hitData.put("repository", repository);

    // Validate permissions & build hit data map
    String repoId = project + "^" + repository;
    Repository repoObject;
    if (repoMap == null) { // current user is system administrator
        repoObject = repositoryServiceManager.getRepositoryService().getBySlug(
            project, repository);
    } else { // must validate against allowed repositories for non-administrators
        repoObject = repoMap.get(repoId);
    }

    if (repoObject != null &&
        repoObject.getProject().getKey().equals(project) &&
        repoObject.getSlug().equals(repository)) {

        // Generate refs array
        ImmutableSortedSet<String> refSet;
        try {
            refSet = ImmutableSortedSet.copyOf((Iterable<String>) hitSource.get("refs"));
        } catch (Exception e) {
            log.warn("Invalid refs collection detected for element in {}/{}", project, repository, e);
            return null;
        }
        if (refSet.isEmpty()) {
            log.warn("Detected empty refs collection for element in {}/{}", project, repository);
            return null;
        }
        hitData.put("refs", refSet);

        // Human-readable labels
        hitData
            .put("projectname", repoObject.getProject().getName())
            .put("repositoryname", repoObject.getName());

        if (type.equals("commit")) {
            hitData
                .put("hash", getStringFromMap(hitSource, "hash"))
                .put("subject", getStringFromMap(hitSource, "subject"))
                .put("body", getStringFromMap(hitSource, "body"))
                .put("commitDate", getDateStringFromMap(hitSource, "commitdate"))
                .put("authorName", getStringFromMap(hitSource, "authorname"))
                .put("authorEmail", getStringFromMap(hitSource, "authoremail"));

        } else if (type.equals("file")) {
            HighlightField highlightField = hit.getHighlightFields().get("contents");
            String path = getStringFromMap(hitSource, "path");
            String primaryRef = "refs/heads/master";
            if (!refSet.contains(primaryRef)) {
                primaryRef = refSet.iterator().next();
            }
            String contents = getStringFromMap(hitSource, "contents");
            SourceSearch searchedContents = SourceSearch.search(
                contents, highlightField, 1, maxPreviewLines, maxMatchLines);
            String extension = getStringFromMap(hitSource, "extension");

            hitData
                .put("path", path)
                .put("blob", getStringFromMap(hitSource, "blob"))
                .put("primaryRef", primaryRef)
                .put("sourceLines", searchedContents.getJoinedLines())
                .put("sourceLineNums", searchedContents.getJoinedLineNums())
                .put("isPreview", searchedContents.isPreview())
                .put("shownLines", searchedContents.getLines().length)
                .put("excessLines", searchedContents.getExcess())
                .put("extension", extension)
                .put("noHighlight", noHighlight.contains(extension));
        }
    } else {
        return null;
    }

    return hitData.build();
}