List of usage examples for com.google.common.collect ImmutableSet isEmpty
boolean isEmpty();
From source file:org.apache.aurora.scheduler.state.TaskStateMachine.java
/** * Attempt to transition the state machine to the provided state. * At the time this method returns, any work commands required to satisfy the state transition * will be appended to the work queue./*from www . jav a 2 s. c om*/ * * TODO(maxim): The current StateManager/TaskStateMachine interaction makes it hard to expose * a dedicated task deletion method without leaking out the state machine implementation details. * Consider refactoring here to allow for an unambiguous task deletion without resorting to * Optional.absent(). * * @param status Status to apply to the task or absent if a task deletion is required. * @return {@code true} if the state change was allowed, {@code false} otherwise. */ public synchronized TransitionResult updateState(final Optional<ScheduleStatus> status) { requireNonNull(status); Preconditions.checkState(sideEffects.isEmpty()); /** * Don't bother applying noop state changes. If we end up modifying task state without a * state transition (e.g. storing resource consumption of a running task), we need to find * a different way to suppress noop transitions. */ TaskState taskState = status.transform(STATUS_TO_TASK_STATE).or(DELETED); if (stateMachine.getState() == taskState) { return new TransitionResult(NOOP, ImmutableSet.of()); } boolean success = stateMachine.transition(taskState); ImmutableSet<SideEffect> transitionEffects = ImmutableSet.copyOf(sideEffects); sideEffects.clear(); if (success) { return new TransitionResult(SUCCESS, transitionEffects); } return new TransitionResult(transitionEffects.isEmpty() ? ILLEGAL : ILLEGAL_WITH_SIDE_EFFECTS, transitionEffects); }
From source file:org.springframework.ide.eclipse.boot.dash.views.BootDashLabels.java
public StyledString getStyledText(BootDashElement element, BootDashColumn column) { //The big case below should set either one of 'label' or'styledLabel', depending // on whether it is 'styling capable'. String label = null;/*from w ww.j a v a 2 s . co m*/ StyledString styledLabel = null; if (element != null) { switch (column) { case TAGS: String text = TagUtils.toString(element.getTags()); styledLabel = stylers == null ? new StyledString(text) : TagUtils.applyTagStyles(text, stylers.tag()); break; case PROJECT: IJavaProject jp = element.getJavaProject(); if (jp == null) { // Not all projects in elements are Java projects. CF elements accept any project that contains a valid manifest.yml since the manifest.yml may // point to an executable archive for the app (.jar/.war) IProject project = element.getProject(); if (project != null) { label = project.getName(); } else { // Project and app (element) name are shown in separate columns now. If // there is no project mapping // do not show the element name anymore. That way the user knows that there is // no mapping for that element. label = ""; } } else { styledLabel = getJavaLabels().getStyledText(jp); //TODO: should use 'element.hasDevtools()' but its not implemented // yet on CF elements. boolean devtools = BootPropertyTester.hasDevtools(element.getProject()); if (devtools) { StyledString devtoolsDecoration = new StyledString(" [devtools]", stylers.darkGreen()); styledLabel.append(devtoolsDecoration); } } break; case HOST: String host = element.getLiveHost(); label = host == null ? UNKNOWN_LABEL : host; break; case TREE_VIEWER_MAIN: BootDashColumn[] cols = element.getColumns(); styledLabel = new StyledString(); for (BootDashColumn col : cols) { //Ignore RUN_STATE_ICN because its already represented in the label's icon. if (col != BootDashColumn.RUN_STATE_ICN) { StyledString append = getStyledText(element, col); if (hasText(append)) { Styler styler = getPrefixSuffixStyler(col); if (!hasText(styledLabel)) { // Nothing in the label so far, don't added brackets to first piece styledLabel = styledLabel.append(append); } else { if (col == BootDashColumn.DEFAULT_PATH) { styledLabel = styledLabel.append(" ").append(append); } else { if (styler == null) { styledLabel = styledLabel.append(" [").append(append).append("]"); } else { styledLabel = styledLabel.append(" [", styler).append(append).append("]", styler); } } } } } } break; case NAME: styledLabel = new StyledString(); if (element.getName() != null) { styledLabel.append(element.getName()); } else { styledLabel.append(UNKNOWN_LABEL); } break; case DEVTOOLS: if (element.hasDevtools()) { styledLabel = new StyledString("devtools", stylers.darkGreen()); } else { styledLabel = new StyledString(); } case RUN_STATE_ICN: label = element.getRunState().toString(); break; case LIVE_PORT: RunState runState = element.getRunState(); if (runState == RunState.RUNNING || runState == RunState.DEBUGGING) { String textLabel; ImmutableSet<Integer> ports = element.getLivePorts(); if (ports.isEmpty()) { textLabel = "unknown port"; } else { StringBuilder str = new StringBuilder(); String separator = ""; for (Integer port : ports) { str.append(separator); str.append(":"); str.append(port); separator = " "; } textLabel = str.toString(); } if (stylers == null) { label = textLabel; } else { styledLabel = new StyledString(textLabel, stylers.darkGreen()); } } break; case DEFAULT_PATH: String path = element.getDefaultRequestMappingPath(); if (stylers == null) { label = path == null ? "" : path; } else { styledLabel = new StyledString(path == null ? "" : path, stylers.darkGrey()); } break; case INSTANCES: int actual = element.getActualInstances(); int desired = element.getDesiredInstances(); if (desired != 1 || actual > 1) { //Don't show: less clutter, you can already see whether a single instance is running or not if (stylers == null) { label = actual + "/" + desired; } else { styledLabel = new StyledString(actual + "/" + desired, stylers.darkBlue()); } } break; case EXPOSED_URL: runState = element.getRunState(); if (runState == RunState.RUNNING || runState == RunState.DEBUGGING) { List<String> tunnelNames = new ArrayList<>(); if (element instanceof AbstractLaunchConfigurationsDashElement<?>) { ImmutableSet<ILaunchConfiguration> launches = ((AbstractLaunchConfigurationsDashElement<?>) element) .getLaunchConfigs(); for (ILaunchConfiguration launchConfig : launches) { tunnelNames.add(launchConfig.getName()); } } for (String tunnelName : tunnelNames) { NGROKClient ngrokClient = NGROKLaunchTracker.get(tunnelName); if (ngrokClient != null) { if (styledLabel == null) { styledLabel = new StyledString("\u27A4 " + ngrokClient.getTunnel().getPublic_url(), stylers.darkBlue()); } else { styledLabel.append( new StyledString(" / \u27A4 " + ngrokClient.getTunnel().getPublic_url(), stylers.darkBlue())); } } } } break; default: label = UNKNOWN_LABEL; } } if (styledLabel != null) { return styledLabel; } else if (label != null) { return new StyledString(label); } return new StyledString(""); }
From source file:com.google.devtools.build.lib.remote.GrpcActionCache.java
@Override public ContentDigest uploadBlob(byte[] blob) throws InterruptedException { ContentDigest digest = ContentDigests.computeDigest(blob); ImmutableSet<ContentDigest> missing = getMissingDigests(ImmutableList.of(digest)); try {//from w w w . j a v a 2s . c o m if (!missing.isEmpty()) { uploadChunks(1, new BlobChunkInlineIterator(blob)); } return digest; } catch (IOException e) { // This will never happen. throw new RuntimeException(); } }
From source file:com.facebook.buck.apple.project_generator.XCodeProjectCommandHelper.java
private TargetGraph getProjectGraphForIde(ListeningExecutorService executor, ImmutableSet<BuildTarget> passedInTargets) throws InterruptedException, BuildFileParseException, BuildTargetException, IOException { if (passedInTargets.isEmpty()) { return parser .buildTargetGraphForTargetNodeSpecs(buckEventBus, cell, enableParserProfiling, executor, ImmutableList.of(TargetNodePredicateSpec.of(x -> true, BuildFileSpec.fromRecursivePath(Paths.get(""), cell.getRoot())))) .getTargetGraph();// www. j ava2 s . com } Preconditions.checkState(!passedInTargets.isEmpty()); return parser.buildTargetGraph(buckEventBus, cell, enableParserProfiling, executor, passedInTargets); }
From source file:com.facebook.buck.cli.Main.java
private void loadListenersFromBuckConfig(ImmutableList.Builder<BuckEventListener> eventListeners, ProjectFilesystem projectFilesystem, BuckConfig config) { final ImmutableSet<String> paths = config.getListenerJars(); if (paths.isEmpty()) { return;//from w w w. j a v a 2 s. c o m } URL[] urlsArray = new URL[paths.size()]; try { int i = 0; for (String path : paths) { String urlString = "file://" + projectFilesystem.getAbsolutifier().apply(Paths.get(path)); urlsArray[i] = new URL(urlString); i++; } } catch (MalformedURLException e) { throw new HumanReadableException(e.getMessage()); } // This ClassLoader is disconnected to allow searching the JARs (and just the JARs) for classes. ClassLoader isolatedClassLoader = URLClassLoader.newInstance(urlsArray, null); ImmutableSet<ClassPath.ClassInfo> classInfos; try { ClassPath classPath = ClassPath.from(isolatedClassLoader); classInfos = classPath.getTopLevelClasses(); } catch (IOException e) { throw new HumanReadableException(e.getMessage()); } // This ClassLoader will actually work, because it is joined to the parent ClassLoader. URLClassLoader workingClassLoader = URLClassLoader.newInstance(urlsArray); for (ClassPath.ClassInfo classInfo : classInfos) { String className = classInfo.getName(); try { Class<?> aClass = Class.forName(className, true, workingClassLoader); if (BuckEventListener.class.isAssignableFrom(aClass)) { BuckEventListener listener = aClass.asSubclass(BuckEventListener.class).newInstance(); eventListeners.add(listener); } } catch (ReflectiveOperationException e) { throw new HumanReadableException("Error loading event listener class '%s': %s: %s", className, e.getClass(), e.getMessage()); } } }
From source file:com.google.template.soy.jssrc.dsl.CodeChunk.java
/** * Temporary method to ease migration to the CodeChunk DSL. * * <p>Because of the recursive nature of the JS codegen system, it is generally not possible * to convert one codegen method at a time to use the CodeChunk DSL. * However, the business logic inside those methods can be migrated incrementally. * Methods that do not yet use the CodeChunk DSL can "unwrap" inputs using this method * and "wrap" results using {@link CodeChunk#fromExpr(JsExpr)}. This is safe as long as * each CodeChunk generated for production code is * {@link CodeChunk.WithValue#isRepresentableAsSingleExpression}. * * TODO(user): remove./*from w ww . j a v a2 s . c om*/ */ public final JsExpr assertExpr() { RequiresCollector.IntoImmutableSet collector = new RequiresCollector.IntoImmutableSet(); JsExpr expr = assertExprAndCollectRequires(collector); ImmutableSet<GoogRequire> requires = collector.get(); if (!requires.isEmpty()) { throw new IllegalStateException("calling assertExpr() would drop requires!: " + requires); } return expr; }
From source file:com.google.javascript.jscomp.newtypes.JSType.java
private static JSType makeType(int mask, ImmutableSet<ObjectType> objs, String typeVar, ImmutableSet<EnumType> enums) { // Fix up the mask for objects and enums if (Preconditions.checkNotNull(enums).isEmpty()) { mask &= ~ENUM_MASK;//from w w w . ja v a2s . com } else { mask |= ENUM_MASK; } if (Preconditions.checkNotNull(objs).isEmpty()) { mask &= ~NON_SCALAR_MASK; } else { mask |= NON_SCALAR_MASK; } if (objs.isEmpty() && typeVar == null && enums.isEmpty()) { return MaskType.make(mask); } if (!JSType.isInhabitable(objs)) { return BOTTOM; } if (mask == NON_SCALAR_MASK) { return new ObjsType(objs); } if (mask == (NON_SCALAR_MASK | NULL_MASK)) { return new NullableObjsType(objs); } return new UnionType(mask, objs, typeVar, enums); }
From source file:com.facebook.buck.ide.intellij.IjProjectCommandHelper.java
private int buildRequiredTargetsWithoutUsingCacheForAnnotatedTargets( TargetGraphAndTargets targetGraphAndTargets, ImmutableSet<BuildTarget> requiredBuildTargets) throws IOException, InterruptedException { ImmutableSet<BuildTarget> annotatedTargets = getTargetsWithAnnotations( targetGraphAndTargets.getTargetGraph(), requiredBuildTargets); ImmutableSet<BuildTarget> unannotatedTargets = Sets.difference(requiredBuildTargets, annotatedTargets) .immutableCopy();/*w w w . j a v a 2s. co m*/ int exitCode = runBuild(unannotatedTargets); if (exitCode != 0) { addBuildFailureError(); } if (annotatedTargets.isEmpty()) { return exitCode; } int annotationExitCode = buckBuildRunner.runBuild(annotatedTargets, true); if (exitCode == 0 && annotationExitCode != 0) { addBuildFailureError(); } return exitCode == 0 ? annotationExitCode : exitCode; }
From source file:org.springframework.ide.eclipse.boot.dash.model.AbstractLaunchConfigurationsDashElement.java
private ILaunchConfiguration getOrCreateLaunchConfig(UserInteractions ui) throws Exception { ILaunchConfiguration conf = null;/*from w w w . j a v a 2 s.co m*/ ImmutableSet<ILaunchConfiguration> configs = getLaunchConfigs(); if (configs.isEmpty()) { IType mainType = chooseMainType(ui); if (mainType != null) { RunTarget target = getTarget(); IJavaProject jp = getJavaProject(); conf = target.createLaunchConfig(jp, mainType); } } else { conf = chooseConfig(ui, configs); } return conf; }
From source file:com.google.devtools.build.android.dexer.DexFileSplitter.java
@VisibleForTesting static void splitIntoShards(Options options) throws IOException { checkArgument(!options.minimalMainDex || options.mainDexListFile != null, "--minimal-main-dex not allowed without --main-dex-list"); if (!Files.exists(options.outputDirectory)) { Files.createDirectories(options.outputDirectory); }/* w ww. j av a 2 s. c om*/ ImmutableSet<String> classesInMainDex = options.mainDexListFile != null ? ImmutableSet.copyOf(Files.readAllLines(options.mainDexListFile, UTF_8)) : null; try (Closer closer = Closer.create(); DexFileSplitter out = new DexFileSplitter(options.outputDirectory, options.maxNumberOfIdxPerDex)) { // 1. Scan inputs in order and keep first occurrence of each class, keeping all zips open. // We don't process anything yet so we can shard in sorted order, which is what dx would do // if presented with a single jar containing all the given inputs. // TODO(kmb): Abandon alphabetic sorting to process each input fully before moving on (still // requires scanning inputs twice for main dex list). LinkedHashMap<String, ZipFile> deduped = new LinkedHashMap<>(); for (Path inputArchive : options.inputArchives) { ZipFile zip = closer.register(new ZipFile(inputArchive.toFile())); zip.stream().filter(ZipEntryPredicates.suffixes(".dex", ".class")) .forEach(e -> deduped.putIfAbsent(e.getName(), zip)); } ImmutableList<Map.Entry<String, ZipFile>> files = deduped.entrySet().stream() .sorted(Comparator.comparing(e -> e.getKey(), ZipEntryComparator::compareClassNames)) .collect(ImmutableList.toImmutableList()); // 2. Process each class in desired order, rolling from shard to shard as needed. if (classesInMainDex == null || classesInMainDex.isEmpty()) { out.processDexFiles(files, Predicates.alwaysTrue()); } else { // To honor --main_dex_list make two passes: // 1. process only the classes listed in the given file // 2. process the remaining files Predicate<String> mainDexFilter = ZipEntryPredicates.classFileNameFilter(classesInMainDex); out.processDexFiles(files, mainDexFilter); // Fail if main_dex_list is too big, following dx's example checkState(out.shardsWritten() == 0, "Too many classes listed in main dex list file " + "%s, main dex capacity exceeded", options.mainDexListFile); if (options.minimalMainDex) { out.nextShard(); // Start new .dex file if requested } out.processDexFiles(files, Predicates.not(mainDexFilter)); } } }