Check that a kafka topic exist

@param topic_name name of topic
334779
@Then("^A kafka topic named '(.+?)' exists")
    public void kafkaTopicExist(String topic_name) throws KeeperException, InterruptedException {
        assert commonspec.getKafkaUtils().getZkUtils().pathExists("/" + topic_name) : "There is no topic with that name";
    }
441549
def _check_kafka_disconnect(self):
        """"""
        for node_id in self.consumer._client._conns:
            conn = self.consumer._client._conns[node_id]
            if conn.state == ConnectionStates.DISCONNECTED or \
                    conn.state == ConnectionStates.DISCONNECTING:
                self._spawn_kafka_connection_thread()
                break
836946
def incident_exists(name, message, status):
    
    incidents = cachet.Incidents(endpoint=ENDPOINT)
    all_incidents = json.loads(incidents.get())
    for incident in all_incidents['data']:
        if name == incident['name'] and \
           status == incident['status'] and \
           message.strip() == incident['message'].strip():
            return True
    return False
515781
@Async
    public void send(String topic, String content) {
        try {
            if (!StringUtils.isBlank(content)) {
                log.debug("Sending kafka event with data {} to topic {}", content, topic);
                template.send(topic, content);
            }
        } catch (Exception e) {
            log.error("Error send timeline event", e);
            throw e;
        }
    }
474787
public boolean exists(String indexName) {
        try {
            final JestResult result = jestClient.execute(new GetSettings.Builder().addIndex(indexName).build());
            return result.isSucceeded() && Iterators.contains(result.getJsonObject().fieldNames(), indexName);
        } catch (IOException e) {
            throw new ElasticsearchException("Couldn't check existence of index " + indexName, e);
        }
    }
1179175
private KafkaConsumer<String, byte[]> _getConsumer(String topic, boolean autoCommitOffsets) {
        KafkaConsumer<String, byte[]> consumer = topicConsumers.get(topic);
        if (consumer == null) {
            consumer = KafkaHelper.createKafkaConsumer(bootstrapServers, consumerGroupId,
                    consumeFromBeginning, autoCommitOffsets, consumerProperties);
            KafkaConsumer<String, byte[]> existingConsumer = topicConsumers.putIfAbsent(topic,
                    consumer);
            if (existingConsumer != null) {
                consumer.close();
                consumer = existingConsumer;
            } else {
                _checkAndSubscribe(consumer, topic);
            }
        }
        return consumer;
    }
761946
private void scheduleAcknowledgment(final String topic) {
    if (!acknowledgeScheduled.has(topic)) {
      acknowledgeScheduled.set(topic, true);
      Platform.scheduler().scheduleDelay(acknowledgeDelayMillis, new Handler<Void>() {
        @Override
        public void handle(Void event) {
          if (acknowledgeScheduled.has(topic)) {
            acknowledgeScheduled.remove(topic);
            // Check we're still out of date, and not already catching up.
            double knownHeadSequence = knownHeadSequences.getNumber(topic);
            double currentSequence = currentSequences.getNumber(topic);
            if (knownHeadSequence > currentSequence
                && (!acknowledgeNumbers.has(topic) || knownHeadSequence > acknowledgeNumbers
                    .getNumber(topic))) {
              acknowledgeNumbers.set(topic, knownHeadSequence);
              log.log(Level.CONFIG, "Catching up to " + knownHeadSequence);
              catchup(topic, currentSequence);
            } else {
              log.log(Level.FINE, "No need to catchup");
            }
          }
        }
      });
    }
  }
887452
private boolean topicImplicity(final String topic, final String[] splitTopic) {

        try {
            return topicMatcher.matches(stripedTopic, this.splitTopic, nonWildCard, endsWithWildCard, rootWildCard, topic, splitTopic);
        } catch (InvalidTopicException e) {
            return false;
        }
    }
1199229
public boolean isMatchingTopic(String topic) {
		if (isFixedTopics()) {
			return getFixedTopics().contains(topic);
		} else {
			return topicPattern.matcher(topic).matches();
		}
	}
980204
def topic_exists(name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    topics = list_topics(region=region, key=key, keyid=keyid, profile=profile)
    return name in list(topics.values() + topics.keys())
946291
def publish(self, topic, messages, key=None):
        

        if not isinstance(messages, list):
            messages = [messages]

        first = True
        success = False
        if key is None:
            key = int(time.time() * 1000)

        messages = [encodeutils.to_utf8(m) for m in messages]

        key = bytes(str(key), 'utf-8') if PY3 else str(key)

        while not success:
            try:
                self._producer.send_messages(topic, key, *messages)
                success = True
            except Exception:
                if first:
                    # This is a warning because of all the other warning and
                    # error messages that are logged in this case. This way
                    # someone looking at the log file can see the retry
                    log.warn("Failed send on topic {}, clear metadata and retry"
                             .format(topic))

                    # If Kafka is running in Kubernetes, the cached metadata
                    # contains the IP Address of the Kafka pod. If the Kafka
                    # pod has restarted, the IP Address will have changed
                    # which would have caused the first publish to fail. So,
                    # clear the cached metadata and retry the publish
                    self._kafka.reset_topic_metadata(topic)
                    first = False
                    continue
                log.exception('Error publishing to {} topic.'.format(topic))
                raise
889645
private void doAsynSend(final String topicName, final String messageKey,final DefaultMessage message) {
		// 异步发送
        this.kafkaProducer.send(new ProducerRecord<String, Object>(topicName, messageKey,message.sendBodyOnly() ? message.getBody() : message), new Callback() {

            @Override
            public void onCompletion(RecordMetadata metadata, Exception ex) {
                if (ex != null) {
                	for (ProducerEventHandler handler : eventHanlders) {
                		try {handler.onError(topicName, message);} catch (Exception e) {}
    				}
                	log.error("kafka_send_fail,topic="+topicName+",messageId="+messageKey,ex);
                } else {
                	for (ProducerEventHandler handler : eventHanlders) {
                		try {handler.onSuccessed(topicName, metadata);} catch (Exception e) {}
    				}
                    if (log.isDebugEnabled()) {
                        log.debug("kafka_send_success,topic=" + topicName + ", messageId=" + messageKey + ", partition=" + metadata.partition() + ", offset=" + metadata.offset());
                    }
                }
            }
        });
	}
963300
private boolean validateExistingTopicTags(final ITopicNode topicNode, final BaseTopicWrapper<?> topic) {
        // Ignore validating revision topics
        if (topicNode.getRevision() != null) {
            return true;
        }

        boolean valid = true;
        final List<String> tagNames = topicNode.getTags(true);
        if (!tagNames.isEmpty()) {
            final Set<TagWrapper> tags = new HashSet<TagWrapper>();
            for (final String tagName : tagNames) {
                // Check if the app should be shutdown
                if (isShuttingDown.get()) {
                    shutdown.set(true);
                    return false;
                }
                // Get the tag from the database
                TagWrapper tag = null;
                try {
                    tag = tagProvider.getTagByName(tagName);
                } catch (NotFoundException e) {

                }

                // Check that it exists
                if (tag != null) {
                    tags.add(tag);
                }
            }

            // Add all the existing tags
            if (topic.getTags() != null) {
                tags.addAll(topic.getTags().getItems());
            }

            // Check that the mutex value entered is correct
            final Map<Integer, List<TagWrapper>> mapping = EntityUtilities.getCategoryMappingFromTagList(tags);
            for (final Entry<Integer, List<TagWrapper>> catEntry : mapping.entrySet()) {
                final CategoryWrapper cat = categoryProvider.getCategory(catEntry.getKey());
                final List<TagWrapper> catTags = catEntry.getValue();

                // Check if the app should be shutdown
                if (isShuttingDown.get()) {
                    shutdown.set(true);
                    return false;
                }

                // Check that only one tag has been set if the category is mutually exclusive
                if (cat.isMutuallyExclusive() && catTags.size() > 1) {
                    log.error(String.format(ProcessorConstants.ERROR_TOPIC_TOO_MANY_CATS_MSG, topicNode.getLineNumber(), cat.getName(),
                            topicNode.getText()));
                    valid = false;
                }
            }
        }
        return valid;
    }
365218
public static String getTopicName(State state) {
    Preconditions.checkArgument(state.contains(KafkaSource.TOPIC_NAME),
        "Missing configuration property " + KafkaSource.TOPIC_NAME);

    return state.getProp(KafkaSource.TOPIC_NAME);
  }
405983
public synchronized Topic getTopic(String topicName) {
        if (topicName == null || topicName.length() == 0) {
            throw new JavametricsException("Topic names must not be null or 0 length");
        }
        if (topics.containsKey(topicName)) {
            return topics.get(topicName);
        } else {
            Topic topic = new TopicImpl(topicName);
            topics.put(topicName, topic);
            return topic;
        }
    }
128041
public boolean indexExists(String name) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpHead head = new HttpHead(String.format("http://%s:%d/%s", host, port, name));
        try {
            CloseableHttpResponse response = client.execute(head);
            return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
        } finally {
            head.releaseConnection();
        }
    }
217642
def set_topic_attributes(TopicArn, AttributeName, AttributeValue, region=None, key=None, keyid=None,
                         profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    try:
        conn.set_topic_attributes(TopicArn=TopicArn, AttributeName=AttributeName,
                                  AttributeValue=AttributeValue)
        log.debug('Set attribute %s=%s on SNS topic %s',
                  AttributeName, AttributeValue, TopicArn)
        return True
    except botocore.exceptions.ClientError as e:
        log.error('Failed to set attribute %s=%s for SNS topic %s: %s',
                  AttributeName, AttributeValue, TopicArn, e)
        return False