Example usage for com.google.common.collect ImmutableSet contains

List of usage examples for com.google.common.collect ImmutableSet contains

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet contains.

Prototype

boolean contains(Object o);

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:ch.acanda.eclipse.pmd.v07tov08.PMDProjectSettings.java

public Set<RuleSetConfiguration> getActiveRuleSetConfigurations(
        final ImmutableList<RuleSetConfiguration> configs) {
    final ImmutableSet.Builder<RuleSetConfiguration> activeConfigs = ImmutableSet.builder();
    try {//from  w ww.j ava2 s . c o  m
        final ImmutableSet.Builder<Integer> idsBuilder = ImmutableSet.builder();
        final String activeRuleSetIds = nullToEmpty(project.getPersistentProperty(ACTIVE_RULE_SET_IDS));
        for (final String id : Splitter.on(',').omitEmptyStrings().split(activeRuleSetIds)) {
            idsBuilder.add(Integer.parseInt(id));
        }
        final ImmutableSet<Integer> ids = idsBuilder.build();
        for (final RuleSetConfiguration config : configs) {
            if (ids.contains(config.getId())) {
                activeConfigs.add(config);
            }
        }
    } catch (final CoreException e) {
        PMDPlugin.getDefault()
                .error("Cannot retrieve active rule set configuration ids of project " + project.getName(), e);
    }
    return activeConfigs.build();
}

From source file:org.ambraproject.rhino.service.impl.IngestionService.java

@VisibleForTesting
ManifestXml getManifestXml(Archive archive) throws IOException {
    final ImmutableSet<String> entryNames = archive.getEntryNames();
    if (!entryNames.contains(MANIFEST_XML)) {
        throw new RestClientException("Archive has no manifest file", HttpStatus.BAD_REQUEST);
    }/* ww  w  . j a  va2  s  .c o  m*/

    ManifestXml manifestXml;
    try (InputStream manifestStream = new BufferedInputStream(archive.openFile(MANIFEST_XML))) {
        manifestXml = new ManifestXml(AmbraService.parseXml(manifestStream));
    }
    return manifestXml;
}

From source file:com.facebook.buck.io.Watchman.java

@VisibleForTesting
@SuppressWarnings("PMD.PrematureDeclaration")
static Watchman build(ListeningProcessExecutor executor,
        Function<Path, Optional<WatchmanClient>> watchmanConnector, ImmutableSet<Path> projectWatchList,
        ImmutableMap<String, String> env, ExecutableFinder exeFinder, Console console, Clock clock,
        Optional<Long> commandTimeoutMillis) throws InterruptedException {
    LOG.info("Creating for: " + projectWatchList);
    Optional<WatchmanClient> watchmanClient = Optional.empty();
    try {//from w w  w .  ja  v a2 s.  co m
        Path watchmanPath = exeFinder.getExecutable(WATCHMAN, env).toAbsolutePath();
        Optional<? extends Map<String, ?>> result;

        long timeoutMillis = commandTimeoutMillis.orElse(DEFAULT_COMMAND_TIMEOUT_MILLIS);
        long endTimeNanos = clock.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
        result = execute(executor, console, clock, timeoutMillis, TimeUnit.MILLISECONDS.toNanos(timeoutMillis),
                watchmanPath, "get-sockname");

        if (!result.isPresent()) {
            return NULL_WATCHMAN;
        }

        String rawSockname = (String) result.get().get("sockname");
        if (rawSockname == null) {
            return NULL_WATCHMAN;
        }
        Path socketPath = Paths.get(rawSockname);

        LOG.info("Connecting to Watchman version %s at %s", result.get().get("version"), socketPath);
        watchmanClient = watchmanConnector.apply(socketPath);
        if (!watchmanClient.isPresent()) {
            LOG.warn("Could not connect to Watchman, disabling.");
            return NULL_WATCHMAN;
        }
        LOG.debug("Connected to Watchman");

        long versionQueryStartTimeNanos = clock.nanoTime();
        result = watchmanClient.get().queryWithTimeout(endTimeNanos - versionQueryStartTimeNanos, "version",
                ImmutableMap.of("required", REQUIRED_CAPABILITIES, "optional", ALL_CAPABILITIES.keySet()));

        LOG.info("Took %d ms to query capabilities %s",
                TimeUnit.NANOSECONDS.toMillis(clock.nanoTime() - versionQueryStartTimeNanos), ALL_CAPABILITIES);

        if (!result.isPresent()) {
            LOG.warn("Could not get version response from Watchman, disabling Watchman");
            watchmanClient.get().close();
            return NULL_WATCHMAN;
        }

        ImmutableSet.Builder<Capability> capabilitiesBuilder = ImmutableSet.builder();
        if (!extractCapabilities(result.get(), capabilitiesBuilder)) {
            LOG.warn("Could not extract capabilities, disabling Watchman");
            watchmanClient.get().close();
            return NULL_WATCHMAN;
        }
        ImmutableSet<Capability> capabilities = capabilitiesBuilder.build();
        LOG.debug("Got Watchman capabilities: %s", capabilities);

        ImmutableMap.Builder<Path, ProjectWatch> projectWatchesBuilder = ImmutableMap.builder();
        ImmutableMap.Builder<Path, String> clockIdsBuilder = ImmutableMap.builder();
        for (Path rootPath : projectWatchList) {
            Optional<ProjectWatch> projectWatch = queryWatchProject(watchmanClient.get(), rootPath, clock,
                    endTimeNanos - clock.nanoTime());
            if (!projectWatch.isPresent()) {
                watchmanClient.get().close();
                return NULL_WATCHMAN;
            }
            projectWatchesBuilder.put(rootPath, projectWatch.get());

            if (capabilities.contains(Capability.CLOCK_SYNC_TIMEOUT)) {
                Optional<String> clockId = queryClock(watchmanClient.get(), projectWatch.get().getWatchRoot(),
                        clock, endTimeNanos - clock.nanoTime());
                if (clockId.isPresent()) {
                    clockIdsBuilder.put(rootPath, clockId.get());
                }
            }
        }

        return new Watchman(projectWatchesBuilder.build(), capabilities, clockIdsBuilder.build(),
                Optional.of(socketPath), watchmanClient);
    } catch (ClassCastException | HumanReadableException | IOException e) {
        LOG.warn(e, "Unable to determine the version of watchman. Going without.");
        if (watchmanClient.isPresent()) {
            try {
                watchmanClient.get().close();
            } catch (IOException ioe) {
                LOG.warn(ioe, "Could not close watchman query client");
            }
        }
        return NULL_WATCHMAN;
    }
}

From source file:com.spectralogic.ds3client.commands.AbstractResponse.java

public void checkStatusCode(final int... expectedStatuses) throws IOException {
    final ImmutableSet<Integer> expectedSet = this.createExpectedSet(expectedStatuses);
    final int statusCode = this.getStatusCode();
    if (!expectedSet.contains(statusCode)) {
        final String responseString = this.readResponseString();
        throw new FailedRequestException(ResponseUtils.toImmutableIntList(expectedStatuses), statusCode,
                parseErrorResponse(responseString), responseString);
    }//from w  w w .  jav a2 s .co  m
}

From source file:com.appunite.socketio.SocketIOBase.java

private ConnectionResult connect(String url)
        throws WrongHttpResponseCode, IOException, WrongSocketIOResponse, InterruptedException {
    Uri uri = Uri.parse(url);/*from   w ww  .j ava  2  s.  c o m*/

    synchronized (mInterruptionLock) {
        if (mInterrupted) {
            throw new InterruptedException();
        }
        mRequest = new HttpGet(url);
    }
    HTTPUtils.setupDefaultHeaders(mRequest);

    HttpResponse response = getClient().execute(mRequest);
    synchronized (mInterruptionLock) {
        if (mRequest.isAborted() || mInterrupted) {
            mRequest = null;
            throw new InterruptedException();
        }
        mRequest = null;
    }
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new WrongHttpResponseCode(response);
    }

    String responseStr = HTTPUtils.getStringFromResponse(response);
    StringTokenizer responseSplit = new StringTokenizer(responseStr, ":");

    ConnectionResult result = new ConnectionResult();
    try {
        result.sessionId = responseSplit.nextToken();
        if (TextUtils.isEmpty(result.sessionId)) {
            throw new WrongSocketIOResponse("Empty socket io session id");
        }

        result.timeout = getIntOrAbsetFromString(responseSplit.nextToken());
        result.heartbeat = getIntOrAbsetFromString(responseSplit.nextToken());

        ImmutableSet<String> types = getTypesFromString(responseSplit.nextToken());
        if (!types.contains("websocket")) {
            throw new WrongSocketIOResponse("Websocket not found in server response");
        }
    } catch (NoSuchElementException e) {
        throw new WrongSocketIOResponse("Not enough color separated values in response", e);
    }
    result.socketUri = new Uri.Builder().scheme("ws").encodedAuthority(uri.getEncodedAuthority())
            .path(uri.getPath()).appendPath("websocket").appendPath(result.sessionId).build();
    return result;
}

From source file:org.apache.james.jmap.model.MessageProperties.java

private MessageProperties selectBody() {
    ImmutableSet<MessageProperty> messageProperties = buildOutputMessageProperties();
    if (messageProperties.contains(MessageProperty.body)) {
        return usingProperties(
                Sets.difference(Sets.union(messageProperties, ImmutableSet.of(MessageProperty.textBody)),
                        ImmutableSet.of(MessageProperty.body)));
    }/*from w  ww .  j  a v  a2  s .  c  o m*/
    return this;
}

From source file:com.facebook.buck.features.apple.project.WorkspaceAndProjectGenerator.java

/**
 * Find transitive dependencies of inputs for building.
 *
 * @param projectGraph {@link TargetGraph} containing nodes
 * @param nodes Nodes to fetch dependencies for.
 * @param excludes Nodes to exclude from dependencies list.
 * @return targets and their dependencies that should be build.
 *//*from  w  w w . j a  v a2  s .com*/
private static ImmutableSet<TargetNode<?>> getTransitiveDepsAndInputs(XCodeDescriptions xcodeDescriptions,
        TargetGraph projectGraph, AppleDependenciesCache dependenciesCache,
        Iterable<? extends TargetNode<?>> nodes, ImmutableSet<TargetNode<?>> excludes) {
    return FluentIterable.from(nodes)
            .transformAndConcat(input -> AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
                    xcodeDescriptions, projectGraph, Optional.of(dependenciesCache),
                    RecursiveDependenciesMode.BUILDING, input, Optional.empty()))
            .append(nodes).filter(input -> !excludes.contains(input)
                    && xcodeDescriptions.isXcodeDescription(input.getDescription()))
            .toSet();
}

From source file:com.spectralogic.ds3client.commands.interfaces.AbstractResponse.java

public void checkStatusCode(final int... expectedStatuses) throws IOException {
    final ImmutableSet<Integer> expectedSet = this.createExpectedSet(expectedStatuses);
    final int statusCode = this.getStatusCode();
    if (!expectedSet.contains(statusCode)) {
        if (checkForManagementPortException()) {
            throw new FailedRequestUsingMgmtPortException(ResponseUtils.toImmutableIntList(expectedStatuses));
        }/*from   ww w.  j  a v  a 2  s.c  o  m*/
        final String responseString = this.readResponseString();
        throw new FailedRequestException(ResponseUtils.toImmutableIntList(expectedStatuses), statusCode,
                parseErrorResponse(responseString), responseString);
    }
}

From source file:org.springframework.ide.eclipse.boot.dash.model.ToggleFiltersModel.java

private void saveFilters(ImmutableSet<FilterChoice> filters) {
    try {/*from w  w w  . j  a  va 2  s . c o  m*/
        for (FilterChoice f : getAvailableFilters()) {
            boolean active = filters.contains(f);
            if (active == f.defaultEnable) {
                //don't store default values that way if we change the default in the future then
                // users will get the new default rather than their persisted value
                persistentProperties.put(f.getId(), (String) null);
            } else {
                persistentProperties.put(f.getId(), active);
            }
        }
    } catch (Exception e) {
        //trouble saving filters... log and move on. This is not critical
        BootDashActivator.log(e);
    }
}

From source file:com.facebook.buck.ide.intellij.aggregation.AggregationTree.java

private ImmutableSet<Path> findExcludes(AggregationTreeNode parentNode,
        ImmutableSet<Path> modulePathsToAggregate) {
    return parentNode.getChildrenPaths().stream().filter(path -> !modulePathsToAggregate.contains(path))
            .collect(MoreCollectors.toImmutableSet());
}