com.google.common.collect.Iterables Java Examples

The following examples show how to use com.google.common.collect.Iterables. 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: ErrorInfo.java    From bazel with Apache License 2.0 6 votes vote down vote up
public ErrorInfo(
    NestedSet<SkyKey> rootCauses,
    @Nullable Exception exception,
    SkyKey rootCauseOfException,
    ImmutableList<CycleInfo> cycles,
    boolean isDirectlyTransient,
    boolean isTransitivelyTransient,
    boolean isCatastrophic) {
  Preconditions.checkState(exception != null || !Iterables.isEmpty(cycles),
      "At least one of exception and cycles must be non-null/empty, respectively");
  Preconditions.checkState((exception == null) == (rootCauseOfException == null),
      "exception and rootCauseOfException must both be null or non-null, got %s  %s",
      exception, rootCauseOfException);

  this.rootCauses = rootCauses;
  this.exception = exception;
  this.rootCauseOfException = rootCauseOfException;
  this.cycles = cycles;
  this.isDirectlyTransient = isDirectlyTransient;
  this.isTransitivelyTransient = isTransitivelyTransient;
  this.isCatastrophic = isCatastrophic;
}
 
Example #2
Source File: VectorizedHashAggOperator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws Exception {
  /* BaseTestOperator calls operator.close() twice on each operator it creates */
  if (!closed) {
    updateStats();
    try {
      AutoCloseables.close(Iterables.concat(
        partitionToLoadSpilledData != null ? Collections.singletonList(partitionToLoadSpilledData) : new ArrayList<>(0),
        partitionSpillHandler != null ? Collections.singletonList(partitionSpillHandler) : new ArrayList<>(0),
        fixedBlockVector != null ? Collections.singletonList(fixedBlockVector) : new ArrayList<>(0),
        variableBlockVector != null ? Collections.singletonList(variableBlockVector) : new ArrayList<>(0),
        hashAggPartitions != null ? Arrays.asList(hashAggPartitions) : new ArrayList<>(0),
        outgoing));
    } finally {
      partitionToLoadSpilledData = null;
      partitionSpillHandler = null;
      fixedBlockVector = null;
      variableBlockVector = null;
      closed = true;
    }
  }
}
 
Example #3
Source File: JavaWriter.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
public void file(Filer filer, CharSequence name,  Iterable<? extends Element> originatingElements)
    throws IOException {
  JavaFileObject sourceFile = filer.createSourceFile(name,
      Iterables.toArray(originatingElements, Element.class));
  Closer closer = Closer.create();
  try {
    write(closer.register(sourceFile.openWriter()));
  } catch (Exception e) {
    try {
      sourceFile.delete();
    } catch (Exception e2) {
      // couldn't delete the file
    }
    throw closer.rethrow(e);
  } finally {
    closer.close();
  }
}
 
Example #4
Source File: ConfigInheritanceYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testInheritsRuntimeParentConfigOfTypeMapWithOneBigVal() throws Exception {
    String yaml = Joiner.on("\n").join(
            "services:",
            "- type: org.apache.brooklyn.entity.stock.BasicApplication",
            "  brooklyn.config:",
            "    test.confMapThing:",
            "      mykey: myval",
            "      mykey2: $brooklyn:config(\"myOtherConf\")",
            "    myOtherConf: myOther",
            "  brooklyn.children:",
            "  - type: org.apache.brooklyn.core.test.entity.TestEntity");

    final Entity app = createStartWaitAndLogApplication(yaml);
    TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
 
    assertEquals(entity.config().get(TestEntity.CONF_MAP_THING), ImmutableMap.of("mykey", "myval", "mykey2", "myOther"));
}
 
Example #5
Source File: PostalAddressRepository.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Programmatic
public PostalAddress findByAddress(
        final CommunicationChannelOwner owner, 
        final String address1, 
        final String postalCode, 
        final String city, 
        final Country country) {

    // TODO: rewrite to use JDK8 streams
    final List<CommunicationChannelOwnerLink> links =
            communicationChannelOwnerLinkRepository.findByOwnerAndCommunicationChannelType(owner, CommunicationChannelType.POSTAL_ADDRESS);
    final Iterable<PostalAddress> postalAddresses =
            Iterables.transform(
                    links,
                    CommunicationChannelOwnerLink.Functions.communicationChannel(PostalAddress.class));
    final Optional<PostalAddress> postalAddressIfFound =
            Iterables.tryFind(postalAddresses, PostalAddress.Predicates.equalTo(address1, postalCode, city, country));
    return postalAddressIfFound.orNull();
}
 
Example #6
Source File: SkyframeExecutor.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Configures a given set of configured targets. */
EvaluationResult<ActionLookupValue> configureTargets(
    ExtendedEventHandler eventHandler,
    List<ConfiguredTargetKey> values,
    List<AspectValueKey> aspectKeys,
    boolean keepGoing,
    int numThreads)
    throws InterruptedException {
  checkActive();

  eventHandler.post(new ConfigurationPhaseStartedEvent(configuredTargetProgress));
  EvaluationContext evaluationContext =
      EvaluationContext.newBuilder()
          .setKeepGoing(keepGoing)
          .setNumThreads(numThreads)
          .setExecutorServiceSupplier(
              () -> NamedForkJoinPool.newNamedPool("skyframe-evaluator", numThreads))
          .setEventHander(eventHandler)
          .build();
  EvaluationResult<ActionLookupValue> result =
      buildDriver.evaluate(Iterables.concat(values, aspectKeys), evaluationContext);
  // Get rid of any memory retained by the cache -- all loading is done.
  perBuildSyscallCache.clear();
  return result;
}
 
Example #7
Source File: DynamicWebAppClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void undeploy(String targetName) {
    checkNotNull(targetName, "targetName");
    targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName);
    
    // set it up so future nodes get the right wars
    if (!removeFromWarsByContext(this, targetName)) {
        DynamicTasks.submit(Tasks.warning("Context "+targetName+" not known at "+this+"; attempting to undeploy regardless", null), this);
    }
    
    log.debug("Undeploying "+targetName+" across cluster "+this+"; WARs now "+getConfig(WARS_BY_CONTEXT));

    Iterable<CanDeployAndUndeploy> targets = Iterables.filter(getChildren(), CanDeployAndUndeploy.class);
    TaskBuilder<Void> tb = Tasks.<Void>builder().parallel(true).displayName("Undeploy "+targetName+" across cluster (size "+Iterables.size(targets)+")");
    for (Entity target: targets) {
        tb.add(whenServiceUp(target, Effectors.invocation(target, UNDEPLOY, MutableMap.of("targetName", targetName)),
            "Undeploy "+targetName+" at "+target+" when ready"));
    }
    DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked();

    // Update attribute
    Set<String> deployedWars = MutableSet.copyOf(getAttribute(DEPLOYED_WARS));
    deployedWars.remove( FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName) );
    sensors().set(DEPLOYED_WARS, deployedWars);
}
 
Example #8
Source File: Office365ManagerImpl.java    From Microsoft-Cloud-Services-for-Android with MIT License 6 votes vote down vote up
private String getPermissionDisplayName(String displayName) {
    // replace '.' and '_' with space characters and title case the display name
    return Joiner.on(' ').
            join(Iterables.transform(
                            Splitter.on(' ').split(
                                    CharMatcher.anyOf("._").
                                            replaceFrom(displayName, ' ')),
                            new Function<String, String>() {
                                @Override
                                public String apply(String str) {
                                    return Character.toUpperCase(str.charAt(0)) + str.substring(1);
                                }
                            }
                    )
            );
}
 
Example #9
Source File: KBPSpec2016LinkingLoader.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
@Override
protected ImmutableLinkingLine parseResponseSetLine(List<String> parts,
    final Optional<ImmutableMap<String, String>> foreignIDToLocal,
    final Map<String, Response> responsesByUID)
    throws IOException {
  if (parts.size() > 2) {
    log.warn(
        "IDs provided using tabs! This is contrary to the guidelines for the 2016 eval and may be changed!");
  }
  if (parts.size() == 2 && parts.get(1).contains(" ")) {
    final List<String> responseIDs = StringUtils.onSpaces().splitToList(parts.get(1));
    parts = ImmutableList.copyOf(Iterables.concat(ImmutableList.of(parts.get(0)), responseIDs));
  }
  if (parts.size() >= 2) {
    return ImmutableLinkingLine.of(ResponseSet.from(parseResponses(parts.subList(1, parts.size()),
        foreignIDToLocal, responsesByUID)), Optional.of(parts.get(0)));
  } else {
    throw new IOException("Line must have at least two fields");
  }
}
 
Example #10
Source File: ConstantExpressionsInterpreterTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testEnumLiteral_WithStaticImport() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("import static test.Enum1.* ");
    _builder.newLine();
    _builder.append("class C { ");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("Enum1 testFoo = RED");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtendFile file = this.file(_builder.toString());
    final XtendField field = IterableExtensions.<XtendField>head(Iterables.<XtendField>filter(IterableExtensions.<XtendTypeDeclaration>head(file.getXtendTypes()).getMembers(), XtendField.class));
    Object _evaluate = this.interpreter.evaluate(field.getInitialValue(), field.getType());
    final JvmEnumerationLiteral blue = ((JvmEnumerationLiteral) _evaluate);
    Assert.assertEquals("RED", blue.getSimpleName());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #11
Source File: PerformanceCachingGoogleCloudStorageTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void testListBucketInfoAndObjectInfo() throws IOException {
  List<GoogleCloudStorageItemInfo> expectedBuckets = ImmutableList.of(ITEM_A, ITEM_B);
  List<GoogleCloudStorageItemInfo> expectedObjectsInBucketA =
      ImmutableList.of(ITEM_A_A, ITEM_A_AA, ITEM_A_ABA, ITEM_A_B);
  Iterable<GoogleCloudStorageItemInfo> expectedAllCachedItems =
      Iterables.concat(expectedBuckets, expectedObjectsInBucketA);

  List<GoogleCloudStorageItemInfo> objects1 =
      gcs.listObjectInfo(BUCKET_A, /* objectNamePrefix= */ null, /* delimiter= */ null);
  assertThat(objects1).containsExactlyElementsIn(expectedObjectsInBucketA);
  assertThat(cache.getAllItemsRaw()).containsExactlyElementsIn(expectedObjectsInBucketA);

  List<GoogleCloudStorageItemInfo> buckets = gcs.listBucketInfo();
  assertThat(buckets).containsExactlyElementsIn(expectedBuckets);
  assertThat(cache.getAllItemsRaw()).containsExactlyElementsIn(expectedAllCachedItems);

  List<GoogleCloudStorageItemInfo> objects2 =
      gcs.listObjectInfo(BUCKET_A, /* objectNamePrefix= */ null, /* delimiter= */ null);
  assertThat(objects2).containsExactlyElementsIn(expectedObjectsInBucketA);
  assertThat(cache.getAllItemsRaw()).containsExactlyElementsIn(expectedAllCachedItems);

  verify(gcsDelegate).listBucketInfo();
  verify(gcsDelegate, times(2))
      .listObjectInfo(eq(BUCKET_A), eq(null), eq(null), eq(MAX_RESULTS_UNLIMITED));
}
 
Example #12
Source File: SegmentStoreScatterDataProvider.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Create an instance of {@link SegmentStoreScatterDataProvider} for a given
 * analysis ID. Returns a null instance if the ISegmentStoreProvider is
 * null. If the provider is an instance of {@link IAnalysisModule}, analysis
 * is also scheduled.
 * <p>
 * If the trace has multiple analysis modules with the same secondary ID,
 * <code>null</code> is returned so the caller can try to make a
 * {@link TmfTreeXYCompositeDataProvider} for all the traces instead
 *
 * @param trace
 *            A trace on which we are interested to fetch a model
 * @param secondaryId
 *            The ID of the analysis to use for this provider
 * @return An instance of SegmentStoreDataProvider. Returns a null if the
 *         ISegmentStoreProvider is null.
 * @since 4.0
 */
public static @Nullable ITmfTreeDataProvider<? extends ITmfTreeDataModel> create(ITmfTrace trace, String secondaryId) {
    // The trace can be an experiment, so we need to know if there are multiple
    // analysis modules with the same ID
    Iterable<ISegmentStoreProvider> modules = TmfTraceUtils.getAnalysisModulesOfClass(trace, ISegmentStoreProvider.class);
    Iterable<ISegmentStoreProvider> filteredModules = Iterables.filter(modules, m -> ((IAnalysisModule) m).getId().equals(secondaryId));
    Iterator<ISegmentStoreProvider> iterator = filteredModules.iterator();
    if (iterator.hasNext()) {
        ISegmentStoreProvider module = iterator.next();
        if (iterator.hasNext()) {
            // More than one module, must be an experiment, return null so the factory can
            // try with individual traces
            return null;
        }
        ((IAnalysisModule) module).schedule();
        return new SegmentStoreScatterDataProvider(trace, module, secondaryId);
    }
    return null;
}
 
Example #13
Source File: AutoScalerPolicyRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoScalerResizesAfterRebind() throws Exception {
    origCluster.start(ImmutableList.of(origLoc));
    origCluster.policies().add(AutoScalerPolicy.builder()
            .name("myname")
            .metric(METRIC_SENSOR)
            .entityWithMetric(origCluster)
            .metricUpperBound(10)
            .metricLowerBound(100)
            .minPoolSize(1)
            .maxPoolSize(3)
            .buildSpec());
    
    TestApplication newApp = rebind();
    DynamicCluster newCluster = (DynamicCluster) Iterables.getOnlyElement(newApp.getChildren());

    assertEquals(newCluster.getCurrentSize(), (Integer)1);
    
    ((EntityInternal)newCluster).sensors().set(METRIC_SENSOR, 1000);
    EntityAsserts.assertGroupSizeEqualsEventually(newCluster, 3);
    
    ((EntityInternal)newCluster).sensors().set(METRIC_SENSOR, 1);
    EntityAsserts.assertGroupSizeEqualsEventually(newCluster, 1);
}
 
Example #14
Source File: QueryAssertions.java    From presto with Apache License 2.0 6 votes vote down vote up
public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected, String message)
{
    assertNotNull(actual, "actual is null");
    assertNotNull(expected, "expected is null");

    ImmutableMultiset<?> actualSet = ImmutableMultiset.copyOf(actual);
    ImmutableMultiset<?> expectedSet = ImmutableMultiset.copyOf(expected);
    if (!actualSet.equals(expectedSet)) {
        Multiset<?> unexpectedRows = Multisets.difference(actualSet, expectedSet);
        Multiset<?> missingRows = Multisets.difference(expectedSet, actualSet);
        int limit = 100;
        fail(format(
                "%snot equal\n" +
                        "Actual rows (up to %s of %s extra rows shown, %s rows in total):\n    %s\n" +
                        "Expected rows (up to %s of %s missing rows shown, %s rows in total):\n    %s\n",
                message == null ? "" : (message + "\n"),
                limit,
                unexpectedRows.size(),
                actualSet.size(),
                Joiner.on("\n    ").join(Iterables.limit(unexpectedRows, limit)),
                limit,
                missingRows.size(),
                expectedSet.size(),
                Joiner.on("\n    ").join(Iterables.limit(missingRows, limit))));
    }
}
 
Example #15
Source File: ViewUtils.java    From a-sync-browser with Mozilla Public License 2.0 6 votes vote down vote up
public static <E extends View> Iterable<E> listViews(View rootView,@Nullable Class<E> clazz){
    if(clazz == null){
        if(rootView==null){
            return Collections.emptyList();
        }else {
            if(rootView instanceof ViewGroup){
                List list=Lists.newArrayList();
                ViewGroup viewGroup=(ViewGroup)rootView;
                list.add(viewGroup);
                for(int i=0;i<viewGroup.getChildCount();i++){
                    list.addAll((Collection)listViews(viewGroup.getChildAt(i),null));
                }
                return list;
            }else{
                return (Iterable)Collections.singletonList(rootView);
            }
        }
    }else{
        return Iterables.filter((Iterable)listViews(rootView,null), Predicates.<Object>instanceOf(clazz));
    }
}
 
Example #16
Source File: DomainRegistry.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean domainExists(final String domainID) {
	try {
		Iterables.find(getDomains(), new Predicate<IDomain>() {
			@Override
			public boolean apply(IDomain input) {
				return input.getDomainID()
						.equals(domainID == null || domainID.isEmpty()
								? BasePackage.Literals.DOMAIN_ELEMENT__DOMAIN_ID.getDefaultValueLiteral()
								: domainID);
			}
		});
	} catch (NoSuchElementException e) {
		return false;
	}
	return true;
}
 
Example #17
Source File: DependencyManager.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Computes a reflection's oldest dependent materialization from the reflections it depends upon.<br>
 * If the reflection only depends on physical datasets, returns Optional.absent()
 */
public Optional<Long> getOldestDependentMaterialization(ReflectionId reflectionId) {
  // retrieve all the reflection entries reflectionId depends on
  final Iterable<Long> dependencies = filterReflectionDependencies(graph.getPredecessors(reflectionId))
    .transform(getLastMaterializationDoneFunc)
    .transform(new Function<Materialization, Long>() {
      @Nullable
      @Override
      public Long apply(@Nullable Materialization m) {
        return m != null ? m.getLastRefreshFromPds() : null;
      }
    })
    .filter(notNull());

  if (Iterables.isEmpty(dependencies)) {
    return Optional.absent();
  }

  return Optional.of(Ordering.natural().min(dependencies));
}
 
Example #18
Source File: RebindFeedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration")
public void testSshFeedRegisteredInStartIsPersisted() throws Exception {
    LocalhostMachineProvisioningLocation origLoc = origApp.newLocalhostProvisioningLocation();
    SshMachineLocation origMachine = origLoc.obtain();

    TestEntity origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class).impl(MyEntityWithSshFeedImpl.class)
            .location(origMachine));
    
    origApp.start(ImmutableList.<Location>of());

    EntityAsserts.assertAttributeEqualsEventually(origEntity, SENSOR_INT, 0);
    assertEquals(origEntity.feeds().getFeeds().size(), 1);

    newApp = rebind();
    TestEntity newEntity = (TestEntity) Iterables.getOnlyElement(newApp.getChildren());
    
    Collection<Feed> newFeeds = newEntity.feeds().getFeeds();
    assertEquals(newFeeds.size(), 1);
    
    // Expect the feed to still be polling
    newEntity.sensors().set(SENSOR_INT, null);
    EntityAsserts.assertAttributeEqualsEventually(newEntity, SENSOR_INT, 0);
}
 
Example #19
Source File: TestExtensionRegistry.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
public static ExtensionRegistry getInstance() {
  ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
  Iterable<FieldDescriptor> extensionDescriptors = Iterables.concat(
      AllExtensions.getDescriptor().getExtensions(),
      RepeatedExtensions.getDescriptor().getExtensions()
  );

  for (FieldDescriptor extension : extensionDescriptors) {
    if (extension.getJavaType() == JavaType.MESSAGE) {
      extensionRegistry.add(extension, Nested.getDefaultInstance());
    } else {
      extensionRegistry.add(extension);
    }
  }

  return extensionRegistry;
}
 
Example #20
Source File: LegacyCentralDogma.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<PushResult> push(String projectName, String repositoryName, Revision baseRevision,
                                          Author author, String summary, String detail, Markup markup,
                                          Iterable<? extends Change<?>> changes) {
    final CompletableFuture<com.linecorp.centraldogma.internal.thrift.Commit> future = run(callback -> {
        validateProjectAndRepositoryName(projectName, repositoryName);
        requireNonNull(baseRevision, "baseRevision");
        requireNonNull(author, "author");
        requireNonNull(summary, "summary");
        requireNonNull(detail, "detail");
        requireNonNull(markup, "markup");
        requireNonNull(changes, "changes");
        checkArgument(!Iterables.isEmpty(changes), "changes is empty.");
        client.push(projectName, repositoryName,
                    RevisionConverter.TO_DATA.convert(baseRevision),
                    AuthorConverter.TO_DATA.convert(author), summary,
                    new Comment(detail).setMarkup(MarkupConverter.TO_DATA.convert(markup)),
                    convertToList(changes, ChangeConverter.TO_DATA::convert),
                    callback);
    });
    return future.thenApply(PushResultConverter.TO_MODEL::convert);
}
 
Example #21
Source File: CppCompileAction.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * For the given {@code usedModules}, looks up modules discovered by their generating actions.
 *
 * <p>The returned value only contains a map from elements of {@code usedModules} to the {@link
 * #discoveredModules} required to use them. If dependent actions have not been executed yet (and
 * thus {@link #discoveredModules} aren't known yet, returns null.
 */
@Nullable
private static Map<Artifact, NestedSet<? extends Artifact>> computeTransitivelyUsedModules(
    SkyFunction.Environment env, Collection<Artifact.DerivedArtifact> usedModules)
    throws InterruptedException {
  Map<SkyKey, SkyValue> actionExecutionValues =
      env.getValues(
          Iterables.transform(usedModules, Artifact.DerivedArtifact::getGeneratingActionKey));
  if (env.valuesMissing()) {
    return null;
  }
  ImmutableMap.Builder<Artifact, NestedSet<? extends Artifact>> transitivelyUsedModules =
      ImmutableMap.builderWithExpectedSize(usedModules.size());
  for (Artifact.DerivedArtifact module : usedModules) {
    Preconditions.checkState(
        module.isFileType(CppFileTypes.CPP_MODULE), "Non-module? %s", module);
    ActionExecutionValue value =
        Preconditions.checkNotNull(
            (ActionExecutionValue) actionExecutionValues.get(module.getGeneratingActionKey()),
            module);
    transitivelyUsedModules.put(module, value.getDiscoveredModules());
  }
  return transitivelyUsedModules.build();
}
 
Example #22
Source File: CompilationHelperTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Regression test: tests that Python CPU configurations are taken into account
 * when generating a rule's aggregating middleman, so that otherwise equivalent rules can sustain
 * distinct middlemen.
 */
@Test
public void testPythonCcConfigurations() throws Exception {
  setupJavaPythonCcConfigurationFiles();

  // Equivalent cc / Python configurations:

  ConfiguredTargetAndData ccRuleA = getConfiguredTargetAndData("//foo:liba.so");
  List<Artifact> middleman1 = getAggregatingMiddleman(ccRuleA, true);
  ConfiguredTargetAndData ccRuleB = getConfiguredTargetAndData("//foo:libb.so");
  getAggregatingMiddleman(ccRuleB, true);
  assertThrows(
      UncheckedActionConflictException.class,
      () -> analysisEnvironment.registerWith(getMutableActionGraph()));

  // This should succeed because the py_binary's middleman is under the Python configuration's
  // internal directory, while the cc_binary's middleman is under the cc config's directory,
  // and both configurations are the same.
  ConfiguredTargetAndData pyRuleB =
      getConfiguredTargetAndDataDirectPrerequisite(
          getConfiguredTargetAndData("//foo:c"), "//foo:libb.so");

  List<Artifact> middleman2 = getAggregatingMiddleman(pyRuleB, true);
  assertThat(Iterables.getOnlyElement(middleman2).getExecPathString())
      .isEqualTo(Iterables.getOnlyElement(middleman1).getExecPathString());
}
 
Example #23
Source File: HttpConfigAspectValidator.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private void checkQueryParameterConstraints(Method method, HttpAttribute binding) {
  checkHttpQueryParameterConstraints(
      method,
      FluentIterable.from(binding.getParamSelectors())
          .transform(
              new Function<FieldSelector, Field>() {
                @Override
                public Field apply(FieldSelector selector) {
                  return Iterables.getLast(selector.getFields());
                }
              }),
      Sets.<MessageType>newHashSet());
}
 
Example #24
Source File: HasBadgesGroovyPostbuildPlugin.java    From jenkins-build-monitor-plugin with MIT License 5 votes vote down vote up
@Override
public Badges asJson() {
    Iterator<GroovyPostbuildAction> badges = Iterables.filter(job.lastBuild().allDetailsOf(GroovyPostbuildAction.class), filter).iterator();

    return badges.hasNext()
        ? new Badges(badges)
        : null; // `null` because we don't want to serialise an empty object
}
 
Example #25
Source File: ObjcLibraryTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testArchiveAction_simulator() throws Exception {
  useConfiguration("--apple_platform_type=ios", "--cpu=ios_i386", "--ios_cpu=i386");
  createLibraryTargetWriter("//objc:lib")
      .setAndCreateFiles("srcs", "a.m", "b.m", "private.h")
      .setAndCreateFiles("hdrs", "c.h")
      .write();

  CommandAction archiveAction = archiveAction("//objc:lib");
  assertThat(archiveAction.getArguments())
      .isEqualTo(
          ImmutableList.of(
              "tools/osx/crosstool/iossim/libtool",
              "-static",
              "-filelist",
              getBinArtifact("lib-archive.objlist", getConfiguredTarget("//objc:lib"))
                  .getExecPathString(),
              "-arch_only",
              "i386",
              "-syslibroot",
              AppleToolchain.sdkDir(),
              "-o",
              Iterables.getOnlyElement(archiveAction.getOutputs()).getExecPathString()));
  assertThat(baseArtifactNames(archiveAction.getInputs()))
      .containsAtLeast("a.o", "b.o", "lib-archive.objlist", CROSSTOOL_LINK_MIDDLEMAN);
  assertThat(baseArtifactNames(archiveAction.getOutputs())).containsExactly("liblib.a");
  assertRequiresDarwin(archiveAction);
}
 
Example #26
Source File: AmazonKinesisSinkTask.java    From kinesis-kafka-connector with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(Throwable t) {
	if (t instanceof UserRecordFailedException) {
		Attempt last = Iterables.getLast(((UserRecordFailedException) t).getResult().getAttempts());
		throw new DataException("Kinesis Producer was not able to publish data - " + last.getErrorCode() + "-"
				+ last.getErrorMessage());

	}
	throw new DataException("Exception during Kinesis put", t);
}
 
Example #27
Source File: SARLValidator.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isInitialized(JvmField input) {
	if (super.isInitialized(input)) {
		return true;
	}
	// Check initialization into a static constructor.
	final XtendField sarlField = (XtendField) this.associations.getPrimarySourceElement(input);
	if (sarlField == null) {
		return false;
	}
	final XtendTypeDeclaration declaringType = sarlField.getDeclaringType();
	if (declaringType == null) {
		return false;
	}
	for (final XtendConstructor staticConstructor : Iterables.filter(Iterables.filter(
			declaringType.getMembers(), XtendConstructor.class), it -> it.isStatic())) {
		if (staticConstructor.getExpression() != null) {
			for (final XAssignment assign : EcoreUtil2.getAllContentsOfType(staticConstructor.getExpression(), XAssignment.class)) {
				if (assign.isStatic() && Strings.equal(input.getIdentifier(), assign.getFeature().getIdentifier())) {
					// Mark the field as initialized in order to be faster during the next initialization test.
					this.readAndWriteTracking.markInitialized(input, null);
					return true;
				}
			}
		}
	}
	return false;
}
 
Example #28
Source File: ResultDescriptor.java    From newts with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the set of unique source names; The names of the underlying samples used as the
 * source of aggregations.
 * 
 * @return source names
 */
public Set<String> getSourceNames() {
    return Sets.newHashSet(Iterables.transform(getDatasources().values(), new Function<Datasource, String>() {

        @Override
        public String apply(Datasource input) {
            return input.getSource();
        }
    }));
}
 
Example #29
Source File: ReferenceExamplesTest.java    From solidity-ide with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void parseReferenceFile() throws Exception {
	String content = new String(Files.readAllBytes(path));
	SolidityModel model = parseHelper.parse(content, URI.createFileURI(path.toAbsolutePath().toString()), set);
	Assert.assertNotNull("Could not load model " + path, model);
	Iterable<Issue> issues = Iterables.filter(validationHelper.validate(model), new Predicate<Issue>() {
		@Override
		public boolean apply(Issue input) {
			return Severity.ERROR == input.getSeverity();
		}
	});
	if (!isEmpty(issues))
		fail("Errors in resource: " + path + ": " + issues);

}
 
Example #30
Source File: RunfilesTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private void checkConflictWarning() {
  assertContainsEvent("overwrote runfile");
  assertWithMessage("ConflictChecker.put should have warned once")
      .that(eventCollector.count())
      .isEqualTo(1);
  assertThat(Iterables.getOnlyElement(eventCollector).getKind()).isEqualTo(EventKind.WARNING);
}