List of usage examples for com.google.common.collect ImmutableList stream
default Stream<E> stream()
From source file:com.spectralogic.dsbrowser.gui.components.localfiletreetable.LocalFileTreeTablePresenter.java
private TreeItem<Ds3TreeTableValue> getRemoteDestination() { final ImmutableList<TreeItem<Ds3TreeTableValue>> currentRemoteSelection = ds3Common.getDs3TreeTableView() .getSelectionModel().getSelectedItems().stream().collect(GuavaCollectors.immutableList()); //Finding root in case of double click to get selected items if (Guard.isNullOrEmpty(currentRemoteSelection)) { //If no destination selected, attempt to use current remote root final TreeItem<Ds3TreeTableValue> root = ds3Common.getDs3TreeTableView().getRoot(); if (root != null && root.getValue() != null) { LOG.info("No remote selection, using remote root"); return root; } else {/*from ww w.j a va 2 s. co m*/ return null; } } else if (currentRemoteSelection.size() > 1) { alert.error("multipleDestError"); return null; } return currentRemoteSelection.stream().findFirst().orElse(null); }
From source file:com.spotify.missinglink.maven.CheckMojo.java
private Collection<Conflict> loadArtifactsAndCheckConflicts() { // includes declared and transitive dependencies, anything in the scopes configured to be // included/* w ww. jav a2s.co m*/ final List<org.apache.maven.artifact.Artifact> projectDeps = this.project.getArtifacts().stream() .filter(artifact -> includeScopes.contains(Scope.valueOf(artifact.getScope()))) .collect(Collectors.toList()); getLog().debug("project dependencies: " + projectDeps.stream().map(this::mavenCoordinates).collect(Collectors.toList())); Stopwatch stopwatch = Stopwatch.createStarted(); // artifacts in runtime scope from the maven project (including transitives) final ImmutableList<Artifact> runtimeProjectArtifacts = constructArtifacts(projectDeps); stopwatch.stop(); getLog().debug("constructing runtime artifacts took: " + asMillis(stopwatch) + " ms"); // also need to load JDK classes from the bootstrap classpath final String bootstrapClasspath = bootClassPathToUse(); stopwatch.reset().start(); final List<Artifact> bootstrapArtifacts = constructArtifacts( Arrays.<String>asList(bootstrapClasspath.split(System.getProperty("path.separator")))); stopwatch.stop(); getLog().debug("constructing bootstrap artifacts took: " + asMillis(stopwatch) + " ms"); final ImmutableList<Artifact> allArtifacts = ImmutableList.<Artifact>builder() .addAll(runtimeProjectArtifacts).addAll(bootstrapArtifacts).build(); final ImmutableList<Artifact> runtimeArtifactsAfterExclusions = ImmutableList.copyOf(runtimeProjectArtifacts .stream().filter(artifact -> !isExcluded(artifact)).collect(Collectors.toSet())); final Artifact projectArtifact = toArtifact(project.getBuild().getOutputDirectory()); if (projectArtifact.classes().isEmpty()) { getLog().warn("No classes found in project build directory" + " - did you run 'mvn compile' first?"); } stopwatch.reset().start(); getLog().debug("Checking for conflicts starting from " + projectArtifact.name().name()); getLog().debug("Artifacts included in the project: "); for (Artifact artifact : runtimeArtifactsAfterExclusions) { getLog().debug(" " + artifact.name().name()); } final Collection<Conflict> conflicts = conflictChecker.check(projectArtifact, runtimeArtifactsAfterExclusions, allArtifacts); stopwatch.stop(); getLog().debug("conflict checking took: " + asMillis(stopwatch) + " ms"); getLog().debug(conflicts.size() + " total conflicts found"); return conflicts; }
From source file:com.google.gerrit.server.update.ReviewDbBatchUpdate.java
static void execute(ImmutableList<ReviewDbBatchUpdate> updates, BatchUpdateListener listener, @Nullable RequestId requestId, boolean dryrun) throws UpdateException, RestApiException { if (updates.isEmpty()) { return;//from www. ja v a 2s . co m } setRequestIds(updates, requestId); try { Order order = getOrder(updates, listener); boolean updateChangesInParallel = getUpdateChangesInParallel(updates); switch (order) { case REPO_BEFORE_DB: for (ReviewDbBatchUpdate u : updates) { u.executeUpdateRepo(); } listener.afterUpdateRepos(); for (ReviewDbBatchUpdate u : updates) { u.executeRefUpdates(dryrun); } listener.afterUpdateRefs(); for (ReviewDbBatchUpdate u : updates) { u.reindexChanges(u.executeChangeOps(updateChangesInParallel, dryrun)); } listener.afterUpdateChanges(); break; case DB_BEFORE_REPO: for (ReviewDbBatchUpdate u : updates) { u.reindexChanges(u.executeChangeOps(updateChangesInParallel, dryrun)); } for (ReviewDbBatchUpdate u : updates) { u.executeUpdateRepo(); } for (ReviewDbBatchUpdate u : updates) { u.executeRefUpdates(dryrun); } break; default: throw new IllegalStateException("invalid execution order: " + order); } ChangeIndexer.allAsList(updates.stream().flatMap(u -> u.indexFutures.stream()).collect(toList())).get(); // Fire ref update events only after all mutations are finished, since callers may assume a // patch set ref being created means the change was created, or a branch advancing meaning // some changes were closed. updates.stream().filter(u -> u.batchRefUpdate != null) .forEach(u -> u.gitRefUpdated.fire(u.project, u.batchRefUpdate, u.getAccount().orElse(null))); if (!dryrun) { for (ReviewDbBatchUpdate u : updates) { u.executePostOps(); } } } catch (Exception e) { wrapAndThrowException(e); } }
From source file:com.google.devtools.build.android.desugar.CoreLibrarySupport.java
public void makeDispatchHelpers(GeneratedClassStore store) { HashMap<Class<?>, ClassVisitor> dispatchHelpers = new HashMap<>(); for (Collection<EmulatedMethod> group : emulatedDefaultMethods.asMap().values()) { checkState(!group.isEmpty());/*from w ww . j a va 2 s . co m*/ Class<?> root = group.stream().map(EmulatedMethod::owner) .max(DefaultMethodClassFixer.SubtypeComparator.INSTANCE).get(); checkState(group.stream().map(m -> m.owner()).allMatch(o -> root.isAssignableFrom(o)), "Not a single unique method: %s", group); String methodName = group.stream().findAny().get().name(); ImmutableList<Class<?>> customOverrides = findCustomOverrides(root, methodName); for (EmulatedMethod methodDefinition : group) { Class<?> owner = methodDefinition.owner(); ClassVisitor dispatchHelper = dispatchHelpers.computeIfAbsent(owner, clazz -> { String className = clazz.getName().replace('.', '/') + "$$Dispatch"; ClassVisitor result = store.add(className); result.visit(Opcodes.V1_7, // Must be public so dispatch methods can be called from anywhere Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC, className, /*signature=*/ null, "java/lang/Object", EMPTY_LIST); return result; }); // Types to check for before calling methodDefinition's companion, sub- before super-types ImmutableList<Class<?>> typechecks = concat(group.stream().map(EmulatedMethod::owner), customOverrides.stream()).filter(o -> o != owner && owner.isAssignableFrom(o)).distinct() // should already be but just in case .sorted(DefaultMethodClassFixer.SubtypeComparator.INSTANCE) .collect(ImmutableList.toImmutableList()); makeDispatchHelperMethod(dispatchHelper, methodDefinition, typechecks); } } }
From source file:com.facebook.buck.tools.consistency.RuleKeyFileParser.java
/** * Parse a thrift compact serialized file * * @param filename The name of the file/* ww w . j av a 2 s.c o m*/ * @param targetNames The name of the targets that should be found * @return A {@link ParsedRuleKeyFile} object that all deserialized rules, and the rule key hash * of the specified target * @throws ParseException If an IO or serialization error occurs, or if the target could not be * found in the file */ public ParsedRuleKeyFile parseFile(Path filename, ImmutableSet<String> targetNames) throws ParseException { // If //foo/bar/... is passed in, we want to find all targets that start with // //foo/bar, and that are of the right type, and add them as root nodes ImmutableList<String> recursiveTargetPrefixes = targetNames.stream() .filter(name -> name.endsWith("/...") || name.endsWith(":")).map(name -> { int idx = name.lastIndexOf("/..."); if (idx != -1) { return name.substring(0, idx); } else { return name; } }).collect(ImmutableList.toImmutableList()); long startNanos = System.nanoTime(); int initialSize; try { initialSize = Math.toIntExact(filename.toFile().length() / THRIFT_STRUCT_SIZE); } catch (ArithmeticException e) { throw new ParseException(e, filename, "File size is too large (>2.1 billion objects would be deserialized"); } ImmutableMap.Builder<String, RuleKeyNode> rootNodesBuilder = ImmutableMap.builder(); Map<String, RuleKeyNode> rules = new HashMap<>(); try { reader.readFile(filename, ruleKey -> { RuleKeyNode newNode = new RuleKeyNode(ruleKey); if ("DEFAULT".equals(ruleKey.type)) { // If either a specific rule is present, or if the target starts with one of the // prefixes if (targetNames.contains(ruleKey.name) || recursiveTargetPrefixes.stream() .filter(prefix -> ruleKey.name.startsWith(prefix)).findFirst().isPresent()) { rootNodesBuilder.put(ruleKey.name, newNode); } } RuleKeyNode oldValue = rules.put(ruleKey.key, newNode); if (oldValue != null && !oldValue.ruleKey.equals(newNode.ruleKey)) { throw new RuntimeException(new ParseException(filename, "Found two rules with the same key, but different values. Key: %s, first value: " + "%s, second value: %s", ruleKey.key, oldValue.ruleKey, newNode.ruleKey)); } return false; }); } catch (RuntimeException e) { if (e.getCause() instanceof ParseException) { throw (ParseException) e.getCause(); } } ImmutableMap<String, RuleKeyNode> rootNodes = rootNodesBuilder.build(); for (String targetName : targetNames) { if (!targetName.endsWith("/...") && !targetName.endsWith(":") && !rootNodes.containsKey(targetName)) { throw new ParseException(filename, "Could not find %s in %s", targetName, filename); } } Duration runtime = Duration.ofNanos(System.nanoTime() - startNanos); return new ParsedRuleKeyFile(filename, rootNodes, rules, runtime); }
From source file:com.spectralogic.dsbrowser.gui.components.ds3panel.Ds3PanelPresenter.java
@SuppressWarnings("unchecked") private void initListeners() { ds3DeleteButton.setOnAction(SafeHandler.logHandle(event -> ds3DeleteObject())); ds3Refresh.setOnAction(SafeHandler.logHandle(event -> RefreshCompleteViewWorker .refreshCompleteTreeTableView(ds3Common, workers, dateTimeUtils, loggingService))); ds3ParentDir.setOnAction(SafeHandler.logHandle(event -> goToParentDirectory())); ds3NewFolder.setOnAction(SafeHandler .logHandle(event -> CreateService.createFolderPrompt(ds3Common, loggingService, resourceBundle))); ds3TransferLeft.setOnAction(SafeHandler.logHandle(event -> { try {//from www. ja v a 2s .c om ds3TransferToLocal(); } catch (final IOException e) { LOG.error("Could not transfer to Local FIleSystem", e); } })); ds3NewBucket.setOnAction(SafeHandler.logHandle(event -> { LOG.debug("Attempting to create bucket..."); CreateService.createBucketPrompt(ds3Common, workers, loggingService, dateTimeUtils, resourceBundle); })); ds3SessionStore.getObservableList().addListener((ListChangeListener<Session>) c -> { if (c.next() && c.wasAdded()) { final List<? extends Session> newItems = c.getAddedSubList(); newItems.forEach(newSession -> { createTabAndSetBehaviour(newSession); loggingService.logMessage(resourceBundle.getString("starting") + StringConstants.SPACE + newSession.getSessionName() + StringConstants.SESSION_SEPARATOR + newSession.getEndpoint() + StringConstants.SPACE + resourceBundle.getString("session"), LogType.SUCCESS); }); } }); ds3SessionTabPane.getSelectionModel().selectedItemProperty().addListener((ov, oldTab, newTab) -> { try { if (newTab.getContent() instanceof VBox) { final VBox vbox = (VBox) newTab.getContent(); final Optional<Node> first = vbox.getChildren().stream().filter(i -> i instanceof TreeTableView) .findFirst(); if (first.isPresent()) { final TreeTableView<Ds3TreeTableValue> ds3TreeTableView = (TreeTableView<Ds3TreeTableValue>) first .get(); final ImmutableList<TreeItem<Ds3TreeTableValue>> values = ds3TreeTableView .getSelectionModel().getSelectedItems().stream() .collect(GuavaCollectors.immutableList()); ds3Common.setDs3TreeTableView(ds3TreeTableView); ds3Common.setCurrentTabPane(ds3SessionTabPane); final String info = StringBuilderUtil .getPaneItemsString(ds3TreeTableView.getExpandedItemCount(), ds3TreeTableView.getSelectionModel().getSelectedItems().size()) .toString(); if (Guard.isNullOrEmpty(values)) { setBlank(true); } else { setBlank(false); final Optional<TreeItem<Ds3TreeTableValue>> ds3TreeTableValueTreeItemElement = values .stream().findFirst(); if (ds3TreeTableValueTreeItemElement.isPresent()) { calculateFiles(ds3TreeTableView); } } getPaneItemsLabel().setVisible(true); getPaneItemsLabel().setText(info); } else { LOG.info("TreeTableView is null"); } } else { ds3Common.setCurrentSession(null); setBlank(true); disableSearch(true); } } catch (final Throwable t) { LOG.error("Not able to parse:", t); } }); ds3SessionTabPane.getTabs().addListener((ListChangeListener<Tab>) c -> { if (c.next() && c.wasRemoved()) { if (ds3SessionTabPane.getTabs().size() == 1) { disableMenu(true); } ds3Common.getDs3PanelPresenter().getInfoLabel().setVisible(false); } else if (c.wasAdded()) { disableMenu(false); } }); deepStorageBrowserPresenter.getJobProgressView().setGraphicFactory(task -> { final ImageView imageView = new ImageView(); imageView.setImage(new Image(ImageURLs.SETTINGS_ICON)); final Button button = new Button(); button.setGraphic(imageView); button.setTooltip(new Tooltip(resourceBundle.getString("viewOrModifyJobPriority"))); button.setOnAction(event -> modifyJobPriority(task)); return button; }); }
From source file:com.facebook.buck.core.build.engine.impl.CachingBuildRuleBuilder.java
private void finalizeBuiltLocally(AtomicReference<Long> outputSize) throws IOException, StepFailedException, InterruptedException { BuildRuleSuccessType success = BuildRuleSuccessType.BUILT_LOCALLY; // Try get the output size now that all outputs have been recorded. outputSize.set(getBuildInfoRecorder().getOutputSize()); getBuildInfoRecorder().addMetadata(BuildInfo.MetadataKey.OUTPUT_SIZE, outputSize.get().toString()); if (rule instanceof HasPostBuildSteps) { executePostBuildSteps(((HasPostBuildSteps) rule).getPostBuildSteps(buildRuleBuildContext)); }/*from w w w. j a v a 2 s . c o m*/ // Invalidate any cached hashes for the output paths, since we've updated them. for (Path path : getBuildInfoRecorder().getRecordedPaths()) { fileHashCache.invalidate(rule.getProjectFilesystem().resolve(path)); } // Doing this here is probably not strictly necessary, however in the case of // pipelined rules built locally we will never do an input-based cache check. // That check would have written the key to metadata, and there are some asserts // during cache upload that try to ensure they are present. if (SupportsInputBasedRuleKey.isSupported(rule) && !getBuildInfoRecorder() .getBuildMetadataFor(BuildInfo.MetadataKey.INPUT_BASED_RULE_KEY).isPresent() && inputBasedKey.get().isPresent()) { getBuildInfoRecorder().addBuildMetadata(BuildInfo.MetadataKey.INPUT_BASED_RULE_KEY, inputBasedKey.get().get().toString()); } // If this rule uses dep files, make sure we store the new dep file // list and re-calculate the dep file rule key. if (dependencyFileRuleKeyManager.useDependencyFileRuleKey()) { // Query the rule for the actual inputs it used. ImmutableList<SourcePath> inputs = ((SupportsDependencyFileRuleKey) rule) .getInputsAfterBuildingLocally(buildRuleBuildContext, executionContext.getCellPathResolver()); // Record the inputs into our metadata for next time. // TODO(#9117006): We don't support a way to serlialize `SourcePath`s to the cache, // so need to use DependencyFileEntry's instead and recover them on deserialization. ImmutableList<String> inputStrings = inputs.stream() .map(inputString -> DependencyFileEntry.fromSourcePath(inputString, pathResolver)) .map(ObjectMappers.toJsonFunction()).collect(ImmutableList.toImmutableList()); getBuildInfoRecorder().addMetadata(BuildInfo.MetadataKey.DEP_FILE, inputStrings); // Re-calculate and store the depfile rule key for next time. Optional<RuleKeyAndInputs> depFileRuleKeyAndInputs = dependencyFileRuleKeyManager .calculateDepFileRuleKey(Optional.of(inputStrings), /* allowMissingInputs */ false); if (depFileRuleKeyAndInputs.isPresent()) { RuleKey depFileRuleKey = depFileRuleKeyAndInputs.get().getRuleKey(); getBuildInfoRecorder().addBuildMetadata(BuildInfo.MetadataKey.DEP_FILE_RULE_KEY, depFileRuleKey.toString()); // Push an updated manifest to the cache. if (manifestRuleKeyManager.useManifestCaching()) { // TODO(cjhopman): This should be able to use manifestKeySupplier. try (Scope ignored = LeafEvents.scope(eventBus, "updating_and_storing_manifest")) { Optional<RuleKeyAndInputs> manifestKey = calculateManifestKey(eventBus); if (manifestKey.isPresent()) { getBuildInfoRecorder().addBuildMetadata(BuildInfo.MetadataKey.MANIFEST_KEY, manifestKey.get().getRuleKey().toString()); long buildTimeMs = buildTimestampsMillis == null ? -1 : buildTimestampsMillis.getSecond() - buildTimestampsMillis.getFirst(); ManifestStoreResult manifestStoreResult = manifestRuleKeyManager.updateAndStoreManifest( depFileRuleKeyAndInputs.get().getRuleKey(), depFileRuleKeyAndInputs.get().getInputs(), manifestKey.get(), buildTimeMs); this.buildRuleScopeManager.setManifestStoreResult(manifestStoreResult); if (manifestStoreResult.getStoreFuture().isPresent()) { uploadCompleteFuture = manifestStoreResult.getStoreFuture().get(); } } } } } } // Make sure the origin field is filled in. getBuildInfoRecorder().addBuildMetadata(BuildInfo.MetadataKey.ORIGIN_BUILD_ID, buildId.toString()); // Make sure that all of the local files have the same values they would as if the // rule had been built locally. getBuildInfoRecorder().addBuildMetadata(BuildInfo.MetadataKey.TARGET, rule.getBuildTarget().toString()); getBuildInfoRecorder().addBuildMetadata(BuildInfo.MetadataKey.CONFIGURATION, targetConfigurationSerializer.serialize(rule.getBuildTarget().getTargetConfiguration())); getBuildInfoRecorder().addMetadata(BuildInfo.MetadataKey.RECORDED_PATHS, getBuildInfoRecorder() .getRecordedPaths().stream().map(Object::toString).collect(ImmutableList.toImmutableList())); if (success.shouldWriteRecordedMetadataToDiskAfterBuilding()) { try { boolean clearExistingMetadata = success.shouldClearAndOverwriteMetadataOnDisk(); getBuildInfoRecorder().writeMetadataToDisk(clearExistingMetadata); } catch (IOException e) { throw new IOException(String.format("Failed to write metadata to disk for %s.", rule), e); } } if (shouldWriteOutputHashes(outputSize.get())) { try (Scope ignored = LeafEvents.scope(eventBus, "computing_output_hashes")) { onDiskBuildInfo.writeOutputHashes(fileHashCache); } } }
From source file:com.facebook.buck.distributed.RemoteExecutionStorageService.java
@Override public ImmutableList<UploadResult> batchUpdateBlobs(final ImmutableList<UploadData> blobs) { RemoteExecutionStoreRequest request = new RemoteExecutionStoreRequest(); final AtomicLong totalPayloadsSizeBytes = new AtomicLong(0); List<ThrowingSupplier<InputStream, IOException>> payloads = Lists.newArrayList(); for (UploadData item : blobs) { com.facebook.buck.distributed.thrift.Digest digest = convertDigest(item.digest); new com.facebook.buck.distributed.thrift.Digest(); totalPayloadsSizeBytes.addAndGet(item.digest.getSize()); DigestAndContent digestAndContent = new DigestAndContent(); digestAndContent.setDigest(digest); request.addToDigests(digestAndContent); payloads.add(item.data);/* w w w . ja va2 s . c o m*/ } FrontendRequest frontendRequest = new FrontendRequest().setType(FrontendRequestType.REMOTE_EXECUTION_STORE) .setRemoteExecutionStoreRequest(request); HybridThriftRequestHandler<FrontendRequest> hybridRequest = new HybridThriftRequestHandler<FrontendRequest>( frontendRequest) { @Override public long getTotalPayloadsSizeBytes() { return totalPayloadsSizeBytes.get(); } @Override public int getNumberOfPayloads() { return blobs.size(); } @Override public InputStream getPayloadStream(int index) throws IOException { return blobs.get(index).data.get(); } }; service.makeRequest(hybridRequest, HybridThriftResponseHandler.createNoPayloadHandler( new FrontendResponse(), RemoteExecutionStorageService::validateResponseOrThrow)); return blobs.stream().map(item -> new UploadResult(item.digest, 0, "")) .collect(ImmutableList.toImmutableList()); }
From source file:com.google.api.codegen.transformer.csharp.CSharpGapicSnippetsTransformer.java
private List<StaticLangApiMethodSnippetView> generateMethods(InterfaceContext context) { List<StaticLangApiMethodSnippetView> methods = new ArrayList<>(); for (MethodModel method : csharpCommonTransformer.getSupportedMethods(context)) { MethodConfig methodConfig = context.getMethodConfig(method); MethodContext methodContext = context.asRequestMethodContext(method); if (methodConfig.isGrpcStreaming()) { methods.add(generateGrpcStreamingRequestMethod(methodContext)); } else if (methodConfig.isLongRunningOperation()) { if (methodConfig.isFlattening()) { ImmutableList<FlatteningConfig> flatteningGroups = methodConfig.getFlatteningConfigs(); boolean requiresNameSuffix = flatteningGroups.size() > 1; for (int i = 0; i < flatteningGroups.size(); i++) { FlatteningConfig flatteningGroup = flatteningGroups.get(i); String nameSuffix = requiresNameSuffix ? Integer.toString(i + 1) : ""; MethodContext methodContextFlat = context.asFlattenedMethodContext(method, flatteningGroup); methods.add(generateOperationFlattenedAsyncMethod(methodContextFlat, nameSuffix)); methods.add(generateOperationFlattenedMethod(methodContextFlat, nameSuffix)); }/* w ww. jav a 2 s .c o m*/ } methods.add(generateOperationRequestAsyncMethod(methodContext)); methods.add(generateOperationRequestMethod(methodContext)); } else if (methodConfig.isPageStreaming()) { if (methodConfig.isFlattening()) { ImmutableList<FlatteningConfig> flatteningGroups = methodConfig.getFlatteningConfigs(); // Find flattenings that have ambiguous parameters, and mark them to use named arguments. // Ambiguity occurs in a page-stream flattening that has one or two extra string // parameters (that are not resource-names) compared to any other flattening of this same // method. // Create a string for each flattening, encoding which parameters are strings and // not-strings. Each character in the string refers to a parameter. Each string refers // to a flattening. String[] stringParams = flatteningGroups.stream().map(flat -> flat.getFlattenedFieldConfigs() .values().stream() .map(field -> field.getField().getType().isStringType() && field.getResourceNameConfig() == null ? 's' : '.') .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString()).toArray(String[]::new); // Array of which flattenings need to use named arguments. // Each array entry refers to the correspondingly indexed flattening. Boolean[] requiresNamedParameters = Arrays.stream(stringParams) .map(a -> Arrays.stream(stringParams) .anyMatch(b -> a.startsWith(b + "s") || a.startsWith(b + "ss"))) .toArray(Boolean[]::new); boolean requiresNameSuffix = flatteningGroups.size() > 1; // Build method list. for (int i = 0; i < flatteningGroups.size(); i++) { FlatteningConfig flatteningGroup = flatteningGroups.get(i); String nameSuffix = requiresNameSuffix ? Integer.toString(i + 1) : ""; MethodContext methodContextFlat = context.asFlattenedMethodContext(method, flatteningGroup); methods.add(generatePagedFlattenedAsyncMethod(methodContextFlat, nameSuffix, requiresNamedParameters[i])); methods.add(generatePagedFlattenedMethod(methodContextFlat, nameSuffix, requiresNamedParameters[i])); } } methods.add(generatePagedRequestAsyncMethod(methodContext)); methods.add(generatePagedRequestMethod(methodContext)); } else { if (methodConfig.isFlattening()) { ImmutableList<FlatteningConfig> flatteningGroups = methodConfig.getFlatteningConfigs(); boolean requiresNameSuffix = flatteningGroups.size() > 1; for (int i = 0; i < flatteningGroups.size(); i++) { FlatteningConfig flatteningGroup = flatteningGroups.get(i); String nameSuffix = requiresNameSuffix ? Integer.toString(i + 1) : ""; MethodContext methodContextFlat = context.asFlattenedMethodContext(method, flatteningGroup); methods.add(generateFlattenedAsyncMethod(methodContextFlat, nameSuffix)); methods.add(generateFlattenedMethod(methodContextFlat, nameSuffix)); } } methods.add(generateRequestAsyncMethod(methodContext)); methods.add(generateRequestMethod(methodContext)); } } return methods; }
From source file:com.spectralogic.dsbrowser.gui.components.ds3panel.Ds3PanelPresenter.java
private void ds3TransferToLocal() throws IOException { final Session session = getSession(); if ((session == null) || (ds3Common == null)) { alert.error("invalidSession"); return;/*ww w . java2s . co m*/ } // Verify valid remote TreeTableView final TreeTableView<Ds3TreeTableValue> ds3TreeTableView = getTreeTableView(); if (ds3TreeTableView == null) { LOG.info("Files not selected"); alert.info(FILE_SELECT); return; } // Verify remote files to GET selected if ((ds3TreeTableView.getSelectionModel() == null) || (ds3TreeTableView.getSelectionModel().getSelectedItems() == null)) { LOG.info("Files not selected"); alert.info(FILE_SELECT); return; } final ImmutableList<Ds3TreeTableValue> selectedItemsAtSourceLocationList = ds3TreeTableView .getSelectionModel().getSelectedItems().stream().map(TreeItem::getValue) .collect(GuavaCollectors.immutableList()); // Verify local destination selected final TreeTableView<FileTreeModel> localTreeTableView = ds3Common.getLocalTreeTableView(); if (localTreeTableView == null) { return; } final Label localFilePathIndicator = ds3Common.getLocalFilePathIndicator(); final String fileRootItem = localFilePathIndicator.getText(); final ObservableList<TreeItem<FileTreeModel>> selectedItemsAtDestination = localTreeTableView .getSelectionModel().getSelectedItems(); if (fileRootItem.equals(resourceBundle.getString("myComputer"))) { if (Guard.isNullOrEmpty(selectedItemsAtDestination)) { LOG.info("Location not selected"); alert.error("sourceFileSelectError"); return; } } if (selectedItemsAtDestination.size() > 1) { alert.error("multipleDestError"); return; } final ImmutableList<FileTreeModel> selectedItemsAtDestinationList = selectedItemsAtDestination.stream() .map(TreeItem::getValue).collect(GuavaCollectors.immutableList()); //Getting selected item at source location final ImmutableList<Ds3TreeTableValueCustom> selectedItemsAtSourceLocationListCustom = selectedItemsAtSourceLocationList .stream() .map(v -> new Ds3TreeTableValueCustom(v.getBucketName(), v.getFullName(), v.getType(), v.getSize(), v.getLastModified(), v.getOwner(), v.isSearchOn())) .collect(GuavaCollectors.immutableList()); final Path localPath; //Getting selected item at destination location final Optional<FileTreeModel> first = selectedItemsAtDestinationList.stream().findFirst(); if (!first.isPresent()) { localPath = Paths.get(fileRootItem); } else { final FileTreeModel selectedAtDest = first.get(); if (selectedAtDest.getType().equals(FileTreeModel.Type.File)) { localPath = selectedAtDest.getPath().getParent(); } else { localPath = selectedAtDest.getPath(); } } startGetJob(selectedItemsAtSourceLocationListCustom, localPath, selectedItemsAtDestination); }