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: VectorizedHashAggOperator.java From dremio-oss with Apache License 2.0 | 6 votes |
@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 #2
Source File: PostalAddressRepository.java From estatio with Apache License 2.0 | 6 votes |
@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 #3
Source File: DynamicWebAppClusterImpl.java From brooklyn-library with Apache License 2.0 | 6 votes |
@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 #4
Source File: Office365ManagerImpl.java From Microsoft-Cloud-Services-for-Android with MIT License | 6 votes |
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 #5
Source File: KBPSpec2016LinkingLoader.java From tac-kbp-eal with MIT License | 6 votes |
@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 #6
Source File: ConstantExpressionsInterpreterTest.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
@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 #7
Source File: CompilationHelperTest.java From bazel with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: SegmentStoreScatterDataProvider.java From tracecompass with Eclipse Public License 2.0 | 6 votes |
/** * 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 #9
Source File: LegacyCentralDogma.java From centraldogma with Apache License 2.0 | 6 votes |
@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 #10
Source File: QueryAssertions.java From presto with Apache License 2.0 | 6 votes |
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 #11
Source File: ErrorInfo.java From bazel with Apache License 2.0 | 6 votes |
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 File: ViewUtils.java From a-sync-browser with Mozilla Public License 2.0 | 6 votes |
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 #13
Source File: DomainRegistry.java From statecharts with Eclipse Public License 1.0 | 6 votes |
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 #14
Source File: TestExtensionRegistry.java From jackson-datatype-protobuf with Apache License 2.0 | 6 votes |
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 #15
Source File: AutoScalerPolicyRebindTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@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 #16
Source File: PerformanceCachingGoogleCloudStorageTest.java From hadoop-connectors with Apache License 2.0 | 6 votes |
@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 #17
Source File: ConfigInheritanceYamlTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@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 #18
Source File: CppCompileAction.java From bazel with Apache License 2.0 | 6 votes |
/** * 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 #19
Source File: RebindFeedTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@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 #20
Source File: DependencyManager.java From dremio-oss with Apache License 2.0 | 6 votes |
/** * 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 #21
Source File: JavaWriter.java From dagger2-sample with Apache License 2.0 | 6 votes |
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 #22
Source File: SkyframeExecutor.java From bazel with Apache License 2.0 | 6 votes |
/** 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 #23
Source File: JdtFindReferencesTest.java From xtext-xtend with Eclipse Public License 2.0 | 5 votes |
@Test public void testMethodJavaElements() { try { StringConcatenation _builder = new StringConcatenation(); _builder.append("class Xtend {"); _builder.newLine(); _builder.append("\t"); _builder.append("def foo() {"); _builder.newLine(); _builder.append("\t"); _builder.append("}"); _builder.newLine(); _builder.append("}"); _builder.newLine(); final XtendMember method = IterableExtensions.<XtendMember>head(IterableExtensions.<XtendClass>head(Iterables.<XtendClass>filter(this._workbenchTestHelper.xtendFile("Xtend.xtend", _builder.toString()).getXtendTypes(), XtendClass.class)).getMembers()); IResourcesSetupUtil.waitForBuild(); 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 File: InfusionAltarBlock.java From the-hallow with MIT License | 5 votes |
public void getCombinedInventory(InfusionAltarBlockEntity altarEntity) { List<ItemStack> input = new ArrayList<ItemStack>(); altarEntity.linkedPillars.forEach((pos, entity) -> { if (!entity.storedStack.isEmpty()) { input.add(entity.storedStack.copy()); } }); combinedInventory = new InfusionInventory(altarEntity.storedStack, Iterables.toArray(input, ItemStack.class)); }
Example #25
Source File: N4JSMemberRedefinitionValidator.java From n4js with Eclipse Public License 1.0 | 5 votes |
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 return; } if (!(definition instanceof N4ClassDefinition)) { // Non-class static polyfills aren't allowed. Validated somewhere else. return; } TClass filledClass = MemberRedefinitionUtils.getFilledClass((N4ClassDefinition) definition); if (null == filledClass) { // Invalid static polyfill class. Validated somewhere else. return; } // Iterate over all inherited members SourceAwareIterator memberIterator = mm.actuallyInheritedAndMixedMembers(); while (memberIterator.hasNext()) { TMember next = memberIterator.next(); ContainerType<?> containingType = next.getContainingType(); // Issue an error if the member isn't owned by the filled class if (containingType != filledClass) { messageMissingOwnedAccessor(ownedAccessor); } } } }
Example #26
Source File: ControllerSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testBody() throws IOException, ParseException { File file = new File("src/test/java/controller/ParameterizedController.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); ControllerRouteModel route = getModelByPath(model, "/params/4"); assertThat(route.getParams()).hasSize(1); final RouteParamModel o = (RouteParamModel) Iterables.get(route.getParams(), 0); assertThat(o.getParamType()).isEqualTo(RouteParamModel.ParamType.BODY); assertThat(o.getName()).isEqualTo("body"); // Special value. assertThat(o.getValueType()).isEqualTo(String.class.getSimpleName()); }
Example #27
Source File: CollectTargetsInPackageFunction.java From bazel with Apache License 2.0 | 5 votes |
@Nullable @Override 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()) { env.getListener() .handle( Event.error( "package contains errors: " + packageId.getPackageFragment().getPathString())); } env.getValues( Iterables.transform( TargetPatternResolverUtil.resolvePackageTargets(pkg, argument.getFilteringPolicy()), TO_TRANSITIVE_TRAVERSAL_KEY)); if (env.valuesMissing()) { return null; } return CollectTargetsInPackageValue.INSTANCE; }
Example #28
Source File: IncomingMessageData.java From beam-client-java with MIT License | 5 votes |
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 component.data; } } })); }
Example #29
Source File: FjFirstTypeSystem.java From xsemantics with Eclipse Public License 1.0 | 5 votes |
protected Result<List<Field>> applyRuleFields(final RuleEnvironment G, final RuleApplicationTrace _trace_, final org.eclipse.xsemantics.example.fj.fj.Class cl) throws RuleFailedException { List<Field> fields = null; // output parameter final List<org.eclipse.xsemantics.example.fj.fj.Class> superclasses = this.superclassesInternal(_trace_, cl); Collections.reverse(superclasses); fields = CollectionLiterals.<Field>newArrayList(); for (final org.eclipse.xsemantics.example.fj.fj.Class superclass : superclasses) { List<Field> _typeSelect = EcoreUtil2.<Field>typeSelect( superclass.getMembers(), Field.class); 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( cl.getMembers(), Field.class); 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 File: XtextValidator.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
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; }