Search in sources :

Example 6 with Collections2

use of com.google.common.collect.Collections2 in project Conversations by siacs.

the class JingleConnectionManager method deliverMessage.

public void deliverMessage(final Account account, final Jid to, final Jid from, final Element message, String remoteMsgId, String serverMsgId, long timestamp) {
    Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
    final String sessionId = message.getAttribute("id");
    if (sessionId == null) {
        return;
    }
    if ("accept".equals(message.getName())) {
        for (AbstractJingleConnection connection : connections.values()) {
            if (connection instanceof JingleRtpConnection) {
                final JingleRtpConnection rtpConnection = (JingleRtpConnection) connection;
                final AbstractJingleConnection.Id id = connection.getId();
                if (id.account == account && id.sessionId.equals(sessionId)) {
                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
                    return;
                }
            }
        }
        return;
    }
    final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
    final boolean addressedDirectly = to != null && to.equals(account.getJid());
    final AbstractJingleConnection.Id id;
    if (fromSelf) {
        if (to != null && to.isFullJid()) {
            id = AbstractJingleConnection.Id.of(account, to, sessionId);
        } else {
            return;
        }
    } else {
        id = AbstractJingleConnection.Id.of(account, from, sessionId);
    }
    final AbstractJingleConnection existingJingleConnection = connections.get(id);
    if (existingJingleConnection != null) {
        if (existingJingleConnection instanceof JingleRtpConnection) {
            ((JingleRtpConnection) existingJingleConnection).deliveryMessage(from, message, serverMsgId, timestamp);
        } else {
            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + existingJingleConnection.getClass().getName() + " does not support jingle messages");
        }
        return;
    }
    if (fromSelf) {
        if ("proceed".equals(message.getName())) {
            final Conversation c = mXmppConnectionService.findOrCreateConversation(account, id.with, false, false);
            final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
            if (previousBusy != null) {
                previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
                if (serverMsgId != null) {
                    previousBusy.setServerMsgId(serverMsgId);
                }
                previousBusy.setTime(timestamp);
                mXmppConnectionService.updateMessage(previousBusy, true);
                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": updated previous busy because call got picked up by another device");
                return;
            }
        }
        // TODO handle reject for cases where we don’t have carbon copies (normally reject is to be sent to own bare jid as well)
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignore jingle message from self");
        return;
    }
    if ("propose".equals(message.getName())) {
        final Propose propose = Propose.upgrade(message);
        final List<GenericDescription> descriptions = propose.getDescriptions();
        final Collection<RtpDescription> rtpDescriptions = Collections2.transform(Collections2.filter(descriptions, d -> d instanceof RtpDescription), input -> (RtpDescription) input);
        if (rtpDescriptions.size() > 0 && rtpDescriptions.size() == descriptions.size() && isUsingClearNet(account)) {
            final Collection<Media> media = Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
            if (media.contains(Media.UNKNOWN)) {
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered unknown media in session proposal. " + propose);
                return;
            }
            final Optional<RtpSessionProposal> matchingSessionProposal = findMatchingSessionProposal(account, id.with, ImmutableSet.copyOf(media));
            if (matchingSessionProposal.isPresent()) {
                final String ourSessionId = matchingSessionProposal.get().sessionId;
                final String theirSessionId = id.sessionId;
                if (ComparisonChain.start().compare(ourSessionId, theirSessionId).compare(account.getJid().toEscapedString(), id.with.toEscapedString()).result() > 0) {
                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": our session lost tie break. automatically accepting their session. winning Session=" + theirSessionId);
                    // TODO a retract for this reason should probably include some indication of tie break
                    retractSessionProposal(matchingSessionProposal.get());
                    final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, from);
                    this.connections.put(id, rtpConnection);
                    rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
                } else {
                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": our session won tie break. waiting for other party to accept. winningSession=" + ourSessionId);
                }
                return;
            }
            final boolean stranger = isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
            if (isBusy() || stranger) {
                writeLogMissedIncoming(account, id.with.asBareJid(), id.sessionId, serverMsgId, timestamp);
                if (stranger) {
                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring call proposal from stranger " + id.with);
                    return;
                }
                final int activeDevices = account.activeDevicesWithRtpCapability();
                Log.d(Config.LOGTAG, "active devices with rtp capability: " + activeDevices);
                if (activeDevices == 0) {
                    final MessagePacket reject = mXmppConnectionService.getMessageGenerator().sessionReject(from, sessionId);
                    mXmppConnectionService.sendMessagePacket(account, reject);
                } else {
                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring proposal because busy on this device but there are other devices");
                }
            } else {
                final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, from);
                this.connections.put(id, rtpConnection);
                rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
                rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
            }
        } else {
            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to react to proposed session with " + rtpDescriptions.size() + " rtp descriptions of " + descriptions.size() + " total descriptions");
        }
    } else if (addressedDirectly && "proceed".equals(message.getName())) {
        synchronized (rtpSessionProposals) {
            final RtpSessionProposal proposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
            if (proposal != null) {
                rtpSessionProposals.remove(proposal);
                final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
                rtpConnection.setProposedMedia(proposal.media);
                this.connections.put(id, rtpConnection);
                rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
                rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
            } else {
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver proceed");
                if (remoteMsgId == null) {
                    return;
                }
                final MessagePacket errorMessage = new MessagePacket();
                errorMessage.setTo(from);
                errorMessage.setId(remoteMsgId);
                errorMessage.setType(MessagePacket.TYPE_ERROR);
                final Element error = errorMessage.addChild("error");
                error.setAttribute("code", "404");
                error.setAttribute("type", "cancel");
                error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
                mXmppConnectionService.sendMessagePacket(account, errorMessage);
            }
        }
    } else if (addressedDirectly && "reject".equals(message.getName())) {
        final RtpSessionProposal proposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
        synchronized (rtpSessionProposals) {
            if (proposal != null && rtpSessionProposals.remove(proposal) != null) {
                writeLogMissedOutgoing(account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
                toneManager.transition(RtpEndUserState.DECLINED_OR_BUSY, proposal.media);
                mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, proposal.with, proposal.sessionId, RtpEndUserState.DECLINED_OR_BUSY);
            } else {
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver reject");
            }
        }
    } else {
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved out of order jingle message" + message);
    }
}
Also used : Conversational(eu.siacs.conversations.entities.Conversational) Content(eu.siacs.conversations.xmpp.jingle.stanzas.Content) RtpDescription(eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription) Config(eu.siacs.conversations.Config) ScheduledFuture(java.util.concurrent.ScheduledFuture) IqPacket(eu.siacs.conversations.xmpp.stanzas.IqPacket) Reason(eu.siacs.conversations.xmpp.jingle.stanzas.Reason) HashMap(java.util.HashMap) Collections2(com.google.common.collect.Collections2) Account(eu.siacs.conversations.entities.Account) Element(eu.siacs.conversations.xml.Element) Conversation(eu.siacs.conversations.entities.Conversation) SecureRandom(java.security.SecureRandom) GenericDescription(eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription) Optional(com.google.common.base.Optional) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) FileTransferDescription(eu.siacs.conversations.xmpp.jingle.stanzas.FileTransferDescription) Objects(com.google.common.base.Objects) WeakReference(java.lang.ref.WeakReference) Log(android.util.Log) XmppConnection(eu.siacs.conversations.xmpp.XmppConnection) MessagePacket(eu.siacs.conversations.xmpp.stanzas.MessagePacket) ImmutableSet(com.google.common.collect.ImmutableSet) Contact(eu.siacs.conversations.entities.Contact) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Propose(eu.siacs.conversations.xmpp.jingle.stanzas.Propose) Set(java.util.Set) JinglePacket(eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket) ComparisonChain(com.google.common.collect.ComparisonChain) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Transferable(eu.siacs.conversations.entities.Transferable) List(java.util.List) Message(eu.siacs.conversations.entities.Message) RtpSessionStatus(eu.siacs.conversations.entities.RtpSessionStatus) XmppConnectionService(eu.siacs.conversations.services.XmppConnectionService) Namespace(eu.siacs.conversations.xml.Namespace) OnIqPacketReceived(eu.siacs.conversations.xmpp.OnIqPacketReceived) Base64(android.util.Base64) Preconditions(com.google.common.base.Preconditions) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) AbstractConnectionManager(eu.siacs.conversations.services.AbstractConnectionManager) Collections(java.util.Collections) Jid(eu.siacs.conversations.xmpp.Jid) Message(eu.siacs.conversations.entities.Message) Element(eu.siacs.conversations.xml.Element) GenericDescription(eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription) Conversation(eu.siacs.conversations.entities.Conversation) RtpDescription(eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription) MessagePacket(eu.siacs.conversations.xmpp.stanzas.MessagePacket) Propose(eu.siacs.conversations.xmpp.jingle.stanzas.Propose) RtpSessionStatus(eu.siacs.conversations.entities.RtpSessionStatus)

Example 7 with Collections2

use of com.google.common.collect.Collections2 in project hive by apache.

the class CommitTxnHandler method getAllWriteEventInfo.

private List<WriteEventInfo> getAllWriteEventInfo(Context withinContext) throws Exception {
    String contextDbName = StringUtils.normalizeIdentifier(withinContext.replScope.getDbName());
    GetAllWriteEventInfoRequest request = new GetAllWriteEventInfoRequest(eventMessage.getTxnId());
    request.setDbName(contextDbName);
    List<WriteEventInfo> writeEventInfoList = withinContext.db.getMSC().getAllWriteEventInfo(request);
    return ((writeEventInfoList == null) ? null : new ArrayList<>(Collections2.filter(writeEventInfoList, writeEventInfo -> {
        assert (writeEventInfo != null);
        // it should be skipped.
        return (ReplUtils.tableIncludedInReplScope(withinContext.replScope, writeEventInfo.getTable()) && ReplUtils.tableIncludedInReplScope(withinContext.oldReplScope, writeEventInfo.getTable()) && !withinContext.getTablesForBootstrap().contains(writeEventInfo.getTable().toLowerCase()));
    })));
}
Also used : LoginException(javax.security.auth.login.LoginException) MetaException(org.apache.hadoop.hive.metastore.api.MetaException) DumpMetaData(org.apache.hadoop.hive.ql.parse.repl.load.DumpMetaData) Collections2(com.google.common.collect.Collections2) GetAllWriteEventInfoRequest(org.apache.hadoop.hive.metastore.api.GetAllWriteEventInfoRequest) SemanticException(org.apache.hadoop.hive.ql.parse.SemanticException) DumpType(org.apache.hadoop.hive.ql.parse.repl.DumpType) StringUtils(org.apache.hadoop.hive.metastore.utils.StringUtils) ArrayList(java.util.ArrayList) WriteEventInfo(org.apache.hadoop.hive.metastore.api.WriteEventInfo) Lists(com.google.common.collect.Lists) EximUtil(org.apache.hadoop.hive.ql.parse.EximUtil) Path(org.apache.hadoop.fs.Path) ReplChangeManager(org.apache.hadoop.hive.metastore.ReplChangeManager) HiveUtils(org.apache.hadoop.hive.ql.metadata.HiveUtils) HiveConf(org.apache.hadoop.hive.conf.HiveConf) Table(org.apache.hadoop.hive.ql.metadata.Table) IOException(java.io.IOException) HiveFatalException(org.apache.hadoop.hive.ql.metadata.HiveFatalException) File(java.io.File) Partition(org.apache.hadoop.hive.ql.metadata.Partition) List(java.util.List) NotificationEvent(org.apache.hadoop.hive.metastore.api.NotificationEvent) ReplUtils(org.apache.hadoop.hive.ql.exec.repl.util.ReplUtils) CommitTxnMessage(org.apache.hadoop.hive.metastore.messaging.CommitTxnMessage) GetAllWriteEventInfoRequest(org.apache.hadoop.hive.metastore.api.GetAllWriteEventInfoRequest) WriteEventInfo(org.apache.hadoop.hive.metastore.api.WriteEventInfo) ArrayList(java.util.ArrayList)

Example 8 with Collections2

use of com.google.common.collect.Collections2 in project gerrit by GerritCodeReview.

the class ConsistencyChecker method checkPatchSets.

private boolean checkPatchSets() {
    List<PatchSet> all;
    try {
        // Iterate in descending order.
        all = PS_ID_ORDER.sortedCopy(psUtil.byChange(notes));
    } catch (StorageException e) {
        ProblemInfo problem = problem("Failed to look up patch sets");
        logger.atWarning().withCause(e).log("Error in consistency check of change %s: %s", notes.getChangeId(), problem);
        return false;
    }
    patchSetsBySha = MultimapBuilder.hashKeys(all.size()).treeSetValues(PS_ID_ORDER).build();
    Map<String, Ref> refs;
    try {
        refs = repo.getRefDatabase().exactRef(all.stream().map(ps -> ps.id().toRefName()).toArray(String[]::new));
    } catch (IOException e) {
        ProblemInfo problem = problem("Error reading refs");
        logger.atWarning().withCause(e).log("Error in consistency check of change %s: %s", notes.getChangeId(), problem);
        refs = Collections.emptyMap();
    }
    List<DeletePatchSetFromDbOp> deletePatchSetOps = new ArrayList<>();
    for (PatchSet ps : all) {
        // Check revision format.
        int psNum = ps.id().get();
        String refName = ps.id().toRefName();
        ObjectId objId = ps.commitId();
        patchSetsBySha.put(objId, ps);
        // Check ref existence.
        ProblemInfo refProblem = null;
        Ref ref = refs.get(refName);
        if (ref == null) {
            refProblem = problem("Ref missing: " + refName);
        } else if (!objId.equals(ref.getObjectId())) {
            String actual = ref.getObjectId() != null ? ref.getObjectId().name() : "null";
            refProblem = problem(String.format("Expected %s to point to %s, found %s", ref.getName(), objId.name(), actual));
        }
        // Check object existence.
        RevCommit psCommit = parseCommit(objId, String.format("patch set %d", psNum));
        if (psCommit == null) {
            if (fix != null && fix.deletePatchSetIfCommitMissing) {
                deletePatchSetOps.add(new DeletePatchSetFromDbOp(lastProblem(), ps.id()));
            }
            continue;
        } else if (refProblem != null && fix != null) {
            fixPatchSetRef(refProblem, ps);
        }
        if (ps.id().equals(change().currentPatchSetId())) {
            currPsCommit = psCommit;
        }
    }
    // Delete any bad patch sets found above, in a single update.
    deletePatchSets(deletePatchSetOps);
    // Check for duplicates.
    for (Map.Entry<ObjectId, Collection<PatchSet>> e : patchSetsBySha.asMap().entrySet()) {
        if (e.getValue().size() > 1) {
            problem(String.format("Multiple patch sets pointing to %s: %s", e.getKey().name(), Collections2.transform(e.getValue(), PatchSet::number)));
        }
    }
    return currPs != null && currPsCommit != null;
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) MultimapBuilder(com.google.common.collect.MultimapBuilder) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) Inject(com.google.inject.Inject) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) Collections2(com.google.common.collect.Collections2) SubmissionId(com.google.gerrit.entities.SubmissionId) PatchSetInfoFactory(com.google.gerrit.server.patch.PatchSetInfoFactory) UpdateException(com.google.gerrit.server.update.UpdateException) Accounts(com.google.gerrit.server.account.Accounts) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Locale(java.util.Locale) Map(java.util.Map) RetryHelper(com.google.gerrit.server.update.RetryHelper) UrlFormatter(com.google.gerrit.server.config.UrlFormatter) PluginItemContext(com.google.gerrit.server.plugincontext.PluginItemContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Collection(java.util.Collection) Set(java.util.Set) RefUpdate(org.eclipse.jgit.lib.RefUpdate) Status(com.google.gerrit.extensions.common.ProblemInfo.Status) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) PS_ID_ORDER(com.google.gerrit.server.ChangeUtil.PS_ID_ORDER) Nullable(com.google.gerrit.common.Nullable) Ref(org.eclipse.jgit.lib.Ref) AutoValue(com.google.auto.value.AutoValue) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) FluentLogger(com.google.common.flogger.FluentLogger) Iterables(com.google.common.collect.Iterables) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) FixInput(com.google.gerrit.extensions.api.changes.FixInput) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) PatchSetState(com.google.gerrit.server.notedb.PatchSetState) RepoContext(com.google.gerrit.server.update.RepoContext) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) REFS_CHANGES(com.google.gerrit.entities.RefNames.REFS_CHANGES) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) Comparator.comparing(java.util.Comparator.comparing) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ChangeUtil(com.google.gerrit.server.ChangeUtil) ChangeContext(com.google.gerrit.server.update.ChangeContext) PatchSetInfoNotAvailableException(com.google.gerrit.server.patch.PatchSetInfoNotAvailableException) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) CurrentUser(com.google.gerrit.server.CurrentUser) StorageException(com.google.gerrit.exceptions.StorageException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) SetMultimap(com.google.common.collect.SetMultimap) ObjectId(org.eclipse.jgit.lib.ObjectId) Provider(com.google.inject.Provider) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) Project(com.google.gerrit.entities.Project) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) Collections(java.util.Collections) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) Repository(org.eclipse.jgit.lib.Repository) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) PatchSet(com.google.gerrit.entities.PatchSet) IOException(java.io.IOException) Ref(org.eclipse.jgit.lib.Ref) Collection(java.util.Collection) StorageException(com.google.gerrit.exceptions.StorageException) Map(java.util.Map) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 9 with Collections2

use of com.google.common.collect.Collections2 in project metron by apache.

the class ConfigurationManagerIntegrationTest method setup.

@BeforeEach
public void setup() throws Exception {
    testZkServer = new TestingServer(true);
    zookeeperUrl = testZkServer.getConnectString();
    client = ConfigurationsUtils.getClient(zookeeperUrl);
    client.start();
    File sensorDir = new File(new File(TestConstants.SAMPLE_CONFIG_PATH), ENRICHMENT.getDirectory());
    sensors.addAll(Collections2.transform(Arrays.asList(sensorDir.list()), s -> Iterables.getFirst(Splitter.on('.').split(s), "null")));
    tmpDir = TestUtils.createTempDir(this.getClass().getName());
    configDir = TestUtils.createDir(tmpDir, "config");
    parsersDir = TestUtils.createDir(configDir, "parsers");
    enrichmentsDir = TestUtils.createDir(configDir, "enrichments");
    indexingDir = TestUtils.createDir(configDir, "indexing");
    pushAllConfigs();
}
Also used : TestingServer(org.apache.curator.test.TestingServer) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) BeforeEach(org.junit.jupiter.api.BeforeEach) Iterables(com.google.common.collect.Iterables) Arrays(java.util.Arrays) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ENRICHMENT(org.apache.metron.common.configuration.ConfigurationType.ENRICHMENT) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Collections2(com.google.common.collect.Collections2) HashSet(java.util.HashSet) PatchMode(org.apache.metron.common.cli.ConfigurationManager.PatchMode) StringUtils.stripLines(org.apache.metron.common.utils.StringUtils.stripLines) TestingServer(org.apache.curator.test.TestingServer) ConfigurationType(org.apache.metron.common.configuration.ConfigurationType) ConfigurationsUtils(org.apache.metron.common.configuration.ConfigurationsUtils) JSONUtils(org.apache.metron.common.utils.JSONUtils) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) PosixParser(org.apache.commons.cli.PosixParser) Splitter(com.google.common.base.Splitter) ADD(org.apache.metron.common.cli.ConfigurationManager.PatchMode.ADD) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) GLOBAL(org.apache.metron.common.configuration.ConfigurationType.GLOBAL) Files(java.nio.file.Files) TestConstants(org.apache.metron.TestConstants) PROFILER(org.apache.metron.common.configuration.ConfigurationType.PROFILER) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) Set(java.util.Set) TestUtils(org.apache.metron.integration.utils.TestUtils) IOException(java.io.IOException) INDEXING(org.apache.metron.common.configuration.ConfigurationType.INDEXING) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) PARSER(org.apache.metron.common.configuration.ConfigurationType.PARSER) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) CuratorFramework(org.apache.curator.framework.CuratorFramework) BooleanWritable(org.apache.hadoop.io.BooleanWritable) Paths(java.nio.file.Paths) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Multiline(org.adrianwalker.multilinestring.Multiline) Optional(java.util.Optional) Assertions.assertDoesNotThrow(org.junit.jupiter.api.Assertions.assertDoesNotThrow) File(java.io.File) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 10 with Collections2

use of com.google.common.collect.Collections2 in project copybara by google.

the class GitHubPrOrigin method checkRequiredCheckRuns.

/**
 * Check that the PR has a conclusion of "success" for each check_run whose name is in the list
 * provided in the `required_check_runs` param
 */
private void checkRequiredCheckRuns(GitHubApi api, String project, PullRequest prData) throws ValidationException, RepoException {
    Set<String> requiredCheckRuns = getRequiredCheckRuns();
    if (forceImport() || requiredCheckRuns.isEmpty()) {
        return;
    }
    try (ProfilerTask ignore = generalOptions.profiler().start("github_api_get_combined_status")) {
        CheckRuns checkRuns = api.getCheckRuns(project, prData.getHead().getSha());
        Set<String> requiredButNotPresent = Sets.newHashSet(requiredCheckRuns);
        List<CheckRun> passedCheckRuns = checkRuns.getCheckRuns().stream().filter(e -> e.getConclusion().equals("success")).collect(Collectors.toList());
        requiredButNotPresent.removeAll(Collections2.transform(passedCheckRuns, CheckRun::getName));
        if (!requiredButNotPresent.isEmpty()) {
            throw new EmptyChangeException(String.format("Cannot migrate http://github.com/%s/pull/%d because the following check runs " + "have not been passed: %s", project, prData.getNumber(), requiredButNotPresent));
        }
    }
}
Also used : GitHubUtil.asHeadRef(com.google.copybara.git.github.util.GitHubUtil.asHeadRef) Origin(com.google.copybara.Origin) CombinedStatus(com.google.copybara.git.github.api.CombinedStatus) Collections2(com.google.common.collect.Collections2) Review(com.google.copybara.git.github.api.Review) ImmutableListMultimap.toImmutableListMultimap(com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap) Matcher(java.util.regex.Matcher) Change(com.google.copybara.Change) BaselinesWithoutLabelVisitor(com.google.copybara.BaselinesWithoutLabelVisitor) CannotResolveRevisionException(com.google.copybara.exception.CannotResolveRevisionException) Endpoint(com.google.copybara.Endpoint) Splitter(com.google.common.base.Splitter) GeneralOptions(com.google.copybara.GeneralOptions) Path(java.nio.file.Path) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) User(com.google.copybara.git.github.api.User) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) List(java.util.List) GitHubApi(com.google.copybara.git.github.api.GitHubApi) PullRequest(com.google.copybara.git.github.api.PullRequest) GitHubUtil.asMergeRef(com.google.copybara.git.github.util.GitHubUtil.asMergeRef) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) AutoValue(com.google.auto.value.AutoValue) Optional(java.util.Optional) Joiner(com.google.common.base.Joiner) AuthorAssociation(com.google.copybara.git.github.api.AuthorAssociation) Iterables(com.google.common.collect.Iterables) CheckRuns(com.google.copybara.git.github.api.CheckRuns) ValidationException.checkCondition(com.google.copybara.exception.ValidationException.checkCondition) RepoException(com.google.copybara.exception.RepoException) SubmoduleStrategy(com.google.copybara.git.GitOrigin.SubmoduleStrategy) HashSet(java.util.HashSet) GitHubUtil(com.google.copybara.git.github.util.GitHubUtil) Label(com.google.copybara.git.github.api.Label) State(com.google.copybara.git.github.api.Status.State) ImmutableList(com.google.common.collect.ImmutableList) Issue(com.google.copybara.git.github.api.Issue) Nullable(javax.annotation.Nullable) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry) Uninterruptibles(com.google.common.util.concurrent.Uninterruptibles) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) CharMatcher(com.google.common.base.CharMatcher) ValidationException(com.google.copybara.exception.ValidationException) ReaderImpl(com.google.copybara.git.GitOrigin.ReaderImpl) PatchTransformation(com.google.copybara.transform.patch.PatchTransformation) Console(com.google.copybara.util.console.Console) TimeUnit(java.util.concurrent.TimeUnit) Authoring(com.google.copybara.authoring.Authoring) Checker(com.google.copybara.checks.Checker) Glob(com.google.copybara.util.Glob) CheckRun(com.google.copybara.git.github.api.CheckRun) Preconditions(com.google.common.base.Preconditions) Status(com.google.copybara.git.github.api.Status) GitHubHost(com.google.copybara.git.github.util.GitHubHost) GitHubPrUrl(com.google.copybara.git.github.util.GitHubHost.GitHubPrUrl) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) CheckRuns(com.google.copybara.git.github.api.CheckRuns) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) CheckRun(com.google.copybara.git.github.api.CheckRun) EmptyChangeException(com.google.copybara.exception.EmptyChangeException)

Aggregations

Collections2 (com.google.common.collect.Collections2)13 Set (java.util.Set)11 List (java.util.List)10 Collection (java.util.Collection)9 Collections (java.util.Collections)7 ImmutableSet (com.google.common.collect.ImmutableSet)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashSet (java.util.HashSet)6 Map (java.util.Map)6 Preconditions (com.google.common.base.Preconditions)4 Iterables (com.google.common.collect.Iterables)4 Sets (com.google.common.collect.Sets)4 File (java.io.File)4 HashMap (java.util.HashMap)4 Optional (java.util.Optional)4 TimeUnit (java.util.concurrent.TimeUnit)4 AutoValue (com.google.auto.value.AutoValue)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 Splitter (com.google.common.base.Splitter)3