Java Code Examples for

The following examples show how to use These examples are extracted from open source projects. 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 Project: dremio-oss   Author: dremio   File:    License: Apache License 2.0 6 votes vote down vote up
public void close() throws Exception {
  /* BaseTestOperator calls operator.close() twice on each operator it creates */
  if (!closed) {
    try {
        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),
    } finally {
      partitionToLoadSpilledData = null;
      partitionSpillHandler = null;
      fixedBlockVector = null;
      variableBlockVector = null;
      closed = true;
Example #2
Source Project: estatio   Author: estatio   File:    License: Apache License 2.0 6 votes vote down vote up
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 =
    final Optional<PostalAddress> postalAddressIfFound =
            Iterables.tryFind(postalAddresses, PostalAddress.Predicates.equalTo(address1, postalCode, city, country));
    return postalAddressIfFound.orNull();
Example #3
Source Project: brooklyn-library   Author: apache   File:    License: Apache License 2.0 6 votes vote down vote up
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"));

    // 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 #4
Source Project: Microsoft-Cloud-Services-for-Android   Author: microsoft   File:    License: 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(' ').
                            Splitter.on(' ').split(
                                            replaceFrom(displayName, ' ')),
                            new Function<String, String>() {
                                public String apply(String str) {
                                    return Character.toUpperCase(str.charAt(0)) + str.substring(1);
Example #5
Source Project: tac-kbp-eal   Author: BBN-E   File:    License: MIT License 6 votes vote down vote up
protected ImmutableLinkingLine parseResponseSetLine(List<String> parts,
    final Optional<ImmutableMap<String, String>> foreignIDToLocal,
    final Map<String, Response> responsesByUID)
    throws IOException {
  if (parts.size() > 2) {
        "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 #6
Source Project: xtext-xtend   Author: eclipse   File:    License: Eclipse Public License 2.0 6 votes vote down vote up
public void testEnumLiteral_WithStaticImport() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("import static test.Enum1.* ");
    _builder.append("class C { ");
    _builder.append("Enum1 testFoo = RED");
    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 #7
Source Project: bazel   Author: bazelbuild   File:    License: 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.
public void testPythonCcConfigurations() throws Exception {

  // Equivalent cc / Python configurations:

  ConfiguredTargetAndData ccRuleA = getConfiguredTargetAndData("//");
  List<Artifact> middleman1 = getAggregatingMiddleman(ccRuleA, true);
  ConfiguredTargetAndData ccRuleB = getConfiguredTargetAndData("//");
  getAggregatingMiddleman(ccRuleB, true);
      () -> 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 =
          getConfiguredTargetAndData("//foo:c"), "//");

  List<Artifact> middleman2 = getAggregatingMiddleman(pyRuleB, true);
Example #8
Source Project: tracecompass   Author: tracecompass   File:    License: 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 =;
        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 #9
Source Project: centraldogma   Author: line   File:    License: Apache License 2.0 6 votes vote down vote up
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,
                    AuthorConverter.TO_DATA.convert(author), summary,
                    new Comment(detail).setMarkup(MarkupConverter.TO_DATA.convert(markup)),
                    convertToList(changes, ChangeConverter.TO_DATA::convert),
    return future.thenApply(PushResultConverter.TO_MODEL::convert);
Example #10
Source Project: presto   Author: prestosql   File:    License: 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;
                "%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"),
                Joiner.on("\n    ").join(Iterables.limit(unexpectedRows, limit)),
                Joiner.on("\n    ").join(Iterables.limit(missingRows, limit))));
Example #11
Source Project: bazel   Author: bazelbuild   File:    License: 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 #12
Source Project: a-sync-browser   Author: davide-imbriaco   File:    License: 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){
            return Collections.emptyList();
        }else {
            if(rootView instanceof ViewGroup){
                List list=Lists.newArrayList();
                ViewGroup viewGroup=(ViewGroup)rootView;
                for(int i=0;i<viewGroup.getChildCount();i++){
                return list;
                return (Iterable)Collections.singletonList(rootView);
        return Iterables.filter((Iterable)listViews(rootView,null), Predicates.<Object>instanceOf(clazz));
Example #13
Source Project: statecharts   Author: Yakindu   File:    License: 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>() {
			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 #14
Source Project: jackson-datatype-protobuf   Author: HubSpot   File:    License: Apache License 2.0 6 votes vote down vote up
public static ExtensionRegistry getInstance() {
  ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
  Iterable<FieldDescriptor> extensionDescriptors = Iterables.concat(

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

  return extensionRegistry;
Example #15
Source Project: brooklyn-server   Author: apache   File:    License: Apache License 2.0 6 votes vote down vote up
public void testAutoScalerResizesAfterRebind() throws Exception {
    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 #16
Source Project: hadoop-connectors   Author: GoogleCloudDataproc   File:    License: Apache License 2.0 6 votes vote down vote up
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);

  List<GoogleCloudStorageItemInfo> buckets = gcs.listBucketInfo();

  List<GoogleCloudStorageItemInfo> objects2 =
      gcs.listObjectInfo(BUCKET_A, /* objectNamePrefix= */ null, /* delimiter= */ null);

  verify(gcsDelegate, times(2))
      .listObjectInfo(eq(BUCKET_A), eq(null), eq(null), eq(MAX_RESULTS_UNLIMITED));
Example #17
Source Project: brooklyn-server   Author: apache   File:    License: Apache License 2.0 6 votes vote down vote up
public void testInheritsRuntimeParentConfigOfTypeMapWithOneBigVal() throws Exception {
    String yaml = Joiner.on("\n").join(
            "- 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 #18
Source Project: bazel   Author: bazelbuild   File:    License: 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.
private static Map<Artifact, NestedSet<? extends Artifact>> computeTransitivelyUsedModules(
    SkyFunction.Environment env, Collection<Artifact.DerivedArtifact> usedModules)
    throws InterruptedException {
  Map<SkyKey, SkyValue> actionExecutionValues =
          Iterables.transform(usedModules, Artifact.DerivedArtifact::getGeneratingActionKey));
  if (env.valuesMissing()) {
    return null;
  ImmutableMap.Builder<Artifact, NestedSet<? extends Artifact>> transitivelyUsedModules =
  for (Artifact.DerivedArtifact module : usedModules) {
        module.isFileType(CppFileTypes.CPP_MODULE), "Non-module? %s", module);
    ActionExecutionValue value =
            (ActionExecutionValue) actionExecutionValues.get(module.getGeneratingActionKey()),
    transitivelyUsedModules.put(module, value.getDiscoveredModules());
Example #19
Source Project: brooklyn-server   Author: apache   File:    License: Apache License 2.0 6 votes vote down vote up
public void testSshFeedRegisteredInStartIsPersisted() throws Exception {
    LocalhostMachineProvisioningLocation origLoc = origApp.newLocalhostProvisioningLocation();
    SshMachineLocation origMachine = origLoc.obtain();

    TestEntity origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class).impl(MyEntityWithSshFeedImpl.class)

    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 #20
Source Project: dremio-oss   Author: dremio   File:    License: 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(new Function<Materialization, Long>() {
      public Long apply(@Nullable Materialization m) {
        return m != null ? m.getLastRefreshFromPds() : null;

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

  return Optional.of(Ordering.natural().min(dependencies));
Example #21
Source Project: dagger2-sample   Author: yongjhih   File:    License: 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 {
  } catch (Exception e) {
    try {
    } catch (Exception e2) {
      // couldn't delete the file
    throw closer.rethrow(e);
  } finally {
Example #22
Source Project: bazel   Author: bazelbuild   File:    License: 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(); ConfigurationPhaseStartedEvent(configuredTargetProgress));
  EvaluationContext evaluationContext =
              () -> NamedForkJoinPool.newNamedPool("skyframe-evaluator", numThreads))
  EvaluationResult<ActionLookupValue> result =
      buildDriver.evaluate(Iterables.concat(values, aspectKeys), evaluationContext);
  // Get rid of any memory retained by the cache -- all loading is done.
  return result;
Example #23
Source Project: xtext-xtend   Author: eclipse   File:    License: Eclipse Public License 2.0 5 votes vote down vote up
public void testMethodJavaElements() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("class Xtend {");
    _builder.append("def foo() {");
    final XtendMember method = IterableExtensions.<XtendMember>head(IterableExtensions.<XtendClass>head(Iterables.<XtendClass>filter(this._workbenchTestHelper.xtendFile("Xtend.xtend", _builder.toString()).getXtendTypes(), XtendClass.class)).getMembers());
    Iterable<IJavaElement> _javaElements = this._jvmModelFindReferenceHandler.getJavaElements(method);
    final Procedure1<Iterable<IJavaElement>> _function = (Iterable<IJavaElement> it) -> {
      Assert.assertEquals(1, IterableExtensions.size(it));
      final Function1<IJavaElement, Boolean> _function_1 = (IJavaElement it_1) -> {
        return Boolean.valueOf(((it_1 instanceof IMethod) && Objects.equal(((IMethod) it_1).getElementName(), "foo")));
      Assert.assertTrue(IterableExtensions.<IJavaElement>exists(it, _function_1));
    ObjectExtensions.<Iterable<IJavaElement>>operator_doubleArrow(_javaElements, _function);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
Example #24
Source Project: the-hallow   Author: fabric-community   File:    License: MIT License 5 votes vote down vote up
public void getCombinedInventory(InfusionAltarBlockEntity altarEntity) {
	List<ItemStack> input = new ArrayList<ItemStack>();
	altarEntity.linkedPillars.forEach((pos, entity) -> {
		if (!entity.storedStack.isEmpty()) {
	combinedInventory = new InfusionInventory(altarEntity.storedStack, Iterables.toArray(input, ItemStack.class));
Example #25
Source Project: n4js   Author: eclipse   File:    License: Eclipse Public License 1.0 5 votes vote down vote up
private void checkUnpairedAccessorFilling(MemberMatrix mm, N4ClassifierDefinition definition) {
	if (definition.getDefinedType().isStaticPolyfill() && mm.hasMixedAccessorPair()) {
		FieldAccessor ownedAccessor = (FieldAccessor) Iterables.getFirst(mm.owned(), null);

		if (null == ownedAccessor) {
			// Should not happen, a mixed accessor pair implies at least one owned member
		if (!(definition instanceof N4ClassDefinition)) {
			// Non-class static polyfills aren't allowed. Validated somewhere else.

		TClass filledClass = MemberRedefinitionUtils.getFilledClass((N4ClassDefinition) definition);
		if (null == filledClass) {
			// Invalid static polyfill class. Validated somewhere else.

		// Iterate over all inherited members
		SourceAwareIterator memberIterator = mm.actuallyInheritedAndMixedMembers();
		while (memberIterator.hasNext()) {
			TMember next =;
			ContainerType<?> containingType = next.getContainingType();

			// Issue an error if the member isn't owned by the filled class
			if (containingType != filledClass) {
Example #26
Source Project: wisdom   Author: wisdom-framework   File:    License: Apache License 2.0 5 votes vote down vote up
public void testBody() throws IOException, ParseException {
    File file = new File("src/test/java/controller/");
    final CompilationUnit declaration = JavaParser.parse(file);
    ControllerModel model = new ControllerModel();
    visitor.visit(declaration, model);

    ControllerRouteModel route = getModelByPath(model, "/params/4");
    final RouteParamModel o = (RouteParamModel) Iterables.get(route.getParams(), 0);
    assertThat(o.getName()).isEqualTo("body"); // Special value.
Example #27
Source Project: bazel   Author: bazelbuild   File:    License: Apache License 2.0 5 votes vote down vote up
public SkyValue compute(SkyKey skyKey, Environment env)
    throws SkyFunctionException, InterruptedException {
  CollectTargetsInPackageValue.CollectTargetsInPackageKey argument =
      (CollectTargetsInPackageValue.CollectTargetsInPackageKey) skyKey.argument();
  PackageIdentifier packageId = argument.getPackageId();
  PackageValue packageValue = (PackageValue) env.getValue(PackageValue.key(packageId));
  if (env.valuesMissing()) {
    return null;
  Package pkg = packageValue.getPackage();
  if (pkg.containsErrors()) {
                "package contains errors: " + packageId.getPackageFragment().getPathString()));
          TargetPatternResolverUtil.resolvePackageTargets(pkg, argument.getFilteringPolicy()),
  if (env.valuesMissing()) {
    return null;
  return CollectTargetsInPackageValue.INSTANCE;
Example #28
Source Project: beam-client-java   Author: mixer   File:    License: MIT License 5 votes vote down vote up
public String asString() {
    Joiner j = Joiner.on("");
    Iterable<MessageTextComponent> components = Collections2.filter(this.message.message, Predicates.notNull());

    return j.join(Iterables.transform(components, new Function<MessageTextComponent, String>() {
        @Override public String apply(MessageTextComponent component) {
            switch (component.type) {
                case EMOTICON: return component.text;
                case LINK: return component.url;
                case TEXT: default: return;
Example #29
Source Project: xsemantics   Author: eclipse   File:    License: Eclipse Public License 1.0 5 votes vote down vote up
protected Result<List<Field>> applyRuleFields(final RuleEnvironment G, final RuleApplicationTrace _trace_, final cl) throws RuleFailedException {
  List<Field> fields = null; // output parameter
  final List<> superclasses = this.superclassesInternal(_trace_, cl);
  fields = CollectionLiterals.<Field>newArrayList();
  for (final superclass : superclasses) {
    List<Field> _typeSelect = EcoreUtil2.<Field>typeSelect(
    Iterables.<Field>addAll(fields, _typeSelect);
  /* fields += EcoreUtil2::typeSelect( cl.members, typeof(Field) ) or true */
    RuleFailedException previousFailure = null;
    try {
      List<Field> _typeSelect_1 = EcoreUtil2.<Field>typeSelect(
      boolean _add = Iterables.<Field>addAll(fields, _typeSelect_1);
      /* fields += EcoreUtil2::typeSelect( cl.members, typeof(Field) ) */
      if (!_add) {
        sneakyThrowRuleFailedException("fields += EcoreUtil2::typeSelect( cl.members, typeof(Field) )");
    } catch (Exception e) {
      previousFailure = extractRuleFailedException(e);
      /* true */
  return new Result<List<Field>>(fields);
Example #30
Source Project: xtext-core   Author: eclipse   File:    License: Eclipse Public License 2.0 5 votes vote down vote up
protected List<GeneratedMetamodel> getInheritedGeneratedMetamodels(ReferencedMetamodel metamodel) {
	List<GeneratedMetamodel> allGeneratedMetamodels = new ArrayList<GeneratedMetamodel>();
	Grammar grammar = GrammarUtil.getGrammar(metamodel);
	Set<Grammar> visited = Sets.newHashSet();
	for (Grammar usedGrammar : grammar.getUsedGrammars())
		Iterables.addAll(allGeneratedMetamodels, getAllGeneratedMetamodels(usedGrammar, visited));
	if (allGeneratedMetamodels.isEmpty())
		return Collections.emptyList();
	return allGeneratedMetamodels;