Java Code Examples for com.google.common.collect.ImmutableMap#values()

The following examples show how to use com.google.common.collect.ImmutableMap#values() . 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: RestGetFieldMappingAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to find out if the only included fieldmapping metadata is typed NULL, which means
 * that type and index exist, but the field did not
 */
private boolean isFieldMappingMissingField(ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex) throws IOException {
    if (mappingsByIndex.size() != 1) {
        return false;
    }

    for (ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>> value : mappingsByIndex.values()) {
        for (ImmutableMap<String, FieldMappingMetaData> fieldValue : value.values()) {
            for (Map.Entry<String, FieldMappingMetaData> fieldMappingMetaDataEntry : fieldValue.entrySet()) {
                if (fieldMappingMetaDataEntry.getValue().isNull()) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 2
Source File: TaskManagerCommandScopeTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void commandScopeCloseDoesNotBlockForAsyncMode() {
  TestBackgroundTaskManager testBackgroundTaskManager = TestBackgroundTaskManager.of();
  TaskManagerCommandScope scope =
      new TaskManagerCommandScope(testBackgroundTaskManager, new BuildId(), false);

  Semaphore blocker = new Semaphore(0);

  BackgroundTask<?> task1 =
      BackgroundTask.of("test1", ignored -> blocker.acquire(), new Object());
  BackgroundTask<?> task2 =
      BackgroundTask.of("test2", ignored -> blocker.acquire(), new Object());
  scope.schedule(task1);
  scope.schedule(task2);

  ImmutableMap<BackgroundTask<?>, Future<Unit>> scheduledTasks = scope.getScheduledTasksResults();

  assertTrue(scheduledTasks.containsKey(task1));
  assertTrue(scheduledTasks.containsKey(task2));

  scope.close();

  for (Future<Unit> f : scheduledTasks.values()) {
    assertFalse(f.isDone());
  }
}
 
Example 3
Source File: Main.java    From turbine with Apache License 2.0 6 votes vote down vote up
/** Writes source files generated by annotation processors. */
private static void writeSources(
    TurbineOptions options, ImmutableMap<String, SourceFile> generatedSources)
    throws IOException {
  if (!options.gensrcOutput().isPresent()) {
    return;
  }
  Path path = Paths.get(options.gensrcOutput().get());
  try (OutputStream os = Files.newOutputStream(path);
      BufferedOutputStream bos = new BufferedOutputStream(os, BUFFER_SIZE);
      JarOutputStream jos = new JarOutputStream(bos)) {
    for (SourceFile source : generatedSources.values()) {
      addEntry(jos, source.path(), source.source().getBytes(UTF_8));
    }
    writeManifest(jos, manifest());
  }
}
 
Example 4
Source File: ArtifactsDiff.java    From intellij with Apache License 2.0 6 votes vote down vote up
public static ArtifactsDiff diffArtifacts(
    @Nullable ImmutableMap<String, ArtifactState> oldState,
    ImmutableMap<String, OutputArtifact> newArtifacts)
    throws InterruptedException, ExecutionException {
  ImmutableMap<String, ArtifactState> newState = computeState(newArtifacts.values());
  // Find new/updated
  final ImmutableMap<String, ArtifactState> previous =
      oldState != null ? oldState : ImmutableMap.of();
  ImmutableList<OutputArtifact> updated =
      newState.entrySet().stream()
          .filter(
              e -> {
                ArtifactState old = previous.get(e.getKey());
                return old == null || old.isMoreRecent(e.getValue());
              })
          .map(e -> newArtifacts.get(e.getKey()))
          .collect(toImmutableList());

  // Find removed
  Set<ArtifactState> removed = new HashSet<>(previous.values());
  newState.forEach((k, v) -> removed.remove(v));

  return new AutoValue_ArtifactsDiff(newState, updated, ImmutableSet.copyOf(removed));
}
 
Example 5
Source File: HeaderRootTrimmer.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static Set<ExecutionRootPath> collectExecutionRootPaths(
    TargetMap targetMap,
    Predicate<TargetIdeInfo> targetFilter,
    ImmutableMap<TargetKey, CToolchainIdeInfo> toolchainLookupMap) {
  Set<ExecutionRootPath> paths = Sets.newHashSet();
  for (TargetIdeInfo target : targetMap.targets()) {
    if (target.getcIdeInfo() != null && targetFilter.test(target)) {
      paths.addAll(target.getcIdeInfo().getTransitiveSystemIncludeDirectories());
      paths.addAll(target.getcIdeInfo().getTransitiveIncludeDirectories());
      paths.addAll(target.getcIdeInfo().getTransitiveQuoteIncludeDirectories());
    }
  }
  Set<CToolchainIdeInfo> toolchains = new LinkedHashSet<>(toolchainLookupMap.values());
  for (CToolchainIdeInfo toolchain : toolchains) {
    paths.addAll(toolchain.getBuiltInIncludeDirectories());
  }
  return paths;
}
 
Example 6
Source File: TaskManagerCommandScopeTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void commandScopeCloseBlocksUntilTasksCompleteForBlockingMode() {
  TestBackgroundTaskManager testBackgroundTaskManager = TestBackgroundTaskManager.of();
  TaskManagerCommandScope scope =
      new TaskManagerCommandScope(testBackgroundTaskManager, new BuildId(), true);
  BackgroundTask<?> task1 = BackgroundTask.of("test1", ignored -> {}, new Object());
  BackgroundTask<?> task2 = BackgroundTask.of("test2", ignored -> {}, new Object());
  scope.schedule(task1);
  scope.schedule(task2);

  ImmutableMap<BackgroundTask<?>, Future<Unit>> scheduledTasks = scope.getScheduledTasksResults();

  assertTrue(scheduledTasks.containsKey(task1));
  assertTrue(scheduledTasks.containsKey(task2));

  scope.close();

  for (Future<Unit> f : scheduledTasks.values()) {
    assertTrue(f.isDone());
  }
}
 
Example 7
Source File: ArtifactRootTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void derivedSerialization() throws IOException, SerializationException {
  Path execRoot = scratch.dir("/thisisaveryverylongexecrootthatwedontwanttoserialize");
  ArtifactRoot derivedRoot = ArtifactRoot.asDerivedRoot(execRoot, "first", "second", "third");
  ObjectCodecRegistry registry = AutoRegistry.get();
  ImmutableMap<Class<?>, Object> dependencies =
      ImmutableMap.<Class<?>, Object>builder()
          .put(FileSystem.class, scratch.getFileSystem())
          .put(
              Root.RootCodecDependencies.class,
              new Root.RootCodecDependencies(/*likelyPopularRoot=*/ Root.fromPath(execRoot)))
          .build();
  ObjectCodecRegistry.Builder registryBuilder = registry.getBuilder();
  for (Object val : dependencies.values()) {
    registryBuilder.addReferenceConstant(val);
  }
  ObjectCodecs objectCodecs = new ObjectCodecs(registryBuilder.build(), dependencies);
  ByteString serialized = objectCodecs.serialize(derivedRoot);
  // 30 bytes as of 2020/04/27.
  assertThat(serialized.size()).isLessThan(31);
}
 
Example 8
Source File: GraphAnalyses.java    From tac-kbp-eal with MIT License 5 votes vote down vote up
static void renderClusteredBarChart(final ImmutableMap<String, List<Double>> scores, final File outFile,
    final GnuPlotRenderer renderer,
    final String chartTitle, final String xAxisLabel, final String yAxisLabel,
    final ImmutableList<String> clusterNames, final Palette palette)
    throws IOException {

  final ImmutableSet.Builder<Double> scoreSetBuilder = ImmutableSet.builder();
  for(final List<Double> scoreList : scores.values()) {
    scoreSetBuilder.addAll(scoreList);
  }
  final int maxCount = (int)Math.ceil(Ordering.natural().max(scoreSetBuilder.build()));

  final Axis X_AXIS = Axis.xAxis().setLabel(xAxisLabel).rotateLabels().build();
  final Axis Y_AXIS = Axis.yAxis().setLabel(yAxisLabel).setRange(
      Range.closed(0.0, (double) roundUpNearestFactor(maxCount))).build();

  final ClusteredBarChart.Builder chartBuilder = ClusteredBarChart.builder()
      .setTitle(chartTitle)
      .setXAxis(X_AXIS).setYAxis(Y_AXIS)
      .setBoxWidth(0.9)
      .withPalette(palette);

  for(int i=0; i<clusterNames.size(); i++) {
    chartBuilder.addBarCluster(clusterNames.get(i));
  }

  for(final Map.Entry<String, List<Double>> entry : scores.entrySet()) {
    final String systemName = entry.getKey();
    final List<Double> systemScores = entry.getValue();

    chartBuilder.addClusteredBar(ClusteredBarChart.ClusteredBar.create(systemName, systemScores));
  }

  renderer.renderTo(chartBuilder.build(), outFile);
}
 
Example 9
Source File: AbstractAsynchronousCache.java    From buck with Apache License 2.0 5 votes vote down vote up
private void doMultiCheck(ImmutableMap<RuleKey, ClaimedFetchRequest> ruleKeyToRequest) {
  try {
    ImmutableMap<RuleKey, CacheResult> ruleKeyToResult =
        multiContainsImpl(ruleKeyToRequest.keySet()).getCacheResults();
    for (Map.Entry<RuleKey, CacheResult> result : ruleKeyToResult.entrySet()) {
      CacheResult cacheResult = result.getValue();
      ClaimedFetchRequest claimedFetchRequest = ruleKeyToRequest.get(result.getKey());
      if (claimedFetchRequest == null) {
        LOG.verbose("Recived cache result for not requested rule key.");
        continue;
      }
      if (!cacheResult.getType().isSuccess()) {
        // If rule key is not present in the cache, there is no point in trying to download
        // it.
        claimedFetchRequest.setResult(cacheResult);
      } else {
        // Otherwise reschedule it. It will be added to the fetch queue and it will be picked
        // by fetching thread.
        claimedFetchRequest.reschedule();
      }
    }
  } catch (IOException e) {
    String msg =
        String.format(
            "multicheck(<%s>): %s: %s",
            Joiner.on(", ").join(ruleKeyToRequest.keySet()),
            e.getClass().getName(),
            e.getMessage());
    // Some of these might already be fulfilled. That's fine, this set() call will just be
    // ignored.
    for (ClaimedFetchRequest request : ruleKeyToRequest.values()) {
      request.setResult(CacheResult.error(name, mode, msg));
    }
  }
}
 
Example 10
Source File: StarlarkTransition.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static BuildOptions unalias(
    BuildOptions options, ImmutableMap<Label, Label> aliasToActual) {
  if (aliasToActual.isEmpty()) {
    return options;
  }
  Collection<Label> aliases = aliasToActual.keySet();
  Collection<Label> actuals = aliasToActual.values();
  BuildOptions.Builder toReturn = options.toBuilder();
  for (Map.Entry<Label, Object> entry : options.getStarlarkOptions().entrySet()) {
    Label setting = entry.getKey();
    if (actuals.contains(setting)) {
      // if entry is keyed by an actual (e.g. <entry2> in javadoc), don't care about its value
      // it's stale
      continue;
    } else if (aliases.contains(setting)) {
      // if an entry is keyed by an alias (e.g. <entry1> in javadoc), newly key (overwrite) its
      // actual to its alias' value and remove the alias-keyed entry
      toReturn.addStarlarkOption(
          aliasToActual.get(setting), options.getStarlarkOptions().get(setting));
      toReturn.removeStarlarkOption(setting);
    } else {
      // else - just copy over
      toReturn.addStarlarkOption(entry.getKey(), entry.getValue());
    }
  }
  return toReturn.build();
}
 
Example 11
Source File: TestUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static <T> T roundTrip(T value, ImmutableMap<Class<?>, Object> dependencies)
    throws IOException, SerializationException {
  ObjectCodecRegistry.Builder builder = AutoRegistry.get().getBuilder();
  for (Object constant : dependencies.values()) {
    builder.addReferenceConstant(constant);
  }
  ObjectCodecRegistry registry = builder.build();
  return new DeserializationContext(registry, dependencies)
      .deserialize(
          toBytes(new SerializationContext(registry, dependencies), value).newCodedInput());
}
 
Example 12
Source File: SchematicPlacement.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void updateEnclosingBox()
{
    ImmutableMap<String, SelectionBox> boxes = this.getSubRegionBoxes(RequiredEnabled.ANY);
    BlockPos pos1 = null;
    BlockPos pos2 = null;

    for (SelectionBox box : boxes.values())
    {
        BlockPos tmp;
        tmp = fi.dy.masa.malilib.util.PositionUtils.getMinCorner(box.getPos1(), box.getPos2());

        if (pos1 == null)
        {
            pos1 = tmp;
        }
        else if (tmp.getX() < pos1.getX() || tmp.getY() < pos1.getY() || tmp.getZ() < pos1.getZ())
        {
            pos1 = fi.dy.masa.malilib.util.PositionUtils.getMinCorner(tmp, pos1);
        }

        tmp = fi.dy.masa.malilib.util.PositionUtils.getMaxCorner(box.getPos1(), box.getPos2());

        if (pos2 == null)
        {
            pos2 = tmp;
        }
        else if (tmp.getX() > pos2.getX() || tmp.getY() > pos2.getY() || tmp.getZ() > pos2.getZ())
        {
            pos2 = fi.dy.masa.malilib.util.PositionUtils.getMaxCorner(tmp, pos2);
        }
    }

    if (pos1 != null && pos2 != null)
    {
        this.enclosingBox = new Box(pos1, pos2);
        this.gridSettings.setDefaultSize(PositionUtils.getAreaSizeFromRelativeEndPosition(pos2.subtract(pos1)));
    }
}
 
Example 13
Source File: AsyncVersionedTargetGraphBuilder.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableSet<VersionInfoKey> discoverPreliminaryDeps(VersionInfoKey node) {
  TargetNode<?> targetNode = node.getTargetNode();
  Optional<TargetNode<VersionedAliasDescriptionArg>> versionedNode =
      TargetGraphVersionTransformations.getVersionedNode(targetNode);

  Iterable<BuildTarget> versionedDeps;
  if (versionedNode.isPresent()) {
    ImmutableMap<Version, BuildTarget> versions =
        versionedNode.get().getConstructorArg().getVersions();

    // Merge in the versioned deps and the version domain.

    // For each version choice, inherit the transitive constraints by wrapping them in an
    // implication dependent on the specific version that pulls them in.
    versionedDeps = versions.values();

  } else {
    Iterable<BuildTarget> deps =
        TargetGraphVersionTransformations.getDeps(typeCoercerFactory, targetNode);
    versionedDeps =
        Iterables.filter(
            deps,
            dep -> {
              TargetNode<?> depNode = targetGraph.get(dep);
              return TargetGraphVersionTransformations.isVersionPropagator(depNode)
                  || TargetGraphVersionTransformations.getVersionedNode(depNode).isPresent();
            });
  }
  return ImmutableSet.copyOf(
      Iterables.transform(
          versionedDeps,
          buildTarget -> ImmutableVersionInfoKey.of(targetGraph.get(buildTarget))));
}
 
Example 14
Source File: MergedTargetGraph.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Group notes by {@link UnflavoredBuildTarget}. */
public static MergedTargetGraph merge(DirectedAcyclicGraph<TargetNode<?>> targetGraph) {
  ImmutableMap<UnflavoredBuildTarget, MergedTargetNode> index =
      MergedTargetNode.group(targetGraph.getNodes());

  MutableDirectedGraph<MergedTargetNode> graph = new MutableDirectedGraph<>();

  for (MergedTargetNode node : index.values()) {
    graph.addNode(node);
  }

  for (Map.Entry<TargetNode<?>, TargetNode<?>> edge : targetGraph.getOutgoingEdges().entries()) {
    TargetNode<?> source = edge.getKey();
    TargetNode<?> sink = edge.getValue();
    MergedTargetNode mergedSource =
        Preconditions.checkNotNull(
            index.get(source.getBuildTarget().getUnflavoredBuildTarget()),
            "node must exist in index: %s",
            source.getBuildTarget().getUnflavoredBuildTarget());
    MergedTargetNode mergedSink =
        Preconditions.checkNotNull(
            index.get(sink.getBuildTarget().getUnflavoredBuildTarget()),
            "node must exist in index: %s",
            sink.getBuildTarget().getUnflavoredBuildTarget());
    graph.addEdge(mergedSource, mergedSink);
  }

  return new MergedTargetGraph(graph, index);
}
 
Example 15
Source File: AutoAnnotationProcessor.java    From auto with Apache License 2.0 4 votes vote down vote up
private void processMethod(ExecutableElement method) {
  if (!method.getModifiers().contains(Modifier.STATIC)) {
    throw abortWithError(method, "@AutoAnnotation method must be static");
  }

  TypeElement annotationElement = getAnnotationReturnType(method);

  Set<Class<?>> wrapperTypesUsedInCollections = wrapperTypesUsedInCollections(method);

  ImmutableMap<String, ExecutableElement> memberMethods = getMemberMethods(annotationElement);
  TypeElement methodClass = (TypeElement) method.getEnclosingElement();
  String pkg = TypeSimplifier.packageNameOf(methodClass);

  ImmutableMap<String, AnnotationValue> defaultValues = getDefaultValues(annotationElement);
  ImmutableMap<String, Member> members = getMembers(method, memberMethods);
  ImmutableMap<String, Parameter> parameters = getParameters(annotationElement, method, members);
  validateParameters(annotationElement, method, members, parameters, defaultValues);

  String generatedClassName = generatedClassName(method);

  AutoAnnotationTemplateVars vars = new AutoAnnotationTemplateVars();
  vars.annotationFullName = annotationElement.toString();
  vars.annotationName = TypeEncoder.encode(annotationElement.asType());
  vars.className = generatedClassName;
  vars.generated = getGeneratedTypeName();
  vars.members = members;
  vars.params = parameters;
  vars.pkg = pkg;
  vars.wrapperTypesUsedInCollections = wrapperTypesUsedInCollections;
  vars.gwtCompatible = isGwtCompatible(annotationElement);
  ImmutableMap<String, Integer> invariableHashes = invariableHashes(members, parameters.keySet());
  vars.invariableHashSum = 0;
  for (int h : invariableHashes.values()) {
    vars.invariableHashSum += h;
  }
  vars.invariableHashes = invariableHashes.keySet();
  String text = vars.toText();
  text = TypeEncoder.decode(text, processingEnv, pkg, annotationElement.asType());
  text = Reformatter.fixup(text);
  String fullName = fullyQualifiedName(pkg, generatedClassName);
  writeSourceFile(fullName, text, methodClass);
}
 
Example 16
Source File: UnconfiguredSelectorListResolver.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
@SuppressWarnings("unchecked")
protected <T> T resolveSelector(
    SelectableConfigurationContext configurationContext,
    BuildTarget buildTarget,
    DependencyStack dependencyStack,
    String attributeName,
    Selector<T> selector) {
  Map<Selectable, Object> matchingConditions =
      findMatchingConditions(configurationContext, selector, dependencyStack);

  Object matchingResult = null;
  assertNotMultipleMatches(matchingConditions, attributeName, buildTarget);
  if (matchingConditions.size() == 1) {
    matchingResult = Iterables.getOnlyElement(matchingConditions.values());
  }

  if (matchingResult == null) {
    assertSelectorHasDefault(buildTarget, dependencyStack, attributeName, selector);
    matchingResult = selector.getDefaultConditionValue();
  }

  if (matchingResult == null) {
    return null;
  }

  ImmutableList.Builder<String> builder = new ImmutableList.Builder<String>();
  if (selector.getDefaultConditionValue() instanceof ImmutableList) {
    ImmutableMap<SelectorKey, ImmutableList<String>> conditions =
        (ImmutableMap<SelectorKey, ImmutableList<String>>) selector.getConditions();

    for (ImmutableList<String> list : conditions.values()) {
      builder.addAll(list);
    }

    return (T) builder.build();
  }

  return (T) matchingResult;
}
 
Example 17
Source File: DesugarRunner.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
  DesugarRule desugarRule =
      Iterables.getOnlyElement(
          getTestClass().getAnnotatedFieldValues(test, Rule.class, DesugarRule.class));

  // Compile source Java files before desugar transformation.
  try {
    desugarRule.compileSourceInputs();
  } catch (IOException | SourceCompilationException e) {
    throw new IllegalStateException(e);
  }

  JdkSuppress jdkSuppress = getJdkSuppress(method);
  if (jdkSuppress != null) {
    ImmutableMap<String, Integer> inputClassFileMajorVersions =
        desugarRule.getInputClassFileMajorVersionMap();
    ImmutableCollection<Integer> classFileVersions = inputClassFileMajorVersions.values();
    if (min(classFileVersions) < jdkSuppress.minJdkVersion()
        || max(classFileVersions) > jdkSuppress.maxJdkVersion()) {
      return new VacuousSuccess(
          String.format(
              "@Test method (%s) passed vacuously without execution: All or part of the input"
                  + " class file versions (%s) does not meet the declared prerequisite version"
                  + " range (%s) for testing.",
              method, inputClassFileMajorVersions, jdkSuppress));
    }
  }

  try {
    desugarRule.executeDesugarTransformation();
    desugarRule.injectTestInstanceFields();
    Method reflectMethod = method.getMethod();

    ImmutableMap.Builder<Parameter, Object> parameterBindingsBuilder = ImmutableMap.builder();
    // Load bindings from annotations.
    if (reflectMethod.isAnnotationPresent(ParameterValueSourceSet.class)
        || reflectMethod.isAnnotationPresent(ParameterValueSource.class)) {
      parameterBindingsBuilder.putAll(
          ((ValueSourceAnnotatedMethod) method).getResolvableParameters());
    }
    // Load bindings from desugar rule.
    parameterBindingsBuilder.putAll(desugarRule.getResolvableParameters(reflectMethod));

    ImmutableMap<Parameter, Object> parameterBindings = parameterBindingsBuilder.build();
    Parameter[] parameters = reflectMethod.getParameters();
    int parameterCount = parameters.length;
    Object[] resolvedParameterValues = new Object[parameterCount];
    for (int i = 0; i < parameterCount; i++) {
      resolvedParameterValues[i] = parameterBindings.get(parameters[i]);
    }
    return new InvokeMethodWithParams(method, test, resolvedParameterValues);
  } catch (Throwable throwable) {
    throw new IllegalStateException(throwable);
  }
}
 
Example 18
Source File: AsyncVersionedTargetGraphBuilder.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("PMD")
public TargetGraph build() throws TimeoutException, InterruptedException, VersionException {
  LOG.debug(
      "Starting version target graph transformation (nodes %d)",
      unversionedTargetGraphCreationResult.getTargetGraph().getNodes().size());
  long start = System.currentTimeMillis();

  ImmutableSet<VersionTargetGraphKey> rootKeys =
      RichStream.from(
              unversionedTargetGraphCreationResult
                  .getTargetGraph()
                  .getAll(unversionedTargetGraphCreationResult.getBuildTargets()))
          .map(ImmutableVersionTargetGraphKey::of)
          .collect(ImmutableSet.toImmutableSet());

  ImmutableMap<VersionTargetGraphKey, Future<TargetNode<?>>> results =
      asyncTransformationEngine.computeAll(rootKeys);

  // Wait for actions to complete.
  for (Future<TargetNode<?>> futures : results.values()) {
    try {
      futures.get(timeout, timeUnit);
    } catch (ExecutionException e) {
      Throwable rootCause = Throwables.getRootCause(e);
      Throwables.throwIfInstanceOf(rootCause, VersionException.class);
      Throwables.throwIfInstanceOf(rootCause, TimeoutException.class);
      Throwables.throwIfInstanceOf(rootCause, RuntimeException.class);
      throw new IllegalStateException(
          String.format("Unexpected exception: %s: %s", e.getClass(), e.getMessage()), e);
    }
  }

  asyncTransformationEngine.close();
  versionInfoAsyncTransformationEngine.close();

  long end = System.currentTimeMillis();

  VersionedTargetGraph graph = versionedTargetGraphTransformer.targetGraphBuilder.build();
  LOG.debug(
      "Finished version target graph transformation in %.2f (nodes %d, roots: %d)",
      (end - start) / 1000.0, graph.getSize(), versionedTargetGraphTransformer.roots.get());

  return graph;
}
 
Example 19
Source File: BindingGraphValidator.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
/**
 * Validates that the scope (if any) of this component are compatible with the scopes of the
 * bindings available in this component
 */
void validateComponentScope(final BindingGraph subject,
    final ValidationReport.Builder<BindingGraph> reportBuilder,
    ImmutableMap<BindingKey, ResolvedBindings> resolvedBindings) {
  Optional<Equivalence.Wrapper<AnnotationMirror>> componentScope =
      subject.componentDescriptor().wrappedScope();
  ImmutableSet.Builder<String> incompatiblyScopedMethodsBuilder = ImmutableSet.builder();
  for (ResolvedBindings bindings : resolvedBindings.values()) {
    if (bindings.bindingKey().kind().equals(BindingKey.Kind.CONTRIBUTION)) {
      for (ContributionBinding contributionBinding : bindings.ownedContributionBindings()) {
        if (contributionBinding instanceof ProvisionBinding) {
          ProvisionBinding provisionBinding = (ProvisionBinding) contributionBinding;
          if (provisionBinding.scope().isPresent()
              && !componentScope.equals(provisionBinding.wrappedScope())) {
            // Scoped components cannot reference bindings to @Provides methods or @Inject
            // types decorated by a different scope annotation. Unscoped components cannot
            // reference to scoped @Provides methods or @Inject types decorated by any
            // scope annotation.
            switch (provisionBinding.bindingKind()) {
              case PROVISION:
                ExecutableElement provisionMethod =
                    MoreElements.asExecutable(provisionBinding.bindingElement());
                incompatiblyScopedMethodsBuilder.add(
                    methodSignatureFormatter.format(provisionMethod));
                break;
              case INJECTION:
                incompatiblyScopedMethodsBuilder.add(stripCommonTypePrefixes(
                    provisionBinding.scope().get().toString()) + " class "
                        + provisionBinding.bindingTypeElement().getQualifiedName());
                break;
              default:
                throw new IllegalStateException();
            }
          }
        }
      }
    }
  }
  ImmutableSet<String> incompatiblyScopedMethods = incompatiblyScopedMethodsBuilder.build();
  if (!incompatiblyScopedMethods.isEmpty()) {
    TypeElement componentType = subject.componentDescriptor().componentDefinitionType();
    StringBuilder message = new StringBuilder(componentType.getQualifiedName());
    if (componentScope.isPresent()) {
      message.append(" scoped with ");
      message.append(stripCommonTypePrefixes(ErrorMessages.format(componentScope.get().get())));
      message.append(" may not reference bindings with different scopes:\n");
    } else {
      message.append(" (unscoped) may not reference scoped bindings:\n");
    }
    for (String method : incompatiblyScopedMethods) {
      message.append(ErrorMessages.INDENT).append(method).append("\n");
    }
    reportBuilder.addItem(message.toString(), componentType,
        subject.componentDescriptor().componentAnnotation());
  }
}
 
Example 20
Source File: SysNetworkServiceImpl.java    From paas with Apache License 2.0 4 votes vote down vote up
@Transactional(rollbackFor = CustomException.class)
@Override
public ResultVO syncByContainerId(String containerId) {
    try {
        List<ContainerNetwork> dbList = containerNetworkMapper.selectList(new EntityWrapper<ContainerNetwork>().eq("container_id", containerId));
        boolean[] dbFlag = new boolean[dbList.size()];
        Arrays.fill(dbFlag, false);

        ContainerInfo containerInfo =  dockerClient.inspectContainer(containerId);
        ImmutableMap<String, AttachedNetwork> networkImmutableMap =  containerInfo.networkSettings().networks();

        int addCount = 0, deleteCount = 0;
        if(networkImmutableMap != null && networkImmutableMap.size() > 0) {
            boolean flag = false;
            for(AttachedNetwork attachedNetwork : networkImmutableMap.values()) {
                String networkId = attachedNetwork.networkId();
                if(StringUtils.isNotBlank(networkId)) {
                    // 判断数据库中是否有该条记录
                    for(int i=0; i<dbList.size(); i++) {
                        if(dbFlag[i]) {
                            continue;
                        }
                        if(hasExist(containerId, networkId)) {
                            dbFlag[i] = true;
                            flag = true;
                            break;
                        }
                    }

                    // 保存新纪录
                    if(!flag) {
                        ContainerNetwork containerNetwork = new ContainerNetwork(containerId, networkId);
                        containerNetworkMapper.insert(containerNetwork);
                        addCount++;
                    }
                }
            }

            // 删除失效记录
            for(int i=0; i< dbList.size(); i++) {
                if(!dbFlag[i]) {
                    containerNetworkMapper.deleteById(dbList.get(i).getId());
                    deleteCount++;
                }
            }
        }

        Map<String, Integer> map = new HashMap<>(16);
        map.put("add", addCount);
        map.put("delete", deleteCount);
        return ResultVOUtils.success(map);
    } catch (Exception e) {
        return ResultVOUtils.error(ResultEnum.CONTAINER_NETWORK_SYNC_ERROR);
    }
}